@pirireis/webglobeplugins 0.17.1 → 1.0.3

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.
Files changed (67) hide show
  1. package/Math/haversine.js +22 -0
  2. package/Math/methods.js +15 -2
  3. package/Math/tessellation/methods.js +4 -1
  4. package/Math/tessellation/nearest-value-padding.js +112 -0
  5. package/Math/tessellation/spherical-triangle-area.js +99 -0
  6. package/Math/tessellation/tile-merger.js +346 -215
  7. package/Math/tessellation/triangle-tessellation.js +381 -9
  8. package/Math/vec3.js +4 -0
  9. package/Math/xyz-tile.js +18 -0
  10. package/altitude-locator/plugin.js +1 -2
  11. package/investigation-tools/draw/tiles/adapters.js +2 -2
  12. package/investigation-tools/draw/tiles/tiles.js +2 -2
  13. package/package.json +1 -1
  14. package/programs/helpers/fadeaway.js +6 -1
  15. package/programs/point-on-globe/square-pixel-point.js +1 -0
  16. package/programs/polygon-on-globe/texture-dem-triangles.js +94 -116
  17. package/programs/totems/camera-totem-attactment-interface.js +1 -0
  18. package/programs/totems/camerauniformblock.js +33 -22
  19. package/programs/totems/dem-textures-manager.js +265 -0
  20. package/programs/vectorfields/logics/drawrectangleparticles.js +51 -18
  21. package/programs/vectorfields/logics/{ubo-new.js → particle-ubo.js} +5 -14
  22. package/programs/vectorfields/logics/pixelbased.js +42 -36
  23. package/programs/vectorfields/pingpongbuffermanager.js +34 -8
  24. package/semiplugins/shape-on-terrain/terrain-polygon/adapters.js +55 -0
  25. package/semiplugins/shape-on-terrain/terrain-polygon/data/cache.js +102 -0
  26. package/semiplugins/shape-on-terrain/terrain-polygon/data/index-polygon-map.js +45 -0
  27. package/semiplugins/shape-on-terrain/terrain-polygon/data/manager.js +4 -0
  28. package/semiplugins/shape-on-terrain/terrain-polygon/data/master-worker.js +177 -0
  29. package/semiplugins/shape-on-terrain/terrain-polygon/data/polygon-to-triangles.js +100 -0
  30. package/semiplugins/shape-on-terrain/terrain-polygon/data/random.js +121 -0
  31. package/semiplugins/shape-on-terrain/terrain-polygon/data/types.js +1 -0
  32. package/semiplugins/shape-on-terrain/terrain-polygon/data/worker-contact.js +63 -0
  33. package/semiplugins/shape-on-terrain/terrain-polygon/data/worker.js +125 -0
  34. package/semiplugins/shape-on-terrain/terrain-polygon/terrain-polygon.js +219 -0
  35. package/semiplugins/shape-on-terrain/terrain-polygon/types.js +8 -0
  36. package/semiplugins/shell/bbox-renderer/logic.js +18 -58
  37. package/semiplugins/shell/bbox-renderer/object.js +19 -9
  38. package/tracks/point-heat-map/point-to-heat-map-flow.js +1 -1
  39. package/tracks/point-tracks/plugin.js +13 -6
  40. package/tracks/timetracks/program-line-strip.js +1 -1
  41. package/util/account/single-attribute-buffer-management/buffer-manager.js +5 -3
  42. package/util/account/single-attribute-buffer-management/buffer-orchestrator.js +2 -2
  43. package/util/gl-util/uniform-block/manager.js +20 -10
  44. package/util/helper-methods.js +8 -0
  45. package/util/picking/fence.js +4 -2
  46. package/util/picking/picker-displayer.js +51 -9
  47. package/util/programs/draw-texture-on-canvas.js +18 -15
  48. package/util/shaderfunctions/geometrytransformations.js +67 -1
  49. package/vectorfield/waveparticles/plugin.js +241 -116
  50. package/vectorfield/wind/adapters/image-to-fields.js +61 -0
  51. package/vectorfield/wind/adapters/types.js +1 -0
  52. package/vectorfield/wind/imagetovectorfieldandmagnitude.js +6 -9
  53. package/vectorfield/wind/plugin-persistant copy.js +364 -0
  54. package/vectorfield/wind/plugin-persistant.js +375 -0
  55. package/vectorfield/wind/plugin.js +1 -1
  56. package/Math/tessellation/earcut/adapters.js +0 -37
  57. package/Math/tessellation/hybrid-triangle-tessellation-meta.js +0 -123
  58. package/Math/tessellation/shred-input.js +0 -18
  59. package/Math/tessellation/tiler.js +0 -50
  60. package/Math/tessellation/triangle-tessellation-meta.js +0 -523
  61. package/programs/polygon-on-globe/texture-dem-triangle-test-plugin-triangle.js +0 -328
  62. package/programs/vectorfields/logics/drawrectangleparticles1.js +0 -112
  63. package/semiplugins/shape-on-terrain/terrain-cover/texture-dem-cover.js +0 -1
  64. package/util/gl-util/uniform-block/types.js +0 -1
  65. package/util/webglobe/index.js +0 -2
  66. /package/Math/tessellation/{zoom-catch.js → constants.js} +0 -0
  67. /package/util/{webglobe/gldefaultstates.js → globe-default-gl-states.js} +0 -0
@@ -1,52 +1,89 @@
1
- function displayTileMetaData(tilesMetaData) {
2
- // show maxZoom minZoom
3
- console.log(`Max Level: ${tilesMetaData.maxLevel}
4
- Min Level: ${tilesMetaData.minLevel}`);
1
+ import { calculateMergedMeshDimLength } from "./methods";
2
+ import { NearestValuePadding } from "./nearest-value-padding";
3
+ function keyMethod(x, y, level) {
4
+ return `${level}_${x}_${y}`;
5
5
  }
6
- function keyMethod(row, column, level) {
7
- return `${level}_${row}_${column}`;
8
- }
9
- function calculateParentTile(row, column, level) {
6
+ function calculateParentTile(x, y, level) {
10
7
  return {
11
- row: Math.floor(row / 2),
12
- column: Math.floor(column / 2),
8
+ x: Math.floor(x / 2),
9
+ y: Math.floor(y / 2),
13
10
  level: level - 1
14
11
  };
15
12
  }
16
- function createMapAndMetaData(tiles) {
13
+ function createMapAndMetaData(tiles, globe) {
17
14
  const tileMap = new Map();
18
15
  let maxLevel = -Infinity;
19
16
  let minLevel = Infinity;
20
- const tileLimitsByZoom = new Map();
17
+ // Intermediate storage to analyze distributions per zoom level
18
+ const zoomData = new Map();
19
+ // 1. First Pass: Populate Map and Collect Coordinates
21
20
  for (const tile of tiles) {
22
- const key = keyMethod(tile.row, tile.column, tile.level);
21
+ const key = keyMethod(tile.x, tile.y, tile.level);
23
22
  tileMap.set(key, tile);
24
- if (tile.level > maxLevel) {
23
+ // Update Level Range
24
+ if (tile.level > maxLevel)
25
25
  maxLevel = tile.level;
26
- }
27
- if (tile.level < minLevel) {
26
+ if (tile.level < minLevel)
28
27
  minLevel = tile.level;
28
+ // Collect Data
29
+ if (!zoomData.has(tile.level)) {
30
+ zoomData.set(tile.level, { xValues: [], yValues: [] });
29
31
  }
30
- if (!tileLimitsByZoom.has(tile.level)) {
31
- tileLimitsByZoom.set(tile.level, {
32
- minRow: tile.row,
33
- maxRow: tile.row,
34
- minCol: tile.column,
35
- maxCol: tile.column
36
- });
32
+ const data = zoomData.get(tile.level);
33
+ data.xValues.push(tile.x);
34
+ data.yValues.push(tile.y);
35
+ }
36
+ const tileLimitsByZoom = new Map();
37
+ // 2. Second Pass: Analyze Data per Zoom Level
38
+ zoomData.forEach((data, level) => {
39
+ // --- Calculate Gravity Centers (Mode) ---
40
+ // --- Calculate Min/Max and Antimeridian ---
41
+ // Sort X values to detect gaps
42
+ const sortedX = [...new Set(data.xValues)].sort((a, b) => a - b);
43
+ const minY = Math.min(...data.yValues);
44
+ const maxY = Math.max(...data.yValues);
45
+ let minX = sortedX[0];
46
+ let maxX = sortedX[sortedX.length - 1];
47
+ let isAntimeridian = false;
48
+ // We only check for wrapping if we have tiles near both edges (0 and Max)
49
+ // A simple heuristic: find the largest gap between sorted indices.
50
+ let maxGap = 0;
51
+ let gapIndex = -1;
52
+ for (let i = 0; i < sortedX.length - 1; i++) {
53
+ const gap = sortedX[i + 1] - sortedX[i];
54
+ if (gap > maxGap) {
55
+ maxGap = gap;
56
+ gapIndex = i;
57
+ }
37
58
  }
38
- else {
39
- const limits = tileLimitsByZoom.get(tile.level);
40
- if (tile.row < limits.minRow)
41
- limits.minRow = tile.row;
42
- if (tile.row > limits.maxRow)
43
- limits.maxRow = tile.row;
44
- if (tile.column < limits.minCol)
45
- limits.minCol = tile.column;
46
- if (tile.column > limits.maxCol)
47
- limits.maxCol = tile.column;
59
+ // Also check the wrap-around gap (distance from last tile to world end + first tile)
60
+ // Though strictly for clustering split, we usually look for the internal gap.
61
+ // If the largest internal gap is significantly large (e.g., > worldWidth / 2),
62
+ // we treat the smaller numbers as the "East of view" (Right side)
63
+ // and large numbers as "West of view" (Left side) relative to the dateline.
64
+ // let centerX = getGravityCenter(data.xValues);
65
+ // const centerY = getGravityCenter(data.yValues);
66
+ const { x: centerX, y: centerY } = getCenterFromCamera(globe, level);
67
+ if (maxGap > 5 && maxX === Math.pow(2, level) - 1 && minX === 0) {
68
+ isAntimeridian = true;
69
+ // Cluster 1 (Low X): sortedX[0] ... sortedX[gapIndex] -> "West Cluster" (The Americas/Left side of map 0..x)
70
+ // Cluster 2 (High X): sortedX[gapIndex+1] ... end -> "East Cluster" (Asia/Right side of map x..max)
71
+ // Per requirements:
72
+ // "max value now represents max of west cluster" -> Max of the Low X numbers
73
+ maxX = sortedX[gapIndex];
74
+ // "min values represents min of east cluster" -> Min of the High X numbers
75
+ minX = sortedX[gapIndex + 1];
48
76
  }
49
- }
77
+ tileLimitsByZoom.set(level, {
78
+ minX,
79
+ maxX,
80
+ minY,
81
+ maxY,
82
+ antimeridian: isAntimeridian,
83
+ centerX,
84
+ centerY
85
+ });
86
+ });
50
87
  return {
51
88
  tileMap,
52
89
  maxLevel,
@@ -54,98 +91,234 @@ function createMapAndMetaData(tiles) {
54
91
  tileLimitsByZoom
55
92
  };
56
93
  }
94
+ // Helper to find the most frequent value (Gravity Center)
95
+ function getMode(arr) {
96
+ if (arr.length === 0)
97
+ return 0;
98
+ const map = new Map();
99
+ let maxCount = 0;
100
+ let mode = arr[0];
101
+ for (const num of arr) {
102
+ const count = (map.get(num) || 0) + 1;
103
+ map.set(num, count);
104
+ if (count > maxCount) {
105
+ maxCount = count;
106
+ mode = num;
107
+ }
108
+ }
109
+ return mode;
110
+ }
111
+ function getGravityCenter(arr) {
112
+ if (arr.length === 0)
113
+ return 0;
114
+ const sum = arr.reduce((acc, val) => acc + val, 0);
115
+ return Math.round(sum / arr.length);
116
+ }
117
+ function getCenterFromCamera(globe, zoom) {
118
+ const camLongLat = globe.FCamera.FCamLongLat;
119
+ const n = Math.pow(2, zoom);
120
+ const x = Math.floor((camLongLat.x / (2 * Math.PI) + 0.5) * n);
121
+ const y = Math.floor((camLongLat.y / Math.PI + 0.5) * n);
122
+ return { x, y };
123
+ }
57
124
  function populateTileIntoHigherZoomLevel(tileMesh, tileDimensionLength, targetDimensionLength) {
58
- const newMesh = new Array(targetDimensionLength).fill(0).map(() => new Float32Array(targetDimensionLength));
125
+ const newMesh = Array.from({ length: targetDimensionLength }, () => new Float32Array(targetDimensionLength));
59
126
  // use linear interpolation to populate
60
127
  for (let row = 0; row < targetDimensionLength; row++) {
61
128
  for (let col = 0; col < targetDimensionLength; col++) {
62
- const srcRow = row * (tileDimensionLength - 1) / (targetDimensionLength - 1);
63
- const srcCol = col * (tileDimensionLength - 1) / (targetDimensionLength - 1);
64
- const srcRowLow = Math.floor(srcRow);
65
- const srcRowHigh = Math.min(Math.ceil(srcRow), tileDimensionLength - 1);
66
- const srcColLow = Math.floor(srcCol);
67
- const srcColHigh = Math.min(Math.ceil(srcCol), tileDimensionLength - 1);
68
- const topLeft = tileMesh[srcRowLow][srcColLow];
69
- const topRight = tileMesh[srcRowLow][srcColHigh];
70
- const bottomLeft = tileMesh[srcRowHigh][srcColLow];
71
- const bottomRight = tileMesh[srcRowHigh][srcColHigh];
72
- const top = topLeft + (topRight - topLeft) * (srcCol - srcColLow);
73
- const bottom = bottomLeft + (bottomRight - bottomLeft) * (srcCol - srcColLow);
74
- newMesh[row][col] = top + (bottom - top) * (srcRow - srcRowLow);
129
+ const sourceRow = row / (targetDimensionLength - 1) * (tileDimensionLength - 1);
130
+ const sourceCol = col / (targetDimensionLength - 1) * (tileDimensionLength - 1);
131
+ const rowLow = Math.floor(sourceRow);
132
+ const rowHigh = Math.min(Math.ceil(sourceRow), tileDimensionLength - 1);
133
+ const colLow = Math.floor(sourceCol);
134
+ const colHigh = Math.min(Math.ceil(sourceCol), tileDimensionLength - 1);
135
+ const topLeft = tileMesh[rowLow][colLow];
136
+ const topRight = tileMesh[rowLow][colHigh];
137
+ const bottomLeft = tileMesh[rowHigh][colLow];
138
+ const bottomRight = tileMesh[rowHigh][colHigh];
139
+ const top = topLeft + (topRight - topLeft) * (sourceCol - colLow);
140
+ const bottom = bottomLeft + (bottomRight - bottomLeft) * (sourceCol - colLow);
141
+ newMesh[row][col] = top + (bottom - top) * (sourceRow - rowLow);
75
142
  }
76
143
  }
77
144
  return newMesh;
78
145
  }
146
+ function fillFromChildren(targetMesh, targetDimensionLength, childrenMeshes, sourceDimensionLength, startX, startY) {
147
+ const halfDim = (sourceDimensionLength - 1) / 2;
148
+ // Child 0: Top Left
149
+ if (childrenMeshes[0]) {
150
+ const child = childrenMeshes[0];
151
+ for (let r = 0; r <= halfDim; r++) {
152
+ // Read from top of child (source convention is bottom-up, so top is index Length-1)
153
+ // We skip every second row: (L-1), (L-3), ...
154
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
155
+ const rowData = child[childRowIndex];
156
+ for (let c = 0; c <= halfDim; c++) {
157
+ // Skip every second column
158
+ const val = rowData[c * 2];
159
+ const targetIdx = (startY + r) * targetDimensionLength + (startX + c);
160
+ targetMesh[targetIdx] = val;
161
+ }
162
+ }
163
+ }
164
+ // Child 1: Top Right
165
+ // In mergeTiles loop (dx outer, dy inner), index 2 corresponds to dx=1, dy=0 (Top Right)
166
+ if (childrenMeshes[2]) {
167
+ const child = childrenMeshes[2];
168
+ for (let r = 0; r <= halfDim; r++) {
169
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
170
+ const rowData = child[childRowIndex];
171
+ for (let c = 0; c <= halfDim; c++) {
172
+ const val = rowData[c * 2];
173
+ const targetIdx = (startY + r) * targetDimensionLength + (startX + halfDim + c);
174
+ if (isNaN(targetMesh[targetIdx])) {
175
+ targetMesh[targetIdx] = val;
176
+ }
177
+ }
178
+ }
179
+ }
180
+ // Child 2: Bottom Left
181
+ // In mergeTiles loop, index 1 corresponds to dx=0, dy=1 (Bottom Left)
182
+ if (childrenMeshes[1]) {
183
+ const child = childrenMeshes[1];
184
+ for (let r = 0; r <= halfDim; r++) {
185
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
186
+ const rowData = child[childRowIndex];
187
+ for (let c = 0; c <= halfDim; c++) {
188
+ const val = rowData[c * 2];
189
+ const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + c);
190
+ if (isNaN(targetMesh[targetIdx])) {
191
+ targetMesh[targetIdx] = val;
192
+ }
193
+ }
194
+ }
195
+ }
196
+ // Child 3: Bottom Right
197
+ if (childrenMeshes[3]) {
198
+ const child = childrenMeshes[3];
199
+ for (let r = 0; r <= halfDim; r++) {
200
+ const childRowIndex = (sourceDimensionLength - 1) - (r * 2);
201
+ const rowData = child[childRowIndex];
202
+ for (let c = 0; c <= halfDim; c++) {
203
+ const val = rowData[c * 2];
204
+ const targetIdx = (startY + halfDim + r) * targetDimensionLength + (startX + halfDim + c);
205
+ if (isNaN(targetMesh[targetIdx])) {
206
+ targetMesh[targetIdx] = val;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
79
212
  // This function is correct, assuming its inputs are prepared properly.
80
213
  // This function is correct, assuming its inputs are prepared properly.
81
214
  function moveMeshToMergedMesh(targetMesh, targetDimensionLength, sourceMesh, sourceDimensionLength, startX, startY) {
82
- for (let row = 0; row < sourceDimensionLength; row++) {
83
- for (let col = 0; col < sourceDimensionLength; col++) {
84
- const targetIndex = (startY + row) * targetDimensionLength + (startX + col);
85
- // Check if source value exists
86
- if (sourceMesh[row] === undefined || sourceMesh[row][col] === undefined) {
87
- console.warn(`Source data missing at [${row}][${col}]`);
88
- continue;
89
- }
90
- const value = sourceMesh[row][col];
91
- if (isNaN(value)) {
92
- console.warn(`NaN value found in source mesh at row: ${row}, col: ${col}`);
93
- }
94
- ;
95
- if (targetIndex >= targetMesh.length) {
96
- console.warn(`⚠️ Target index out of bounds: ${targetIndex} >= ${targetMesh.length}`);
97
- continue;
215
+ // sourceMesh[0][0] is south west corner
216
+ // targetMesh[0][0] is top left corner
217
+ let targetIndex = startY * targetDimensionLength + startX;
218
+ for (let y = 0; y < sourceDimensionLength; y++) {
219
+ // Read from bottom to top (source mesh convention)
220
+ const vertical = sourceMesh[sourceDimensionLength - y - 1];
221
+ for (let x = 0; x < sourceDimensionLength; x++) {
222
+ const value = vertical[x];
223
+ // const currentValue = targetMesh[targetIndex];
224
+ // TODO: investigate why overlapping values are not the same. cancel parent filling
225
+ // if (!isNaN(value) && value !== 0 && currentValue !== 0) {
226
+ // if (currentValue !== value) {
227
+ // console.warn(`Overlapping values are not the same: currentValue=${currentValue}, newValue=${value}`);
228
+ // }
229
+ // }
230
+ if (isNaN(targetMesh[targetIndex])) {
231
+ targetMesh[targetIndex] = value;
98
232
  }
99
- targetMesh[targetIndex] = value;
233
+ targetIndex++;
100
234
  }
235
+ targetIndex += targetDimensionLength - sourceDimensionLength;
101
236
  }
102
237
  }
103
238
  function limitCheck(limit, limitRange = 12) {
104
- const rowRange = limit.maxRow - limit.minRow + 1;
105
- const colRange = limit.maxCol - limit.minCol + 1;
239
+ // TODO: far tiles from camera should be pruned to fit in the limit range
240
+ const rowRange = limit.maxX - limit.minX + 1;
241
+ const colRange = limit.maxY - limit.minY + 1;
106
242
  if (rowRange > limitRange || colRange > limitRange) {
107
243
  console.warn(`Tile limit range exceeded: Row Range = ${rowRange}, Col Range = ${colRange}, Limit Range = ${limitRange}`);
108
244
  throw new Error("Tile limit range exceeded");
109
245
  }
110
246
  }
111
247
  function mergeTiles(tilesMetaData, mergeCount = 8, tileDimensionLength = 5, processLimit = 6) {
112
- const mergedMeshDimLength = tileDimensionLength * mergeCount - (mergeCount - 1);
113
- const processedTiles = new Set();
248
+ const mergedMeshDimLength = calculateMergedMeshDimLength(mergeCount, tileDimensionLength);
249
+ const nearestValuePadding = new NearestValuePadding(tileDimensionLength, mergeCount);
250
+ // Helper to check if a number is between range (inclusive)
114
251
  const result = [];
115
252
  for (let zoom = tilesMetaData.maxLevel; zoom >= tilesMetaData.minLevel; zoom--) {
116
- let processedTileCountFromCurrentLevel = 0;
117
- let processedTileCountFromParentLevel = 0;
118
253
  if (tilesMetaData.maxLevel - zoom >= processLimit) {
119
254
  break;
120
255
  }
121
256
  const limits = tilesMetaData.tileLimitsByZoom.get(zoom);
122
- const mergedMesh = new Float32Array(mergedMeshDimLength * mergedMeshDimLength).fill(0);
257
+ if (!limits)
258
+ continue;
259
+ const mergedMesh = new Float32Array(mergedMeshDimLength * mergedMeshDimLength).fill(NaN);
260
+ // Initialize BBox.
261
+ // We track East (high X) and West (low X) clusters separately for Antimeridian cases.
123
262
  const bboxLimit = {
124
263
  ur: { x: -Infinity, y: -Infinity },
125
264
  ll: { x: Infinity, y: Infinity }
126
265
  };
127
- if (!limits)
128
- continue;
129
- limitCheck(limits, 12);
130
- for (let row = limits.minRow; row <= limits.maxRow; row++) {
131
- for (let col = limits.minCol; col <= limits.maxCol; col++) {
132
- const key = keyMethod(row, col, zoom);
133
- if (processedTiles.has(key)) {
134
- continue;
266
+ // Specific BBox trackers for antimeridian split
267
+ let eastClusterMinX = Infinity; // For the left side of the view (e.g. 170)
268
+ let westClusterMaxX = -Infinity; // For the right side of the view (e.g. -170)
269
+ // limitCheck(limits, 20); // Assumed helper<
270
+ const worldWidth = Math.pow(2, zoom);
271
+ // --- Task 1: Calculate Grid Origin (Centering) ---
272
+ // We determine where the top-left of our mergeCount x mergeCount grid starts in tile coordinates.
273
+ let originX = limits.minX;
274
+ let originY = limits.minY;
275
+ const rangeX = limits.antimeridian
276
+ ? (worldWidth - limits.minX) + limits.maxX + 1
277
+ : limits.maxX - limits.minX + 1;
278
+ const rangeY = limits.maxY - limits.minY + 1;
279
+ // If the data is wider than the mesh, center it using centerX
280
+ if (rangeX > mergeCount && limits.centerX !== undefined) {
281
+ originX = Math.floor(limits.centerX - (mergeCount / 2));
282
+ }
283
+ // If the data is taller than the mesh, center it using centerY
284
+ if (rangeY > mergeCount && limits.centerY !== undefined) {
285
+ originY = Math.floor(limits.centerY - (mergeCount / 2));
286
+ }
287
+ // --- Task 2: Iterate Grid Slots ---
288
+ // Instead of iterating tile coordinates, we iterate the target grid slots (0..mergeCount)
289
+ // and calculate which tile belongs there.
290
+ for (let i = 0; i < mergeCount; i++) {
291
+ for (let j = 0; j < mergeCount; j++) {
292
+ // Calculate actual Tile Coordinates
293
+ // Handle X Wrapping for Antimeridian
294
+ let tileX = (originX + i);
295
+ // JS modulo of negative numbers behaves oddly, ensure positive wrap
296
+ tileX = ((tileX % worldWidth) + worldWidth) % worldWidth;
297
+ const tileY = originY + j;
298
+ // --- Validity Check ---
299
+ // Check if this specific tileX/tileY is actually part of the visible map data
300
+ let isValidX = false;
301
+ if (limits.antimeridian) {
302
+ isValidX = tileX >= limits.minX || tileX <= limits.maxX;
303
+ }
304
+ else {
305
+ isValidX = tileX >= limits.minX && tileX <= limits.maxX;
135
306
  }
307
+ const isValidY = tileY >= limits.minY && tileY <= limits.maxY;
308
+ if (!isValidX || !isValidY)
309
+ continue;
310
+ const key = keyMethod(tileX, tileY, zoom);
136
311
  const tile = tilesMetaData.tileMap.get(key);
312
+ // Calculate mesh offset (target position in pixels/floats)
313
+ const meshOffsetX = i * (tileDimensionLength - 1);
314
+ const meshOffsetY = j * (tileDimensionLength - 1);
137
315
  if (tile) {
138
- // move tile mesh to merged mesh
139
- moveMeshToMergedMesh(mergedMesh, mergedMeshDimLength, tile.mesh, tileDimensionLength, (row - limits.minRow) * (tileDimensionLength - 1), (col - limits.minCol) * (tileDimensionLength - 1));
140
- // moveMeshToMergedMesh2(
141
- // mergedMesh, mergedMeshDimLength,
142
- // (row + col) % 2 === 0 ? 0.1 : 0,
143
- // tileDimensionLength,
144
- // (row - limits.minRow) * (tileDimensionLength - 1), (col - limits.minCol) * (tileDimensionLength - 1)
145
- // );
146
- processedTiles.add(key);
147
- processedTileCountFromCurrentLevel++;
148
- // update bbox
316
+ // 1. Direct Tile Found
317
+ nearestValuePadding.insert(tile.x, tile.y); // Using original coordinates for padding logic
318
+ moveMeshToMergedMesh(mergedMesh, mergedMeshDimLength, tile.mesh, tileDimensionLength, meshOffsetX, meshOffsetY);
319
+ // Update BBox Limits
320
+ // We simply expand the LL/UR.
321
+ // Post-processing will fix the inverted X for antimeridian.
149
322
  if (tile.bbox.ll.x < bboxLimit.ll.x)
150
323
  bboxLimit.ll.x = tile.bbox.ll.x;
151
324
  if (tile.bbox.ll.y < bboxLimit.ll.y)
@@ -154,145 +327,103 @@ function mergeTiles(tilesMetaData, mergeCount = 8, tileDimensionLength = 5, proc
154
327
  bboxLimit.ur.x = tile.bbox.ur.x;
155
328
  if (tile.bbox.ur.y > bboxLimit.ur.y)
156
329
  bboxLimit.ur.y = tile.bbox.ur.y;
157
- /**
158
- } else {
159
- // try to find parent tile
160
- const parent = calculateParentTile(row, col, zoom);
161
- const parentKey = keyMethod(parent.row, parent.column, parent.level);
330
+ // Track clusters for antimeridian split
331
+ // High X values (East Cluster) -> Left side of visual boundary
332
+ // Low X values (West Cluster) -> Right side of visual boundary
333
+ if (limits.antimeridian) {
334
+ if (tileX >= limits.minX) {
335
+ if (tile.bbox.ll.x < eastClusterMinX)
336
+ eastClusterMinX = tile.bbox.ll.x;
337
+ }
338
+ else {
339
+ if (tile.bbox.ur.x > westClusterMaxX)
340
+ westClusterMaxX = tile.bbox.ur.x;
341
+ }
342
+ }
343
+ }
344
+ else {
345
+ // 2. Parent Tile Fallback
346
+ const parentTileCoord = calculateParentTile(tileX, tileY, zoom);
347
+ const parentKey = keyMethod(parentTileCoord.x, parentTileCoord.y, parentTileCoord.level);
162
348
  const parentTile = tilesMetaData.tileMap.get(parentKey);
163
-
164
349
  if (parentTile) {
165
- // Parent's 4 children at current zoom level
166
- const parentTopLeftChildRow = parent.row * 2;
167
- const parentTopLeftChildCol = parent.column * 2;
168
- const topLeftChildKey = keyMethod(parentTopLeftChildRow, parentTopLeftChildCol, zoom);
169
-
170
- // Only process parent once
171
- if (!processedTiles.has(topLeftChildKey)) {
172
- // Check if parent's area is within or overlaps the current limits
173
- const parentBottomRightChildRow = parentTopLeftChildRow + 1;
174
- const parentBottomRightChildCol = parentTopLeftChildCol + 1;
175
-
176
- // Check if parent's children overlap with current zoom's limits
177
- if (parentTopLeftChildRow > limits.maxRow ||
178
- parentBottomRightChildRow < limits.minRow ||
179
- parentTopLeftChildCol > limits.maxCol ||
180
- parentBottomRightChildCol < limits.minCol) {
181
- // Parent doesn't overlap, skip
182
- processedTiles.add(key);
183
- continue;
350
+ const populatedMesh = populateTileIntoHigherZoomLevel(parentTile.mesh, tileDimensionLength, tileDimensionLength * 2 - 1);
351
+ // Adjust offset for parent logic
352
+ // If current tile is odd (right/bottom), the parent mesh drawing needs to shift back
353
+ // because 'populatedMesh' covers 2x2.
354
+ const parentDrawOffsetX = meshOffsetX - (tileX % 2) * (tileDimensionLength - 1);
355
+ const parentDrawOffsetY = meshOffsetY - (tileY % 2) * (tileDimensionLength - 1);
356
+ moveMeshToMergedMesh(mergedMesh, mergedMeshDimLength, populatedMesh, tileDimensionLength * 2 - 1, parentDrawOffsetX, parentDrawOffsetY);
357
+ // Padding logic for parents
358
+ const xP = parentTile.x * 2;
359
+ const yP = parentTile.y * 2;
360
+ for (let dx = 0; dx < 2; dx++) {
361
+ for (let dy = 0; dy < 2; dy++) {
362
+ nearestValuePadding.insert(xP + dx, yP + dy);
184
363
  }
185
-
186
- // Upscale parent to cover all 4 children
187
- const parentTileUpscaledMesh = populateTileIntoHigherZoomLevel(
188
- parentTile.mesh,
189
- tileDimensionLength,
190
- tileDimensionLength * 2 - 1
191
- );
192
-
193
- // Calculate destination position (parent's top-left child position)
194
- // Clamp to limits to handle edge cases
195
- const actualStartRow = Math.max(parentTopLeftChildRow, limits.minRow);
196
- const actualStartCol = Math.max(parentTopLeftChildCol, limits.minCol);
197
-
198
- const destRow = (actualStartRow - limits.minRow) * (tileDimensionLength - 1);
199
- const destCol = (actualStartCol - limits.minCol) * (tileDimensionLength - 1);
200
-
201
- // Calculate source offset if parent starts before limits
202
- const srcRowOffset = (actualStartRow - parentTopLeftChildRow) * (tileDimensionLength - 1);
203
- const srcColOffset = (actualStartCol - parentTopLeftChildCol) * (tileDimensionLength - 1);
204
-
205
- // Calculate how much to copy
206
- const actualEndRow = Math.min(parentBottomRightChildRow, limits.maxRow);
207
- const actualEndCol = Math.min(parentBottomRightChildCol, limits.maxCol);
208
-
209
- const copyRows = (actualEndRow - actualStartRow + 1) * (tileDimensionLength - 1);
210
- const copyCols = (actualEndCol - actualStartCol + 1) * (tileDimensionLength - 1);
211
-
212
- // Copy only the visible portion
213
- moveMeshToMergedMeshPartial(
214
- mergedMesh,
215
- mergedMeshDimLength,
216
- parentTileUpscaledMesh,
217
- tileDimensionLength * 2 - 1,
218
- destRow,
219
- destCol,
220
- srcRowOffset,
221
- srcColOffset,
222
- copyRows,
223
- copyCols
224
- );
225
-
226
- // Mark all 4 child positions as processed (even if out of bounds)
227
- for (let dr = 0; dr < 2; dr++) {
228
- for (let dc = 0; dc < 2; dc++) {
229
- const childRow = parentTopLeftChildRow + dr;
230
- const childCol = parentTopLeftChildCol + dc;
231
- const childKey = keyMethod(childRow, childCol, zoom);
232
- processedTiles.add(childKey);
364
+ }
365
+ }
366
+ else {
367
+ // 3. Children Tile Fallback
368
+ const childrenTiles = [];
369
+ let anyChildren = 0;
370
+ for (let dx = 0; dx < 2; dx++) {
371
+ for (let dy = 0; dy < 2; dy++) {
372
+ const childX = tileX * 2 + dx;
373
+ const childY = tileY * 2 + dy;
374
+ const childKey = keyMethod(childX, childY, zoom + 1);
375
+ const childTile = tilesMetaData.tileMap.get(childKey);
376
+ if (childTile) {
377
+ anyChildren++;
378
+ childrenTiles.push(childTile.mesh);
379
+ }
380
+ else {
381
+ childrenTiles.push(undefined);
233
382
  }
234
383
  }
235
-
236
- processedTileCountFromParentLevel++;
237
-
238
- // Update bbox (use actual parent bbox, not child bbox)
239
- if (parentTile.bbox.ll.x < bboxLimit.ll.x) bboxLimit.ll.x = parentTile.bbox.ll.x;
240
- if (parentTile.bbox.ll.y < bboxLimit.ll.y) bboxLimit.ll.y = parentTile.bbox.ll.y;
241
- if (parentTile.bbox.ur.x > bboxLimit.ur.x) bboxLimit.ur.x = parentTile.bbox.ur.x;
242
- if (parentTile.bbox.ur.y > bboxLimit.ur.y) bboxLimit.ur.y = parentTile.bbox.ur.y;
243
- } else {
244
- // Already processed via parent
245
- processedTiles.add(key);
246
384
  }
247
- } else {
248
- // No parent available
249
- processedTiles.add(key);
385
+ if (anyChildren > 0) {
386
+ nearestValuePadding.insert(tileX, tileY);
387
+ fillFromChildren(mergedMesh, mergedMeshDimLength, childrenTiles, tileDimensionLength, meshOffsetX, meshOffsetY);
388
+ }
250
389
  }
251
-
252
- */
253
390
  }
254
391
  }
255
392
  }
256
- const rowRatio = (limits.maxRow - limits.minRow + 1) / mergeCount;
257
- const colRatio = (limits.maxCol - limits.minCol + 1) / mergeCount;
258
- // console.log(`Zoom ${zoom}: Processed ${processedTileCountFromCurrentLevel} from current level, ${processedTileCountFromParentLevel} from parent level. Coverage: ${(rowRatio * 100).toFixed(1)}% x ${(colRatio * 100).toFixed(1)}%`);
259
- result.push({ mesh: mergedMesh, bbox: bboxLimit, zoom: zoom, coverRatio: { x: rowRatio, y: colRatio } });
393
+ // Post-Processing BBox for Antimeridian
394
+ if (limits.antimeridian) {
395
+ // Task: bbox.ll should contain lower-left of East Cluster, bbox.ur should contain upper-right of West Cluster
396
+ // This creates the condition ur.x < ll.x (e.g. 170 to -170)
397
+ // Only update if we actually found tiles in those clusters
398
+ if (eastClusterMinX !== Infinity)
399
+ bboxLimit.ll.x = eastClusterMinX;
400
+ if (westClusterMaxX !== -Infinity)
401
+ bboxLimit.ur.x = westClusterMaxX;
402
+ // console.log("Antimeridian BBox adjusted:", bboxLimit);
403
+ }
404
+ // We pad the merged mesh based on the VALID range we iterated.
405
+ // Since we iterate 0..mergeCount, the indices are implicitly 0..mergeCount
406
+ // However, the clamp function usually expects absolute coordinates.
407
+ // Given the new "Grid" approach, the mesh is always locally 0 to mergeCount in valid data.
408
+ // We pass the grid-relative limits to clamp.
409
+ nearestValuePadding.clamp(mergedMesh, 0, 0, mergeCount, mergeCount);
410
+ nearestValuePadding.clear();
411
+ // Calculate Cover Ratio
412
+ // How much of the mesh grid (mergeCount) is covered by actual data range?
413
+ const currentWidth = limits.antimeridian ? rangeX : (limits.maxX - limits.minX + 1);
414
+ const currentHeight = limits.maxY - limits.minY + 1;
415
+ const usedWidth = Math.min(mergeCount, currentWidth);
416
+ const usedHeight = Math.min(mergeCount, currentHeight);
417
+ const xRatio = calculateMergedMeshDimLength(usedWidth, tileDimensionLength) / mergedMeshDimLength;
418
+ const yRatio = calculateMergedMeshDimLength(usedHeight, tileDimensionLength) / mergedMeshDimLength;
419
+ result.push({ mesh: mergedMesh, bbox: bboxLimit, zoom: zoom, coverRatio: { x: xRatio, y: yRatio } });
260
420
  }
261
421
  return result;
262
422
  }
263
- export function mergeMeshes(tiles, mergeCount = 12, tileDimensionLength = 5, processLimit = 6) {
423
+ export function mergeMeshes(tiles, mergeCount = 12, tileDimensionLength = 5, processLimit = 6, globe) {
264
424
  // filter out tiles with NaN values
265
425
  // return returnTop6tiles(tiles);
266
- const tilesMetaData = createMapAndMetaData(tiles);
426
+ const tilesMetaData = createMapAndMetaData(tiles, globe);
267
427
  const mergedTiles = mergeTiles(tilesMetaData, mergeCount, tileDimensionLength, processLimit);
268
428
  return mergedTiles;
269
429
  }
270
- function returnTop6tiles(tiles) {
271
- const tilesMetaData = createMapAndMetaData(tiles);
272
- const hightestZoom = tilesMetaData.maxLevel;
273
- const result = [];
274
- let counter = 6;
275
- function tileToMergedTileInfo(tile) {
276
- const mesh = new Float32Array(tile.mesh[0].length * tile.mesh[0].length);
277
- for (let row = 0; row < tile.mesh[0].length; row++) {
278
- for (let col = 0; col < tile.mesh[0].length; col++) {
279
- mesh[row * tile.mesh[0].length + col] = tile.mesh[0][row * tile.mesh[0].length + col];
280
- }
281
- }
282
- return {
283
- mesh: mesh,
284
- zoom: tile.level,
285
- bbox: tile.bbox,
286
- coverRatio: { x: 1, y: 1 },
287
- };
288
- }
289
- for (const tile of tiles) {
290
- if (counter === 0)
291
- break;
292
- if (tile.level === hightestZoom) {
293
- result.push(tileToMergedTileInfo(tile));
294
- counter--;
295
- }
296
- }
297
- return result;
298
- }