@buley/hexgrid-3d 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.json +28 -0
- package/LICENSE +39 -0
- package/README.md +291 -0
- package/examples/basic-usage.tsx +52 -0
- package/package.json +65 -0
- package/public/hexgrid-worker.js +1763 -0
- package/rust/Cargo.toml +41 -0
- package/rust/src/lib.rs +740 -0
- package/rust/src/math.rs +574 -0
- package/rust/src/spatial.rs +245 -0
- package/rust/src/statistics.rs +496 -0
- package/src/HexGridEnhanced.ts +16 -0
- package/src/Snapshot.ts +1402 -0
- package/src/adapters.ts +65 -0
- package/src/algorithms/AdvancedStatistics.ts +328 -0
- package/src/algorithms/BayesianStatistics.ts +317 -0
- package/src/algorithms/FlowField.ts +126 -0
- package/src/algorithms/FluidSimulation.ts +99 -0
- package/src/algorithms/GraphAlgorithms.ts +184 -0
- package/src/algorithms/OutlierDetection.ts +391 -0
- package/src/algorithms/ParticleSystem.ts +85 -0
- package/src/algorithms/index.ts +13 -0
- package/src/compat.ts +96 -0
- package/src/components/HexGrid.tsx +31 -0
- package/src/components/NarrationOverlay.tsx +221 -0
- package/src/components/index.ts +2 -0
- package/src/features.ts +125 -0
- package/src/index.ts +30 -0
- package/src/math/HexCoordinates.ts +15 -0
- package/src/math/Matrix4.ts +35 -0
- package/src/math/Quaternion.ts +37 -0
- package/src/math/SpatialIndex.ts +114 -0
- package/src/math/Vector3.ts +69 -0
- package/src/math/index.ts +11 -0
- package/src/note-adapter.ts +124 -0
- package/src/ontology-adapter.ts +77 -0
- package/src/stores/index.ts +1 -0
- package/src/stores/uiStore.ts +85 -0
- package/src/types/index.ts +3 -0
- package/src/types.ts +152 -0
- package/src/utils/image-utils.ts +25 -0
- package/src/wasm/HexGridWasmWrapper.ts +753 -0
- package/src/wasm/index.ts +7 -0
- package/src/workers/hexgrid-math.ts +177 -0
- package/src/workers/hexgrid-worker.worker.ts +1807 -0
- package/tsconfig.json +18 -0
|
@@ -0,0 +1,1763 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/// <reference lib="webworker" />
|
|
3
|
+
const WORKER_ID = Math.random().toString(36).substring(7);
|
|
4
|
+
console.log('[hexgrid-worker] loaded id=', WORKER_ID);
|
|
5
|
+
const workerDebug = {
|
|
6
|
+
cohesionBoost: 6.0, // BOOSTED: strongly favor growth near cluster centroids to build larger regions
|
|
7
|
+
enableMerges: true, // ENABLED: merge small fragments into nearby larger clusters
|
|
8
|
+
mergeSmallComponentsThreshold: 20, // INCREASED: merge clusters of 20 hexes or fewer
|
|
9
|
+
mergeLogs: false,
|
|
10
|
+
evolutionIntervalMs: 30000,
|
|
11
|
+
debugLogs: false,
|
|
12
|
+
enableCellDeath: true, // ENABLED: allow fully surrounded cells to die and respawn with better positioning
|
|
13
|
+
cellDeathProbability: 0.05, // 5% chance per evolution for fully surrounded cells to reset
|
|
14
|
+
enableMutation: true, // ENABLED: allow dying cells to mutate into different photos
|
|
15
|
+
mutationProbability: 0.3, // 30% chance for a dying cell to respawn as a different photo
|
|
16
|
+
enableVirilityBoost: true, // ENABLED: boost infection rate based on photo velocity/upvotes
|
|
17
|
+
virilityMultiplier: 1.0, // Multiplier for virility effect (1.0 = normal, higher = more impact)
|
|
18
|
+
annealingRate: 2.0 // Multiplier for death/churn rates to help system escape local optima (1.0 = normal, higher = more reorganization)
|
|
19
|
+
};
|
|
20
|
+
// Tuning flags for cluster tiling behaviour
|
|
21
|
+
workerDebug.clusterPreserveAspect = true; // when true, preserve cluster aspect ratio when mapping to tile grid
|
|
22
|
+
workerDebug.clusterDynamicTiling = true; // when true, calculate tilesX/tilesY dynamically based on cluster aspect ratio
|
|
23
|
+
workerDebug.clusterAnchor = 'center'; // 'center' or 'min' (used during aspect correction)
|
|
24
|
+
workerDebug.clusterGlobalAlign = false; // when true, clusters snap to global tile anchor for better neighbor alignment
|
|
25
|
+
workerDebug.clusterUvInset = 0.0; // shrink UVs slightly to allow texture filtering/edge blending (0..0.5)
|
|
26
|
+
workerDebug.clusterJitter = 0.0; // small (0..0.5) fractional jitter applied to normalized coords before quantization
|
|
27
|
+
// adjacency mode for cluster tiling: 'hex' (6-way) or 'rect' (4-way). 'rect' gives raster-like, cohesive images
|
|
28
|
+
workerDebug.clusterAdjacency = 'rect';
|
|
29
|
+
// maximum number of tiles to allocate for a cluster when dynamically expanding (cap)
|
|
30
|
+
workerDebug.clusterMaxTiles = 128;
|
|
31
|
+
// whether to 'contain' (fit whole image within cluster bounds) or 'cover' (fill cluster and allow cropping)
|
|
32
|
+
workerDebug.clusterFillMode = 'contain';
|
|
33
|
+
// scan order for filling tiles: 'row' = left->right each row, 'serpentine' = zig-zag per row
|
|
34
|
+
workerDebug.clusterScanMode = 'row';
|
|
35
|
+
// when true, compute tile centers using hex-row parity offsets so ordering follows hex staggering
|
|
36
|
+
workerDebug.clusterParityAware = true;
|
|
37
|
+
// when true, include computed tile centers in evolved message for debug visualization
|
|
38
|
+
workerDebug.showTileCenters = false;
|
|
39
|
+
// when true, enable direct hex lattice mapping fast-path (parity-correct row/col inference)
|
|
40
|
+
workerDebug.clusterHexLattice = true;
|
|
41
|
+
// when true, horizontally nudge odd rows' UV sampling by half a tile width to compensate
|
|
42
|
+
// for physical hex center staggering (attempts to eliminate visible half-hex seams)
|
|
43
|
+
workerDebug.clusterParityUvShift = true;
|
|
44
|
+
// when true, compact gaps in each row of the hex lattice for more contiguous image tiles
|
|
45
|
+
workerDebug.clusterCompactGaps = true;
|
|
46
|
+
const cache = { neighborMap: new Map(), gridBounds: null, photoClusters: new Map(), connectedComponents: new Map(), gridPositions: new Map(), lastInfectionCount: 0, lastGeneration: -1, isSpherical: false, cacheReady: false };
|
|
47
|
+
function safePostError(err) { try {
|
|
48
|
+
self.postMessage({ type: 'error', error: err instanceof Error ? err.message : String(err) });
|
|
49
|
+
}
|
|
50
|
+
catch (e) { } }
|
|
51
|
+
function getGridBounds(positions) {
|
|
52
|
+
if (cache.gridBounds)
|
|
53
|
+
return cache.gridBounds;
|
|
54
|
+
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
|
|
55
|
+
for (const p of positions) {
|
|
56
|
+
if (!p)
|
|
57
|
+
continue;
|
|
58
|
+
minX = Math.min(minX, p[0]);
|
|
59
|
+
maxX = Math.max(maxX, p[0]);
|
|
60
|
+
minY = Math.min(minY, p[1]);
|
|
61
|
+
maxY = Math.max(maxY, p[1]);
|
|
62
|
+
}
|
|
63
|
+
cache.gridBounds = { minX, maxX, minY, maxY, width: maxX - minX, height: maxY - minY };
|
|
64
|
+
return cache.gridBounds;
|
|
65
|
+
}
|
|
66
|
+
function distanceBetween(a, b, bounds, isSpherical) {
|
|
67
|
+
let dx = b[0] - a[0];
|
|
68
|
+
let dy = b[1] - a[1];
|
|
69
|
+
if (isSpherical && bounds.width > 0 && bounds.height > 0) {
|
|
70
|
+
if (Math.abs(dx) > bounds.width / 2) {
|
|
71
|
+
dx = dx > 0 ? dx - bounds.width : dx + bounds.width;
|
|
72
|
+
}
|
|
73
|
+
if (Math.abs(dy) > bounds.height / 2) {
|
|
74
|
+
dy = dy > 0 ? dy - bounds.height : dy + bounds.height;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return Math.sqrt(dx * dx + dy * dy);
|
|
78
|
+
}
|
|
79
|
+
function getNeighborsCached(index, positions, hexRadius) {
|
|
80
|
+
// Immediate return if cached - no blocking
|
|
81
|
+
if (cache.neighborMap.has(index)) {
|
|
82
|
+
const cached = cache.neighborMap.get(index);
|
|
83
|
+
if (Array.isArray(cached))
|
|
84
|
+
return cached;
|
|
85
|
+
// Invalid cache entry - clear it and recompute
|
|
86
|
+
cache.neighborMap.delete(index);
|
|
87
|
+
}
|
|
88
|
+
// Validate inputs before computation
|
|
89
|
+
if (!positions || !Array.isArray(positions) || positions.length === 0) {
|
|
90
|
+
console.warn('[getNeighborsCached] Invalid positions array, returning empty');
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
if (typeof index !== 'number' || index < 0 || index >= positions.length) {
|
|
94
|
+
console.warn('[getNeighborsCached] Invalid index', index, 'for positions length', positions.length);
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
if (typeof hexRadius !== 'number' || hexRadius <= 0) {
|
|
98
|
+
console.warn('[getNeighborsCached] Invalid hexRadius', hexRadius);
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
const out = [];
|
|
102
|
+
const pos = positions[index];
|
|
103
|
+
if (!pos) {
|
|
104
|
+
console.warn('[getNeighborsCached] No position at index', index);
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const bounds = getGridBounds(positions);
|
|
109
|
+
const threshold = Math.sqrt(3) * hexRadius * 1.15;
|
|
110
|
+
const isSpherical = !!cache.isSpherical;
|
|
111
|
+
// Fast path: check only nearby candidates (≈6 neighbors for hex grid)
|
|
112
|
+
// For hex grids, each hex has at most 6 neighbors
|
|
113
|
+
// Limit search to reduce O(n²) to O(n)
|
|
114
|
+
const maxNeighbors = 10; // Safety margin for irregular grids
|
|
115
|
+
for (let j = 0; j < positions.length; j++) {
|
|
116
|
+
if (j === index)
|
|
117
|
+
continue;
|
|
118
|
+
const p2 = positions[j];
|
|
119
|
+
if (!p2)
|
|
120
|
+
continue;
|
|
121
|
+
const d = distanceBetween(pos, p2, bounds, isSpherical);
|
|
122
|
+
if (d <= threshold) {
|
|
123
|
+
out.push(j);
|
|
124
|
+
// Early exit if we found enough neighbors
|
|
125
|
+
if (out.length >= maxNeighbors)
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
cache.neighborMap.set(index, out);
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
console.error('[getNeighborsCached] Error computing neighbors:', e);
|
|
133
|
+
return [];
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
// Calculate UV bounds for a tile based on its grid position within a tilesX x tilesY grid
|
|
138
|
+
// V=1.0 represents the top of the texture in this codebase
|
|
139
|
+
function calculateUvBoundsFromGridPosition(gridCol, gridRow, tilesX, tilesY) {
|
|
140
|
+
const minU = gridCol / tilesX;
|
|
141
|
+
const maxU = (gridCol + 1) / tilesX;
|
|
142
|
+
// V=1 is top, so row 0 maps to top (maxV=1, minV=1-1/tilesY)
|
|
143
|
+
const minV = 1 - (gridRow + 1) / tilesY;
|
|
144
|
+
const maxV = 1 - gridRow / tilesY;
|
|
145
|
+
return [minU, minV, maxU, maxV];
|
|
146
|
+
}
|
|
147
|
+
function findConnectedComponents(indices, positions, hexRadius) {
|
|
148
|
+
// Immediate synchronous check - if this doesn't log, the function isn't being called or is blocked
|
|
149
|
+
const startMarker = performance.now();
|
|
150
|
+
console.log('[findConnectedComponents] FUNCTION ENTERED - indices.length=', indices.length, 'positions.length=', positions.length, 'hexRadius=', hexRadius, 'marker=', startMarker);
|
|
151
|
+
// Validate inputs immediately
|
|
152
|
+
if (!indices || !Array.isArray(indices)) {
|
|
153
|
+
console.error('[findConnectedComponents] Invalid indices:', indices);
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
if (!positions || !Array.isArray(positions)) {
|
|
157
|
+
console.error('[findConnectedComponents] Invalid positions:', positions);
|
|
158
|
+
return [];
|
|
159
|
+
}
|
|
160
|
+
if (typeof hexRadius !== 'number' || hexRadius <= 0) {
|
|
161
|
+
console.error('[findConnectedComponents] Invalid hexRadius:', hexRadius);
|
|
162
|
+
return [];
|
|
163
|
+
}
|
|
164
|
+
console.log('[findConnectedComponents] About to enter try block');
|
|
165
|
+
// Add immediate log after try block entry to confirm execution reaches here
|
|
166
|
+
let tryBlockEntered = false;
|
|
167
|
+
try {
|
|
168
|
+
tryBlockEntered = true;
|
|
169
|
+
console.log('[findConnectedComponents] ✅ TRY BLOCK ENTERED - marker=', performance.now() - startMarker, 'ms');
|
|
170
|
+
console.log('[findConnectedComponents] Inside try block - Starting with', indices.length, 'indices');
|
|
171
|
+
const set = new Set(indices);
|
|
172
|
+
const visited = new Set();
|
|
173
|
+
const comps = [];
|
|
174
|
+
let componentCount = 0;
|
|
175
|
+
for (const start of indices) {
|
|
176
|
+
if (visited.has(start))
|
|
177
|
+
continue;
|
|
178
|
+
componentCount++;
|
|
179
|
+
console.log('[findConnectedComponents] Starting component', componentCount, 'from index', start);
|
|
180
|
+
const q = [start];
|
|
181
|
+
visited.add(start);
|
|
182
|
+
const comp = [];
|
|
183
|
+
let iterations = 0;
|
|
184
|
+
const maxIterations = indices.length * 10; // Safety limit
|
|
185
|
+
while (q.length > 0) {
|
|
186
|
+
iterations++;
|
|
187
|
+
if (iterations > maxIterations) {
|
|
188
|
+
console.error('[findConnectedComponents] Safety limit reached! indices=', indices.length, 'component=', componentCount, 'iterations=', iterations);
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
if (iterations % 100 === 0) {
|
|
192
|
+
console.log('[findConnectedComponents] Component', componentCount, 'iteration', iterations, 'queue length', q.length);
|
|
193
|
+
}
|
|
194
|
+
const cur = q.shift();
|
|
195
|
+
if (cur === undefined || cur === null) {
|
|
196
|
+
console.error('[findConnectedComponents] Invalid cur value:', cur);
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
comp.push(cur);
|
|
200
|
+
try {
|
|
201
|
+
const neighbors = getNeighborsCached(cur, positions, hexRadius);
|
|
202
|
+
if (!Array.isArray(neighbors)) {
|
|
203
|
+
console.error('[findConnectedComponents] getNeighborsCached returned non-array:', typeof neighbors, neighbors);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
for (const n of neighbors) {
|
|
207
|
+
if (typeof n !== 'number' || isNaN(n)) {
|
|
208
|
+
console.error('[findConnectedComponents] Invalid neighbor index:', n, 'type:', typeof n);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (!visited.has(n) && set.has(n)) {
|
|
212
|
+
visited.add(n);
|
|
213
|
+
q.push(n);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
console.error('[findConnectedComponents] Error getting neighbors for index', cur, ':', e);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
console.log('[findConnectedComponents] Component', componentCount, 'complete:', comp.length, 'nodes,', iterations, 'iterations');
|
|
223
|
+
comps.push(comp);
|
|
224
|
+
}
|
|
225
|
+
console.log('[findConnectedComponents] Complete:', comps.length, 'components found');
|
|
226
|
+
const elapsed = performance.now() - startMarker;
|
|
227
|
+
console.log('[findConnectedComponents] ✅ RETURNING - elapsed=', elapsed, 'ms, components=', comps.length);
|
|
228
|
+
return comps;
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
const elapsed = performance.now() - startMarker;
|
|
232
|
+
console.error('[findConnectedComponents] ERROR after', elapsed, 'ms:', e, 'indices.length=', indices.length, 'tryBlockEntered=', tryBlockEntered);
|
|
233
|
+
// If we never entered the try block, something is seriously wrong
|
|
234
|
+
if (!tryBlockEntered) {
|
|
235
|
+
console.error('[findConnectedComponents] CRITICAL: Try block never entered! This suggests a hang before try block.');
|
|
236
|
+
}
|
|
237
|
+
throw e;
|
|
238
|
+
}
|
|
239
|
+
finally {
|
|
240
|
+
const elapsed = performance.now() - startMarker;
|
|
241
|
+
if (elapsed > 1000) {
|
|
242
|
+
console.warn('[findConnectedComponents] ⚠️ Function took', elapsed, 'ms to complete');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function calculatePhotoCentroids(infections, positions, hexRadius) {
|
|
247
|
+
try {
|
|
248
|
+
console.log('[calculatePhotoCentroids] Starting with', infections.size, 'infections');
|
|
249
|
+
const byPhoto = new Map();
|
|
250
|
+
for (const [idx, inf] of infections) {
|
|
251
|
+
if (!inf || !inf.photo)
|
|
252
|
+
continue;
|
|
253
|
+
const arr = byPhoto.get(inf.photo.id) || [];
|
|
254
|
+
arr.push(idx);
|
|
255
|
+
byPhoto.set(inf.photo.id, arr);
|
|
256
|
+
}
|
|
257
|
+
console.log('[calculatePhotoCentroids] Grouped into', byPhoto.size, 'photos');
|
|
258
|
+
const centroids = new Map();
|
|
259
|
+
let photoNum = 0;
|
|
260
|
+
for (const [photoId, inds] of byPhoto) {
|
|
261
|
+
photoNum++;
|
|
262
|
+
console.log('[calculatePhotoCentroids] Processing photo', photoNum, '/', byPhoto.size, 'photoId=', photoId, 'indices=', inds.length);
|
|
263
|
+
try {
|
|
264
|
+
console.log('[calculatePhotoCentroids] About to call findConnectedComponents with', inds.length, 'indices');
|
|
265
|
+
const callStartTime = performance.now();
|
|
266
|
+
let comps;
|
|
267
|
+
try {
|
|
268
|
+
// Add a pre-call validation to ensure we're not calling with invalid data
|
|
269
|
+
if (!inds || inds.length === 0) {
|
|
270
|
+
console.warn('[calculatePhotoCentroids] Empty indices array, skipping findConnectedComponents');
|
|
271
|
+
comps = [];
|
|
272
|
+
}
|
|
273
|
+
else if (!positions || positions.length === 0) {
|
|
274
|
+
console.warn('[calculatePhotoCentroids] Empty positions array, skipping findConnectedComponents');
|
|
275
|
+
comps = [];
|
|
276
|
+
}
|
|
277
|
+
else {
|
|
278
|
+
comps = findConnectedComponents(inds, positions, hexRadius);
|
|
279
|
+
const callElapsed = performance.now() - callStartTime;
|
|
280
|
+
console.log('[calculatePhotoCentroids] findConnectedComponents RETURNED with', comps.length, 'components after', callElapsed, 'ms');
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
const callElapsed = performance.now() - callStartTime;
|
|
285
|
+
console.error('[calculatePhotoCentroids] findConnectedComponents threw error after', callElapsed, 'ms:', e);
|
|
286
|
+
// Return empty components on error to allow evolution to continue
|
|
287
|
+
comps = [];
|
|
288
|
+
}
|
|
289
|
+
console.log('[calculatePhotoCentroids] findConnectedComponents returned', comps.length, 'components');
|
|
290
|
+
console.log('[calculatePhotoCentroids] Found', comps.length, 'components for photo', photoId);
|
|
291
|
+
const cs = [];
|
|
292
|
+
for (const comp of comps) {
|
|
293
|
+
let sx = 0, sy = 0;
|
|
294
|
+
for (const i of comp) {
|
|
295
|
+
const p = positions[i];
|
|
296
|
+
if (p) {
|
|
297
|
+
sx += p[0];
|
|
298
|
+
sy += p[1];
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (comp.length > 0)
|
|
302
|
+
cs.push([sx / comp.length, sy / comp.length]);
|
|
303
|
+
}
|
|
304
|
+
centroids.set(photoId, cs);
|
|
305
|
+
}
|
|
306
|
+
catch (e) {
|
|
307
|
+
console.error('[calculatePhotoCentroids] Error processing photo', photoId, ':', e);
|
|
308
|
+
centroids.set(photoId, []);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
console.log('[calculatePhotoCentroids] Completed, returning', centroids.size, 'photo centroids');
|
|
312
|
+
return centroids;
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
console.error('[calculatePhotoCentroids] FATAL ERROR:', e);
|
|
316
|
+
throw e;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
function calculateContiguity(indices, positions, hexRadius) {
|
|
320
|
+
const set = new Set(indices);
|
|
321
|
+
let total = 0;
|
|
322
|
+
for (const idx of indices)
|
|
323
|
+
for (const n of getNeighborsCached(idx, positions, hexRadius))
|
|
324
|
+
if (set.has(n))
|
|
325
|
+
total++;
|
|
326
|
+
return total;
|
|
327
|
+
}
|
|
328
|
+
// Assign cluster-aware grid positions so each hex in a cluster shows a different part of the image
|
|
329
|
+
// Returns tile centers for debug visualization when workerDebug.showTileCenters is enabled
|
|
330
|
+
function assignClusterGridPositions(infections, positions, hexRadius) {
|
|
331
|
+
var _a;
|
|
332
|
+
const debugCenters = [];
|
|
333
|
+
try {
|
|
334
|
+
console.log('[assignClusterGridPositions] Starting with', infections.size, 'infections');
|
|
335
|
+
// Group infections by photo
|
|
336
|
+
const byPhoto = new Map();
|
|
337
|
+
for (const [idx, inf] of infections) {
|
|
338
|
+
if (!inf || !inf.photo)
|
|
339
|
+
continue;
|
|
340
|
+
const arr = byPhoto.get(inf.photo.id) || [];
|
|
341
|
+
arr.push(idx);
|
|
342
|
+
byPhoto.set(inf.photo.id, arr);
|
|
343
|
+
}
|
|
344
|
+
console.log('[assignClusterGridPositions] Processing', byPhoto.size, 'unique photos');
|
|
345
|
+
// Cluster size analytics
|
|
346
|
+
let totalClusters = 0;
|
|
347
|
+
let clusterSizes = [];
|
|
348
|
+
// Process each photo's clusters
|
|
349
|
+
for (const [photoId, indices] of byPhoto) {
|
|
350
|
+
// Find connected components (separate clusters of the same photo)
|
|
351
|
+
const components = findConnectedComponents(indices, positions, hexRadius);
|
|
352
|
+
totalClusters += components.length;
|
|
353
|
+
for (const comp of components) {
|
|
354
|
+
if (comp && comp.length > 0)
|
|
355
|
+
clusterSizes.push(comp.length);
|
|
356
|
+
}
|
|
357
|
+
console.log('[assignClusterGridPositions] Photo', photoId.substring(0, 8), 'has', components.length, 'clusters, sizes:', components.map(c => c.length).join(','));
|
|
358
|
+
// Process each cluster separately
|
|
359
|
+
let clusterIndex = 0;
|
|
360
|
+
for (const cluster of components) {
|
|
361
|
+
if (!cluster || cluster.length === 0)
|
|
362
|
+
continue;
|
|
363
|
+
// Get the tiling configuration from the first infection in the cluster
|
|
364
|
+
const firstInf = infections.get(cluster[0]);
|
|
365
|
+
if (!firstInf)
|
|
366
|
+
continue;
|
|
367
|
+
// --- Hex lattice mapping fast-path -------------------------------------------------
|
|
368
|
+
// If enabled, derive tile coordinates directly from inferred axial-like row/col indices
|
|
369
|
+
// instead of using normalized bounding boxes + spatial nearest matching. This produces
|
|
370
|
+
// contiguous, parity-correct tiling where adjacent hexes map to adjacent UV tiles.
|
|
371
|
+
if (workerDebug.clusterHexLattice) {
|
|
372
|
+
try {
|
|
373
|
+
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
|
|
374
|
+
for (const idx of cluster) {
|
|
375
|
+
const p = positions[idx];
|
|
376
|
+
if (!p)
|
|
377
|
+
continue;
|
|
378
|
+
if (p[0] < minX)
|
|
379
|
+
minX = p[0];
|
|
380
|
+
if (p[0] > maxX)
|
|
381
|
+
maxX = p[0];
|
|
382
|
+
if (p[1] < minY)
|
|
383
|
+
minY = p[1];
|
|
384
|
+
if (p[1] > maxY)
|
|
385
|
+
maxY = p[1];
|
|
386
|
+
}
|
|
387
|
+
const clusterWidth = Math.max(0, maxX - minX);
|
|
388
|
+
const clusterHeight = Math.max(0, maxY - minY);
|
|
389
|
+
// Infer spacings from hexRadius (flat-top hex layout):
|
|
390
|
+
const horizSpacing = Math.sqrt(3) * hexRadius;
|
|
391
|
+
const vertSpacing = 1.5 * hexRadius;
|
|
392
|
+
// Build lattice coordinates (rowIndex, colIndex) respecting row parity offset.
|
|
393
|
+
const latticeCoords = new Map();
|
|
394
|
+
let minRow = Infinity, maxRow = -Infinity, minCol = Infinity, maxCol = -Infinity;
|
|
395
|
+
for (const id of cluster) {
|
|
396
|
+
const p = positions[id];
|
|
397
|
+
if (!p)
|
|
398
|
+
continue;
|
|
399
|
+
const rowF = (p[1] - minY) / vertSpacing;
|
|
400
|
+
const row = Math.round(rowF);
|
|
401
|
+
// Row parity offset: odd rows in generatePixelScreen are shifted +0.5 * horizSpacing.
|
|
402
|
+
const rowOffset = (row % 2 === 1) ? (horizSpacing * 0.5) : 0;
|
|
403
|
+
const colF = (p[0] - (minX + rowOffset)) / horizSpacing;
|
|
404
|
+
const col = Math.round(colF);
|
|
405
|
+
latticeCoords.set(id, { row, col });
|
|
406
|
+
if (row < minRow)
|
|
407
|
+
minRow = row;
|
|
408
|
+
if (row > maxRow)
|
|
409
|
+
maxRow = row;
|
|
410
|
+
if (col < minCol)
|
|
411
|
+
minCol = col;
|
|
412
|
+
if (col > maxCol)
|
|
413
|
+
maxCol = col;
|
|
414
|
+
}
|
|
415
|
+
const latticeRows = maxRow - minRow + 1;
|
|
416
|
+
const latticeCols = maxCol - minCol + 1;
|
|
417
|
+
// Initial tile grid matches lattice extents.
|
|
418
|
+
let tilesX = latticeCols;
|
|
419
|
+
let tilesY = latticeRows;
|
|
420
|
+
// If we have more hexes than lattice cells due to rounding collisions, expand.
|
|
421
|
+
const rawTileCount = tilesX * tilesY;
|
|
422
|
+
if (cluster.length > rawTileCount) {
|
|
423
|
+
// Simple expansion: grow columns while respecting max cap.
|
|
424
|
+
const MAX_TILES = typeof workerDebug.clusterMaxTiles === 'number' && workerDebug.clusterMaxTiles > 0 ? Math.floor(workerDebug.clusterMaxTiles) : 128;
|
|
425
|
+
while (tilesX * tilesY < cluster.length && tilesX * tilesY < MAX_TILES) {
|
|
426
|
+
if (tilesX <= tilesY)
|
|
427
|
+
tilesX++;
|
|
428
|
+
else
|
|
429
|
+
tilesY++;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
console.log('[assignClusterGridPositions][hex-lattice] cluster', photoId.substring(0, 8), 'size', cluster.length, 'latticeCols', latticeCols, 'latticeRows', latticeRows, 'tilesX', tilesX, 'tilesY', tilesY);
|
|
433
|
+
// Build optional serpentine ordering for assignment uniqueness (not strictly needed since lattice mapping is direct)
|
|
434
|
+
const serpentine = (workerDebug.clusterScanMode === 'serpentine');
|
|
435
|
+
// Assign each infection a gridPosition derived from lattice coordinates compressed into tile grid domain.
|
|
436
|
+
// Enhancement: compact gaps in each row for more contiguous image mapping
|
|
437
|
+
const compactGaps = workerDebug.clusterCompactGaps !== false;
|
|
438
|
+
// Build row-by-row column mapping to handle gaps
|
|
439
|
+
const rowColMap = new Map(); // row -> (oldCol -> newCol)
|
|
440
|
+
if (compactGaps) {
|
|
441
|
+
for (let row = minRow; row <= maxRow; row++) {
|
|
442
|
+
const colsInRow = Array.from(latticeCoords.entries())
|
|
443
|
+
.filter(([_, lc]) => lc.row === row)
|
|
444
|
+
.map(([_, lc]) => lc.col)
|
|
445
|
+
.sort((a, b) => a - b);
|
|
446
|
+
const colMap = new Map();
|
|
447
|
+
colsInRow.forEach((oldCol, newIdx) => {
|
|
448
|
+
colMap.set(oldCol, newIdx);
|
|
449
|
+
});
|
|
450
|
+
rowColMap.set(row, colMap);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// Collision detection: track which tiles are occupied
|
|
454
|
+
const tileOccupancy = new Map(); // "col,row" -> nodeId
|
|
455
|
+
const tileKey = (c, r) => `${c},${r}`;
|
|
456
|
+
for (const id of cluster) {
|
|
457
|
+
const inf = infections.get(id);
|
|
458
|
+
if (!inf)
|
|
459
|
+
continue;
|
|
460
|
+
const lc = latticeCoords.get(id);
|
|
461
|
+
if (!lc)
|
|
462
|
+
continue;
|
|
463
|
+
let gridCol = compactGaps && rowColMap.has(lc.row)
|
|
464
|
+
? ((_a = rowColMap.get(lc.row).get(lc.col)) !== null && _a !== void 0 ? _a : (lc.col - minCol))
|
|
465
|
+
: (lc.col - minCol);
|
|
466
|
+
let gridRow = lc.row - minRow;
|
|
467
|
+
if (serpentine && (gridRow % 2 === 1)) {
|
|
468
|
+
gridCol = (tilesX - 1) - gridCol;
|
|
469
|
+
}
|
|
470
|
+
// Clamp to valid range
|
|
471
|
+
if (gridCol < 0)
|
|
472
|
+
gridCol = 0;
|
|
473
|
+
if (gridCol >= tilesX)
|
|
474
|
+
gridCol = tilesX - 1;
|
|
475
|
+
if (gridRow < 0)
|
|
476
|
+
gridRow = 0;
|
|
477
|
+
if (gridRow >= tilesY)
|
|
478
|
+
gridRow = tilesY - 1;
|
|
479
|
+
// Collision resolution: if tile is occupied, find nearest free tile
|
|
480
|
+
const key = tileKey(gridCol, gridRow);
|
|
481
|
+
if (tileOccupancy.has(key)) {
|
|
482
|
+
const nodePos = positions[id];
|
|
483
|
+
let bestCol = gridCol, bestRow = gridRow;
|
|
484
|
+
let bestDist = Infinity;
|
|
485
|
+
// Search in expanding radius for free tile
|
|
486
|
+
for (let radius = 1; radius <= Math.max(tilesX, tilesY); radius++) {
|
|
487
|
+
let found = false;
|
|
488
|
+
for (let dc = -radius; dc <= radius; dc++) {
|
|
489
|
+
for (let dr = -radius; dr <= radius; dr++) {
|
|
490
|
+
if (Math.abs(dc) !== radius && Math.abs(dr) !== radius)
|
|
491
|
+
continue; // Only check perimeter
|
|
492
|
+
const testCol = gridCol + dc;
|
|
493
|
+
const testRow = gridRow + dr;
|
|
494
|
+
if (testCol < 0 || testCol >= tilesX || testRow < 0 || testRow >= tilesY)
|
|
495
|
+
continue;
|
|
496
|
+
const testKey = tileKey(testCol, testRow);
|
|
497
|
+
if (!tileOccupancy.has(testKey)) {
|
|
498
|
+
// Calculate distance to this tile's center
|
|
499
|
+
const tileU = (testCol + 0.5) / tilesX;
|
|
500
|
+
const tileV = (testRow + 0.5) / tilesY;
|
|
501
|
+
const tileCenterX = minX + tileU * clusterWidth;
|
|
502
|
+
const tileCenterY = minY + tileV * clusterHeight;
|
|
503
|
+
const dist = Math.hypot(nodePos[0] - tileCenterX, nodePos[1] - tileCenterY);
|
|
504
|
+
if (dist < bestDist) {
|
|
505
|
+
bestDist = dist;
|
|
506
|
+
bestCol = testCol;
|
|
507
|
+
bestRow = testRow;
|
|
508
|
+
found = true;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (found)
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
gridCol = bestCol;
|
|
517
|
+
gridRow = bestRow;
|
|
518
|
+
}
|
|
519
|
+
tileOccupancy.set(tileKey(gridCol, gridRow), id);
|
|
520
|
+
// Optionally support vertical anchor flip
|
|
521
|
+
if (workerDebug.clusterAnchor === 'max') {
|
|
522
|
+
gridRow = Math.max(0, tilesY - 1 - gridRow);
|
|
523
|
+
}
|
|
524
|
+
let uvBounds = calculateUvBoundsFromGridPosition(gridCol, gridRow, tilesX, tilesY);
|
|
525
|
+
const inset = Math.max(0, Math.min(0.49, Number(workerDebug.clusterUvInset) || 0));
|
|
526
|
+
if (inset > 0) {
|
|
527
|
+
const u0 = uvBounds[0], v0 = uvBounds[1], u1 = uvBounds[2], v1 = uvBounds[3];
|
|
528
|
+
const du = (u1 - u0) * inset;
|
|
529
|
+
const dv = (v1 - v0) * inset;
|
|
530
|
+
uvBounds = [u0 + du, v0 + dv, u1 - du, v1 - dv];
|
|
531
|
+
}
|
|
532
|
+
// Optional parity UV shift: shift odd rows horizontally by half a tile width in UV space.
|
|
533
|
+
// Enhanced: use precise hex geometry for sub-pixel accuracy
|
|
534
|
+
if (workerDebug.clusterParityUvShift && (gridRow % 2 === 1)) {
|
|
535
|
+
// Use actual lattice row parity from hex geometry, not tile row
|
|
536
|
+
const hexRowParity = lc.row % 2;
|
|
537
|
+
const shift = hexRowParity === 1 ? 0.5 / tilesX : 0;
|
|
538
|
+
let u0 = uvBounds[0] + shift;
|
|
539
|
+
let u1 = uvBounds[2] + shift;
|
|
540
|
+
// Wrap within [0,1]
|
|
541
|
+
if (u0 >= 1)
|
|
542
|
+
u0 -= 1;
|
|
543
|
+
if (u1 > 1)
|
|
544
|
+
u1 -= 1;
|
|
545
|
+
// Guard against pathological wrapping inversion (should not occur with shift<tileWidth)
|
|
546
|
+
if (u1 < u0) {
|
|
547
|
+
// If inverted due to wrapping edge case, clamp instead of wrap
|
|
548
|
+
u0 = Math.min(u0, 1 - (1 / tilesX));
|
|
549
|
+
u1 = Math.min(1, u0 + (1 / tilesX));
|
|
550
|
+
}
|
|
551
|
+
uvBounds = [u0, uvBounds[1], u1, uvBounds[3]];
|
|
552
|
+
}
|
|
553
|
+
infections.set(id, Object.assign(Object.assign({}, inf), { gridPosition: [gridCol, gridRow], uvBounds, tilesX, tilesY }));
|
|
554
|
+
}
|
|
555
|
+
// Advance cluster index and continue to next cluster (skip legacy logic)
|
|
556
|
+
clusterIndex++;
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
catch (e) {
|
|
560
|
+
console.warn('[assignClusterGridPositions][hex-lattice] failed, falling back to legacy path:', e);
|
|
561
|
+
// fall through to existing (spatial) logic
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// Find the bounding box of this cluster in grid space first
|
|
565
|
+
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
|
|
566
|
+
for (const idx of cluster) {
|
|
567
|
+
const pos = positions[idx];
|
|
568
|
+
if (!pos)
|
|
569
|
+
continue;
|
|
570
|
+
minX = Math.min(minX, pos[0]);
|
|
571
|
+
maxX = Math.max(maxX, pos[0]);
|
|
572
|
+
minY = Math.min(minY, pos[1]);
|
|
573
|
+
maxY = Math.max(maxY, pos[1]);
|
|
574
|
+
}
|
|
575
|
+
const clusterWidth = Math.max(0, maxX - minX);
|
|
576
|
+
const clusterHeight = Math.max(0, maxY - minY);
|
|
577
|
+
console.log('[assignClusterGridPositions] Cluster bounds:', {
|
|
578
|
+
photoId: photoId.substring(0, 8),
|
|
579
|
+
clusterIndex,
|
|
580
|
+
hexCount: cluster.length,
|
|
581
|
+
minX: minX.toFixed(2),
|
|
582
|
+
maxX: maxX.toFixed(2),
|
|
583
|
+
minY: minY.toFixed(2),
|
|
584
|
+
maxY: maxY.toFixed(2),
|
|
585
|
+
width: clusterWidth.toFixed(2),
|
|
586
|
+
height: clusterHeight.toFixed(2)
|
|
587
|
+
});
|
|
588
|
+
// Calculate optimal tilesX and tilesY based on cluster aspect ratio
|
|
589
|
+
// This ensures the tile grid matches the spatial layout of the cluster
|
|
590
|
+
const clusterAspect = clusterHeight > 0 ? clusterWidth / clusterHeight : 1.0;
|
|
591
|
+
const targetTileCount = 16; // Target ~16 tiles total for good image distribution
|
|
592
|
+
console.log('[assignClusterGridPositions] Cluster aspect:', clusterAspect.toFixed(3), '(width/height)');
|
|
593
|
+
let tilesX;
|
|
594
|
+
let tilesY;
|
|
595
|
+
if (cluster.length === 1) {
|
|
596
|
+
// Single hexagon: use 1x1
|
|
597
|
+
tilesX = 1;
|
|
598
|
+
tilesY = 1;
|
|
599
|
+
}
|
|
600
|
+
else if (workerDebug.clusterDynamicTiling !== false) {
|
|
601
|
+
// Dynamic tiling: match cluster aspect ratio
|
|
602
|
+
// sqrt(tilesX * tilesY) = sqrt(targetTileCount)
|
|
603
|
+
// tilesX / tilesY = clusterAspect
|
|
604
|
+
// => tilesX = clusterAspect * tilesY
|
|
605
|
+
// => clusterAspect * tilesY * tilesY = targetTileCount
|
|
606
|
+
// => tilesY = sqrt(targetTileCount / clusterAspect)
|
|
607
|
+
tilesY = Math.max(1, Math.round(Math.sqrt(targetTileCount / clusterAspect)));
|
|
608
|
+
tilesX = Math.max(1, Math.round(clusterAspect * tilesY));
|
|
609
|
+
// Clamp to reasonable range
|
|
610
|
+
tilesX = Math.max(1, Math.min(8, tilesX));
|
|
611
|
+
tilesY = Math.max(1, Math.min(8, tilesY));
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
// Fallback to fixed tiling from infection config
|
|
615
|
+
tilesX = Math.max(1, firstInf.tilesX || 4);
|
|
616
|
+
tilesY = Math.max(1, firstInf.tilesY || 4);
|
|
617
|
+
}
|
|
618
|
+
// If the cluster contains more hexes than tiles, expand the tile grid
|
|
619
|
+
// to avoid many hexes mapping to the same UV tile (which causes repeating
|
|
620
|
+
// image patches). Preserve the tile aspect ratio but scale up the total
|
|
621
|
+
// tile count to be at least cluster.length, clamped to a safe maximum.
|
|
622
|
+
try {
|
|
623
|
+
const currentTileCount = tilesX * tilesY;
|
|
624
|
+
const requiredTiles = Math.max(currentTileCount, cluster.length);
|
|
625
|
+
const MAX_TILES = typeof workerDebug.clusterMaxTiles === 'number' && workerDebug.clusterMaxTiles > 0 ? Math.max(1, Math.floor(workerDebug.clusterMaxTiles)) : 64;
|
|
626
|
+
const targetTiles = Math.min(requiredTiles, MAX_TILES);
|
|
627
|
+
if (targetTiles > currentTileCount) {
|
|
628
|
+
// preserve aspect ratio roughly: ratio = tilesX / tilesY
|
|
629
|
+
const ratio = tilesX / Math.max(1, tilesY);
|
|
630
|
+
// compute new tilesY from targetTiles and ratio
|
|
631
|
+
let newTilesY = Math.max(1, Math.round(Math.sqrt(targetTiles / Math.max(1e-9, ratio))));
|
|
632
|
+
let newTilesX = Math.max(1, Math.round(ratio * newTilesY));
|
|
633
|
+
// if rounding produced fewer tiles than needed, bump progressively
|
|
634
|
+
while (newTilesX * newTilesY < targetTiles) {
|
|
635
|
+
if (newTilesX <= newTilesY)
|
|
636
|
+
newTilesX++;
|
|
637
|
+
else
|
|
638
|
+
newTilesY++;
|
|
639
|
+
if (newTilesX * newTilesY >= MAX_TILES)
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
// clamp to reasonable maxima
|
|
643
|
+
newTilesX = Math.max(1, Math.min(16, newTilesX));
|
|
644
|
+
newTilesY = Math.max(1, Math.min(16, newTilesY));
|
|
645
|
+
tilesX = newTilesX;
|
|
646
|
+
tilesY = newTilesY;
|
|
647
|
+
console.log('[assignClusterGridPositions] Expanded tile grid to', tilesX, 'x', tilesY, '=', tilesX * tilesY, 'tiles');
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
catch (e) {
|
|
651
|
+
// if anything goes wrong, keep original tilesX/tilesY
|
|
652
|
+
}
|
|
653
|
+
console.log('[assignClusterGridPositions] Final tile dimensions:', tilesX, 'x', tilesY, '=', tilesX * tilesY, 'tiles for', cluster.length, 'hexes');
|
|
654
|
+
// Single-hex or degenerate clusters: assign a deterministic tile so single hexes don't all use [0,0]
|
|
655
|
+
if (cluster.length === 1 || clusterWidth < 1e-6 || clusterHeight < 1e-6) {
|
|
656
|
+
const idx = cluster[0];
|
|
657
|
+
const inf = infections.get(idx);
|
|
658
|
+
if (!inf)
|
|
659
|
+
continue;
|
|
660
|
+
// Deterministic hash from index to pick a tile
|
|
661
|
+
const h = (idx * 2654435761) >>> 0;
|
|
662
|
+
const gridCol = h % tilesX;
|
|
663
|
+
let gridRow = ((h >>> 8) % tilesY);
|
|
664
|
+
// If configured, allow anchoring to the bottom of the image (flip vertical tile index)
|
|
665
|
+
if (workerDebug.clusterAnchor === 'max') {
|
|
666
|
+
gridRow = Math.max(0, tilesY - 1 - gridRow);
|
|
667
|
+
}
|
|
668
|
+
const uvBounds = calculateUvBoundsFromGridPosition(gridCol, gridRow, tilesX, tilesY);
|
|
669
|
+
infections.set(idx, Object.assign(Object.assign({}, inf), { gridPosition: [gridCol, gridRow], uvBounds }));
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
// Optionally preserve aspect ratio when mapping cluster to tile grid
|
|
673
|
+
const preserveAspect = !!workerDebug.clusterPreserveAspect;
|
|
674
|
+
let normMinX = minX, normMinY = minY, normWidth = clusterWidth, normHeight = clusterHeight;
|
|
675
|
+
if (preserveAspect) {
|
|
676
|
+
const clusterAspect = clusterWidth / clusterHeight;
|
|
677
|
+
const tileAspect = tilesX / tilesY;
|
|
678
|
+
const fillMode = workerDebug.clusterFillMode || 'contain';
|
|
679
|
+
if (fillMode === 'contain') {
|
|
680
|
+
// current behavior: pad shorter dimension so the whole image fits (no cropping)
|
|
681
|
+
if (clusterAspect > tileAspect) {
|
|
682
|
+
const effectiveHeight = clusterWidth / tileAspect;
|
|
683
|
+
const pad = effectiveHeight - clusterHeight;
|
|
684
|
+
if (workerDebug.clusterAnchor === 'min') {
|
|
685
|
+
normMinY = minY;
|
|
686
|
+
}
|
|
687
|
+
else {
|
|
688
|
+
normMinY = minY - pad / 2;
|
|
689
|
+
}
|
|
690
|
+
normHeight = effectiveHeight;
|
|
691
|
+
}
|
|
692
|
+
else if (clusterAspect < tileAspect) {
|
|
693
|
+
const effectiveWidth = clusterHeight * tileAspect;
|
|
694
|
+
const pad = effectiveWidth - clusterWidth;
|
|
695
|
+
if (workerDebug.clusterAnchor === 'min') {
|
|
696
|
+
normMinX = minX;
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
normMinX = minX - pad / 2;
|
|
700
|
+
}
|
|
701
|
+
normWidth = effectiveWidth;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
else {
|
|
705
|
+
// 'cover' mode: scale so tile grid fully covers cluster bounds, allowing cropping
|
|
706
|
+
if (clusterAspect > tileAspect) {
|
|
707
|
+
// cluster is wider than tile grid: scale width down (crop left/right)
|
|
708
|
+
const effectiveWidth = clusterHeight * tileAspect;
|
|
709
|
+
const crop = clusterWidth - effectiveWidth;
|
|
710
|
+
if (workerDebug.clusterAnchor === 'min') {
|
|
711
|
+
normMinX = minX + crop; // crop from right
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
normMinX = minX + crop / 2;
|
|
715
|
+
}
|
|
716
|
+
normWidth = effectiveWidth;
|
|
717
|
+
}
|
|
718
|
+
else if (clusterAspect < tileAspect) {
|
|
719
|
+
// cluster is taller than tile grid: scale height down (crop top/bottom)
|
|
720
|
+
const effectiveHeight = clusterWidth / tileAspect;
|
|
721
|
+
const crop = clusterHeight - effectiveHeight;
|
|
722
|
+
if (workerDebug.clusterAnchor === 'min') {
|
|
723
|
+
normMinY = minY + crop;
|
|
724
|
+
}
|
|
725
|
+
else {
|
|
726
|
+
normMinY = minY + crop / 2;
|
|
727
|
+
}
|
|
728
|
+
normHeight = effectiveHeight;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
// Assign grid positions using preferred-quantized -> nearest-free strategy
|
|
733
|
+
// Guard tiny normalized dimensions to avoid degenerate quantization
|
|
734
|
+
// This produces contiguous tiling for clusters and avoids many hexes
|
|
735
|
+
// quantizing into the same UV tile.
|
|
736
|
+
try {
|
|
737
|
+
const clusterSet = new Set(cluster);
|
|
738
|
+
// Helper: tile bounds check
|
|
739
|
+
const inTileBounds = (c, r) => c >= 0 && c < tilesX && r >= 0 && r < tilesY;
|
|
740
|
+
// Tile occupancy map key
|
|
741
|
+
const tileKey = (c, r) => `${c},${r}`;
|
|
742
|
+
// Pre-allocate occupancy map and assignment map
|
|
743
|
+
const occupied = new Map();
|
|
744
|
+
const assignment = new Map();
|
|
745
|
+
// Choose origin by cluster centroid (closest hex to centroid)
|
|
746
|
+
let cx = 0, cy = 0;
|
|
747
|
+
for (const id of cluster) {
|
|
748
|
+
const p = positions[id];
|
|
749
|
+
cx += p[0];
|
|
750
|
+
cy += p[1];
|
|
751
|
+
}
|
|
752
|
+
cx /= cluster.length;
|
|
753
|
+
cy /= cluster.length;
|
|
754
|
+
let originIndex = cluster[0];
|
|
755
|
+
let bestD = Infinity;
|
|
756
|
+
for (const id of cluster) {
|
|
757
|
+
const p = positions[id];
|
|
758
|
+
const d = Math.hypot(p[0] - cx, p[1] - cy);
|
|
759
|
+
if (d < bestD) {
|
|
760
|
+
bestD = d;
|
|
761
|
+
originIndex = id;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
// Tile-first scanline assignment: build tiles in row-major order, then pick nearest unassigned node
|
|
765
|
+
const startCol = Math.floor(tilesX / 2);
|
|
766
|
+
const startRow = Math.floor(tilesY / 2);
|
|
767
|
+
// Ensure normalized dims aren't tiny
|
|
768
|
+
const MIN_NORM = 1e-6;
|
|
769
|
+
if (normWidth < MIN_NORM)
|
|
770
|
+
normWidth = MIN_NORM;
|
|
771
|
+
if (normHeight < MIN_NORM)
|
|
772
|
+
normHeight = MIN_NORM;
|
|
773
|
+
// Build tile list in row-major or serpentine order depending on config
|
|
774
|
+
const tiles = [];
|
|
775
|
+
const scanMode = (workerDebug.clusterScanMode || 'row');
|
|
776
|
+
for (let r = 0; r < tilesY; r++) {
|
|
777
|
+
if (scanMode === 'serpentine' && (r % 2 === 1)) {
|
|
778
|
+
// right-to-left on odd rows for serpentine
|
|
779
|
+
for (let c = tilesX - 1; c >= 0; c--)
|
|
780
|
+
tiles.push([c, r]);
|
|
781
|
+
}
|
|
782
|
+
else {
|
|
783
|
+
for (let c = 0; c < tilesX; c++)
|
|
784
|
+
tiles.push([c, r]);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
// Helper: compute tile center in cluster-space
|
|
788
|
+
const parityAware = !!workerDebug.clusterParityAware;
|
|
789
|
+
// compute physical horizontal offset for hex parity from cluster geometry
|
|
790
|
+
const hexSpacingFactor = Number(workerDebug.hexSpacing) || 1;
|
|
791
|
+
// initial fallback spacing based on configured hexRadius
|
|
792
|
+
let realHorizSpacing = Math.sqrt(3) * hexRadius * hexSpacingFactor;
|
|
793
|
+
// Try to infer horizontal spacing from actual node positions in the cluster.
|
|
794
|
+
// Group nodes into approximate rows and measure adjacent x-deltas.
|
|
795
|
+
try {
|
|
796
|
+
const rowBuckets = new Map();
|
|
797
|
+
for (const id of cluster) {
|
|
798
|
+
const p = positions[id];
|
|
799
|
+
if (!p)
|
|
800
|
+
continue;
|
|
801
|
+
// ratio across normalized height
|
|
802
|
+
const ratio = (p[1] - normMinY) / Math.max(1e-9, normHeight);
|
|
803
|
+
let r = Math.floor(ratio * tilesY);
|
|
804
|
+
r = Math.max(0, Math.min(tilesY - 1, r));
|
|
805
|
+
const arr = rowBuckets.get(r) || [];
|
|
806
|
+
arr.push(p[0]);
|
|
807
|
+
rowBuckets.set(r, arr);
|
|
808
|
+
}
|
|
809
|
+
const diffs = [];
|
|
810
|
+
for (const xs of rowBuckets.values()) {
|
|
811
|
+
if (!xs || xs.length < 2)
|
|
812
|
+
continue;
|
|
813
|
+
xs.sort((a, b) => a - b);
|
|
814
|
+
for (let i = 1; i < xs.length; i++)
|
|
815
|
+
diffs.push(xs[i] - xs[i - 1]);
|
|
816
|
+
}
|
|
817
|
+
if (diffs.length > 0) {
|
|
818
|
+
diffs.sort((a, b) => a - b);
|
|
819
|
+
const mid = Math.floor(diffs.length / 2);
|
|
820
|
+
realHorizSpacing = diffs.length % 2 === 1 ? diffs[mid] : ((diffs[mid - 1] + diffs[mid]) / 2);
|
|
821
|
+
if (!isFinite(realHorizSpacing) || realHorizSpacing <= 0)
|
|
822
|
+
realHorizSpacing = Math.sqrt(3) * hexRadius * hexSpacingFactor;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
catch (e) {
|
|
826
|
+
// fallback to default computed spacing
|
|
827
|
+
realHorizSpacing = Math.sqrt(3) * hexRadius * hexSpacingFactor;
|
|
828
|
+
}
|
|
829
|
+
// tile center calculation: simple regular grid, no parity offset
|
|
830
|
+
// The hex positions already have natural staggering, so tile centers should be regular
|
|
831
|
+
const tileCenter = (col, row) => {
|
|
832
|
+
const u = (col + 0.5) / tilesX;
|
|
833
|
+
const v = (row + 0.5) / tilesY;
|
|
834
|
+
const x = normMinX + u * normWidth;
|
|
835
|
+
const y = normMinY + v * normHeight;
|
|
836
|
+
return [x, y];
|
|
837
|
+
};
|
|
838
|
+
console.log('[assignClusterGridPositions] Normalized bounds for tiling:', {
|
|
839
|
+
normMinX: normMinX.toFixed(2),
|
|
840
|
+
normMinY: normMinY.toFixed(2),
|
|
841
|
+
normWidth: normWidth.toFixed(2),
|
|
842
|
+
normHeight: normHeight.toFixed(2),
|
|
843
|
+
preserveAspect,
|
|
844
|
+
fillMode: workerDebug.clusterFillMode
|
|
845
|
+
});
|
|
846
|
+
// SPATIAL assignment: each hex gets the tile whose center is spatially nearest
|
|
847
|
+
// This guarantees perfect alignment between hex positions and tile centers
|
|
848
|
+
// Build centers map first
|
|
849
|
+
const centers = [];
|
|
850
|
+
for (let r = 0; r < tilesY; r++)
|
|
851
|
+
for (let c = 0; c < tilesX; c++) {
|
|
852
|
+
const [x, y] = tileCenter(c, r);
|
|
853
|
+
centers.push({ t: [c, r], x, y });
|
|
854
|
+
}
|
|
855
|
+
// Optionally collect centers for debug visualization
|
|
856
|
+
if (workerDebug.showTileCenters) {
|
|
857
|
+
debugCenters.push({
|
|
858
|
+
photoId,
|
|
859
|
+
clusterIndex,
|
|
860
|
+
centers: centers.map(c => ({ x: c.x, y: c.y, col: c.t[0], row: c.t[1] }))
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
// Assign each hex to its nearest tile center (purely spatial)
|
|
864
|
+
// Log a few examples to verify the mapping
|
|
865
|
+
const assignmentSamples = [];
|
|
866
|
+
for (const nodeId of cluster) {
|
|
867
|
+
const nodePos = positions[nodeId];
|
|
868
|
+
if (!nodePos)
|
|
869
|
+
continue;
|
|
870
|
+
let nearestTile = centers[0].t;
|
|
871
|
+
let nearestDist = Infinity;
|
|
872
|
+
let nearestCenter = centers[0];
|
|
873
|
+
for (const c of centers) {
|
|
874
|
+
const dist = Math.hypot(nodePos[0] - c.x, nodePos[1] - c.y);
|
|
875
|
+
if (dist < nearestDist) {
|
|
876
|
+
nearestDist = dist;
|
|
877
|
+
nearestTile = c.t;
|
|
878
|
+
nearestCenter = c;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
assignment.set(nodeId, nearestTile);
|
|
882
|
+
occupied.set(tileKey(nearestTile[0], nearestTile[1]), true);
|
|
883
|
+
// Sample first few for debugging
|
|
884
|
+
if (assignmentSamples.length < 5) {
|
|
885
|
+
assignmentSamples.push({
|
|
886
|
+
nodeId,
|
|
887
|
+
nodeX: nodePos[0],
|
|
888
|
+
nodeY: nodePos[1],
|
|
889
|
+
tileCol: nearestTile[0],
|
|
890
|
+
tileRow: nearestTile[1],
|
|
891
|
+
centerX: nearestCenter.x,
|
|
892
|
+
centerY: nearestCenter.y,
|
|
893
|
+
dist: nearestDist
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
console.log('[assignClusterGridPositions] Spatially assigned', cluster.length, 'hexes to nearest tile centers');
|
|
898
|
+
console.log('[assignClusterGridPositions] Sample assignments:', assignmentSamples.map(s => `node#${s.nodeId} at (${s.nodeX.toFixed(1)},${s.nodeY.toFixed(1)}) → tile[${s.tileCol},${s.tileRow}] center(${s.centerX.toFixed(1)},${s.centerY.toFixed(1)}) dist=${s.dist.toFixed(1)}`).join('\n '));
|
|
899
|
+
// Optional: Neighborhood-aware refinement to reduce visual seams
|
|
900
|
+
// For each hex, check if its neighbors suggest a better tile assignment for visual continuity
|
|
901
|
+
if (workerDebug.clusterNeighborAware !== false) {
|
|
902
|
+
const maxIterations = 3; // Multiple passes to propagate improvements
|
|
903
|
+
for (let iter = 0; iter < maxIterations; iter++) {
|
|
904
|
+
let adjustments = 0;
|
|
905
|
+
for (const nodeId of cluster) {
|
|
906
|
+
const currentTile = assignment.get(nodeId);
|
|
907
|
+
if (!currentTile)
|
|
908
|
+
continue;
|
|
909
|
+
// Get neighbors within this cluster
|
|
910
|
+
const neighbors = getNeighborsCached(nodeId, positions, hexRadius);
|
|
911
|
+
const clusterNeighbors = neighbors.filter(n => clusterSet.has(n) && assignment.has(n));
|
|
912
|
+
if (clusterNeighbors.length === 0)
|
|
913
|
+
continue;
|
|
914
|
+
// Collect neighbor tiles and compute centroid
|
|
915
|
+
const neighborTiles = [];
|
|
916
|
+
for (const n of clusterNeighbors) {
|
|
917
|
+
const nt = assignment.get(n);
|
|
918
|
+
if (nt)
|
|
919
|
+
neighborTiles.push(nt);
|
|
920
|
+
}
|
|
921
|
+
if (neighborTiles.length === 0)
|
|
922
|
+
continue;
|
|
923
|
+
// Compute average neighbor tile position
|
|
924
|
+
let avgCol = 0, avgRow = 0;
|
|
925
|
+
for (const [c, r] of neighborTiles) {
|
|
926
|
+
avgCol += c;
|
|
927
|
+
avgRow += r;
|
|
928
|
+
}
|
|
929
|
+
avgCol /= neighborTiles.length;
|
|
930
|
+
avgRow /= neighborTiles.length;
|
|
931
|
+
// Find the tile closest to the neighbor average that's spatially near this node
|
|
932
|
+
const nodePos = positions[nodeId];
|
|
933
|
+
if (!nodePos)
|
|
934
|
+
continue;
|
|
935
|
+
let bestAlternative = null;
|
|
936
|
+
let bestScore = Infinity;
|
|
937
|
+
// Consider tiles in a local neighborhood around current tile
|
|
938
|
+
const searchRadius = 2;
|
|
939
|
+
for (let dc = -searchRadius; dc <= searchRadius; dc++) {
|
|
940
|
+
for (let dr = -searchRadius; dr <= searchRadius; dr++) {
|
|
941
|
+
const candidateCol = Math.max(0, Math.min(tilesX - 1, currentTile[0] + dc));
|
|
942
|
+
const candidateRow = Math.max(0, Math.min(tilesY - 1, currentTile[1] + dr));
|
|
943
|
+
const candidate = [candidateCol, candidateRow];
|
|
944
|
+
// Score: distance to neighbor tile average + spatial distance to tile center
|
|
945
|
+
const tileDist = Math.hypot(candidateCol - avgCol, candidateRow - avgRow);
|
|
946
|
+
const [cx, cy] = tileCenter(candidateCol, candidateRow);
|
|
947
|
+
const spatialDist = Math.hypot(nodePos[0] - cx, nodePos[1] - cy);
|
|
948
|
+
const score = tileDist * 0.7 + spatialDist * 0.3;
|
|
949
|
+
if (score < bestScore) {
|
|
950
|
+
bestScore = score;
|
|
951
|
+
bestAlternative = candidate;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
// If we found a better tile and it's different from current, update
|
|
956
|
+
if (bestAlternative && (bestAlternative[0] !== currentTile[0] || bestAlternative[1] !== currentTile[1])) {
|
|
957
|
+
assignment.set(nodeId, bestAlternative);
|
|
958
|
+
adjustments++;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
if (adjustments === 0)
|
|
962
|
+
break; // Converged
|
|
963
|
+
console.log('[assignClusterGridPositions] Neighbor-aware refinement iteration', iter + 1, ':', adjustments, 'adjustments');
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
// Finally write assignments back into infections with UV bounds/inset
|
|
967
|
+
const inset = Math.max(0, Math.min(0.49, Number(workerDebug.clusterUvInset) || 0));
|
|
968
|
+
for (const id of cluster) {
|
|
969
|
+
const inf = infections.get(id);
|
|
970
|
+
if (!inf)
|
|
971
|
+
continue;
|
|
972
|
+
let assignedTile = assignment.get(id) || [0, 0];
|
|
973
|
+
// Support bottom anchoring: flip the vertical tile index when 'max' is configured
|
|
974
|
+
if (workerDebug.clusterAnchor === 'max') {
|
|
975
|
+
assignedTile = [assignedTile[0], Math.max(0, tilesY - 1 - assignedTile[1])];
|
|
976
|
+
}
|
|
977
|
+
let uvBounds = calculateUvBoundsFromGridPosition(assignedTile[0], assignedTile[1], tilesX, tilesY);
|
|
978
|
+
if (inset > 0) {
|
|
979
|
+
const u0 = uvBounds[0], v0 = uvBounds[1], u1 = uvBounds[2], v1 = uvBounds[3];
|
|
980
|
+
const du = (u1 - u0) * inset;
|
|
981
|
+
const dv = (v1 - v0) * inset;
|
|
982
|
+
uvBounds = [u0 + du, v0 + dv, u1 - du, v1 - dv];
|
|
983
|
+
}
|
|
984
|
+
infections.set(id, Object.assign(Object.assign({}, inf), { gridPosition: [assignedTile[0], assignedTile[1]], uvBounds, tilesX, tilesY }));
|
|
985
|
+
}
|
|
986
|
+
console.log('[assignClusterGridPositions] Assigned grid positions to', cluster.length, 'hexes in cluster (BFS)');
|
|
987
|
+
}
|
|
988
|
+
catch (e) {
|
|
989
|
+
console.error('[assignClusterGridPositions] BFS assignment failed, falling back to quantization', e);
|
|
990
|
+
// fallback: leave previous behavior (quantization) to avoid breaking
|
|
991
|
+
}
|
|
992
|
+
clusterIndex++;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
// Log cluster statistics
|
|
996
|
+
if (clusterSizes.length > 0) {
|
|
997
|
+
clusterSizes.sort((a, b) => b - a); // descending
|
|
998
|
+
const avgSize = clusterSizes.reduce((sum, s) => sum + s, 0) / clusterSizes.length;
|
|
999
|
+
const medianSize = clusterSizes[Math.floor(clusterSizes.length / 2)];
|
|
1000
|
+
const maxSize = clusterSizes[0];
|
|
1001
|
+
const smallClusters = clusterSizes.filter(s => s <= 3).length;
|
|
1002
|
+
console.log('[assignClusterGridPositions] CLUSTER STATS: total=', totalClusters, 'avg=', avgSize.toFixed(1), 'median=', medianSize, 'max=', maxSize, 'small(≤3)=', smallClusters, '/', totalClusters, '(', (100 * smallClusters / totalClusters).toFixed(0), '%)');
|
|
1003
|
+
}
|
|
1004
|
+
console.log('[assignClusterGridPositions] Complete');
|
|
1005
|
+
}
|
|
1006
|
+
catch (e) {
|
|
1007
|
+
console.error('[assignClusterGridPositions] Error:', e);
|
|
1008
|
+
}
|
|
1009
|
+
return debugCenters;
|
|
1010
|
+
}
|
|
1011
|
+
function postOptimizationMerge(infections, positions, hexRadius, debug = false) {
|
|
1012
|
+
var _a;
|
|
1013
|
+
try {
|
|
1014
|
+
if (!workerDebug || !workerDebug.enableMerges) {
|
|
1015
|
+
if (debug && workerDebug.mergeLogs)
|
|
1016
|
+
console.log('[merge] disabled');
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
const threshold = typeof workerDebug.mergeSmallComponentsThreshold === 'number' ? workerDebug.mergeSmallComponentsThreshold : 3;
|
|
1020
|
+
const byPhoto = new Map();
|
|
1021
|
+
for (const [idx, inf] of infections) {
|
|
1022
|
+
const arr = byPhoto.get(inf.photo.id) || [];
|
|
1023
|
+
arr.push(idx);
|
|
1024
|
+
byPhoto.set(inf.photo.id, arr);
|
|
1025
|
+
}
|
|
1026
|
+
let merges = 0;
|
|
1027
|
+
for (const [photoId, inds] of byPhoto) {
|
|
1028
|
+
const comps = findConnectedComponents(inds, positions, hexRadius);
|
|
1029
|
+
const small = comps.filter(c => c.length > 0 && c.length <= threshold);
|
|
1030
|
+
const big = comps.filter(c => c.length > threshold);
|
|
1031
|
+
if (small.length === 0 || big.length === 0)
|
|
1032
|
+
continue;
|
|
1033
|
+
const bounds = getGridBounds(positions);
|
|
1034
|
+
for (const s of small) {
|
|
1035
|
+
let best = null;
|
|
1036
|
+
let bestD = Infinity;
|
|
1037
|
+
for (const b of big) {
|
|
1038
|
+
let sx = 0, sy = 0, bx = 0, by = 0;
|
|
1039
|
+
for (const i of s) {
|
|
1040
|
+
const p = positions[i];
|
|
1041
|
+
if (p) {
|
|
1042
|
+
sx += p[0];
|
|
1043
|
+
sy += p[1];
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
for (const i of b) {
|
|
1047
|
+
const p = positions[i];
|
|
1048
|
+
if (p) {
|
|
1049
|
+
bx += p[0];
|
|
1050
|
+
by += p[1];
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const scx = sx / s.length, scy = sy / s.length, bcx = bx / b.length, bcy = by / b.length;
|
|
1054
|
+
const dx = Math.abs(scx - bcx);
|
|
1055
|
+
const dy = Math.abs(scy - bcy);
|
|
1056
|
+
let effDx = dx;
|
|
1057
|
+
let effDy = dy;
|
|
1058
|
+
if (cache.isSpherical && bounds.width > 0 && bounds.height > 0) {
|
|
1059
|
+
if (effDx > bounds.width / 2)
|
|
1060
|
+
effDx = bounds.width - effDx;
|
|
1061
|
+
if (effDy > bounds.height / 2)
|
|
1062
|
+
effDy = bounds.height - effDy;
|
|
1063
|
+
}
|
|
1064
|
+
const d = Math.sqrt(effDx * effDx + effDy * effDy);
|
|
1065
|
+
if (d < bestD) {
|
|
1066
|
+
bestD = d;
|
|
1067
|
+
best = b;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
if (!best)
|
|
1071
|
+
continue;
|
|
1072
|
+
const recipientId = (_a = infections.get(best[0])) === null || _a === void 0 ? void 0 : _a.photo.id;
|
|
1073
|
+
if (!recipientId)
|
|
1074
|
+
continue;
|
|
1075
|
+
const before = calculateContiguity(best, positions, hexRadius);
|
|
1076
|
+
const after = calculateContiguity([...best, ...s], positions, hexRadius);
|
|
1077
|
+
if (after > before + 1) {
|
|
1078
|
+
for (const idx of s) {
|
|
1079
|
+
const inf = infections.get(idx);
|
|
1080
|
+
if (!inf)
|
|
1081
|
+
continue;
|
|
1082
|
+
infections.set(idx, Object.assign(Object.assign({}, inf), { photo: infections.get(best[0]).photo }));
|
|
1083
|
+
}
|
|
1084
|
+
merges++;
|
|
1085
|
+
if (debug && workerDebug.mergeLogs)
|
|
1086
|
+
console.log(`[merge] moved ${s.length} -> ${recipientId}`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
catch (e) {
|
|
1092
|
+
if (debug)
|
|
1093
|
+
console.warn('[merge] failed', e);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
function normalizePrevState(prevState) {
|
|
1097
|
+
try {
|
|
1098
|
+
if (!prevState)
|
|
1099
|
+
return { infections: new Map(), availableIndices: [] };
|
|
1100
|
+
let infectionsMap;
|
|
1101
|
+
if (prevState.infections instanceof Map) {
|
|
1102
|
+
infectionsMap = prevState.infections;
|
|
1103
|
+
}
|
|
1104
|
+
else if (Array.isArray(prevState.infections)) {
|
|
1105
|
+
try {
|
|
1106
|
+
infectionsMap = new Map(prevState.infections);
|
|
1107
|
+
}
|
|
1108
|
+
catch (e) {
|
|
1109
|
+
infectionsMap = new Map();
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
else if (typeof prevState.infections === 'object' && prevState.infections !== null && typeof prevState.infections.entries === 'function') {
|
|
1113
|
+
try {
|
|
1114
|
+
infectionsMap = new Map(Array.from(prevState.infections.entries()));
|
|
1115
|
+
}
|
|
1116
|
+
catch (e) {
|
|
1117
|
+
infectionsMap = new Map();
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
else {
|
|
1121
|
+
infectionsMap = new Map();
|
|
1122
|
+
}
|
|
1123
|
+
const available = Array.isArray(prevState.availableIndices) ? prevState.availableIndices : [];
|
|
1124
|
+
return { infections: infectionsMap, availableIndices: available, generation: prevState.generation };
|
|
1125
|
+
}
|
|
1126
|
+
catch (e) {
|
|
1127
|
+
safePostError(e);
|
|
1128
|
+
return { infections: new Map(), availableIndices: [] };
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function evolveInfectionSystem(prevState, positions, photos, hexRadius, currentTime, debug = false) {
|
|
1132
|
+
var _a;
|
|
1133
|
+
try {
|
|
1134
|
+
console.log('[evolve] Step 1: Validating positions...');
|
|
1135
|
+
if (!positions || positions.length === 0) {
|
|
1136
|
+
safePostError(new Error('positions required for evolve'));
|
|
1137
|
+
return null;
|
|
1138
|
+
}
|
|
1139
|
+
console.log('[evolve] Step 2: Normalizing state...');
|
|
1140
|
+
const normalized = normalizePrevState(prevState);
|
|
1141
|
+
const infectionsMap = normalized.infections;
|
|
1142
|
+
const availableSet = new Set(Array.isArray(normalized.availableIndices) ? normalized.availableIndices : []);
|
|
1143
|
+
console.log('[evolve] Step 3: Cleaning infections...');
|
|
1144
|
+
for (const [idx, inf] of infectionsMap) {
|
|
1145
|
+
if (!inf || !inf.photo) {
|
|
1146
|
+
infectionsMap.delete(idx);
|
|
1147
|
+
availableSet.add(idx);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
console.log('[evolve] Step 4: Calculating centroids...');
|
|
1151
|
+
const centroids = calculatePhotoCentroids(infectionsMap, positions, hexRadius);
|
|
1152
|
+
console.log('[evolve] Step 5: Creating new state copies...');
|
|
1153
|
+
const newInfections = new Map(infectionsMap);
|
|
1154
|
+
const newAvailable = new Set(availableSet);
|
|
1155
|
+
const generation = (prevState && typeof prevState.generation === 'number') ? prevState.generation + 1 : 0;
|
|
1156
|
+
console.log('[evolve] Step 6: Growth step - processing', infectionsMap.size, 'infections...');
|
|
1157
|
+
// Skip growth step if we have no infections or no photos
|
|
1158
|
+
if (infectionsMap.size === 0 || photos.length === 0) {
|
|
1159
|
+
console.log('[evolve] Skipping growth - no infections or no photos');
|
|
1160
|
+
}
|
|
1161
|
+
else {
|
|
1162
|
+
// Cell death step: allow fully surrounded cells to die and respawn for optimization
|
|
1163
|
+
if (workerDebug.enableCellDeath && typeof workerDebug.cellDeathProbability === 'number') {
|
|
1164
|
+
// Apply annealing rate to base death probability
|
|
1165
|
+
const annealingRate = typeof workerDebug.annealingRate === 'number' && workerDebug.annealingRate > 0
|
|
1166
|
+
? workerDebug.annealingRate
|
|
1167
|
+
: 1.0;
|
|
1168
|
+
const baseDeathProb = Math.max(0, Math.min(1, workerDebug.cellDeathProbability * annealingRate));
|
|
1169
|
+
const mutationEnabled = !!workerDebug.enableMutation;
|
|
1170
|
+
const baseMutationProb = mutationEnabled && typeof workerDebug.mutationProbability === 'number'
|
|
1171
|
+
? Math.max(0, Math.min(1, workerDebug.mutationProbability))
|
|
1172
|
+
: 0;
|
|
1173
|
+
let deathCount = 0;
|
|
1174
|
+
let mutationCount = 0;
|
|
1175
|
+
let invaderExpulsions = 0;
|
|
1176
|
+
// Calculate cluster sizes for mutation scaling
|
|
1177
|
+
const clusterSizes = new Map();
|
|
1178
|
+
for (const [_, inf] of infectionsMap) {
|
|
1179
|
+
clusterSizes.set(inf.photo.id, (clusterSizes.get(inf.photo.id) || 0) + 1);
|
|
1180
|
+
}
|
|
1181
|
+
for (const [idx, inf] of infectionsMap) {
|
|
1182
|
+
const neighbors = getNeighborsCached(idx, positions, hexRadius);
|
|
1183
|
+
const totalNeighbors = neighbors.length;
|
|
1184
|
+
// Count neighbors with the same photo (affinity)
|
|
1185
|
+
const samePhotoNeighbors = neighbors.filter(n => {
|
|
1186
|
+
const nInf = newInfections.get(n);
|
|
1187
|
+
return nInf && nInf.photo.id === inf.photo.id;
|
|
1188
|
+
});
|
|
1189
|
+
// Calculate affinity ratio: 1.0 = all same photo, 0.0 = none same photo
|
|
1190
|
+
const affinityRatio = totalNeighbors > 0 ? samePhotoNeighbors.length / totalNeighbors : 0;
|
|
1191
|
+
// Count hostile (different photo) neighbors and diversity
|
|
1192
|
+
const hostileNeighbors = totalNeighbors - samePhotoNeighbors.length;
|
|
1193
|
+
const hostileRatio = totalNeighbors > 0 ? hostileNeighbors / totalNeighbors : 0;
|
|
1194
|
+
// Calculate diversity: how many unique different photo types surround this cell
|
|
1195
|
+
const uniqueHostilePhotos = new Set();
|
|
1196
|
+
for (const n of neighbors) {
|
|
1197
|
+
const nInf = newInfections.get(n);
|
|
1198
|
+
if (nInf && nInf.photo.id !== inf.photo.id) {
|
|
1199
|
+
uniqueHostilePhotos.add(nInf.photo.id);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
const diversityCount = uniqueHostilePhotos.size;
|
|
1203
|
+
const maxDiversity = 6; // hex grid max neighbors
|
|
1204
|
+
const diversityRatio = diversityCount / maxDiversity;
|
|
1205
|
+
// Affinity-adjusted death probability with boundary pressure:
|
|
1206
|
+
// - High affinity (well-integrated) = low death rate
|
|
1207
|
+
// - Low affinity (invader) = high death rate
|
|
1208
|
+
// - Partial hostile neighbors = MUCH higher death rate (boundary warfare)
|
|
1209
|
+
// - Solitary cells = VERY high death rate
|
|
1210
|
+
//
|
|
1211
|
+
// Base formula: deathProb = baseDeathProb * (1 - affinityRatio)^2
|
|
1212
|
+
// Boundary pressure: if 1-5 hostile neighbors, apply exponential penalty
|
|
1213
|
+
let affinityPenalty = Math.pow(1 - affinityRatio, 2);
|
|
1214
|
+
// Solitary cell penalty: cells with 0-1 same neighbors are extremely vulnerable
|
|
1215
|
+
// Diversity amplifies this: being alone among many different photos is worst case
|
|
1216
|
+
if (samePhotoNeighbors.length <= 1) {
|
|
1217
|
+
// Base 10x penalty, increased by diversity: 2-6 different neighbors = 1.5x-3x additional multiplier
|
|
1218
|
+
// Formula: 10 × (1 + diversityRatio × 2)
|
|
1219
|
+
// 1 hostile type: 10x penalty
|
|
1220
|
+
// 3 hostile types (50% diversity): 20x penalty
|
|
1221
|
+
// 6 hostile types (100% diversity): 30x penalty
|
|
1222
|
+
const diversityPenalty = 1 + diversityRatio * 2;
|
|
1223
|
+
affinityPenalty *= (10 * diversityPenalty);
|
|
1224
|
+
}
|
|
1225
|
+
// Boundary warfare multiplier: cells partially surrounded by enemies are in danger
|
|
1226
|
+
if (hostileNeighbors > 0 && hostileNeighbors < totalNeighbors) {
|
|
1227
|
+
// Peak danger at 50% hostile (3/6 neighbors): apply up to 4x multiplier
|
|
1228
|
+
// Formula: 1 + 3 * sin(hostileRatio * π) creates a bell curve peaking at 0.5
|
|
1229
|
+
const boundaryPressure = 1 + 3 * Math.sin(hostileRatio * Math.PI);
|
|
1230
|
+
affinityPenalty *= boundaryPressure;
|
|
1231
|
+
}
|
|
1232
|
+
const adjustedDeathProb = Math.min(1, baseDeathProb * affinityPenalty);
|
|
1233
|
+
// Calculate mutation probability based on cluster size and virility
|
|
1234
|
+
// Larger, more popular clusters spawn more mutations
|
|
1235
|
+
let mutationProb = baseMutationProb;
|
|
1236
|
+
if (mutationEnabled && photos.length > 1) {
|
|
1237
|
+
const clusterSize = clusterSizes.get(inf.photo.id) || 1;
|
|
1238
|
+
const velocity = typeof inf.photo.velocity === 'number' ? inf.photo.velocity : 0;
|
|
1239
|
+
// Cluster size multiplier: larger clusters spawn more mutations (1-100 cells → 1x-10x)
|
|
1240
|
+
const clusterMultiplier = Math.min(10, Math.log10(clusterSize + 1) + 1);
|
|
1241
|
+
// Virility multiplier: popular photos spawn more mutations (0-100 velocity → 1x-3x)
|
|
1242
|
+
const virilityMultiplier = 1 + (Math.min(100, Math.max(0, velocity)) / 100) * 2;
|
|
1243
|
+
// Combined mutation rate
|
|
1244
|
+
mutationProb = Math.min(1, baseMutationProb * clusterMultiplier * virilityMultiplier);
|
|
1245
|
+
}
|
|
1246
|
+
// Only consider cells with at least some neighbors (avoid isolated cells)
|
|
1247
|
+
if (totalNeighbors >= 1 && Math.random() < adjustedDeathProb) {
|
|
1248
|
+
const isInvader = affinityRatio < 0.5; // Less than half neighbors are same photo
|
|
1249
|
+
// Check for mutation: respawn as a different photo instead of just dying
|
|
1250
|
+
if (mutationEnabled && Math.random() < mutationProb && photos.length > 1) {
|
|
1251
|
+
// Pick a random photo from the pool that's different from current
|
|
1252
|
+
const otherPhotos = photos.filter(p => p.id !== inf.photo.id);
|
|
1253
|
+
if (otherPhotos.length > 0) {
|
|
1254
|
+
const newPhoto = otherPhotos[Math.floor(Math.random() * otherPhotos.length)];
|
|
1255
|
+
const tilesX = 4;
|
|
1256
|
+
const tilesY = 4;
|
|
1257
|
+
const uvBounds = calculateUvBoundsFromGridPosition(0, 0, tilesX, tilesY);
|
|
1258
|
+
// Mutate: replace with new photo instead of dying
|
|
1259
|
+
newInfections.set(idx, {
|
|
1260
|
+
photo: newPhoto,
|
|
1261
|
+
gridPosition: [0, 0],
|
|
1262
|
+
infectionTime: currentTime,
|
|
1263
|
+
generation,
|
|
1264
|
+
uvBounds: uvBounds,
|
|
1265
|
+
scale: 0.4,
|
|
1266
|
+
growthRate: 0.08,
|
|
1267
|
+
tilesX: tilesX,
|
|
1268
|
+
tilesY: tilesY
|
|
1269
|
+
});
|
|
1270
|
+
mutationCount++;
|
|
1271
|
+
}
|
|
1272
|
+
else {
|
|
1273
|
+
// No other photos available, just die normally
|
|
1274
|
+
newInfections.delete(idx);
|
|
1275
|
+
newAvailable.add(idx);
|
|
1276
|
+
deathCount++;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
else {
|
|
1280
|
+
// Normal death: remove and make available for respawn
|
|
1281
|
+
newInfections.delete(idx);
|
|
1282
|
+
newAvailable.add(idx);
|
|
1283
|
+
deathCount++;
|
|
1284
|
+
if (isInvader)
|
|
1285
|
+
invaderExpulsions++;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
if (deathCount > 0 || mutationCount > 0 || invaderExpulsions > 0) {
|
|
1290
|
+
console.log('[evolve] Cell death: removed', deathCount, 'cells (', invaderExpulsions, 'invaders expelled), mutated', mutationCount, 'cells');
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
// Growth step: prefer neighbors that increase contiguity and are closer to centroids
|
|
1294
|
+
let growthIterations = 0;
|
|
1295
|
+
for (const [idx, inf] of infectionsMap) {
|
|
1296
|
+
growthIterations++;
|
|
1297
|
+
if (growthIterations % 10 === 0)
|
|
1298
|
+
console.log('[evolve] Growth iteration', growthIterations, '/', infectionsMap.size);
|
|
1299
|
+
const neighbors = getNeighborsCached(idx, positions, hexRadius);
|
|
1300
|
+
for (const n of neighbors) {
|
|
1301
|
+
if (!newAvailable.has(n))
|
|
1302
|
+
continue;
|
|
1303
|
+
let base = 0.5; // BOOSTED from 0.3 to encourage more aggressive growth
|
|
1304
|
+
const sameNeighbors = getNeighborsCached(n, positions, hexRadius).filter(x => newInfections.has(x) && newInfections.get(x).photo.id === inf.photo.id).length;
|
|
1305
|
+
if (sameNeighbors >= 2)
|
|
1306
|
+
base = 0.95;
|
|
1307
|
+
else if (sameNeighbors === 1)
|
|
1308
|
+
base = 0.75; // BOOSTED to favor contiguous growth
|
|
1309
|
+
// Virility boost: photos with higher velocity (upvotes/engagement) grow faster
|
|
1310
|
+
if (workerDebug.enableVirilityBoost && typeof inf.photo.velocity === 'number' && inf.photo.velocity > 0) {
|
|
1311
|
+
const virilityMult = typeof workerDebug.virilityMultiplier === 'number' ? workerDebug.virilityMultiplier : 1.0;
|
|
1312
|
+
// Normalize velocity to a 0-1 range (assuming velocity is already normalized or 0-100)
|
|
1313
|
+
// Then apply as a percentage boost: velocity=100 -> 100% boost (2x), velocity=50 -> 50% boost (1.5x)
|
|
1314
|
+
const normalizedVelocity = Math.min(1, Math.max(0, inf.photo.velocity / 100));
|
|
1315
|
+
const virilityBoost = 1 + (normalizedVelocity * virilityMult);
|
|
1316
|
+
base *= virilityBoost;
|
|
1317
|
+
}
|
|
1318
|
+
// Centroid cohesion bias
|
|
1319
|
+
try {
|
|
1320
|
+
const cList = centroids.get(inf.photo.id) || [];
|
|
1321
|
+
if (cList.length > 0) {
|
|
1322
|
+
const bounds = getGridBounds(positions);
|
|
1323
|
+
let minD = Infinity;
|
|
1324
|
+
const p = positions[n];
|
|
1325
|
+
for (const c of cList) {
|
|
1326
|
+
const dx = Math.abs(p[0] - c[0]);
|
|
1327
|
+
const dy = Math.abs(p[1] - c[1]);
|
|
1328
|
+
let effDx = dx;
|
|
1329
|
+
let effDy = dy;
|
|
1330
|
+
if (cache.isSpherical && bounds.width > 0 && bounds.height > 0) {
|
|
1331
|
+
if (effDx > bounds.width / 2)
|
|
1332
|
+
effDx = bounds.width - effDx;
|
|
1333
|
+
if (effDy > bounds.height / 2)
|
|
1334
|
+
effDy = bounds.height - effDy;
|
|
1335
|
+
}
|
|
1336
|
+
const d = Math.sqrt(effDx * effDx + effDy * effDy);
|
|
1337
|
+
if (d < minD)
|
|
1338
|
+
minD = d;
|
|
1339
|
+
}
|
|
1340
|
+
const radius = Math.max(1, hexRadius * 3);
|
|
1341
|
+
const distFactor = Math.max(0, Math.min(1, 1 - (minD / radius)));
|
|
1342
|
+
const boost = typeof workerDebug.cohesionBoost === 'number' ? workerDebug.cohesionBoost : 0.6;
|
|
1343
|
+
base *= (1 + distFactor * boost);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
catch (e) {
|
|
1347
|
+
if (debug)
|
|
1348
|
+
console.warn('cohesion calc failed', e);
|
|
1349
|
+
}
|
|
1350
|
+
if (Math.random() < Math.min(0.999, base)) {
|
|
1351
|
+
const tilesX = inf.tilesX || 4;
|
|
1352
|
+
const tilesY = inf.tilesY || 4;
|
|
1353
|
+
const uvBounds = calculateUvBoundsFromGridPosition(0, 0, tilesX, tilesY);
|
|
1354
|
+
newInfections.set(n, { photo: inf.photo, gridPosition: [0, 0], infectionTime: currentTime, generation, uvBounds: uvBounds, scale: 0.4, growthRate: inf.growthRate || 0.08, tilesX: tilesX, tilesY: tilesY });
|
|
1355
|
+
newAvailable.delete(n);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
console.log('[evolve] Step 7: Deterministic fill - processing', newAvailable.size, 'available positions...');
|
|
1361
|
+
// Skip deterministic fill if we have no photos or no existing infections to base decisions on
|
|
1362
|
+
if (photos.length === 0 || newInfections.size === 0) {
|
|
1363
|
+
console.log('[evolve] Skipping deterministic fill - no photos or no infections');
|
|
1364
|
+
}
|
|
1365
|
+
else {
|
|
1366
|
+
// Deterministic fill for holes with >=2 same-photo neighbors
|
|
1367
|
+
let fillIterations = 0;
|
|
1368
|
+
for (const a of Array.from(newAvailable)) {
|
|
1369
|
+
fillIterations++;
|
|
1370
|
+
if (fillIterations % 50 === 0)
|
|
1371
|
+
console.log('[evolve] Fill iteration', fillIterations, '/', newAvailable.size);
|
|
1372
|
+
const neighbors = getNeighborsCached(a, positions, hexRadius);
|
|
1373
|
+
const counts = new Map();
|
|
1374
|
+
for (const n of neighbors) {
|
|
1375
|
+
const inf = newInfections.get(n);
|
|
1376
|
+
if (!inf)
|
|
1377
|
+
continue;
|
|
1378
|
+
counts.set(inf.photo.id, (counts.get(inf.photo.id) || 0) + 1);
|
|
1379
|
+
}
|
|
1380
|
+
let bestId;
|
|
1381
|
+
let best = 0;
|
|
1382
|
+
for (const [pid, c] of counts)
|
|
1383
|
+
if (c > best) {
|
|
1384
|
+
best = c;
|
|
1385
|
+
bestId = pid;
|
|
1386
|
+
}
|
|
1387
|
+
if (bestId && best >= 2) {
|
|
1388
|
+
const src = photos.find(p => p.id === bestId) || ((_a = Array.from(infectionsMap.values())[0]) === null || _a === void 0 ? void 0 : _a.photo);
|
|
1389
|
+
if (src) {
|
|
1390
|
+
const tilesX = 4;
|
|
1391
|
+
const tilesY = 4;
|
|
1392
|
+
const uvBounds = calculateUvBoundsFromGridPosition(0, 0, tilesX, tilesY);
|
|
1393
|
+
newInfections.set(a, { photo: src, gridPosition: [0, 0], infectionTime: currentTime, generation, uvBounds: uvBounds, scale: 0.35, growthRate: 0.08, tilesX: tilesX, tilesY: tilesY });
|
|
1394
|
+
newAvailable.delete(a);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
console.log('[evolve] Step 8: Optimization merge pass...');
|
|
1400
|
+
// Conservative merge pass (opt-in)
|
|
1401
|
+
postOptimizationMerge(newInfections, positions, hexRadius, !!workerDebug.mergeLogs);
|
|
1402
|
+
console.log('[evolve] Step 9: Assigning cluster-aware grid positions...');
|
|
1403
|
+
// Make clusters self-aware by assigning grid positions based on spatial layout
|
|
1404
|
+
const tileCenters = assignClusterGridPositions(newInfections, positions, hexRadius);
|
|
1405
|
+
console.log('[evolve] Step 10: Returning result - generation', generation, 'infections', newInfections.size);
|
|
1406
|
+
return { infections: newInfections, availableIndices: Array.from(newAvailable), lastEvolutionTime: currentTime, generation, tileCenters };
|
|
1407
|
+
}
|
|
1408
|
+
catch (e) {
|
|
1409
|
+
safePostError(e);
|
|
1410
|
+
return null;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
let lastEvolutionAt = 0;
|
|
1414
|
+
function mergeDebugFromPayload(d) {
|
|
1415
|
+
if (!d || typeof d !== 'object')
|
|
1416
|
+
return;
|
|
1417
|
+
// Map main-thread naming (evolveIntervalMs) into worker's evolutionIntervalMs
|
|
1418
|
+
if (typeof d.evolveIntervalMs === 'number')
|
|
1419
|
+
d.evolutionIntervalMs = d.evolveIntervalMs;
|
|
1420
|
+
// Merge into workerDebug
|
|
1421
|
+
try {
|
|
1422
|
+
Object.assign(workerDebug, d);
|
|
1423
|
+
}
|
|
1424
|
+
catch (e) { }
|
|
1425
|
+
}
|
|
1426
|
+
self.onmessage = function (ev) {
|
|
1427
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
1428
|
+
const raw = ev.data;
|
|
1429
|
+
try {
|
|
1430
|
+
if (!raw || typeof raw !== 'object')
|
|
1431
|
+
return;
|
|
1432
|
+
const type = raw.type;
|
|
1433
|
+
const payload = (_a = raw.data) !== null && _a !== void 0 ? _a : raw;
|
|
1434
|
+
if (type === 'setDataAndConfig' || type === 'setDebug') {
|
|
1435
|
+
// Accept either { type:'setDataAndConfig', data: { photos, debug } } or { type:'setDebug', debug }
|
|
1436
|
+
const dbg = (_c = (_b = payload.debug) !== null && _b !== void 0 ? _b : raw.debug) !== null && _c !== void 0 ? _c : payload;
|
|
1437
|
+
mergeDebugFromPayload(dbg);
|
|
1438
|
+
// Pre-build neighbor cache if positions are provided
|
|
1439
|
+
if (type === 'setDataAndConfig') {
|
|
1440
|
+
const incomingIsSpherical = typeof payload.isSpherical === 'boolean' ? Boolean(payload.isSpherical) : cache.isSpherical;
|
|
1441
|
+
const shouldUpdateTopology = typeof payload.isSpherical === 'boolean' && incomingIsSpherical !== cache.isSpherical;
|
|
1442
|
+
if (shouldUpdateTopology)
|
|
1443
|
+
invalidateCaches(incomingIsSpherical);
|
|
1444
|
+
else
|
|
1445
|
+
invalidateCaches();
|
|
1446
|
+
const positions = payload.positions;
|
|
1447
|
+
if (!positions || !Array.isArray(positions))
|
|
1448
|
+
return;
|
|
1449
|
+
const hexRadius = typeof payload.hexRadius === 'number' ? payload.hexRadius : 24;
|
|
1450
|
+
console.log('[hexgrid-worker] Pre-building neighbor cache for', positions.length, 'positions...');
|
|
1451
|
+
const startTime = Date.now();
|
|
1452
|
+
// Build ALL neighbor relationships in one O(n²) pass instead of n×O(n) passes
|
|
1453
|
+
try {
|
|
1454
|
+
const bounds = getGridBounds(positions);
|
|
1455
|
+
const threshold = Math.sqrt(3) * hexRadius * 1.15;
|
|
1456
|
+
const isSpherical = !!cache.isSpherical;
|
|
1457
|
+
// Initialize empty arrays for all positions
|
|
1458
|
+
for (let i = 0; i < positions.length; i++) {
|
|
1459
|
+
cache.neighborMap.set(i, []);
|
|
1460
|
+
}
|
|
1461
|
+
// Single pass: check each pair once and add bidirectional neighbors
|
|
1462
|
+
for (let i = 0; i < positions.length; i++) {
|
|
1463
|
+
const pos1 = positions[i];
|
|
1464
|
+
if (!pos1)
|
|
1465
|
+
continue;
|
|
1466
|
+
// Only check j > i to avoid duplicate checks
|
|
1467
|
+
for (let j = i + 1; j < positions.length; j++) {
|
|
1468
|
+
const pos2 = positions[j];
|
|
1469
|
+
if (!pos2)
|
|
1470
|
+
continue;
|
|
1471
|
+
const d = distanceBetween(pos1, pos2, bounds, isSpherical);
|
|
1472
|
+
if (d <= threshold) {
|
|
1473
|
+
// Add bidirectional neighbors
|
|
1474
|
+
cache.neighborMap.get(i).push(j);
|
|
1475
|
+
cache.neighborMap.get(j).push(i);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
// Log progress every 100 positions
|
|
1479
|
+
if ((i + 1) % 100 === 0) {
|
|
1480
|
+
console.log('[hexgrid-worker] Processed', i + 1, '/', positions.length, 'positions');
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
const elapsed = Date.now() - startTime;
|
|
1484
|
+
console.log('[hexgrid-worker] ✅ Neighbor cache built in', elapsed, 'ms - ready for evolution!');
|
|
1485
|
+
// Mark cache as ready
|
|
1486
|
+
cache.cacheReady = true;
|
|
1487
|
+
// Notify main thread that cache is ready
|
|
1488
|
+
try {
|
|
1489
|
+
self.postMessage({ type: 'cache-ready', data: { elapsed, positions: positions.length } });
|
|
1490
|
+
}
|
|
1491
|
+
catch (e) { }
|
|
1492
|
+
}
|
|
1493
|
+
catch (e) {
|
|
1494
|
+
console.error('[hexgrid-worker] Error during cache pre-build:', e);
|
|
1495
|
+
// Mark cache as ready anyway to allow evolution to proceed
|
|
1496
|
+
cache.cacheReady = true;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
if (type === 'evolve') {
|
|
1502
|
+
// Check if neighbor cache is ready before processing evolve
|
|
1503
|
+
if (!cache.cacheReady) {
|
|
1504
|
+
console.log('[hexgrid-worker] ⏸️ Evolve message received but cache not ready yet - deferring...');
|
|
1505
|
+
// Defer this evolve message by re-posting it after a short delay
|
|
1506
|
+
setTimeout(() => {
|
|
1507
|
+
try {
|
|
1508
|
+
self.postMessage({ type: 'deferred-evolve', data: { reason: 'cache-not-ready' } });
|
|
1509
|
+
}
|
|
1510
|
+
catch (e) { }
|
|
1511
|
+
// Re-process the message
|
|
1512
|
+
self.onmessage(ev);
|
|
1513
|
+
}, 100);
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
// Normalize payload shape: support { data: { prevState, positions, photos, hexRadius, debug } }
|
|
1517
|
+
mergeDebugFromPayload(payload.debug || payload);
|
|
1518
|
+
// Diagnostic: log that an evolve was received and the available payload keys (only when debugLogs enabled)
|
|
1519
|
+
try {
|
|
1520
|
+
if (workerDebug && workerDebug.debugLogs) {
|
|
1521
|
+
console.log('[hexgrid-worker] evolve received, payload keys=', Object.keys(payload || {}), 'workerDebug.evolutionIntervalMs=', workerDebug.evolutionIntervalMs, 'workerDebug.evolveIntervalMs=', workerDebug.evolveIntervalMs);
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
catch (e) { }
|
|
1525
|
+
const now = Date.now();
|
|
1526
|
+
const interval = typeof workerDebug.evolutionIntervalMs === 'number' ? workerDebug.evolutionIntervalMs : (typeof workerDebug.evolveIntervalMs === 'number' ? workerDebug.evolveIntervalMs : 60000);
|
|
1527
|
+
console.log('[hexgrid-worker] Throttle check: interval=', interval, 'lastEvolutionAt=', lastEvolutionAt, 'now=', now, 'diff=', now - lastEvolutionAt, 'willThrottle=', (now - lastEvolutionAt < interval));
|
|
1528
|
+
// Throttle: if we're within the interval, notify (debug) and skip processing
|
|
1529
|
+
const reason = payload.reason || (raw && raw.reason);
|
|
1530
|
+
const bypassThrottle = reason === 'photos-init' || reason === 'reset';
|
|
1531
|
+
// Clear, high-signal log for build verification: reports whether the current evolve will bypass the worker throttle
|
|
1532
|
+
console.log('[hexgrid-worker] THROTTLE DECISION', { interval, lastEvolutionAt, now, diff: now - lastEvolutionAt, willThrottle: (!bypassThrottle && (now - lastEvolutionAt < interval)), reason, bypassThrottle });
|
|
1533
|
+
// Throttle: if we're within the interval and not bypassed, notify (debug) and skip processing
|
|
1534
|
+
if (!bypassThrottle && now - lastEvolutionAt < interval) {
|
|
1535
|
+
console.log('[hexgrid-worker] ⛔ THROTTLED - skipping evolution processing');
|
|
1536
|
+
if (workerDebug && workerDebug.debugLogs) {
|
|
1537
|
+
try {
|
|
1538
|
+
self.postMessage({ type: 'throttled-evolve', data: { receivedAt: now, nextAvailableAt: lastEvolutionAt + interval, payloadKeys: Object.keys(payload || {}), reason } });
|
|
1539
|
+
}
|
|
1540
|
+
catch (e) { }
|
|
1541
|
+
}
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
// Mark processed time and send ack for an evolve we will process
|
|
1545
|
+
lastEvolutionAt = now;
|
|
1546
|
+
console.log('[hexgrid-worker] ✅ PROCESSING evolution - lastEvolutionAt updated to', now);
|
|
1547
|
+
try {
|
|
1548
|
+
if (workerDebug && workerDebug.debugLogs) {
|
|
1549
|
+
try {
|
|
1550
|
+
self.postMessage({ type: 'ack-evolve', data: { receivedAt: now, payloadKeys: Object.keys(payload || {}) } });
|
|
1551
|
+
}
|
|
1552
|
+
catch (e) { }
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
catch (e) { }
|
|
1556
|
+
// Emit a lightweight processing marker so the client can see evolve processing started
|
|
1557
|
+
try {
|
|
1558
|
+
if (workerDebug && workerDebug.debugLogs) {
|
|
1559
|
+
try {
|
|
1560
|
+
self.postMessage({ type: 'processing-evolve', data: { startedAt: now, payloadKeys: Object.keys(payload || {}) } });
|
|
1561
|
+
}
|
|
1562
|
+
catch (e) { }
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
catch (e) { }
|
|
1566
|
+
const state = (_f = (_e = (_d = payload.prevState) !== null && _d !== void 0 ? _d : payload.state) !== null && _e !== void 0 ? _e : raw.state) !== null && _f !== void 0 ? _f : null;
|
|
1567
|
+
const positions = (_h = (_g = payload.positions) !== null && _g !== void 0 ? _g : raw.positions) !== null && _h !== void 0 ? _h : [];
|
|
1568
|
+
const photos = (_k = (_j = payload.photos) !== null && _j !== void 0 ? _j : raw.photos) !== null && _k !== void 0 ? _k : [];
|
|
1569
|
+
const hexRadius = typeof payload.hexRadius === 'number' ? payload.hexRadius : (typeof raw.hexRadius === 'number' ? raw.hexRadius : 16);
|
|
1570
|
+
if (typeof payload.isSpherical === 'boolean' && Boolean(payload.isSpherical) !== cache.isSpherical) {
|
|
1571
|
+
invalidateCaches(Boolean(payload.isSpherical));
|
|
1572
|
+
}
|
|
1573
|
+
console.log('[hexgrid-worker] 🔧 About to call evolveInfectionSystem');
|
|
1574
|
+
console.log('[hexgrid-worker] - state generation:', state === null || state === void 0 ? void 0 : state.generation);
|
|
1575
|
+
console.log('[hexgrid-worker] - state infections:', ((_l = state === null || state === void 0 ? void 0 : state.infections) === null || _l === void 0 ? void 0 : _l.length) || ((_m = state === null || state === void 0 ? void 0 : state.infections) === null || _m === void 0 ? void 0 : _m.size) || 0);
|
|
1576
|
+
console.log('[hexgrid-worker] - positions:', (positions === null || positions === void 0 ? void 0 : positions.length) || 0);
|
|
1577
|
+
console.log('[hexgrid-worker] - photos:', (photos === null || photos === void 0 ? void 0 : photos.length) || 0);
|
|
1578
|
+
console.log('[hexgrid-worker] - hexRadius:', hexRadius);
|
|
1579
|
+
let res;
|
|
1580
|
+
let timeoutId;
|
|
1581
|
+
let timedOut = false;
|
|
1582
|
+
// Set a watchdog timer to detect hangs (10 seconds)
|
|
1583
|
+
timeoutId = setTimeout(() => {
|
|
1584
|
+
timedOut = true;
|
|
1585
|
+
console.error('[hexgrid-worker] ⏱️ TIMEOUT: evolveInfectionSystem is taking too long (>10s)! Possible infinite loop.');
|
|
1586
|
+
try {
|
|
1587
|
+
self.postMessage({ type: 'error', error: 'Evolution timeout - possible infinite loop' });
|
|
1588
|
+
}
|
|
1589
|
+
catch (e) { }
|
|
1590
|
+
}, 10000);
|
|
1591
|
+
try {
|
|
1592
|
+
console.log('[hexgrid-worker] 🚀 Calling evolveInfectionSystem NOW...');
|
|
1593
|
+
const startTime = Date.now();
|
|
1594
|
+
res = evolveInfectionSystem(state, positions, photos, hexRadius, now, !!workerDebug.debugLogs);
|
|
1595
|
+
const elapsed = Date.now() - startTime;
|
|
1596
|
+
clearTimeout(timeoutId);
|
|
1597
|
+
console.log('[hexgrid-worker] ✅ evolveInfectionSystem RETURNED successfully in', elapsed, 'ms');
|
|
1598
|
+
}
|
|
1599
|
+
catch (err) {
|
|
1600
|
+
clearTimeout(timeoutId);
|
|
1601
|
+
console.error('[hexgrid-worker] ❌ FATAL: evolveInfectionSystem threw an error:', err);
|
|
1602
|
+
console.error('[hexgrid-worker] Error stack:', err instanceof Error ? err.stack : 'no stack');
|
|
1603
|
+
safePostError(err);
|
|
1604
|
+
return;
|
|
1605
|
+
}
|
|
1606
|
+
if (timedOut) {
|
|
1607
|
+
console.error('[hexgrid-worker] ⏱️ Function eventually returned but after timeout was triggered');
|
|
1608
|
+
}
|
|
1609
|
+
if (!res) {
|
|
1610
|
+
console.log('[hexgrid-worker] ❌ evolveInfectionSystem returned null!');
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
console.log('[hexgrid-worker] ✅ Evolution complete! New generation=', res.generation, 'infections=', res.infections.size);
|
|
1614
|
+
try {
|
|
1615
|
+
const payload = { infections: Array.from(res.infections.entries()), availableIndices: res.availableIndices, lastEvolutionTime: res.lastEvolutionTime, generation: res.generation };
|
|
1616
|
+
if (res.tileCenters && res.tileCenters.length > 0) {
|
|
1617
|
+
payload.tileCenters = res.tileCenters;
|
|
1618
|
+
console.log('[hexgrid-worker] Including', res.tileCenters.length, 'tile center sets in evolved message');
|
|
1619
|
+
}
|
|
1620
|
+
self.postMessage({ type: 'evolved', data: payload });
|
|
1621
|
+
// Record posted generation/infection count so later auto-triggers can avoid regressing
|
|
1622
|
+
try {
|
|
1623
|
+
cache.lastGeneration = res.generation;
|
|
1624
|
+
cache.lastInfectionCount = res.infections ? res.infections.size : 0;
|
|
1625
|
+
}
|
|
1626
|
+
catch (e) { }
|
|
1627
|
+
}
|
|
1628
|
+
catch (e) {
|
|
1629
|
+
console.error('[hexgrid-worker] ❌ Failed to post evolved message:', e);
|
|
1630
|
+
}
|
|
1631
|
+
console.log('[hexgrid-worker] 📤 Posted evolved message back to main thread');
|
|
1632
|
+
// Emit a completion marker so the client can confirm the evolve finished end-to-end
|
|
1633
|
+
try {
|
|
1634
|
+
if (workerDebug && workerDebug.debugLogs) {
|
|
1635
|
+
try {
|
|
1636
|
+
self.postMessage({ type: 'evolved-complete', data: { finishedAt: Date.now(), generation: res.generation, lastEvolutionTime: res.lastEvolutionTime } });
|
|
1637
|
+
}
|
|
1638
|
+
catch (e) { }
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
catch (e) { }
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
if (type === 'optimize') {
|
|
1645
|
+
try {
|
|
1646
|
+
const infectionsArr = payload.infections || raw.infections || [];
|
|
1647
|
+
const infections = new Map(infectionsArr);
|
|
1648
|
+
const positions = (_o = payload.positions) !== null && _o !== void 0 ? _o : raw.positions;
|
|
1649
|
+
const hexRadius = typeof payload.hexRadius === 'number' ? payload.hexRadius : (typeof raw.hexRadius === 'number' ? raw.hexRadius : 16);
|
|
1650
|
+
postOptimizationMerge(infections, positions, hexRadius, !!workerDebug.mergeLogs);
|
|
1651
|
+
try {
|
|
1652
|
+
self.postMessage({ type: 'optimized', data: { infections: Array.from(infections.entries()) } });
|
|
1653
|
+
}
|
|
1654
|
+
catch (e) { }
|
|
1655
|
+
}
|
|
1656
|
+
catch (e) {
|
|
1657
|
+
safePostError(e);
|
|
1658
|
+
}
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
catch (err) {
|
|
1663
|
+
safePostError(err);
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
// Additional helpers that the optimizer uses (kept separate and consistent)
|
|
1667
|
+
function calculatePhotoContiguityCached(photoIdOrPhoto, indices, positions, hexRadius, debugLogs = true) {
|
|
1668
|
+
const photoId = typeof photoIdOrPhoto === 'string' ? photoIdOrPhoto : photoIdOrPhoto.id;
|
|
1669
|
+
return calculatePhotoContiguity(photoId, indices, positions, hexRadius, debugLogs);
|
|
1670
|
+
}
|
|
1671
|
+
function calculatePhotoContiguity(photoId, indices, positions, hexRadius, debugLogs = true) {
|
|
1672
|
+
let totalScore = 0;
|
|
1673
|
+
const indicesSet = new Set(indices);
|
|
1674
|
+
for (const index of indices) {
|
|
1675
|
+
const neighbors = getNeighborsCached(index, positions, hexRadius);
|
|
1676
|
+
let connections = 0;
|
|
1677
|
+
for (const neighborIndex of neighbors) {
|
|
1678
|
+
if (indicesSet.has(neighborIndex))
|
|
1679
|
+
connections++;
|
|
1680
|
+
}
|
|
1681
|
+
totalScore += connections;
|
|
1682
|
+
}
|
|
1683
|
+
return totalScore;
|
|
1684
|
+
}
|
|
1685
|
+
function calculateSwappedContiguityCached(photoId, indices, positions, hexRadius, fromIndex, toIndex, infections, debugLogs = true) {
|
|
1686
|
+
const tempIndices = [...indices];
|
|
1687
|
+
const fromPos = tempIndices.indexOf(fromIndex);
|
|
1688
|
+
const toPos = tempIndices.indexOf(toIndex);
|
|
1689
|
+
if (fromPos !== -1)
|
|
1690
|
+
tempIndices[fromPos] = toIndex;
|
|
1691
|
+
if (toPos !== -1)
|
|
1692
|
+
tempIndices[toPos] = fromIndex;
|
|
1693
|
+
return calculatePhotoContiguity(photoId, tempIndices, positions, hexRadius, debugLogs);
|
|
1694
|
+
}
|
|
1695
|
+
function analyzeLocalEnvironment(centerIndex, infections, positions, hexRadius, radius = 2, debugLogs = true) {
|
|
1696
|
+
const centerPos = positions[centerIndex];
|
|
1697
|
+
const localIndices = [];
|
|
1698
|
+
const visited = new Set();
|
|
1699
|
+
const queue = [[centerIndex, 0]];
|
|
1700
|
+
while (queue.length > 0) {
|
|
1701
|
+
const [currentIndex, distance] = queue.shift();
|
|
1702
|
+
if (visited.has(currentIndex) || distance > radius)
|
|
1703
|
+
continue;
|
|
1704
|
+
visited.add(currentIndex);
|
|
1705
|
+
localIndices.push(currentIndex);
|
|
1706
|
+
if (distance < radius) {
|
|
1707
|
+
const neighbors = getNeighborsCached(currentIndex, positions, hexRadius);
|
|
1708
|
+
for (const neighborIndex of neighbors) {
|
|
1709
|
+
if (!visited.has(neighborIndex))
|
|
1710
|
+
queue.push([neighborIndex, distance + 1]);
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
let infectedCount = 0;
|
|
1715
|
+
const photoCounts = new Map();
|
|
1716
|
+
const clusterSizes = new Map();
|
|
1717
|
+
let boundaryPressure = 0;
|
|
1718
|
+
let totalVariance = 0;
|
|
1719
|
+
for (const index of localIndices) {
|
|
1720
|
+
const infection = infections.get(index);
|
|
1721
|
+
if (infection) {
|
|
1722
|
+
infectedCount++;
|
|
1723
|
+
const photoId = infection.photo.id;
|
|
1724
|
+
photoCounts.set(photoId, (photoCounts.get(photoId) || 0) + 1);
|
|
1725
|
+
clusterSizes.set(photoId, (clusterSizes.get(photoId) || 0) + 1);
|
|
1726
|
+
}
|
|
1727
|
+
else {
|
|
1728
|
+
boundaryPressure += 0.1;
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
const totalPhotos = photoCounts.size;
|
|
1732
|
+
const avgPhotoCount = infectedCount / Math.max(totalPhotos, 1);
|
|
1733
|
+
for (const count of photoCounts.values())
|
|
1734
|
+
totalVariance += Math.pow(count - avgPhotoCount, 2);
|
|
1735
|
+
const localVariance = totalVariance / Math.max(infectedCount, 1);
|
|
1736
|
+
let dominantPhoto = null;
|
|
1737
|
+
let maxCount = 0;
|
|
1738
|
+
for (const [photoId, count] of photoCounts) {
|
|
1739
|
+
if (count > maxCount) {
|
|
1740
|
+
maxCount = count;
|
|
1741
|
+
for (const infection of infections.values()) {
|
|
1742
|
+
if (infection.photo.id === photoId) {
|
|
1743
|
+
dominantPhoto = infection.photo;
|
|
1744
|
+
break;
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
const density = infectedCount / Math.max(localIndices.length, 1);
|
|
1750
|
+
const stability = dominantPhoto ? (maxCount / Math.max(infectedCount, 1)) : 0;
|
|
1751
|
+
return { density, stability, dominantPhoto, clusterSizes, boundaryPressure, localVariance };
|
|
1752
|
+
}
|
|
1753
|
+
function invalidateCaches(isSpherical) {
|
|
1754
|
+
cache.neighborMap.clear();
|
|
1755
|
+
cache.gridBounds = null;
|
|
1756
|
+
cache.photoClusters.clear();
|
|
1757
|
+
cache.connectedComponents.clear();
|
|
1758
|
+
cache.gridPositions.clear();
|
|
1759
|
+
cache.cacheReady = false;
|
|
1760
|
+
if (typeof isSpherical === 'boolean')
|
|
1761
|
+
cache.isSpherical = isSpherical;
|
|
1762
|
+
}
|
|
1763
|
+
console.log('[hexgrid-worker] ready');
|