-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabsorption-8.js
More file actions
1664 lines (1442 loc) · 50.4 KB
/
absorption-8.js
File metadata and controls
1664 lines (1442 loc) · 50.4 KB
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
// === ABSORPTION-8.JS: PRESSURE-BASED RESOURCE FLOW SYSTEM ===
// Enhanced plant simulation with pressure-based water/energy flow inspired by magmasim
// Built on the solid foundation of absorption-5.js
document.addEventListener("DOMContentLoaded", async () => {
// Fixed canvas size - 64x64 for testing (as per user preference)
const GRID_WIDTH = 64;
const GRID_HEIGHT = 64;
const SCALE_SIZE = 8;
const app = new PIXI.Application({
width: GRID_WIDTH * SCALE_SIZE,
height: GRID_HEIGHT * SCALE_SIZE,
backgroundColor: 0x000000,
});
document.getElementById("canvas-div").appendChild(app.view);
// === CONSTANTS ===
const CONSTANTS = {
// World parameters
WORLD: {
SCALE_SIZE: SCALE_SIZE,
TICK_INTERVAL: 40,
COLS: GRID_WIDTH,
ROWS: GRID_HEIGHT,
},
// Particle modes and transformations
FLUX: {
P_ENERGY: 0.08, // 8% chance for energy spawning
WATER_DIAGONAL_CHANCE: 0.3,
},
// Plant genetics parameters
GENETICS: {
GROWTH_ENERGY_THRESHOLD: 8,
MUTATION_RATE: 0.1,
MUTATION_STRENGTH: 0.2,
},
// Growth parameters
GROWTH: {
ENERGY_TO_GROW: 5,
GROWTH_COST: 3,
MAX_ENERGY: 20,
},
// Simulation parameters
SIMULATION: {
INITIAL_WATER_COUNT: 400,
INITIAL_SEED_COUNT: 1,
},
// NEW: Pressure system parameters
PRESSURE: {
FORCE_DECAY: 0.95, // Forces decay slowly to build up pressure
DIRECT_TRANSFER: 0.8, // 80% of force transferred directly to blocking particle
INDIRECT_TRANSFER: 0.2, // 20% distributed to alternate paths
MIN_FORCE_THRESHOLD: 0.05, // Lower threshold to trigger flow more easily
MAX_FORCE: 15, // Higher maximum pressure force
FLOW_PROBABILITY_MULTIPLIER: 0.5, // Higher probability = force * multiplier
},
};
// Colors and mode definitions
const colors = {
ENERGY: 0xffff00,
WATER: 0x0066ff,
VAPOR: 0xc8ffff,
SEED: 0x8b4513,
STEM: 0x228b22,
LEAF: 0x00ff00,
BUD: 0x90ee90,
NODE: 0x14a014,
FLOWER: 0xff69b4,
};
const modeTextures = Object.entries(colors).reduce((acc, [mode, color]) => {
const graphics = new PIXI.Graphics();
graphics.beginFill(color);
graphics.drawRect(0, 0, 1, 1);
graphics.endFill();
acc[mode] = app.renderer.generateTexture(graphics);
return acc;
}, {});
// Performance monitoring setup
const fpsTextStyle = new PIXI.TextStyle({
fontFamily: "Arial",
fontSize: 24,
fill: "white",
});
const fpsText = new PIXI.Text("FPS: 0", fpsTextStyle);
fpsText.x = 10;
fpsText.y = 10;
app.stage.addChild(fpsText);
const particleCountText = new PIXI.Text("Particles: 0", fpsTextStyle);
particleCountText.x = 10;
particleCountText.y = 40;
app.stage.addChild(particleCountText);
const fastForwardText = new PIXI.Text("", fpsTextStyle);
fastForwardText.x = 10;
fastForwardText.y = 70;
app.stage.addChild(fastForwardText);
const statusText = new PIXI.Text(
"PAUSED - Press SPACE to step | R for report",
fpsTextStyle
);
statusText.x = 10;
statusText.y = 100;
app.stage.addChild(statusText);
// Core simulation parameters
let particles = [];
let frame = 0;
let fastForward = false;
let fastForwardFactor = 10;
let paused = true;
let lastRenderTime = performance.now();
let idCounter = 1;
// Grid setup with fixed dimensions
let scaleSize = CONSTANTS.WORLD.SCALE_SIZE;
let cols = CONSTANTS.WORLD.COLS;
let rows = CONSTANTS.WORLD.ROWS;
// Particle modes
const Mode = {
ENERGY: "ENERGY",
WATER: "WATER",
VAPOR: "VAPOR",
SEED: "SEED",
STEM: "STEM",
LEAF: "LEAF",
BUD: "BUD",
NODE: "NODE",
FLOWER: "FLOWER",
};
// === SECTION 2: ENHANCED LAYERED OCCUPANCY GRIDS ===
class LayeredOccupancyGrid {
constructor(cols, rows) {
this.cols = cols;
this.rows = rows;
// Separate layers for different particle types
this.plantLayer = new Array(cols * rows).fill(null);
this.waterLayer = new Array(cols * rows).fill(null);
this.energyLayer = new Array(cols * rows).fill(null);
// NEW: Pressure tracking layers
this.waterPressure = new Array(cols * rows).fill(0);
this.energyPressure = new Array(cols * rows).fill(0);
// Visual overlays
this.waterOverlays = new Array(cols * rows).fill(null);
this.energyOverlays = new Array(cols * rows).fill(null);
}
getIndex(x, y) {
return y * this.cols + x;
}
// Plant layer methods (unchanged)
setPlant(x, y, particle) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = particle;
}
}
getPlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.plantLayer[this.getIndex(x, y)];
}
return null;
}
removePlant(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
this.plantLayer[this.getIndex(x, y)] = null;
}
}
// NEW: Pressure methods
addWaterPressure(x, y, force) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.waterPressure[index] = Math.min(
this.waterPressure[index] + force,
CONSTANTS.PRESSURE.MAX_FORCE
);
}
}
addEnergyPressure(x, y, force) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.energyPressure[index] = Math.min(
this.energyPressure[index] + force,
CONSTANTS.PRESSURE.MAX_FORCE
);
}
}
getWaterPressure(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.waterPressure[this.getIndex(x, y)];
}
return 0;
}
getEnergyPressure(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.energyPressure[this.getIndex(x, y)];
}
return 0;
}
decayPressures() {
// Decay all pressure forces each tick
for (let i = 0; i < this.waterPressure.length; i++) {
this.waterPressure[i] *= CONSTANTS.PRESSURE.FORCE_DECAY;
this.energyPressure[i] *= CONSTANTS.PRESSURE.FORCE_DECAY;
// Remove negligible forces
if (this.waterPressure[i] < CONSTANTS.PRESSURE.MIN_FORCE_THRESHOLD) {
this.waterPressure[i] = 0;
}
if (this.energyPressure[i] < CONSTANTS.PRESSURE.MIN_FORCE_THRESHOLD) {
this.energyPressure[i] = 0;
}
}
}
// Enhanced water layer methods with pressure
setWater(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
this.waterLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.waterOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0x0066ff, 0.2);
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.waterOverlays[index] = overlay;
} else if (!particle && this.waterOverlays[index]) {
app.stage.removeChild(this.waterOverlays[index]);
this.waterOverlays[index] = null;
}
}
}
getWater(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.waterLayer[this.getIndex(x, y)];
}
return null;
}
hasWater(x, y) {
return this.getWater(x, y) !== null;
}
// Enhanced energy layer methods with pressure
setEnergy(x, y, particle = null) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
const index = this.getIndex(x, y);
// Special handling for seeds (allow energy stacking)
const plantAtPosition = this.getPlant(x, y);
if (
particle &&
this.energyLayer[index] !== null &&
plantAtPosition &&
plantAtPosition.mode === Mode.SEED
) {
return; // Keep first energy accessible for seeds
}
this.energyLayer[index] = particle;
// Create/remove visual overlay
if (particle && !this.energyOverlays[index]) {
const overlay = new PIXI.Graphics();
overlay.beginFill(0xffff00, 0.1);
overlay.drawRect(0, 0, scaleSize, scaleSize);
overlay.endFill();
overlay.x = x * scaleSize;
overlay.y = y * scaleSize;
app.stage.addChild(overlay);
this.energyOverlays[index] = overlay;
} else if (!particle && this.energyOverlays[index]) {
app.stage.removeChild(this.energyOverlays[index]);
this.energyOverlays[index] = null;
}
}
}
getEnergy(x, y) {
if (x >= 0 && x < this.cols && y >= 0 && y < this.rows) {
return this.energyLayer[this.getIndex(x, y)];
}
return null;
}
hasEnergy(x, y) {
return this.getEnergy(x, y) !== null;
}
// Utility methods (unchanged)
isPlantOccupied(x, y) {
if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return true;
return this.getPlant(x, y) !== null;
}
isEmptyMooreNeighborhood(x, y) {
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = x + dx,
ny = y + dy;
if (nx < 0 || nx >= this.cols || ny < 0 || ny >= this.rows) continue;
if (this.getPlant(nx, ny)) return false;
}
}
return true;
}
getPlantNeighbors(x, y) {
let neighbors = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
let nx = x + dx,
ny = y + dy;
if (nx >= 0 && nx < this.cols && ny >= 0 && ny < this.rows) {
const plant = this.getPlant(nx, ny);
if (plant !== null) {
neighbors.push({ plant, x: nx, y: ny });
}
}
}
}
return neighbors;
}
}
let occupancyGrid = new LayeredOccupancyGrid(cols, rows);
// Helper function to count plant cells for a given plant ID
function countPlantCells(plantId) {
return particles.filter((p) => p.isPlantPart() && p.plantId === plantId)
.length;
}
// === SECTION 3: PLANT GENETICS SYSTEM (unchanged from absorption-5) ===
class PlantGenetics {
constructor(parentA = null, parentB = null) {
if (parentA && parentB) {
this.combineParents(parentA, parentB);
} else if (parentA) {
this.inheritFromParent(parentA);
} else {
this.generateRandom();
}
}
generateRandom() {
this.genes = {
internodeSpacing: 3 + Math.floor(Math.random() * 4), // 3-6
budGrowthLimit: 8 + Math.floor(Math.random() * 8), // 8-15
leafNodePattern: [1, 1, 0, 1], // Default phyllotaxis
branchingNodes: [5, 8], // Which nodes branch
branchAngle: 45, // Angle of branches
leafDelay: 2, // Ticks before leaf buds activate
floweringHeight: 8, // Height to start flowering
energyThreshold: 8, // Energy needed for growth
droughtTolerance: 0.5 + Math.random() * 0.5,
coldTolerance: 0.5 + Math.random() * 0.5,
};
}
inheritFromParent(parent) {
this.genes = JSON.parse(JSON.stringify(parent.genes));
this.mutate();
}
combineParents(parentA, parentB) {
this.genes = {};
Object.keys(parentA.genes).forEach((key) => {
this.genes[key] =
Math.random() < 0.5 ? parentA.genes[key] : parentB.genes[key];
});
this.mutate();
}
mutate() {
if (Math.random() < CONSTANTS.GENETICS.MUTATION_RATE) {
const keys = Object.keys(this.genes);
const mutKey = keys[Math.floor(Math.random() * keys.length)];
if (typeof this.genes[mutKey] === "number") {
const change =
(Math.random() - 0.5) * 2 * CONSTANTS.GENETICS.MUTATION_STRENGTH;
this.genes[mutKey] = Math.max(1, this.genes[mutKey] * (1 + change));
}
}
}
calculateFitness() {
const spacing = this.genes.internodeSpacing;
const height = this.genes.budGrowthLimit;
const energy = this.genes.energyThreshold;
return (
10 -
Math.abs(spacing - 4) +
(15 - Math.abs(height - 12)) +
(10 - Math.abs(energy - 8))
);
}
getColor() {
const fitness = this.calculateFitness();
if (fitness > 30) return 0xffd700; // Gold
if (fitness > 25) return 0xffa500; // Orange
if (fitness > 20) return 0x32cd32; // Lime green
return 0x228b22; // Forest green
}
}
// === SECTION 4: ENHANCED PARTICLE CLASS WITH PRESSURE SYSTEM ===
class Particle {
constructor(x, y, mode = Mode.WATER) {
this.pos = { x, y };
this.id = idCounter++;
this.mode = mode;
this.age = 0;
// Plant-specific properties
this.plantId = null;
this.genetics = null;
this.parent = null;
this.children = [];
// Movement properties
this.isFalling = true;
this.fallingDirection = null;
// NEW: Pressure system properties
this.resourceDemand = new Map(); // Tracks resource demands for different sources
this.lastFlowAttempt = 0; // Tracks when we last tried to flow
// Logging flags
this.hasAttemptedSprout = false;
this.hasLoggedBlocked = false;
this.hasLoggedFirstRender = false;
// Create sprite
this.sprite = new PIXI.Sprite(modeTextures[this.mode]);
this.sprite.x = Math.floor(x * scaleSize);
this.sprite.y = Math.floor(y * scaleSize);
this.sprite.scale.set(scaleSize, scaleSize);
if (this.isPlantPart()) {
this.sprite.alpha = 0.5;
}
app.stage.addChild(this.sprite);
// Create aura for energy particles
if (this.mode === Mode.ENERGY && !this.auraSprite) {
this.auraSprite = new PIXI.Graphics();
this.auraSprite.beginFill(0xffff00, 0.05);
this.auraSprite.drawRect(0, 0, scaleSize * 3, scaleSize * 3);
this.auraSprite.endFill();
this.auraSprite.x = (x - 1) * scaleSize;
this.auraSprite.y = (y - 1) * scaleSize;
app.stage.addChildAt(this.auraSprite, 0);
this.sprite.alpha = 0.1;
}
// Set in appropriate occupancy grid layer
if (this.isPlantPart()) {
occupancyGrid.setPlant(x, y, this);
} else if (this.mode === Mode.ENERGY) {
occupancyGrid.setEnergy(x, y, this);
} else if (this.mode === Mode.WATER) {
occupancyGrid.setWater(x, y, this);
}
}
isPlantPart() {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(this.mode);
}
setMode(mode) {
if (this.mode !== mode) {
const oldMode = this.mode;
this.mode = mode;
if (this.sprite) {
this.sprite.texture = modeTextures[mode];
if (this.isPlantPart() && this.genetics) {
const color = this.genetics.getColor();
this.sprite.tint = color;
}
}
// Handle occupancy grid changes
if (this.isPlantPart() && !this.wasPlantPart(oldMode)) {
occupancyGrid.setPlant(this.pos.x, this.pos.y, this);
} else if (!this.isPlantPart() && this.wasPlantPart(oldMode)) {
occupancyGrid.removePlant(this.pos.x, this.pos.y);
}
}
}
wasPlantPart(mode) {
return [
Mode.SEED,
Mode.STEM,
Mode.LEAF,
Mode.BUD,
Mode.NODE,
Mode.FLOWER,
].includes(mode);
}
update() {
this.age++;
// Update based on mode
if (this.mode === Mode.WATER) {
this.updateWater();
} else if (this.mode === Mode.ENERGY) {
this.updateEnergy();
} else if (this.mode === Mode.VAPOR) {
this.updateVapor();
} else if (this.mode === Mode.SEED) {
this.updateSeed();
} else if (this.mode === Mode.BUD) {
this.updateBud();
} else if (this.mode === Mode.FLOWER) {
this.updateFlower();
this.updatePlantPart();
} else if (this.isPlantPart()) {
this.updatePlantPart();
}
}
// === NEW: PRESSURE-BASED RESOURCE FLOW METHODS ===
createResourceDemand(resourceType, force) {
// Creates pressure/demand for a resource at this location
if (resourceType === "water") {
occupancyGrid.addWaterPressure(this.pos.x, this.pos.y, force);
} else if (resourceType === "energy") {
occupancyGrid.addEnergyPressure(this.pos.x, this.pos.y, force);
}
}
tryPressureBasedFlow(resourceType) {
// NEW: Pressure-based resource flow inspired by magmasim
const isWater = resourceType === "water";
const hasResource = isWater
? occupancyGrid.hasWater(this.pos.x, this.pos.y)
: occupancyGrid.hasEnergy(this.pos.x, this.pos.y);
if (!hasResource) return false;
const pressure = isWater
? occupancyGrid.getWaterPressure(this.pos.x, this.pos.y)
: occupancyGrid.getEnergyPressure(this.pos.x, this.pos.y);
// Calculate flow probability based on pressure
const flowProbability = Math.min(
pressure * CONSTANTS.PRESSURE.FLOW_PROBABILITY_MULTIPLIER,
1.0
);
// Only attempt flow if there's sufficient pressure
if (pressure < CONSTANTS.PRESSURE.MIN_FORCE_THRESHOLD) {
// Debug: Log why flow isn't happening
if (pressure > 0) {
console.log(
`⚠️ ${this.mode} at (${this.pos.x}, ${
this.pos.y
}): ${resourceType} pressure ${pressure.toFixed(
2
)} below threshold ${CONSTANTS.PRESSURE.MIN_FORCE_THRESHOLD}`
);
}
return false;
}
// Try to flow based on probability
if (Math.random() < flowProbability) {
console.log(
`🔄 ${this.mode} at (${this.pos.x}, ${
this.pos.y
}) attempting ${resourceType} flow with pressure ${pressure.toFixed(
2
)}, probability ${flowProbability.toFixed(2)}`
);
return this.attemptResourceFlow(resourceType, pressure);
}
return false;
}
attemptResourceFlow(resourceType, pressure) {
// Attempt to flow resource to neighboring plant cells
const neighbors = this.getResourceFlowNeighbors(resourceType);
for (const neighbor of neighbors) {
const canFlow =
resourceType === "water"
? !occupancyGrid.hasWater(neighbor.x, neighbor.y)
: !occupancyGrid.hasEnergy(neighbor.x, neighbor.y);
if (canFlow) {
// Flow resource to neighbor
const resource =
resourceType === "water"
? occupancyGrid.getWater(this.pos.x, this.pos.y)
: occupancyGrid.getEnergy(this.pos.x, this.pos.y);
if (resource) {
// Remove from current position
if (resourceType === "water") {
occupancyGrid.setWater(this.pos.x, this.pos.y, null);
occupancyGrid.setWater(neighbor.x, neighbor.y, resource);
} else {
occupancyGrid.setEnergy(this.pos.x, this.pos.y, null);
occupancyGrid.setEnergy(neighbor.x, neighbor.y, resource);
}
// Update resource particle position
resource.pos.x = neighbor.x;
resource.pos.y = neighbor.y;
resource.sprite.x = neighbor.x * scaleSize;
resource.sprite.y = neighbor.y * scaleSize;
if (resource.auraSprite) {
resource.auraSprite.x = (neighbor.x - 1) * scaleSize;
resource.auraSprite.y = (neighbor.y - 1) * scaleSize;
}
console.log(
`💧 ${resourceType} flowed from (${this.pos.x}, ${this.pos.y}) to (${neighbor.x}, ${neighbor.y}) via pressure`
);
return true;
}
} else {
// Neighbor is blocked - distribute pressure
this.distributePressureToNeighbor(neighbor, resourceType, pressure);
}
}
return false;
}
distributePressureToNeighbor(neighbor, resourceType, pressure) {
// Distribute pressure forces when flow is blocked (inspired by magmasim)
const directForce = pressure * CONSTANTS.PRESSURE.DIRECT_TRANSFER;
const indirectForce = pressure * CONSTANTS.PRESSURE.INDIRECT_TRANSFER;
// Direct pressure to blocking neighbor
if (resourceType === "water") {
occupancyGrid.addWaterPressure(neighbor.x, neighbor.y, directForce);
} else {
occupancyGrid.addEnergyPressure(neighbor.x, neighbor.y, directForce);
}
// Indirect pressure to alternate paths
const alternates = this.getAlternateFlowPaths(neighbor, resourceType);
for (const alt of alternates) {
if (resourceType === "water") {
occupancyGrid.addWaterPressure(
alt.x,
alt.y,
indirectForce / alternates.length
);
} else {
occupancyGrid.addEnergyPressure(
alt.x,
alt.y,
indirectForce / alternates.length
);
}
}
}
getResourceFlowNeighbors(resourceType) {
// Get neighbors for resource flow based on plant hierarchy and adjacency
let neighbors = [];
if (resourceType === "water") {
// Water flows UPWARD: from parent to children (root to extremities)
if (this.children) {
for (const child of this.children) {
if (child.isPlantPart && child.isPlantPart()) {
neighbors.push({
x: child.pos.x,
y: child.pos.y,
plant: child,
priority: 1,
});
}
}
}
// Also check adjacent plant cells that are higher (closer to extremities)
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = this.pos.x + dx;
const ny = this.pos.y + dy;
if (
nx >= 0 &&
nx < cols &&
ny >= 0 &&
ny < rows &&
ny < this.pos.y
) {
const plant = occupancyGrid.getPlant(nx, ny);
if (plant && plant.plantId === this.plantId) {
const exists = neighbors.some((n) => n.x === nx && n.y === ny);
if (!exists) {
neighbors.push({
x: nx,
y: ny,
plant: plant,
priority: 2,
});
}
}
}
}
}
} else {
// Energy flows DOWNWARD: from children to parent (extremities to root)
if (
this.parent &&
this.parent.isPlantPart &&
this.parent.isPlantPart()
) {
neighbors.push({
x: this.parent.pos.x,
y: this.parent.pos.y,
plant: this.parent,
priority: 1,
});
}
if (this.children) {
for (const child of this.children) {
if (child.isPlantPart && child.isPlantPart()) {
neighbors.push({
x: child.pos.x,
y: child.pos.y,
plant: child,
priority: 2,
});
}
}
}
// Also check adjacent plant cells that are lower (closer to root)
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = this.pos.x + dx;
const ny = this.pos.y + dy;
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows) {
const plant = occupancyGrid.getPlant(nx, ny);
if (plant && plant.plantId === this.plantId) {
const exists = neighbors.some((n) => n.x === nx && n.y === ny);
if (!exists) {
// Priority 1 if cell is lower (toward root), priority 3 if higher
const priority = ny > this.pos.y ? 1 : 3;
neighbors.push({
x: nx,
y: ny,
plant: plant,
priority: priority,
});
}
}
}
}
}
}
// Sort by priority
neighbors.sort((a, b) => a.priority - b.priority);
return neighbors;
}
getAlternateFlowPaths(blockedNeighbor, resourceType) {
// Get alternate flow paths when primary path is blocked
const alternates = [];
// Check adjacent cells that are part of the same plant
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
const nx = this.pos.x + dx;
const ny = this.pos.y + dy;
if (nx >= 0 && nx < cols && ny >= 0 && ny < rows) {
const plant = occupancyGrid.getPlant(nx, ny);
if (
plant &&
plant.plantId === this.plantId &&
(nx !== blockedNeighbor.x || ny !== blockedNeighbor.y)
) {
alternates.push({ x: nx, y: ny, plant });
}
}
}
}
return alternates;
}
// === ENHANCED PARTICLE MOVEMENT ===
moveRel(x, y) {
let newY = this.pos.y + y;
if (newY < 0) {
newY = 0;
} else if (newY >= rows) {
newY = rows - 1;
}
let newX = this.pos.x + x;
if (newX < 0 || newX >= cols) {
return false;
}
this.pos.x = newX;
this.pos.y = newY;
if (this.sprite) {
this.sprite.x = Math.floor(this.pos.x * scaleSize);
this.sprite.y = Math.floor(this.pos.y * scaleSize);
}
// Update occupancy grid
if (this.isPlantPart()) {
occupancyGrid.removePlant(this.pos.x - x, this.pos.y - y);
occupancyGrid.setPlant(this.pos.x, this.pos.y, this);
} else if (this.mode === Mode.ENERGY) {
occupancyGrid.setEnergy(this.pos.x - x, this.pos.y - y, null);
occupancyGrid.setEnergy(this.pos.x, this.pos.y, this);
} else if (this.mode === Mode.WATER) {
occupancyGrid.setWater(this.pos.x - x, this.pos.y - y, null);
occupancyGrid.setWater(this.pos.x, this.pos.y, this);
}
return true;
}
// === VISUAL OVERLAY METHODS ===
createWaterOverlay() {
if (this.mode !== Mode.WATER) return;
if (!this.waterOverlay) {
this.waterOverlay = new PIXI.Graphics();
this.waterOverlay.beginFill(0x0066ff, 0.2);
this.waterOverlay.drawRect(0, 0, scaleSize, scaleSize);
this.waterOverlay.endFill();
this.waterOverlay.x = this.pos.x * scaleSize;
this.waterOverlay.y = this.pos.y * scaleSize;
app.stage.addChild(this.waterOverlay);
}
if (!this.waterAura) {
this.waterAura = new PIXI.Graphics();
this.waterAura.beginFill(0x0066ff, 0.1);
this.waterAura.drawRect(0, 0, scaleSize * 3, scaleSize * 3);
this.waterAura.endFill();
this.waterAura.x = (this.pos.x - 1) * scaleSize;
this.waterAura.y = (this.pos.y - 1) * scaleSize;
app.stage.addChildAt(this.waterAura, 0);
}
}
updateWaterOverlay() {
if (this.waterOverlay) {
this.waterOverlay.x = this.pos.x * scaleSize;
this.waterOverlay.y = this.pos.y * scaleSize;
}
if (this.waterAura) {
this.waterAura.x = (this.pos.x - 1) * scaleSize;
this.waterAura.y = (this.pos.y - 1) * scaleSize;
}
}
// === PARTICLE UPDATE METHODS ===
isPositionOccupied(x, y) {
if (x < 0 || x >= cols || y < 0 || y >= rows) return true;
if (occupancyGrid.isPlantOccupied(x, y)) return true;
for (const particle of particles) {
if (
particle !== this &&
particle.mode === Mode.WATER &&
particle.pos.x === x &&
particle.pos.y === y
) {
return true;
}
}
if (this.mode === Mode.ENERGY) {
for (const particle of particles) {
if (
particle !== this &&
particle.mode === Mode.ENERGY &&
particle.pos.x === x &&
particle.pos.y === y
) {
const plantAtPosition = occupancyGrid.getPlant(x, y);
if (plantAtPosition && plantAtPosition.mode === Mode.SEED) {
return false; // Allow stacking on seeds
}
return true;
}
}
}
return false;
}
updateWater() {
// Water physics with pressure awareness
if (this.isFalling && this.pos.y < rows - 1) {
if (!this.isPositionOccupied(this.pos.x, this.pos.y + 1)) {
this.moveRel(0, 1);
this.fallingDirection = null;
} else {
if (this.fallingDirection === null) {
this.fallingDirection = Math.random() < 0.5 ? "left" : "right";
}
if (this.fallingDirection === "left") {
if (!this.isPositionOccupied(this.pos.x - 1, this.pos.y + 1)) {
this.moveRel(-1, 1);
} else if (!this.isPositionOccupied(this.pos.x - 1, this.pos.y)) {
this.moveRel(-1, 0);
} else {
this.fallingDirection = "right";
}
} else {
if (!this.isPositionOccupied(this.pos.x + 1, this.pos.y + 1)) {
this.moveRel(1, 1);
} else if (!this.isPositionOccupied(this.pos.x + 1, this.pos.y)) {
this.moveRel(1, 0);
} else {
this.fallingDirection = "left";
}
}
}
} else if (this.pos.y >= rows - 1) {
this.isFalling = false;
}
// Water absorption by seeds (root uptake)
const plant = occupancyGrid.getPlant(this.pos.x, this.pos.y);
if (plant && plant.plantId && plant.mode === Mode.SEED) {
const alreadyHasWater = occupancyGrid.hasWater(this.pos.x, this.pos.y);
if (!alreadyHasWater) {
occupancyGrid.setWater(this.pos.x, this.pos.y, this);
this.sprite.visible = false;
this.isFalling = false;
this.createWaterOverlay();
console.log(
`💧 Water absorbed by SEED (root uptake) at (${this.pos.x}, ${this.pos.y})`
);