September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -8,9 +8,9 @@
{{omit from|Sed}}
{{omit from|Batch File}}
[[Category:Raster graphics operations]]
Generate a random black and white 320x240 image continuously,
Generate a random black and white &nbsp; '''320'''<small>x</small>'''240''' &nbsp; image continuously,
showing FPS (frames per second).
Sample image:
[[Image:NoiseOutput.png]]
;A sample image: [[Image:NoiseOutput.png|600px||center|sample]]
<br><br>

View file

@ -1,7 +1,7 @@
package main
/* Note, the x-go-binding/ui/x11 lib is under development and has as a temp solution
set the x window to a static hight and with, you have to manualy set these
set the x window to a static height and with, you have to manualy set these
to 240 x 320 in code.google.com/p/x-go-binding/ui/x11/conn.go */
import "code.google.com/p/x-go-binding/ui"

View file

@ -0,0 +1,39 @@
using Gtk, GtkUtilities
function randbw(ctx, w, h)
pic = zeros(Int64, w, h)
for i in 1:length(pic)
pic[i] = rand([1, 0])
end
copy!(ctx, pic)
end
const can = @GtkCanvas()
const win = GtkWindow(can, "Image Noise", 320, 240)
@guarded draw(can) do widget
ctx = getgc(can)
h = height(can)
w = width(can)
randbw(ctx, w, h)
end
show(can)
const cond = Condition()
endit(w) = notify(cond)
signal_connect(endit, win, :destroy)
while true
frames = 0
t = time()
for _ in 1:100
draw(can)
show(can)
sleep(0.0001)
frames += 1
end
fps = round(frames / (time() - t), digits=1)
set_gtk_property!(win, :title, "Image Noise: $fps fps")
end
wait(cond)

View file

@ -0,0 +1,23 @@
import random
import rapid/gfx
var
window = initRWindow()
.size(320, 240)
.title("Rosetta Code - image noise")
.open()
surface = window.openGfx()
surface.loop:
draw ctx, step:
ctx.clear(gray(0))
ctx.begin()
for y in 0..window.height:
for x in 0..window.width:
if rand(0..1) == 0:
ctx.point((x.float, y.float))
ctx.draw(prPoints)
echo 1 / (step / 60)
update step:
discard step

View file

@ -0,0 +1,35 @@
import random
import rapid/gfx
var
window = initRWindow()
.size(320, 240)
.title("Rosetta Code - image noise")
.open()
surface = window.openGfx()
let
noiseShader = surface.newRProgram(RDefaultVshSrc, """
uniform float time;
float rand(vec2 pos) {
return fract(sin(dot(pos.xy + time, vec2(12.9898,78.233))) * 43758.5453123);
}
vec4 rFragment(vec4 col, sampler2D tex, vec2 pos, vec2 uv) {
return vec4(vec3(step(0.5, rand(uv))), 1.0);
}
""")
surface.vsync = false
surface.loop:
draw ctx, step:
noiseShader.uniform("time", time())
ctx.program = noiseShader
ctx.begin()
ctx.rect(0, 0, surface.width, surface.height)
ctx.draw()
echo 1 / (step / 60)
update step:
discard step

View file

@ -1,29 +1,22 @@
use NativeCall;
use SDL2::Raw;
use nqp;
my int ($w, $h) = 320, 240;
my SDL_Window $window;
my SDL_Renderer $renderer;
constant $sdl-lib = 'SDL2';
sub SDL_RenderDrawPoints( SDL_Renderer $, CArray[int32] $points, int32 $count ) returns int32 is native($sdl-lib) {*}
SDL_Init(VIDEO);
$window = SDL_CreateWindow(
"some white noise",
my SDL_Window $window = SDL_CreateWindow(
"White Noise - Perl 6",
SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
$w, $h,
SHOWN
RESIZABLE
);
$renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE );
SDL_ClearError();
my SDL_Renderer $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE );
my $noise_texture = SDL_CreateTexture($renderer, %PIXELFORMAT<RGB332>, STREAMING, $w, $h);
my $pixdatabuf = CArray[int64].new(0, 1234, 1234, 1234);
my $pixdatabuf = CArray[int64].new(0, $w, $h, $w);
sub render {
my int $pitch;
@ -50,10 +43,7 @@ sub render {
my $event = SDL_Event.new;
my @times;
main: loop {
my $start = nqp::time_n();
while SDL_PollEvent($event) {
my $casted_event = SDL_CastEvent($event);
@ -66,13 +56,21 @@ main: loop {
}
render();
@times.push: nqp::time_n() - $start;
print fps;
}
@times .= sort;
say '';
my @timings = (@times[* div 50], @times[* div 4], @times[* div 2], @times[* * 3 div 4], @times[* - * div 100]);
say "frames per second:";
say (1 X/ @timings).fmt("%3.4f");
sub fps {
state $fps-frames = 0;
state $fps-now = now;
state $fps = '';
$fps-frames++;
if now - $fps-now >= 1 {
$fps = [~] "\b" x 40, ' ' x 20, "\b" x 20 ,
sprintf "FPS: %5.2f ", ($fps-frames / (now - $fps-now)).round(.01);
$fps-frames = 0;
$fps-now = now;
}
$fps
}

View file

@ -0,0 +1,40 @@
use Gtk3 '-init';
use Glib qw/TRUE FALSE/;
use Time::HiRes qw/ tv_interval gettimeofday/;
my $time0 = [gettimeofday];
my $frames = -8; # account for set-up steps before drawing
my $window = Gtk3::Window->new();
$window->set_default_size(320, 240);
$window->set_border_width(0);
$window->set_title("Image_noise");
$window->set_app_paintable(TRUE);
my $da = Gtk3::DrawingArea->new();
$da->signal_connect('draw' => \&draw_in_drawingarea);
$window->add($da);
$window->show_all();
Glib::Timeout->add (1, \&update);
Gtk3->main;
sub draw_in_drawingarea {
my ($widget, $cr, $data) = @_;
$cr->set_line_width(1);
for $x (1..320) {
for $y (1..240) {
int rand 2 ? $cr->set_source_rgb(0, 0, 0) : $cr->set_source_rgb(1, 1, 1);
$cr->rectangle( $x, $y, 1, 1);
$cr->stroke;
}
}
}
sub update {
$da->queue_draw;
my $elapsed = tv_interval( $time0, [gettimeofday] );
$frames++;
printf "fps: %.1f\n", $frames/$elapsed if $frames > 5;
return TRUE;
}

View file

@ -0,0 +1,64 @@
-- demo\rosetta\ImageNoise.exw
include pGUI.e
Ihandle dlg, canvas, timer
cdCanvas cddbuffer, cdcanvas
constant TITLE = "Image noise"
integer fps = 129 -- (typical value)
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
sequence bw = repeat(0,w*h)
for x=0 to w-1 do
for y=0 to h-1 do
if rand(2)=2 then bw[x*h+y+1] = 255 end if
end for
end for
cdCanvasPutImageRectRGB(cddbuffer, w, h, {bw,bw,bw})
cdCanvasFlush(cddbuffer)
fps += 1
return IUP_DEFAULT
end function
atom t1 = time()
function timer_cb(Ihandle /*ih*/)
if time()>t1 then
IupSetStrAttribute(dlg, "TITLE", "%s [%g FPS])",{TITLE,fps})
fps = 0
t1 = time()+1
end if
IupUpdate(canvas)
return IUP_IGNORE
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas(NULL)
IupSetAttribute(canvas, "RASTERSIZE", "320x240")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
timer = IupTimer(Icallback("timer_cb"), 10)
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", TITLE)
IupCloseOnEscape(dlg)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
IupMainLoop()
IupClose()
end procedure
main()

View file

@ -0,0 +1,23 @@
color black = color(0);
color white = color(255);
void setup(){
size(320,240);
// frameRate(300); // 60 by default
}
void draw(){
loadPixels();
for(int i=0; i<pixels.length; i++){
if(random(1)<0.5){
pixels[i] = black;
}else{
pixels[i] = white;
}
}
updatePixels();
fill(0,128);
rect(0,0,60,20);
fill(255);
text(frameRate, 5,15);
}

View file

@ -1,131 +1,142 @@
Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Tell windows we want to handle all the painting and that we want it
' to double buffer the form's rectangle (Double Buffering
' removes/ reduces flickering).
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
' Tell windows we want to handle all the painting and that we want it to double buffer
' the form's rectangle (Double Buffering removes/reduces flickering).
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
' Prevent the user from resizing the window. Our draw code is not
' setup to recalculate on the fly.
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
' Prevent the user from resizing the window. Our draw code is not
' setup to recalculate on the fly.
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
' The window size and the client rectangle aren't the same.
' To get the proper dimensions for our exercise we need to
' figure out the difference and add it to our 320x240
' requirement.
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
' The window size and the client rectangle aren't the same.
' To get the proper dimensions for our exercise we need to
' figure out the difference and add it to our 320x240
' requirement.
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
' Pop the window, bring it to the front and give windows time to
' reflect the changes.
Show()
Activate()
Application.DoEvents()
' Pop the window, bring it to the front and give windows time to
' reflect the changes.
Show()
Activate()
Application.DoEvents()
' Hit the loop and keep going until we receive a close request.
RenderLoop()
' Hit the loop and keep going until we receive a close request.
RenderLoop()
' We're done. Exit the application.
Close()
' We're done. Exit the application.
Close()
End Sub
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
' Close the application when the user hits escape.
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
' Close the application when the user hits escape.
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' We'll cancel the form close request if we're still running so we
' don't get an error during runtime and set the close request flag.
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' We'll cancel the form close request if we're still running so we don't get an error during runtime and set the close request flag.
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width, PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
' Get ourselves a nice, clean, black canvas to work with.
g.Clear(Color.Black)
' Get ourselves a nice, clean, black canvas to work with.
g.Clear(Color.Black)
' Prep our bitmap for a read.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
' Prep our bitmap for a read.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
' Allocate sufficient space for the pixel data and
' flash copy it to our array.
' We want an integer to hold the color for each pixel in the canvas.
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
' Start looping.
Do
' Find our frame time and add it to the total amount of time
' elapsed since our last FPS update (once per second).
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
' Adjust the number of loops since the last whole second has elapsed
iLoops += 1
If fElapsed >= 1.0F Then
' Since we've now had a whole second elapse
' figure the Frames Per Second,
' measure our string,
' setup our backing rectangle for the FPS string
' (so it's clearly visible over the snow)
' reset our loop counter
' and our elapsed counter.
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
' We don't set this to 0 in case our frame time has gone
' a bit over 1 second since last update.
fElapsed -= 1.0F
iLoops = 0
End If
' Allocate sufficient space for the pixel data and
' flash copy it to our array.
' We want an integer to hold the color for each pixel in the canvas.
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
' Generate our snow.
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
' Start looping.
Do
' Find our frame time and add it to the total amount of time
' elapsed since our last FPS update (once per second).
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset()
oStopwatch.Start()
' Prep the bitmap for an update.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
' Flash copy the new data into our bitmap.
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
' Adjust the number of loops since the last whole second has elapsed.
iLoops += 1
' Draw the backing for our FPS display.
g.FillRectangle(Brushes.Black, oFPSBG)
' Draw our FPS.
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
If fElapsed >= 1.0F Then
' Since we've now had a whole second elapse
' figure the Frames Per Second,
' measure our string,
' setup our backing rectangle for the FPS string (so it's clearly visible over the snow)
' reset our loop counter
' and our elapsed counter.
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding - oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F ' We don't set this to 0 incase our frame time has gone a bit over 1 second since last update.
iLoops = 0
End If
' Update the form's background and draw.
BackgroundImage = b
Invalidate(ClientRectangle)
' Generate our snow.
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
' Let windows handle some queued events.
Application.DoEvents()
Loop While bRunning
' Prep the bitmap for an update.
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
' Flash copy the new data into our bitmap.
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0, oPixels.Length)
b.UnlockBits(oBMPData)
' Draw the backing for our FPS display.
g.FillRectangle(Brushes.Black, oFPSBG)
' Draw our FPS.
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
' Update the form's background and draw.
BackgroundImage = b
Invalidate(ClientRectangle)
' Let windows handle some queued events.
Application.DoEvents()
Loop While bRunning
End Sub
End Sub
End Class