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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ The documentation site with API references and guides is at <https://ioextend.gi
- The API can evolve before 1.0.
- Standalone HTML export generates self-contained files with all geometry inlined. IOViewer does not simplify meshes, so models with millions of triangles produce large files; reduce them before export.
- The binary geometry block is assembled in memory before it is written, so it must stay below 2 GB.
- The [local clustered LOD viewer](docs/viewer-performance-baseline.md#real-ifc-and-rvt) supports element visibility and isolation, properties, filled sections, measurement snapping and display modes. Cluster packages also carry authored review data, including saved views, linked models, grids, clashes, BCF and 4D. The [14.85 GB benchmark](docs/viewer-performance-baseline.md#1485-gb-federation-of-real-geometry) exercises page streaming across a federation of prepared IFC/RVT geometry.
- The [local clustered LOD viewer](docs/viewer-performance-baseline.md#real-ifc-and-rvt) supports element visibility and isolation, properties, filled sections, measurement snapping and display modes. Cluster packages carry authored review data, including saved views, linked models, grids, clashes, BCF and 4D, and [share exact repeated meshes](docs/viewer-performance-baseline.md#repeated-meshes). The [14.85 GB benchmark](docs/viewer-performance-baseline.md#1485-gb-federation-of-real-geometry) exercises page streaming across a federation of prepared IFC/RVT geometry.
- `HtmlViewerOptions.MaxMeshVertices` is unlimited by default. When a lower limit cuts the model, the viewer shows a banner with the number of meshes written.
- The viewer needs WebGL 2; without it the page says so. If the browser drops the graphics context, the page shows a message asking to reload it.
- Transparent objects are sorted per chunk of merged geometry (or per cell of instanced copies), not per object, so overlapping transparent objects in the same chunk can blend in the wrong order.
Expand Down
25 changes: 25 additions & 0 deletions docs/viewer-performance-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,31 @@ Both hierarchies retained all triangles returned by their adapters. The RVT adap
drawable geometry and 33 with potentially missing parts. Import and handoff took around 21 seconds for the IFC and
7 minutes 26 seconds for the RVT. The measurements in the table start at browser navigation to prepared data.

#### Repeated meshes

The cluster export reuses meshes that reference the same source geometry and detects exact copies stored under
distinct geometry IDs. Coordinates, triangle indices in their original order, normals and UVs are compared at
source precision. A hash narrows the search and a full comparison confirms each match. Copies with the same
rotation, scale and handedness share a template even if their translations, materials or element IDs differ.
Each distinct linear transform is baked separately. A placement keeps ordinary coordinates if reconstructing
its vertices from the template and shift would change any coordinate by more than half the viewer's 1/1024 m grid step.

The builder writes shared meshes to `shapes.bin` and stores their placements in leaf pages. The viewer draws
opaque and blended batches separately and groups textured batches by texture. Each visible batch uses GPU
instancing, and the page-buffer budget includes its geometry and instance attributes. Properties, selection,
visibility and measurement still operate on individual placements. Coarse ancestors keep their simplified meshes.
Existing `.ivmesh` files and ready-made packages remain readable. Re-export the source and repack it to pick up
instances.

| Input | Placed records using shared meshes | Geometry without / with instances, MB | Peak page buffers, MiB |
| --- | ---: | ---: | ---: |
| 746 MB IFC | 1,378 | 594.7 / 586.0 | 90.4 / 98.1 |
| 139 MB RVT | 1,133 | 297.4 / 279.3 | 107.5 / 91.6 |

Each pair was packed from the same export and retained the same triangle count. Geometry totals include `shapes.bin`.
Chromium on Radeon measured 16.8 ms p95 across the orbit and close route for both packages in each pair. The extra
leaf batches changed the cluster hierarchy and the number of resident pages along each route.

#### Close RVT profile

The second traversal can still request pages. The third traversal holds new requests after the pending pages finish
Expand Down
157 changes: 138 additions & 19 deletions src/IOViewer/Exporters/ClusterSourceWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ internal static class ClusterSourceWriter
{
private const int RecordIndices = 8192 * 3;
private const uint Signature = 0x33534d49; // IMS3
private const uint SharedSignature = 0x34534d49; // IMS4

// shortcut: share translations within each baked linear transform, until streamed draws carry full matrices.
private readonly record struct ShapeKey(int Geometry, Vector3d X, Vector3d Y, Vector3d Z);
private readonly record struct ShapeRecord(long Offset, BoundingBox3d Bounds, int Vertices, int Indices, bool Closed);

internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions options)
{
Expand All @@ -37,12 +42,23 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt
var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id);
var materials = scene.Materials.ToDictionary(material => material.Id);
var textures = scene.Textures.Select((texture, index) => (texture.Id, index)).ToDictionary(texture => texture.Id, texture => texture.index);
var canonical = FindEqualMeshes(geometries, scene.Instances);
ShapeKey Key(SceneInstance instance, Transform3d t) => new(canonical[instance.GeometryId], t.XAxis, t.YAxis, t.ZAxis);
var uses = new Dictionary<ShapeKey, int>();
foreach (var instance in scene.Instances)
{
if (!canonical.ContainsKey(instance.GeometryId)) continue;
var key = Key(instance, instance.Transform ?? Transform3d.Identity);
uses[key] = uses.GetValueOrDefault(key) + 1;
}
var templates = uses.Where(entry => entry.Value > 1).ToDictionary(entry => entry.Key, _ => new List<ShapeRecord>());
bool sharedFormat = templates.Count > 0;
var closed = new Dictionary<int, bool>();
var bounds = scene.ComputeBounds();
var origin = bounds.IsEmpty ? Vector3d.Zero : bounds.Center;
if (!double.IsFinite(origin.X) || !double.IsFinite(origin.Y) || !double.IsFinite(origin.Z))
throw new InvalidDataException("Non-finite scene origin.");
writer.Write(Signature);
writer.Write(sharedFormat ? SharedSignature : Signature);
writer.Write(origin.X);
writer.Write(origin.Y);
writer.Write(origin.Z);
Expand All @@ -65,12 +81,30 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt
? textures.GetValueOrDefault(textureId, -1) : -1;
var transform = instance.Transform ?? Transform3d.Identity;
var rebased = transform with { Translation = transform.Translation - origin };
var template = canonical.ContainsKey(geometry.Id) ? templates.GetValueOrDefault(Key(instance, transform)) : null;
bool hasNormals = geometry.Normals?.Count == geometry.Vertices.Count;
bool hasUvs = geometry.UVs?.Count == geometry.Vertices.Count;
var shift = Vector3d.Zero;
if (template is not null && SharedTranslation(geometry, rebased) is { } translation)
{
shift = translation;
if (template.Count > 0)
{
foreach (var record in template)
{
WriteHeader(record.Bounds, record.Vertices, record.Indices, record.Closed, record.Offset);
triangles += record.Indices / 3;
}
continue;
}
rebased = transform with { Translation = Vector3d.Zero };
}
else template = null;
var nx = Vector3d.Cross(transform.YAxis, transform.ZAxis);
var ny = Vector3d.Cross(transform.ZAxis, transform.XAxis);
var nz = Vector3d.Cross(transform.XAxis, transform.YAxis);
bool mirrored = Vector3d.Dot(transform.XAxis, nx) < 0;
bool hasIndices = geometry.Indices.Count != 0;
bool hasNormals = geometry.Normals?.Count == geometry.Vertices.Count;
int count = hasIndices ? geometry.Indices.Count : geometry.Vertices.Count / 3 * 3;
if (count % 3 != 0) throw new InvalidDataException($"Invalid triangle indices in geometry {geometry.Id}.");
if (!closed.TryGetValue(geometry.Id, out bool solid))
Expand All @@ -94,33 +128,22 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt
{
slot = vertices.Count;
remap.Add(index, slot);
var p = rebased.Apply(geometry.Vertices[index]);
var point = new Vector3d((float)p.X, (float)p.Y, (float)p.Z);
if (!float.IsFinite((float)point.X) || !float.IsFinite((float)point.Y) || !float.IsFinite((float)point.Z))
throw new InvalidDataException($"Non-finite vertex in geometry {geometry.Id}.");
var p = template is null ? geometry.Vertices[index] : geometry.Vertices[index] - geometry.Vertices[0];
var point = RoundPoint(rebased.Apply(p));
vertices.Add(point);
box = box.Encapsulate(point);
if (hasNormals)
{
var n = geometry.Normals![index];
normals.Add(((nx * n.X + ny * n.Y + nz * n.Z) * (mirrored ? -1 : 1)).Normalized());
}
if (texture >= 0) uvs.Add(geometry.UVs![index]);
if (texture >= 0 || (template is not null && hasUvs)) uvs.Add(geometry.UVs![index]);
}
indices.Add(slot);
}
WriteVector(writer, box.Min);
WriteVector(writer, box.Max);
writer.Write(vertices.Count);
writer.Write(length);
writer.Write(color.R);
writer.Write(color.G);
writer.Write(color.B);
writer.Write(color.A);
writer.Write(hasNormals ? 1 : 0);
writer.Write(instance.ElementId);
writer.Write(texture);
writer.Write(solid ? 1 : 0);
long offset = template is null ? -1 : writer.BaseStream.Position;
template?.Add(new ShapeRecord(offset, box, vertices.Count, length, solid));
WriteHeader(box, vertices.Count, length, solid, offset);
foreach (var p in vertices) WriteVector(writer, p);
foreach (var n in normals) WriteVector(writer, n);
foreach (int i in indices) writer.Write(i);
Expand All @@ -134,6 +157,27 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt
triangles += length / 3;
start += length;
}

void WriteHeader(BoundingBox3d box, int vertexCount, int indexCount, bool isClosed, long shapeOffset)
{
WriteVector(writer, template is null ? box.Min : RoundBounds(box.Min + shift, false));
WriteVector(writer, template is null ? box.Max : RoundBounds(box.Max + shift, true));
writer.Write(vertexCount);
writer.Write(indexCount);
writer.Write(color.R);
writer.Write(color.G);
writer.Write(color.B);
writer.Write(color.A);
writer.Write(hasNormals ? 1 : 0);
writer.Write(instance.ElementId);
writer.Write(texture);
writer.Write((isClosed ? 1 : 0) | (sharedFormat && (texture >= 0 || (template is not null && hasUvs)) ? 2 : 0));
if (sharedFormat)
{
writer.Write(shapeOffset);
WriteVector(writer, shift);
}
}
}
if (triangles == 0) throw new InvalidDataException("The source contains no triangle geometry.");
long geometryEnd = writer.BaseStream.Position;
Expand All @@ -150,6 +194,81 @@ private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOpt
return triangles;
}

private static Vector3d? SharedTranslation(SceneGeometry geometry, Transform3d rebased)
{
// Two float32 values can cancel and erase detail that the original world-space vertex retains.
const double tolerance = GeometryQuantizer.Step / 2;
static bool Preserved(double world, double local, double shift) =>
Math.Abs((double)(float)world - (float)((float)local + shift)) <= tolerance;

var anchor = geometry.Vertices[0];
var position = rebased.Apply(anchor);
var shift = new Vector3d((float)position.X, (float)position.Y, (float)position.Z);
var linear = rebased with { Translation = Vector3d.Zero };
foreach (var vertex in geometry.Vertices)
{
var world = rebased.Apply(vertex);
var local = linear.Apply(vertex - anchor);
if (!Preserved(world.X, local.X, shift.X) || !Preserved(world.Y, local.Y, shift.Y)
|| !Preserved(world.Z, local.Z, shift.Z)) return null;
}
return shift;
}

private static Vector3d RoundPoint(Vector3d p)
{
var point = new Vector3d((float)p.X, (float)p.Y, (float)p.Z);
if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z))
throw new InvalidDataException("Non-finite vertex or placement in clustered geometry.");
return point;
}

private static Vector3d RoundBounds(Vector3d p, bool upper)
{
static float Outward(double value, bool upper)
{
var rounded = (float)value;
return upper && rounded < value ? MathF.BitIncrement(rounded)
: !upper && rounded > value ? MathF.BitDecrement(rounded) : rounded;
}
RoundPoint(p);
return new(Outward(p.X, upper), Outward(p.Y, upper), Outward(p.Z, upper));
}

private static Dictionary<int, int> FindEqualMeshes(Dictionary<int, SceneGeometry> geometries, IEnumerable<SceneInstance> instances)
{
var used = instances.Select(instance => instance.GeometryId).Distinct().Select(id => geometries.GetValueOrDefault(id))
.Where(mesh => mesh is { Topology: SceneTopology.Triangles } && mesh.Vertices.Count >= 3).Select(mesh => mesh!);
var canonical = new Dictionary<int, int>();
foreach (var group in used.GroupBy(mesh => (mesh.Vertices.Count, mesh.Indices.Count, mesh.Normals?.Count, mesh.UVs?.Count)))
{
if (!group.Skip(1).Any())
{
var mesh = group.First();
canonical.Add(mesh.Id, mesh.Id);
continue;
}
var candidates = new Dictionary<int, List<SceneGeometry>>();
foreach (var mesh in group)
{
var hash = new HashCode();
foreach (var vertex in mesh.Vertices) hash.Add(vertex);
foreach (var index in mesh.Indices) hash.Add(index);
if (mesh.Normals is { } normals) foreach (var normal in normals) hash.Add(normal);
if (mesh.UVs is { } uvs) foreach (var uv in uvs) hash.Add(uv);
var key = hash.ToHashCode();
if (!candidates.TryGetValue(key, out var matches)) candidates.Add(key, matches = []);
var equal = matches.Find(candidate => candidate.Vertices.SequenceEqual(mesh.Vertices)
&& candidate.Indices.SequenceEqual(mesh.Indices) && Same(candidate.Normals, mesh.Normals) && Same(candidate.UVs, mesh.UVs));
if (equal is null) matches.Add(mesh);
canonical.Add(mesh.Id, equal?.Id ?? mesh.Id);
}
}
return canonical;

static bool Same<T>(IReadOnlyList<T>? a, IReadOnlyList<T>? b) => a is null ? b is null : b is not null && a.SequenceEqual(b);
}

// Tessellation can duplicate vertices at normal and UV seams.
private static bool IsClosed(SceneGeometry geometry, int count)
{
Expand Down
Loading