Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ API between minor releases.

## [Unreleased]

### Fixed

- Standalone HTML follows point indices and keeps each selected point's color and intensity.
- Unused vertices in indexed points and lines no longer affect framing.

## [0.4.3] - 2026-12-02

### Added
Expand Down
87 changes: 79 additions & 8 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ private void ValidateMetadata()
}
}

/// <summary>Counts the instances the viewer does not draw because their geometry is neither triangles nor points.</summary>
/// <summary>Counts instances that use a topology the standalone viewer does not draw.</summary>
public static int UndrawnInstances(SceneDocument scene)
{
var topology = new Dictionary<int, SceneTopology>();
Expand All @@ -283,18 +283,31 @@ public static int UndrawnInstances(SceneDocument scene)
private Dictionary<long, int> Build()
{
var geometries = new Dictionary<int, SceneGeometry>();
bool hasVertexSelection = false;
foreach (var geometry in _scene.Geometries)
{
if (!geometries.TryAdd(geometry.Id, geometry))
{
throw new InvalidDataException($"Geometry id {geometry.Id} is used by more than one geometry.");
}
if (geometry.Topology == SceneTopology.Triangles) CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}");
else if (geometry.Topology == SceneTopology.Lines)
if (geometry.Topology is SceneTopology.Triangles or SceneTopology.Lines or SceneTopology.Points)
{
CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}");
}
if (geometry.Topology == SceneTopology.Lines)
{
int segVerts = geometry.Indices.Count > 0 ? geometry.Indices.Count : geometry.Vertices.Count;
if (segVerts % 2 != 0) throw new InvalidDataException($"Line geometry {geometry.Id} has an odd vertex count.");
if (geometry.Indices.Count > 0)
{
var compact = CompactLineVertices(geometry);
geometries[geometry.Id] = compact;
hasVertexSelection |= !ReferenceEquals(compact, geometry);
}
}
else if (geometry.Topology == SceneTopology.Points && geometry.Indices.Count > 0)
{
hasVertexSelection = true;
}
if (!geometry.Vertices.All(IsFinite) || geometry.Normals?.All(IsFinite) == false
|| geometry.UVs?.All(uv => double.IsFinite(uv.X) && double.IsFinite(uv.Y)) == false)
Expand Down Expand Up @@ -351,7 +364,7 @@ private Dictionary<long, int> Build()
if (!elementIndex.TryAdd(id, i)) throw new InvalidDataException($"Element id {id} is used by more than one element.");
}

_bounds = _scene.ComputeBounds();
_bounds = hasVertexSelection ? ComputeSelectedBounds(geometries) : _scene.ComputeBounds();
_rtcOffset = _bounds.IsEmpty ? Vector3d.Zero : _bounds.Center;
if (!IsFinite(_rtcOffset) || !_bounds.IsEmpty && (!IsFinite(_bounds.Min - _rtcOffset) || !IsFinite(_bounds.Max - _rtcOffset)))
throw new InvalidDataException("The scene bounds are not finite in viewer coordinates.");
Expand Down Expand Up @@ -430,6 +443,50 @@ private Dictionary<long, int> Build()
return elementIndex;
}

private BoundingBox3d ComputeSelectedBounds(Dictionary<int, SceneGeometry> geometries)
{
var bounds = BoundingBox3d.Empty;
foreach (var instance in _scene.Instances)
{
var geometry = geometries[instance.GeometryId];
var transform = instance.Transform ?? Transform3d.Identity;
if (geometry.Topology == SceneTopology.Points && geometry.Indices.Count > 0)
{
foreach (int index in geometry.Indices) bounds = bounds.Encapsulate(transform.Apply(geometry.Vertices[index]));
}
else
{
foreach (var vertex in geometry.Vertices) bounds = bounds.Encapsulate(transform.Apply(vertex));
}
}
return bounds;
}

// Line vertices outside the index list must not move the geometry's Float32 origin.
private static SceneGeometry CompactLineVertices(SceneGeometry geometry)
{
var remap = new int[geometry.Vertices.Count];
int count = 0;
foreach (int index in geometry.Indices)
{
if (remap[index] == 0) remap[index] = ++count;
}
if (count == geometry.Vertices.Count) return geometry;

var vertices = new Vector3d[count];
for (int i = 0; i < remap.Length; i++)
{
if (remap[i] != 0) vertices[remap[i] - 1] = geometry.Vertices[i];
}
return new SceneGeometry
{
Id = geometry.Id,
Topology = geometry.Topology,
Vertices = vertices,
Indices = geometry.Indices.Select(index => remap[index] - 1).ToArray(),
};
}

// CAD vector lines (especially 1:100 paper sheets) contain sub-millimetre details that would be
// distorted by the 1/1024 m triangle grid, so store local Float32 coordinates relative to min.
private void AddLineInstance(
Expand Down Expand Up @@ -492,18 +549,20 @@ private static IReadOnlyList<int> LineIndices(SceneGeometry geometry) =>
private void AddPointInstance(SceneGeometry geometry, SceneInstance instance, Dictionary<long, int> elementIndex)
{
var transform = instance.Transform ?? Transform3d.Identity;
var rtc = new Vector3d[geometry.Vertices.Count];
var indices = geometry.Indices;
bool indexed = indices.Count > 0;
var rtc = new Vector3d[indexed ? indices.Count : geometry.Vertices.Count];
var box = BoundingBox3d.Empty;
for (int i = 0; i < rtc.Length; i++)
{
rtc[i] = transform.Apply(geometry.Vertices[i]) - _rtcOffset;
rtc[i] = transform.Apply(geometry.Vertices[indexed ? indices[i] : i]) - _rtcOffset;
box = box.Encapsulate(rtc[i]);
}

int geometryIndex;
Vector3d translation;
byte[]? colors = _pointColors.GetValueOrDefault(geometry.Id);
byte[]? intensities = _pointIntensities.GetValueOrDefault(geometry.Id);
byte[]? colors = SelectPointSamples(_pointColors.GetValueOrDefault(geometry.Id), indices, 3);
byte[]? intensities = SelectPointSamples(_pointIntensities.GetValueOrDefault(geometry.Id), indices, 1);
if (GeometryQuantizer.TryQuantize(rtc, out var origin, out var q))
{
var local = box.IsEmpty ? box : new BoundingBox3d(box.Min - origin, box.Max - origin);
Expand All @@ -526,6 +585,18 @@ private void AddPointInstance(SceneGeometry geometry, SceneInstance instance, Di
AddMatrix(Transform3d.Identity, translation, _pointMatrix);
}

private static byte[]? SelectPointSamples(byte[]? samples, IReadOnlyList<int> indices, int stride)
{
if (samples is null || indices.Count == 0) return samples;

var selected = new byte[checked(indices.Count * stride)];
for (int i = 0; i < indices.Count; i++)
{
samples.AsSpan(indices[i] * stride, stride).CopyTo(selected.AsSpan(i * stride, stride));
}
return selected;
}

private static void CheckIndices(IReadOnlyList<int> indices, int vertexCount, string owner)
{
for (int i = 0; i < indices.Count; i++)
Expand Down
37 changes: 37 additions & 0 deletions src/IOViewer/Viewer/test/e2e/cad.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,40 @@ test('text-only spaces fit and draw their annotations, including wrapped and hid
expect(await mode()).toBe(false);
expect(errors).toEqual([]);
});

test('indexed points keep their colors and unused vertices do not frame points or lines', async ({ page }) => {
await page.goto(pathToFileURL(path.join(viewerDir, 'test-results/cad-indexed.html')).href);
await page.evaluate(() => window.__ioviewer.ready);

const result = await page.evaluate(() => {
const { scene, controls, points, lines } = window.__ioviewer;
const offsetX = JSON.parse(document.getElementById('ioviewer-meta').textContent).rtcOffset[0];
const worldTargetX = () => controls.target.x + offsetX;
const initialTarget = worldTargetX();
const pointGeometry = points.root.children[0].geometry;
const lineGeometry = lines.root.children[0].geometry;
const fitElement = (element) => {
scene.isolate([element]);
const bounds = scene.visibleBox();
controls.fitBox(bounds, false);
return { width: bounds.max.x - bounds.min.x, target: worldTargetX() };
};
return {
pointCount: pointGeometry.getAttribute('position').count,
colors: Array.from(pointGeometry.getAttribute('color').array),
lineVertexCount: lineGeometry.getAttribute('position').count,
initialTarget,
pointFrame: fitElement(0),
lineFrame: fitElement(1),
};
});

expect(result).toEqual({
pointCount: 2,
colors: [0, 0, 1, 1, 0, 0],
lineVertexCount: 2,
initialTarget: 1,
pointFrame: { width: 2, target: 1 },
lineFrame: { width: 2, target: 1 },
});
});
33 changes: 33 additions & 0 deletions tests/IOViewer.Tests/LinePayloadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,39 @@ public void Annotations_And_Sheets_Are_Serialized_With_Centered_Coordinates()
Assert.Equal("#14171c", sheets[1].GetProperty("background").GetString());
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void Indexed_Lines_Use_Referenced_Vertices_For_Local_And_Scene_Bounds(bool shared)
{
var scene = CadDrawing();
var geometry = scene.Geometries[0];
geometry.Vertices = [new(0, 0, 0), new(-10_000, 0, 0), new(2, 1, 0)];
geometry.Indices = [2, 0];
scene.Instances.RemoveAt(1);

if (shared)
{
scene.Instances.Add(new SceneInstance
{
ElementId = 2,
GeometryId = 1,
Transform = Transform3d.Translate(new(1, 0, 0)),
});
}

var view = ViewerHtml.Export(new ViewerDocument(scene));
var line = view.Geometries[0];
var positions = view.Positions(line);
var indices = view.Read(line.GetProperty("indices"));
Assert.Equal(2, indices.Length);
Assert.Equal(2, positions[(int)indices[0] * 3]);
Assert.Equal(0, positions[(int)indices[1] * 3]);
Assert.Equal([2, 1, 0], line.GetProperty("bbox").GetProperty("max").EnumerateArray().Select(v => v.GetDouble()));
Assert.Equal([shared ? 1.5 : 1, 0.5, 0],
view.Meta.GetProperty("rtcOffset").EnumerateArray().Select(v => v.GetDouble()));
}

[Fact]
public void Lines_Preserve_SubMillimetre_PaperSheet_Precision()
{
Expand Down
33 changes: 33 additions & 0 deletions tests/IOViewer.Tests/PointPayloadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,39 @@ public void Points_Are_Written_As_Format4_Points_And_Not_Skipped()
Assert.Equal([0, 0, 0, 1, 0, 0, 0, 1, 0], view.Positions(view.Geometries[0]));
}

[Fact]
public void Indexed_Points_Keep_Selected_Color_And_Intensity_Order_And_Fit_Their_Bounds()
{
var scene = Cloud();
var geometry = scene.Geometries[0];
geometry.Vertices = [new(0, 0, 0), new(10_000, 0, 0), new(2, 1, 0)];
geometry.Indices = [2, 0];
var doc = new ViewerDocument(scene)
{
PointColors = new() { [1] = [255, 0, 0, 0, 255, 0, 0, 0, 255] },
PointIntensities = new() { [1] = [11, 22, 33] },
};

var view = ViewerHtml.Export(doc);
var points = view.Geometries[0];

Assert.Equal([2, 1, 0, 0, 0, 0], view.Positions(points));
Assert.Equal([0, 0, 255, 255, 0, 0], view.Read(points.GetProperty("colors")));
Assert.Equal([33, 11], view.Read(points.GetProperty("intensities")));
Assert.Equal([1, 0.5, 0], view.Meta.GetProperty("rtcOffset").EnumerateArray().Select(v => v.GetDouble()));
Assert.Equal([-1, -0.5, 0], view.Meta.GetProperty("bbox").GetProperty("min").EnumerateArray().Select(v => v.GetDouble()));
Assert.Equal([1, 0.5, 0], view.Meta.GetProperty("bbox").GetProperty("max").EnumerateArray().Select(v => v.GetDouble()));
}

[Fact]
public void Point_Indices_Must_Reference_Existing_Vertices()
{
var scene = Cloud();
scene.Geometries[0].Indices = [2, 3];

Assert.Throws<InvalidDataException>(() => ViewerHtml.Export(new ViewerDocument(scene)));
}

[Fact]
public void Point_Rgb_And_Panorama_Roundtrip_And_Use_The_Viewer_Binary_Block()
{
Expand Down
1 change: 1 addition & 0 deletions tests/IOViewer.Tests/ViewerHtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public double[] Read(JsonElement view)
result[i] = type switch
{
"f32" => BinaryPrimitives.ReadSingleLittleEndian(span[(i * 4)..]),
"u8" => span[i],
"u16" => BinaryPrimitives.ReadUInt16LittleEndian(span[(i * 2)..]),
"i16" => BinaryPrimitives.ReadInt16LittleEndian(span[(i * 2)..]),
"u32" => BinaryPrimitives.ReadUInt32LittleEndian(span[(i * 4)..]),
Expand Down
23 changes: 23 additions & 0 deletions tests/fixtures/viewer/cad-indexed.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"Kind": "ioviewer",
"Format": 2,
"Scene": {
"Kind": "ioscene",
"Format": 1,
"Title": "Indexed CAD primitives",
"Models": [{"Id": 1, "Key": "fixture", "Name": "Fixture"}],
"Elements": [
{"Id": 1, "Name": "Points", "ModelId": 1},
{"Id": 2, "Name": "Line", "ModelId": 1}
],
"Geometries": [
{"Id": 1, "Topology": 2, "Vertices": [0, 0, 0, 10000, 0, 0, 2, 1, 0], "Indices": [2, 0]},
{"Id": 2, "Topology": 1, "Vertices": [0, 0, 0, -10000, 0, 0, 2, 1, 0], "Indices": [2, 0]}
],
"Instances": [
{"ElementId": 1, "GeometryId": 1},
{"ElementId": 2, "GeometryId": 2}
]
},
"PointColors": {"1": "/wAAAP8AAAD/"}
}
Loading