-
Notifications
You must be signed in to change notification settings - Fork 0
/
parametric.js
7266 lines (7035 loc) · 245 KB
/
parametric.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BigNumber } from '../api/BigNumber';
import { FreeCost } from '../api/Costs';
import { Localization } from '../api/Localization';
import { MathExpression } from '../api/MathExpression';
import { theory } from '../api/Theory';
import { Upgrade } from '../api/Upgrades';
import { Utils } from '../api/Utils';
import { Vector3 } from '../api/Vector3';
import { Frame } from '../api/ui/Frame';
import { ui } from '../api/ui/UI';
import { ClearButtonVisibility } from '../api/ui/properties/ClearButtonVisibility';
import { Color } from '../api/ui/properties/Color';
import { FontFamily } from '../api/ui/properties/FontFamily';
import { Keyboard } from '../api/ui/properties/Keyboard';
import { LayoutOptions } from '../api/ui/properties/LayoutOptions';
import { LineBreakMode } from '../api/ui/properties/LineBreakMode';
import { TextAlignment } from '../api/ui/properties/TextAlignment';
import { Thickness } from '../api/ui/properties/Thickness';
import { TouchType } from '../api/ui/properties/TouchType';
var id = 'parametric_L_systems_renderer';
var getName = (language) =>
{
let names =
{
en: 'Param. L-systems Renderer',
};
return names[language] || names.en;
}
var getDescription = (language) =>
{
let descs =
{
en:
`An educational tool that allows you to model plants and fractal figures.
Supported L-system features:
- Parametric, context-sensitive (2L) systems
- Stochastic (randomised) rules
- 3D turtle controls
- Polygon modelling
Other features:
- Can save a whole army of systems!
- Camera modes: static and turtle-following
- Drawing speed and advanced stroke options!
Note: Systems from LSR can be ported to P-LSR with minimal changes. However, ` +
`the opposite is rarely true.`,
};
return descs[language] || descs.en;
}
var authors = 'propfeds\n\nThanks to:\nSir Gilles-Philippe Paillé, for ' +
'providing help with quaternions\nskyhigh173#3120, for ' +
'suggesting clipboard and JSON internal state formatting';
var version = 0.02;
let time = 0;
let page = 0;
let offlineReset = true;
let gameIsOffline = false;
let altTerEq = false;
let tickDelayMode = false;
let resetLvlOnConstruct = true;
let measurePerformance = false;
let debugCamPath = false;
let normaliseQuaternions = false;
let maxCharsPerTick = 500;
let menuLang = Localization.language;
let savedSystems = new Map();
let getImageSize = (width) =>
{
if(width >= 1080)
return 48;
if(width >= 720)
return 36;
if(width >= 360)
return 24;
return 20;
}
let getBtnSize = (width) =>
{
if(width >= 1080)
return 96;
if(width >= 720)
return 72;
if(width >= 360)
return 48;
return 40;
}
let getMediumBtnSize = (width) =>
{
if(width >= 1080)
return 88;
if(width >= 720)
return 66;
if(width >= 360)
return 44;
return 36;
}
let getSmallBtnSize = (width) =>
{
if(width >= 1080)
return 80;
if(width >= 720)
return 60;
if(width >= 360)
return 40;
return 32;
}
/**
* Returns a C-style formatted string from a BigNumber. Note that it can only
* handle up to the Number limit.
* @param {BigNumber} x the number.
* @returns {string}
*/
let getCString = (x) => parseFloat(x.toString(6)).toString();
/**
* Purge a string array of empty lines.
* @param {string[]} arr the array.
* @returns {string[]}
*/
let purgeEmpty = (arr) => {
let result = [];
let idx = 0;
for (let i = 0; i < arr.length; ++i) {
// I hope this deep-copies
if (arr[i]) {
result[idx] = arr[i];
++idx;
}
}
return result;
};
const BUTTON_HEIGHT = getBtnSize(ui.screenWidth);
const SMALL_BUTTON_HEIGHT = getSmallBtnSize(ui.screenWidth);
const ENTRY_CHAR_LIMIT = 5000;
const TRIM_SP = /\s+/g;
const LS_RULE = /([^:]+)(:(.+))?=(.*)/;
// Context doesn't need to check for nested brackets!
const LS_CONTEXT =
/((.)(\(([^\)]+)\))?<)?((.)(\(([^\)]+)\))?)(>(.)(\(([^\)]+)\))?)?/;
const BACKTRACK_LIST = new Set('+-&^\\/|[$T');
const locStrings =
{
en:
{
versionName: 'v1.02',
welcomeSystemName: 'Calendula',
welcomeSystemDesc: 'The classic flower to start a month.',
equationOverlayLong: '{0} – {1}\n\n{2}\n\n{3}',
equationOverlay: '{0}\n\n{1}',
rendererBuildingTree: `\\begin{{matrix}}Building\\enspace ancestree...&
\\text{{Stg. {0}}}&({1}\\text{{ symbols}})\\end{{matrix}}`,
rendererDeriving: `\\begin{{matrix}}Deriving...&\\text{{Stg. {0}}}&({1}
\\text{{ symbols}})\\end{{matrix}}`,
currencyTime: ' (elapsed)',
varLvDesc: '\\text{{Stage: }}{0}{1}',
varTdDesc: '\\text{{Tick length: }}{0}\\text{{ sec}}',
varTdDescInf: '\\text{{Tick length: }}\\infty',
varTsDesc: '\\text{{Tickspeed: }}{0}/\\text{{sec}}',
varIdDesc: '\\text{{Init. delay: }}{0}\\text{{ sec}}',
upgResumeInfo: 'Resumes the last rendered system',
saPatienceTitle: 'You\'re watching grass grow.',
saPatienceDesc: 'Let the renderer draw a 10-minute long figure or ' +
'playlist.',
saPatienceHint: 'Be patient.',
btnSave: 'Save',
btnClear: 'Clear All',
btnDefault: '* Reset to Defaults',
btnVar: 'Variables',
btnAdd: 'Add',
btnUp: '▲',
btnDown: '▼',
btnReroll: 'Reroll',
btnConstruct: 'Construct',
btnDelete: 'Delete',
btnView: 'View',
btnClipboard: 'Clipboard',
btnOverwrite: 'Overwrite',
btnSaveCopy: 'Save as Copy',
btnSelect: 'Select',
btnSelected: '(Selected)',
btnPrev: 'Previous',
btnNext: 'Next',
btnClose: 'Close',
btnImport: 'Import',
btnContents: 'Table of\nContents',
btnPage: '{0}',
btnMenuLSystem: 'L-system menu',
btnMenuRenderer: 'Renderer menu',
btnMenuSave: 'Save/load',
btnMenuTheory: 'Settings',
btnMenuManual: 'User guide',
btnResume: 'Resume – {0}',
btnStartMeasure: 'Measure performance',
btnEndMeasure: 'Stop measuring',
btnLoadTest: 'Load test system',
measurement: '{0}: max {1}ms, avg {2}ms over {3} ticks',
rerollSeed: 'You are about to reroll the system\'s seed.',
resetRenderer: 'You are about to reset the renderer.',
menuSequence: '{0} (Stage {1})',
labelLevelSeq: 'Stage {0}: {1} symbols',
labelLevelSeqLoading: 'Stage {0}: {1}/{2} symbols',
labelChars: '({0} symbols)',
labelFilter: 'Filter: ',
labelParams: 'Parameters: ',
menuLSystem: 'L-system Menu',
labelAxiom: 'Axiom: ',
labelAngle: 'Turning angle (°): ',
labelRules: `Production rules: {0}`,
labelModels: `Model specifications: {0}`,
labelIgnored: 'Turtle-ignored: ',
labelCtxIgnored: 'Context-ignored: ',
labelTropism: 'Tropism (gravity): ',
labelSeed: 'Seed (≠ 0): ',
menuVariables: 'Define Variables',
labelVars: 'Variables: {0}',
menuRenderer: 'Renderer Menu',
labelInitScale: '* Initial scale: ',
labelFigScale: '* Figure scale: ',
labelCamMode: 'Camera mode: {0}',
camModes: ['Fixed', 'Linear', 'Quadratic'],
labelCamCentre: 'Fixed camera centre (x,): ',
labelCamOffset: '... centre (y, z): ',
labelFollowFactor: 'Follow factor (0-1): ',
labelLoopMode: 'Looping mode: {0}',
loopModes: ['Off', 'Stage', 'Playlist'],
labelUpright: '* Upright figure: ',
labelBTTail: 'Draw tail end: ',
labelLoadModels: '* Load models: ',
labelQuickdraw: '* Quickdraw: ',
labelQuickBT: '* Quick backtrack: ',
labelHesitate: '* Stutter on backtrack: ',
labelHesitateApex: '* Stutter at apex: ',
labelHesitateFork: '* Stutter at fork: ',
labelOldTropism: '* Alternate tropism method: ',
labelBTList: '* Backtrack list: ',
labelRequireReset: '* Modifying this setting will require a reset.',
menuSave: 'Save/Load Menu',
labelCurrentSystem: 'Current system: ',
labelSavedSystems: 'Saved systems: {0}',
labelApplyCamera: 'Applies static camera: ',
menuClipboard: 'Clipboard Menu',
labelTotalLength: 'Total length: {0}',
labelEntryCharLimit: `Warning: This entry has been capped at {0} ` +
`characters. Proceed with caution.`,
menuNaming: 'Save System',
labelName: 'Title: ',
defaultSystemName: 'Untitled L-system',
labelDesc: 'Description: ',
noDescription: 'No description.',
duplicateSuffix: ' (copy)',
menuTheory: 'Theory Settings',
labelOfflineReset: 'Reset graph on tabbing in: ',
labelResetLvl: 'Reset renderer controls on construction: ',
labelTerEq: 'Tertiary equation: {0}',
terEqModes: ['Coordinates', 'Orientation'],
labelMeasure: 'Measure performance: ',
debugCamPath: 'Debug camera path: ',
labelMaxCharsPerTick: 'Maximum loaded symbols/tick: ',
labelInternalState: 'Internal state: ',
menuManual: 'User Guide ({0}/{1})',
menuTOC: 'Table of Contents',
labelSource: 'Reference: ',
manualSystemDesc: 'From the user guide, page {0}.',
manual:
[
{
title: 'Introduction',
contents:
`Welcome to the Parametric L-systems Renderer! This guide aims to help you ` +
`understand parametric L-systems in detail, as well as instructions on how ` +
`to effectively use this theory to construct and render them. Before using ` +
`the theory however, it is recommended to try out the Classic version first.
Without further a due, let's start discovering the wonders of L-systems.
Notice: A gallery for regular L-systems has opened! Visit that theory instead.`
},
{
title: 'Differences between LSR versions',
contents:
`First of all, the terminology for Level has been changed to Stage.
That was the only major change.
Anyway. In Parametric, as multiple rules can exist for one symbol, they are ` +
`checked from top to bottom when deriving, regardless of context or condition.
This is different from how it was defined in The Algorithmic Beauty of ` +
`Plants, where rules with a context are prioritised. Therefore, arrange your ` +
`rules accordingly.
The syntax for multiple derivations on the same line has also changed from , ` +
`(comma) to ; (semi-colon), due to the introduction of parameters.
Finally, declaring models now has a slightly different syntax due to changes ` +
`to (legacy) rule processing to account for context-sensitivity:
~> {symbol} = {model}`
},
{
title: 'Context-sensitivity',
contents:
`One of the main weaknesses in the original L-system syntax comes from the ` +
`fact that each symbol has no way of interacting with other symbols. This ` +
`makes it unfit for applications of cellular automata or modelling forms of ` +
`communication between a plant's organs.
Context-sensitive L-systems allow this to work, by letting a symbol see both ` +
`its ancestor (the symbol to its immediate left), and its child to the right ` +
`(children, if it opens up multiple branches). A context-sensitive rule goes ` +
`as follows:
{left} < {symbol} > {right} = {derivation}
The symbol will only derive according to this rule if its ancestor bears the ` +
`same symbol as {left}, and one of its children bears the same symbol as ` +
`{right}.
Note: P-LSR uses a context-sensitive variant called 2L-systems, where the 2 ` +
`means that a context is determined by two symbols: an ancestor and a child. ` +
`Another variant, 1L-systems, only determines a context in one direction.
Note 2: The list of context-ignored symbols can be configured in the ` +
`L-system menu. These symbols will be left out of the ancestree computation.`
},
{
title: 'Example: Signal propagation',
contents:
`A simple signal sent by the concurrent youth. The signal, denoted by the ` +
`letter B, starts from the 🅱ase of the tree and travels to the to🅿️.
Axiom: B[+AAA]A[-AA]A[+A]A
B<A = B
B = A
Context-ignored: +-
Turning angle: 30°
Applies static camera:
Scale: 4
Centre: (0, 2, 0)
Upright`
},
{
title: 'Example: Cellular botanica',
contents:
`A cellular automaton that has been transformed into a tree. Originally ` +
`studied in 1974 by Hogeweg and Hesper, this is one of the 3584 patterns ` +
`generated in the study using symbols 0 and 1.
Axiom: F1F1F1
0<0>0 = 0
0<0>1 = 1[-F1F1]
0<1>0 = 1
0<1>1 = 1
1<0>0 = 0
1<0>1 = 1F1
1<1>0 = 1
1<1>1 = 0
+ = -
- = +
Turtle-ignored: 01
Context-ignored: F+-
Turning angle: 22.5°
Applies static camera:
Scale: lv+2
Centre: (0, lv/2+1, 0)
Upright`
},
{
title: 'Parametric L-systems: A primer',
contents:
`With many of the systems we have encountered until now, we know that their ` +
`size can grow quickly, even exponentially. One segment of a tree branch ` +
`could be sixteen Fs long, and its trunk 128 metres. As a result, the ` +
`L-system very quickly loses its readability. Another consequence, is that ` +
`we may not express any length precisely using only integers.
Then, a solution to that would be the ability to embed extra information ` +
`onto each symbol, perhaps to lengthen a segment to the desired ratio, or ` +
`turn around by a specific angle. And thus, Lindenmayer proposed the idea of ` +
`parametric L-systems.
F(d): moves turtle forward by a distance d, and draw a line.
(Note: other letters move by 1 instead of taking the parameter.)
+-&^\\/(a): rotate turtle by an angle of a degrees.
T(g): applies a tropism force of g.
T(g, x, y, z): applies a tropism of g in the direction (x, y, z).`
},
{
title: 'Example: The Koch curve',
contents:
`The Koch curve belongs to a family of self-similar fractals generated by ` +
`the iterated function systems (IFS) method. An IFS can construct a fractal ` +
`by recursively applying affine transformations (translation, rotation, ` +
`scaling) to an initial figure... an axiom! Many IFSs can be reconstructed ` +
`using parametric L-systems, as long as only lines are involved.
Axiom: F(1)
F(d) = F(d/3)+F(d/3)-(120)F(d/3)+F(d/3)
Turning angle: 60°
Applies static camera:
Scale: 1/2
Centre: (1/2, sqrt(3)/12, 0)`
},
{
title: 'Parametric 2L-systems',
contents:
`Beyond geometric applications, parametric L-systems allow individual ` +
`symbols to hold additional information such as its state of growth, elapsed ` +
`time, etc. They can be even peeked at in context rules!
The syntax for a parametric rule goes as follows:
{symbol}({param_0},...) : {condition*} = {derivation_0} : {probability**} ;...
Examples:
I(t) : t>0 = FI(t-1)
A(t) : t>5 = B(t+1)CD(t^0.5, t-2)
Example including context:
A(x) < B(y) > C(z) : x+y+z>10 = E((x+y)/2)F((y+z)/2)
Note: All arithmetic processing in parameters is done using the game's ` +
`MathExpression class (just like the formulae for Auto-prestige/supremacy). ` +
`As such, there are several unavailable expressions:
% (modulus)
== (equality)
true, false (keywords)
a ? b : c (conditional ternary)
Conversion (from boolean to number)
For more information, check the Math Expression manual in the Auto-prestige ` +
`settings.
* When omitted, the condition is assumed to be always true.
** When omitted, the chance is assumed to be 100%.`
},
{
title: 'Example: Stamp stick',
contents:
`Adopted from an L-system made in Houdini. The symbol J represents 4 organs ` +
`at the same time, with the 'type' parameter controlling which model to load:
type <= 0: leaves,
type <= 1: flower bud,
type <= 2: blooming flower,
type <= 3: closed flower,
and the 's' parameter controlling the model's size.
Variables: b = 2.25
The variable b controls how quickly the model type switches, with lower ` +
`values being faster. A lower value also decreases the organ density.
Axiom: FA(1)
A(t): t<=5*b = F(2/b)//[+(24)&B(t)]//[&B(t)]//[&B(t)]A(t+1)
B(t) = J(0.15, t/b-2)
J(s, type) = J(s*0.75+0.25, type)
~>J(s, type): type<=0 = {[+(32)F(s).-TF(s)TF.-TF(s)..][-(32)F(s)+(16)[TF(s)TF.].]}
~>J(s, type): type<=1 = [Fp(s)/(60)p(s)/(60)p(s)]
~>p(s) = {[+F(s/2).--F(s/2).][-F(s/2).].}
~>J(s, type): type<=2 = [FTk(s)/(72)k(s)/(72)k(s)/(72)k(s)/(72)k(s)]
~>k(s) = {[F(s).+(72)[&F(s-0.3).][F(s)..][^F(s-0.3).].]}
~>J(s, type): type<=3 = [FTm(s)/(72)m(s)/(72)m(s)/(72)m(s)/(72)m(s)]
~>m(s) = {[+(24)F(s).-F(s/2)..].}
Turtle-ignored: A
Turning angle: 48°
Tropism: 0.16
Applies static camera:
Scale: 7
Centre: (0, lv/2+1, 0)
Upright`,
source: 'https://www.houdinikitchen.net/2019/12/21/how-to-create-l-systems/'
},
{
title: 'Example: Mistletoe',
contents:
`Welcome to the Parametric L-systems Renderer!
Axiom: ++M(0)
M(t): t<2 = FM(t+1)
M(t): t<3 = [&T$M(t+1, 0)]/(120)[&T$M(t+1, 0)]/(120)[&T$M(t+1, 0)]
M(t, i): t<5 = FM(t+1, i): 0.7-i; FK(0)M(t+1, i+0.3): 0.3+i
M(t, i): t>=5 = [&TM(t-2, i+0.3)]/(180)[&TM(t-2, i+0.3)]
~> M(t): t<3 = [+(48)L(t)]/(180)[+(48)L(t)]
~> M(t, i) = [+(48)L(2+0.4*t)]/(180)[+(48)L(2+0.4*t)]
~> L(t) = {[+(16)TF(t/6).&(16)-(16)TF(t/10).-TF(t/8)..][-(16)TF(t/6)[&(16)+(16)TF(t/10).].]}
K(c)>M(t, i): c<3 = K(c+1): 0.7-t/10; B(0.3): 0.3+t/10
K(t): t<3 = K(t+1): 0.3+t/10; : 0.7-t/10
K(t): t>=3 = [&&\\B(0.3)]/(120)[&&\\B(0.24)]/(120)[&&B(0.27)]
~> K(t) = [&&F(0.3+t/10)]/(120)[&&F(0.3+t/10)]/(120)[&&F(0.3+t/10)]
B(s) = B(s*0.9+0.1)
~> B(s) = {[-(67.5)F(s).+(45)F(s).+(45)F(s).+(45)F(s).+(45)F(s).+(45)F(s).+(45)F(s).]}
Turning angle: 32°
Seed: 1362151494
Tropism: 0.16
Applies static camera:
Scale: 6
Centre: (3, 3, 0)`
},
{
title: 'Appendix: Credits',
contents:
`First of all, a biggest thanks goes out to Sir Gilles-Philippe Paillé of ` +
`Conic Games. Without his work on the game Exponential Idle, the foundation ` +
`for this theory, perhaps I would have never found myself writing this page ` +
`today. He, along with the people in the #custom-theories-dev channel, has ` +
`also helped me with numerous problems of custom theories (CT) development.
If by any chance you have not yet tried this game, I highly recommend it. ` +
`The download link is provided at the bottom of this page.`,
source: 'https://conicgames.github.io/exponentialidle'
},
{
title: 'Credits (2)',
contents:
`The other massive thanks goes to Algorithmic Botany, the research team that ` +
`has been expanding Lindenmayer's work on L-systems. The site also hosts the ` +
`book 'The Algorithmic Beauty of Plants', which has been the primary source ` +
`of reference in the development of LSR, including the various syntax and ` +
`processing rules, as well as explanations to the scientific motives behind ` +
`the design of L-systems.`,
source: 'http://algorithmicbotany.org/'
}
]
}
};
/**
* Returns a localised string.
* @param {string} name the string's internal name.
* @returns {string}
*/
let getLoc = (name, lang = menuLang) =>
{
if(lang in locStrings && name in locStrings[lang])
return locStrings[lang][name];
if(name in locStrings.en)
return locStrings.en[name];
return `String missing: ${lang}.${name}`;
}
/**
* Returns a string of a fixed decimal number, with a fairly uniform width.
* @param {number} x the number.
* @returns {string}
*/
let getCoordString = (x) => x.toFixed(x >= -0.01 ?
(x <= 9.999 ? 3 : (x <= 99.99 ? 2 : 1)) :
(x < -9.99 ? (x < -99.9 ? 0 : 1) : 2)
);
/**
* Represents an instance of the Xorshift RNG.
*/
class Xorshift
{
/**
* @constructor
* @param {number} seed must be initialized to non-zero.
*/
constructor(seed = 0)
{
this.x = seed;
this.y = 0;
this.z = 0;
this.w = 0;
for(let i = 0; i < 64; ++i)
this.nextInt;
}
/**
* Returns a random integer within [0, 2^31) probably.
* @returns {number}
*/
get nextInt()
{
let t = this.x ^ (this.x << 11);
this.x = this.y;
this.y = this.z;
this.z = this.w;
this.w ^= (this.w >> 19) ^ t ^ (t >> 8);
return this.w;
}
/**
* Returns a random floating point number within [0, 1).
* @returns {number}
*/
get nextFloat()
{
return (this.nextInt >>> 0) / ((1 << 30) * 2);
}
/**
* Returns a full random double floating point number using 2 rolls.
* @returns {number}
*/
get nextDouble()
{
let top, bottom, result;
do
{
top = this.nextInt >>> 10;
bottom = this.nextFloat;
result = (top + bottom) / (1 << 21);
}
while(result === 0);
return result;
}
/**
* Returns a random integer within a range of [start, end).
* @param {number} start the range's lower bound.
* @param {number} end the range's upper bound, plus 1.
* @returns {number}
*/
nextRange(start, end)
{
// [start, end)
let size = end - start;
return start + Math.floor(this.nextFloat * size);
}
/**
* Returns a random element from an array.
* @param {any[]} array the array.
* @returns {any}
*/
choice(array)
{
return array[this.nextRange(0, array.length)];
}
}
/**
* Represents one hell of a quaternion.
*/
class Quaternion
{
/**
* @constructor
* @param {number} r (default: 1) the real component.
* @param {number} i (default: 0) the imaginary i component.
* @param {number} j (default: 0) the imaginary j component.
* @param {number} k (default: 0) the imaginary k component.
*/
constructor(r = 1, i = 0, j = 0, k = 0)
{
/**
* @type {number} the real component.
*/
this.r = r;
/**
* @type {number} the imaginary i component.
*/
this.i = i;
/**
* @type {number} the imaginary j component.
*/
this.j = j;
/**
* @type {number} the imaginary k component.
*/
this.k = k;
}
/**
* Computes the sum of the current quaternion with another. Does not modify
* the original quaternion.
* @param {Quaternion} quat this other quaternion.
* @returns {Quaternion}
*/
add(quat)
{
return new Quaternion(
this.r + quat.r,
this.i + quat.i,
this.j + quat.j,
this.k + quat.k
);
}
/**
* Computes the product of the current quaternion with another. Does not
* modify the original quaternion.
* @param {Quaternion} quat this other quaternion.
* @returns {Quaternion}
*/
mul(quat)
{
let t0 = this.r * quat.r - this.i * quat.i -
this.j * quat.j - this.k * quat.k;
let t1 = this.r * quat.i + this.i * quat.r +
this.j * quat.k - this.k * quat.j;
let t2 = this.r * quat.j - this.i * quat.k +
this.j * quat.r + this.k * quat.i;
let t3 = this.r * quat.k + this.i * quat.j -
this.j * quat.i + this.k * quat.r;
let result = new Quaternion(t0, t1, t2, t3);
if(normaliseQuaternions)
return result.normalise;
else
return result;
}
/**
* Rotates the quaternion by some degrees.
* @param {number} degrees degrees.
* @param {string} symbol the corresponding symbol in L-system language.
*/
rotate(degrees = 0, symbol = '+')
{
if(degrees == 0)
return this;
let halfAngle = degrees * Math.PI / 360;
let s = Math.sin(halfAngle);
let c = Math.cos(halfAngle);
let rotation;
switch(symbol)
{
case '+':
rotation = new Quaternion(-c, 0, 0, s);
break;
case '-':
rotation = new Quaternion(-c, 0, 0, -s);
break;
case '&':
rotation = new Quaternion(-c, 0, s, 0);
break;
case '^':
rotation = new Quaternion(-c, 0, -s, 0);
break;
case '\\':
rotation = new Quaternion(-c, s, 0, 0);
break;
case '/':
rotation = new Quaternion(-c, -s, 0, 0);
break;
default:
return this;
}
return rotation.mul(this);
}
/**
* Computes the negation of a quaternion. The negation also acts as the
* inverse if the quaternion's norm is 1, which is the case with rotation
* quaternions.
* @returns {Quaternion}
*/
get neg()
{
return new Quaternion(this.r, -this.i, -this.j, -this.k);
}
/**
* Computes the norm of a quaternion.
* @returns {number}
*/
get norm()
{
return Math.sqrt(this.r ** 2 + this.i ** 2 + this.j ** 2 + this.k ** 2);
}
/**
* Normalises a quaternion.
* @returns {Quaternion}
*/
get normalise()
{
let n = this.norm;
return new Quaternion(this.r / n, this.i / n, this.j / n, this.k / n);
}
/**
* Returns a heading vector from the quaternion.
* @returns {Vector3}
*/
get headingVector()
{
let r = this.neg.mul(xUpQuat).mul(this);
return new Vector3(r.i, r.j, r.k);
}
/**
* Returns an up vector from the quaternion.
* @returns {Vector3}
*/
get upVector()
{
let r = this.neg.mul(yUpQuat).mul(this);
return new Vector3(r.i, r.j, r.k);
}
/**
* Returns a side vector (left or right?) from the quaternion.
* @returns {Vector3}
*/
get sideVector()
{
let r = this.neg.mul(zUpQuat).mul(this);
return new Vector3(r.i, r.j, r.k);
}
/**
* (Deprecated) Rotate from a heading vector to another. Inaccurate!
* @param {Vector3} src the current heading.
* @param {Vector3} dst the target heading.
* @returns {Quaternion}
*/
rotateFrom(src, dst)
{
let dp = src.x * dst.x + src.y * dst.y +
src.z * dst.z;
let rotAxis;
if(dp < -1 + 1e-8)
{
/* Edge case
If the two vectors are in opposite directions, just reverse.
*/
return zUpQuat.mul(this);
}
rotAxis = new Vector3(
src.y * dst.z - src.z * dst.y,
src.z * dst.x - src.x * dst.z,
src.x * dst.y - src.y * dst.x,
);
let s = Math.sqrt((1 + dp) * 2);
// I forgore that our quaternions have to be all negative, dunnoe why
return this.mul(new Quaternion(
-s / 2,
rotAxis.x / s,
rotAxis.y / s,
rotAxis.z / s
));
}
/**
* https://stackoverflow.com/questions/71518531/how-do-i-convert-a-direction-vector-to-a-quaternion
* (Deprecated) Applies a gravi-tropism vector to the quaternion.
* @param {number} weight the vector's length (negative for upwards).
* @returns {Quaternion}
*/
applyTropismVector(weight = 0)
{
if(weight == 0)
return this;
let curHead = this.headingVector;
let newHead = curHead - new Vector3(0, weight, 0);
let n = newHead.length;
if(n == 0)
return this;
newHead /= n;
let result = this.rotateFrom(curHead, newHead);
return result;
}
/**
* Applies a gravi-tropism vector to the quaternion.
* @param {number} weight the branch's susceptibility to bending.
* @param {number} x the tropism vector's x component.
* @param {number} y the tropism vector's y component.
* @param {number} z the tropism vector's z component.
* @returns {Quaternion}
*/
applyTropism(weight = 0, x = 0, y = -1, z = 0)
{
if(weight == 0)
return this;
// a = e * |HxT| (n)
let curHead = this.headingVector;
let rotAxis = new Vector3(
curHead.y * z - curHead.z * y,
curHead.z * x - curHead.x * z,
curHead.x * y - curHead.y * x,
);
let n = rotAxis.length;
if(n == 0)
return this;
rotAxis /= n;
let a = weight * n / 2;
let s = Math.sin(a);
let c = Math.cos(a);
// I don't know why it works the opposite way this time
return this.mul(new Quaternion(
-c,
rotAxis.x * s,
rotAxis.y * s,
rotAxis.z * s
));
}
/**
* https://gamedev.stackexchange.com/questions/198977/how-to-solve-for-the-angle-of-a-axis-angle-rotation-that-gets-me-closest-to-a-sp/199027#199027
* Rolls the quaternion so that its up vector aligns with the earth.
* @returns {Quaternion}
*/
alignToVertical()
{
// L = V×H / |V×H|
let curHead = this.headingVector;
let curUp = this.upVector;
let side = new Vector3(curHead.z, 0, -curHead.x);
let n = side.length;
if(n == 0)
return this;
side /= n;
// U = HxL
let newUp = new Vector3(
curHead.y * side.z - curHead.z * side.y,
curHead.z * side.x - curHead.x * side.z,
curHead.x * side.y - curHead.y * side.x,
);
let a = Math.atan2(
curUp.x * side.x + curUp.y * side.y + curUp.z * side.z,
curUp.x * newUp.x + curUp.y * newUp.y + newUp.z * newUp.z,
) / 2;
let s = Math.sin(a);
let c = Math.cos(a);
return new Quaternion(-c, s, 0, 0).mul(this);
}
/**
* Returns the quaternion's string representation.
* @returns {string}
*/
toString()
{
return `${getCoordString(this.r)} + ${getCoordString(this.i)}i + ${getCoordString(this.j)}j + ${getCoordString(this.k)}k`;
}
}
/**
* Represents a parametric L-system.
*/
class LSystem {
constructor(axiom = '', rules = [], turnAngle = 0, seed = 0, ignoreList = '', ctxIgnoreList = '', tropism = 0, variables = {}, models = []) {
// User input
this.userInput =
{
axiom: axiom,
rules: purgeEmpty(rules),
models: purgeEmpty(models),
turnAngle: turnAngle,
seed: seed,
ignoreList: ignoreList,
ctxIgnoreList: ctxIgnoreList,
tropism: tropism,
variables: variables
};
// I want to transfer them to a map to deep copy them. LS menu uses
// arrays so we're fine on that.
this.variables = new Map();
for (let key in variables)
this.variables.set(key, MathExpression.parse(variables[key]).
evaluate());
let axiomMatches = this.parseSequence(axiom.replace(TRIM_SP, ''));
this.axiom = axiomMatches.result;
let axiomParamStrings = axiomMatches.params;
this.axiomParams = [];
this.varGetter = (v) => this.variables.get(v);
// Manually calculate axiom parameters
for (let i = 0; i < axiomParamStrings.length; ++i) {
if (!axiomParamStrings[i]) {
this.axiomParams[i] = null;
continue;
}
let params = this.parseParams(axiomParamStrings[i]);
this.axiomParams[i] = [];
for (let j = 0; j < params.length; ++j)
this.axiomParams[i][j] = MathExpression.parse(params[j]).
evaluate(this.varGetter);
// Maybe leave them at BigNumber?
}
let ruleMatches = [];
let concatRules = this.userInput.rules.concat(this.userInput.models);
for (let i = 0; i < concatRules.length; ++i) {
ruleMatches.push([...concatRules[i].replace(TRIM_SP, '').
match(LS_RULE)]);
// Indices 1, 3, 4 are context, condition, and all derivations
}
this.rules = new Map();
this.models = new Map();
for (let i = 0; i < ruleMatches.length; ++i) {
// [i][1]: context
let contextMatch = [...ruleMatches[i][1].match(LS_CONTEXT)];