Image noise: Difference between revisions

m
m (→‎Optimized example: Fixed typo (hight → height))
 
(32 intermediate revisions by 16 users not shown)
Line 16:
;A sample image: [[Image:NoiseOutput.png|600px||center|sample]]
<br><br>
=={{header|6502 Assembly}}==
{{works with|https://skilldrick.github.io/easy6502/ Easy6502}}
Easy6502's built-in RNG allows for random pixels to be displayed in an infinite loop. Unfortunately these pixels are far too large to
effectively display an FPS counter, although the unused Y register in the program below could theoretically output that.
<syntaxhighlight lang="6502asm">define sysRandom $fe
 
Snow:
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0200,x ;store in first section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0300,x ;store in second section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0400,x ;store in third section of VRAM
 
lda sysRandom ;get a random number
and #$01 ;remove all but bit 0
sta $0500,x ;store in last section of VRAM
 
inx ;next X
jmp Snow ;loop forever</syntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
DEFINE TEXT_SIZE="40"
BYTE ARRAY text(TEXT_SIZE)
 
CARD FUNC GetFrame()
BYTE RTCLOK1=$13,RTCLOK2=$14
CARD res
BYTE lsb=res,msb=res+1
 
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
 
PROC CalcFPS(CARD frames REAL POINTER fps)
BYTE PALNTSC=$D014
REAL ms,r1000
 
IF PALNTSC=15 THEN
frames==*60
ELSE
frames==*50
FI
 
IntToReal(1000,r1000)
IntToReal(frames,ms)
RealDiv(r1000,ms,fps)
RETURN
 
PROC FillNoise()
BYTE POINTER ptr
BYTE x,y,rnd=$D20A
 
ptr=PeekC(88)
FOR y=0 TO 191
DO
FOR x=0 TO 39
DO
ptr^=rnd
ptr==+1
OD
OD
RETURN
 
PROC PrepareScreen()
BYTE COLOR1=$02C5,COLOR2=$02C6
CARD SDLSTL=$0230,ptr
BYTE i,v
BYTE ARRAY dlist(205)
 
Graphics(8+16)
COLOR1=$0F
COLOR2=$00
 
;prepare text
FOR i=0 TO TEXT_SIZE-1
DO
text(i)=0
OD
text(6)='F-32
text(7)='P-32
text(8)='S-32
 
;modify display list to add one row with text on the top
dlist(0)=$70
dlist(1)=$70
dlist(2)=$42
PokeC(dlist+3,text)
ptr=SDLSTL
ptr==+3
FOR i=5 TO 202
DO
dlist(i)=Peek(ptr)
ptr==+1
OD
PokeC(dlist+203,dlist)
 
SDLSTL=dlist
RETURN
 
PROC PrintFPS(REAL POINTER fps)
CHAR ARRAY tmp(20)
BYTE i
 
StrR(fps,tmp)
FOR i=1 TO 5
DO
text(i-1)=tmp(i)-32
OD
RETURN
 
PROC Main()
BYTE CH=$02FC
CARD beg,end
REAL fps
 
PrepareScreen()
beg=GetFrame()
DO
FillNoise()
end=GetFrame()
CalcFPS(end-beg,fps)
PrintFPS(fps)
beg=end
UNTIL CH#$FF
OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Image_noise.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|Lumen}}
noise.ads:
<langsyntaxhighlight Adalang="ada">with Lumen.Image;
 
package Noise is
Line 26 ⟶ 165:
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;
 
end Noise;</langsyntaxhighlight>
 
noise.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Discrete_Random;
 
package body Noise is
Line 56 ⟶ 195:
end Create_Image;
 
end Noise;</langsyntaxhighlight>
 
test_noise.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Calendar;
with Ada.Text_IO;
with System.Address_To_Access_Conversions;
Line 237 ⟶ 376:
when Program_End =>
null;
end Test_Noise;</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 248 ⟶ 387:
This example gets steady 48 FPS on a TI-84 Plus Silver Edition running at 15 MHz. It gets 26 FPS when running at 6 MHz. Some pixels appear gray because the duration of each frame is shorter than the screen's notoriously slow response time. If a pixel is toggled very quickly, it never has time to fully transition to white or black.
 
<langsyntaxhighlight lang="axe">.Enable 15 MHz full speed mode
Full
.Disable memory access delays (adds 1 FPS)
Line 290 ⟶ 429:
Lbl FPS
N++
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> dx% = 320
dy% = 240
images% = 100000
Line 329 ⟶ 468:
SYS "SetWindowText", @hwnd%, "BBC BASIC: " + STR$(frame%*100 DIV TIME) + " fps"
ENDIF
UNTIL FALSE</langsyntaxhighlight>
[[File:image_noise_bbc.jpg]]
 
Line 336 ⟶ 475:
{{libheader|SDL}}
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <time.h>
Line 385 ⟶ 524:
surf = SDL_SetVideoMode(320, 240, 8, SDL_DOUBLEBUF | SDL_HWSURFACE);
blit_noise(surf);
}</langsyntaxhighlight>
===Fast OpenGL method===
{{libheader|GLUT}}
Depending on your hardware, you might be able to get thousands of frames per second. Compiled with <code>gcc -lglut -lGL -g -Wall -O2</code>.
<langsyntaxhighlight lang="c">#include <GL/glut.h>
#include <GL/gl.h>
#include <stdio.h>
Line 435 ⟶ 574:
glutMainLoop();
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Max 185 FPS on .NET 4.0/Windows 7 64-bit on Athlon II X4 620 - ATI Radeon X1200.
 
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
class Program
{
static Size size = new Size(320, 240);
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
 
static PictureBox pb;
static BackgroundWorker worker;
 
static double time = 0;
static double frames = 0;
static Random rand = new Random();
 
static byte tmp;
static byte white = 255;
static byte black = 0;
static int halfmax = int.MaxValue / 2; // more voodoo! calling Next() is faster than Next(2)!
 
static IEnumerable<byte> YieldVodoo()
{
// Yield 3 times same number (i.e 255 255 255) for numpixels times.
 
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white; // no more lists!
 
// no more loops! yield! yield! yield!
yield return tmp;
yield return tmp;
yield return tmp;
}
}
 
static Image Randimg()
{
// Low-level bitmaps
var bitmap = new Bitmap(size.Width, size.Height);
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
 
Marshal.Copy(
YieldVodoo().ToArray<byte>(),// source
0, // start
data.Scan0, // scan0 is a pointer to low-level bitmap data
numbytes); // number of bytes in source
 
bitmap.UnlockBits(data);
return bitmap;
}
 
[STAThread]
static void Main()
{
var form = new Form();
 
form.AutoSize = true;
form.Size = new Size(0, 0);
form.Text = "Test";
 
form.FormClosed += delegate
{
Application.Exit();
};
 
worker = new BackgroundWorker();
 
worker.DoWork += delegate
{
System.Threading.Thread.Sleep(500); // remove try/catch, just wait a bit before looping
 
while (true)
{
var a = DateTime.Now;
pb.Image = Randimg();
var b = DateTime.Now;
 
time += (b - a).TotalSeconds;
frames += 1;
 
if (frames == 30)
{
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
 
time = 0;
frames = 0;
}
}
};
 
worker.RunWorkerAsync();
 
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
 
pb = new PictureBox();
pb.Size = size;
 
flp.AutoSize = true;
flp.Controls.Add(pb);
 
form.Show();
Application.Run();
}
}</syntaxhighlight>
 
=={{header|C++}}==
===Version 1 (windows.h)===
[[File:noise_cpp.png]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <sstream>
Line 671 ⟶ 928:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
===Version 2 (SDL2)===
=={{header|C sharp|C#}}==
{{libheader|SDL2}}
Max 185 FPS on .NET 4.0/Windows 7 64-bit on Athlon II X4 620 - ATI Radeon X1200.
'''Source:''' https://gist.github.com/KatsumiKougen/58c53e77dc45e4e3a13661ff7b38c1ea
<syntaxhighlight lang="cpp">
// Standard C++ stuff
#include <iostream>
#include <string>
#include <random>
 
// SDL2 stuff
<lang csharp>using System;
#include "SDL2/SDL.h"
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
// Other crazy stuffs
class Program
#define SCREEN_WIDTH 320
{
#define SCREEN_HEIGHT 240
static Size size = new Size(320, 240);
#define COLOUR_BLACK 0, 0, 0, 0xff
static Rectangle rectsize = new Rectangle(new Point(0, 0), size);
#define COLOUR_WHITE 0xff, 0xff, 0xff, 0xff
static int numpixels = size.Width * size.Height;
static int numbytes = numpixels * 3;
 
// Compile: g++ -std=c++20 -Wall -Wextra -pedantic ImageNoise.cpp -o ImageNoise -lSDL2
static PictureBox pb;
static BackgroundWorker worker;
 
template <class RandomGenerator>
static double time = 0;
void BlitNoise(SDL_Renderer *r, int width, int height, auto &dist, RandomGenerator &generator) {
static double frames = 0;
staticfor Random(int randy = new0; Random()y < height; ++y) {
for (int x = 0; x < width; ++x) {
 
// Use the random number generator in C++ Standard Library to determine draw colour
static byte tmp;
if (dist(generator) == 0)
static byte white = 255;
// Set colour to black
static byte black = 0;
SDL_SetRenderDrawColor(r, COLOUR_BLACK);
static int halfmax = int.MaxValue / 2; // more voodoo! calling Next() is faster than Next(2)!
else if (dist(generator) == 1)
 
// Set colour to white
static IEnumerable<byte> YieldVodoo()
SDL_SetRenderDrawColor(r, COLOUR_WHITE);
{
// Yield 3 times same number (i.e// 255Go 255through 255)every forscanline, numpixelsand times.put pixels
SDL_RenderDrawPoint(r, x, y);
 
for (int i = 0; i < numpixels; i++)
{
tmp = rand.Next() < halfmax ? black : white; // no more lists!
 
// no more loops! yield! yield! yield!
yield return tmp;
yield return tmp;
yield return tmp;
}
}
}
 
void UpdateFPS(unsigned &frame_count, unsigned &timer, SDL_Window *window) {
static Image Randimg()
static Uint64 LastTime = 0;
{
std::string NewWindowTitle;
// Low-level bitmaps
Uint64 Time = SDL_GetTicks(),
var bitmap = new Bitmap(size.Width, size.Height);
Delta = Time - LastTime;
var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
timer += Delta;
 
if (timer > 1000) Marshal.Copy({
unsigned ElapsedTime = timer / 1000;
YieldVodoo().ToArray<byte>(),// source
NewWindowTitle = "Image noise - " + std::to_string((int)((float)frame_count/(float)ElapsedTime)) + " FPS"; // Dirty string trick
0, // start
SDL_SetWindowTitle(window, const_cast<char*>(NewWindowTitle.c_str()));
data.Scan0, // scan0 is a pointer to low-level bitmap data
timer = 0;
numbytes); // number of bytes in source
frame_count = 0;
 
bitmapNewWindowTitle.UnlockBitsclear(data);
return bitmap;
}
LastTime = Time;
}
 
int main() {
[STAThread]
std::random_device Device; // Random number device
static void Main()
std::mt19937_64 Generator(Device()); // Random number generator
{
std::uniform_int_distribution ColourState(0, 1); // Colour state
var form = new Form();
unsigned Frames = 0,
 
form.AutoSize Timer = true0;
form.Size = new Size(0, 0);
SDL_Window *Window = NULL; // Define window
form.Text = "Test";
SDL_Renderer *Renderer = NULL; // Define renderer
 
form.FormClosed += delegate
// Init everything just {for sure
SDL_Init(SDL_INIT_EVERYTHING);
Application.Exit();
};
// Set window size to 320x240, always shown
 
Window = SDL_CreateWindow("Image noise - ?? FPS", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
worker = new BackgroundWorker();
Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED);
 
worker.DoWork += delegate
// Set background colour {to white
SDL_SetRenderDrawColor(Renderer, COLOUR_WHITE);
System.Threading.Thread.Sleep(500); // remove try/catch, just wait a bit before looping
SDL_RenderClear(Renderer);
 
while (true)
// Create an event handler and a "quit" {flag
SDL_Event e;
var a = DateTime.Now;
bool pb.ImageKillWindow = Randimg()false;
var b = DateTime.Now;
// The window runs until the "quit" flag is set to true
 
while (!KillWindow) {
time += (b - a).TotalSeconds;
while (SDL_PollEvent(&e) != 0) frames += 1;{
// Go through the events in the queue
 
ifswitch (framese.type) == 30){
{// Event: user hits a key
case SDL_QUIT: case SDL_KEYDOWN:
Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time);
// Destroy window
 
timeKillWindow = 0true;
frames = 0break;
}
}
};
// Render the noise
BlitNoise(Renderer, SCREEN_WIDTH, SCREEN_HEIGHT, ColourState, Generator);
SDL_RenderPresent(Renderer);
// Increment the "Frames" variable.
// Then show the FPS count in the window title.
++Frames;
UpdateFPS(Frames, Timer, Window);
}
// Destroy renderer and window
SDL_DestroyRenderer(Renderer);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
</syntaxhighlight>
 
{{output}}
worker.RunWorkerAsync();
<center>[[File:C++ image noise SDL2.gif|280px]]</center>
 
FlowLayoutPanel flp = new FlowLayoutPanel();
form.Controls.Add(flp);
 
pb = new PictureBox();
pb.Size = size;
 
flp.AutoSize = true;
flp.Controls.Add(pb);
 
form.Show();
Application.Run();
}
}</lang>
 
=={{header|Common Lisp}}==
{{libheader|lispbuilder-sdl}}
noise_sdl.lisp:
<langsyntaxhighlight lang="lisp">;; (require :lispbuilder-sdl)
 
(defun draw-noise (surface)
Line 832 ⟶ 1,084:
 
(main)
</syntaxhighlight>
</lang>
 
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight Dlang="d">import std.stdio, std.random, sdl.SDL;
 
void main() {
Line 860 ⟶ 1,111:
lastTime = time;
}
}</langsyntaxhighlight>
This D version shows about 155 FPS, while on the same PC the C version shows about 180 FPS.
 
Generating random bits with the C core.stdc.stdlib.rand the performance becomes about the same of the C version.
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
{{libheader| System.SysUtils}}
{{libheader| Vcl.Forms}}
{{libheader| Vcl.Graphics}}
{{libheader| Vcl.Controls}}
{{libheader| System.Classes}}
{{libheader| Vcl.ExtCtrls}}
<syntaxhighlight lang="delphi">
unit Main;
 
interface
 
uses
Winapi.Windows, System.SysUtils, Vcl.Forms, Vcl.Graphics, Vcl.Controls,
System.Classes, Vcl.ExtCtrls;
 
type
TfmNoise = class(TForm)
tmr1sec: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure tmr1secTimer(Sender: TObject);
end;
 
var
fmNoise: TfmNoise;
Surface: TBitmap;
FrameCount: Cardinal = 0;
 
implementation
 
{$R *.dfm}
 
procedure TfmNoise.FormCreate(Sender: TObject);
begin
Surface := TBitmap.Create;
Surface.SetSize(320, 240);
Surface.PixelFormat := pf1bit;
Randomize;
end;
 
procedure TfmNoise.FormDestroy(Sender: TObject);
begin
Surface.Free;
end;
 
type
PDWordArray = ^TDWordArray;
 
TDWordArray = array[0..16383] of DWord;
 
procedure TfmNoise.FormPaint(Sender: TObject);
var
x, y: Integer;
line: PWordArray;
begin
with Surface do
for y := 0 to Height - 1 do
begin
line := Surface.ScanLine[y];
for x := 0 to (Width div 16) - 1 do
line[x] := Random($FFFF);
// Fill 16 pixels at same time
end;
 
Canvas.Draw(0, 0, Surface);
Inc(FrameCount);
Application.ProcessMessages;
Invalidate;
end;
 
procedure TfmNoise.tmr1secTimer(Sender: TObject);
begin
Caption := 'FPS: ' + FrameCount.ToString;
FrameCount := 0;
end;
 
end.</syntaxhighlight>
Resources form:
<syntaxhighlight lang="delphi">
object fmNoise: TfmNoise
Left = 0
Top = 0
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
Caption = 'fmNoise'
ClientHeight = 240
ClientWidth = 320
OnCreate = FormCreate
OnDestroy = FormDestroy
OnPaint = FormPaint
object tmr1sec: TTimer
Interval = 2000
OnTimer = tmr1secTimer
end
end
</syntaxhighlight>
{{out}}
<pre>
1400 to 1600 FPS
</pre>
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=XZDBqoMwEEX3fsWhi0dLaRp1UbPw/Yi4kDSCUI3EUPTvH9EE+roImTl3Zm4ys7OaeTGelQ2NQGSAti/r0CEc7duwcqcUBdtxB+6M9khRhpOJzE500zB23gSxd1xr8hAOPcu2+GE03PCS38jT6FzyqCI4bG9FTHeLSlLI//p3f5V0b1YfvO+cPz0v/HCin5dTqpPU6VUR9Y6afU5aQNNS0yClRClFu//LOtZQiLeUuUrN1rElnKuE4WO19tW4bnoOk6doY4E4/ET2Bw== Run it]
 
<syntaxhighlight>
proc pset x y c . .
color c
move x / 3.2 y / 3.2
rect 0.3 0.3
.
on animate
fr += 1
if systime - t0 >= 1
move 10 78
color -2
rect 80 20
color -1
move 10 80
text fr / (systime - t0) & " fps"
t0 = systime
fr = 0
.
col[] = [ 000 999 ]
for x = 0 to 319
for y = 0 to 199
pset x y col[randint 2]
.
.
.
</syntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
Line 869 ⟶ 1,252:
Currently, Euler Math Toolbox does not have optimized routines to plot matrices with color information. The frames per second are consequently not really good.
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function noiseimg () ...
$aspect(320,240); clg;
Line 883 ⟶ 1,266:
>noiseimg
2.73544353263
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
This implementation includes two methods to update the pixels values. One uses unsafe methods and can do 350 fps on my machine, the second uses safe code to marshal the new values onto the bitmap data and can do 240 fps on the same machine.
<langsyntaxhighlight lang="fsharp">open System.Windows.Forms
open System.Drawing
open System.Drawing.Imaging
Line 960 ⟶ 1,343:
Application.Run()
0
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
Line 966 ⟶ 1,349:
~150 FPS
 
<langsyntaxhighlight lang="factor">USING: accessors calendar images images.viewer kernel math
math.parser models models.arrow random sequences threads timers
ui ui.gadgets ui.gadgets.labels ui.gadgets.packs ;
Line 1,035 ⟶ 1,418:
MAIN-WINDOW: open-noise-window
{ { title "Black and White noise" } }
<bw-noise-gadget> with-fps >>gadgets ;</langsyntaxhighlight>
 
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
{{libheader|SDL2}}
 
<syntaxhighlight lang="Forth">\ Bindings to SDL2 functions
s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init SDL_Init n -- n
c-function sdl-quit SDL_Quit -- void
c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a
c-function sdl-createrenderer SDL_CreateRenderer a n n -- a
c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n
c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n
c-function sdl-renderpresent SDL_RenderPresent a -- void
c-function sdl-delay SDL_Delay n -- void
c-function sdl-ticks SDL_GetTicks -- n
 
require random.fs
 
0 value window
0 value renderer
240 constant height
320 constant width
 
: black 0 0 0 255 ;
: white 255 255 255 255 ;
: black-or-white 2 random if black else white then ;
 
: init-image ( -- )
$20 sdl-init drop
s\" Rosetta Task : Image Noise\x0" drop 0 0 width height $0 sdl-createwindow to window
window -1 $2 sdl-createrenderer to renderer
page
;
 
: image-noise-generate
height 0 do
width 0 do
renderer black-or-white sdl-setdrawcolor drop
renderer i j sdl-drawpoint drop
loop
loop
;
 
: .FPS swap - 1000 swap / 0 0 at-xy . ." FPS" ;
 
: image-noise
init-image
100 0 do
sdl-ticks
image-noise-generate renderer sdl-renderpresent
sdl-ticks .FPS
loop
sdl-quit
;
 
image-noise</syntaxhighlight>
 
 
 
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 13-07-2018
' compile with: fbc -s console
' or: fbc -s gui
Line 1,074 ⟶ 1,518:
WindowTitle "fps = " + Str(fps)
 
Wend</langsyntaxhighlight>
 
 
=={{header|FutureBasic}}==
FB has native image noise filters.
<syntaxhighlight lang="futurebasic">
 
_window = 1
begin enum output 1
_noiseView
_fpsLabel
end enum
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 340, 300 )
window _window, @"Rosetta Code Image Noise", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
r = fn CGRectMake( 10, 50, 320, 240 )
imageview _noiseView, YES, , r, NSImageScaleAxesIndependently, NSImageAlignCenter, NSImageFrameNone, _window
r = fn CGRectMake( 20, 10, 280, 24 )
textlabel _fpsLabel, @"Estimated FPS: 60", r, _window
ControlSetAlignment( _fpsLabel, NSTextAlignmentCenter )
end fn
 
local fn CIImageToImageRef( ciImage as CIImageRef ) as ImageRef
CIImageRepRef rep = fn CIImageRepWithCIImage( ciImage )
CGSize size = fn ImageRepSize( rep )
ImageRef image = fn ImageWithSize( size )
ImageAddRepresentation( image, rep )
end fn = image
 
local fn NoiseCIImage as CIImageRef
CIFilterRef filter = fn CIFilterWithName( @"CIPhotoEffectNoir" )
ObjectSetValueForKey( filter, fn ObjectValueForKey( fn CIFilterWithName(@"CIRandomGenerator"), @"outputImage" ), @"inputImage" )
CIFilterSetDefaults( filter )
CIImageRef outputCIImage = fn CIImageByCroppingToRect( fn CIFilterOutputImage( filter ), fn CGRectMake( rnd(1000), rnd(1000), 500, 500 ) )
end fn = outputCIImage
 
local fn BuildNoiseView
block NSInteger renderedFrames
renderedFrames = 0
timerbegin, 1.0/60, YES
CIImageRef noiseCIImage = fn NoiseCIImage
ImageRef noiseImage = fn CIImageToImageRef( noiseCIImage )
ImageViewSetImage( _noiseView, noiseImage )
renderedFrames++
if( renderedFrames == 60 )
ControlSetStringValue( _fpsLabel, fn StringWithFormat( @"Estimated FPS: %ld", renderedFrames ) )
renderedFrames = 0
end if
timerend
end fn
 
void local fn DoDialog( ev as long, tag as long, wnd as long )
select ( ev )
case _windowWillClose : end
end select
end fn
 
 
randomize
 
on dialog fn DoDialog
 
fn BuildWindow
fn BuildNoiseView
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Image Noise.png]]
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,164 ⟶ 1,682:
}
}
</syntaxhighlight>
</lang>
===Optimized example===
A second example that is somewhat more optimized but maybe more complicated.
(~3000fps on a Thinkpad x220 laptop)
<langsyntaxhighlight lang="go">package main
 
/* Note, the x-go-binding/ui/x11 lib is under development and has as a temp solution
Line 1,266 ⟶ 1,784:
}
}
</syntaxhighlight>
</lang>
[[File:GoNoise.png]]
 
Line 1,272 ⟶ 1,790:
This uses the GLFW-b bindings for GLFW 3 support:
<pre>cabal install glfw-b</pre>
<langsyntaxhighlight Haskelllang="haskell">import qualified Graphics.Rendering.OpenGL as GL
import qualified Graphics.UI.GLFW as GLFW
import qualified Foreign as F
Line 1,339 ⟶ 1,857:
case key of
GLFW.Key'Q -> GLFW.setWindowShouldClose win True
_ -> return ()</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,349 ⟶ 1,867:
* Using DrawImage to draw a randomly constructed bi-level images(see pg 157 of the graphics book, speed ~= 10x)
 
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 1,367 ⟶ 1,885:
Event() # wait for any window event
close(&window)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides a family of print formatting routines]
 
=={{header|J}}==
<langsyntaxhighlight lang="j">coclass'example'
(coinsert[require)'jzopengl'
Line 1,420 ⟶ 1,938:
)
p_run''</langsyntaxhighlight>
 
The script auto-starts when run (that last line <code><nowiki>p_run''</nowiki></code> is responsible for the auto-start.
Line 1,440 ⟶ 1,958:
 
- Very fast: 1000+ FPS on a 2.8 GHz Core Duo (with 64-bit JRE). This is capped because the maximum resolution of the timers available is 1 ms
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
Line 1,559 ⟶ 2,077:
});
}
}</langsyntaxhighlight>[[File:javanoise2.png]]
 
=={{header|JavaScript}}==
[http://jsfiddle.net/bZJvr/ jsFiddle Demo]
 
<langsyntaxhighlight lang="javascript"><body>
<canvas id='c'></canvas>
 
Line 1,612 ⟶ 2,130:
animate();
</script>
</body></langsyntaxhighlight>
About 59 frames/second on Firefox 4.
 
=={{header|Julia}}==
With Gtk, gets about 80 frames per second on a older, dual core 3 Ghz processor.
<langsyntaxhighlight lang="julia">using Gtk, GtkUtilities
 
function randbw(ctx, w, h)
Line 1,656 ⟶ 2,174:
 
wait(cond)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import java.awt.*
Line 1,776 ⟶ 2,294:
}
})
}</langsyntaxhighlight>
 
{{out}}
Line 1,785 ⟶ 2,303:
=={{header|Liberty BASIC}}==
Generates the random bitmap programmatically, then chops it each time in a different way.
<syntaxhighlight lang="lb">
<lang lb>
WindowWidth =411
w =320
Line 1,858 ⟶ 2,376:
close #w
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
*Note, you will need to insert a plot component to get this to work.
<syntaxhighlight lang="maple">
<lang Maple>
a:=0;
t:=time[real]();
Line 1,873 ⟶ 2,391:
 
end do:
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>
time = AbsoluteTime[]; Animate[
Column[{Row[{"FPS: ", Round[n/(AbsoluteTime[] - time)]}],
RandomImage[1, {320, 240}]}], {n, 1, Infinity, 1}]
</syntaxhighlight>
</lang>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
try destroydialog testRollout catch ()
Line 1,917 ⟶ 2,435:
createdialog testrollout
</syntaxhighlight>
</lang>
 
=={{header|MiniScript}}==
This implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
clear
tileSetLength = 32
width = 320
height = 240
cellSize = [960/width, 600/height]
colors = [color.black, color.white]
 
newImg = function
img = Image.create(tileSetLength, 1)
for i in range(0, tileSetLength - 1)
img.setPixel i, 0, colors[rnd * 2]
end for
return img
end function
 
display(5).mode = displayMode.tile
td = display(5)
td.cellSize = cellSize
td.extent = [width, height]
td.tileSetTileSize = 1
for x in range(0, width - 1)
for y in range(0, height - 1)
td.setCell x, y, rnd * tileSetLength
end for
end for
frames = 0
startTime = time
while true
td.tileSet = newImg
frames += 1
dt = time - startTime
if dt >= 1 then
text.row = 25; print "FPS: " + round(frames / dt, 2)
frames = 0
startTime = time
end if
end while
</syntaxhighlight>
[[File:Minimicro-noise-32.gif]]
 
=={{header|Nim}}==
 
===Using OpenGL===
 
{{trans|C}}
{{libheader|OpenGL}}
 
On a small laptop running Manjaro and without a dedicated graphic card, we get 550-600 FPS.
 
<syntaxhighlight lang="nim">import times
 
import opengl
import opengl/glut
 
const
W = 320
H = 240
SLen = W * H div sizeof(int)
 
var
frame = 0
bits: array[SLen, uint]
last, start: Time
 
#---------------------------------------------------------------------------------------------------
 
proc render() {.cdecl.} =
## Render the window.
 
var r = bits[0] + 1
for i in countdown(bits.high, 0):
r *= 1103515245
bits[i] = r xor bits[i] shr 16
 
glClear(GL_COLOR_BUFFER_BIT)
glBitmap(W, H, 0, 0, 0, 0, cast[ptr GLubyte](bits.addr))
glFlush()
 
inc frame
if (frame and 15) == 0:
let t = getTime()
if t > last:
last = t
echo "fps: ", frame.float / (t - start).inSeconds.float
 
#---------------------------------------------------------------------------------------------------
 
proc initGfx(argc: ptr cint; argv: pointer) =
## Initialize OpenGL rendering.
 
glutInit(argc, argv)
glutInitDisplayMode(GLUT_RGB)
glutInitWindowSize(W, H)
glutIdleFunc(render)
discard glutCreateWindow("Noise")
glutDisplayFunc(render)
loadExtensions()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
var argc: cint = 0
initGfx(addr(argc), nil)
start = getTime()
last = start
glutMainLoop()</syntaxhighlight>
 
===Using library "Rapid"===
{{libheader|rapid}}
 
Unfortunately, these examples no longer work for some reason.
 
Naive implementation:
 
<langsyntaxhighlight lang="nim">import random
 
import rapid/gfx
Line 1,947 ⟶ 2,576:
echo 1 / (step / 60)
update step:
discard step</langsyntaxhighlight>
 
Optimized implementation using shaders:
 
<langsyntaxhighlight lang="nim">import random
 
import rapid/gfx
Line 1,985 ⟶ 2,614:
echo 1 / (step / 60)
update step:
discard step</langsyntaxhighlight>
 
On a Ryzen 5 1600 and a Vega 56 the naive implementation struggles to maintain 10 FPS. The GPU-powered version, however, reaches up to 12000-13000 FPS.
Line 1,992 ⟶ 2,621:
{{libheader|OCamlSDL}}
with the [[OCamlSDL|ocaml-sdl]] bindings:
<langsyntaxhighlight lang="ocaml">let frames =
{ contents = 0 }
 
Line 2,040 ⟶ 2,669:
in
Sys.catch_break true;
blit_noise surf</langsyntaxhighlight>
 
compile to native-code with:
Line 2,058 ⟶ 2,687:
 
In a more idiomatic way, using the modules Graphics and Unix from the standard OCaml library:
<langsyntaxhighlight lang="ocaml">open Graphics
 
let white = (rgb 255 255 255)
Line 2,084 ⟶ 2,713:
with _ ->
flush stdout;
close_graph ()</langsyntaxhighlight>
 
run this script with:
Line 2,096 ⟶ 2,725:
 
[[Image_Noise/OCaml/OpenGL|Equivalent]] of the C-OpenGL method.
 
=={{header|Perl}}==
<lang perl>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;
}</lang>
 
=={{header|Perl 6}}==
Variant of a script packaged with the SDL2::Raw module.
 
<lang perl6>use NativeCall;
use SDL2::Raw;
 
my int ($w, $h) = 320, 240;
 
SDL_Init(VIDEO);
 
my SDL_Window $window = SDL_CreateWindow(
"White Noise - Perl 6",
SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
$w, $h,
RESIZABLE
);
 
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, $w, $h, $w);
 
sub render {
my int $pitch;
my int $cursor;
 
# work-around to pass the pointer-pointer.
my $pixdata = nativecast(Pointer[int64], $pixdatabuf);
SDL_LockTexture($noise_texture, SDL_Rect, $pixdata, $pitch);
 
$pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));
 
loop (my int $row; $row < $h; $row = $row + 1) {
loop (my int $col; $col < $w; $col = $col + 1) {
$pixdata[$cursor + $col] = Bool.roll ?? 0xff !! 0x0;
}
$cursor = $cursor + $pitch;
}
 
SDL_UnlockTexture($noise_texture);
 
SDL_RenderCopy($renderer, $noise_texture, SDL_Rect, SDL_Rect);
SDL_RenderPresent($renderer);
}
 
my $event = SDL_Event.new;
 
main: loop {
 
while SDL_PollEvent($event) {
my $casted_event = SDL_CastEvent($event);
 
given $casted_event {
when *.type == QUIT {
last main;
}
}
}
 
render();
print fps;
}
 
say '';
 
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
}</lang>
 
=={{header|Pascal}}==
Line 2,223 ⟶ 2,730:
{{libheader|SDL}}
It is SDL-internally limited to 200 fps.
<langsyntaxhighlight lang="pascal">Program ImageNoise;
 
uses
Line 2,264 ⟶ 2,771:
lastTime := time;
end;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">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;
}</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
Not optimised, gets about 130 fps.
<langsyntaxhighlight Phixlang="phix">-- demo\rosetta\ImageNoise.exw
include pGUI.e
 
Line 2,324 ⟶ 2,873:
dlg = IupDialog(canvas)
IupSetAttribute(dlg, "TITLE", TITLE)
IupCloseOnEscape(dlg)
 
IupShow(dlg)
Line 2,332 ⟶ 2,880:
end procedure
 
main()</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
This solution works on ErsatzLisp, the Java version of PicoLisp. It creates a 'JFrame' window, and calls inlined Java code to handle the image.
<langsyntaxhighlight PicoLisplang="picolisp">(javac "ImageNoise" "JPanel" NIL
"java.util.*"
"java.awt.*" "java.awt.image.*" "javax.swing.*" )
Line 2,386 ⟶ 2,934:
 
# Start with 25 frames per second
(imageNoise 320 240 25)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="text">Image_Noise: procedure options (main); /* 3 November 2013 */
declare (start_time, end_time) float (18);
declare (frame, m, n) fixed binary;
Line 2,415 ⟶ 2,963:
end display;
 
end Image_Noise;</langsyntaxhighlight>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">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);
}</syntaxhighlight>
 
==={{header|Processing Python mode}}===
<syntaxhighlight lang="python">black = color(0)
white = color(255)
 
def setup():
size(320, 240)
# frameRate(30) # 60 by default
 
 
def draw():
loadPixels()
for i in range(len(pixels)):
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)</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#filter=0.2 ; Filter parameter for the FPS-calculation
#UpdateFreq=100 ; How often to update the FPS-display
 
Line 2,453 ⟶ 3,049:
Until Not Event
EndIf
ForEver</langsyntaxhighlight>
[[Image:Image_Noise_in_PureBasic.png‎]]
 
Line 2,460 ⟶ 3,056:
{{libheader|PIL}}
 
<langsyntaxhighlight lang="python">import time
import random
import Tkintertkinter
from PIL import Image, ImageTk # PIL libray
from PIL import ImageTk
 
 
class App(object):
class App:
def __init__(self, size, root):
self.root = root
self.root.title("Image Noise Test")
 
self.img = Image.new("RGB1", size)
self.label = Tkintertkinter.Label(root)
self.label.pack()
 
Line 2,477 ⟶ 3,075:
self.frames = 0
self.size = size
self.n_pixels = self.size[0] * self.size[1]
 
self.loop()
 
def loop(self):
self.tastart_time = time.time()
# 13 FPS boost. half integer idea from C#.
rnd = random.random
white = (255, 255, 255)
black = (0, 0, 0)
npixels = self.size[0] * self.size[1]
data = [white if rnd() > 0.5 else black for i in xrange(npixels)]
self.img.putdata(data)
self.pimg = ImageTk.PhotoImage(self.img)
self.label["image"] = self.pimg
self.tb = time.time()
 
self.time += img.putdata(self.tb - self.ta)
[255 if b > 127 else 0 for b in random.randbytes(self.n_pixels)]
)
 
self.bitmap_image = ImageTk.BitmapImage(self.img)
self.label["image"] = self.bitmap_image
 
end_time = time.time()
self.time += end_time - start_time
self.frames += 1
 
if self.frames == 30:
try:
self.fps = self.frames / self.time
except ZeroDivisionError:
self.fps = "INSTANT"
 
print ("%d frames in %3.2f seconds (%s FPS)" %
print(f"{self.frames,} frames in {self.time,:3.2f} self.seconds ({fps} FPS)")
self.time = 0
self.frames = 0
 
self.root.after(1, self.loop)
 
 
def main():
root = Tkintertkinter.Tk()
app = App((320, 240), root)
root.mainloop()
 
 
main()</lang>
if __name__ == "__main__":
About 28 FPS max, Python 2.6.6.
main()
</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require 2htdp/image 2htdp/universe)
Line 2,543 ⟶ 3,144:
[on-draw draw]
[on-tick handle-tick (/ 1. 120)])
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Variant of a script packaged with the SDL2::Raw module.
 
<syntaxhighlight lang="raku" line>use NativeCall;
use SDL2::Raw;
 
my int ($w, $h) = 320, 240;
 
SDL_Init(VIDEO);
 
my SDL_Window $window = SDL_CreateWindow(
"White Noise - Raku",
SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,
$w, $h,
RESIZABLE
);
 
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, $w, $h, $w);
 
sub render {
my int $pitch;
my int $cursor;
 
# work-around to pass the pointer-pointer.
my $pixdata = nativecast(Pointer[int64], $pixdatabuf);
SDL_LockTexture($noise_texture, SDL_Rect, $pixdata, $pitch);
 
$pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));
 
loop (my int $row; $row < $h; $row = $row + 1) {
loop (my int $col; $col < $w; $col = $col + 1) {
$pixdata[$cursor + $col] = Bool.roll ?? 0xff !! 0x0;
}
$cursor = $cursor + $pitch;
}
 
SDL_UnlockTexture($noise_texture);
 
SDL_RenderCopy($renderer, $noise_texture, SDL_Rect, SDL_Rect);
SDL_RenderPresent($renderer);
}
 
my $event = SDL_Event.new;
 
main: loop {
 
while SDL_PollEvent($event) {
my $casted_event = SDL_CastEvent($event);
 
given $casted_event {
when *.type == QUIT {
last main;
}
}
}
 
render();
print fps;
}
 
say '';
 
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
}</syntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program times (elapsed) the generation of 100 frames of random black&white image.*/
parse arg sw sd im . /*obtain optional args from the C.L. */
if sw=='' | sw=="," then sw=320 /*SW specified? No, then use default.*/
Line 2,568 ⟶ 3,250:
$=$ || _ /*append row to $ string.*/
end /*y*/ /* [↑] build the image. */
return</langsyntaxhighlight>
 
=={{header|RPL}}==
RPL can only handle 131x64 screens. Despite such a small size, displaying graphics is very slow: FPH (frames Per Hour) would be a more appropriate unit.
====HP 28/48 version====
≪ TICKS (0,0) PMIN (130,64) PMAX
'''DO'''
CLLCD
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LAST INV 3 DISP '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x y R→C PIXEL '''END'''
'''NEXT NEXT'''
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
HP-28 users shall replace <code>TICKS</code> by a <code>SYSEVAL</code> call, which address value depends on their ROM version.
====HP-48G version====
From the HP-48G model, the graphics system has been completely reviewed, and so the commands:
≪ TICKS
'''DO'''
ERASE
'''IF''' TICKS OVER - 8192 / B→R '''THEN'''
LASTARG INV 1 →GROB PICT RCL {#0h #42h} ROT GOR PICT STO {#0 #0} PVIEW '''END'''
0 130 '''FOR''' x
0 63 '''FOR''' y
'''IF''' RAND 0.5 > '''THEN''' x R→B y R→B 2 →LIST PIXON '''END'''
'''NEXT NEXT'''
{#0 #0} PVIEW
'''UNTIL''' 0 '''END'''
≫ '<span style="color:blue">NOISE</span>' STO
FPS = 0.0095
 
=={{header|Ruby}}==
Line 2,574 ⟶ 3,287:
{{libheader|ruby-opengl}}
 
<langsyntaxhighlight lang="ruby">require 'rubygems'
require 'gl'
require 'glut'
Line 2,596 ⟶ 3,309:
 
Glut.glutCreateWindow "noise"
Glut.glutMainLoop</langsyntaxhighlight>
 
{{libheader|rubygems}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby.
<syntaxhighlight lang="ruby">
PALLETE = %w[#000000 #FFFFFF]
attr_reader :black, :dim, :white
def settings
size(320, 240)
end
 
def setup
sketch_title 'Image Noise'
@black = color(PALLETE[0])
@white = color(PALLETE[1])
@dim = width * height
load_pixels
end
 
def draw
dim.times { |idx| pixels[idx] = (rand < 0.5) ? black : white }
update_pixels
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frame_rate, 5, 15)
end
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">begSec = time$("seconds")
graphic #g, 320,240
tics = 320 * 240
Line 2,611 ⟶ 3,352:
print "Seconds;";totSec;" Count:";tics;" Tics / sec:";tics/totSec;" fps:";1/totSec
render #g
#g "flush"</langsyntaxhighlight>
 
=={{header|Scala}}==
This is basically the same as the Java version, except without using BufferedImage.
<langsyntaxhighlight lang="scala">
import java.awt.event.{ActionEvent, ActionListener}
import swing.{Panel, MainFrame, SimpleSwingApplication}
Line 2,661 ⟶ 3,402:
repainter.start()
framerateChecker.start()
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tk
 
proc generate {img width height} {
Line 2,698 ⟶ 3,440:
pack [label .l -image noise]
update
looper</langsyntaxhighlight>
 
{{omit from|PARI/GP}}
Line 2,705 ⟶ 3,447:
Windows Forms Application.
 
<langsyntaxhighlight lang="vbnet">Imports System.Drawing.Imaging
 
Public Class frmSnowExercise
Line 2,847 ⟶ 3,589:
End Sub
End Class
</syntaxhighlight>
</lang>
Sample:<BR>
[[Image:SHSnowExercise.jpg]]
 
=={{header|Wren}}==
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "dome" for Window
import "graphics" for Canvas, Color
import "random" for Random
 
class Game {
static init() {
Window.title = "Image Noise"
__w = 320
__h = 240
Window.resize(__w, __h)
Canvas.resize(__w, __h)
__r = Random.new()
__t = System.clock
}
 
static update() {}
 
static draw(dt) {
Canvas.cls() // default background is black
for (x in 0...__w) {
for (y in 0...__h) {
if (__r.int(2) == 0) {
Canvas.pset(x, y, Color.white)
}
}
}
var t = System.clock
var fps = (1/(t - __t)).round
Canvas.print("FPS: %(fps)", 10, 10, Color.red)
__t = t
}
}</syntaxhighlight>
 
=={{header|XPL0}}==
Line 2,855 ⟶ 3,632:
intrinsic could display this image at 327 FPS if Ran(2) was faster.)
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int CpuReg, \address of CPU register array (from GetReg)
FPS, \frames per second, the display's update rate
Line 2,880 ⟶ 3,657:
until KeyHit;
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{works with|Game Boy Color}}
Omitting the initialization code and the other logic keeping the machine working, this will focus solely on the code responsible for creating the effect. The "random" noise was generated by loading this program's ROM image in YY-CHR (a binary file editor) and copying it to its own file, then loading that file into the Game Boy Color's video memory. The framerate is usually 60 FPS but occasionally dips to 59. At first, every tile on screen is the same, but the "noise" effect is caused by:
 
* A "frame timer" variable that increments every vertical blank is used as a pseudo-RNG.
* A variable called "cosine_index" is incremented and its cosine is taken, then the screen is scrolled by that amount.
* Each iteration of the main game loop alters the interrupt handler (which is executed in RAM, having been copied from ROM before the main game loop begins) so that the sine is taken rather than the cosine.
* During the main game loop, the frame timer is also used to select a random graphics tile from among 16 possibilities, and draws it to a randomly selected tile on screen using a simple "xor-shift" routine.
 
<syntaxhighlight lang="z80">forever:
ld hl,frametimer
ld a,(hl)
rrca
rrca
rrca
xor (hl) ;crude xorshift rng used to select a "random" location to draw to.
 
ld h,0
ld L,a ;this random value becomes the low byte of HL
 
rlc L
rl h ;reduce the RNG's bias towards the top of the screen by shifting one bit into H.
ld a,&98 ;high byte of gb vram
add h ;h will equal either 0 or 1.
ld H,a ;now H will either equal &98 or &99
ld a,(frametimer) ;it's possible that this value is different from before since every vblank it increments.
;the vblank code was omitted because it's mostly irrelevant to the task.
and &0f ;select one of sixteen tiles to draw to the screen at the randomly chosen VRAM location.
call LCDWait ;disable interrupts, and wait until the Game Boy is ready to update the tilemap
ei ;enable interrupts again.
ld (hl),a ;now we can store the frame timer AND &0F into video ram.
ld hl,vblankflag ;set to 1 by the vblank routine.
xor a
wait:
halt ;waits for an interrupt.
cp (hl) compare 0 to vblankflag
jr z,wait ;vblank flag is still 1 so keep waiting.
ld (hl),a ;clear vblank flag.
 
 
ld hl,&FFFF ;master interrupt register
res 1,(hl) ;disable hblank interrupt.
 
ld bc,2
ld a,(frametimer)
bit 4,a ;check bit 4 of frametimer, if zero, we'll do sine instead of cosine. Bit 4 was chosen arbitrarily.
jr nz,doSine
ld hl,cos
jr nowStore
doSine:
ld hl,sin
nowStore: ;store desired routine as the CALL address
ld a,L
LD (&A000+(callpoint-TV_Static_FX+1)),a
;using label arithmetic we can work out the place to modify the code.
;hblank interrupt immediately jumps to cartridge RAM at &A000
ld a,H
LD (&A000+(callpoint-TV_Static_FX+2)),a ;store the high byte.
 
ld hl,&FFFF
set 1,(hl) ;re-enable hblank interrupt
 
jp forever</syntaxhighlight>
 
And the interrupt handler located at memory address <code>&A000</code>:
<syntaxhighlight lang="z80">TV_Static_FX:
;this code runs every time the game boy finishes drawing one row of pixels, unless the interrupt is disabled as described above.
push hl
push af
ld hl,(COSINE_INDEX)
inc (hl)
ld a,(hl)
 
callpoint:
call cos ;<--- SMC, gets changed to "CALL SIN" by main game loop when bit 4 of frametimer equals 0, and back to
;"CALL COS" when bit 4 of frametimer equals 1.
; returns cos(A) into A
 
LD (&FF43),A ;output cos(frametimer) to horizontal scroll register
done_TV_Static_FX:
pop af
pop hl
reti ;return to main program
TV_Static_FX_End:</syntaxhighlight>
 
{{out}}
[https://ibb.co/Ns7jy0x Output image of program]
1,983

edits