hilbert-chart-3d 0.2.1 → 0.3.1

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.2.1 hilbert-chart-3d - https://github.com/vasturiano/hilbert-chart-3d
1
+ // Version 0.3.1 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) :
@@ -25395,6 +25395,48 @@
25395
25395
 
25396
25396
  }
25397
25397
 
25398
+ /**
25399
+ * Creates a texture from a canvas element.
25400
+ *
25401
+ * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
25402
+ * to `true` immediately since a canvas can directly be used for rendering.
25403
+ *
25404
+ * @augments Texture
25405
+ */
25406
+ class CanvasTexture extends Texture {
25407
+
25408
+ /**
25409
+ * Constructs a new texture.
25410
+ *
25411
+ * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
25412
+ * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
25413
+ * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
25414
+ * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
25415
+ * @param {number} [magFilter=LinearFilter] - The mag filter value.
25416
+ * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
25417
+ * @param {number} [format=RGBAFormat] - The texture format.
25418
+ * @param {number} [type=UnsignedByteType] - The texture type.
25419
+ * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
25420
+ */
25421
+ constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
25422
+
25423
+ super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
25424
+
25425
+ /**
25426
+ * This flag can be used for type testing.
25427
+ *
25428
+ * @type {boolean}
25429
+ * @readonly
25430
+ * @default true
25431
+ */
25432
+ this.isCanvasTexture = true;
25433
+
25434
+ this.needsUpdate = true;
25435
+
25436
+ }
25437
+
25438
+ }
25439
+
25398
25440
  /**
25399
25441
  * This class can be used to automatically save the depth information of a
25400
25442
  * rendering into a texture.
@@ -144628,14 +144670,25 @@ var<${access}> ${ name } : ${ structName };`;
144628
144670
  this.boundingSphere = new Sphere(new Vector3(x, y, z), Math.sqrt(3) * halfWidth);
144629
144671
  return;
144630
144672
  }
144673
+ const turnTolerance = 1e-6;
144631
144674
  const path = [];
144675
+ const incoming = new Vector3();
144676
+ const outgoing = new Vector3();
144632
144677
  for (let index = 0; index < points.length; index++) {
144633
144678
  const point = points[index];
144634
144679
  if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y) || !Number.isFinite(point.z)) {
144635
144680
  throw new TypeError(`points[${index}] must have finite x, y, and z coordinates`);
144636
144681
  }
144637
144682
  const copy = new Vector3(point.x, point.y, point.z);
144638
- if (index === 0 || copy.distanceToSquared(path[path.length - 1]) > 0) path.push(copy);
144683
+ if (path.length && copy.distanceToSquared(path[path.length - 1]) === 0) continue;
144684
+ while (path.length >= 2) {
144685
+ incoming.subVectors(path[path.length - 1], path[path.length - 2]);
144686
+ outgoing.subVectors(copy, path[path.length - 1]);
144687
+ const dot = incoming.dot(outgoing) / Math.sqrt(incoming.lengthSq() * outgoing.lengthSq());
144688
+ if (dot < 1 - turnTolerance) break;
144689
+ path.pop();
144690
+ }
144691
+ path.push(copy);
144639
144692
  }
144640
144693
  this.parameters = {
144641
144694
  points: path.map(point => point.clone()),
@@ -144672,7 +144725,6 @@ var<${access}> ${ name } : ${ structName };`;
144672
144725
  for (let i = 0; i < directions.length; i++) {
144673
144726
  directions[i] = path[i + 1].clone().sub(path[i]).normalize();
144674
144727
  }
144675
- const turnTolerance = 1e-6;
144676
144728
  const isClosed = path.length > 2 && path[0].distanceToSquared(path[path.length - 1]) === 0;
144677
144729
  for (let i = 1; i < directions.length; i++) {
144678
144730
  const dot = directions[i - 1].dot(directions[i]);
@@ -144795,10 +144847,10 @@ var<${access}> ${ name } : ${ structName };`;
144795
144847
  positions[positionOffset++] = point.z;
144796
144848
  if (hasCustomUVs) {
144797
144849
  uvs[uvOffset++] = customUVs[i * 2];
144798
- uvs[uvOffset++] = customUVs[i * 2 + 1];
144850
+ uvs[uvOffset++] = 1 - customUVs[i * 2 + 1];
144799
144851
  } else {
144800
144852
  uvs[uvOffset++] = i === 1 || i === 2 ? 1 : 0;
144801
- uvs[uvOffset++] = i >= 2 ? 1 : 0;
144853
+ uvs[uvOffset++] = i >= 2 ? 0 : 1;
144802
144854
  }
144803
144855
  }
144804
144856
  indices[indexOffset++] = vertexOffset;
@@ -144825,8 +144877,8 @@ var<${access}> ${ name } : ${ structName };`;
144825
144877
  const endV = i === directions.length - 1 && !isClosed ? 1 : (pathDistances[i + 1] + (isClosed ? 0 : halfWidth)) / totalLength;
144826
144878
  for (const a of faceCorners) {
144827
144879
  const b = (a + 1) % 4;
144828
- const startU = a / 4;
144829
- const endU = (a + 1) / 4;
144880
+ const startU = 0;
144881
+ const endU = 1;
144830
144882
  sideUVs[0] = startU;
144831
144883
  sideUVs[1] = startV;
144832
144884
  sideUVs[2] = endU;
@@ -144864,6 +144916,7 @@ var<${access}> ${ name } : ${ structName };`;
144864
144916
  class ThreeHilbertGeometry extends SquareTubeGeometry {
144865
144917
  constructor(order, start, length, {
144866
144918
  padding = 0,
144919
+ paddingAbsolute = 0,
144867
144920
  simplifyCurves = true
144868
144921
  } = {}) {
144869
144922
  super(...getSuperParams());
@@ -144875,6 +144928,7 @@ var<${access}> ${ name } : ${ structName };`;
144875
144928
  start,
144876
144929
  length,
144877
144930
  padding,
144931
+ paddingAbsolute,
144878
144932
  simplifyCurves
144879
144933
  };
144880
144934
  function getSuperParams() {
@@ -144890,7 +144944,8 @@ var<${access}> ${ name } : ${ structName };`;
144890
144944
  }
144891
144945
  }
144892
144946
  const points = hilbert3D(undefined, 1, order - 1, start, length);
144893
- const lineWidth = 1 / 2 ** (order - 1) * (1 - Math.min(1, padding));
144947
+ const w = 2 ** (1 - order); // Full width without padding
144948
+ const lineWidth = (w - Math.min(paddingAbsolute, w * 0.5)) * (1 - Math.min(1, padding));
144894
144949
  return [points, lineWidth];
144895
144950
  }
144896
144951
  }
@@ -147716,6 +147771,424 @@ var<${access}> ${ name } : ${ structName };`;
147716
147771
  const colorStr2Hex = str => isNaN(str) ? parseInt(tinycolor(str).toHex(), 16) : str;
147717
147772
  const colorAlpha = str => str && isNaN(str) ? color(str).opacity : 1;
147718
147773
 
147774
+ const MAX_LABEL_CHARS = 32;
147775
+ const GLYPH_COUNT = 256;
147776
+ const GLYPHS_PER_ROW = 16;
147777
+ const GLYPH_SIZE = 64;
147778
+ const MIN_LABEL_FONT_SIZE = 0.05;
147779
+ const MAX_LABEL_FONT_SIZE = 0.8;
147780
+ const MAX_CUBE_LABEL_FONT_SIZE = 0.5;
147781
+ const MAX_LABEL_WIDTH = 0.92;
147782
+ const LABEL_CHARACTER_ADVANCE = 0.8;
147783
+ function createLabelAtlas(data, labelAccessor, labelColorAccessor) {
147784
+ const labelIds = new Map();
147785
+ const labels = new WeakMap();
147786
+ data.forEach(d => {
147787
+ const label = labelAccessor(d);
147788
+ const color = labelColorAccessor(d);
147789
+ if (!label || !color) return;
147790
+ const characters = Array.from(String(label));
147791
+ const text = characters.length > MAX_LABEL_CHARS ? `${characters.slice(0, MAX_LABEL_CHARS - 3).join('')}...` : characters.join('');
147792
+ let id = labelIds.get(text);
147793
+ if (id === undefined) {
147794
+ id = labelIds.size;
147795
+ labelIds.set(text, id);
147796
+ }
147797
+ labels.set(d, {
147798
+ id,
147799
+ length: Array.from(text).length,
147800
+ text,
147801
+ color
147802
+ });
147803
+ });
147804
+ if (!labelIds.size) return null;
147805
+ const glyphCanvas = document.createElement('canvas');
147806
+ glyphCanvas.width = GLYPHS_PER_ROW * GLYPH_SIZE;
147807
+ glyphCanvas.height = GLYPHS_PER_ROW * GLYPH_SIZE;
147808
+ const glyphContext = glyphCanvas.getContext('2d');
147809
+ if (!glyphContext) throw new Error('Unable to create canvas context for label glyphs');
147810
+ glyphContext.font = 'bold 64px monospace';
147811
+ glyphContext.textAlign = 'center';
147812
+ glyphContext.textBaseline = 'middle';
147813
+ for (let code = 0; code < GLYPH_COUNT; code++) {
147814
+ const character = String.fromCharCode(code);
147815
+ if (code < 32 || code === 127) continue;
147816
+ const x = code % GLYPHS_PER_ROW * GLYPH_SIZE + GLYPH_SIZE / 2;
147817
+ const y = Math.floor(code / GLYPHS_PER_ROW) * GLYPH_SIZE + GLYPH_SIZE / 2;
147818
+ glyphContext.fillStyle = '#fff';
147819
+ glyphContext.fillText(character, x, y);
147820
+ }
147821
+ const glyphTexture = new CanvasTexture(glyphCanvas);
147822
+ glyphTexture.magFilter = LinearFilter;
147823
+ glyphTexture.minFilter = LinearFilter;
147824
+ glyphTexture.colorSpace = SRGBColorSpace;
147825
+ const labelsPerRow = 128;
147826
+ const textureWidth = labelsPerRow * MAX_LABEL_CHARS;
147827
+ const textureHeight = Math.ceil(labelIds.size / labelsPerRow);
147828
+ const labelData = new Uint8Array(textureWidth * textureHeight * 4);
147829
+ labelIds.forEach((id, text) => {
147830
+ Array.from(text).forEach((character, charIndex) => {
147831
+ const code = character.codePointAt(0);
147832
+ const x = id % labelsPerRow * MAX_LABEL_CHARS + charIndex;
147833
+ const y = Math.floor(id / labelsPerRow);
147834
+ const supported = code >= 32 && code <= 255 && (code < 127 || code >= 160);
147835
+ labelData[(y * textureWidth + x) * 4] = supported ? code : 63;
147836
+ });
147837
+ });
147838
+ const labelTexture = new DataTexture(labelData, textureWidth, textureHeight, RGBAFormat, UnsignedByteType);
147839
+ labelTexture.magFilter = NearestFilter;
147840
+ labelTexture.minFilter = NearestFilter;
147841
+ labelTexture.generateMipmaps = false;
147842
+ labelTexture.needsUpdate = true;
147843
+ return {
147844
+ labels,
147845
+ glyphTexture,
147846
+ labelTexture,
147847
+ labelsPerRow,
147848
+ labelCount: labelIds.size
147849
+ };
147850
+ }
147851
+ function createLabelMaterial(color, labelAtlas) {
147852
+ const material = new MeshLambertMaterial();
147853
+ const opacity = colorAlpha(color);
147854
+ material.color.set(colorStr2Hex(color));
147855
+ material.transparent = opacity < 1;
147856
+ material.opacity = opacity;
147857
+ if (labelAtlas) {
147858
+ material.onBeforeCompile = shader => {
147859
+ shader.uniforms.labelGlyphTexture = {
147860
+ value: labelAtlas.glyphTexture
147861
+ };
147862
+ shader.uniforms.labelDataTexture = {
147863
+ value: labelAtlas.labelTexture
147864
+ };
147865
+ shader.uniforms.labelDataTextureSize = {
147866
+ value: new Vector2(labelAtlas.labelTexture.image.width, labelAtlas.labelTexture.image.height)
147867
+ };
147868
+ shader.uniforms.labelLabelsPerRow = {
147869
+ value: labelAtlas.labelsPerRow
147870
+ };
147871
+ shader.vertexShader = shader.vertexShader.replace('#include <common>', `#include <common>
147872
+ attribute float hilbertLabelId;
147873
+ attribute float hilbertLabelLength;
147874
+ attribute float hilbertLabelAspect;
147875
+ attribute float hilbertLabelMaxFontSize;
147876
+ attribute float hilbertLabelReverse;
147877
+ attribute vec4 hilbertLabelColor;
147878
+ varying vec2 vHilbertLabelUv;
147879
+ varying float vHilbertLabelId;
147880
+ varying float vHilbertLabelLength;
147881
+ varying float vHilbertLabelAspect;
147882
+ varying float vHilbertLabelMaxFontSize;
147883
+ varying float vHilbertLabelReverse;
147884
+ varying vec4 vHilbertLabelColor;`).replace('#include <begin_vertex>', `#include <begin_vertex>
147885
+ vHilbertLabelUv = uv;
147886
+ vHilbertLabelId = hilbertLabelId;
147887
+ vHilbertLabelLength = hilbertLabelLength;
147888
+ vHilbertLabelAspect = hilbertLabelAspect;
147889
+ vHilbertLabelMaxFontSize = hilbertLabelMaxFontSize;
147890
+ vHilbertLabelReverse = hilbertLabelReverse;
147891
+ vHilbertLabelColor = hilbertLabelColor;`);
147892
+ shader.fragmentShader = shader.fragmentShader.replace('#include <common>', `#include <common>
147893
+ uniform sampler2D labelGlyphTexture;
147894
+ uniform sampler2D labelDataTexture;
147895
+ uniform vec2 labelDataTextureSize;
147896
+ uniform float labelLabelsPerRow;
147897
+ varying vec2 vHilbertLabelUv;
147898
+ varying float vHilbertLabelId;
147899
+ varying float vHilbertLabelLength;
147900
+ varying float vHilbertLabelAspect;
147901
+ varying float vHilbertLabelMaxFontSize;
147902
+ varying float vHilbertLabelReverse;
147903
+ varying vec4 vHilbertLabelColor;`).replace('#include <map_fragment>', `#include <map_fragment>
147904
+ if (vHilbertLabelId >= 0.0 && vHilbertLabelUv.x >= 0.0 && vHilbertLabelUv.x <= 1.0) {
147905
+ float aspect = max(vHilbertLabelAspect, 0.001);
147906
+ float visibleLength = vHilbertLabelLength;
147907
+ float textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
147908
+ float maxFontSize = min(${MAX_LABEL_FONT_SIZE.toFixed(2)}, vHilbertLabelMaxFontSize);
147909
+ float fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
147910
+ bool isTruncated = fontSize < ${MIN_LABEL_FONT_SIZE.toFixed(2)};
147911
+ 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));
147912
+ textUnits = 1.0 + max(visibleLength - 1.0, 0.0) * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
147913
+ fontSize = min(maxFontSize, aspect * ${MAX_LABEL_WIDTH.toFixed(2)} / textUnits);
147914
+ float characterSize = fontSize / aspect;
147915
+ float characterAdvance = characterSize * ${LABEL_CHARACTER_ADVANCE.toFixed(2)};
147916
+ float textWidth = characterSize + characterAdvance * max(visibleLength - 1.0, 0.0);
147917
+ float textStart = (1.0 - textWidth) * 0.5;
147918
+ float textPosition = vHilbertLabelUv.x - textStart;
147919
+ if (textPosition >= 0.0 && textPosition < textWidth) {
147920
+ float glyphVerticalPosition = (vHilbertLabelUv.y - 0.5) / max(fontSize, 0.001) + 0.5;
147921
+ if (glyphVerticalPosition >= 0.0 && glyphVerticalPosition <= 1.0) {
147922
+ float charPosition = textPosition / max(characterAdvance, 0.001);
147923
+ float charSlot = floor(charPosition);
147924
+ float charIndex = mix(charSlot, visibleLength - 1.0 - charSlot, vHilbertLabelReverse);
147925
+ float glyphHorizontalPosition = (textPosition - charSlot * characterAdvance) / max(characterSize, 0.001);
147926
+ glyphHorizontalPosition = mix(glyphHorizontalPosition, 1.0 - glyphHorizontalPosition, vHilbertLabelReverse);
147927
+ float labelRow = floor(vHilbertLabelId / labelLabelsPerRow);
147928
+ float labelColumn = mod(vHilbertLabelId, labelLabelsPerRow);
147929
+ vec2 dataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + charIndex, labelRow) + 0.5) / labelDataTextureSize;
147930
+ float charCode = floor(texture2D(labelDataTexture, dataUv).r * 255.0 + 0.5);
147931
+ if (isTruncated && charIndex >= visibleLength - 3.0) charCode = 46.0;
147932
+ vec2 glyphCell = vec2(mod(charCode, 16.0), floor(charCode / 16.0));
147933
+ vec2 glyphUv = vec2(0.015625 + clamp(glyphHorizontalPosition, 0.0, 1.0) * 0.96875, 0.015625 + (1.0 - glyphVerticalPosition) * 0.96875);
147934
+ vec2 glyphAtlasUv = vec2(glyphCell.x + glyphUv.x, 16.0 - glyphCell.y - glyphUv.y) / 16.0;
147935
+ float glyphCoverage = texture2D(labelGlyphTexture, glyphAtlasUv).a;
147936
+ float previousCharSlot = charSlot - 1.0;
147937
+ float previousCharIndex = mix(previousCharSlot, visibleLength - 1.0 - previousCharSlot, vHilbertLabelReverse);
147938
+ float previousGlyphPosition = (textPosition - previousCharSlot * characterAdvance) / max(characterSize, 0.001);
147939
+ previousGlyphPosition = mix(previousGlyphPosition, 1.0 - previousGlyphPosition, vHilbertLabelReverse);
147940
+ if (charSlot > 0.0 && previousGlyphPosition < 1.0) {
147941
+ vec2 previousDataUv = (vec2(labelColumn * ${MAX_LABEL_CHARS}.0 + previousCharIndex, labelRow) + 0.5) / labelDataTextureSize;
147942
+ float previousCharCode = floor(texture2D(labelDataTexture, previousDataUv).r * 255.0 + 0.5);
147943
+ if (isTruncated && previousCharIndex >= visibleLength - 3.0) previousCharCode = 46.0;
147944
+ vec2 previousGlyphCell = vec2(mod(previousCharCode, 16.0), floor(previousCharCode / 16.0));
147945
+ vec2 previousGlyphAtlasUv = vec2(
147946
+ previousGlyphCell.x + 0.015625 + clamp(previousGlyphPosition, 0.0, 1.0) * 0.96875,
147947
+ 16.0 - previousGlyphCell.y - glyphUv.y
147948
+ ) / 16.0;
147949
+ glyphCoverage = max(glyphCoverage, texture2D(labelGlyphTexture, previousGlyphAtlasUv).a);
147950
+ }
147951
+ float glyphAlpha = glyphCoverage * vHilbertLabelColor.a;
147952
+ diffuseColor.rgb = mix(diffuseColor.rgb, vHilbertLabelColor.rgb, glyphAlpha);
147953
+ }
147954
+ }
147955
+ }`);
147956
+ };
147957
+ material.customProgramCacheKey = () => 'three-hilbert-label-glyph-atlas';
147958
+ }
147959
+ return material;
147960
+ }
147961
+ function addLabelAttributes(geometry, records, instanced = false) {
147962
+ const vertexCount = geometry.getAttribute('position').count;
147963
+ const count = instanced ? records.length : vertexCount;
147964
+ const makeAttribute = (array, itemSize) => instanced ? new InstancedBufferAttribute(array, itemSize) : new Float32BufferAttribute(array, itemSize);
147965
+ const ids = new Float32Array(count);
147966
+ const lengths = new Float32Array(count);
147967
+ const colors = new Float32Array(count * 4);
147968
+ records.forEach(({
147969
+ info
147970
+ }, index) => {
147971
+ const labelColor = info?.color;
147972
+ const color = new Color$1(labelColor ? colorStr2Hex(labelColor) : 0xffffff);
147973
+ const start = instanced ? index : 0;
147974
+ const end = instanced ? index + 1 : count;
147975
+ for (let i = start; i < end; i++) {
147976
+ ids[i] = info ? info.id : -1;
147977
+ lengths[i] = info ? info.length : 0;
147978
+ colors[i * 4] = color.r;
147979
+ colors[i * 4 + 1] = color.g;
147980
+ colors[i * 4 + 2] = color.b;
147981
+ colors[i * 4 + 3] = labelColor ? colorAlpha(labelColor) : 0;
147982
+ }
147983
+ });
147984
+ geometry.setAttribute('hilbertLabelId', makeAttribute(ids, 1));
147985
+ geometry.setAttribute('hilbertLabelLength', makeAttribute(lengths, 1));
147986
+ geometry.setAttribute('hilbertLabelColor', makeAttribute(colors, 4));
147987
+ }
147988
+ function mapLabelUVs(geometry) {
147989
+ const uvs = geometry.getAttribute('uv');
147990
+ if (!uvs) return;
147991
+ const positions = geometry.getAttribute('position');
147992
+ const points = geometry.parameters?.points;
147993
+ const labelAspects = new Float32Array(uvs.count);
147994
+ const labelMaxFontSizes = new Float32Array(uvs.count).fill(MAX_LABEL_FONT_SIZE);
147995
+ const labelReverse = new Float32Array(uvs.count);
147996
+ const uTurnInteriorFaces = getUTurnInteriorFaces(points, positions);
147997
+ const sideQuads = [];
147998
+ if (points?.length > 1) {
147999
+ const sideQuadCount = (points.length - 1) * 4;
148000
+ for (let vertex = 0; vertex + 3 < uvs.count && vertex / 4 < sideQuadCount; vertex += 4) {
148001
+ let minU = Infinity;
148002
+ let maxU = -Infinity;
148003
+ let minV = Infinity;
148004
+ let maxV = -Infinity;
148005
+ for (let corner = 0; corner < 4; corner++) {
148006
+ minU = Math.min(minU, uvs.getX(vertex + corner));
148007
+ maxU = Math.max(maxU, uvs.getX(vertex + corner));
148008
+ minV = Math.min(minV, uvs.getY(vertex + corner));
148009
+ maxV = Math.max(maxV, uvs.getY(vertex + corner));
148010
+ }
148011
+ if (maxU <= minU || maxV === minV) continue;
148012
+ sideQuads.push({
148013
+ vertex,
148014
+ minU,
148015
+ maxU,
148016
+ minV,
148017
+ maxV
148018
+ });
148019
+ }
148020
+ } else {
148021
+ for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
148022
+ let minU = Infinity;
148023
+ let maxU = -Infinity;
148024
+ let minV = Infinity;
148025
+ let maxV = -Infinity;
148026
+ for (let corner = 0; corner < 4; corner++) {
148027
+ minU = Math.min(minU, uvs.getX(vertex + corner));
148028
+ maxU = Math.max(maxU, uvs.getX(vertex + corner));
148029
+ minV = Math.min(minV, uvs.getY(vertex + corner));
148030
+ maxV = Math.max(maxV, uvs.getY(vertex + corner));
148031
+ }
148032
+ if (Math.abs(maxU - minU - 0.25) > 0.01 || maxV <= minV) continue;
148033
+ sideQuads.push({
148034
+ vertex,
148035
+ minU,
148036
+ maxU,
148037
+ minV,
148038
+ maxV
148039
+ });
148040
+ }
148041
+ }
148042
+ const sideQuadVertices = new Set(sideQuads.map(({
148043
+ vertex
148044
+ }) => vertex));
148045
+ sideQuads.forEach(({
148046
+ vertex,
148047
+ minU,
148048
+ maxU,
148049
+ minV,
148050
+ maxV
148051
+ }, index) => {
148052
+ for (let corner = 0; corner < 4; corner++) labelReverse[vertex + corner] = 1;
148053
+ if (uTurnInteriorFaces.has(vertex)) {
148054
+ for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
148055
+ return;
148056
+ }
148057
+ if (positions && !isRectangularFace(positions, vertex)) {
148058
+ for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
148059
+ return;
148060
+ }
148061
+ const pathSegment = Math.floor(index / 4);
148062
+ const startPoint = points?.[pathSegment];
148063
+ const endPoint = points?.[pathSegment + 1];
148064
+ const dx = endPoint ? endPoint.x - startPoint.x : 0;
148065
+ const dy = endPoint ? endPoint.y - startPoint.y : 0;
148066
+ const dz = endPoint ? endPoint.z - startPoint.z : 0;
148067
+ const segmentLength = Math.hypot(dx, dy, dz);
148068
+ const projectedDistances = Array.from({
148069
+ length: 4
148070
+ }, (_, corner) => {
148071
+ const positionIndex = vertex + corner;
148072
+ 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);
148073
+ });
148074
+ const minDistance = Math.min(...projectedDistances);
148075
+ const maxDistance = Math.max(...projectedDistances);
148076
+ const labelLength = maxDistance - minDistance;
148077
+ const sideWidth = positions ? new Vector3().fromBufferAttribute(positions, vertex).distanceTo(new Vector3().fromBufferAttribute(positions, vertex + 1)) : 0;
148078
+ if (sideWidth > 0) {
148079
+ for (let corner = 0; corner < 4; corner++) labelAspects[vertex + corner] = labelLength / sideWidth;
148080
+ }
148081
+ if (labelLength < 1e-6) {
148082
+ for (let corner = 0; corner < 4; corner++) uvs.setX(vertex + corner, -1);
148083
+ return;
148084
+ }
148085
+ for (let corner = 0; corner < 4; corner++) {
148086
+ const positionIndex = vertex + corner;
148087
+ const alongLabel = (projectedDistances[corner] - minDistance) / labelLength;
148088
+ const sidePosition = uvs.getX(positionIndex);
148089
+ uvs.setXY(positionIndex, 1 - alongLabel, 1 - (sidePosition - minU) / (maxU - minU));
148090
+ }
148091
+ });
148092
+ if (!sideQuads.length) {
148093
+ mapSingleCellSideUVs(geometry, uvs, labelAspects, labelMaxFontSizes);
148094
+ } else {
148095
+ for (let vertex = 0; vertex + 3 < uvs.count; vertex += 4) {
148096
+ if (sideQuadVertices.has(vertex)) continue;
148097
+ for (let corner = 0; corner < 4; corner++) {
148098
+ uvs.setX(vertex + corner, -1);
148099
+ }
148100
+ }
148101
+ }
148102
+ geometry.setAttribute('hilbertLabelAspect', new Float32BufferAttribute(labelAspects, 1));
148103
+ geometry.setAttribute('hilbertLabelMaxFontSize', new Float32BufferAttribute(labelMaxFontSizes, 1));
148104
+ geometry.setAttribute('hilbertLabelReverse', new Float32BufferAttribute(labelReverse, 1));
148105
+ uvs.needsUpdate = true;
148106
+ }
148107
+ function getUTurnInteriorFaces(points, positions) {
148108
+ const hiddenFaces = new Set();
148109
+ if (!points || points.length < 4 || !positions) return hiddenFaces;
148110
+ const directions = points.slice(1).map((point, index) => point.clone().sub(points[index]).normalize());
148111
+ for (let middleSegment = 1; middleSegment < directions.length - 1; middleSegment++) {
148112
+ const incoming = directions[middleSegment - 1];
148113
+ const middle = directions[middleSegment];
148114
+ const outgoing = directions[middleSegment + 1];
148115
+ if (incoming.dot(outgoing) > -0.999999 || Math.abs(incoming.dot(middle)) > 1e-6) continue;
148116
+ const interiorNormals = [{
148117
+ segment: middleSegment - 1,
148118
+ normal: middle
148119
+ }, {
148120
+ segment: middleSegment,
148121
+ normal: incoming.clone().negate()
148122
+ }, {
148123
+ segment: middleSegment + 1,
148124
+ normal: middle
148125
+ }];
148126
+ interiorNormals.forEach(({
148127
+ segment,
148128
+ normal
148129
+ }) => {
148130
+ const pathCenter = points[segment].clone().add(points[segment + 1]).multiplyScalar(0.5);
148131
+ for (let side = 0; side < 4; side++) {
148132
+ const vertex = (segment * 4 + side) * 4;
148133
+ const faceCenter = new Vector3();
148134
+ for (let corner = 0; corner < 4; corner++) {
148135
+ faceCenter.add(new Vector3().fromBufferAttribute(positions, vertex + corner));
148136
+ }
148137
+ faceCenter.multiplyScalar(0.25).sub(pathCenter);
148138
+ faceCenter.addScaledVector(directions[segment], -faceCenter.dot(directions[segment]));
148139
+ if (faceCenter.lengthSq() > 0 && faceCenter.normalize().dot(normal) > 0.9) hiddenFaces.add(vertex);
148140
+ }
148141
+ });
148142
+ }
148143
+ return hiddenFaces;
148144
+ }
148145
+ function isRectangularFace(positions, vertex) {
148146
+ const corners = Array.from({
148147
+ length: 4
148148
+ }, (_, corner) => new Vector3().fromBufferAttribute(positions, vertex + corner));
148149
+ const edges = corners.map((corner, index) => corners[(index + 1) % 4].clone().sub(corner));
148150
+ const scale = Math.max(...edges.map(edge => edge.length()));
148151
+ const tolerance = scale * 1e-4;
148152
+ const oppositeEdgesMatch = edges[0].clone().add(edges[2]).length() <= tolerance && edges[1].clone().add(edges[3]).length() <= tolerance;
148153
+ const adjacentEdgesPerpendicular = Math.abs(edges[0].dot(edges[1])) <= edges[0].length() * edges[1].length() * 1e-4;
148154
+ return oppositeEdgesMatch && adjacentEdgesPerpendicular;
148155
+ }
148156
+ function mapSingleCellSideUVs(geometry, uvs, labelAspects, labelMaxFontSizes) {
148157
+ const positions = geometry.getAttribute('position');
148158
+ const normals = geometry.getAttribute('normal');
148159
+ if (!positions || !normals || positions.count !== 24) return;
148160
+ for (let vertex = 0; vertex + 3 < positions.count; vertex += 4) {
148161
+ const normalX = normals.getX(vertex);
148162
+ const normalY = normals.getY(vertex);
148163
+ const normalZ = normals.getZ(vertex);
148164
+ const rightX = Math.abs(normalY) > 0.9 ? 1 : normalZ > 0.9 ? 1 : normalZ < -0.9 ? -1 : 0;
148165
+ const rightZ = Math.abs(normalY) > 0.9 ? 0 : normalX > 0.9 ? -1 : normalX < -0.9 ? 1 : 0;
148166
+ const upY = Math.abs(normalY) > 0.9 ? 0 : 1;
148167
+ const upZ = Math.abs(normalY) > 0.9 ? normalY > 0 ? -1 : 1 : 0;
148168
+ let minRight = Infinity;
148169
+ let maxRight = -Infinity;
148170
+ let minUp = Infinity;
148171
+ let maxUp = -Infinity;
148172
+ for (let corner = 0; corner < 4; corner++) {
148173
+ const index = vertex + corner;
148174
+ const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
148175
+ const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
148176
+ minRight = Math.min(minRight, right);
148177
+ maxRight = Math.max(maxRight, right);
148178
+ minUp = Math.min(minUp, up);
148179
+ maxUp = Math.max(maxUp, up);
148180
+ }
148181
+ for (let corner = 0; corner < 4; corner++) {
148182
+ const index = vertex + corner;
148183
+ const right = positions.getX(index) * rightX + positions.getZ(index) * rightZ;
148184
+ const up = positions.getY(index) * upY + positions.getZ(index) * upZ;
148185
+ uvs.setXY(index, (right - minRight) / (maxRight - minRight), (up - minUp) / (maxUp - minUp));
148186
+ labelAspects[index] = (maxRight - minRight) / (maxUp - minUp);
148187
+ labelMaxFontSizes[index] = MAX_CUBE_LABEL_FONT_SIZE;
148188
+ }
148189
+ }
148190
+ }
148191
+
147719
148192
  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]];
147720
148193
  const {
147721
148194
  orientations: HILBERT_ORIENTATIONS,
@@ -147751,8 +148224,10 @@ var<${access}> ${ name } : ${ structName };`;
147751
148224
  data,
147752
148225
  order,
147753
148226
  paddingAccessor,
148227
+ paddingAbsoluteAccessor,
147754
148228
  colorAccessor,
147755
148229
  labelAccessor,
148230
+ labelAtlas,
147756
148231
  defaultColorScale,
147757
148232
  simplifyCurves,
147758
148233
  SCALE
@@ -147765,57 +148240,74 @@ var<${access}> ${ name } : ${ structName };`;
147765
148240
  const usedGeometryKeys = new Set();
147766
148241
  data.forEach(d => {
147767
148242
  const padding = paddingAccessor(d);
148243
+ const paddingAbsolute = paddingAbsoluteAccessor(d);
148244
+ const labelInfo = labelAtlas?.labels.get(d);
148245
+ const label = labelInfo?.text ?? labelAccessor(d);
147768
148246
  if (!useInstancing) {
147769
- geometries.set(d, createGeometry(order, d, padding, simplifyCurves));
148247
+ const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
148248
+ if (labelAtlas) addLabelAttributes(geometry, [{
148249
+ info: labelInfo
148250
+ }]);
148251
+ geometries.set(d, geometry);
147770
148252
  fallbackData.push(d);
147771
148253
  return;
147772
148254
  }
147773
- const description = getSimpleHilbertGeometry(order, d.start, d.length, padding, simplifyCurves);
148255
+ const description = getSimpleHilbertGeometry(order, d.start, d.length, padding, paddingAbsolute, simplifyCurves);
147774
148256
  if (!description) {
147775
- geometries.set(d, createGeometry(order, d, padding, simplifyCurves));
148257
+ const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
148258
+ if (labelAtlas) addLabelAttributes(geometry, [{
148259
+ info: labelInfo
148260
+ }]);
148261
+ geometries.set(d, geometry);
147776
148262
  fallbackData.push(d);
147777
148263
  return;
147778
148264
  }
147779
- const color = colorAccessor?.(d) || defaultColorScale(labelAccessor(d) || '');
148265
+ const color = colorAccessor?.(d) || defaultColorScale(label || '');
147780
148266
  const {
147781
148267
  points,
147782
148268
  width,
147783
148269
  scale
147784
148270
  } = description;
147785
148271
  const key = getCurvePath(points);
147786
- const geometryKey = `${key}|${width / scale}`;
148272
+ const geometryKey = `${key}|${width / scale}|${Boolean(labelAtlas)}`;
147787
148273
  usedGeometryKeys.add(geometryKey);
147788
148274
  let templateGeometry = geometryCache.get(geometryKey);
147789
148275
  if (!templateGeometry) {
147790
- const geometry = createGeometry(order, d, padding, simplifyCurves);
148276
+ const geometry = createGeometry(order, d, padding, paddingAbsolute, simplifyCurves, Boolean(labelAtlas));
147791
148277
  templateGeometry = createTemplateGeometry(geometry, points[0], scale);
147792
148278
  geometryCache.set(geometryKey, templateGeometry);
147793
148279
  geometry.dispose();
147794
148280
  }
147795
- let material = instanceMaterialCache.get(color);
148281
+ const materialKey = color;
148282
+ let material = instanceMaterialCache.get(materialKey);
147796
148283
  if (!material) {
147797
- const opacity = colorAlpha(color);
147798
- material = new MeshLambertMaterial();
147799
- material.color.set(colorStr2Hex(color));
147800
- material.transparent = opacity < 1;
147801
- material.opacity = opacity;
147802
- instanceMaterialCache.set(color, material);
148284
+ if (!labelAtlas) {
148285
+ const opacity = colorAlpha(color);
148286
+ material = new MeshLambertMaterial();
148287
+ material.color.set(colorStr2Hex(color));
148288
+ material.transparent = opacity < 1;
148289
+ material.opacity = opacity;
148290
+ } else {
148291
+ material = createLabelMaterial(color, labelAtlas);
148292
+ }
148293
+ instanceMaterialCache.set(materialKey, material);
147803
148294
  }
147804
148295
  let colorBatches = batches.get(geometryKey);
147805
148296
  if (!colorBatches) {
147806
148297
  colorBatches = new Map();
147807
148298
  batches.set(geometryKey, colorBatches);
147808
148299
  }
147809
- let batch = colorBatches.get(color);
148300
+ let batch = colorBatches.get(materialKey);
147810
148301
  if (!batch) {
147811
148302
  batch = {
147812
148303
  geometry: templateGeometry,
147813
148304
  material,
147814
148305
  transforms: new Float32Array(256),
147815
148306
  count: 0,
147816
- data: []
148307
+ data: [],
148308
+ labelRecords: []
147817
148309
  };
147818
- colorBatches.set(color, batch);
148310
+ colorBatches.set(materialKey, batch);
147819
148311
  }
147820
148312
  const instanceScale = scale * SCALE;
147821
148313
  let transforms = batch.transforms;
@@ -147831,6 +148323,9 @@ var<${access}> ${ name } : ${ structName };`;
147831
148323
  transforms[transformOffset + 3] = points[0].z * SCALE;
147832
148324
  batch.count++;
147833
148325
  batch.data.push(d);
148326
+ if (labelAtlas) batch.labelRecords.push({
148327
+ info: labelInfo
148328
+ });
147834
148329
  });
147835
148330
  geometryCache.forEach((geometry, key) => {
147836
148331
  if (!usedGeometryKeys.has(key)) {
@@ -147841,7 +148336,9 @@ var<${access}> ${ name } : ${ structName };`;
147841
148336
  const meshes = [];
147842
148337
  batches.forEach(colorBatches => {
147843
148338
  colorBatches.forEach(batch => {
147844
- const mesh = new InstancedMesh(batch.geometry, batch.material, batch.count);
148339
+ const geometry = batch.geometry.clone();
148340
+ if (labelAtlas) addLabelAttributes(geometry, batch.labelRecords, true);
148341
+ const mesh = new InstancedMesh(geometry, batch.material, batch.count);
147845
148342
  const matrices = mesh.instanceMatrix.array;
147846
148343
  for (let i = 0; i < batch.count; i++) {
147847
148344
  const transformOffset = i * 4;
@@ -147861,17 +148358,21 @@ var<${access}> ${ name } : ${ structName };`;
147861
148358
  meshes.push(mesh);
147862
148359
  });
147863
148360
  });
148361
+ geometryCache.forEach(geometry => geometry.dispose());
147864
148362
  return {
147865
148363
  fallbackData,
147866
148364
  geometries,
147867
148365
  meshes
147868
148366
  };
147869
148367
  }
147870
- function createGeometry(order, datum, padding, simplifyCurves) {
147871
- return new ThreeHilbertGeometry(order, datum.start, datum.length, {
148368
+ function createGeometry(order, datum, padding, paddingAbsolute, simplifyCurves, labeled) {
148369
+ const geometry = new ThreeHilbertGeometry(order, datum.start, datum.length, {
147872
148370
  padding,
148371
+ paddingAbsolute,
147873
148372
  simplifyCurves
147874
148373
  });
148374
+ if (labeled) mapLabelUVs(geometry);
148375
+ return geometry;
147875
148376
  }
147876
148377
  function createTemplateGeometry(geometry, origin, scale) {
147877
148378
  const templateGeometry = new BufferGeometry();
@@ -147890,7 +148391,7 @@ var<${access}> ${ name } : ${ structName };`;
147890
148391
  templateGeometry.computeBoundingSphere();
147891
148392
  return templateGeometry;
147892
148393
  }
147893
- function getSimpleHilbertGeometry(order, start, length, padding, simplifyCurves) {
148394
+ function getSimpleHilbertGeometry(order, start, length, padding, paddingAbsolute, simplifyCurves) {
147894
148395
  const isBigInt = typeof start === 'bigint' && typeof length === 'bigint';
147895
148396
  if (!Number.isInteger(order) || typeof start === 'bigint' !== (typeof length === 'bigint')) return null;
147896
148397
  if (!isBigInt && (!Number.isFinite(start) || !Number.isFinite(length))) return null;
@@ -147907,7 +148408,7 @@ var<${access}> ${ name } : ${ structName };`;
147907
148408
  }
147908
148409
  }
147909
148410
  const cellSize = 1 / 2 ** (pointOrder - 1);
147910
- const width = cellSize * (1 - Math.min(1, padding));
148411
+ const width = (cellSize - Math.min(paddingAbsolute, cellSize * 0.5)) * (1 - Math.min(1, padding));
147911
148412
  if (!(width > 0) || !Number.isFinite(width)) return null;
147912
148413
  if (pointOrder <= 0) {
147913
148414
  const points = [{
@@ -148002,12 +148503,15 @@ var<${access}> ${ name } : ${ structName };`;
148002
148503
  padding: {
148003
148504
  default: 0
148004
148505
  },
148506
+ paddingAbsolute: {
148507
+ default: 0
148508
+ },
148005
148509
  color: {},
148006
148510
  label: {
148007
148511
  default: 'name'
148008
148512
  },
148009
148513
  labelColor: {
148010
- default: () => 'white'
148514
+ default: () => 'lavender'
148011
148515
  },
148012
148516
  simplifyCurves: {
148013
148517
  default: true
@@ -148026,6 +148530,7 @@ var<${access}> ${ name } : ${ structName };`;
148026
148530
  const g = new ThreeHilbertGeometry(state.order, start, length);
148027
148531
  g.computeBoundingBox();
148028
148532
  const bbox = g.boundingBox.clone();
148533
+ g.dispose();
148029
148534
  bbox.min.multiplyScalar(SCALE);
148030
148535
  bbox.max.multiplyScalar(SCALE);
148031
148536
  return bbox;
@@ -148034,7 +148539,8 @@ var<${access}> ${ name } : ${ structName };`;
148034
148539
  stateInit() {
148035
148540
  return {
148036
148541
  defaultColorScale: ordinal(Paired),
148037
- instancedMeshes: []
148542
+ instancedMeshes: [],
148543
+ labelAtlas: null
148038
148544
  };
148039
148545
  },
148040
148546
  init: function (threeObj, state) {
@@ -148055,9 +148561,13 @@ var<${access}> ${ name } : ${ structName };`;
148055
148561
  update: function (state, changedProps) {
148056
148562
  // Data accessors
148057
148563
  const paddingAccessor = index$3(state.padding);
148564
+ const paddingAbsoluteAccessor = index$3(state.paddingAbsolute);
148058
148565
  const colorAccessor = index$3(state.color);
148059
148566
  const labelAccessor = index$3(state.label);
148060
- index$3(state.labelColor);
148567
+ const labelColorAccessor = index$3(state.labelColor);
148568
+ const previousLabelAtlas = state.labelAtlas;
148569
+ const labelAtlas = createLabelAtlas(state.data, labelAccessor, labelColorAccessor);
148570
+ state.labelAtlas = labelAtlas;
148061
148571
  const {
148062
148572
  fallbackData,
148063
148573
  geometries,
@@ -148067,8 +148577,10 @@ var<${access}> ${ name } : ${ structName };`;
148067
148577
  data: state.data,
148068
148578
  order: state.order,
148069
148579
  paddingAccessor,
148580
+ paddingAbsoluteAccessor,
148070
148581
  colorAccessor,
148071
148582
  labelAccessor,
148583
+ labelAtlas,
148072
148584
  defaultColorScale: state.defaultColorScale,
148073
148585
  simplifyCurves: state.simplifyCurves,
148074
148586
  SCALE
@@ -148084,20 +148596,29 @@ var<${access}> ${ name } : ${ structName };`;
148084
148596
  const [hilbertObj] = obj.children;
148085
148597
 
148086
148598
  // update color
148087
- const color = colorAccessor?.(d) || state.defaultColorScale(labelAccessor(d) || '');
148088
- let material = materialCache.get(color);
148089
- if (!material) {
148599
+ const label = labelAtlas?.labels.get(d)?.text ?? labelAccessor(d);
148600
+ const color = colorAccessor?.(d) || state.defaultColorScale(label || '');
148601
+ const materialKey = color;
148602
+ let material = materialCache.get(materialKey);
148603
+ if (!material && labelAtlas) {
148604
+ material = createLabelMaterial(color, labelAtlas);
148605
+ materialCache.set(materialKey, material);
148606
+ } else if (!material) {
148090
148607
  const opacity = colorAlpha(color);
148091
148608
  material = new MeshLambertMaterial();
148092
148609
  material.color.set(colorStr2Hex(color));
148093
148610
  material.transparent = opacity < 1;
148094
148611
  material.opacity = opacity;
148095
- materialCache.set(color, material);
148612
+ materialCache.set(materialKey, material);
148096
148613
  }
148097
148614
  hilbertObj.material = material;
148098
148615
  hilbertObj.geometry?.dispose();
148099
148616
  hilbertObj.geometry = geometries.get(d);
148100
148617
  }).digest(fallbackData);
148618
+ if (previousLabelAtlas) {
148619
+ previousLabelAtlas.glyphTexture.dispose();
148620
+ previousLabelAtlas.labelTexture.dispose();
148621
+ }
148101
148622
  }
148102
148623
  });
148103
148624
 
@@ -148190,6 +148711,13 @@ var<${access}> ${ name } : ${ structName };`;
148190
148711
  },
148191
148712
  triggerUpdate: false
148192
148713
  },
148714
+ paddingAbsolute: {
148715
+ default: 0,
148716
+ onChange(v, state) {
148717
+ state.hilbert.paddingAbsolute(v);
148718
+ },
148719
+ triggerUpdate: false
148720
+ },
148193
148721
  color: {
148194
148722
  onChange(v, state) {
148195
148723
  state.hilbert.color(v);
@@ -148204,7 +148732,7 @@ var<${access}> ${ name } : ${ structName };`;
148204
148732
  triggerUpdate: false
148205
148733
  },
148206
148734
  labelColor: {
148207
- default: () => 'white',
148735
+ default: () => 'lavender',
148208
148736
  onChange(v, state) {
148209
148737
  state.hilbert.labelColor(v);
148210
148738
  },