diff --git a/CHANGELOG.md b/CHANGELOG.md index b56be58..73105f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Read checksum-verified E57 image blobs and scanner-aligned FARO RGB panoramas. +- Expose retained source point attributes and decoder concurrency through scene adapter options. + +### Changed + +- Leica LGSX version 22 decodes differential Morton positions, native RGB and intensity, retaining duplicate returns. +- FARO FLS distance mode 26 decodes both range-grid halves with optional Morton RGB and intensity. + ## [0.1.1] - 2026-11-25 ### Added diff --git a/README.md b/README.md index 018df30..e28ea8f 100644 --- a/README.md +++ b/README.md @@ -42,11 +42,11 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies | Format | Extensions | Support level | | --- | --- | --- | -| ASTM E57 | `.e57` | Points decoded for a defined subset: uncompressed bit-packed streams with single or double precision Cartesian coordinates or scaled-integer coordinates (raw value times scale plus offset), or spherical range, azimuth and elevation converted to Cartesian points, with 8-bit colour and 8-bit intensity, or colour with a wider Integer range from zero and intensity as a wider Integer, a Float or a scaled integer. Pose translation and rotation are applied. Only plain bit-packing is decoded: a scan whose codecs vector names another codec lists normally and fails when its points are read, and the message names it. Per-point validity flags skip invalid points and clear invalid channels when their streams hold one flag byte per record; other shapes are not interpreted. Images are not read, so a scan with them still lists and reads its points. Page checksums are verified. | +| ASTM E57 | `.e57` | Points decoded for a defined subset: uncompressed bit-packed streams with single or double precision Cartesian coordinates or scaled-integer coordinates (raw value times scale plus offset), or spherical range, azimuth and elevation converted to Cartesian points, with 8-bit colour and 8-bit intensity, or colour with a wider Integer range from zero and intensity as a wider Integer, a Float or a scaled integer. Pose translation and rotation are applied. Only plain bit-packing is decoded: a scan whose codecs vector names another codec lists normally and fails when its points are read, and the message names it. Per-point validity flags skip invalid points and clear invalid channels when their streams hold one flag byte per record; other shapes are not interpreted. Registered image blobs can be read explicitly through the format API. Page checksums are verified. | | ReCap scan | `.rcs` | Experimental. The header is read; point decoding covers the node layouts that are described in the code, which is the one of major version 3. A file of another version is listed with its header, but reading its points fails with a message that names the version. A further layout is described only when the files of that version may be used for the tests, so that its offsets can be verified. The channels of the points follow from the size of the payload of the nodes: colour and intensity when the records are long enough, and normals when the node holds the plane of them. A node payload whose byte count is not a whole multiple of a known record size, as in BLK360 exports (container 3.2) whose records are variable-length, is rejected with a message that names the container version instead of being guessed. | | ReCap project | `.rcp` | Lists the scans of the project manifest and opens the `.rcs` files it finds next to the project. The transform of a scan node places the scan in the project and is applied to its points unless `ApplyTransform` is false; when the manifest states no transform, the transform of the scan file is used. | -| Leica scan container | `.lgsx`, `.lgs` | Experimental. Points are decoded from the compressed point blocks: position, and colour, intensity and normals when the block has them. When the container assigns its points to its setups, there is one scan per setup, named after the setup, with the pose and the bounds of the setup when its record holds them; the pose is applied unless `ApplyTransform` is false. When the container does not assign its points, all points of the container form one scan and a warning says so. The point count is taken from the container when it states one; otherwise it is found by decoding the data, which is slow on large files. `PclReadOptions.Blocks` reads only the blocks of the scan in that file-order range (per scan, so a setup scan ranges over its own blocks); `PclReadOptions.MaxDegreeOfParallelism` above 1 decodes those blocks in parallel and still yields the points in file order with consecutive `Index` values. | -| FARO scan | `.fls`, or a FARO scan folder | Experimental. The scan grid and angles are read from the stored parameters and points are projected from the range grid; a file without them fails to open. The point count is the number of valid returns, which is counted on the first access; `FaroScan.GridSize` is the size of the scan grid. For a scan folder the layout of the samples is derived from the size of the data stream and the size of the grid, and the scale of the intensity from the values that are stored; when the sizes do not fit, the layout is assumed and a warning says so. | +| Leica scan container | `.lgsx`, `.lgs` | Experimental. Version 22 point blocks decode differential Morton coordinates, RGB and intensity. Normals are unavailable for that block version. When the container assigns its points to its setups, there is one scan per setup, named after the setup, with the pose and the bounds of the setup when its record holds them; the pose is applied unless `ApplyTransform` is false. When the container does not assign its points, all points of the container form one scan and a warning says so. The point count is taken from the container when it states one; otherwise it is found by decoding the data, which is slow on large files. `PclReadOptions.Blocks` reads only the blocks of the scan in that file-order range (per scan, so a setup scan ranges over its own blocks); `PclReadOptions.MaxDegreeOfParallelism` above 1 decodes those blocks in parallel and still yields the points in file order with consecutive `Index` values. | +| FARO scan | `.fls`, or a FARO scan folder | Experimental. Single-file containers with distance mode 26 decode both halves of the range grid and their optional RGB and intensity planes. The scan grid and angles are read from the stored parameters and points are projected from the range grid; a file without them fails to open. The point count is the number of valid returns, which is counted on the first access; `FaroScan.GridSize` is the size of the scan grid. For a scan folder the layout of the samples is derived from the size of the data stream and the size of the grid, and the scale of the intensity from the values that are stored; when the sizes do not fit, the layout is assumed and a warning says so. | | PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental. The manifest (scan names, ids, poses, counts) is read. Points come from the referenced `.bin` files, in either of two layouts: a table of named channels, or numbered sections with a property table and Snappy-compressed channels, which PclIO decodes itself. Colour, intensity and normals are reported only when the file has that channel; in the second layout positions, colours, intensities, normals (`Normals`, three float32 components per point) and the per-point flags (`FilterBits`, one byte per point) are read, while the grid indices stored beside them are not interpreted, so by default every stored point that passes the plausibility rule below is returned. With `PclReadOptions.ExcludeFilteredPoints` the points with a non-zero flag are not returned. A manifest with a scan position list takes the point count from the manifest, else from the data file; a manifest with a data object list takes it from the data file the object refers to, and every location that shares one file reports its full count, because the shares are not recorded. A project shell whose data files are absent lists no scans, and a manifest whose referenced data files are missing reads no points; neither is a readable fixture. | | EdgeWise | `.c3db`, `.c3ptx` | Experimental. A `.c3db` point database lists the scan clusters and a `.c3ptx` is one cluster file; the cluster files give positions only, as three 16-bit offsets from the cluster centre per point. The scale of the offsets is not stored in the files, so the reader assumes 32768 units = 0.128 m unless the caller states it with `PclReadOptions.EdgeWiseCoordinateScale`. | | LAS | `.las` | Points decoded from versions 1.0 to 1.4 with point formats 0 to 10: XYZ with scale and offset, intensity, classification and RGB for the colour formats (2, 3, 5, 7, 8, 10). GPS time, return numbers, scan angles, point source ids, near infrared and waveform packet descriptors are not interpreted; extra bytes past a format's base size are skipped. The extended point counts of 1.4 are used when stated. Coordinate system records name an `EPSG:` code from a GeoTIFF key directory when it holds one, else the OGC WKT when one is stored. | @@ -119,7 +119,7 @@ These readers drop data without an error or a warning, so a scan can yield fewer data file in neither layout, or in the sectioned layout with an element type or header value the reader does not support, cannot be read: the project lists it with a warning and reading its points throws `NotSupportedException`. A compressed stream whose copies reach back more than 8 MiB is not decoded: reading its points throws `NotSupportedException`, without an earlier warning. -- Leica: padding entries and points that coincide with a block's origin are dropped, a compressed stream above its size limit is +- Leica: the legacy block layout drops padding and points that coincide with a block's origin, a compressed stream above its size limit is skipped, and a block that is not recognised ends the scan. The reader counts what it dropped or skipped and reports it in the warnings of the document, so that an incomplete result is visible. With `PclReadOptions.Strict` the read fails instead. - EdgeWise: a database node whose point count is 0 is skipped. diff --git a/docs/getting-started.md b/docs/getting-started.md index 133f9a7..1804ee1 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -83,11 +83,11 @@ reading), `NotSupportedException` (unrecognised format or unsupported feature) o | Format | Extensions | Support level | | --- | --- | --- | -| ASTM E57 | `.e57` | Points decoded for a defined subset (uncompressed bit-packed streams, single or double precision Cartesian coordinates, 8-bit colour and intensity). Per-point validity flags and images are not read. | +| ASTM E57 | `.e57` | Points decoded for a defined subset (uncompressed bit-packed streams, single or double precision Cartesian coordinates, 8-bit colour and intensity). The format API also reads image blobs with checksum verification. | | ReCap scan | `.rcs` | Experimental; layout of major version 3 only. | | ReCap project | `.rcp` | Lists scans; opens the `.rcs` files it finds next to the project. Node transforms are not applied. | -| Leica scan container | `.lgsx`, `.lgs` | Experimental; poses and bounds are not read, and all points of a container form one scan. | -| FARO scan | `.fls`, or a FARO scan folder | Experimental; the scan grid comes from the stored parameters. A folder scan is read with an assumed layout, and a warning says so. | +| Leica scan container | `.lgsx`, `.lgs` | Experimental. Version 22 blocks provide geometry, RGB and intensity. Containers without setup assignments open as one scan in container coordinates. | +| FARO scan | `.fls`, or a FARO scan folder | Experimental. Single-file distance mode 26 reconstructs both halves of the scan grid. A folder scan is read with an assumed layout and carries a warning. | | PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental; manifest plus point data files in one of two layouts (named channels, or sections with Snappy-compressed channels); a data file in neither layout is not read. | | EdgeWise | `.c3db`, `.c3ptx` | Experimental; positions only, with a coordinate scale that is an assumption of the reader. | | LAS | `.las` | Versions 1.0 to 1.4 with point formats 0 to 10; positions, intensity, classification and RGB for the colour formats. | diff --git a/docs/public-api.md b/docs/public-api.md index 8036d0a..cc65fa3 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -103,6 +103,15 @@ no colour. ## Format documents +For sampling plans, `LgsxDocument.GetEncodedPointCount` reads the declared counts in version 22 point block headers without +decompressing the point data. It returns null when the file uses another block layout or has no point blocks. +`PclSceneOptions.PointObserver` receives retained points in scene geometry order, including their source attributes. +`PclSceneOptions.MaxDegreeOfParallelism` passes the requested concurrency to formats that support block decoding. + +The E57 reader exposes checksum-verified image blobs through `E57Document.ReadImageBlob`. +`FaroFlsDocument.ReadColorPanorama` returns the scanner-aligned mode 26 RGB raster in an equirectangular projection. +The image is RGB24 in row-major order and has a height of half the requested width. Pixels outside the recorded angles are black. + `E57Document`/`E57Scan`, `RcsScanDocument`/`RcsScan`, `RcpProjectDocument`/`RcpScan`, `LgsxDocument`/`LgsxScan`/`LgsxEntry`/`LgsxSetup`, `FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan`, `LazDocument`/`LazScan`, `CopcDocument`/`CopcScan`, `PcdDocument`/`PcdScan`, `PlyDocument`/`PlyScan`, `PtsDocument`/`PtsScan`, `PtxDocument`/`PtxScan`, `XyzDocument`/`XyzScan`, `SbfDocument`/`SbfScan`, `Tiles3dDocument`/`PntsScan`/`GlbScan`, `PotreeDocument`/`PotreeScan`, `EptDocument`/`EptScan`, `PtgDocument`/`PtgScan` and `CcBinDocument`/`CcBinScan` are the readers behind `PclFile.Open`. Each has a static `Open` method and format-specific properties (for example the E57 version or the FARO scanner model). diff --git a/src/PclIO.Scene/PclSceneOptions.cs b/src/PclIO.Scene/PclSceneOptions.cs index cfb2226..3304f06 100644 --- a/src/PclIO.Scene/PclSceneOptions.cs +++ b/src/PclIO.Scene/PclSceneOptions.cs @@ -50,6 +50,22 @@ public int SubsampleStep } } + /// Receives each retained point in scene order with the id of its geometry, before the scene discards point attributes. + public Action? PointObserver { get; init; } + + private readonly int _maxDegreeOfParallelism = 1; + + /// Maximum degree of parallelism for the source point reader. Formats that do not support it read sequentially. + public int MaxDegreeOfParallelism + { + get => _maxDegreeOfParallelism; + init + { + ArgumentOutOfRangeException.ThrowIfLessThan(value, 1, nameof(value)); + _maxDegreeOfParallelism = value; + } + } + private readonly double _metresPerUnit = 1.0; /// diff --git a/src/PclIO.Scene/PclSceneReader.cs b/src/PclIO.Scene/PclSceneReader.cs index fdb9e04..606e760 100644 --- a/src/PclIO.Scene/PclSceneReader.cs +++ b/src/PclIO.Scene/PclSceneReader.cs @@ -141,6 +141,7 @@ private static PclSceneResult Convert(PclDocument document, string key, string? { MaxPoints = remaining, SubsampleStep = options.SubsampleStep, + MaxDegreeOfParallelism = options.MaxDegreeOfParallelism, ApplyTransform = true, }; @@ -148,10 +149,12 @@ private static PclSceneResult Convert(PclDocument document, string key, string? var normals = new List(); bool hasColors = false, hasIntensities = false, hasClassifications = false; bool anyNormal = false, allNormals = true; + int geometryId = scene.Geometries.Count + 1; foreach (PclPoint point in scan.ReadPoints(readOptions)) { vertices.Add(new Vector3d(point.X * scale, point.Y * scale, point.Z * scale)); + options.PointObserver?.Invoke(geometryId, point); if (point.Color.HasValue) hasColors = true; if (point.Intensity.HasValue) hasIntensities = true; if (point.Classification.HasValue) hasClassifications = true; @@ -181,7 +184,7 @@ private static PclSceneResult Convert(PclDocument document, string key, string? scansWithPoints++; var geometry = new SceneGeometry { - Id = scene.Geometries.Count + 1, + Id = geometryId, Topology = SceneTopology.Points, Vertices = vertices, }; diff --git a/src/PclIO/Formats/E57/E57Document.cs b/src/PclIO/Formats/E57/E57Document.cs index 949ca13..d8a87eb 100644 --- a/src/PclIO/Formats/E57/E57Document.cs +++ b/src/PclIO/Formats/E57/E57Document.cs @@ -13,11 +13,11 @@ namespace PclIO.Formats.E57; /// Cartesian X/Y/Z are single or double precision floats or scaled integers (raw value times scale plus offset), /// or spherical range, azimuth and elevation converted to Cartesian points. Colour and intensity are Integer fields /// with a range from zero (8, 16 or 32 bits), Float fields, or scaled-integer intensity; per-point validity flags -/// skip invalid points and clear invalid channels. Images are not read. +/// skip invalid points and clear invalid channels. Image blobs are available through . /// Not supported (reported with when points are read): integer coordinates, /// other codecs (the scan must use plain bit-packing: an empty codecs vector), and packets whose streams hold /// different record counts. -/// Per-point validity flags of another shape, images and 2D data are not interpreted. +/// Per-point validity flags of another shape and other 2D data are not interpreted. /// public sealed class E57Document : PclDocument { @@ -154,6 +154,20 @@ public static E57Document Open(string path, PclReadOptions? options = null) return document; } + /// Reads a paged image blob referenced by the E57 XML and validates its section header. + /// Physical byte offset of the blob section from the XML. + /// Number of image bytes declared by the XML. + public byte[] ReadImageBlob(ulong fileOffset, int length) + { + if (length is < 4 or > 16 * 1024 * 1024) + throw FormatError.Corrupted("E57 image blob size is outside the supported range."); + using var reader = new E57StreamReader(FilePath, PageSize); + byte[] bytes = reader.ReadLogicalBytes(fileOffset, (ulong)(16 + length)); + if (bytes[0] != 0 || Bytes.ReadUInt64LE(bytes.AsSpan(8, 8)) != (ulong)((16 + length + 3) & ~3)) + throw FormatError.Corrupted("E57 image blob section header does not match its XML length."); + return bytes.AsSpan(16).ToArray(); + } + // DTDs are refused (no entity expansion, no external resolution) and the tree is bounded before it is built. private static XDocument ParseXml(string xmlText) { diff --git a/src/PclIO/Formats/Faro/FaroFlsDocument.cs b/src/PclIO/Formats/Faro/FaroFlsDocument.cs index becb23f..49eaf48 100644 --- a/src/PclIO/Formats/Faro/FaroFlsDocument.cs +++ b/src/PclIO/Formats/Faro/FaroFlsDocument.cs @@ -102,7 +102,8 @@ private FaroFlsDocument( ole2Path: isOle2 ? path : null, hasColors: hasColors, hasIntensities: hasIntensities, - recordSize: recordSize)); + recordSize: recordSize, + storageDistanceFactor: g.StorageDistanceFactor)); } /// Opens a FARO scan container file or scan folder and reads its scan parameters. @@ -156,6 +157,20 @@ public static FaroFlsDocument Open(string path, PclReadOptions? options = null) return document; } + /// + /// Reads the scanner-aligned colour raster as an RGB24 equirectangular image. + /// Pixels outside the recorded angular range are black. Horizontal centre faces +X. + /// Returns null when the file has no supported colour raster. + /// + /// An even image width from 2 to 4096 pixels. Height is half the width. + public byte[]? ReadColorPanorama(int width = 2048) + { + if (width is < 2 or > 4096 || width % 2 != 0) + throw new ArgumentOutOfRangeException(nameof(width)); + + return ((FaroScan)_scans[0]).ReadColorPanorama(width); + } + private static FaroFlsDocument OpenContainer(string path) { long fileSize = new FileInfo(path).Length; @@ -173,12 +188,15 @@ private static FaroFlsDocument OpenContainer(string path) if (dist != null) { ulong len = storage.GetStreamLength(dist); - if (len > (ulong)fileSize || (cells * 2 - HeaderSlack) / MaxDeflateRatio > (long)len) + long minimumPlaneBytes = g.StorageDistanceFactor != null ? cells / 2 : cells * 2; + if (len > (ulong)fileSize || (minimumPlaneBytes - HeaderSlack) / MaxDeflateRatio > (long)len) throw FormatError.Corrupted("distance stream is too small for the declared scan grid"); } - bool hasColors = FirstExisting(storage, "Scans/1/Color0", "Color0") != null; - bool hasIntensities = FirstExisting(storage, "Scans/1/Grey0", "Grey0") != null; + bool hasColors = FirstExisting(storage, "Scans/1/Color0", "Color0") != null || + (g.StorageDistanceFactor != null && FirstExisting(storage, "Scans/1/Color1", "Color1") != null); + bool hasIntensities = FirstExisting(storage, "Scans/1/Grey0", "Grey0") != null || + (g.StorageDistanceFactor != null && FirstExisting(storage, "Scans/1/Grey1", "Grey1") != null); return new FaroFlsDocument(path, fileSize, g, cells, null, isOle2: true, hasColors, hasIntensities); } @@ -204,7 +222,7 @@ private static FaroFlsDocument OpenContainer(string path) /// Scan grid and identity read from the scan parameters. private readonly record struct Geometry( - string? Model, string? Serial, int Rows, int Cols, double RowStart, double RowEnd, double ColEnd) + string? Model, string? Serial, int Rows, int Cols, double RowStart, double RowEnd, double ColEnd, double? StorageDistanceFactor) { private const double AngleTolerance = 1e-6; @@ -226,7 +244,17 @@ public static Geometry Parse(string text) if (colEnd == 0 || Math.Abs(colEnd) > Math.Tau + AngleTolerance) throw FormatError.Corrupted("azimuth range is invalid"); - return new Geometry(model, serial, rows, cols, rowStart, rowEnd, colEnd); + string? factorText = Find(text, KeyPattern("StorageDistFact", "([^\\s}]+)")); + double? factor = null; + if (factorText != null) + { + if (!double.TryParse(factorText, NumberStyles.Float, CultureInfo.InvariantCulture, out double storedFactor) || + !double.IsFinite(storedFactor) || storedFactor <= 0) + throw FormatError.Corrupted("storage distance factor is invalid"); + factor = storedFactor; + } + + return new Geometry(model, serial, rows, cols, rowStart, rowEnd, colEnd, factor); } // A parameter is stored either as 'Name "key" Value v' or as 'key = v'. @@ -299,6 +327,7 @@ public sealed class FaroScan : PclScan private readonly bool _hasColors; private readonly bool _hasIntensities; private readonly int _recordSize; + private readonly double? _storageDistanceFactor; private readonly Lazy _validReturns; private double _intensityScale = TwelveBitScale; @@ -346,7 +375,8 @@ internal FaroScan( string? ole2Path = null, bool hasColors = false, bool hasIntensities = false, - int recordSize = DefaultRecordSize) + int recordSize = DefaultRecordSize, + double? storageDistanceFactor = null) { if (rows <= 0 || cols <= 0) throw new ArgumentOutOfRangeException(nameof(rows), "Scan grid dimensions must be positive."); @@ -365,6 +395,7 @@ internal FaroScan( _hasColors = hasColors; _hasIntensities = hasIntensities; _recordSize = recordSize; + _storageDistanceFactor = storageDistanceFactor; // The count is made once even when several threads reach it at the same time, and the value is published // whole, so a concurrent first access cannot observe a partial count. @@ -424,6 +455,9 @@ private long CountContainerReturns() using var dist = Plane.Open(storage, "Dist0", 2, GridSize, fileLength) ?? throw FormatError.Corrupted("distance stream not found"); + if (dist.IsDelta) + return ReadDeltaSamples(storage, dist, fileLength, 1, false).LongCount(); + long count = 0; byte[] cell = new byte[2]; for (long idx = 0; idx < GridSize; idx++) @@ -491,6 +525,22 @@ private IEnumerable ReadContainerPoints(PclReadOptions options) // Planes are inflated sequentially in small chunks, so memory stays bounded by the compressed data of the file. using var dist = Plane.Open(storage, "Dist0", 2, cells, fileLength) ?? throw FormatError.Corrupted("distance stream not found"); + if (dist.IsDelta) + { + long count = 0; + long max = options.MaxPoints ?? long.MaxValue; + if (max <= 0) yield break; + foreach (var sample in ReadDeltaSamples(storage, dist, fileLength, Math.Max(1, options.SubsampleStep), true)) + { + var position = Project(sample.Index, sample.Range); + if (options.ApplyTransform) position = Transform.TransformPoint(position); + yield return new PclPoint(position, Color: sample.Color, Intensity: sample.Intensity, Index: (ulong)count); + if (++count >= max) yield break; + } + + yield break; + } + using var color = Plane.Open(storage, "Color0", 3, cells, fileLength); using var grey = Plane.Open(storage, "Grey0", 1, cells, fileLength); @@ -528,6 +578,120 @@ private IEnumerable ReadContainerPoints(PclReadOptions options) } } + private IEnumerable<(long Index, double Range, PclColor? Color, float? Intensity)> ReadDeltaSamples( + Ole2Storage storage, Plane first, long fileLength, int step, bool includeAttributes) + { + if (_cols % 2 != 0 || _storageDistanceFactor is not double distanceFactor) + throw FormatError.Corrupted("delta planes require an even column count and storage distance factor"); + + long cells = (long)_rows * _cols; + long halfCells = cells / 2; + for (int half = 0; half < 2; half++) + { + using var second = half == 1 ? Plane.Open(storage, "Dist1", 2, cells, fileLength) : null; + Plane distance = half == 0 ? first : second ?? throw FormatError.Corrupted("second distance plane not found"); + using var color = includeAttributes ? Plane.Open(storage, "Color" + half, 3, cells, fileLength) : null; + using var grey = includeAttributes ? Plane.Open(storage, "Grey" + half, 1, cells, fileLength) : null; + int storedDistance = 0, storedColor = 0, storedGrey = 0; + for (long i = 0; i < halfCells; i++) + { + if (i % _rows == 0) storedDistance = storedColor = storedGrey = 0; + + storedDistance = distance.ReadDelta(storedDistance, int.MaxValue); + if (color != null) storedColor = color.ReadDelta(storedColor, 0x1FFFFFF); + if (grey != null) storedGrey = grey.ReadDelta(storedGrey, 2047); + + long index = half * halfCells + i; + double range = storedDistance / distanceFactor; + if (index % step != 0 || range < MinRange || range > MaxRange) continue; + PclColor? rgb = color != null + ? new PclColor(UnpackChannel(storedColor), UnpackChannel(storedColor >> 1), UnpackChannel(storedColor >> 2)) + : null; + yield return (index, range, rgb, grey != null ? storedGrey / 2047.0f : null); + } + + distance.RequireEnd(); + color?.RequireEnd(); + grey?.RequireEnd(); + } + } + + internal byte[]? ReadColorPanorama(int width) + { + if (!_isOle2 || !_hasColors || _storageDistanceFactor == null || _cols % 2 != 0) return null; + string path = _ole2Path!; + long length = new FileInfo(path).Length; + long cells = (long)_rows * _cols; + int height = width / 2; + byte[] rgb = new byte[width * height * 3]; + using var storage = Ole2Storage.Open(path); + + var columns = Enumerable.Range(0, width).Select(x => + { + double yaw = ((x + 0.5) / width - 0.5) * Math.Tau; + double azimuth = (Math.PI / 2 - yaw + Math.Tau) % Math.Tau; + if (_colEnd < 0) azimuth = (Math.Tau - azimuth) % Math.Tau; + int col = (int)Math.Round(azimuth / Math.Abs(_colEnd) * _cols); + if (col == _cols && Math.Abs(Math.Abs(_colEnd) - Math.Tau) < 1e-6) col = 0; + return (Column: col, Pixel: x); + }).Where(item => item.Column < _cols).OrderBy(item => item.Column).ToArray(); + + int[] rows = Enumerable.Range(0, height).Select(y => + { + double elevation = (0.5 - (y + 0.5) / height) * Math.PI; + return (int)Math.Round((elevation - _rowStart) / (_rowEnd - _rowStart) * _rows); + }).ToArray(); + + int halfColumns = _cols / 2; + int destination = 0; + var values = new int[_rows]; + bool hasPanorama = false; + for (int half = 0; half < 2; half++) + { + using var color = Plane.Open(storage, "Color" + half, 3, cells, length); + if (color is not { IsDelta: true }) + { + while (destination < columns.Length && columns[destination].Column < (half + 1) * halfColumns) + destination++; + continue; + } + + hasPanorama = true; + for (int col = half * halfColumns; col < (half + 1) * halfColumns; col++) + { + int value = 0; + for (int row = 0; row < _rows; row++) + values[row] = value = color.ReadDelta(value, 0x1FFFFFF); + + while (destination < columns.Length && columns[destination].Column == col) + { + int x = columns[destination++].Pixel; + for (int y = 0; y < height; y++) + { + int row = rows[y]; + if ((uint)row >= (uint)_rows) continue; + int packed = values[row]; + int offset = (y * width + x) * 3; + rgb[offset] = UnpackChannel(packed); + rgb[offset + 1] = UnpackChannel(packed >> 1); + rgb[offset + 2] = UnpackChannel(packed >> 2); + } + } + } + + color.RequireEnd(); + } + + return hasPanorama ? rgb : null; + } + + private static byte UnpackChannel(int packed) + { + int channel = 0; + for (int bit = 0; bit < 8; bit++) channel |= ((packed >> (bit * 3)) & 1) << bit; + return (byte)channel; + } + private IEnumerable ReadFolderPoints(PclReadOptions options) { string streamPath = _streamPath ?? throw FormatError.Corrupted("scan data stream not found"); @@ -599,7 +763,7 @@ private sealed class Plane : IDisposable { private readonly Stream _stream; private readonly int _cellBytes; - private readonly long _limit; + private long _limit; private readonly byte[] _head = new byte[HeaderSearchWindow]; private readonly byte[] _skip = new byte[8192]; private int _headPos; @@ -607,6 +771,8 @@ private sealed class Plane : IDisposable private long _consumed; private long _position; + public bool IsDelta { get; private set; } + private Plane(Stream stream, int cellBytes, long limit) { _stream = stream; @@ -629,15 +795,14 @@ private Plane(Stream stream, int cellBytes, long limit) long limit = cells * cellBytes + FaroFlsDocument.HeaderSlack; byte[] data = storage.ReadStream(path); bool gzip = data.Length >= 3 && data[0] == 0x1F && data[1] == 0x8B && data[2] == 0x08; - if (!gzip && data.Length > limit) - throw FormatError.Corrupted("stream is larger than the declared scan grid allows"); - var input = new MemoryStream(data, writable: false); Stream stream = gzip ? new GZipStream(input, CompressionMode.Decompress) : input; - var plane = new Plane(stream, cellBytes, limit); + var plane = new Plane(new BufferedStream(stream, 8192), cellBytes, limit); try { - plane.SkipHeader(); + plane.SkipHeader(name, cells); + if (!gzip && data.Length > plane._limit) + throw FormatError.Corrupted("stream is larger than the declared scan grid allows"); } catch { @@ -664,13 +829,70 @@ public bool TryRead(long index, byte[] cell) return true; } + // The first byte has six magnitude bits, a sign bit and a continuation bit. Following bytes have + // seven magnitude bits and a continuation bit. The predictor is reset for each column. + public int ReadDelta(int previous, int max) + { + if (!IsDelta) throw FormatError.Corrupted("inconsistent sample plane formats"); + int first = ReadByte(); + if (first < 0) throw FormatError.Truncated("a delta sample"); + + long magnitude = first & 63; + int current = first; + for (int shift = 6; (current & 128) != 0; shift += 7) + { + if (shift > 27) throw FormatError.Corrupted("delta sample is too large"); + current = ReadByte(); + if (current < 0) throw FormatError.Truncated("a delta sample"); + magnitude |= (long)(current & 127) << shift; + } + + long value = previous + ((first & 64) == 0 ? magnitude : -magnitude); + if (value < 0 || value > max) throw FormatError.Corrupted("decoded sample is out of range"); + return (int)value; + } + + public void RequireEnd() + { + if (ReadByte() != '\n' || ReadByte() != '}' || ReadByte() != -1) + throw FormatError.Corrupted("sample plane does not end after the declared grid"); + } + + private int ReadByte() + { + if (_headPos >= _headLen) + { + _headLen = Pull(_head); + _headPos = 0; + } + + return _headPos < _headLen ? _head[_headPos++] : -1; + } + // Skips the optional text header: everything up to and including an opening brace near the start, then blanks. // A stream without a brace in its first bytes has no header and is read from its first byte. - private void SkipHeader() + private void SkipHeader(string name, long cells) { _headLen = Pull(_head); int brace = Array.IndexOf(_head, (byte)'{', 0, _headLen); - _headPos = brace >= 0 ? brace + 1 : 0; + _headPos = brace + 1; + string header = brace >= 0 ? Encoding.ASCII.GetString(_head, 0, brace) : string.Empty; + string[] fields = header.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + if (fields.Length > 0 && fields[0] is "DataMode" or "DistDataFormat" or "ColorDataFormat") + { + bool distance = name.StartsWith("Dist", StringComparison.Ordinal); + bool supported = distance + ? fields is ["DataMode", "26", "DistDataFormat", "1", "Scan2DataBase", _] + : fields is ["ColorDataFormat", "1", "Scan2DataBase", _]; + if (!supported) throw FormatError.Unsupported("unknown sample plane encoding"); + if (!long.TryParse(fields[^1], NumberStyles.None, CultureInfo.InvariantCulture, out long count) || count != cells || + _headPos >= _headLen || _head[_headPos++] != (byte)' ') + throw FormatError.Corrupted("sample plane header does not match the declared grid"); + + IsDelta = true; + _limit = cells * 5 / 2 + FaroFlsDocument.HeaderSlack; + return; + } while (true) { diff --git a/src/PclIO/Formats/Leica/LgsxDocument.cs b/src/PclIO/Formats/Leica/LgsxDocument.cs index 144f93f..12bfbe1 100644 --- a/src/PclIO/Formats/Leica/LgsxDocument.cs +++ b/src/PclIO/Formats/Leica/LgsxDocument.cs @@ -82,6 +82,34 @@ internal void AddWarning(string message) } } + /// + /// Returns the sum of the declared point counts in the version 22 block headers, or null for other layouts. + /// This reads the block headers and does not decompress their data. + /// + public long? GetEncodedPointCount() + { + var entry = Entries.FirstOrDefault(e => e.Name.Equals("PointCloud", StringComparison.OrdinalIgnoreCase)); + if (entry == null) return null; + using var stream = File.OpenRead(FilePath); + var chain = ReadBlockChain(stream, entry); + if (chain.Count == 0) return null; + + Span header = stackalloc byte[16]; + long total = 0; + foreach (var (start, _) in chain) + { + stream.Position = start + 12; + stream.ReadExactly(header); + if (Bytes.ReadUInt32LE(header) != LgsxScan.Morton96Version) return null; + ulong count = Bytes.ReadUInt64LE(header[8..]); + if (count is 0 or > LgsxScan.MaxFrameBytes) + throw FormatError.Corrupted("point block declares an invalid point count."); + total = checked(total + (long)count); + } + + return total; + } + /// Opens a Leica container and reads its table of contents. /// Path of the .lgsx or .lgs file. /// Read options; currently unused when opening. @@ -521,7 +549,7 @@ public sealed class LgsxScan : PclScan // Limits that bound memory and work for sizes declared by the file. private const int MaxCompressedFrameBytes = 10_000_000; - private const int MaxFrameBytes = 16 * 1024 * 1024; + internal const int MaxFrameBytes = 16 * 1024 * 1024; private const int MaxFramesPerBlock = 64; private const long MaxBlockBytes = 128L * 1024 * 1024; @@ -531,6 +559,8 @@ public sealed class LgsxScan : PclScan // Minimum plane counts at which an optional channel is read. private const int ColorFrames = 14; + private const int Morton96Planes = 12; + internal const uint Morton96Version = 22; private const int IntensityFrames = 16; private const int NormalFrames = 19; @@ -576,13 +606,13 @@ private sealed class ReadState public override long PointCount => _declaredPointCount ?? (_pointCount >= 0 ? _pointCount : _pointCount = CountPoints()); - /// True when the first point block carries colour planes. + /// True when the colour encoding of the first point block is supported. public override bool HasColors => Channels.Colors; /// True when the first point block carries intensity planes. public override bool HasIntensities => Channels.Intensities; - /// True when the first point block carries normal planes. + /// True when the normal encoding of the first point block is supported. public override bool HasNormals => Channels.Normals; private (bool Colors, bool Intensities, bool Normals) Channels => _channels ??= DetectChannels(); @@ -602,7 +632,10 @@ internal LgsxScan(string id, string name, string path, LgsxEntry? pointCloudEntr } /// Decoded planes of one point block together with its coordinate frame. - private sealed record Block(double ScaleX, double ScaleY, double ScaleZ, double MinX, double MinY, double MinZ, List Frames); + private sealed record Block(double ScaleX, double ScaleY, double ScaleZ, double MinX, double MinY, double MinZ, + List Frames, NativeLayout? Layout); + + private sealed record NativeLayout(int PointCount, int Intensity, int Color); private long CountPoints() => ReadPoints(new PclReadOptions { ApplyTransform = false }).LongCount(); @@ -611,8 +644,12 @@ private sealed record Block(double ScaleX, double ScaleY, double ScaleZ, double if (_entry == null) return (false, false, false); using var fs = File.OpenRead(_filePath); - foreach (var block in ReadBlocks(fs, new ReadState())) + foreach (var (start, length) in LgsxDocument.ReadBlockChain(fs, _entry)) { + if (!BelongsToScan(start)) continue; + var (block, _, _, _, _) = DecodeBlock(fs, start, length); + if (block == null) continue; + if (block.Layout is { } layout) return (layout.Color >= 0, layout.Intensity >= 0, false); int n = block.Frames.Count; return (n >= ColorFrames, n >= IntensityFrames, n >= NormalFrames); } @@ -623,10 +660,9 @@ private sealed record Block(double ScaleX, double ScaleY, double ScaleZ, double /// Streams the points of this scan. /// /// - /// Positions are decoded from the packed position planes of each block. A code of zero at any slot except the - /// first of a block is treated as unused padding and is not returned, so a real point that sits exactly at the - /// block origin is dropped. A block yields as many points as its shortest position plane holds. Returned points - /// keep consecutive values. + /// Version 22 blocks store differential 96-bit Morton positions. A zero delta repeats the previous position. + /// The legacy four-plane layout treats zero codes after the first slot as padding. + /// Returned points keep consecutive values. /// /// /// With only the blocks of the scan in that range are read; without it all @@ -823,7 +859,15 @@ private void SetChainEnd(FileStream fs, ReadState state, if (chain.FullChain.Count > 0) { long lastEnd = chain.FullChain[^1].Start + chain.FullChain[^1].Length; - if (chain.PayloadEnd - lastEnd >= 8 + 128) state.ChainEndedEarly = true; + if (chain.PayloadEnd - lastEnd >= 8 + 128) + { + // Version 22 payloads end with a JSON tree descriptor after the last point block. + ReadOnlySpan descriptor = "{\n\t\"tree-header-info\""u8; + Span prefix = stackalloc byte[descriptor.Length]; + fs.Position = lastEnd; + fs.ReadExactly(prefix); + state.ChainEndedEarly = !prefix.SequenceEqual(descriptor); + } } else { @@ -867,81 +911,6 @@ private void ReportIncompleteData(bool strict, ReadState state) _document?.AddWarning(message); } - /// Walks the chain of point blocks and yields those that carry point planes and belong to this scan. - private IEnumerable ReadBlocks(FileStream fs, ReadState state) - { - long fileLength = fs.Length; - long decodedLimit = DecodedAllowanceBytes + (fileLength * DecodedBytesPerFileByte); - long decodedBytes = 0; - byte[] blockHeader = new byte[128]; - - var chain = LgsxDocument.ReadBlockChain(fs, _entry!); - long payloadEnd = (long)_entry!.Offset + (long)_entry.Size; - - foreach (var (blockStart, blockLength) in chain) - { - if (!BelongsToScan(blockStart)) continue; - - // The block header follows the 8-byte block signature and length. - fs.Position = blockStart + 8; - fs.ReadExactly(blockHeader); - - double scaleX = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x34, 8)); - double scaleY = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x3C, 8)); - double scaleZ = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x44, 8)); - double minX = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x4C, 8)); - double minY = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x54, 8)); - double minZ = Bytes.ReadDoubleLE(blockHeader.AsSpan(0x5C, 8)); - - long blockEnd = blockStart + blockLength; - - // Find the first compressed frame; its 8-byte length prefix precedes it. - byte[] searchBuf = new byte[(int)Math.Min(1024L, blockLength)]; - fs.Position = blockStart + 8; - int bytesRead = fs.Read(searchBuf, 0, searchBuf.Length); - int firstFrame = -1; - for (int s = 0; s < bytesRead - 4; s++) - { - if (searchBuf.AsSpan(s, 4).SequenceEqual(FrameMagic)) - { - firstFrame = s; - break; - } - } - - if (firstFrame >= 8) - { - long firstFrameOffset = blockStart + firstFrame; - var frames = ReadAllFrames(fs, firstFrameOffset, blockEnd, state); - - // Many small blocks that each expand a lot would otherwise make the file cost unbounded time. - foreach (byte[] plane in frames) decodedBytes += plane.Length; - if (decodedBytes > decodedLimit) - throw FormatError.Corrupted("the point data decompresses to more than the accepted total size."); - - // Blocks with fewer than four planes carry no positions. - if (frames.Count >= 4) - { - if (!(double.IsFinite(scaleX) && scaleX > 0 && double.IsFinite(scaleY) && scaleY > 0 && - double.IsFinite(scaleZ) && scaleZ > 0 && - double.IsFinite(minX) && double.IsFinite(minY) && double.IsFinite(minZ))) - throw FormatError.Corrupted("point block has an invalid coordinate scale or origin."); - - state.BlocksRead++; - yield return new Block(scaleX, scaleY, scaleZ, minX, minY, minZ, frames); - } - } - } - - // Data that is left in the point data but that is not a point block means that the reader did not read - // everything the container holds. - if (chain.Count > 0) - { - long lastEnd = chain[^1].Start + chain[^1].Length; - if (payloadEnd - lastEnd >= 8 + 128) state.ChainEndedEarly = true; - } - } - // A scan without its own blocks holds all of them; otherwise only the blocks the container assigned to it. private bool BelongsToScan(long blockStart) => _blockStarts == null || Array.BinarySearch(_blockStarts, blockStart) >= 0; @@ -997,12 +966,153 @@ private static (Block? Block, long DecodedBytes, long SkippedStreams, long Unusa double.IsFinite(minX) && double.IsFinite(minY) && double.IsFinite(minZ))) throw FormatError.Corrupted("point block has an invalid coordinate scale or origin."); - return (new Block(scaleX, scaleY, scaleZ, minX, minY, minZ, frames), decodedBytes, skippedStreams, 0, incomplete); + NativeLayout? layout = Bytes.ReadUInt32LE(blockHeader.AsSpan(4, 4)) == Morton96Version + ? ReadNativeLayout(searchBuf.AsSpan(0, firstFrame - 8), frames) + : null; + + return (new Block(scaleX, scaleY, scaleZ, minX, minY, minZ, frames, layout), decodedBytes, skippedStreams, 0, incomplete); + } + + private static NativeLayout ReadNativeLayout(ReadOnlySpan header, List frames) + { + const int attributesOffset = 160; + if (header.Length < attributesOffset + 20) + throw FormatError.Truncated("the point block attributes"); + + uint count = Bytes.ReadUInt32LE(header[attributesOffset..]); + ulong points = Bytes.ReadUInt64LE(header[12..]); + if (count == 0 || points == 0 || points > MaxFrameBytes || + frames.Count < Morton96Planes) + throw FormatError.Corrupted("point block has invalid Morton position planes."); + + int offset = attributesOffset + 4; + int intensity = -1; + bool red = false, green = false, blue = false; + int widerPlanes = 0, twoBytePlanes = 0, planeCount = 0; + + for (uint i = 0; i < count; i++) + { + // POSITION occupies twelve byte planes. Subsequent attributes prefix their descriptor with + // the sample width expressed as a power of two. + int width = Morton96Planes; + if (i > 0) + { + if (offset >= header.Length || header[offset] > 2) + throw FormatError.Unsupported("unknown point block attribute size."); + width = 1 << header[offset++]; + } + + int descriptorSize = i == 0 ? 8 : 7; + if (offset > header.Length - descriptorSize) + throw FormatError.Truncated("a point block attribute"); + offset += descriptorSize; + int nameLength = Bytes.ReadUInt16LE(header[(offset - 2)..]); + if (nameLength > header.Length - offset) + throw FormatError.Truncated("a point block attribute name"); + + var name = header.Slice(offset, nameLength); + if (i == 0 && !name.SequenceEqual("POSITION"u8)) + throw FormatError.Corrupted("the first block attribute is not POSITION."); + // The planes are ordered by sample width, with POSITION and four-byte attributes before U16. + if (width > 2) widerPlanes += width; + if (width == 2) + { + if (name.SequenceEqual("INTENSITY"u8)) intensity = twoBytePlanes; + twoBytePlanes += width; + } + if (width == 1) + { + red |= name.SequenceEqual("R"u8); + green |= name.SequenceEqual("G"u8); + blue |= name.SequenceEqual("B"u8); + } + + offset += nameLength; + planeCount += width; + if (planeCount > frames.Count) throw FormatError.Truncated("a point block attribute plane"); + } + + if (frames.Take(planeCount).Any(plane => (ulong)plane.Length != points)) + throw FormatError.Corrupted("point block attribute length does not match the point count."); + + // RGB is a group of three planes after the individual one-byte attributes. + int color = red && green && blue ? planeCount - 3 : -1; + return new NativeLayout((int)points, intensity >= 0 ? widerPlanes + intensity : -1, color); + } + + private static List UnpackNativeBlock(Block block, NativeLayout layout, int step, bool applyTransform, + PclTransform transform, ulong baseIndex) + { + var frames = block.Frames; + var points = new List(1 + (layout.PointCount - 1) / step); + UInt128 morton = 0; + ushort intensity = 0; + int green = 0; + byte[]? greenDeltas = layout.Color >= 0 ? frames[layout.Color] : null; + for (int i = 0; i < layout.PointCount; i++) + { + // Each pair is stored in reverse order. An unpaired final sample keeps its slot. + int slot = i ^ 1; + if (slot >= layout.PointCount) slot = i; + UInt128 delta = 0; + for (int b = Morton96Planes - 1; b >= 0; b--) delta = (delta << 8) | frames[b][slot]; + morton += delta; + if (morton >> 96 != 0) + throw FormatError.Corrupted("point block Morton position exceeds 96 bits."); + + if (layout.Intensity >= 0) + { + int code = frames[layout.Intensity][slot] | (frames[layout.Intensity + 1][slot] << 8); + intensity = unchecked((ushort)(intensity + code)); + } + + if (greenDeltas != null) green = (green + greenDeltas[slot]) & 255; + if (i % step != 0) continue; + + // Green is accumulated across points. Blue and red are byte differences from the current green. + PclColor? color = greenDeltas == null ? null : new PclColor( + unchecked((byte)(green + frames[layout.Color + 2][slot])), + (byte)green, + unchecked((byte)(green + frames[layout.Color + 1][slot]))); + + var position = new PclVector3( + block.MinX + (UnpackMortonAxis(morton) * block.ScaleX), + block.MinY + (UnpackMortonAxis(morton >> 1) * block.ScaleY), + block.MinZ + (UnpackMortonAxis(morton >> 2) * block.ScaleZ)); + if (applyTransform) position = transform.TransformPoint(position); + points.Add(new PclPoint(position, + Color: color, + Intensity: layout.Intensity >= 0 ? intensity / 65535.0f : null, + Index: baseIndex + (ulong)points.Count)); + } + + return points; + } + + private static long UnpackMortonAxis(UInt128 code) + { + // Skip 63 interleaved bits at a time to retain the stride of three for the upper coordinate bits. + uint coordinate = CompactMortonAxis((ulong)code) | CompactMortonAxis((ulong)(code >> 63)) << 21; + return (long)coordinate - (1L << 31); + } + + private static uint CompactMortonAxis(ulong code) + { + code &= 0x1249249249249249UL; + code = (code ^ (code >> 2)) & 0x10C30C30C30C30C3UL; + code = (code ^ (code >> 4)) & 0x100F00F00F00F00FUL; + code = (code ^ (code >> 8)) & 0x1F0000FF0000FFUL; + code = (code ^ (code >> 16)) & 0x1F00000000FFFFUL; + return (uint)((code ^ (code >> 32)) & 0x1FFFFFUL); } /// Unpacks the planes of one block into points, dropping padding slots. The first returned point gets and the rest keep consecutive values; counts dropped slots. private static List UnpackBlock(Block block, int step, bool applyTransform, PclTransform transform, ulong baseIndex, out long dropped) { + dropped = 0; + if (block.Layout is { } layout) + return UnpackNativeBlock(block, layout, step, applyTransform, transform, baseIndex); + var frames = block.Frames; byte[] p0 = frames[0]; byte[] p1 = frames[1]; @@ -1016,7 +1126,6 @@ private static List UnpackBlock(Block block, int step, bool applyTrans int numPoints = Math.Min(p0.Length, Math.Min(p1.Length, Math.Min(p2.Length, p3.Length))); var points = new List(Math.Max(0, (numPoints + step - 1) / step)); - dropped = 0; ulong yielded = baseIndex; for (int i = 0; i < numPoints; i++) @@ -1156,51 +1265,4 @@ private static (List Frames, long DecodedBytes, long SkippedStreams, lon return (list, totalBytes, skipped, incomplete); } - private List ReadAllFrames(FileStream fs, long offset, long maxOffset, ReadState state) - { - var list = new List(); - long limit = Math.Min(maxOffset, fs.Length); - if (offset < 0 || offset + 8 >= limit) return list; - - fs.Position = offset; - byte[] lenBuf = new byte[8]; - long totalBytes = 0; - - while (fs.Position + 8 <= limit) - { - fs.ReadExactly(lenBuf); - - // A zero length marks the end of the frame list. - ulong fLen = Bytes.ReadUInt64LE(lenBuf); - if (fLen == 0) break; - - // A stream that is larger than the accepted size is skipped: the rest of the block is lost with it. - if (fLen > MaxCompressedFrameBytes) - { - state.SkippedStreams++; - break; - } - - if ((long)fLen > limit - fs.Position) break; - - byte[] fData = new byte[(int)fLen]; - fs.ReadExactly(fData); - - if (!fData.AsSpan().StartsWith(FrameMagic)) break; - - if (list.Count >= MaxFramesPerBlock) - throw FormatError.Corrupted($"point block has more than {MaxFramesPerBlock} planes."); - - // The size cap is checked against the frame's declared size before any allocation. - byte[] plane = ZstdDecoder.Decompress(fData, MaxFrameBytes); - - totalBytes += plane.Length; - if (totalBytes > MaxBlockBytes) - throw FormatError.Corrupted($"point block decompresses to more than {MaxBlockBytes} bytes."); - - list.Add(plane); - } - - return list; - } } diff --git a/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs b/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs index a755491..30d0cd9 100644 --- a/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs +++ b/tests/PclIO.Scene.Tests/PclSceneReaderTests.cs @@ -262,7 +262,15 @@ public void SubsampleStep_Thins_The_Points() using var dir = new TempDirectory(); string path = XyzFile(dir, 10); - var result = PclSceneReader.Read(path, new PclSceneOptions { SubsampleStep = 2 }); + var observed = new List<(int Geometry, PclPoint Point)>(); + var result = PclSceneReader.Read(path, new PclSceneOptions + { + SubsampleStep = 2, + PointObserver = (id, point) => observed.Add((id, point)), + }); + var geometry = Assert.Single(result.Document.Geometries); + Assert.All(observed, item => Assert.Equal(geometry.Id, item.Geometry)); + Assert.Equal(geometry.Vertices, observed.Select(item => new Vector3d(item.Point.X, item.Point.Y, item.Point.Z))); Assert.Equal(5, result.PointCount); Assert.Throws(() => new PclSceneOptions { SubsampleStep = 0 }); diff --git a/tests/PclIO.Tests/NativeScanCodecTests.cs b/tests/PclIO.Tests/NativeScanCodecTests.cs new file mode 100644 index 0000000..111ce71 --- /dev/null +++ b/tests/PclIO.Tests/NativeScanCodecTests.cs @@ -0,0 +1,177 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using PclIO.Formats.E57; +using PclIO.Formats.Faro; +using PclIO.Formats.Leica; +using Xunit; + +namespace PclIO.Tests; + +public sealed class NativeScanCodecTests +{ + [Fact] + public void Lgsx_Morton96_Accumulates_Deltas_And_Keeps_Duplicate_Returns() + { + using var dir = new TempDirectory(); + byte[] data = SyntheticFixtures.CreateSyntheticLgsx(SyntheticFixtures.DefaultLeicaPoints.Take(4).ToArray(), + nativeLeicaBlock: true); + using var doc = LgsxDocument.Open(dir.Write("native.lgsx", data)); + Assert.Equal(4, doc.GetEncodedPointCount()); + var scan = Assert.Single(doc.Scans); + var points = scan.ReadPoints(new PclReadOptions { Strict = true }).ToArray(); + + Assert.Equal(new[] { 102.048, 102.049, 102.049, 102.050 }, points.Select(p => p.Position.X)); + Assert.Equal(new[] { 200.002, 200.002, 200.002, 200.003 }, points.Select(p => p.Position.Y)); + Assert.Equal(new[] { 299.996, 299.996, 299.996, 299.997 }, points.Select(p => p.Position.Z)); + Assert.Equal(new[] { 255, 256, 256, 255 }.Select(v => (float?)(v / 65535.0f)), points.Select(p => p.Intensity)); + Assert.True(scan.HasIntensities); + Assert.False(scan.HasColors); + Assert.Equal(new[] { points[0], points[2] with { Index = 1 } }, + scan.ReadPoints(new PclReadOptions { Strict = true, MaxDegreeOfParallelism = 2, SubsampleStep = 2 })); + } + + [Theory] + [InlineData(1)] + [InlineData(3)] + [InlineData(4)] + public void Lgsx_Morton96_Decodes_Native_Rgb_Along_The_Point_Sequence(int count) + { + using var dir = new TempDirectory(); + var source = SyntheticFixtures.DefaultLeicaPoints.Take(count).ToArray(); + byte[] data = SyntheticFixtures.CreateSyntheticLgsx(source, withColorAndIntensity: true, nativeLeicaBlock: true); + using var doc = LgsxDocument.Open(dir.Write("rgb.lgsx", data)); + var scan = Assert.Single(doc.Scans); + + Assert.True(scan.HasColors); + PclColor?[] expected = [new(230, 120, 20), new(67, 200, 254), new(2, 240, 5), new(255, 20, 30)]; + Assert.Equal(expected.Take(count), scan.ReadPoints(new PclReadOptions { Strict = true }).Select(point => point.Color)); + Assert.Equal(expected.Take(count).Where((_, index) => index % 2 == 0), + scan.ReadPoints(new PclReadOptions { Strict = true, SubsampleStep = 2, MaxDegreeOfParallelism = 2 }) + .Select(point => point.Color)); + } + + [Fact] + public void Lgsx_Morton96_Rejects_A_Count_That_Does_Not_Match_Its_Planes() + { + using var dir = new TempDirectory(); + byte[] data = SyntheticFixtures.CreateSyntheticLgsx(SyntheticFixtures.DefaultLeicaPoints.Take(4).ToArray(), + nativeLeicaBlock: true); + int firstBlock = data.AsSpan().IndexOf("APRN"u8); + Assert.True(firstBlock > 0); + BinaryPrimitives.WriteUInt64LittleEndian(data.AsSpan(firstBlock + 20), 5); + using var doc = LgsxDocument.Open(dir.Write("short.lgsx", data)); + + Assert.Throws(() => doc.ReadAllPoints().ToArray()); + } + + [Fact] + public void E57_Image_Blob_Checks_Header_And_Each_Page() + { + const int blobOffset = 80; + byte[] image = Enumerable.Range(0, 1_201).Select(i => unchecked((byte)i)).ToArray(); + byte[] section = new byte[1_220]; + BinaryPrimitives.WriteUInt64LittleEndian(section.AsSpan(8), (ulong)section.Length); + image.CopyTo(section, 16); + byte[] file = new E57Spec { Points = [], RawPackets = section }.Build(); + using var dir = new TempDirectory(); + string path = dir.Write("image.e57", file); + using var doc = E57Document.Open(path); + + Assert.Equal(image, doc.ReadImageBlob(blobOffset, image.Length)); + Assert.Throws(() => doc.ReadImageBlob(blobOffset, image.Length - 1)); + Assert.Throws(() => doc.ReadImageBlob(1020, image.Length)); + + file[1054] ^= 1; + File.WriteAllBytes(path, file); + Assert.Throws(() => doc.ReadImageBlob(blobOffset, image.Length)); + } + + [Fact] + public void Faro_Delta_Planes_Keep_Both_Halves_And_Reset_At_Each_Column() + { + using var dir = new TempDirectory(); + using var doc = FaroFlsDocument.Open(dir.Write("delta.fls", FaroDeltaFixture())); + var scan = Assert.Single(doc.Scans); + var points = scan.ReadPoints().ToArray(); + + Assert.Equal(4, scan.PointCount); + Assert.Equal(new[] { 1.0, 0.5, 2.0, 3.0 }, points.Select(p => + { + var (x, y, z) = p.Position; + return Math.Round(Math.Sqrt(x * x + y * y + z * z), 8); + })); + Assert.True(scan.HasColors); + Assert.True(scan.HasIntensities); + Assert.Equal(new[] { 0UL, 1UL, 2UL, 3UL }, points.Select(p => p.Index)); + Assert.Null(points[0].Color); + Assert.Equal(new PclColor(1, 2, 4), points[3].Color); + Assert.Equal(0.5f, points[3].Intensity!.Value, 3); + Assert.True(points[0].Position.Y > 0 && points[3].Position.Y < 0); + Assert.Equal(new[] { points[0], points[2] with { Index = 1 }, points[3] with { Index = 2 } }, + scan.ReadPoints(new PclReadOptions { SubsampleStep = 2 })); + } + + [Fact] + public void Faro_Panorama_Projects_The_Colour_Grid_To_World_Directions() + { + using var dir = new TempDirectory(); + using var doc = FaroFlsDocument.Open(dir.Write("colour.fls", FaroDeltaFixture())); + + const int width = 64; + byte[] panorama = Assert.IsType(doc.ReadColorPanorama(width)); + Assert.Equal(width * (width / 2) * 3, panorama.Length); + int offset = (25 * width + 16) * 3; + Assert.Equal(new byte[] { 1, 2, 4 }, panorama.AsSpan(offset, 3).ToArray()); + Assert.Equal(new byte[] { 0, 0, 0 }, panorama.AsSpan(0, 3).ToArray()); + Assert.Throws(() => doc.ReadColorPanorama(63)); + } + + [Theory] + [InlineData(27, false, typeof(NotSupportedException))] + [InlineData(26, true, typeof(InvalidDataException))] + public void Faro_Delta_Planes_Reject_Unknown_Encoding_And_Short_Grid(int mode, bool shortHalf, Type error) + { + using var dir = new TempDirectory(); + using var doc = FaroFlsDocument.Open(dir.Write("bad.fls", FaroDeltaFixture(mode, shortHalf))); + + Assert.Throws(error, () => doc.ReadAllPoints().ToArray()); + } + + private static byte[] FaroDeltaFixture(int mode = 26, bool shortHalf = false) + { + var builder = new Ole2Builder(); + int scans = builder.AddStorage(0, "Scans"); + int one = builder.AddStorage(scans, "1"); + builder.AddStream(one, "Params", Encoding.ASCII.GetBytes(SyntheticFixtures.FaroParams("StorageDistFact 32"))); + + // The leading 32 is a sample whose byte happens to be a space. Each of the four rows has one delta, + // followed by a new column whose first sample is +64. In the other half, the first sample is +96. + byte[] first = new byte[18]; + new byte[] { 32, 80, 80, 0, 128, 1, 192, 1 }.CopyTo(first, 0); + byte[] second = new byte[18]; + new byte[] { 160, 1, 224, 1 }.CopyTo(second, 0); + byte[] color = new byte[22]; + new byte[] { 145, 132, 128, 16, 209, 132, 128, 16 }.CopyTo(color, 0); + byte[] grey = new byte[18]; + new byte[] { 128, 16, 192, 16 }.CopyTo(grey, 0); + string distanceHeader = $"DataMode {mode}\nDistDataFormat 1\n"; + builder.AddStream(one, "Dist0", DeltaPlane(distanceHeader, first)); + builder.AddStream(one, "Dist1", DeltaPlane(distanceHeader, shortHalf ? second[..^3] : second)); + builder.AddStream(one, "Color1", DeltaPlane("ColorDataFormat 1\n", color)); + builder.AddStream(one, "Grey1", DeltaPlane("ColorDataFormat 1\n", grey)); + return builder.Build(); + } + + private static byte[] DeltaPlane(string header, byte[] payload) + { + using var storage = new MemoryStream(); + using (var gzip = new GZipStream(storage, CompressionLevel.Fastest, leaveOpen: true)) + { + gzip.Write(Encoding.ASCII.GetBytes($"\n{header}Scan2DataBase 32 {{ ")); + gzip.Write(payload); + gzip.Write("\n}"u8); + } + return storage.ToArray(); + } +} diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs index 303a271..e7f71df 100644 --- a/tests/PclIO.Tests/SyntheticFixtures.cs +++ b/tests/PclIO.Tests/SyntheticFixtures.cs @@ -242,7 +242,7 @@ public static byte[] CreateSyntheticLgsx(IReadOnlyList? points IReadOnlyList? extraPlanes = null, int setupCount = 1, bool assignPointsToSetups = false, bool overlappingSetupRanges = false, bool collidingSetupNames = false, bool damagedSetupRecord = false, bool damagedPointData = false, bool withPointCount = true, bool oversizedFrame = false, bool unknownBlock = false, bool unknownFirstBlock = false, bool truncatedFrameList = false, bool fewPlanes = false, - int blockCount = 0, int damagedBlock = -1) + int blockCount = 0, int damagedBlock = -1, bool nativeLeicaBlock = false) { points ??= DefaultLeicaPoints; using var ms = new MemoryStream(); @@ -257,7 +257,7 @@ public static byte[] CreateSyntheticLgsx(IReadOnlyList? points (byte[] payload, List<(long Start, long Length)> blocks) = BuildLeicaPayload(groups, withColorAndIntensity, extraPlanes ?? [], damagedPointData, withPointCount, oversizedFrame, unknownBlock, - unknownFirstBlock, truncatedFrameList, fewPlanes, damagedBlock); + unknownFirstBlock, truncatedFrameList, fewPlanes, damagedBlock, nativeLeicaBlock); // The point data follows the container entries and their records, so its start is known before they are written. var setupNames = Enumerable.Range(0, setupCount).Select(i => "SETUP-" + (3 + i)).ToList(); @@ -386,7 +386,8 @@ private static void WriteEntry(BinaryWriter bw, string name, ulong payloadOffset private static (byte[] Payload, List<(long Start, long Length)> Blocks) BuildLeicaPayload( IReadOnlyList> groups, bool full, IReadOnlyList extraPlanes, bool damaged = false, bool withPointCount = true, bool oversizedFrame = false, bool unknownBlock = false, - bool unknownFirstBlock = false, bool truncatedFrameList = false, bool fewPlanes = false, int damagedBlock = -1) + bool unknownFirstBlock = false, bool truncatedFrameList = false, bool fewPlanes = false, int damagedBlock = -1, + bool nativeLeicaBlock = false) { using var ms = new MemoryStream(); using var bw = new BinaryWriter(ms); @@ -414,7 +415,7 @@ private static (byte[] Payload, List<(long Start, long Length)> Blocks) BuildLei // A setup without points has no block of its own. if (group.Count == 0) continue; - var frames = BuildFrames(group, full, extraPlanes); + var frames = nativeLeicaBlock ? BuildNativeLeicaFrames(group.Count, full) : BuildFrames(group, full, extraPlanes); if (fewPlanes) frames = [.. frames.Take(3)]; if (damaged || blockIndex == damagedBlock) { @@ -426,12 +427,25 @@ private static (byte[] Payload, List<(long Start, long Length)> Blocks) BuildLei // A frame whose declared length is above the accepted size is skipped by the reader. const ulong OversizedLength = 20_000_000; - int blockLength = 8 + 128 + frames.Sum(f => 8 + f.Length) + (oversizedFrame ? 8 : 0) + (truncatedFrameList ? 8 : 0); + int headerLength = nativeLeicaBlock ? (full ? 232 : 205) : 128; + byte[] blockHeader = new byte[headerLength]; + if (nativeLeicaBlock) + { + BinaryPrimitives.WriteUInt32LittleEndian(blockHeader.AsSpan(4), 22); + BinaryPrimitives.WriteUInt64LittleEndian(blockHeader.AsSpan(12), (ulong)group.Count); + BinaryPrimitives.WriteUInt32LittleEndian(blockHeader.AsSpan(160), full ? 5U : 2U); + const string position = "0A00000000000800504F534954494F4E"; + const string color = "000400000000010052000500000000010047000600000000010042"; + const string intensity = "0108000000000900494E54454E53495459"; + byte[] attributes = Convert.FromHexString(position + (full ? color : "") + intensity); + attributes.CopyTo(blockHeader, 164); + } + + int blockLength = 8 + blockHeader.Length + frames.Sum(f => 8 + f.Length) + (oversizedFrame ? 8 : 0) + (truncatedFrameList ? 8 : 0); long start = ms.Position; bw.Write("APRN"u8.ToArray()); bw.Write((uint)blockLength); - byte[] blockHeader = new byte[128]; double[] frame = [LeicaScale, LeicaScale, LeicaScale, LeicaOriginX, LeicaOriginY, LeicaOriginZ]; for (int i = 0; i < frame.Length; i++) BinaryPrimitives.WriteDoubleLittleEndian(blockHeader.AsSpan(0x34 + (i * 8), 8), frame[i]); @@ -458,9 +472,45 @@ private static (byte[] Payload, List<(long Start, long Length)> Blocks) BuildLei bw.Write(new byte[128]); } + if (nativeLeicaBlock) + { + bw.Write("{\n\t\"tree-header-info\": {} }"u8.ToArray()); + bw.Write(new byte[160]); + } + return (ms.ToArray(), blocks); } + private static List BuildNativeLeicaFrames(int pointCount, bool color) + { + byte[][] codes = + [ + Convert.FromHexString("010000000000000000000000"), + Convert.FromHexString("104992244B92244992244972"), + Convert.FromHexString("0D0000000000000000000000"), + new byte[12], + ]; + var frames = Enumerable.Range(0, 12) + .Select(plane => WrapPlane(codes.Select(code => code[plane]).ToArray())) + .ToList(); + frames.Add(WrapPlane([1, 255, 255, 0])); + frames.Add(WrapPlane([0, 0, 255, 0])); + if (color) + { + frames.Add(WrapPlane([80, 120, 36, 40])); + frames.Add(WrapPlane([54, 156, 10, 21])); + frames.Add(WrapPlane([123, 110, 235, 18])); + } + + return frames; + + byte[] WrapPlane(byte[] storageOrder) + { + if ((pointCount & 1) != 0) storageOrder[pointCount - 1] = storageOrder[pointCount]; + return RawZstdFrame.Wrap(storageOrder[..pointCount]); + } + } + // The compressed planes of one point block: the four position planes and the optional ones. private static List BuildFrames(IReadOnlyList points, bool full, IReadOnlyList extraPlanes) {