Munching squares: Difference between revisions
No more a draft task. |
|||
Line 1:
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from a color table.
|
Revision as of 12:14, 18 May 2013
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from a color table.
Ada
Uses the Cairo component of GtkAda to create and save as png <lang Ada>with Cairo; use Cairo; with Cairo.Png; use Cairo.Png; with Cairo.Image_Surface; use Cairo.Image_Surface; procedure XorPattern is
type xorable is mod 256; Surface : Cairo_Surface; Data : RGB24_Array_Access; Status : Cairo_Status; Num : Byte;
begin
Data := new RGB24_Array(0..256*256-1); for x in Natural range 0..255 loop for y in Natural range 0..255 loop Num := Byte(xorable(x) xor xorable(y)); Data(x+256*y) := RGB24_Data'(Num,0,Num); end loop; end loop; Surface := Create_For_Data_RGB24(Data, 256, 256); Status := Write_To_Png (Surface, "AdaXorPattern.png"); pragma Assert (Status = Cairo_Status_Success);
Burlesque
<lang burlesque> blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24 2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13 18 19 16 17 22 23 20 21 26 27 3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 19 18 17 16 23 22 21 20 27 26 4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11 20 21 22 23 16 17 18 19 28 29 5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10 21 20 23 22 17 16 19 18 29 28 6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9 22 23 20 21 18 19 16 17 30 31 7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8 23 22 21 20 19 18 17 16 31 30 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 24 25 26 27 28 29 30 31 16 17 9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6 25 24 27 26 29 28 31 30 17 16
10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5 26 27 24 25 30 31 28 29 18 19 11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4 27 26 25 24 31 30 29 28 19 18 12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3 28 29 30 31 24 25 26 27 20 21 13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2 29 28 31 30 25 24 27 26 21 20 14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1 30 31 28 29 26 27 24 25 22 23 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 23 22 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 1 2 3 4 5 6 7 8 9 17 16 19 18 21 20 23 22 25 24 27 26 29 28 31 30 1 0 3 2 5 4 7 6 9 8 18 19 16 17 22 23 20 21 26 27 24 25 30 31 28 29 2 3 0 1 6 7 4 5 10 11 19 18 17 16 23 22 21 20 27 26 25 24 31 30 29 28 3 2 1 0 7 6 5 4 11 10 20 21 22 23 16 17 18 19 28 29 30 31 24 25 26 27 4 5 6 7 0 1 2 3 12 13 21 20 23 22 17 16 19 18 29 28 31 30 25 24 27 26 5 4 7 6 1 0 3 2 13 12 22 23 20 21 18 19 16 17 30 31 28 29 26 27 24 25 6 7 4 5 2 3 0 1 14 15 23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24 7 6 5 4 3 2 1 0 15 14 24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23 8 9 10 11 12 13 14 15 0 1 25 24 27 26 29 28 31 30 17 16 19 18 21 20 23 22 9 8 11 10 13 12 15 14 1 0 </lang>
Must be converted to an image with a seperatae program.
C
<lang c>#include <stdlib.h>
- include <stdio.h>
- include <math.h>
- include <string.h>
void hue_to_rgb(double hue, double sat, unsigned char *p) { double x; int c = 255 * sat; hue /= 60; x = (1 - fabs(fmod(hue, 2) - 1)) * 255;
switch((int)hue) { case 0: p[0] = c; p[1] = x; p[2] = 0; return; case 1: p[0] = x; p[1] = c; p[2] = 0; return; case 2: p[0] = 0; p[1] = c; p[2] = x; return; case 3: p[0] = 0; p[1] = x; p[2] = c; return; case 4: p[0] = x; p[1] = 0; p[2] = c; return; case 5: p[0] = c; p[1] = 0; p[2] = x; return; } }
int main(void) { const int size = 512; int i, j; unsigned char *colors = malloc(size * 3); unsigned char *pix = malloc(size * size * 3), *p; FILE *fp;
for (i = 0; i < size; i++) hue_to_rgb(i * 240. / size, i * 1. / size, colors + 3 * i);
for (i = 0, p = pix; i < size; i++) for (j = 0; j < size; j++, p += 3) memcpy(p, colors + (i ^ j) * 3, 3);
fp = fopen("xor.ppm", "wb"); fprintf(fp, "P6\n%d %d\n255\n", size, size); fwrite(pix, size * size * 3, 1, fp); fclose(fp);
C++
- include <windows.h>
- include <string>
//-------------------------------------------------------------------------------------------------- using namespace std;
//-------------------------------------------------------------------------------------------------- const int BMP_SIZE = 512;
//-------------------------------------------------------------------------------------------------- class myBitmap { public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() {
DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp );
} bool create( int w, int h ) {
BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;
hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h; return true;
} void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
} void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush );
} void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) {
BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );
delete [] dwpBits;
} HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen );
} HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr;
}; //-------------------------------------------------------------------------------------------------- class mSquares { public:
mSquares() { bmp.create( BMP_SIZE, BMP_SIZE ); createPallete(); }
void draw() {
HDC dc = bmp.getDC(); for( int y = 0; y < BMP_SIZE; y++ ) for( int x = 0; x < BMP_SIZE; x++ ) { int c = ( x ^ y ) % 256; SetPixel( dc, x, y, clrs[c] ); }
BitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); //bmp.saveBitmap( "f:\\rc\\msquares_cpp.bmp" );
}
private:
void createPallete() {
for( int x = 0; x < 256; x++ ) clrs[x] = RGB( x<<1, x, x<<2 );//rand() % 180 + 50, rand() % 200 + 50, rand() % 180 + 50 );
}
unsigned int clrs[256]; myBitmap bmp;
}; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) {
ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); srand( GetTickCount() ); mSquares s; s.draw(); return system( "pause" );
} //-------------------------------------------------------------------------------------------------- </lang>
C#
<lang csharp>using System.Drawing; using System.Drawing.Imaging; using System.Linq;
class XORPattern {
static void Main() { var size = 0x100; var black = Color.Black.ToArgb(); var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray(); using (var image = new Bitmap(size, size)) { for (var x = 0; x < size; x++) { for (var y = 0; y < size; y++) { image.SetPixel(x, y, palette[x ^ y]); } } image.Save("XORPatternCSharp.png", ImageFormat.Png); } }
}</lang> Output:
D
<lang d>import std.stdio;
void main() {
enum width = 512, height = 512;
auto f = File("xor_pattern.ppm", "wb"); f.writefln("P6\n%d %d\n255", width, height); foreach (y; 0 .. height) foreach (x; 0 .. width) { ubyte c = (x ^ y) & ubyte.max; f.rawWrite(cast(ubyte[3])[255 - c, c / 2, c]); }
}</lang>
Gnuplot
<lang gnuplot>set pm3d map set size square set isosamples 255,255 splot [0:255][0:255]-(floor(x)^floor(y))</lang>
Haskell
<lang haskell>import Data.ByteString import Data.Bits
main = Data.ByteString.writeFile "out.pgm" (pack (fmap (fromIntegral . fromEnum) "P5\n256 256\n256\n" ++ [x `xor` y | x <- [0..255], y <- [0..255]])) </lang>
Go
<lang go>package main
import (
"image" "image/png" "os"
)
func main() {
g := image.NewGray(image.Rect(0, 0, 256, 256)) for i := range g.Pix { g.Pix[i] = uint8(i>>8 ^ i) } f, _ := os.Create("xor.png") png.Encode(f, g) f.Close()
}</lang>
Icon and Unicon
![](http://static.miraheze.org/rosettacodewiki/thumb/f/fe/XORimage-unicon-GR512.png/300px-XORimage-unicon-GR512.png)
<lang Icon>link printf
procedure main(A) #: XOR graphic
wsize := 512 cmax := 32768 wparms := ["Xmas Xor Graphic","g",sprintf("size=%d,%d",wsize),"bg=black"] &window := open!wparms | stop("Unable to open window") every y := 0 to wsize - 1 do every x := 0 to wsize - 1 do { c := cmax/wsize * iand(wsize-1,ixor(x,y)) Fg(sprintf("%d,%d,%d",c,cmax-c,0)) DrawPoint(x,y) } until Event() == &lpress # wait for left button to quit close(&window)
end</lang>
printf.icn provides formatting
J
<lang J> require 'viewmat'
viewmat ~:"1/&.#: ~ i.256</lang>
Java
This example will repeat the pattern if you expand the window. <lang java>import java.awt.Color; import java.awt.Graphics;
import javax.swing.JFrame; import javax.swing.JPanel;
public class XorPattern extends JFrame{
private JPanel xorPanel;
public XorPattern(){ xorPanel = new JPanel(){ @Override public void paint(Graphics g) { for(int y = 0; y < getHeight();y++){ for(int x = 0; x < getWidth();x++){ g.setColor(new Color(0, (x ^ y) % 256, 0)); g.drawLine(x, y, x, y); } } } }; add(xorPanel); setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
public static void main(String[] args){ new XorPattern(); }
Liberty BASIC
<lang lb>
nomainwin
w =512 ' allow for title bar and window border WindowWidth =w +2 WindowHeight =w +34
open "XOR Pattern" for graphics_nsb_nf as #w
#w "trapclose quit"
#w "down"
for x =0 to w -1 for y =0 to w -1 b =( x xor y) and 255 print b #w "color "; 255 -b; " "; b /2; " "; b #w "set "; x; " "; w -y -1 scan next y next x
#w "flush"
wait
sub quit j$ close #w end end sub
</lang> Image available at [[1]]
Mathematica
<lang Mathematica>ListDensityPlot[
Table[Table[ FromDigits[BitXor[IntegerDigits[x, 2, 8], IntegerDigits[y, 2, 8]], 2], {x, 0, 255}], {y, 0, 255}]]</lang>
Output #1:
<lang Mathematica>ArrayPlot[Array[BitXor, {511, 511}]]</lang> Output #2:
MATLAB
<lang matlab>size = 256; [x,y] = meshgrid([0:size-1]);
c = bitxor(x,y);
colormap bone(size);
image(c);
axis equal;</lang>
OCaml
<lang ocaml>open Graphics
let () =
open_graph ""; resize_window 256 256; for y = 0 to pred (size_y()) do for x = 0 to pred (size_x()) do let v = (x lxor y) land 0xFF in set_color (rgb v (255 - v) 0); plot x y done; done; ignore(read_key())</lang>
Run with:
$ ocaml graphics.cma xor_pattern.ml
Output:
Octave
<lang Octave>size = 256; [x,y] = meshgrid([0:size-1]);
c = bitxor(x,y);
colormap(jet(size));
image(c);
axis equal;</lang>
Perl
<lang perl>use GD;
my $img = new GD::Image(256, 256, 1);
for my $y(0..255) {
for my $x(0..255) { my $color = $img->colorAllocate( abs(255 - $x - $y), (255-$x) ^ $y , $x ^ (255-$y)); $img->setPixel($x, $y, $color); }
}
Perl 6
Here's one simple way:
<lang perl6>my $ppm = open("munching.ppm", :w, :bin) or
die "Can't create munching.ppm: $!";
$ppm.print(q :to 'EOT'); P3 256 256 255 EOT
for 0 .. 255 -> $row {
for 0 .. 255 -> $col { my $color = $row +^ $col; $ppm.print("0 $color 0 "); } $ppm.say();
}
$ppm.close(); </lang>
Another way:
<lang perl6>my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, map -> $x { floor ($x/256) ** 3 * 256 }, ((0...255) Z (255...0) Z (0,2...254),(254,252...0));
my $PPM = open "munching.ppm", :w, :bin or die "Can't create munching.ppm: $!";
$PPM.print: qq:to/EOH/;
P6 # munching.pgm 256 256 255 EOH
$PPM.write: @colors[$_] for ^256 X+^ ^256;
PHP
<lang php>header("Content-Type: image/png");
$w = 256; $h = 256;
$im = imagecreate($w, $h)
or die("Cannot Initialize new GD image stream");
$color = array(); for($i=0;$i<256;$i++) {
array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i));
}
for($i=0;$i<$w;$i++) {
for($j=0;$j<$h;$j++) { imagesetpixel($im,$i,$j,$color[$i^$j]); }
}
imagepng($im); imagedestroy($im);</lang>
Prolog
Works with SWI-Prolog and his GUI XPCE. <lang Prolog>xor_pattern :- new(D, window('XOR Pattern')), send(D, size, size(512,512)), new(Img, image(@nil, width := 512, height := 512 , kind := pixmap)),
forall(between(0,511, I), ( forall(between(0,511, J), ( V is I xor J, R is (V * 1024) mod 65536, G is (65536 - V * 1024) mod 65536, ( V mod 2 =:= 0 -> B is (V * 4096) mod 65536 ; B is (65536 - (V * 4096)) mod 65536), send(Img, pixel(I, J, colour(@default, R, G, B))))))),
new(Bmp, bitmap(Img)),
send(D, display, Bmp, point(0,0)),
send(D, open).
</lang>
PureBasic
<lang purebasic>#palletteSize = 128 Procedure.f XorPattern(x, y) ;compute the gradient value from the pixel values
Protected result = x ! y ProcedureReturn Mod(result, #palletteSize) / #palletteSize
EndProcedure
Procedure drawPattern()
StartDrawing(ImageOutput(0)) DrawingMode(#PB_2DDrawing_Gradient) CustomGradient(@XorPattern()) ;specify a gradient pallette from which only specific indexes will be used For i = 1 To #palletteSize GradientColor(1 / i, i * $BACE9B) ; or alternatively use $BEEFDEAD Next Box(0, 0, ImageWidth(0), ImageHeight(0)) StopDrawing()
EndProcedure
If OpenWindow(0, 0, 0, 128, 128, "XOR Pattern", #PB_Window_SystemMenu)
CreateImage(0, WindowWidth(0), WindowHeight(0)) drawPattern() ImageGadget(0, 0, 0, ImageWidth(0), ImageHeight(0), ImageID(0)) Repeat event = WaitWindowEvent(20) Until event = #PB_Event_CloseWindow
Python
<lang Python>import Image, ImageDraw
image = Image.new("RGB", (256, 256)) drawingTool = ImageDraw.Draw(image)
for x in range(256):
for y in range(256): drawingTool.point((x, y), (0, x^y, 0))
del drawingTool
image.save("xorpic.png", "PNG")</lang>
Racket
![](http://static.miraheze.org/rosettacodewiki/c/ca/Munching-racket.png)
<lang racket>
- lang racket
(require racket/draw) (define palette (for/vector ([x 256]) (make-object color% 0 0 x))) (define bm (make-object bitmap% 256 256)) (define dc (new bitmap-dc% [bitmap bm])) (for* ([x 256] [y 256])
(define c (vector-ref palette (bitwise-xor x y))) (send dc set-pixel x y c))
bm </lang>
Ruby
Uses Raster graphics operations/Ruby
![](http://static.miraheze.org/rosettacodewiki/thumb/0/01/Xorpattern_rb.png/300px-Xorpattern_rb.png)
<lang ruby>load 'raster_graphics.rb'
class Pixmap
def self.xor_pattern(width, height, rgb1, rgb2) # create colour table size = 256 colours = Array.new(size) do |i| RGBColour.new( (rgb1.red + (rgb2.red - rgb1.red) * i / size), (rgb1.green + (rgb2.green - rgb1.green) * i / size), (rgb1.blue + (rgb2.blue - rgb1.blue) * i / size), ) end
# create the image pixmap = new(width, height) pixmap.each_pixel do |x, y| pixmap[x,y] = colours[(x^y)%size] end pixmap end
end
img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW) img.save_as_png('xorpattern.png')</lang>
Run BASIC
<lang runbasic>w = 100 graphic #g, w,w for x = 0 to w
for y = 0 to w b = (x xor y) and 255 #g color(255 -b,b /2,b) #g "set "; x; " "; w -y -1 next y
next x render #g
- g "flush"</lang>
Tcl
<lang tcl>package require Tk
proc xorImage {img table} {
set data {} set h [image height $img] set w [image width $img] for {set y 0} {$y < $h} {incr y} {
set row {} for {set x 0} {$x < $w} {incr x} { lappend row [lindex $table [expr {($x^$y) % [llength $table]}]] } lappend data $row
} $img put $data
} proc inRange {i f t} {expr {$f + ($t-$f)*$i/255}} proc mkTable {rf rt gf gt bf bt} {
for {set i 0} {$i < 256} {incr i} {
lappend tbl [format "#%02x%02x%02x" \ [inRange $i $rf $rt] [inRange $i $gf $gt] [inRange $i $bf $bt]]
} return $tbl
}
set img [image create photo -width 512 -height 512] xorImage $img [mkTable 0 255 64 192 255 0] pack [label .l -image $img]</lang>
TI-83 BASIC
Due to the TI-83's 1 bit black and white display, this program uses the home screen and a gradient of characters. Since the TI-83 does not use a standard encoding, the first Sto→ to Str1 may be subjectively interpreted.
<lang ti-83b>PROGRAM:XORPATT
" •.-,+-°-1+o*:πOX"→Str1
ClrHome
{0,0,0,0}→L1 {0,0,0,0)→L2
For(I,1,8,1) For(J,1,16,1) J→A I→B
If A>8 Then A-8→A 1→L1(1) Else 0→L1(1) End
If A>4 Then A-4→A 1→L1(2) Else 0→L1(2) End
If A>2 Then A-2→A 1→L1(3) Else 0→L1(3) End
If A>1 Then 1→L1(4) Else 0→L1(4) End
0→L2(1)
If B>4 Then B-4→B 1→L2(2) Else 0→L2(2) End
If B>2 Then B-2→B 1→L2(3) Else 0→L2(3) End
If B>1 Then 1→L2(4) Else 0→L2(4) End
L1≠L2→L3 8L3(1)+4L3(2)+2L3(3)+L3(4)→C Output(I,J,sub(Str1,C+1,1))
End End Pause </lang>
XPL0
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations int X, Y; [SetVid($101); \set 640x480 graphics with 8-bit color port($3C8):= 0; \set color registers with beautiful shades for X:= 0 to 256-1 do
[port($3C9):= X>>1; \red port($3C9):= X>>3; \green port($3C9):= X; \blue ];
for Y:= 0 to 256-1 do \"color table" is array of 256 registers
for X:= 0 to 256-1 do Point(X, Y, X|Y); \"|" = XOR, not OR which is "!"
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
]</lang>