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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ ioviewer project.glb -o viewer.html
```

Open **Element table** in the viewer and choose `elements.csv`. The viewer reads the file locally and links rows to GLB node
`extras.elementId` values. Search by any part of the element ID or name and narrow the rows by category. Selecting a row
`extras.elementId` values. When both files provide a `uniqueId` for that ID, it must match. The viewer warns about
conflicts and excludes those rows from the table, totals and downloads. Older files without `uniqueId` still match by
`elementId`. Search by any part of the element ID or name and narrow the rows by category. Selecting a row
highlights all its 3D placements. Picking in 3D opens the row's page and highlights the row. If the row is outside the
current results, it appears above them while the search and category stay active. Click a column heading to sort ascending,
then click again to sort descending. Element, category, and type IDs and the quantity columns are sorted numerically,
Expand Down
4 changes: 4 additions & 0 deletions src/IOViewer/Exporters/JsonViewerExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ internal sealed class ViewerJsonFile
public string Kind { get; set; } = FileKind;
public int Format { get; set; } = CurrentFormat;
public SceneDocument Scene { get; set; } = new();
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public Dictionary<int, string?>? GlbUniqueIds { get; set; }
public List<ViewerSectionPlane> SectionPlanes { get; set; } = [];
public ViewerSectionBox? SectionBox { get; set; }
public List<string> HiddenModelKeys { get; set; } = [];
Expand All @@ -88,6 +90,7 @@ internal sealed class ViewerJsonFile
public static ViewerJsonFile From(ViewerDocument doc) => new()
{
Scene = doc.Scene,
GlbUniqueIds = doc.GlbUniqueIds.Count > 0 ? doc.GlbUniqueIds : null,
SectionPlanes = doc.SectionPlanes,
SectionBox = doc.SectionBox,
HiddenModelKeys = doc.HiddenModelKeys,
Expand All @@ -104,6 +107,7 @@ internal sealed class ViewerJsonFile

public ViewerDocument ToDocument() => new(Scene)
{
GlbUniqueIds = GlbUniqueIds ?? [],
SectionPlanes = SectionPlanes,
SectionBox = SectionBox,
HiddenModelKeys = HiddenModelKeys,
Expand Down
14 changes: 14 additions & 0 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ internal sealed class ViewerPayloadWriter
private InstanceViews _lineViews;
private readonly Dictionary<int, byte[]> _pointColors;
private readonly Dictionary<int, byte[]> _pointIntensities;
private readonly Dictionary<int, string?> _glbUniqueIds;
private readonly List<(int Element, Vector3d Position, double Yaw, BlobView Image, BlobView? Intensity, string? Name)> _panoramas = [];
private readonly List<PreparedAnnotation> _annotations = [];
private readonly List<PreparedSheet> _sheets = [];
Expand All @@ -79,6 +80,7 @@ private ViewerPayloadWriter(ViewerDocument doc, HtmlViewerOptions options)
_bcfTopics = doc.BcfTopics;
_pointColors = doc.PointColors;
_pointIntensities = doc.PointIntensities;
_glbUniqueIds = doc.GlbUniqueIds;
_initialSheetKey = doc.InitialSheetKey;
_options = options;
}
Expand Down Expand Up @@ -895,7 +897,19 @@ public void WriteMeta(Stream output)
w.WriteString("author", host?.Author ?? "IOViewer");
w.WriteString("createdAt", host?.CreatedAt ?? DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture));
if (_scene.Models.Count == 1 && host?.SourceFormat == "glb" && _scene.Elements.Any(el => el.SourceId is not null))
{
w.WriteBoolean("elementCsv", true);
if (_glbUniqueIds.Count > 0)
{
w.WriteStartObject("glbUniqueIds");
foreach (var (elementId, uniqueId) in _glbUniqueIds)
{
w.WriteString(elementId.ToString(CultureInfo.InvariantCulture), uniqueId);
FlushIfLarge(w);
}
w.WriteEndObject();
}
}
WriteVector(w, "rtcOffset", _rtcOffset);
WriteBox(w, "bbox", _bounds, _rtcOffset);

Expand Down
27 changes: 20 additions & 7 deletions src/IOViewer/Importers/GlbViewerImporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ private static ViewerDocument Load(Stream stream, string documentTitle, string m

var doc = new SceneDocument { Title = documentTitle };
doc.Models.Add(new SceneModel { Id = 1, Key = modelKey, Name = documentTitle, Path = path, SourceFormat = "glb" });
var viewer = new ViewerDocument(doc);

using var jsonDoc = JsonDocument.Parse(jsonText);
var root = jsonDoc.RootElement;
Expand All @@ -94,7 +95,7 @@ private static ViewerDocument Load(Stream stream, string documentTitle, string m
!root.TryGetProperty("bufferViews", out var bufferViewsEl) ||
binBuffer is null)
{
return new ViewerDocument(doc);
return viewer;
}

var bufferViews = bufferViewsEl.EnumerateArray().ToArray();
Expand Down Expand Up @@ -256,10 +257,16 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName, int? source

var node = nodes[nodeIndex];
var world = ReadNodeTransform(node).Then(parentWorld);
var (sourceId, uniqueId) = ReadIdentity(node);
if (sourceId is int id && uniqueId is not null
&& !viewer.GlbUniqueIds.TryAdd(id, uniqueId) && viewer.GlbUniqueIds[id] != uniqueId)
{
viewer.GlbUniqueIds[id] = null;
}
if (node.TryGetProperty("mesh", out var meshProp))
{
Instantiate(meshProp.GetInt32(), world,
node.TryGetProperty("name", out var nodeName) ? nodeName.GetString() : null, ReadElementId(node));
node.TryGetProperty("name", out var nodeName) ? nodeName.GetString() : null, sourceId);
}

if (node.TryGetProperty("children", out var children))
Expand All @@ -275,13 +282,19 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName, int? source
for (int i = 0; i < meshElements.Length; i++) Instantiate(i, Transform3d.Identity, null, null);
}

return new ViewerDocument(doc);
return viewer;
}

private static int? ReadElementId(JsonElement node) =>
node.TryGetProperty("extras", out var extras) && extras.ValueKind == JsonValueKind.Object
&& extras.TryGetProperty("elementId", out var id) && id.ValueKind == JsonValueKind.Number && id.TryGetInt32(out int value)
? value : null;
private static (int? ElementId, string? UniqueId) ReadIdentity(JsonElement node)
{
if (!node.TryGetProperty("extras", out var extras) || extras.ValueKind != JsonValueKind.Object
|| !extras.TryGetProperty("elementId", out var id) || id.ValueKind != JsonValueKind.Number || !id.TryGetInt32(out int value))
return (null, null);

string? uniqueId = extras.TryGetProperty("uniqueId", out var unique) && unique.ValueKind == JsonValueKind.String
? unique.GetString() : null;
return (value, string.IsNullOrWhiteSpace(uniqueId) ? null : uniqueId);
}

// The sRGB byte of a linear channel: the standard sRGB transfer function, then the nearest byte.
private static byte Srgb(double linear)
Expand Down
3 changes: 3 additions & 0 deletions src/IOViewer/Model/ViewerDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ public ViewerDocument(SceneDocument scene)
/// <summary>The model data.</summary>
public SceneDocument Scene { get; set; } = new();

// Keyed by GLB extras.elementId, including nodes without geometry. Null marks conflicting UniqueIds in the GLB.
internal Dictionary<int, string?> GlbUniqueIds { get; set; } = [];

/// <summary>Cutting planes active at start.</summary>
public List<ViewerSectionPlane> SectionPlanes { get; set; } = [];

Expand Down
362 changes: 181 additions & 181 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const dictionaries = {
'csv.loading': 'Чтение CSV…',
'csv.loaded': '{file} · Связано с 3D: {matched} из {total}',
'csv.noMatch': '{file} · Нет совпадений. Проверьте, что CSV относится к этой модели.',
'csv.conflicts': 'Исключено строк из-за конфликта uniqueId: {count}. Проверьте, что файлы относятся к одной модели.',
'csv.invalid': 'Не удалось прочитать CSV. Выберите таблицу элементов RvtIO с уникальным elementId.',
'csv.noGeometry': 'У этого элемента нет геометрии в модели.',
'csv.search': 'Поиск по ID и имени',
Expand Down Expand Up @@ -257,6 +258,7 @@ const dictionaries = {
'csv.loading': 'Reading CSV…',
'csv.loaded': '{file} · Linked to 3D: {matched} of {total}',
'csv.noMatch': '{file} · No matches. Check that the CSV belongs to this model.',
'csv.conflicts': 'Rows excluded due to conflicting uniqueId values: {count}. Check that the files belong to the same model.',
'csv.invalid': 'Could not read the CSV. Choose an RvtIO element table with unique elementId values.',
'csv.noGeometry': 'This element has no geometry in the model.',
'csv.search': 'Search by ID and name',
Expand Down
13 changes: 13 additions & 0 deletions src/IOViewer/Viewer/src/model/elementCsv.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ export function parseElementCsv(text) {
return { columns, rows, idColumn, rowById };
}

export function reconcileElementRows(csv, glbUniqueIds) {
if (!glbUniqueIds) return { csv, conflicts: 0 };
const uniqueIdColumn = csv.columns.indexOf('uniqueId');
const rows = csv.rows.filter((row) => {
const glbId = glbUniqueIds[row[csv.idColumn]];
const csvId = row[uniqueIdColumn];
// Null marks an elementId assigned to different UniqueIds by nodes in the GLB itself.
return glbId !== null && (glbId === undefined || !csvId?.trim() || glbId === csvId);
});
const conflicts = csv.rows.length - rows.length;
return { csv: conflicts ? { ...csv, ...indexRows(csv, rows) } : csv, conflicts };
}

export function filterElementRows(csv, search, category) {
const query = search.trim().toLowerCase();
if (!query && category === null) return csv;
Expand Down
2 changes: 1 addition & 1 deletion src/IOViewer/Viewer/src/ui/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function mountUI({ root, data, scene, controls, picker, selection, measur
shell.registerPanel('elements', {
icon: icons.elements,
title: t('panel.elements'),
render: (body) => mountElementTable(body, meta.elements, selection),
render: (body) => mountElementTable(body, meta.elements, selection, meta.glbUniqueIds),
});
}
const properties = document.createElement('aside');
Expand Down
11 changes: 7 additions & 4 deletions src/IOViewer/Viewer/src/ui/elementTable.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { formatCount, lang, t } from '../i18n.js';
import { filterElementRows, formatElementCsv, groupElementRows, parseElementCsv, QUANTITY_COLUMNS, sortElementRows, sumElementQuantities } from '../model/elementCsv.js';
import { filterElementRows, formatElementCsv, groupElementRows, parseElementCsv, QUANTITY_COLUMNS, reconcileElementRows, sortElementRows, sumElementQuantities } from '../model/elementCsv.js';
import { el } from './dom.js';

const PAGE_SIZE = 100;
Expand Down Expand Up @@ -28,7 +28,7 @@ function createTotals(label) {
};
}

export function mountElementTable(body, elements, selection) {
export function mountElementTable(body, elements, selection, glbUniqueIds) {
const elementById = new Map();
elements.forEach((element, index) => {
if (element.sourceId != null) elementById.set(element.sourceId, index);
Expand Down Expand Up @@ -244,7 +244,9 @@ export function mountElementTable(body, elements, selection) {
try {
const text = await file.text();
if (request !== loadRequest) return;
csv = parseElementCsv(text);
const parsed = parseElementCsv(text);
const { csv: compatible, conflicts } = reconcileElementRows(parsed, glbUniqueIds);
csv = compatible;
downloadName = file.name.replace(/\.csv$/i, '') + '-filtered.csv';
sortColumn = -1;
ascending = true;
Expand Down Expand Up @@ -276,7 +278,8 @@ export function mountElementTable(body, elements, selection) {
}
let matched = 0;
for (const id of elementById.keys()) if (csv.rowById.has(id)) matched++;
status.textContent = message(matched ? 'csv.loaded' : 'csv.noMatch', { file: file.name, matched, total: csv.rows.length });
status.textContent = message(matched || conflicts ? 'csv.loaded' : 'csv.noMatch', { file: file.name, matched, total: parsed.rows.length });
if (conflicts) status.append(' · ', message('csv.conflicts', { count: formatCount(conflicts) }));
const categoryColumn = csv.columns.indexOf('category');
category.hidden = categoryColumn < 0;
groupToggle.hidden = category.hidden;
Expand Down
56 changes: 52 additions & 4 deletions src/IOViewer/Viewer/test/e2e/element-table.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { viewerDir } from './global-setup.js';

const screenAt = (page, index) => page.evaluate((i) => {
const screenAt = (page, index, xFraction = 0.5) => page.evaluate(({ index, xFraction }) => {
const { scene, camera } = window.__ioviewer;
const box = scene.elementBox(i);
const center = box.getCenter(box.min.clone()).project(camera);
const box = scene.elementBox(index);
const center = box.getCenter(box.min.clone());
center.x = box.min.x + (box.max.x - box.min.x) * xFraction;
center.project(camera);
const rect = document.getElementById('ioviewer-canvas').getBoundingClientRect();
return [rect.left + ((center.x + 1) / 2) * rect.width, rect.top + ((1 - center.y) / 2) * rect.height];
}, index);
}, { index, xFraction });

test('CSV selects all GLB placements and picking in 3D finds the row on another page', async ({ page }) => {
const errors = [];
Expand Down Expand Up @@ -47,6 +49,52 @@ test('CSV selects all GLB placements and picking in 3D finds the row on another
expect(errors).toEqual([]);
});

test('conflicting UniqueIds prevent linking and exclude foreign quantities from totals and downloads', async ({ page }) => {
await page.goto(pathToFileURL(path.join(viewerDir, 'test-results', 'element-table.html')).href);
await page.evaluate(() => window.__ioviewer.ready);
await page.getByRole('button', { name: 'Таблица элементов' }).click();
const panel = page.getByRole('region', { name: 'Таблица элементов' });
const heading = 'elementId,uniqueId,name,category,volume_m3';
const load = async (name, rows) => {
await panel.locator('input[type=file]').setInputFiles({
name, mimeType: 'text/csv', buffer: Buffer.from([heading, ...rows].join('\n')),
});
await expect(panel.getByRole('status')).toContainText(name);
};

const foreign = '101,other-wall-101,Чужая стена,Стены,100';
await load('foreign.csv', [foreign]);
await expect(panel.getByRole('status')).toContainText('Связано с 3D: 0 из 1');
await expect(panel.getByRole('status')).toContainText('конфликта uniqueId: 1');
await expect(panel.getByRole('button', { name: '101', exact: true })).toHaveCount(0);
await expect(panel.locator('.ioviewer-csv-totals dd')).toHaveText(['0', '—', '—', '—']);

const fallback = '202,csv-only-202,Колонна,Опоры,3';
await load('mixed.csv', [foreign, fallback]);
await expect(panel.getByRole('status')).toContainText('Связано с 3D: 1 из 2');
await panel.getByRole('checkbox', { name: 'Группировать по категориям' }).check();
await expect(panel.locator('.ioviewer-csv-group-heading strong')).toHaveText(['Опоры']);
await expect(panel.locator('.ioviewer-csv-group-heading dd')).toHaveText(['1', '—', '—', '3 м³']);
const download = page.waitForEvent('download');
await panel.getByRole('button', { name: 'Скачать CSV' }).click();
const file = await readFile(await (await download).path(), 'utf8');
expect(file).toBe('\uFEFF' + [heading + ',element_count', fallback + ',', 'SUBTOTAL,,,Опоры,3,1', 'TOTAL,,,,3,1', ''].join('\r\n'));

const toggle = page.getByRole('button', { name: 'Таблица элементов' });
await toggle.click();
// Element 101 has two placements. Aim inside the first, away from the gap between them.
await page.mouse.click(...(await screenAt(page, 0, 0.25)));
expect(await page.evaluate(() => [...window.__ioviewer.selection.values()])).toEqual([0]);
await toggle.click();
await expect(panel.getByRole('button', { name: '101', exact: true })).toHaveCount(0);
await expect(panel.getByText('Чужая стена')).toHaveCount(0);

await load('matching.csv', ['101,wall-101,Стена,Стены,5']);
await expect(panel.getByRole('status')).toContainText('Связано с 3D: 1 из 1');
await expect(panel.getByRole('status')).not.toContainText('конфликта uniqueId');
await expect(panel.getByRole('button', { name: '101', exact: true })).toHaveAttribute('aria-pressed', 'true');
});

test('search and category preserve two-way selection, including a picked row outside the filters', async ({ page }) => {
await page.goto(pathToFileURL(path.join(viewerDir, 'test-results', 'element-table.html')).href);
await page.evaluate(() => window.__ioviewer.ready);
Expand Down
4 changes: 2 additions & 2 deletions src/IOViewer/Viewer/test/e2e/global-setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ function elementTableGlb() {
accessors: [{ bufferView: 0, componentType: 5126, count: positions.length / 3, type: 'VEC3' },
{ bufferView: 1, componentType: 5125, count: box.Indices.length, type: 'SCALAR' }],
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],
nodes: [[101, -2], [101, -0.8], [202, 2]].map(([elementId, x]) =>
({ mesh: 0, translation: [x, 0, 0], extras: { elementId } })),
nodes: [[101, -2, 'wall-101'], [101, -0.8, 'wall-101'], [202, 2]].map(([elementId, x, uniqueId]) =>
({ mesh: 0, translation: [x, 0, 0], extras: { elementId, uniqueId } })),
scenes: [{ nodes: [0, 1, 2] }],
});
const metadata = Buffer.from(json.padEnd(Math.ceil(json.length / 4) * 4));
Expand Down
19 changes: 18 additions & 1 deletion src/IOViewer/Viewer/test/unit/elementCsv.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { filterElementRows, formatElementCsv, groupElementRows, parseElementCsv, sortElementRows, sumElementQuantities } from '../../src/model/elementCsv.js';
import { filterElementRows, formatElementCsv, groupElementRows, parseElementCsv, reconcileElementRows, sortElementRows, sumElementQuantities } from '../../src/model/elementCsv.js';

test('reconciles supplied UniqueIds and keeps rows lacking either identity', () => {
const parsed = parseElementCsv([
'elementId,uniqueId,volume_m3', '101,foreign,100', '102,wall,2', '103,,3', '104,csv-only,4',
'105,ambiguous,100', '106, ,6', '107,unmodeled,7',
].join('\n'));
const glbUniqueIds = { 101: 'wall', 102: 'wall', 103: 'known', 105: null, 106: 'known' };
const { csv, conflicts } = reconcileElementRows(parsed, glbUniqueIds);
assert.equal(conflicts, 2);
assert.deepEqual([...csv.rowById], [['102', 0], ['103', 1], ['104', 2], ['106', 3], ['107', 4]]);
assert.deepEqual(sumElementQuantities(csv, csv.rows), [null, null, 22]);
assert.equal(parsed.rows.length, 7);

const legacy = parseElementCsv('elementId,volume_m3\n101,1');
assert.deepEqual(reconcileElementRows(legacy, glbUniqueIds), { csv: legacy, conflicts: 0 });
assert.deepEqual(reconcileElementRows(parsed, undefined), { csv: parsed, conflicts: 0 });
});

test('reads RvtIO CSV with BOM, LF/CRLF, Unicode, quotes, empty cells and zero', () => {
const value = parseElementCsv('\uFEFFelementId,name,volume_m3\r\n-2,"Стена, ""А""\r\nсекция",\r\n0,,0');
Expand Down
Loading
Loading