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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,30 @@ ioviewer model.nwc -o viewer.html
ioviewer model.glb --serve
```

To link a Revit element table with the model, export both files from the same RvtIO run and generate a viewer from the GLB.

```sh
rvtio project.rvt --glb project.glb --csv elements.csv
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
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,
with empty values last. The summary shows the count and total length, area, and volume for all matching rows across
pages. Missing measurements are skipped. A quantity with no valid measurements is shown as a dash.
Enable **Group by category** to see counts and sums for each category alongside its element rows. The totals cover
the full matching group on each page where it appears. Categories appear alphabetically, and selecting the category
heading as the sort column controls the category order. Sorting on another column orders elements within each group.
**Download CSV** saves every matching row across all pages in the selected row order. When grouping is enabled,
each category is followed by a row with `SUBTOTAL` in `elementId` and the category name in `category`. The last row
has `TOTAL` in `elementId`. Both summaries put the element count in `element_count` and sums in the source quantity
columns. Existing columns keep their order. Missing sums are blank, and an empty result exports a count of zero.
The viewer skips summary rows when reopening a downloaded CSV and recalculates the totals from the element rows.
This panel is available for single-model GLB viewers with source element IDs.

Pass `--add` and `--placement` to combine several source models into one offline HTML viewer.

```sh
Expand Down
2 changes: 2 additions & 0 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,8 @@ public void WriteMeta(Stream output)
var host = _scene.Models.Count > 0 ? _scene.Models[0] : null;
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);
WriteVector(w, "rtcOffset", _rtcOffset);
WriteBox(w, "bbox", _bounds, _rtcOffset);

Expand Down
30 changes: 23 additions & 7 deletions src/IOViewer/Importers/GlbViewerImporter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Buffers.Binary;
using System.Globalization;
using System.Text;
using System.Text.Json;
using IOScene;
Expand All @@ -8,7 +9,7 @@ namespace IOViewer.Importers;

/// <summary>
/// Imports standard glTF 2.0 Binary (.glb) files into a ViewerDocument whose scene has one model: one geometry per
/// mesh primitive, one element per node that draws a mesh, and one instance per primitive of that node, with the
/// mesh primitive, one element per source element (or node without a source id), and one instance per primitive, with the
/// node's world transform converted from glTF's Y-up to the scene's Z-up.
/// </summary>
public static class GlbViewerImporter
Expand Down Expand Up @@ -129,10 +130,11 @@ private static ViewerDocument Load(Stream stream, string documentTitle, string m
// Parse meshes lazily: one geometry per (mesh, primitive), one instance per primitive of a node occurrence.
var meshElements = root.TryGetProperty("meshes", out var meshesEl) ? meshesEl.EnumerateArray().ToArray() : [];
var geometryIds = new Dictionary<(int Mesh, int Primitive), int?>();
var sourceElements = new Dictionary<int, SceneElement>();
int meshCounter = 0;

// One element per node occurrence: all primitives of its mesh select, hide and list as one object.
void Instantiate(int meshIndex, Transform3d world, string? nodeName)
// Mesh placements sharing an explicit source element id select and hide together.
void Instantiate(int meshIndex, Transform3d world, string? nodeName, int? sourceId)
{
if (meshIndex < 0 || meshIndex >= meshElements.Length)
{
Expand All @@ -143,7 +145,7 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName)
string meshName = meshEl.TryGetProperty("name", out var mn) ? mn.GetString() ?? $"Mesh {meshCounter + 1}" : $"Mesh {meshCounter + 1}";
if (!meshEl.TryGetProperty("primitives", out var primsEl)) return;

SceneElement? element = null;
SceneElement? element = sourceId is int id ? sourceElements.GetValueOrDefault(id) : null;
int primIndex = -1;
foreach (var prim in primsEl.EnumerateArray())
{
Expand Down Expand Up @@ -204,8 +206,16 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName)

if (element is null)
{
element = new SceneElement { Id = doc.Elements.Count + 1, ModelId = 1, Name = string.IsNullOrEmpty(nodeName) ? meshName : nodeName, Category = "GLB" };
element = new SceneElement
{
Id = doc.Elements.Count + 1,
ModelId = 1,
Name = string.IsNullOrEmpty(nodeName) ? meshName : nodeName,
Category = "GLB",
SourceId = sourceId?.ToString(CultureInfo.InvariantCulture),
};
doc.Elements.Add(element);
if (sourceId is int newId) sourceElements.Add(newId, element);
}

++meshCounter;
Expand Down Expand Up @@ -248,7 +258,8 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName)
var world = ReadNodeTransform(node).Then(parentWorld);
if (node.TryGetProperty("mesh", out var meshProp))
{
Instantiate(meshProp.GetInt32(), world, node.TryGetProperty("name", out var nodeName) ? nodeName.GetString() : null);
Instantiate(meshProp.GetInt32(), world,
node.TryGetProperty("name", out var nodeName) ? nodeName.GetString() : null, ReadElementId(node));
}

if (node.TryGetProperty("children", out var children))
Expand All @@ -261,12 +272,17 @@ void Instantiate(int meshIndex, Transform3d world, string? nodeName)
else
{
// No scene graph: import every mesh once without a node transform.
for (int i = 0; i < meshElements.Length; i++) Instantiate(i, Transform3d.Identity, null);
for (int i = 0; i < meshElements.Length; i++) Instantiate(i, Transform3d.Identity, null, null);
}

return new ViewerDocument(doc);
}

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;

// The sRGB byte of a linear channel: the standard sRGB transfer function, then the nearest byte.
private static byte Srgb(double linear)
{
Expand Down
398 changes: 201 additions & 197 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

52 changes: 52 additions & 0 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,32 @@ const dictionaries = {
link: 'Связанный файл',
panels: 'Панели',
'panel.model': 'Модель',
'panel.elements': 'Таблица элементов',
'csv.open': 'Открыть CSV элементов',
'csv.download': 'Скачать CSV',
'csv.choose': 'Выберите CSV, экспортированный вместе с этой моделью.',
'csv.loading': 'Чтение CSV…',
'csv.loaded': '{file} · Связано с 3D: {matched} из {total}',
'csv.noMatch': '{file} · Нет совпадений. Проверьте, что CSV относится к этой модели.',
'csv.invalid': 'Не удалось прочитать CSV. Выберите таблицу элементов RvtIO с уникальным elementId.',
'csv.noGeometry': 'У этого элемента нет геометрии в модели.',
'csv.search': 'Поиск по ID и имени',
'csv.searchPlaceholder': 'ID или имя',
'csv.allCategories': 'Все категории',
'csv.groupByCategory': 'Группировать по категориям',
'csv.categoryTotals': 'Итоги категории',
'csv.totals': 'Итоги выборки',
'csv.quantity.length_m': 'Длина',
'csv.quantity.area_m2': 'Площадь',
'csv.quantity.volume_m3': 'Объём',
'csv.unit.length_m': 'м',
'csv.unit.area_m2': 'м²',
'csv.unit.volume_m3': 'м³',
'csv.outsideFilters': 'Выбранный элемент вне фильтра.',
'csv.noResults': 'Подходящих строк нет.',
'csv.previous': 'Назад',
'csv.next': 'Далее',
'csv.range': '{first}–{last} из {total}',
'panel.views': 'Виды',
'panel.sections': 'Сечения',
'panel.clashes': 'Коллизии',
Expand Down Expand Up @@ -224,6 +250,32 @@ const dictionaries = {
link: 'Link',
panels: 'Panels',
'panel.model': 'Model',
'panel.elements': 'Element table',
'csv.open': 'Open element CSV',
'csv.download': 'Download CSV',
'csv.choose': 'Choose the CSV exported with this model.',
'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.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',
'csv.searchPlaceholder': 'ID or name',
'csv.allCategories': 'All categories',
'csv.groupByCategory': 'Group by category',
'csv.categoryTotals': 'Category totals',
'csv.totals': 'Filtered totals',
'csv.quantity.length_m': 'Length',
'csv.quantity.area_m2': 'Area',
'csv.quantity.volume_m3': 'Volume',
'csv.unit.length_m': 'm',
'csv.unit.area_m2': 'm²',
'csv.unit.volume_m3': 'm³',
'csv.outsideFilters': 'The selected element is outside the filter.',
'csv.noResults': 'No matching rows.',
'csv.previous': 'Previous',
'csv.next': 'Next',
'csv.range': '{first}–{last} of {total}',
'panel.views': 'Views',
'panel.sections': 'Sections',
'panel.clashes': 'Clashes',
Expand Down
195 changes: 195 additions & 0 deletions src/IOViewer/Viewer/src/model/elementCsv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
export const QUANTITY_COLUMNS = ['length_m', 'area_m2', 'volume_m3'];
const NUMERIC_COLUMNS = new Set(['elementId', 'categoryId', 'typeId', ...QUANTITY_COLUMNS]);
const DECIMAL = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
const textOrder = new Intl.Collator(undefined, { sensitivity: 'base' });
const TOTAL_ROW_ID = 'TOTAL';
const SUBTOTAL_ROW_ID = 'SUBTOTAL';
const ELEMENT_COUNT_COLUMN = 'element_count';

// RFC 4180-style fields, including escaped quotes and line breaks inside a field.
function readRows(text) {
const rows = [];
let row = [];
let field = '';
let quoted = false;
let closed = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (quoted) {
if (ch !== '"') field += ch;
else if (text[i + 1] === '"') {
field += '"';
i++;
} else {
quoted = false;
closed = true;
}
} else if (ch === ',' || ch === '\r' || ch === '\n') {
row.push(field);
field = '';
closed = false;
if (ch === ',') continue;
if (ch === '\r' && text[i + 1] === '\n') i++;
rows.push(row);
row = [];
} else if (ch === '"' && !field && !closed) {
quoted = true;
} else {
if (closed || ch === '"') throw new Error('Invalid CSV quoting');
field += ch;
}
}
if (quoted) throw new Error('Unclosed CSV field');
if (row.length || field || closed) rows.push([...row, field]);
return rows;
}

export function parseElementCsv(text) {
const [columns, ...records] = readRows(text.replace(/^\uFEFF/, ''));
const idColumn = columns?.indexOf('elementId') ?? -1;
if (idColumn < 0 || new Set(columns).size !== columns.length) throw new Error('Missing or duplicate CSV columns');
const footer = records[records.length - 1];
const hasFooter = footer?.[idColumn] === TOTAL_ROW_ID && footer.length === columns.length && columns.includes(ELEMENT_COUNT_COLUMN);
// These rows summarize an earlier export. Re-import the elements and recalculate their totals.
const hasCategories = columns.includes('category');
const rows = hasFooter ? records.filter((row, index) =>
index !== records.length - 1 && !(hasCategories && row[idColumn] === SUBTOTAL_ROW_ID && row.length === columns.length)) : records;
const rowById = new Map();
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const id = row[idColumn];
const number = Number(id);
if (row.length !== columns.length || !Number.isSafeInteger(number) || String(number) !== id || rowById.has(id)) {
throw new Error('Invalid or duplicate CSV element id');
}
rowById.set(id, i);
}
return { columns, rows, idColumn, rowById };
}

export function filterElementRows(csv, search, category) {
const query = search.trim().toLowerCase();
if (!query && category === null) return csv;

const nameColumn = csv.columns.indexOf('name');
const categoryColumn = csv.columns.indexOf('category');
const rows = [];
const rowById = new Map();
for (const row of csv.rows) {
const id = row[csv.idColumn];
if (category !== null && row[categoryColumn] !== category) continue;
if (query && !id.includes(query) && !row[nameColumn]?.toLowerCase().includes(query)) continue;
rowById.set(id, rows.length);
rows.push(row);
}
return { rows, rowById };
}

export function sortElementRows(csv, results, column, ascending) {
return indexRows(csv, sortRows(results.rows, column, csv.columns[column], ascending));
}

function sortRows(rows, column, name, ascending) {
const numeric = NUMERIC_COLUMNS.has(name);
const keyed = rows.map((row) => {
const text = row[column].trim();
const key = numeric ? decimalNumber(text) : text;
return { row, key, missing: numeric ? !Number.isFinite(key) : !text };
});
keyed.sort((a, b) => {
if (a.missing || b.missing) return Number(a.missing) - Number(b.missing);
const comparison = numeric ? a.key - b.key : textOrder.compare(a.key, b.key);
return ascending ? comparison : -comparison;
});
return keyed.map(({ row }) => row);
}

function indexRows(csv, rows) {
const rowById = new Map();
rows.forEach((row, index) => rowById.set(row[csv.idColumn], index));
return { rows, rowById };
}

export function groupElementRows(csv, results, sortColumn = -1, ascending = true) {
const categoryColumn = csv.columns.indexOf('category');
if (categoryColumn < 0) return results;
const byCategory = new Map();
for (const row of results.rows) {
const category = row[categoryColumn];
if (!byCategory.has(category)) byCategory.set(category, []);
byCategory.get(category).push(row);
}

const groups = [...byCategory].sort(([a], [b]) => {
if (!a || !b) return Number(!a) - Number(!b);
const order = textOrder.compare(a, b);
return sortColumn === categoryColumn && !ascending ? -order : order;
}).map(([category, rows]) => {
const totals = sumElementQuantities(csv, rows);
if (sortColumn >= 0 && sortColumn !== categoryColumn) rows = sortRows(rows, sortColumn, csv.columns[sortColumn], ascending);
return { category, rows, totals };
});
let offset = 0;
for (const group of groups) {
group.start = offset;
offset += group.rows.length;
}
return { ...indexRows(csv, groups.flatMap((group) => group.rows)), groups };
}

export function sumElementQuantities(csv, rows) {
return QUANTITY_COLUMNS.map((name) => {
const column = csv.columns.indexOf(name);
if (column < 0) return null;
let sum = 0;
let hasValue = false;
for (const row of rows) {
const value = decimalNumber(row[column].trim());
if (!Number.isFinite(value)) continue;
sum += value;
hasValue = true;
}
return hasValue && Number.isFinite(sum) ? sum : null;
});
}

function decimalNumber(text) {
return DECIMAL.test(text) ? Number(text) : NaN;
}

export function formatElementCsv(columns, rows, quantityTotals = null, groups = null) {
const appendCount = quantityTotals !== null && !columns.includes(ELEMENT_COUNT_COLUMN);
const headings = appendCount ? [...columns, ELEMENT_COUNT_COLUMN] : columns;
const lines = [headings.map(encodeField).join(',')];
const appendRows = (elements) => {
for (const row of elements) lines.push(row.map(encodeField).join(',') + (appendCount ? ',' : ''));
};
const appendTotal = (id, count, sums, category = '') => {
const row = headings.map((name) => {
if (name === 'elementId') return id;
if (name === ELEMENT_COUNT_COLUMN) return String(count);
if (name === 'category') return category;
const sum = sums[QUANTITY_COLUMNS.indexOf(name)];
return sum == null ? '' : String(sum);
});
lines.push(row.map(encodeField).join(','));
};
if (groups) {
for (const group of groups) {
appendRows(group.rows);
appendTotal(SUBTOTAL_ROW_ID, group.rows.length, group.totals, group.category);
}
} else {
appendRows(rows);
}
if (quantityTotals !== null) appendTotal(TOTAL_ROW_ID, rows.length, quantityTotals);
return '\uFEFF' + lines.join('\r\n') + '\r\n';
}

function encodeField(value) {
const trimmed = value.trimStart();
// Plain signed numbers include Revit IDs and measurements. Other formula-like fields are written as text.
const signedNumber = /^[+-]/.test(trimmed) && DECIMAL.test(trimmed.trimEnd());
if (/^[\t\r\n]/.test(value) || (!signedNumber && /^[=+@-]/.test(trimmed))) value = "'" + value;
return /[",\r\n]/.test(value) ? '"' + value.replace(/"/g, '""') + '"' : value;
}
Loading
Loading