-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsim.c
2088 lines (2012 loc) · 87.1 KB
/
sim.c
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
#include "sim.h"
#include "collision.h"
#include "parse.h"
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct atom_ref_at_position {
atom *atom;
struct vector position;
};
// hash table functions -- see appendix.
static void rehash(struct atom_grid *grid, uint32_t size);
static void schedule_flag_reset_if_needed(struct board *board, atom *a);
static atom mark_used_area_with_overlap(struct board *board, struct vector point, uint64_t *overlap);
struct vector mechanism_relative_position(struct mechanism m, int32_t du, int32_t dv, int32_t w)
{
return (struct vector){
m.direction_u.u * du + m.direction_v.u * dv + m.position.u * w,
m.direction_u.v * du + m.direction_v.v * dv + m.position.v * w,
};
}
static void report_collision(struct board *board, struct vector p, const char *reason)
{
// only report the first collision (after that, all bets are off).
if (board->collision)
return;
board->collision = true;
board->collision_location = p;
board->collision_reason = reason;
}
static bool conversion_output(struct board *board, bool active, struct mechanism m, int32_t du, int32_t dv)
{
assert(m.type & CONVERSION_GLYPH);
struct vector pos = mechanism_relative_position(m, du, dv, 1);
atom *output = lookup_atom(board, pos);
if ((*output & VALID) && !(*output & REMOVED)) {
if (board->half_cycle == 2) {
// conversion glyph outputs appear in the second half-cycle.
*output &= ~BEING_PRODUCED;
} else if (active && (*output & BEING_PRODUCED)) {
report_collision(board, pos, "two conversion glyphs outputting to the same point");
return true;
} else if (active && (*output & VAN_BERLO_ATOM)) {
report_collision(board, pos, "conversion glyph output overlaps with van berlo's wheel");
return true;
}
return false;
}
return true;
}
static void produce_atom(struct board *board, struct mechanism m, int32_t du, int32_t dv, atom a)
{
assert(m.type & CONVERSION_GLYPH);
struct vector pos = mechanism_relative_position(m, du, dv, 1);
insert_atom(board, pos, VALID | BEING_PRODUCED | a, "conversion glyph output");
}
static struct atom_ref_at_position get_atom(struct board *board, struct mechanism m, int32_t du, int32_t dv)
{
static const atom empty;
struct vector pos = mechanism_relative_position(m, du, dv, 1);
// conversion glyphs don't consume any inputs in the second half-cycle.
if ((m.type & CONVERSION_GLYPH) && board->half_cycle == 2)
return (struct atom_ref_at_position){ (atom *)&empty, pos };
atom *a = lookup_atom(board, pos);
if (!(*a & VALID))
return (struct atom_ref_at_position){ (atom *)&empty, pos };
// arms need to see removed-but-moving atoms to perform simultaneous motion checks.
if ((m.type & ANY_ARM) && (*a & REMOVED) && (*a & MOVED))
return (struct atom_ref_at_position){ a, pos };
if ((*a & REMOVED) || ((*a & BEING_PRODUCED) && !(m.type & UNBONDING)))
return (struct atom_ref_at_position){ (atom *)&empty, pos };
// only duplication glyphs can see the van berlo's wheel.
if (!(m.type & (DUPLICATION | VAN_BERLO)) && (*a & VAN_BERLO_ATOM))
return (struct atom_ref_at_position){ (atom *)&empty, pos };
// conversion glyphs can't see bonded or grabbed inputs.
if ((m.type & CONVERSION_GLYPH) && ((*a & ALL_BONDS) || (*a & GRABBED)))
return (struct atom_ref_at_position){ (atom *)&empty, pos };
return (struct atom_ref_at_position){ a, pos };
}
__attribute__((noinline))
static void remove_overlapping_atom(struct board *board, struct atom_ref_at_position a)
{
for (uint32_t i = 0; i < board->number_of_overlapped_atoms; ++i) {
if (vectors_equal(board->overlapped_atoms[i].position, a.position)) {
*a.atom = board->overlapped_atoms[i].atom;
schedule_flag_reset_if_needed(board, a.atom);
memmove(board->overlapped_atoms + i,
board->overlapped_atoms + i + 1,
(board->number_of_overlapped_atoms - i - 1) * sizeof(struct atom_at_position));
board->number_of_overlapped_atoms--;
return;
}
}
}
static inline bool remove_atom(struct board *board, struct atom_ref_at_position a)
{
if (*a.atom & OVERLAPS_ATOMS) {
remove_overlapping_atom(board, a);
return false;
} else {
*a.atom = VALID | REMOVED;
return true;
}
}
static inline void transform_atom(atom *a, atom new_type)
{
*a &= ~ANY_ATOM;
*a |= new_type;
}
int direction_for_offset(struct vector d)
{
if (d.u == 1 && d.v == 0)
return 0;
else if (d.u == 0 && d.v == 1)
return 1;
else if (d.u == -1 && d.v == 1)
return 2;
else if (d.u == -1 && d.v == 0)
return 3;
else if (d.u == 0 && d.v == -1)
return 4;
else if (d.u == 1 && d.v == -1)
return 5;
return -1;
}
int angular_distance_between_grabbers(enum mechanism_type type)
{
switch (type & ANY_ARM) {
case ARM:
case PISTON:
return 6;
case TWO_ARM:
return 3;
case THREE_ARM:
return 2;
case SIX_ARM:
case VAN_BERLO:
default:
return 1;
}
}
atom bond_direction(struct mechanism m, int32_t du, int32_t dv)
{
atom base = BOND_LOW_BITS;
int dir = direction_for_offset(mechanism_relative_position(m, du, dv, 0));
if (dir < 0) {
// fprintf(stderr, "internal error: non-orthonormal bond direction (scaled bonder?)\n");
return 0;
} else
return base << dir;
}
// add the proper bond from the `bond` mask unless a bond from the `unless` mask
// already exists in that direction.
static void add_bond(struct mechanism m, atom *a, atom *b, int32_t u, int32_t v, atom bond, atom unless)
{
atom ab = bond_direction(m, u, v);
atom ba = bond_direction(m, -u, -v);
if ((*a & ab & unless) || (*b & ba & unless))
return;
*a |= ab & bond;
*b |= ba & bond;
}
static int normalize_direction(int direction)
{
direction %= 6;
return direction < 0 ? direction + 6 : direction;
}
// rotate an atom's bonds by rotating the bits which represent those bonds.
static void rotate_bonds(atom *a, int rotation)
{
rotation = normalize_direction(rotation);
if (rotation == 0)
return;
// first, shift the bond bits by the rotation amount.
atom bonds = *a & ALL_BONDS;
bonds <<= rotation;
// take the overflow bits that were shifted off the end...
atom mask = 0x3FULL >> (6 - rotation);
atom overflow = bonds & ((mask * BOND_LOW_BITS) << 6);
bonds &= ~overflow;
// ...and shift them back around to the other side.
bonds |= overflow >> 6;
*a &= ~ALL_BONDS;
*a |= bonds;
}
struct vector u_offset_for_direction(int direction)
{
switch (normalize_direction(direction)) {
case 0: return (struct vector){1, 0};
case 1: return (struct vector){0, 1};
case 2: return (struct vector){-1, 1};
case 3: return (struct vector){-1, 0};
case 4: return (struct vector){0, -1};
case 5: return (struct vector){1, -1};
default: abort();
}
}
struct vector v_offset_for_direction(int direction)
{
return u_offset_for_direction(direction + 1);
}
static void apply_conduit(struct solution *solution, struct board *board, struct mechanism m)
{
struct conduit *conduit = &solution->conduits[m.conduit_index];
struct mechanism other_side = solution->glyphs[conduit->other_side_glyph_index];
uint32_t base = 0;
if (board->half_cycle == 1) {
int rotation = direction_for_offset(other_side.direction_u) - direction_for_offset(m.direction_u);
for (uint32_t j = 0; j < conduit->number_of_molecules; ++j) {
uint32_t length = conduit->molecule_lengths[j];
bool valid = true;
bool consume = true;
// if any of the atoms in this molecule have already been consumed
// by some other glyph, then remove the molecule from the conduit.
for (uint32_t k = 0; k < length; ++k) {
struct vector p = conduit->atoms[base + k].position;
atom *a = lookup_atom(board, mechanism_relative_position(m, p.u, p.v, 1));
if (!(*a & VALID) || (*a & REMOVED)) {
valid = false;
break;
}
// mark the shape of the molecule on the board.
*a |= CONDUIT_SHAPE;
}
if (valid) {
// if a bond has been made between any atom of the molecule and
// an atom outside the molecule, then don't consume the atoms
// (but still produce the stored atoms in the second
// half-cycle).
for (uint32_t k = 0; k < length && consume; ++k) {
struct vector p = conduit->atoms[base + k].position;
atom a = *lookup_atom(board, mechanism_relative_position(m, p.u, p.v, 1));
for (int bond_direction = 0; bond_direction < 6 && consume; ++bond_direction) {
if (!(a & (BOND_LOW_BITS << normalize_direction(bond_direction + direction_for_offset(m.direction_u)))))
continue;
struct vector d = u_offset_for_direction(bond_direction);
atom *b = lookup_atom(board, mechanism_relative_position(m, p.u + d.u, p.v + d.v, 1));
if (!(*b & VALID) || (*b & REMOVED) || !(*b & CONDUIT_SHAPE))
consume = false;
}
}
}
// clear the marked molecule shape.
for (uint32_t k = 0; k < length; ++k) {
struct vector p = conduit->atoms[base + k].position;
atom *a = lookup_atom(board, mechanism_relative_position(m, p.u, p.v, 1));
*a &= ~CONDUIT_SHAPE;
}
if (!valid) {
// remove the molecule from the conduit.
memmove(conduit->atoms + base, conduit->atoms + base + length, (conduit->number_of_positions - base - length) * sizeof(struct atom_at_position));
memmove(conduit->molecule_lengths + j, conduit->molecule_lengths + j + 1, (conduit->number_of_molecules - j - 1) * sizeof(uint32_t));
conduit->number_of_molecules--;
j--;
continue;
}
for (uint32_t k = 0; k < length; ++k) {
struct vector delta = conduit->atoms[base + k].position;
struct vector p = mechanism_relative_position(m, delta.u, delta.v, 1);
atom a = conduit->atoms[base + k].atom;
atom *b = lookup_atom(board, p);
if (consume) {
conduit->atoms[base + k].atom = *b;
remove_atom(board, (struct atom_ref_at_position){ b, p });
} else {
// bonds are consumed even if the atoms aren't.
*b &= ~(ALL_BONDS & ~RECENT_BONDS & a);
}
p = mechanism_relative_position(other_side, delta.u, delta.v, 1);
rotate_bonds(&a, rotation);
insert_atom(board, p, a | BEING_PRODUCED, "conduit output");
}
base += length;
}
} else {
conduit = &solution->conduits[other_side.conduit_index];
for (uint32_t j = 0; j < conduit->number_of_molecules; ++j) {
uint32_t length = conduit->molecule_lengths[j];
for (uint32_t k = 0; k < length; ++k) {
struct vector delta = conduit->atoms[base + k].position;
struct vector p = mechanism_relative_position(m, delta.u, delta.v, 1);
*lookup_atom(board, p) &= ~BEING_PRODUCED;
}
base += length;
}
}
}
__attribute__((noinline))
static void unbond_overlapping_atoms(struct board *board, struct atom_ref_at_position a, struct atom_ref_at_position b, atom ab, atom ba)
{
// this isn't actually correct, but just remove all relevant bonds from all overlapping atoms.
for (uint32_t i = 0; i < board->number_of_overlapped_atoms; ++i) {
struct atom_at_position overlap = board->overlapped_atoms[i];
if (vectors_equal(overlap.position, a.position) && (overlap.atom & ab)) {
board->overlapped_atoms[i].atom &= ~ab;
board->overlapped_atoms[i].atom |= ab & RECENT_BONDS;
}
if (vectors_equal(overlap.position, b.position) && (overlap.atom & ba)) {
board->overlapped_atoms[i].atom &= ~ba;
board->overlapped_atoms[i].atom |= ba & RECENT_BONDS;
}
}
}
static void apply_glyphs(struct solution *solution, struct board *board)
{
size_t n = solution->number_of_glyphs;
for (size_t i = 0; i < n; ++i) {
struct mechanism m = solution->glyphs[i];
switch (m.type & ANY_GLYPH) {
case CALCIFICATION: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
if (*a.atom & ANY_ELEMENTAL)
transform_atom(a.atom, SALT);
break;
}
case ANIMISMUS: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
struct atom_ref_at_position b = get_atom(board, m, 1, 0);
bool active = *a.atom & *b.atom & SALT;
bool c = conversion_output(board, active, m, 0, 1);
bool d = conversion_output(board, active, m, 1, -1);
if (c && d && active) {
remove_atom(board, a);
remove_atom(board, b);
produce_atom(board, m, 0, 1, VITAE);
produce_atom(board, m, 1, -1, MORS);
}
break;
}
case PROJECTION: {
struct atom_ref_at_position q = get_atom(board, m, 0, 0);
struct atom_ref_at_position a = get_atom(board, m, 1, 0);
atom metal = *a.atom & ANY_METAL & ~GOLD;
if (metal && !(*q.atom & ALL_BONDS) && !(*q.atom & GRABBED) && (*q.atom & QUICKSILVER)) {
remove_atom(board, q);
transform_atom(a.atom, metal >> 1);
}
break;
}
case DISPERSION: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
bool active = *a.atom & QUINTESSENCE;
bool b = conversion_output(board, active, m, 1, 0);
bool c = conversion_output(board, active, m, 1, -1);
bool d = conversion_output(board, active, m, 0, -1);
bool e = conversion_output(board, active, m, -1, 0);
if (b && c && d && e && active) {
remove_atom(board, a);
produce_atom(board, m, 1, 0, EARTH);
produce_atom(board, m, 1, -1, WATER);
produce_atom(board, m, 0, -1, FIRE);
produce_atom(board, m, -1, 0, AIR);
}
break;
}
case PURIFICATION: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
struct atom_ref_at_position b = get_atom(board, m, 1, 0);
atom metal = *a.atom & *b.atom & ANY_METAL & ~GOLD;
bool c = conversion_output(board, metal, m, 0, 1);
if (c && metal) {
remove_atom(board, a);
remove_atom(board, b);
produce_atom(board, m, 0, 1, metal >> 1);
}
break;
}
case DUPLICATION: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
struct atom_ref_at_position b = get_atom(board, m, 1, 0);
atom elemental = *a.atom & ANY_ELEMENTAL;
if (elemental && (*b.atom & SALT) && !(*b.atom & VAN_BERLO_ATOM))
transform_atom(b.atom, elemental);
break;
}
case UNIFICATION: {
struct atom_ref_at_position a = get_atom(board, m, 0, 1);
struct atom_ref_at_position b = get_atom(board, m, -1, 1);
struct atom_ref_at_position c = get_atom(board, m, 0, -1);
struct atom_ref_at_position d = get_atom(board, m, 1, -1);
bool active = ((*a.atom | *b.atom | *c.atom | *d.atom) & ANY_ELEMENTAL) == ANY_ELEMENTAL;
bool e = conversion_output(board, active, m, 0, 0);
if (e && active) {
remove_atom(board, a);
remove_atom(board, b);
remove_atom(board, c);
remove_atom(board, d);
produce_atom(board, m, 0, 0, QUINTESSENCE);
}
break;
}
case BONDING: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
struct atom_ref_at_position b = get_atom(board, m, 1, 0);
if (*a.atom && *b.atom)
add_bond(m, a.atom, b.atom, 1, 0, NORMAL_BONDS, TRIPLEX_BONDS);
break;
}
case UNBONDING: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
struct atom_ref_at_position b = get_atom(board, m, 1, 0);
if (*a.atom && *b.atom) {
atom ab = bond_direction(m, 1, 0);
atom ba = bond_direction(m, -1, 0);
// record the bond in the RECENT_BONDS bitfield to prevent the
// atoms from being consumed during this half-cycle.
if (*a.atom & ab) {
*a.atom &= ~ab;
*a.atom |= ab & RECENT_BONDS;
schedule_flag_reset_if_needed(board, a.atom);
}
if (*b.atom & ba) {
*b.atom &= ~ba;
*b.atom |= ba & RECENT_BONDS;
schedule_flag_reset_if_needed(board, b.atom);
}
if ((*a.atom & OVERLAPS_ATOMS) || (*b.atom & OVERLAPS_ATOMS))
unbond_overlapping_atoms(board, a, b, ab, ba);
}
break;
}
case TRIPLEX_BONDING: {
struct atom_ref_at_position ky = get_atom(board, m, 0, 0);
struct atom_ref_at_position yr = get_atom(board, m, 0, 1);
struct atom_ref_at_position rk = get_atom(board, m, 1, 0);
if (*ky.atom && *yr.atom && (*ky.atom & *yr.atom & FIRE))
add_bond(m, ky.atom, yr.atom, 0, 1, TRIPLEX_Y_BONDS, NORMAL_BONDS);
if (*yr.atom && *rk.atom && (*yr.atom & *rk.atom & FIRE))
add_bond(m, yr.atom, rk.atom, 1, -1, TRIPLEX_R_BONDS, NORMAL_BONDS);
if (*rk.atom && *ky.atom && (*rk.atom & *ky.atom & FIRE))
add_bond(m, rk.atom, ky.atom, -1, 0, TRIPLEX_K_BONDS, NORMAL_BONDS);
break;
}
case MULTI_BONDING: {
struct atom_ref_at_position center = get_atom(board, m, 0, 0);
struct atom_ref_at_position a = get_atom(board, m, 1, 0);
struct atom_ref_at_position b = get_atom(board, m, 0, -1);
struct atom_ref_at_position c = get_atom(board, m, -1, 1);
if (*center.atom && *a.atom)
add_bond(m, a.atom, center.atom, -1, 0, NORMAL_BONDS, TRIPLEX_BONDS);
if (*center.atom && *b.atom)
add_bond(m, b.atom, center.atom, 0, 1, NORMAL_BONDS, TRIPLEX_BONDS);
if (*center.atom && *c.atom)
add_bond(m, c.atom, center.atom, 1, -1, NORMAL_BONDS, TRIPLEX_BONDS);
break;
}
case DISPOSAL: {
struct atom_ref_at_position a = get_atom(board, m, 0, 0);
if (*a.atom && !(*a.atom & ALL_BONDS) && !(*a.atom & GRABBED))
remove_atom(board, a);
break;
}
case CONDUIT:
apply_conduit(solution, board, m);
break;
case EQUILIBRIUM:
default:
break;
}
}
}
static void adjust_axis_magnitude(struct vector *p, int32_t delta)
{
if (p->u > 0)
p->u += delta;
if (p->u < 0)
p->u -= delta;
if (p->v > 0)
p->v += delta;
if (p->v < 0)
p->v -= delta;
}
static struct vector normalize_axis(struct vector p)
{
if (p.u > 0)
p.u = 1;
if (p.u < 0)
p.u = -1;
if (p.v > 0)
p.v = 1;
if (p.v < 0)
p.v = -1;
return p;
}
static void record_swing_area(struct board *board, struct vector base, struct vector position, int rotation)
{
struct vector offset = { position.u - base.u, position.v - base.v };
if (rotation == -1)
offset = (struct vector){ offset.u + offset.v, -offset.u };
int32_t arm_length = abs(offset.u) | abs(offset.v);
offset = normalize_axis(offset);
switch (arm_length) {
case 3:
mark_used_area(board, (struct vector){ base.u + 3 * offset.u - 1 * offset.v, base.v + 1 * offset.u + 4 * offset.v });
mark_used_area(board, (struct vector){ base.u + 2 * offset.u - 2 * offset.v, base.v + 2 * offset.u + 4 * offset.v });
mark_used_area(board, (struct vector){ base.u + 1 * offset.u - 3 * offset.v, base.v + 3 * offset.u + 4 * offset.v });
// fall through
case 2:
mark_used_area(board, (struct vector){ base.u + 2 * offset.u - 1 * offset.v, base.v + 1 * offset.u + 3 * offset.v });
mark_used_area(board, (struct vector){ base.u + 1 * offset.u - 1 * offset.v, base.v + 1 * offset.u + 2 * offset.v });
mark_used_area(board, (struct vector){ base.u + 1 * offset.u - 2 * offset.v, base.v + 2 * offset.u + 3 * offset.v });
// fall through
case 1:
return;
default:
abort();
}
}
static size_t reserve_movement_index(struct board *board)
{
if (board->movements.length >= MAX_MOVEMENTS)
abort();
size_t capacity = board->movements.capacity;
while (board->movements.length >= capacity)
capacity = 4 * (capacity + 12) / 3;
if (capacity != board->movements.capacity) {
struct movement *elems = realloc(board->movements.movements,
sizeof(struct movement) * capacity);
if (!elems)
abort();
board->movements.movements = elems;
board->movements.capacity = capacity;
}
return board->movements.length++;
}
static bool movements_equal(struct movement a, struct movement b)
{
if (a.rotation == 0 && b.rotation == 0)
return vectors_equal(a.translation, b.translation);
if (a.rotation != b.rotation)
return false;
struct vector a_center = a.type == SWING_MOVEMENT ? a.base : a.absolute_grab_position;
struct vector b_center = b.type == SWING_MOVEMENT ? b.base : b.absolute_grab_position;
return vectors_equal(a_center, b_center);
}
static void move_atom(struct board *board, atom *a, struct vector position, size_t movement_index, uint32_t *chain_atom_list)
{
size_t capacity = board->moving_atoms.capacity;
while (board->moving_atoms.length >= capacity)
capacity = 4 * (capacity + 12) / 3;
if (capacity != board->moving_atoms.capacity) {
struct atom_at_position *elems = realloc(board->moving_atoms.atoms_at_positions,
sizeof(struct atom_at_position) * capacity);
if (!elems)
abort();
board->moving_atoms.atoms_at_positions = elems;
board->moving_atoms.capacity = capacity;
}
board->moving_atoms.atoms_at_positions[board->moving_atoms.length++] = (struct atom_at_position){
.atom = *a,
.position = position,
};
if (*a & IS_CHAIN_ATOM)
move_chain_atom_to_list(board, lookup_chain_atom(board, position), chain_atom_list);
if (remove_atom(board, (struct atom_ref_at_position){ a, position }))
*a |= MOVED | MOVEMENT_INDEX(movement_index);
}
static void move_atoms(struct board *board, atom *a, struct movement movement)
{
if ((*a & VALID) && (*a & REMOVED) && (*a & MOVED)) {
if (!movements_equal(movement, board->movements.movements[GET_MOVEMENT_INDEX(*a)]))
report_collision(board, movement.absolute_grab_position, "atom moved in two directions simultaneously");
return;
}
movement.first_chain_atom = UINT32_MAX;
movement.first_atom_index = board->moving_atoms.cursor;
size_t movement_index = reserve_movement_index(board);
move_atom(board, a, movement.absolute_grab_position, movement_index, &movement.first_chain_atom);
// do a breadth-first search over the molecule, removing each atom from the
// board as it's discovered.
while (board->moving_atoms.cursor < board->moving_atoms.length) {
struct atom_at_position m = board->moving_atoms.atoms_at_positions[board->moving_atoms.cursor];
for (int bond_direction = 0; bond_direction < 6; ++bond_direction) {
if (!(m.atom & (BOND_LOW_BITS << bond_direction) & ~RECENT_BONDS))
continue;
struct vector p = m.position;
struct vector d = u_offset_for_direction(bond_direction);
p.u += d.u;
p.v += d.v;
atom *b = lookup_atom(board, p);
if (!(*b & VALID) || (*b & REMOVED) || (*b & BEING_PRODUCED))
continue;
move_atom(board, b, p, movement_index, &movement.first_chain_atom);
}
board->moving_atoms.cursor++;
}
movement.number_of_atoms = board->moving_atoms.cursor - movement.first_atom_index;
board->movements.movements[movement_index] = movement;
}
static void apply_movement_to_position(struct vector base, struct vector translation, struct vector u, struct vector v, struct vector *position)
{
struct vector delta = *position;
delta.u -= base.u;
delta.v -= base.v;
*position = (struct vector){
u.u * delta.u + v.u * delta.v + base.u + translation.u,
u.v * delta.u + v.v * delta.v + base.v + translation.v,
};
}
static bool range_of_periods_where_motion_is_in_interval(int32_t motion, int32_t interval_min, int32_t interval_max, int32_t *entry_period, int32_t *exit_period)
{
if (motion == 0) {
// if there's no motion, either we stay in the interval forever (if zero
// is in the interval) or we never enter it.
*entry_period = INT32_MIN;
*exit_period = INT32_MAX;
return 0 >= interval_min && 0 <= interval_max;
} else if (motion < 0) {
// if the motion is negative, flip everything so it can be positive.
// note that max and min change roles when their signs change.
motion = -motion;
int32_t tmp = interval_max;
interval_max = -interval_min;
interval_min = -tmp;
}
// if the interval ends before the motion even begins, then we're never in
// the interval.
if (interval_max < 0)
return false;
// find the actual entry and exit periods.
*entry_period = (interval_min + motion - 1) / motion;
*exit_period = interval_max / motion;
// return whether the range is empty (false) or not (true).
return *entry_period <= *exit_period;
}
static bool position_may_eventually_be_visible_to_solution(struct solution *solution, struct vector original, struct vector current)
{
int32_t u_entry, u_exit, v_entry, v_exit;
if (!range_of_periods_where_motion_is_in_interval(current.u - original.u, solution->min_visible_u - original.u, solution->max_visible_u - original.u, &u_entry, &u_exit))
return false;
if (!range_of_periods_where_motion_is_in_interval(current.v - original.v, solution->min_visible_v - original.v, solution->max_visible_v - original.v, &v_entry, &v_exit))
return false;
// return true if the ranges overlap and false otherwise.
return v_entry <= u_exit && u_entry <= v_exit;
}
static int compare_movements_by_number_of_atoms(const void *a, const void *b)
{
return (int)((const struct movement *)a)->number_of_atoms - (int)((const struct movement *)b)->number_of_atoms;
}
static void perform_arm_instructions(struct solution *solution, struct board *board)
{
if (solution->tape_period == 0)
return;
board->moving_atoms.length = 0;
board->moving_atoms.cursor = 0;
board->movements.length = 0;
board->movements.cursor = 0;
uint32_t n = solution->number_of_arms;
for (uint32_t i = 0; i < n; ++i) {
struct mechanism *m = &solution->arms[i];
m->movement = zero_vector;
m->type &= ~MOVED_GRABBED_ATOMS;
if (board->cycle < (uint64_t)solution->arm_tape_start_cycle[i])
continue;
size_t index = board->cycle - (uint64_t)solution->arm_tape_start_cycle[i];
index %= solution->tape_period;
if (index >= solution->arm_tape_length[i])
continue;
char inst = solution->arm_tape[i][index];
if (inst == ' ' || inst == '\0')
continue;
// on half-cycle 1, grab and drop.
// on half-cycle 2, perform the rest of the instructions.
if ((board->half_cycle == 1) != (inst == 'r' || inst == 'f'))
continue;
struct vector track_motion = {0, 0};
// kind of cheesy but it works!
int32_t arm_length = abs(m->direction_u.u) | abs(m->direction_u.v);
// first, validate the instruction.
if (inst == 'r') {
// if the arm is already grabbing, grabbing again does nothing.
// additionally, van berlo's wheel doesn't grab or release.
if ((m->type & GRABBING) || (m->type & VAN_BERLO))
continue;
} else if (inst == 'f') {
// if the arm isn't grabbing, then releasing does nothing.
// additionally, van berlo's wheel doesn't grab or release.
if (!(m->type & GRABBING) || (m->type & VAN_BERLO))
continue;
} else if ((inst == 'w' || inst == 's') && !(m->type & PISTON)) {
report_collision(board, m->position, "trying to extend/retract a non-piston arm");
continue;
} else if (inst == 'w') {
// don't extend pistons past 3 hexes of length.
if (arm_length == 3)
continue;
} else if (inst == 's') {
// don't retract pistons below 1 hex of length.
if (arm_length == 1)
continue;
} else if (inst == 't' || inst == 'g') {
uint32_t index;
if (!lookup_track(solution, m->position, &index)) {
report_collision(board, m->position, "trying to move an arm along a track that isn't on a track");
continue;
}
if (inst == 't')
track_motion = solution->track_minus_motions[index];
else if (inst == 'g')
track_motion = solution->track_plus_motions[index];
// if the motion amount is zero, this is the end of the track.
if (track_motion.u == 0 && track_motion.v == 0)
continue;
}
m->type |= MOVED_GRABBED_ATOMS;
// next, apply the instruction to any grabbed atoms. atom movements are
// added to a list (board->movements) and deferred until later.
int step = angular_distance_between_grabbers(m->type);
for (int direction = 0; direction < 6; direction += step) {
struct vector offset = u_offset_for_direction(direction);
struct vector p = mechanism_relative_position(*m, offset.u, offset.v, 1);
if (inst == 'a')
record_swing_area(board, m->position, p, 1);
if (inst == 'd')
record_swing_area(board, m->position, p, -1);
struct atom_ref_at_position a = get_atom(board, *m, offset.u, offset.v);
if (!*a.atom)
continue;
if (inst == 'r' && !(*a.atom & REMOVED)) {
for (int i = 0; i < NUMBER_OF_ATOM_TYPES; ++i) {
if (*a.atom & ATOM_OF_TYPE(i)) {
board->atom_grabs[i]++;
break;
}
}
atom grabs = (*a.atom & GRABBED) / GRABBED_ONCE;
*a.atom &= ~GRABBED;
*a.atom |= (grabs + 1) * GRABBED_ONCE;
m->type |= GRABBING_LOW_BIT << direction;
continue;
}
if (!(m->type & (GRABBING_LOW_BIT << direction)) || (!(*a.atom & REMOVED) && !(*a.atom & GRABBED)))
continue;
if (inst == 'f' && !(*a.atom & REMOVED) && (*a.atom & GRABBED)) {
atom grabs = (*a.atom & GRABBED) / GRABBED_ONCE;
*a.atom &= ~GRABBED;
*a.atom |= (grabs - 1) * GRABBED_ONCE;
// allow conduits to transport this atom (and any atoms bonded to it).
*a.atom |= BEING_DROPPED;
schedule_flag_reset_if_needed(board, a.atom);
continue;
}
struct movement movement = {
.type = (m->type & PISTON) ? IS_PISTON : 0,
.base = m->position,
.base_rotation = m->arm_rotation,
.grabber_offset = offset,
.absolute_grab_position = a.position,
};
movement.grabber_offset.u *= arm_length;
movement.grabber_offset.v *= arm_length;
switch (inst) {
case 'q': // pivot ccw
movement.type |= PIVOT_MOVEMENT;
movement.rotation = 1;
move_atoms(board, a.atom, movement);
break;
case 'e': // pivot cw
movement.type |= PIVOT_MOVEMENT;
movement.rotation = -1;
move_atoms(board, a.atom, movement);
break;
case 'a': // rotate ccw
movement.type |= SWING_MOVEMENT;
movement.rotation = 1;
move_atoms(board, a.atom, movement);
break;
case 'd': // rotate cw
movement.type |= SWING_MOVEMENT;
movement.rotation = -1;
move_atoms(board, a.atom, movement);
break;
case 'w': // extend piston
movement.type |= PISTON_MOVEMENT;
movement.piston_extension = 1;
movement.translation = normalize_axis(m->direction_u);
move_atoms(board, a.atom, movement);
break;
case 's': // retract piston
movement.type |= PISTON_MOVEMENT;
movement.piston_extension = -1;
movement.translation = normalize_axis(m->direction_u);
movement.translation.u = -movement.translation.u;
movement.translation.v = -movement.translation.v;
move_atoms(board, a.atom, movement);
break;
case 't': // move along track, - direction
case 'g': // move along track, + direction
movement.type |= TRACK_MOVEMENT;
movement.translation = track_motion;
move_atoms(board, a.atom, movement);
break;
default:
break;
}
}
// finally, transform the arm itself.
switch (inst) {
case 'q': // pivot ccw
case 'e': // pivot cw
m->pivot_parity = !m->pivot_parity;
break;
case 'a': { // rotate ccw
struct vector u = u_offset_for_direction(1);
struct vector v = v_offset_for_direction(1);
struct vector nu = {
m->direction_u.u * u.u + m->direction_v.u * u.v,
m->direction_u.v * u.u + m->direction_v.v * u.v,
};
struct vector nv = {
m->direction_u.u * v.u + m->direction_v.u * v.v,
m->direction_u.v * v.u + m->direction_v.v * v.v,
};
m->direction_u = nu;
m->direction_v = nv;
m->arm_rotation++;
break;
}
case 'd': { // rotate cw
struct vector u = u_offset_for_direction(-1);
struct vector v = v_offset_for_direction(-1);
struct vector nu = {
m->direction_u.u * u.u + m->direction_v.u * u.v,
m->direction_u.v * u.u + m->direction_v.v * u.v,
};
struct vector nv = {
m->direction_u.u * v.u + m->direction_v.u * v.v,
m->direction_u.v * v.u + m->direction_v.v * v.v,
};
m->direction_u = nu;
m->direction_v = nv;
m->arm_rotation--;
break;
}
case 'w': // extend piston
adjust_axis_magnitude(&m->direction_u, 1);
adjust_axis_magnitude(&m->direction_v, 1);
break;
case 's': // retract piston
adjust_axis_magnitude(&m->direction_u, -1);
adjust_axis_magnitude(&m->direction_v, -1);
break;
case 't': // move along track, - direction
case 'g': // move along track, + direction
m->position.u += track_motion.u;
m->position.v += track_motion.v;
m->movement = track_motion;
break;
case 'r': // grab
m->type |= GRABBING;
break;
case 'f': // drop
// clear all the mechanism grabbing bits at once.
m->type &= ~GRABBING_EVERYTHING;
m->type &= ~GRABBING;
break;
default:
break;
}
// the weird (uint32_t)-(int64_t) thing is to handle the INT_MIN case.
if (m->arm_rotation > 0 && (uint32_t)m->arm_rotation > solution->maximum_absolute_arm_rotation)
solution->maximum_absolute_arm_rotation = (uint32_t)m->arm_rotation;
else if (m->arm_rotation < 0 && (uint32_t)-(int64_t)m->arm_rotation > solution->maximum_absolute_arm_rotation)
solution->maximum_absolute_arm_rotation = (uint32_t)-(int64_t)m->arm_rotation;
}
// carry out deferred movements.
if (board->half_cycle == 2) {
// report a collision if any static arm is grabbing a moving atom
for (uint32_t i = 0; i < n; ++i) {
struct mechanism *m = &solution->arms[i];
if (board->cycle < (uint64_t)solution->arm_tape_start_cycle[i])
continue;
// check whether the arm is static on this cycle.
if (m->type & MOVED_GRABBED_ATOMS)
continue;
int step = angular_distance_between_grabbers(m->type);
for (int direction = 0; direction < 6; direction += step) {
if (!(m->type & (GRABBING_LOW_BIT << direction)))
continue;
struct vector offset = u_offset_for_direction(direction);
struct vector pos = mechanism_relative_position(*m, offset.u, offset.v, 1);
atom *a = lookup_atom(board, pos);
if ((*a & VALID) && (*a & REMOVED) && (*a & MOVED))
report_collision(board, pos, "atom moved while being held stationary by another arm");
}
}
size_t atom_index = 0;
// sort movements by number of atoms to make the collision bounding box
// optimization work better. this has to be done before fixing up the
// chain atom list pointers.
qsort(board->movements.movements, board->movements.length, sizeof(struct movement), compare_movements_by_number_of_atoms);
size_t offset = board->moving_atoms.length;
if (offset * 2 > board->moving_atoms.capacity) {
board->moving_atoms.capacity = offset * 2;
board->moving_atoms.atoms_at_positions = realloc(board->moving_atoms.atoms_at_positions, sizeof(struct atom_at_position) * board->moving_atoms.capacity);
}
memcpy(board->moving_atoms.atoms_at_positions + offset, board->moving_atoms.atoms_at_positions, sizeof(struct atom_at_position) * offset);
for (size_t i = 0; i < board->movements.length; ++i) {
struct movement *m = &board->movements.movements[i];
memcpy(board->moving_atoms.atoms_at_positions + atom_index, board->moving_atoms.atoms_at_positions + offset + m->first_atom_index, m->number_of_atoms * sizeof(struct atom_at_position));
m->first_atom_index = atom_index;
atom_index += m->number_of_atoms;
}
int32_t maximum_rotation_distance = 1;
atom_index = 0;
// this is kind of terrible. we have to fix up the movement structs to
// look like the game is expecting (instead of the initial state, before
// the movement, the game expects to see the final state, after the
// movement already happened). so, for now, we'll do two passes. this
// code should be cleaned up at some point.
for (size_t i = 0; i < board->movements.length; ++i) {
struct movement *m = &board->movements.movements[i];
if (m->first_chain_atom != UINT32_MAX) {
// m->prev_in_list is pointing to stack data right now; fix it so it
// properly points to the list in the heap.
board->chain_atoms[m->first_chain_atom].prev_in_list = &m->first_chain_atom;
}
// printf("movement: %d %d by %d / %d %d around %d %d (%d)\n", m.absolute_grab_position.u, m.absolute_grab_position.v, m.rotation, m.translation.u, m.translation.v, m.base.u, m.base.v, m.type);
struct vector base = ((m->type & 3) == SWING_MOVEMENT) ? m->base : m->absolute_grab_position;
struct vector u = u_offset_for_direction(m->rotation);
struct vector v = v_offset_for_direction(m->rotation);
for (size_t j = 0; j < m->number_of_atoms; ++j) {
struct atom_at_position *ap = &board->moving_atoms.atoms_at_positions[atom_index++];
apply_movement_to_position(base, m->translation, u, v, &ap->position);
if (m->rotation != 0) {
struct vector delta = ap->position;
delta.u -= base.u;
delta.v -= base.v;
int32_t distance = (abs(delta.u) + abs(delta.v) + abs(delta.u + delta.v)) / 2;
if (distance > maximum_rotation_distance)
maximum_rotation_distance = distance;
rotate_bonds(&ap->atom, m->rotation);
}
}
uint32_t chain = m->first_chain_atom;
while (chain != UINT32_MAX) {
struct chain_atom *ca = &board->chain_atoms[chain];
apply_movement_to_position(base, m->translation, u, v, &ca->current_position);
if (board->chain_mode == EXTEND_CHAIN)
apply_movement_to_position(base, m->translation, u, v, &ca->original_position);
int rotation = ca->flags & CHAIN_ATOM_ROTATION;
ca->flags &= ~CHAIN_ATOM_ROTATION;
ca->flags |= normalize_direction(rotation + m->rotation);
if (m->rotation > 0) {
uint32_t sextants = ((ca->flags & CHAIN_ATOM_SWING_SEXTANTS) >> 1) & CHAIN_ATOM_SWING_SEXTANTS;
sextants |= 1u << (CHAIN_ATOM_SWING_SEXTANTS_SHIFT + 5);
ca->flags &= ~CHAIN_ATOM_SWING_SEXTANTS;
ca->flags |= sextants;
} else if (m->rotation < 0) {
uint32_t sextants = ((ca->flags & CHAIN_ATOM_SWING_SEXTANTS) << 1) & CHAIN_ATOM_SWING_SEXTANTS;
sextants |= 1u << CHAIN_ATOM_SWING_SEXTANTS_SHIFT;
ca->flags &= ~CHAIN_ATOM_SWING_SEXTANTS;
ca->flags |= sextants;
}
chain = ca->next_in_list;
}