hilbert-chart-3d 0.4.1 → 0.6.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.
@@ -1,4 +1,4 @@
1
- // Version 0.4.1 hilbert-chart-3d - https://github.com/vasturiano/hilbert-chart-3d
1
+ // Version 0.6.0 hilbert-chart-3d - https://github.com/vasturiano/hilbert-chart-3d
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4
4
  typeof define === 'function' && define.amd ? define(factory) :
@@ -148859,7 +148859,7 @@ var<${access}> ${ name } : ${ structName };`;
148859
148859
  let topObject = null;
148860
148860
  if (state.hoverDuringDrag || !state.isPointerDragging) {
148861
148861
  const intersects = this.intersectingObjects(state.pointerPos.x, state.pointerPos.y);
148862
- state.hoverOrderComparator && intersects.sort((a, b) => state.hoverOrderComparator(a.object, b.object));
148862
+ state.hoverOrderComparator && intersects.sort((a, b) => state.hoverOrderComparator(a.object, b.object, a, b));
148863
148863
  const topIntersect = intersects.find(d => state.hoverFilter(d.object)) || null;
148864
148864
  topObject = topIntersect ? topIntersect.object : null;
148865
148865
  state.intersection = topIntersect || null;
@@ -149259,14 +149259,14 @@ var<${access}> ${ name } : ${ structName };`;
149259
149259
  return typeof value === 'function' && Function.prototype.toString.call(value).startsWith('class');
149260
149260
  }
149261
149261
 
149262
- const CHILD_PERMUTATIONS$1 = [[0, 3, 4, 7, 6, 5, 2, 1], [0, 7, 6, 1, 2, 5, 4, 3], [0, 7, 6, 1, 2, 5, 4, 3], [2, 3, 0, 1, 6, 7, 4, 5], [2, 3, 0, 1, 6, 7, 4, 5], [4, 3, 2, 5, 6, 1, 0, 7], [4, 3, 2, 5, 6, 1, 0, 7], [6, 5, 2, 1, 0, 3, 4, 7]];
149262
+ const CHILD_PERMUTATIONS = [[0, 3, 4, 7, 6, 5, 2, 1], [0, 7, 6, 1, 2, 5, 4, 3], [0, 7, 6, 1, 2, 5, 4, 3], [2, 3, 0, 1, 6, 7, 4, 5], [2, 3, 0, 1, 6, 7, 4, 5], [4, 3, 2, 5, 6, 1, 0, 7], [4, 3, 2, 5, 6, 1, 0, 7], [6, 5, 2, 1, 0, 3, 4, 7]];
149263
149263
  const ORIENTATIONS = [[0, 1, 2, 3, 4, 5, 6, 7]];
149264
149264
  const ORIENTATION_TRANSITIONS = [];
149265
149265
  const ORIENTATION_IDS = new Map([[ORIENTATIONS[0].join(''), 0]]);
149266
149266
  for (let i = 0; i < ORIENTATIONS.length; i++) {
149267
149267
  const orientation = ORIENTATIONS[i];
149268
149268
  const transitions = [];
149269
- for (const permutation of CHILD_PERMUTATIONS$1) {
149269
+ for (const permutation of CHILD_PERMUTATIONS) {
149270
149270
  const childOrientation = permutation.map(index => orientation[index]);
149271
149271
  const key = childOrientation.join('');
149272
149272
  let id = ORIENTATION_IDS.get(key);
@@ -152562,33 +152562,13 @@ var<${access}> ${ name } : ${ structName };`;
152562
152562
  const GLYPH_COUNT = 256;
152563
152563
  const GLYPHS_PER_ROW = 16;
152564
152564
  const GLYPH_SIZE = 64;
152565
- const MIN_LABEL_FONT_SIZE = 0.05;
152566
152565
  const MAX_LABEL_FONT_SIZE = 0.8;
152567
- const MAX_CUBE_LABEL_FONT_SIZE = 0.5;
152566
+ const MIN_LABEL_FONT_SIZE = 0.05;
152568
152567
  const MAX_LABEL_WIDTH = 0.92;
152569
152568
  const LABEL_CHARACTER_ADVANCE = 0.8;
152570
- function createLabelAtlas(data, labelAccessor, labelColorAccessor) {
152571
- const labelIds = new Map();
152572
- const labels = new WeakMap();
152573
- data.forEach(d => {
152574
- const label = labelAccessor(d);
152575
- const color = labelColorAccessor(d);
152576
- if (!label || !color) return;
152577
- const characters = Array.from(String(label));
152578
- const text = characters.length > MAX_LABEL_CHARS ? `${characters.slice(0, MAX_LABEL_CHARS - 3).join('')}...` : characters.join('');
152579
- let id = labelIds.get(text);
152580
- if (id === undefined) {
152581
- id = labelIds.size;
152582
- labelIds.set(text, id);
152583
- }
152584
- labels.set(d, {
152585
- id,
152586
- length: Array.from(text).length,
152587
- text,
152588
- color
152589
- });
152590
- });
152591
- if (!labelIds.size) return null;
152569
+ let glyphTexture;
152570
+ function getGlyphTexture() {
152571
+ if (glyphTexture) return glyphTexture;
152592
152572
  const glyphCanvas = document.createElement('canvas');
152593
152573
  glyphCanvas.width = GLYPHS_PER_ROW * GLYPH_SIZE;
152594
152574
  glyphCanvas.height = GLYPHS_PER_ROW * GLYPH_SIZE;
@@ -152605,383 +152585,211 @@ var<${access}> ${ name } : ${ structName };`;
152605
152585
  glyphContext.fillStyle = '#fff';
152606
152586
  glyphContext.fillText(character, x, y);
152607
152587
  }
152608
- const glyphTexture = new CanvasTexture(glyphCanvas);
152588
+ glyphTexture = new CanvasTexture(glyphCanvas);
152609
152589
  glyphTexture.magFilter = LinearFilter;
152610
152590
  glyphTexture.minFilter = LinearFilter;
152611
152591
  glyphTexture.colorSpace = SRGBColorSpace;
152612
- const labelsPerRow = 128;
152613
- const textureWidth = labelsPerRow * MAX_LABEL_CHARS;
152614
- const textureHeight = Math.ceil(labelIds.size / labelsPerRow);
152615
- const labelData = new Uint8Array(textureWidth * textureHeight * 4);
152616
- labelIds.forEach((id, text) => {
152617
- Array.from(text).forEach((character, charIndex) => {
152618
- const code = character.codePointAt(0);
152619
- const x = id % labelsPerRow * MAX_LABEL_CHARS + charIndex;
152620
- const y = Math.floor(id / labelsPerRow);
152621
- const supported = code >= 32 && code <= 255 && (code < 127 || code >= 160);
152622
- labelData[(y * textureWidth + x) * 4] = supported ? code : 63;
152623
- });
152624
- });
152625
- const labelTexture = new DataTexture(labelData, textureWidth, textureHeight, RGBAFormat, UnsignedByteType);
152626
- labelTexture.magFilter = NearestFilter;
152627
- labelTexture.minFilter = NearestFilter;
152628
- labelTexture.generateMipmaps = false;
152629
- labelTexture.needsUpdate = true;
152630
- return {
152631
- labels,
152632
- glyphTexture,
152633
- labelTexture,
152634
- labelsPerRow,
152635
- labelCount: labelIds.size
152636
- };
152637
- }
152638
- function createLabelMaterial(color, labelAtlas) {
152639
- const material = new MeshLambertMaterial();
152640
- const opacity = colorAlpha(color);
152641
- material.color.set(colorStr2Hex(color));
152642
- material.transparent = opacity < 1;
152643
- material.opacity = opacity;
152644
- if (labelAtlas) {
152645
- material.onBeforeCompile = shader => {
152646
- shader.uniforms.labelGlyphTexture = {
152647
- value: labelAtlas.glyphTexture
152648
- };
152649
- shader.uniforms.labelDataTexture = {
152650
- value: labelAtlas.labelTexture
152651
- };
152652
- shader.uniforms.labelDataTextureSize = {
152653
- value: new Vector2(labelAtlas.labelTexture.image.width, labelAtlas.labelTexture.image.height)
152654
- };
152655
- shader.uniforms.labelLabelsPerRow = {
152656
- value: labelAtlas.labelsPerRow
152657
- };
152658
- shader.vertexShader = shader.vertexShader.replace('#include <common>', `#include <common>
152659
- attribute float hilbertLabelId;
152660
- attribute float hilbertLabelLength;
152661
- attribute float hilbertLabelAspect;
152662
- attribute float hilbertLabelMaxFontSize;
152663
- attribute float hilbertLabelReverse;
152664
- attribute vec4 hilbertLabelColor;
152665
- varying vec2 vHilbertLabelUv;
152666
- varying float vHilbertLabelId;
152667
- varying float vHilbertLabelLength;
152668
- varying float vHilbertLabelAspect;
152669
- varying float vHilbertLabelMaxFontSize;
152670
- varying float vHilbertLabelReverse;
152671
- varying vec4 vHilbertLabelColor;`).replace('#include <begin_vertex>', `#include <begin_vertex>
152672
- vHilbertLabelUv = uv;
152673
- vHilbertLabelId = hilbertLabelId;
152674
- vHilbertLabelLength = hilbertLabelLength;
152675
- vHilbertLabelAspect = hilbertLabelAspect;
152676
- vHilbertLabelMaxFontSize = hilbertLabelMaxFontSize;
152677
- vHilbertLabelReverse = hilbertLabelReverse;
152678
- vHilbertLabelColor = hilbertLabelColor;`);
152679
- shader.fragmentShader = shader.fragmentShader.replace('#include <common>', `#include <common>
152680
- uniform sampler2D labelGlyphTexture;
152681
- uniform sampler2D labelDataTexture;
152682
- uniform vec2 labelDataTextureSize;
152683
- uniform float labelLabelsPerRow;
152684
- varying vec2 vHilbertLabelUv;
152685
- varying float vHilbertLabelId;
152686
- varying float vHilbertLabelLength;
152687
- varying float vHilbertLabelAspect;
152688
- varying float vHilbertLabelMaxFontSize;
152689
- varying float vHilbertLabelReverse;
152690
- varying vec4 vHilbertLabelColor;`).replace('#include <map_fragment>', `#include <map_fragment>
152691
- if (vHilbertLabelId >= 0.0 && vHilbertLabelUv.x >= 0.0 && vHilbertLabelUv.x <= 1.0) {
152692
- float aspect = max(vHilbertLabelAspect, 0.001);
152693
- float visibleLength = vHilbertLabelLength;
152694
- float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152695
- float maxFontSize = min(${MAX_LABEL_FONT_SIZE.toFixed(2)}, vHilbertLabelMaxFontSize);
152696
- float fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
152697
- bool isTruncated = fontSize < ${MIN_LABEL_FONT_SIZE.toFixed(2)};
152698
- if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / ${MIN_LABEL_FONT_SIZE.toFixed(2)} - 1.0) / ${LABEL_CHARACTER_ADVANCE.toFixed(2)}) + 1.0));
152699
- textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152700
- fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
152701
- float characterSize = fontSize / aspect;
152702
- float characterAdvance = characterSize * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152703
- float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);
152704
- float textStart = (1.0 - textWidth) * 0.5;
152705
- float textPosition = vHilbertLabelUv.x - textStart;
152706
- if (textPosition >= 0.0 && textPosition < textWidth) {
152707
- float glyphVerticalPosition = (vHilbertLabelUv.y - 0.5) / max(fontSize, 0.001) + 0.5;
152708
- if (glyphVerticalPosition >= 0.0 && glyphVerticalPosition <= 1.0) {
152709
- float charPosition = textPosition / max(characterAdvance, 0.001);
152710
- float charSlot = floor(charPosition);
152711
- float charIndex = mix(charSlot, visibleLength - 1.0 - charSlot, vHilbertLabelReverse);
152712
- float glyphHorizontalPosition = (textPosition - charSlot * characterAdvance) / max(characterSize, 0.001);
152713
- glyphHorizontalPosition = mix(glyphHorizontalPosition, 1.0 - glyphHorizontalPosition, vHilbertLabelReverse);
152714
- float labelRow = floor(vHilbertLabelId / labelLabelsPerRow);
152715
- float labelColumn = mod(vHilbertLabelId, labelLabelsPerRow);
152716
- vec2 dataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + charIndex, labelRow) + 0.5) / labelDataTextureSize;
152717
- float charCode = floor(texture2D(labelDataTexture, dataUv).r * 255.0 + 0.5);
152718
- if (isTruncated && charIndex >= visibleLength - 3.0) charCode = 46.0;
152719
- vec2 glyphCell = vec2(mod(charCode, 16.0), floor(charCode / 16.0));
152720
- vec2 glyphUv = vec2(0.015625 + clamp(glyphHorizontalPosition, 0.0, 1.0) * 0.96875, 0.015625 + (1.0 - glyphVerticalPosition) * 0.96875);
152721
- vec2 glyphAtlasUv = vec2(glyphCell.x + glyphUv.x, 16.0 - glyphCell.y - glyphUv.y) / 16.0;
152722
- float glyphCoverage = texture2D(labelGlyphTexture, glyphAtlasUv).a;
152723
- float previousCharSlot = charSlot - 1.0;
152724
- float previousCharIndex = mix(previousCharSlot, visibleLength - 1.0 - previousCharSlot, vHilbertLabelReverse);
152725
- float previousGlyphPosition = (textPosition - previousCharSlot * characterAdvance) / max(characterSize, 0.001);
152726
- previousGlyphPosition = mix(previousGlyphPosition, 1.0 - previousGlyphPosition, vHilbertLabelReverse);
152727
- if (charSlot > 0.0 && previousGlyphPosition < 1.0) {
152728
- vec2 previousDataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + previousCharIndex, labelRow) + 0.5) / labelDataTextureSize;
152729
- float previousCharCode = floor(texture2D(labelDataTexture, previousDataUv).r * 255.0 + 0.5);
152730
- if (isTruncated && previousCharIndex >= visibleLength - 3.0) previousCharCode = 46.0;
152731
- vec2 previousGlyphCell = vec2(mod(previousCharCode, 16.0), floor(previousCharCode / 16.0));
152732
- vec2 previousGlyphAtlasUv = vec2(
152733
- previousGlyphCell.x + 0.015625 + clamp(previousGlyphPosition, 0.0, 1.0) * 0.96875,
152734
- 16.0 - previousGlyphCell.y - glyphUv.y
152735
- ) / 16.0;
152736
- glyphCoverage = max(glyphCoverage, texture2D(labelGlyphTexture, previousGlyphAtlasUv).a);
152737
- }
152738
- float glyphAlpha = glyphCoverage * vHilbertLabelColor.a;
152739
- diffuseColor.rgb = mix(diffuseColor.rgb, vHilbertLabelColor.rgb, glyphAlpha);
152740
- }
152741
- }
152742
- }`);
152743
- };
152744
- material.customProgramCacheKey = () => 'three-hilbert-label-glyph-atlas';
152745
- }
152746
- return material;
152747
- }
152748
- function addLabelAttributes(geometry, records, instanced = false) {
152749
- const vertexCount = geometry.getAttribute('position').count;
152750
- const count = instanced ? records.length : vertexCount;
152751
- const makeAttribute = (array, itemSize) => instanced ? new InstancedBufferAttribute(array, itemSize) : new Float32BufferAttribute(array, itemSize);
152752
- const ids = new Float32Array(count);
152753
- const lengths = new Float32Array(count);
152754
- const colors = new Float32Array(count * 4);
152755
- records.forEach(({
152756
- info
152757
- }, index) => {
152758
- const labelColor = info?.color;
152759
- const color = new Color$1(labelColor ? colorStr2Hex(labelColor) : 0xffffff);
152760
- const start = instanced ? index : 0;
152761
- const end = instanced ? index + 1 : count;
152762
- for (let i = start; i < end; i++) {
152763
- ids[i] = info ? info.id : -1;
152764
- lengths[i] = info ? info.length : 0;
152765
- colors[i * 4] = color.r;
152766
- colors[i * 4 + 1] = color.g;
152767
- colors[i * 4 + 2] = color.b;
152768
- colors[i * 4 + 3] = labelColor ? colorAlpha(labelColor) : 0;
152769
- }
152770
- });
152771
- geometry.setAttribute('hilbertLabelId', makeAttribute(ids, 1));
152772
- geometry.setAttribute('hilbertLabelLength', makeAttribute(lengths, 1));
152773
- geometry.setAttribute('hilbertLabelColor', makeAttribute(colors, 4));
152774
- }
152775
- function mapLabelUVs(geometry) {
152776
- const uvs = geometry.getAttribute('uv');
152777
- if (!uvs) return;
152778
- const positions = geometry.getAttribute('position');
152779
- const points = geometry.parameters?.points;
152780
- const labelAspects = new Float32Array(uvs.count);
152781
- const labelMaxFontSizes = new Float32Array(uvs.count).fill(MAX_LABEL_FONT_SIZE);
152782
- const labelReverse = new Float32Array(uvs.count);
152783
- const uTurnInteriorFaces = getUTurnInteriorFaces(points, positions);
152784
- const sideQuads = [];
152785
- if (points?.length > 1) {
152786
- const sideQuadCount = (points.length - 1) * 4;
152787
- for (let vertex = 0; vertex + 3 < uvs.count && vertex / 4 < sideQuadCount; vertex += 4) {
152788
- let minU = Infinity;
152789
- let maxU = -Infinity;
152790
- let minV = Infinity;
152791
- let maxV = -Infinity;
152792
- for (let corner = 0; corner < 4; corner++) {
152793
- minU = Math.min(minU, uvs.getX(vertex + corner));
152794
- maxU = Math.max(maxU, uvs.getX(vertex + corner));
152795
- minV = Math.min(minV, uvs.getY(vertex + corner));
152796
- maxV = Math.max(maxV, uvs.getY(vertex + corner));
152592
+ return glyphTexture;
152593
+ }
152594
+ class LabelAtlas {
152595
+ constructor(data, labelAccessor, labelColorAccessor) {
152596
+ const labelIds = new Map();
152597
+ this.labels = new WeakMap();
152598
+ this.materialCache = new Map();
152599
+ data.forEach(d => {
152600
+ const label = labelAccessor(d);
152601
+ const color = labelColorAccessor(d);
152602
+ if (!label || !color) return;
152603
+ const characters = Array.from(String(label));
152604
+ const text = characters.length > MAX_LABEL_CHARS ? `${characters.slice(0, MAX_LABEL_CHARS - 3).join('')}...` : characters.join('');
152605
+ let id = labelIds.get(text);
152606
+ if (id === undefined) {
152607
+ id = labelIds.size;
152608
+ labelIds.set(text, id);
152797
152609
  }
152798
- if (maxU <= minU || maxV === minV) continue;
152799
- sideQuads.push({
152800
- vertex,
152801
- minU,
152802
- maxU,
152803
- minV,
152804
- maxV
152610
+ this.labels.set(d, {
152611
+ id,
152612
+ length: Array.from(text).length,
152613
+ text,
152614
+ color
152805
152615
  });
152806
- }
152807
- } else {
152808
- for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
152809
- let minU = Infinity;
152810
- let maxU = -Infinity;
152811
- let minV = Infinity;
152812
- let maxV = -Infinity;
152813
- for (let corner = 0; corner < 4; corner++) {
152814
- minU = Math.min(minU, uvs.getX(vertex + corner));
152815
- maxU = Math.max(maxU, uvs.getX(vertex + corner));
152816
- minV = Math.min(minV, uvs.getY(vertex + corner));
152817
- maxV = Math.max(maxV, uvs.getY(vertex + corner));
152818
- }
152819
- if (Math.abs(maxU - minU - 0.25) > 0.01 || maxV <= minV) continue;
152820
- sideQuads.push({
152821
- vertex,
152822
- minU,
152823
- maxU,
152824
- minV,
152825
- maxV
152616
+ });
152617
+ this.labelCount = labelIds.size;
152618
+ if (!this.labelCount) return;
152619
+ this.glyphTexture = getGlyphTexture();
152620
+ this.labelsPerRow = 128;
152621
+ const textureWidth = this.labelsPerRow * MAX_LABEL_CHARS;
152622
+ const textureHeight = Math.ceil(labelIds.size / this.labelsPerRow);
152623
+ const labelData = new Uint8Array(textureWidth * textureHeight * 4);
152624
+ labelIds.forEach((id, text) => {
152625
+ Array.from(text).forEach((character, charIndex) => {
152626
+ const code = character.codePointAt(0);
152627
+ const x = id % this.labelsPerRow * MAX_LABEL_CHARS + charIndex;
152628
+ const y = Math.floor(id / this.labelsPerRow);
152629
+ const supported = code >= 32 && code <= 255 && (code < 127 || code >= 160);
152630
+ labelData[(y * textureWidth + x) * 4] = supported ? code : 63;
152826
152631
  });
152827
- }
152828
- }
152829
- const sideQuadVertices = new Set(sideQuads.map(({
152830
- vertex
152831
- }) => vertex));
152832
- sideQuads.forEach(({
152833
- vertex,
152834
- minU,
152835
- maxU,
152836
- minV,
152837
- maxV
152838
- }, index) => {
152839
- for (let corner = 0; corner < 4; corner++) labelReverse[vertex + corner] = 1;
152840
- if (uTurnInteriorFaces.has(vertex)) {
152841
- for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
152842
- return;
152843
- }
152844
- if (positions && !isRectangularFace(positions, vertex)) {
152845
- for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
152846
- return;
152847
- }
152848
- const pathSegment = Math.floor(index / 4);
152849
- const startPoint = points?.[pathSegment];
152850
- const endPoint = points?.[pathSegment + 1];
152851
- const dx = endPoint ? endPoint.x - startPoint.x : 0;
152852
- const dy = endPoint ? endPoint.y - startPoint.y : 0;
152853
- const dz = endPoint ? endPoint.z - startPoint.z : 0;
152854
- const segmentLength = Math.hypot(dx, dy, dz);
152855
- const projectedDistances = Array.from({
152856
- length: 4
152857
- }, (_, corner) => {
152858
- const positionIndex = vertex + corner;
152859
- return positions && startPoint && segmentLength ? ((positions.getX(positionIndex) - startPoint.x) * dx + (positions.getY(positionIndex) - startPoint.y) * dy + (positions.getZ(positionIndex) - startPoint.z) * dz) / segmentLength : segmentLength * (uvs.getY(positionIndex) - minV) / (maxV - minV);
152860
152632
  });
152861
- const minDistance = Math.min(...projectedDistances);
152862
- const maxDistance = Math.max(...projectedDistances);
152863
- const labelLength = maxDistance - minDistance;
152864
- const sideWidth = positions ? new Vector3().fromBufferAttribute(positions, vertex).distanceTo(new Vector3().fromBufferAttribute(positions, vertex + 1)) : 0;
152865
- if (sideWidth > 0) {
152866
- for (let corner = 0; corner < 4; corner++) labelAspects[vertex + corner] = labelLength / sideWidth;
152867
- }
152868
- if (labelLength < 1e-6) {
152869
- for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
152870
- return;
152871
- }
152872
- for (let corner = 0; corner < 4; corner++) {
152873
- const positionIndex = vertex + corner;
152874
- const alongLabel = (projectedDistances[corner] - minDistance) / labelLength;
152875
- const sidePosition = uvs.getX(positionIndex);
152876
- uvs.setXY(positionIndex, 1 - alongLabel, 1 - (sidePosition - minU) / (maxU - minU));
152877
- }
152878
- });
152879
- if (!sideQuads.length) {
152880
- mapSingleCellSideUVs(geometry, uvs, labelAspects, labelMaxFontSizes);
152881
- } else {
152882
- for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
152883
- if (sideQuadVertices.has(vertex)) continue;
152884
- for (let corner = 0; corner < 4; corner++) {
152885
- uvs.setX(vertex + corner, -1);
152886
- }
152887
- }
152633
+ this.labelTexture = new DataTexture(labelData, textureWidth, textureHeight, RGBAFormat, UnsignedByteType);
152634
+ this.labelTexture.magFilter = NearestFilter;
152635
+ this.labelTexture.minFilter = NearestFilter;
152636
+ this.labelTexture.generateMipmaps = false;
152637
+ this.labelTexture.needsUpdate = true;
152888
152638
  }
152889
- geometry.setAttribute('hilbertLabelAspect', new Float32BufferAttribute(labelAspects, 1));
152890
- geometry.setAttribute('hilbertLabelMaxFontSize', new Float32BufferAttribute(labelMaxFontSizes, 1));
152891
- geometry.setAttribute('hilbertLabelReverse', new Float32BufferAttribute(labelReverse, 1));
152892
- uvs.needsUpdate = true;
152893
- }
152894
- function getUTurnInteriorFaces(points, positions) {
152895
- const hiddenFaces = new Set();
152896
- if (!points || points.length < 4 || !positions) return hiddenFaces;
152897
- const directions = points.slice(1).map((point, index) => point.clone().sub(points[index]).normalize());
152898
- for (let middleSegment = 1; middleSegment < directions.length - 1; middleSegment++) {
152899
- const incoming = directions[middleSegment - 1];
152900
- const middle = directions[middleSegment];
152901
- const outgoing = directions[middleSegment + 1];
152902
- if (incoming.dot(outgoing) > -0.999999 || Math.abs(incoming.dot(middle)) > 1e-6) continue;
152903
- const interiorNormals = [{
152904
- segment: middleSegment - 1,
152905
- normal: middle
152906
- }, {
152907
- segment: middleSegment,
152908
- normal: incoming.clone().negate()
152909
- }, {
152910
- segment: middleSegment + 1,
152911
- normal: middle
152912
- }];
152913
- interiorNormals.forEach(({
152914
- segment,
152915
- normal
152916
- }) => {
152917
- const pathCenter = points[segment].clone().add(points[segment + 1]).multiplyScalar(0.5);
152918
- for (let side = 0; side < 4; side++) {
152919
- const vertex = (segment * 4 + side) * 4;
152920
- const faceCenter = new Vector3();
152921
- for (let corner = 0; corner < 4; corner++) {
152922
- faceCenter.add(new Vector3().fromBufferAttribute(positions, vertex + corner));
152923
- }
152924
- faceCenter.multiplyScalar(0.25).sub(pathCenter);
152925
- faceCenter.addScaledVector(directions[segment], -faceCenter.dot(directions[segment]));
152926
- if (faceCenter.lengthSq() > 0 && faceCenter.normalize().dot(normal) > 0.9) hiddenFaces.add(vertex);
152639
+ isEmpty() {
152640
+ return this.labelCount === 0;
152641
+ }
152642
+ tagGeometry(geometry, records, instanced = false) {
152643
+ if (this.isEmpty()) return;
152644
+ const vertexCount = geometry.getAttribute('position').count;
152645
+ const count = instanced ? records.length : vertexCount;
152646
+ const makeAttribute = (array, itemSize) => instanced ? new InstancedBufferAttribute(array, itemSize) : new Float32BufferAttribute(array, itemSize);
152647
+ const ids = new Float32Array(count);
152648
+ const lengths = new Float32Array(count);
152649
+ const colors = new Float32Array(count * 4);
152650
+ const dummyAspectRatio = new Float32Array(count);
152651
+ records.forEach((d, index) => {
152652
+ if (!this.labels.has(d)) {
152653
+ console.warn(`Label not found for record ${JSON.stringify(d)}. Skipping...`);
152654
+ return;
152655
+ }
152656
+ const label = this.labels.get(d);
152657
+ const labelColor = label?.color;
152658
+ const color = new Color$1(labelColor ? colorStr2Hex(labelColor) : 0xffffff);
152659
+ const opacity = labelColor ? colorAlpha(labelColor) : 0;
152660
+ const id = label ? label.id : -1;
152661
+ const len = label ? label.length : 0;
152662
+ const start = instanced ? index : 0;
152663
+ const end = instanced ? index + 1 : count;
152664
+ for (let i = start; i < end; i++) {
152665
+ ids[i] = id;
152666
+ lengths[i] = len;
152667
+ colors[i * 4] = color.r;
152668
+ colors[i * 4 + 1] = color.g;
152669
+ colors[i * 4 + 2] = color.b;
152670
+ colors[i * 4 + 3] = opacity;
152671
+ dummyAspectRatio[i] = 2.0;
152927
152672
  }
152928
152673
  });
152929
- }
152930
- return hiddenFaces;
152931
- }
152932
- function isRectangularFace(positions, vertex) {
152933
- const corners = Array.from({
152934
- length: 4
152935
- }, (_, corner) => new Vector3().fromBufferAttribute(positions, vertex + corner));
152936
- const edges = corners.map((corner, index) => corners[(index + 1) % 4].clone().sub(corner));
152937
- const scale = Math.max(...edges.map(edge => edge.length()));
152938
- const tolerance = scale * 1e-4;
152939
- const oppositeEdgesMatch = edges[0].clone().add(edges[2]).length() <= tolerance && edges[1].clone().add(edges[3]).length() <= tolerance;
152940
- const adjacentEdgesPerpendicular = Math.abs(edges[0].dot(edges[1])) <= edges[0].length() * edges[1].length() * 1e-4;
152941
- return oppositeEdgesMatch && adjacentEdgesPerpendicular;
152942
- }
152943
- function mapSingleCellSideUVs(geometry, uvs, labelAspects, labelMaxFontSizes) {
152944
- const positions = geometry.getAttribute('position');
152945
- const normals = geometry.getAttribute('normal');
152946
- if (!positions || !normals || positions.count !== 24) return;
152947
- for (let vertex = 0; vertex + 3 < positions.count; vertex += 4) {
152948
- const normalX = normals.getX(vertex);
152949
- const normalY = normals.getY(vertex);
152950
- const normalZ = normals.getZ(vertex);
152951
- const rightX = Math.abs(normalY) > 0.9 ? 1 : normalZ > 0.9 ? 1 : normalZ < -0.9 ? -1 : 0;
152952
- const rightZ = Math.abs(normalY) > 0.9 ? 0 : normalX > 0.9 ? -1 : normalX < -0.9 ? 1 : 0;
152953
- const upY = Math.abs(normalY) > 0.9 ? 0 : 1;
152954
- const upZ = Math.abs(normalY) > 0.9 ? normalY > 0 ? -1 : 1 : 0;
152955
- let minRight = Infinity;
152956
- let maxRight = -Infinity;
152957
- let minUp = Infinity;
152958
- let maxUp = -Infinity;
152959
- for (let corner = 0; corner < 4; corner++) {
152960
- const index = vertex + corner;
152961
- const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
152962
- const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
152963
- minRight = Math.min(minRight, right);
152964
- maxRight = Math.max(maxRight, right);
152965
- minUp = Math.min(minUp, up);
152966
- maxUp = Math.max(maxUp, up);
152674
+ geometry.setAttribute('labelId', makeAttribute(ids, 1));
152675
+ geometry.setAttribute('labelLength', makeAttribute(lengths, 1));
152676
+ geometry.setAttribute('labelColor', makeAttribute(colors, 4));
152677
+ if (!geometry.getAttribute('aspectRatio')) {
152678
+ console.warn(`Geometry requires aspectRatio attribute. Setting 2.0 throughout the faces.`);
152679
+ geometry.setAttribute('aspectRatio', makeAttribute(dummyAspectRatio, 1));
152967
152680
  }
152968
- for (let corner = 0; corner < 4; corner++) {
152969
- const index = vertex + corner;
152970
- const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
152971
- const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
152972
- uvs.setXY(index, (right - minRight) / (maxRight - minRight), (up - minUp) / (maxUp - minUp));
152973
- labelAspects[index] = (maxRight - minRight) / (maxUp - minUp);
152974
- labelMaxFontSizes[index] = MAX_CUBE_LABEL_FONT_SIZE;
152681
+ }
152682
+ getMaterial(color) {
152683
+ let material = this.materialCache.get(color);
152684
+ if (material) return material;
152685
+ material = new MeshLambertMaterial();
152686
+ this.materialCache.set(color, material);
152687
+ const opacity = colorAlpha(color);
152688
+ material.color.set(colorStr2Hex(color));
152689
+ material.transparent = opacity < 1;
152690
+ material.opacity = opacity;
152691
+ if (!this.isEmpty()) {
152692
+ material.onBeforeCompile = shader => {
152693
+ shader.uniforms.labelGlyphTexture = {
152694
+ value: this.glyphTexture
152695
+ };
152696
+ shader.uniforms.labelDataTexture = {
152697
+ value: this.labelTexture
152698
+ };
152699
+ shader.uniforms.labelDataTextureSize = {
152700
+ value: new Vector2(this.labelTexture.image.width, this.labelTexture.image.height)
152701
+ };
152702
+ shader.uniforms.labelLabelsPerRow = {
152703
+ value: this.labelsPerRow
152704
+ };
152705
+ shader.vertexShader = shader.vertexShader.replace('#include <common>', `#include <common>
152706
+ attribute float aspectRatio;
152707
+ attribute vec4 labelColor;
152708
+ attribute float labelId;
152709
+ attribute float labelLength;
152710
+ varying float vAspectRatio;
152711
+ varying vec4 vLabelColor;
152712
+ varying float vLabelId;
152713
+ varying float vLabelLength;
152714
+ varying vec2 vLabelUv;`).replace('#include <begin_vertex>', `#include <begin_vertex>
152715
+ vAspectRatio = aspectRatio;
152716
+ vLabelColor = labelColor;
152717
+ vLabelId = labelId;
152718
+ vLabelLength = labelLength;
152719
+ vLabelUv = uv;`);
152720
+ shader.fragmentShader = shader.fragmentShader.replace('#include <common>', `#include <common>
152721
+ uniform sampler2D labelGlyphTexture;
152722
+ uniform sampler2D labelDataTexture;
152723
+ uniform vec2 labelDataTextureSize;
152724
+ uniform float labelLabelsPerRow;
152725
+ varying float vAspectRatio;
152726
+ varying vec4 vLabelColor;
152727
+ varying float vLabelId;
152728
+ varying float vLabelLength;
152729
+ varying vec2 vLabelUv;`).replace('#include <map_fragment>', `#include <map_fragment>
152730
+ if (vLabelId >= 0.0 && vLabelUv.x >= 0.0 && vLabelUv.x <= 1.0) {
152731
+ float aspect = max(vAspectRatio, 0.001);
152732
+ float visibleLength = vLabelLength;
152733
+ float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152734
+ float maxFontSize = ${MAX_LABEL_FONT_SIZE.toFixed(2)};
152735
+ float fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
152736
+ bool isTruncated = fontSize < ${MIN_LABEL_FONT_SIZE.toFixed(2)};
152737
+ if (isTruncated) visibleLength = min(visibleLength, max(3.0, floor((aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / ${MIN_LABEL_FONT_SIZE.toFixed(2)} - 1.0) / ${LABEL_CHARACTER_ADVANCE.toFixed(2)}) + 1.0));
152738
+ textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152739
+ fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
152740
+ float characterSize = fontSize / aspect;
152741
+ float characterAdvance = characterSize * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
152742
+ float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);
152743
+ float textStart = (1.0 - textWidth) * 0.5;
152744
+ float textPosition = vLabelUv.x - textStart;
152745
+ if (textPosition >= 0.0 && textPosition < textWidth) {
152746
+ float glyphVerticalPosition = (vLabelUv.y - 0.5) / max(fontSize, 0.001) + 0.5;
152747
+ if (glyphVerticalPosition >= 0.0 && glyphVerticalPosition <= 1.0) {
152748
+ float charPosition = textPosition / max(characterAdvance, 0.001);
152749
+ float charIndex = floor(charPosition);
152750
+ float glyphHorizontalPosition = (textPosition - charIndex * characterAdvance) / max(characterSize, 0.001);
152751
+ float labelRow = floor(vLabelId / labelLabelsPerRow);
152752
+ float labelColumn = mod(vLabelId, labelLabelsPerRow);
152753
+ vec2 dataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + charIndex, labelRow) + 0.5) / labelDataTextureSize;
152754
+ float charCode = floor(texture2D(labelDataTexture, dataUv).r * 255.0 + 0.5);
152755
+ if (isTruncated && charIndex >= visibleLength - 3.0) charCode = 46.0;
152756
+ vec2 glyphCell = vec2(mod(charCode, 16.0), floor(charCode / 16.0));
152757
+ vec2 glyphUv = vec2(0.015625 + clamp(glyphHorizontalPosition, 0.0, 1.0) * 0.96875, 0.015625 + (1.0 - glyphVerticalPosition) * 0.96875);
152758
+ vec2 glyphAtlasUv = vec2(glyphCell.x + glyphUv.x, 16.0 - glyphCell.y - glyphUv.y) / 16.0;
152759
+ float glyphCoverage = texture2D(labelGlyphTexture, glyphAtlasUv).a;
152760
+ float previousCharIndex = charIndex - 1.0;
152761
+ float previousGlyphPosition = (textPosition - previousCharIndex * characterAdvance) / max(characterSize, 0.001);
152762
+ if (charIndex > 0.0 && previousGlyphPosition < 1.0) {
152763
+ vec2 previousDataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + previousCharIndex, labelRow) + 0.5) / labelDataTextureSize;
152764
+ float previousCharCode = floor(texture2D(labelDataTexture, previousDataUv).r * 255.0 + 0.5);
152765
+ if (isTruncated && previousCharIndex >= visibleLength - 3.0) previousCharCode = 46.0;
152766
+ vec2 previousGlyphCell = vec2(mod(previousCharCode, 16.0), floor(previousCharCode / 16.0));
152767
+ vec2 previousGlyphAtlasUv = vec2(
152768
+ previousGlyphCell.x + 0.015625 + clamp(previousGlyphPosition, 0.0, 1.0) * 0.96875,
152769
+ 16.0 - previousGlyphCell.y - glyphUv.y
152770
+ ) / 16.0;
152771
+ glyphCoverage = max(glyphCoverage, texture2D(labelGlyphTexture, previousGlyphAtlasUv).a);
152772
+ }
152773
+ float glyphAlpha = glyphCoverage * vLabelColor.a;
152774
+ diffuseColor.rgb = mix(diffuseColor.rgb, vLabelColor.rgb, glyphAlpha);
152775
+ }
152776
+ }
152777
+ }`);
152778
+ };
152779
+ material.customProgramCacheKey = () => 'three-label-glyph-atlas';
152975
152780
  }
152781
+ return material;
152782
+ }
152783
+ dispose() {
152784
+ this.labelTexture?.dispose();
152976
152785
  }
152977
152786
  }
152978
152787
 
152979
- const CHILD_PERMUTATIONS = [[0, 3, 4, 7, 6, 5, 2, 1], [0, 7, 6, 1, 2, 5, 4, 3], [0, 7, 6, 1, 2, 5, 4, 3], [2, 3, 0, 1, 6, 7, 4, 5], [2, 3, 0, 1, 6, 7, 4, 5], [4, 3, 2, 5, 6, 1, 0, 7], [4, 3, 2, 5, 6, 1, 0, 7], [6, 5, 2, 1, 0, 3, 4, 7]];
152980
152788
  const {
152981
152789
  orientations: HILBERT_ORIENTATIONS,
152982
152790
  transitions: HILBERT_ORIENTATION_TRANSITIONS
152983
- } = createOrientationTables();
152984
- function createOrientationTables() {
152791
+ } = (() => {
152792
+ const CHILD_PERMUTATIONS = [[0, 3, 4, 7, 6, 5, 2, 1], [0, 7, 6, 1, 2, 5, 4, 3], [0, 7, 6, 1, 2, 5, 4, 3], [2, 3, 0, 1, 6, 7, 4, 5], [2, 3, 0, 1, 6, 7, 4, 5], [4, 3, 2, 5, 6, 1, 0, 7], [4, 3, 2, 5, 6, 1, 0, 7], [6, 5, 2, 1, 0, 3, 4, 7]];
152985
152793
  const orientations = [[0, 1, 2, 3, 4, 5, 6, 7]];
152986
152794
  const transitions = [];
152987
152795
  const orientationIds = new Map([[orientations[0].join(''), 0]]);
@@ -153005,160 +152813,75 @@ var<${access}> ${ name } : ${ structName };`;
153005
152813
  orientations,
153006
152814
  transitions
153007
152815
  };
153008
- }
153009
- function createInstancedHilbertMeshes({
152816
+ })();
152817
+ function createHilbertGeometries({
153010
152818
  useInstancing = true,
153011
- data,
153012
152819
  order,
152820
+ data,
153013
152821
  paddingAccessor,
153014
152822
  paddingAbsoluteAccessor,
153015
- colorAccessor,
153016
- labelAccessor,
153017
- labelAtlas,
153018
- defaultColorScale,
153019
- simplifyCurves,
153020
- SCALE
152823
+ simplifyCurves
153021
152824
  }) {
153022
- const instanceMaterialCache = new Map();
153023
152825
  const geometryCache = new Map();
153024
- const geometries = new WeakMap();
153025
- const fallbackData = [];
152826
+ const fallbackGeometries = new Map();
153026
152827
  const batches = new Map();
153027
- const usedGeometryKeys = new Set();
153028
152828
  data.forEach(d => {
153029
152829
  const padding = paddingAccessor(d);
153030
152830
  const paddingAbsolute = paddingAbsoluteAccessor(d);
153031
- const labelInfo = labelAtlas?.labels.get(d);
153032
- const label = labelInfo?.text ?? labelAccessor(d);
153033
- if (!useInstancing) {
153034
- const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
153035
- if (labelAtlas) addLabelAttributes(geometry, [{
153036
- info: labelInfo
153037
- }]);
153038
- geometries.set(d, geometry);
153039
- fallbackData.push(d);
153040
- return;
153041
- }
153042
- const description = getSimpleHilbertGeometry(order, d.start, d.length, padding, paddingAbsolute, simplifyCurves);
153043
- if (!description) {
153044
- const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
153045
- if (labelAtlas) addLabelAttributes(geometry, [{
153046
- info: labelInfo
153047
- }]);
153048
- geometries.set(d, geometry);
153049
- fallbackData.push(d);
152831
+ const description = useInstancing && getSimpleHilbertGeometry(order, d.start, d.length, padding, paddingAbsolute, simplifyCurves);
152832
+ if (!useInstancing || !description) {
152833
+ // skip instancing
152834
+ fallbackGeometries.set(d, createGeometry(order, d, padding, paddingAbsolute, simplifyCurves));
153050
152835
  return;
153051
152836
  }
153052
- const color = colorAccessor?.(d) || defaultColorScale(label || '');
153053
152837
  const {
153054
152838
  points,
153055
152839
  width,
153056
152840
  scale
153057
152841
  } = description;
153058
152842
  const key = getCurvePath(points);
153059
- const geometryKey = `${key}|${width / scale}|${Boolean(labelAtlas)}`;
153060
- usedGeometryKeys.add(geometryKey);
153061
- let templateGeometry = geometryCache.get(geometryKey);
153062
- if (!templateGeometry) {
153063
- const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
153064
- templateGeometry = createTemplateGeometry(geometry, points[0], scale);
153065
- geometryCache.set(geometryKey, templateGeometry);
153066
- geometry.dispose();
153067
- }
153068
- const materialKey = color;
153069
- let material = instanceMaterialCache.get(materialKey);
153070
- if (!material) {
153071
- if (!labelAtlas) {
153072
- const opacity = colorAlpha(color);
153073
- material = new MeshLambertMaterial();
153074
- material.color.set(colorStr2Hex(color));
153075
- material.transparent = opacity < 1;
153076
- material.opacity = opacity;
153077
- } else {
153078
- material = createLabelMaterial(color, labelAtlas);
153079
- }
153080
- instanceMaterialCache.set(materialKey, material);
153081
- }
153082
- let colorBatches = batches.get(geometryKey);
153083
- if (!colorBatches) {
153084
- colorBatches = new Map();
153085
- batches.set(geometryKey, colorBatches);
152843
+ const geometryKey = `${key}|${width / scale}`;
152844
+ let geometry = geometryCache.get(geometryKey);
152845
+ if (!geometry) {
152846
+ geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves);
152847
+ geometryCache.set(geometryKey, geometry);
153086
152848
  }
153087
- let batch = colorBatches.get(materialKey);
152849
+ let batch = batches.get(geometryKey);
153088
152850
  if (!batch) {
153089
152851
  batch = {
153090
- geometry: templateGeometry,
153091
- material,
153092
- transforms: new Float32Array(256),
153093
- count: 0,
153094
- data: [],
153095
- labelRecords: []
152852
+ geometry,
152853
+ origin: points[0],
152854
+ scale,
152855
+ instances: []
153096
152856
  };
153097
- colorBatches.set(materialKey, batch);
152857
+ batches.set(geometryKey, batch);
153098
152858
  }
153099
- const instanceScale = scale * SCALE;
153100
- let transforms = batch.transforms;
153101
- if (batch.count * 4 === transforms.length) {
153102
- const expandedTransforms = new Float32Array(transforms.length * 2);
153103
- expandedTransforms.set(transforms);
153104
- transforms = batch.transforms = expandedTransforms;
153105
- }
153106
- const transformOffset = batch.count * 4;
153107
- transforms[transformOffset] = instanceScale;
153108
- transforms[transformOffset + 1] = points[0].x * SCALE;
153109
- transforms[transformOffset + 2] = points[0].y * SCALE;
153110
- transforms[transformOffset + 3] = points[0].z * SCALE;
153111
- batch.count++;
153112
- batch.data.push(d);
153113
- if (labelAtlas) batch.labelRecords.push({
153114
- info: labelInfo
152859
+ batch.instances.push({
152860
+ data: d,
152861
+ position: points[0],
152862
+ scale
153115
152863
  });
153116
152864
  });
153117
- geometryCache.forEach((geometry, key) => {
153118
- if (!usedGeometryKeys.has(key)) {
153119
- geometry.dispose();
153120
- geometryCache.delete(key);
153121
- }
152865
+ const instancedGeometries = Array.from(batches.values());
152866
+ instancedGeometries.forEach(batch => {
152867
+ const sourceGeometry = batch.geometry;
152868
+ batch.geometry = createTemplateGeometry(sourceGeometry, batch.origin, batch.scale);
152869
+ sourceGeometry.dispose();
152870
+ delete batch.origin;
152871
+ delete batch.scale;
153122
152872
  });
153123
- const meshes = [];
153124
- batches.forEach(colorBatches => {
153125
- colorBatches.forEach(batch => {
153126
- const geometry = batch.geometry.clone();
153127
- if (labelAtlas) addLabelAttributes(geometry, batch.labelRecords, true);
153128
- const mesh = new InstancedMesh(geometry, batch.material, batch.count);
153129
- const matrices = mesh.instanceMatrix.array;
153130
- for (let i = 0; i < batch.count; i++) {
153131
- const transformOffset = i * 4;
153132
- const matrixOffset = i * 16;
153133
- const scale = batch.transforms[transformOffset];
153134
- matrices[matrixOffset] = scale;
153135
- matrices[matrixOffset + 5] = scale;
153136
- matrices[matrixOffset + 10] = scale;
153137
- matrices[matrixOffset + 12] = batch.transforms[transformOffset + 1];
153138
- matrices[matrixOffset + 13] = batch.transforms[transformOffset + 2];
153139
- matrices[matrixOffset + 14] = batch.transforms[transformOffset + 3];
153140
- matrices[matrixOffset + 15] = 1;
153141
- }
153142
- mesh.instanceMatrix.needsUpdate = true;
153143
- mesh.computeBoundingSphere();
153144
- mesh.userData.data = batch.data;
153145
- meshes.push(mesh);
153146
- });
153147
- });
153148
- geometryCache.forEach(geometry => geometry.dispose());
153149
152873
  return {
153150
- fallbackData,
153151
- geometries,
153152
- meshes
152874
+ instancedGeometries,
152875
+ fallbackGeometries
153153
152876
  };
153154
152877
  }
153155
- function createGeometry(order, datum, padding, paddingAbsolute, simplifyCurves, labeled) {
152878
+ function createGeometry(order, datum, padding, paddingAbsolute, simplifyCurves) {
153156
152879
  const geometry = new ThreeHilbertGeometry(order, datum.start, datum.length, {
153157
152880
  padding,
153158
152881
  paddingAbsolute,
153159
152882
  simplifyCurves
153160
152883
  });
153161
- if (labeled) mapLabelUVs(geometry);
152884
+ mapLabelUVs(geometry);
153162
152885
  return geometry;
153163
152886
  }
153164
152887
  function createTemplateGeometry(geometry, origin, scale) {
@@ -153176,6 +152899,12 @@ var<${access}> ${ name } : ${ structName };`;
153176
152899
  positions.needsUpdate = true;
153177
152900
  templateGeometry.computeBoundingBox();
153178
152901
  templateGeometry.computeBoundingSphere();
152902
+ if (geometry.parameters) {
152903
+ templateGeometry.parameters = {
152904
+ ...geometry.parameters,
152905
+ points: geometry.parameters.points?.map(point => point.clone().sub(origin).divideScalar(scale))
152906
+ };
152907
+ }
153179
152908
  return templateGeometry;
153180
152909
  }
153181
152910
  function getSimpleHilbertGeometry(order, start, length, padding, paddingAbsolute, simplifyCurves) {
@@ -153276,6 +153005,165 @@ var<${access}> ${ name } : ${ structName };`;
153276
153005
  }
153277
153006
  return path.join('');
153278
153007
  }
153008
+ function mapLabelUVs(geometry) {
153009
+ const uvs = geometry.getAttribute('uv');
153010
+ if (!uvs) return;
153011
+ const positions = geometry.getAttribute('position');
153012
+ const points = geometry.parameters?.points;
153013
+ const labelAspects = new Float32Array(uvs.count);
153014
+ const sideQuads = [];
153015
+ if (points?.length > 1) {
153016
+ const sideQuadCount = (points.length - 1) * 4;
153017
+ for (let vertex = 0; vertex + 3 < uvs.count && vertex / 4 < sideQuadCount; vertex += 4) {
153018
+ let minU = Infinity;
153019
+ let maxU = -Infinity;
153020
+ let minV = Infinity;
153021
+ let maxV = -Infinity;
153022
+ for (let corner = 0; corner < 4; corner++) {
153023
+ minU = Math.min(minU, uvs.getX(vertex + corner));
153024
+ maxU = Math.max(maxU, uvs.getX(vertex + corner));
153025
+ minV = Math.min(minV, uvs.getY(vertex + corner));
153026
+ maxV = Math.max(maxV, uvs.getY(vertex + corner));
153027
+ }
153028
+ if (maxU <= minU || maxV === minV) continue;
153029
+ sideQuads.push({
153030
+ vertex,
153031
+ minU,
153032
+ maxU,
153033
+ minV,
153034
+ maxV
153035
+ });
153036
+ }
153037
+ } else {
153038
+ for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
153039
+ let minU = Infinity;
153040
+ let maxU = -Infinity;
153041
+ let minV = Infinity;
153042
+ let maxV = -Infinity;
153043
+ for (let corner = 0; corner < 4; corner++) {
153044
+ minU = Math.min(minU, uvs.getX(vertex + corner));
153045
+ maxU = Math.max(maxU, uvs.getX(vertex + corner));
153046
+ minV = Math.min(minV, uvs.getY(vertex + corner));
153047
+ maxV = Math.max(maxV, uvs.getY(vertex + corner));
153048
+ }
153049
+ if (Math.abs(maxU - minU - 0.25) > 0.01 || maxV <= minV) continue;
153050
+ sideQuads.push({
153051
+ vertex,
153052
+ minU,
153053
+ maxU,
153054
+ minV,
153055
+ maxV
153056
+ });
153057
+ }
153058
+ }
153059
+ const sideQuadVertices = new Set(sideQuads.map(({
153060
+ vertex
153061
+ }) => vertex));
153062
+ sideQuads.forEach(({
153063
+ vertex,
153064
+ minU,
153065
+ maxU,
153066
+ minV,
153067
+ maxV
153068
+ }, index) => {
153069
+ if (positions && !isRectangularFace(positions, vertex)) {
153070
+ for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
153071
+ return;
153072
+ }
153073
+ const pathSegment = Math.floor(index / 4);
153074
+ const startPoint = points?.[pathSegment];
153075
+ const endPoint = points?.[pathSegment + 1];
153076
+ const dx = endPoint ? endPoint.x - startPoint.x : 0;
153077
+ const dy = endPoint ? endPoint.y - startPoint.y : 0;
153078
+ const dz = endPoint ? endPoint.z - startPoint.z : 0;
153079
+ const segmentLength = Math.hypot(dx, dy, dz);
153080
+ const distance0 = positions && startPoint && segmentLength ? ((positions.getX(vertex) - startPoint.x) * dx + (positions.getY(vertex) - startPoint.y) * dy + (positions.getZ(vertex) - startPoint.z) * dz) / segmentLength : segmentLength * (uvs.getY(vertex) - minV) / (maxV - minV);
153081
+ const distance1 = positions && startPoint && segmentLength ? ((positions.getX(vertex + 1) - startPoint.x) * dx + (positions.getY(vertex + 1) - startPoint.y) * dy + (positions.getZ(vertex + 1) - startPoint.z) * dz) / segmentLength : segmentLength * (uvs.getY(vertex + 1) - minV) / (maxV - minV);
153082
+ const distance2 = positions && startPoint && segmentLength ? ((positions.getX(vertex + 2) - startPoint.x) * dx + (positions.getY(vertex + 2) - startPoint.y) * dy + (positions.getZ(vertex + 2) - startPoint.z) * dz) / segmentLength : segmentLength * (uvs.getY(vertex + 2) - minV) / (maxV - minV);
153083
+ const distance3 = positions && startPoint && segmentLength ? ((positions.getX(vertex + 3) - startPoint.x) * dx + (positions.getY(vertex + 3) - startPoint.y) * dy + (positions.getZ(vertex + 3) - startPoint.z) * dz) / segmentLength : segmentLength * (uvs.getY(vertex + 3) - minV) / (maxV - minV);
153084
+ const minDistance = Math.min(distance0, distance1, distance2, distance3);
153085
+ const maxDistance = Math.max(distance0, distance1, distance2, distance3);
153086
+ const labelLength = maxDistance - minDistance;
153087
+ const edgeX = positions ? positions.getX(vertex + 1) - positions.getX(vertex) : 0;
153088
+ const edgeY = positions ? positions.getY(vertex + 1) - positions.getY(vertex) : 0;
153089
+ const edgeZ = positions ? positions.getZ(vertex + 1) - positions.getZ(vertex) : 0;
153090
+ const sideWidth = Math.sqrt(edgeX * edgeX + edgeY * edgeY + edgeZ * edgeZ);
153091
+ if (sideWidth > 0) {
153092
+ for (let corner = 0; corner < 4; corner++) labelAspects[vertex + corner] = labelLength / sideWidth;
153093
+ }
153094
+ if (labelLength < 1e-6) {
153095
+ for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
153096
+ return;
153097
+ }
153098
+ for (let corner = 0; corner < 4; corner++) {
153099
+ const positionIndex = vertex + corner;
153100
+ const distance = corner === 0 ? distance0 : corner === 1 ? distance1 : corner === 2 ? distance2 : distance3;
153101
+ const alongLabel = (distance - minDistance) / labelLength;
153102
+ const sidePosition = uvs.getX(positionIndex);
153103
+ uvs.setXY(positionIndex, alongLabel, 1 - (sidePosition - minU) / (maxU - minU));
153104
+ }
153105
+ });
153106
+ if (!sideQuads.length) {
153107
+ mapSingleCellSideUVs(geometry, uvs, labelAspects);
153108
+ } else {
153109
+ for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
153110
+ if (sideQuadVertices.has(vertex)) continue;
153111
+ for (let corner = 0; corner < 4; corner++) {
153112
+ uvs.setX(vertex + corner, -1);
153113
+ }
153114
+ }
153115
+ }
153116
+ geometry.setAttribute('aspectRatio', new Float32BufferAttribute(labelAspects, 1));
153117
+ uvs.needsUpdate = true;
153118
+
153119
+ //
153120
+
153121
+ function isRectangularFace(positions, vertex) {
153122
+ const corners = Array.from({
153123
+ length: 4
153124
+ }, (_, corner) => new Vector3().fromBufferAttribute(positions, vertex + corner));
153125
+ const edges = corners.map((corner, index) => corners[(index + 1) % 4].clone().sub(corner));
153126
+ const scale = Math.max(...edges.map(edge => edge.length()));
153127
+ const tolerance = scale * 1e-4;
153128
+ const oppositeEdgesMatch = edges[0].clone().add(edges[2]).length() <= tolerance && edges[1].clone().add(edges[3]).length() <= tolerance;
153129
+ const adjacentEdgesPerpendicular = Math.abs(edges[0].dot(edges[1])) <= edges[0].length() * edges[1].length() * 1e-4;
153130
+ return oppositeEdgesMatch && adjacentEdgesPerpendicular;
153131
+ }
153132
+ function mapSingleCellSideUVs(geometry, uvs, labelAspects) {
153133
+ const positions = geometry.getAttribute('position');
153134
+ const normals = geometry.getAttribute('normal');
153135
+ if (!positions || !normals || positions.count !== 24) return;
153136
+ for (let vertex = 0; vertex + 3 < positions.count; vertex += 4) {
153137
+ const normalX = normals.getX(vertex);
153138
+ const normalY = normals.getY(vertex);
153139
+ const normalZ = normals.getZ(vertex);
153140
+ const rightX = Math.abs(normalY) > 0.9 ? 1 : normalZ > 0.9 ? 1 : normalZ < -0.9 ? -1 : 0;
153141
+ const rightZ = Math.abs(normalY) > 0.9 ? 0 : normalX > 0.9 ? -1 : normalX < -0.9 ? 1 : 0;
153142
+ const upY = Math.abs(normalY) > 0.9 ? 0 : 1;
153143
+ const upZ = Math.abs(normalY) > 0.9 ? normalY > 0 ? -1 : 1 : 0;
153144
+ let minRight = Infinity;
153145
+ let maxRight = -Infinity;
153146
+ let minUp = Infinity;
153147
+ let maxUp = -Infinity;
153148
+ for (let corner = 0; corner < 4; corner++) {
153149
+ const index = vertex + corner;
153150
+ const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
153151
+ const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
153152
+ minRight = Math.min(minRight, right);
153153
+ maxRight = Math.max(maxRight, right);
153154
+ minUp = Math.min(minUp, up);
153155
+ maxUp = Math.max(maxUp, up);
153156
+ }
153157
+ for (let corner = 0; corner < 4; corner++) {
153158
+ const index = vertex + corner;
153159
+ const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
153160
+ const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
153161
+ uvs.setXY(index, (right - minRight) / (maxRight - minRight), (up - minUp) / (maxUp - minUp));
153162
+ labelAspects[index] = (maxRight - minRight) / (maxUp - minUp);
153163
+ }
153164
+ }
153165
+ }
153166
+ }
153279
153167
 
153280
153168
  const SCALE = 100;
153281
153169
  const ThreeHilbert = index$4({
@@ -153325,9 +153213,7 @@ var<${access}> ${ name } : ${ structName };`;
153325
153213
  },
153326
153214
  stateInit() {
153327
153215
  return {
153328
- defaultColorScale: ordinal(Paired),
153329
- instancedMeshes: [],
153330
- labelAtlas: null
153216
+ defaultColorScale: ordinal(Paired)
153331
153217
  };
153332
153218
  },
153333
153219
  init: function (threeObj, state) {
@@ -153335,15 +153221,17 @@ var<${access}> ${ name } : ${ structName };`;
153335
153221
 
153336
153222
  // Main three object to manipulate
153337
153223
  state.scene = threeObj;
153338
- state.dataMapper = new ThreeDigest(threeObj, {
153224
+ state.scene.scale.set(SCALE, SCALE, SCALE);
153225
+ const instancedG = state.instancedG = new Group$1();
153226
+ state.scene.add(instancedG);
153227
+ state.instancedDataMapper = new ThreeDigest(instancedG, {
153339
153228
  objBindAttr: '__threeObjHilbert'
153340
- }).onCreateObj(() => {
153341
- const obj = new Group$1(); // container
153342
- obj.add(new Mesh()); // hilbert curve
153343
-
153344
- obj.scale.set(SCALE, SCALE, SCALE);
153345
- return obj;
153346
153229
  });
153230
+ const fallbackG = new Group$1();
153231
+ state.scene.add(fallbackG);
153232
+ state.fallbackDataMapper = new ThreeDigest(fallbackG, {
153233
+ objBindAttr: '__threeObjHilbert'
153234
+ }).onCreateObj(() => new Mesh());
153347
153235
  },
153348
153236
  update: function (state, changedProps) {
153349
153237
  // Data accessors
@@ -153352,60 +153240,71 @@ var<${access}> ${ name } : ${ structName };`;
153352
153240
  const colorAccessor = index$3(state.color);
153353
153241
  const labelAccessor = index$3(state.label);
153354
153242
  const labelColorAccessor = index$3(state.labelColor);
153355
- const previousLabelAtlas = state.labelAtlas;
153356
- const labelAtlas = createLabelAtlas(state.data, labelAccessor, labelColorAccessor);
153357
- state.labelAtlas = labelAtlas;
153243
+ const getColor = d => colorAccessor?.(d) || state.defaultColorScale(labelAccessor(d) || '');
153244
+ const labelAtlas = new LabelAtlas(state.data, labelAccessor, labelColorAccessor);
153358
153245
  const {
153359
- fallbackData,
153360
- geometries,
153361
- meshes: instancedMeshes
153362
- } = createInstancedHilbertMeshes({
153246
+ instancedGeometries,
153247
+ fallbackGeometries
153248
+ } = createHilbertGeometries({
153363
153249
  useInstancing: state.useInstancedMeshes,
153364
153250
  data: state.data,
153365
153251
  order: state.order,
153366
153252
  paddingAccessor,
153367
153253
  paddingAbsoluteAccessor,
153368
- colorAccessor,
153369
- labelAccessor,
153370
- labelAtlas,
153371
- defaultColorScale: state.defaultColorScale,
153372
- simplifyCurves: state.simplifyCurves,
153373
- SCALE
153254
+ simplifyCurves: state.simplifyCurves
153374
153255
  });
153375
- state.instancedMeshes.forEach(mesh => {
153376
- state.scene.remove(mesh);
153377
- deallocate(mesh);
153256
+ const instancedMeshes = new Map();
153257
+ instancedGeometries.forEach(geometryBatch => {
153258
+ const colorBatches = new Map();
153259
+ geometryBatch.instances.forEach(instance => {
153260
+ // split by color
153261
+ const color = getColor(instance.data);
153262
+ let batch = colorBatches.get(color);
153263
+ if (!batch) {
153264
+ batch = {
153265
+ material: labelAtlas.getMaterial(color),
153266
+ instances: []
153267
+ };
153268
+ colorBatches.set(color, batch);
153269
+ }
153270
+ batch.instances.push(instance);
153271
+ });
153272
+ colorBatches.forEach(({
153273
+ material,
153274
+ instances
153275
+ }) => {
153276
+ const geometry = geometryBatch.geometry.clone();
153277
+ labelAtlas.tagGeometry(geometry, instances.map(instance => instance.data), true);
153278
+ const mesh = new InstancedMesh(geometry, material, instances.length);
153279
+ const matrices = mesh.instanceMatrix.array;
153280
+ instances.forEach(({
153281
+ scale,
153282
+ position
153283
+ }, i) => {
153284
+ const matrixOffset = i * 16;
153285
+ matrices[matrixOffset] = scale;
153286
+ matrices[matrixOffset + 5] = scale;
153287
+ matrices[matrixOffset + 10] = scale;
153288
+ matrices[matrixOffset + 12] = position.x;
153289
+ matrices[matrixOffset + 13] = position.y;
153290
+ matrices[matrixOffset + 14] = position.z;
153291
+ matrices[matrixOffset + 15] = 1;
153292
+ });
153293
+ mesh.instanceMatrix.needsUpdate = true;
153294
+ mesh.computeBoundingSphere();
153295
+ const data = instances.map(instance => instance.data);
153296
+ instancedMeshes.set(data, mesh);
153297
+ });
153298
+ geometryBatch.geometry.dispose();
153378
153299
  });
153379
- state.instancedMeshes = instancedMeshes;
153380
- instancedMeshes.forEach(mesh => state.scene.add(mesh));
153381
- const materialCache = new Map();
153382
- state.dataMapper.onUpdateObj((obj, d) => {
153383
- const [hilbertObj] = obj.children;
153384
-
153385
- // update color
153386
- const label = labelAtlas?.labels.get(d)?.text ?? labelAccessor(d);
153387
- const color = colorAccessor?.(d) || state.defaultColorScale(label || '');
153388
- const materialKey = color;
153389
- let material = materialCache.get(materialKey);
153390
- if (!material && labelAtlas) {
153391
- material = createLabelMaterial(color, labelAtlas);
153392
- materialCache.set(materialKey, material);
153393
- } else if (!material) {
153394
- const opacity = colorAlpha(color);
153395
- material = new MeshLambertMaterial();
153396
- material.color.set(colorStr2Hex(color));
153397
- material.transparent = opacity < 1;
153398
- material.opacity = opacity;
153399
- materialCache.set(materialKey, material);
153400
- }
153401
- hilbertObj.material = material;
153402
- hilbertObj.geometry?.dispose();
153403
- hilbertObj.geometry = geometries.get(d);
153404
- }).digest(fallbackData);
153405
- if (previousLabelAtlas) {
153406
- previousLabelAtlas.glyphTexture.dispose();
153407
- previousLabelAtlas.labelTexture.dispose();
153408
- }
153300
+ state.instancedDataMapper.onCreateObj(d => instancedMeshes.get(d)).digest([...instancedMeshes.keys()]);
153301
+ [...fallbackGeometries.entries()].forEach(([d, geometry]) => labelAtlas.tagGeometry(geometry, [d]));
153302
+ state.fallbackDataMapper.onUpdateObj((obj, d) => {
153303
+ obj.geometry?.dispose();
153304
+ obj.geometry = fallbackGeometries.get(d);
153305
+ obj.material = labelAtlas.getMaterial(getColor(d));
153306
+ }).digest([...fallbackGeometries.keys()]);
153307
+ labelAtlas.dispose();
153409
153308
  }
153410
153309
  });
153411
153310
 
@@ -153567,16 +153466,34 @@ var<${access}> ${ name } : ${ structName };`;
153567
153466
  };
153568
153467
  state.renderObjs.fitToBbox(roBbox, transitionDuration);
153569
153468
  });
153469
+ return this;
153570
153470
  },
153571
153471
  zoomToFit: function (state, transitionDuration, padding) {
153572
- state.renderObjs.zoomTofit(transitionDuration, padding);
153472
+ state.renderObjs.zoomToFit(transitionDuration, padding);
153573
153473
  return this;
153574
153474
  },
153475
+ getPositionAtVal: (state, ...args) => state.hilbert.getPositionAtVal(...args),
153575
153476
  _animationCycle(state) {
153576
153477
  // Frame cycle
153577
153478
  state.renderObjs.tick();
153578
153479
  state.animationFrameRequestId = requestAnimationFrame(this._animationCycle);
153579
153480
  },
153481
+ cameraPosition: function (state, ...args) {
153482
+ if (args.length) {
153483
+ // setter
153484
+ state.renderObjs.cameraPosition(...args);
153485
+ return this;
153486
+ }
153487
+ return state.renderObjs.cameraPosition();
153488
+ },
153489
+ lights: function (state, ...args) {
153490
+ if (args.length) {
153491
+ // setter
153492
+ state.renderObjs.lights(...args);
153493
+ return this;
153494
+ }
153495
+ return state.renderObjs.lights();
153496
+ },
153580
153497
  scene: state => state.renderObjs.scene(),
153581
153498
  // Expose scene
153582
153499
  camera: state => state.renderObjs.camera(),
@@ -153585,6 +153502,29 @@ var<${access}> ${ name } : ${ structName };`;
153585
153502
  // Expose renderer
153586
153503
  controls: state => state.renderObjs.controls(),
153587
153504
  // Expose controls
153505
+ hoverOrderComparator: function (state, dataComp) {
153506
+ state.renderObjs.hoverOrderComparator((_a, _b, a, b) => {
153507
+ const [da, db] = [a, b].map(i => getHilbertObjData(i?.object, i));
153508
+ if (!da) return 1;
153509
+ if (!db) return -1;
153510
+ return dataComp(da, db);
153511
+ });
153512
+ return this;
153513
+ function getHilbertObjData(obj, intersection) {
153514
+ if (!obj) return null;
153515
+ const hilbertObj = getHilbertObj(obj);
153516
+ const d = hilbertObj?.__data || null;
153517
+ return intersection && hilbertObj.isInstancedMesh ? d?.[intersection.instanceId] : d;
153518
+ function getHilbertObj(object) {
153519
+ let obj = object;
153520
+ // recurse up object chain until finding the hilbert object
153521
+ while (obj && !obj.hasOwnProperty('__data')) {
153522
+ obj = obj.parent;
153523
+ }
153524
+ return obj;
153525
+ }
153526
+ }
153527
+ },
153588
153528
  _destructor: function (state) {
153589
153529
  cancelAnimationFrame(state.animationFrameRequestId);
153590
153530
  this.data([]);
@@ -153615,14 +153555,12 @@ var<${access}> ${ name } : ${ structName };`;
153615
153555
  el.appendChild(roDomNode);
153616
153556
  const getHilbertObjData = (obj, intersection) => {
153617
153557
  if (!obj) return null;
153618
- if (intersection && obj.isInstancedMesh) {
153619
- return obj.userData.data?.[intersection.instanceId] || null;
153620
- }
153621
153558
  const hilbertObj = getHilbertObj(obj);
153622
- return hilbertObj?.__data || null;
153559
+ const d = hilbertObj?.__data || null;
153560
+ return intersection && hilbertObj.isInstancedMesh ? d?.[intersection.instanceId] : d;
153623
153561
  function getHilbertObj(object) {
153624
153562
  let obj = object;
153625
- // recurse up object chain until finding the globe object
153563
+ // recurse up object chain until finding the hilbert object
153626
153564
  while (obj && !obj.hasOwnProperty('__data')) {
153627
153565
  obj = obj.parent;
153628
153566
  }