1 module caLib.simulations.ElementaryCA;
2 
3 import caLib.neighbourhoods.OneDimBasicNeighbourhood;
4 import caLib.lattices.OneDimDenseLattice;
5 import caLib.rules.BinaryRule;
6 import caLib.palettes.ColorListPalette;
7 import caLib.renderers.OneDimBasicRenderer;
8 
9 public import caLib_util.graphics : Window;
10 import caLib_util.structs : Simulation, create_Simulation, Color;
11 import std.bigint;
12 import std.conv : to;
13 
14 
15 
16 auto create_ElementaryCA(int width, ubyte ruleNumber,
17 	ubyte delegate(int x) initialCondition, Window window)
18 in
19 {
20 	assert(width > 0);
21 }
22 body
23 {
24 	ruleNumber = wolframRuleNumberToRuleNumber(ruleNumber);
25 
26 	auto neighbourhood = create_OneDimBasicNeighbourhood;
27 	auto lattice = create_OneDimDenseLattice(width, neighbourhood, ubyte(0),
28 		initialCondition);
29 
30 	auto rule = create_BinaryRule(lattice, BigInt(to!string(ruleNumber)));
31 
32 	auto palette = create_ColorListPalette([ubyte(0):Color(0), ubyte(1):Color(uint.max)], Color(255,0,0));
33 	auto renderer = create_OneDimBasicRenderer(lattice, palette, window);
34 
35 	return create_Simulation(lattice, rule, renderer);
36 }
37 
38 
39 
40 ubyte wolframRuleNumberToRuleNumber(ubyte ruleNumber)
41 {
42 	ruleNumber =
43 		((ruleNumber & 1) << 0) +
44 		((ruleNumber & 2) << 3) +
45 		((ruleNumber & 4) << 0) +
46 		((ruleNumber & 8) << 3) +
47 		((ruleNumber & 16) >> 3) +
48 		((ruleNumber & 32) >> 0) +
49 		((ruleNumber & 64) >> 3) +
50 		((ruleNumber & 128) >> 0);
51 
52 	ruleNumber =
53 		((ruleNumber & 1) << 0) +
54 		((ruleNumber & 2) << 0) +
55 		((ruleNumber & 4) << 2) +
56 		((ruleNumber & 8) << 2) +
57 		((ruleNumber & 16) >> 2) +
58 		((ruleNumber & 32) >> 2) +
59 		((ruleNumber & 64) << 0) +
60 		((ruleNumber & 128) << 0);
61 
62 	return ruleNumber;
63 }