From 572d9535f23d2e40ca0a4ddedd2a712f17f47b5a Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Wed, 18 Nov 2026 14:00:00 +0000
Subject: [PATCH] Format: Cloud Optimized Point Cloud (*.copc.laz) (#27)
---
CHANGELOG.md | 6 +
README.md | 3 +-
docs/public-api.md | 9 +-
src/PclIO/Formats/Copc/CopcDocument.cs | 353 ++++++++++++++++++++
src/PclIO/Formats/Copc/CopcHierarchy.cs | 92 +++++
src/PclIO/Formats/Copc/CopcModels.cs | 41 +++
src/PclIO/Formats/Copc/CopcScan.cs | 233 +++++++++++++
src/PclIO/Internal/KindDetector.cs | 75 ++++-
src/PclIO/Model/PclBounds.cs | 7 +
src/PclIO/PclFile.cs | 2 +
src/PclIO/PclFileKind.cs | 3 +
tests/PclIO.Tests/FormatTests.cs | 158 +++++++++
tests/PclIO.Tests/KindDetectionTests.cs | 16 +
tests/PclIO.Tests/RealFileTests.cs | 3 +
tests/PclIO.Tests/RepositoryHygieneTests.cs | 2 +
tests/PclIO.Tests/SyntheticFixtures.cs | 117 +++++++
tests/PclIO.Tests/TestFiles.cs | 4 +-
17 files changed, 1114 insertions(+), 10 deletions(-)
create mode 100644 src/PclIO/Formats/Copc/CopcDocument.cs
create mode 100644 src/PclIO/Formats/Copc/CopcHierarchy.cs
create mode 100644 src/PclIO/Formats/Copc/CopcModels.cs
create mode 100644 src/PclIO/Formats/Copc/CopcScan.cs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a37633a..09c9e8b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -102,6 +102,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Spatial coordinates, intensity, classification, and 8-bit RGB colour; coordinate scale and offset applied;
CRS read from GeoTIFF key directory or OGC WKT VLRs;
Chunk table offsets and per-chunk point counts validated against file boundaries.
+- Cloud Optimized Point Clouds are read (`*.copc.laz`, `PclFileKind.Copc`):
+ Reads octree hierarchy pages (root and child pages) with cycle detection and boundary checks;
+ Octree voxel bounding boxes calculated from center and halfsize metadata;
+ Spatial querying by bounding box (`FindNodes`, `ReadPoints(bounds)`) and by specific node (`ReadPoints(node)`);
+ LAS point formats 0 to 3 decompressed via LASzip arithmetic decoding;
+ LAS 1.4 point formats 6 to 8 read anchor points with coordinates, intensity, classification, and 8-bit RGB colour.
- Leica scans read a block range with opt-in parallel decoding: the new `PclReadOptions.Blocks` selects the blocks of the
scan in file order (per scan) and the new `PclReadOptions.MaxDegreeOfParallelism` (default 1, sequential streaming)
decodes the selected blocks in parallel, keeping file order, consecutive `Index` values and `MaxPoints`/`SubsampleStep`
diff --git a/README.md b/README.md
index b93c97b..2beabfc 100644
--- a/README.md
+++ b/README.md
@@ -52,6 +52,7 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies
| 3D Tiles | `.pnts`, `.glb`, `tileset.json` | OGC 3D Tiles point cloud tiles (.pnts, version 1) with float32 or quantised 16-bit positions (POSITION_QUANTIZED), RGB, RGBA, RGB565, or constant RGBA colour, float32 or octahedral oct16p normals (NORMAL_OCT16P), relative-to-center offsets (RTC_CENTER), and batch table scalar properties (Intensity, Classification). glTF 2.0 binary point clouds (.glb) with mesh primitive mode 0 (POINTS), reading POSITION, COLOR_0, NORMAL, and INTENSITY accessors and node transforms. Hierarchical 3D Tiles tilesets (tileset.json) or folders containing them, accumulating 4x4 transform matrices for referenced point tiles. |
| Potree | `cloud.js`, `metadata.json`, `.hrc`, `.bin` | Potree octree point cloud datasets: Potree 1.x (`cloud.js` manifest) with Cartesian scaled integer or float coordinates, 8-bit or 16-bit RGB/RGBA colours, float32, spheremapped or oct16p normals, intensities and classifications across node files (`.bin`) and hierarchy (`.hrc`). Potree 2.x (`metadata.json` manifest and `octree.bin` stream) with custom attribute schema layouts. Opening supported from manifest, hierarchy, individual node files, or dataset folders. |
| LAZ | `.laz` | LASzip compressed ASPRS LAS (versions 1.0 to 1.4, point formats 0 to 3): XYZ with scale and offset, intensity, classification and 8-bit RGB colour. Decoded via clean-room arithmetic decoder and integer decompressor with pointwise chunked compression (compressor 2) and pointwise uncompressed records (compressor 1). CRS is read from GeoTIFF or WKT VLRs. Point formats 6 to 10 with layered chunked compressor (compressor 3), waveform packets and EVLRs are not currently read. |
+| COPC | `.copc.laz`, `.laz` | Cloud Optimized Point Cloud (COPC octree in LAS 1.4 / LAZ): reads the octree hierarchy (root and sub-hierarchy pages) and voxel bounding boxes, center, halfsize and spacing metadata, streaming points by octree node, bounding box or across the whole dataset. LAS formats 0 to 3 are fully decompressed via LASzip arithmetic decoding; LAS 1.4 formats 6 to 8 decode uncompressed anchor points with exact positions, intensity, classification and RGB colour per octree node. |
### Format detection
@@ -61,7 +62,7 @@ regard to case.
- E57, ReCap scan and Leica files are recognised by their content and accepted with any extension; for Leica, `.lgs` selects the
older container and any other extension `.lgsx`. EdgeWise files are also recognised by content when the extension is none of its own.
- A LAS file is recognised by the `LASF` signature with any extension except `.laz`. A LAZ file is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension. A PCD file is recognised by its header structure with any extension. A PLY file is recognised by its magic word and header structure with any extension. A PTS file is recognised by an integer point count header line followed by coordinate lines with any extension, or coordinate lines with the `.pts` extension. A PTX file is recognised by its 10-line header structure (grid dimensions, scanner pose, 4x4 matrix) with any extension. An XYZ / delimited text file is recognised by an explicit column header containing X, Y, Z in any extension, or by numeric coordinate lines with a recognised extension (`.xyz`, `.asc`, `.txt`, `.csv`). An SBF file is recognised by its companion `[SBF]` header structure with any extension, or by the binary signature `0x2A, 0x2A` (`**`) and record size formula (`.sbf`, `.sbf.data`, `.data`). A 3D Tiles `.pnts` tile is recognised by the `pnts` signature, version 1, and matching byte lengths. A glTF `.glb` point cloud is recognised by the `glTF` signature, version 2, and mesh primitive mode 0 (POINTS). A 3D Tiles tileset is recognised by JSON containing `asset` and `root` objects (`tileset.json`). A Potree dataset is recognised by `cloud.js` (with `octreeDir` and attribute descriptors) or `metadata.json` (version 2.x and point attributes) in `.js` or `.json`, by `.hrc` hierarchy files with 5-byte node records, or by ancestor `cloud.js`/`metadata.json` next to a `.bin` file.
+ A LAS file is recognised by the `LASF` signature with any extension except `.laz` and `.copc.laz`. A LAZ file is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension. A COPC file is recognised by the LAS 1.4 header and the `copc` info variable length record with `.copc.laz` or any extension. A PCD file is recognised by its header structure with any extension. A PLY file is recognised by its magic word and header structure with any extension. A PTS file is recognised by an integer point count header line followed by coordinate lines with any extension, or coordinate lines with the `.pts` extension. A PTX file is recognised by its 10-line header structure (grid dimensions, scanner pose, 4x4 matrix) with any extension. An XYZ / delimited text file is recognised by an explicit column header containing X, Y, Z in any extension, or by numeric coordinate lines with a recognised extension (`.xyz`, `.asc`, `.txt`, `.csv`). An SBF file is recognised by its companion `[SBF]` header structure with any extension, or by the binary signature `0x2A, 0x2A` (`**`) and record size formula (`.sbf`, `.sbf.data`, `.data`). A 3D Tiles `.pnts` tile is recognised by the `pnts` signature, version 1, and matching byte lengths. A glTF `.glb` point cloud is recognised by the `glTF` signature, version 2, and mesh primitive mode 0 (POINTS). A 3D Tiles tileset is recognised by JSON containing `asset` and `root` objects (`tileset.json`). A Potree dataset is recognised by `cloud.js` (with `octreeDir` and attribute descriptors) or `metadata.json` (version 2.x and point attributes) in `.js` or `.json`, by `.hrc` hierarchy files with 5-byte node records, or by ancestor `cloud.js`/`metadata.json` next to a `.bin` file.
- A FARO file must be an OLE2 compound file with the extension `.fls`. A ReCap project must be a ZIP archive with the extension
`.rcp`. A PinPoint file must be a JSON text file with the extension `.smf` or `.srf`.
- The extensions `.c3db` and `.c3ptx` select EdgeWise without a content check. A `.c3ptx` file is read as one cluster file and any
diff --git a/docs/public-api.md b/docs/public-api.md
index e1774ac..ec599a6 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -14,7 +14,7 @@ format-specific members can change when the support for that format changes.
| Type | Use |
|---|---|
| `PclFile` | Static entry point. `DetectKind(path)` and `DetectKind(stream, extension)` return a `PclFileKind`; `Open(path, options)` detects the format and returns a `PclDocument`. |
-| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd`, `Ply`, `Pts`, `Ptx`, `Xyz`, `Sbf`, `Tiles3d`, `Potree` and `Laz`. |
+| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd`, `Ply`, `Pts`, `Ptx`, `Xyz`, `Sbf`, `Tiles3d`, `Potree`, `Laz` and `Copc`. |
| `PclReadOptions` | `MaxPoints` (limit of one read call, null for all, 0 for none), `MaxCoordinateMagnitude` (default 5000, null for no limit; NaN and infinite coordinates are never returned; currently only PinPoint applies it), `EdgeWiseCoordinateScale` (default 0.128 / 32768 metres per unit; the files do not declare it), `SubsampleStep` (1 keeps every point, N keeps about one in N), `Blocks` (range of the scan's blocks in file order, null for all; currently only Leica honours it), `MaxDegreeOfParallelism` (default 1: sequential; above 1 decodes the selected Leica blocks in parallel, keeping file order), `ApplyTransform` (default true), `Strict` (default false: a reader that finds incomplete data fails with `InvalidDataException` instead of adding a warning), `ExcludeFilteredPoints` (default false: points the file marks as filtered are excluded; currently the `FilterBits` channel of the PinPoint sectioned layout), `TextColumns` (explicit column names or layout for delimited text point clouds), `TextDelimiter` (explicit delimiter character for delimited text), `TextCommentPrefix` (prefix for comment lines in delimited text, default `#`) and `TextCoordinateScale` (coordinate scale factor for delimited text, default 1.0). Negative `MaxPoints`, a negative magnitude limit, a negative block start or count, a non-positive or non-finite EdgeWise scale or text coordinate scale, and a step or parallelism below 1 throw `ArgumentOutOfRangeException`. `PclReadOptions.Default` has no limit. |
| `BlockRange` | `StartBlock` (zero-based index of the first block to read) and `BlockCount` (how many blocks at most, null for all from the start on; a range past the last block yields no points, 0 yields none). |
@@ -32,8 +32,9 @@ is the argument, which may also be a file name.
- `E57`, `RecapScan` and the Leica kinds are recognised by content and accepted with any extension; `LeicaLgs` is chosen for the
extension `.lgs` and `LeicaLgsx` for any other. `EdgeWise` is also recognised by content in a file with another extension.
- `Las` is recognised by the `LASF` signature with any extension except `.laz`.
+ `Las` is recognised by the `LASF` signature with any extension except `.laz` and `.copc.laz`.
`Laz` is recognised by the `LASF` signature, a valid LASzip VLR and the `.laz` extension.
+ `Copc` is recognised by the LAS 1.4 header and the `copc` info VLR with `.copc.laz` or any extension.
`Pcd` is recognised by its header structure (the documented entries in order) with any extension.
`Ply` is recognised by its magic word and header structure with any extension.
`Pts` is recognised by an integer point count header line followed by coordinate lines with any extension, or coordinate lines with the `.pts` extension.
@@ -86,6 +87,8 @@ drop points that fail a plausibility rule (see the README), so a scan can yield
| SBF | The point count declared in the binary header (and companion header). Points with non-finite coordinates are skipped. |
| 3D Tiles | Declared in the feature table (POINTS_LENGTH) for .pnts tiles, or the POSITION accessor count for .glb point primitives. |
| Potree | Sum of points across all discovered octree node binary files, or declared in metadata.json. |
+| LAZ | The header count (the extended 1.4 count when it states one). It is not checked against the chunk data until read. |
+| COPC | The header count (the extended 1.4 count when it states one). It is not checked against the chunk data until read. |
`HasColors`, `HasIntensities` and `HasNormals` follow what the file contains, except for the scans of a ReCap project, where all three
are true when the `.rcs` file was found and false otherwise, without the file being opened. A ReCap scan reads the channels
@@ -95,7 +98,7 @@ no colour.
## Format documents
`E57Document`/`E57Scan`, `RcsScanDocument`/`RcsScan`, `RcpProjectDocument`/`RcpScan`, `LgsxDocument`/`LgsxScan`/`LgsxEntry`/`LgsxSetup`,
-`FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan`, `PcdDocument`/`PcdScan`, `PlyDocument`/`PlyScan`, `PtsDocument`/`PtsScan`, `PtxDocument`/`PtxScan`, `XyzDocument`/`XyzScan`, `SbfDocument`/`SbfScan`, `Tiles3dDocument`/`PntsScan`/`GlbScan` and `PotreeDocument`/`PotreeScan` are the readers behind
+`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` and `PotreeDocument`/`PotreeScan` 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).
Their XML documentation states what each reader supports. Prefer `PclFile.Open`, which detects the format and chooses the reader.
diff --git a/src/PclIO/Formats/Copc/CopcDocument.cs b/src/PclIO/Formats/Copc/CopcDocument.cs
new file mode 100644
index 0000000..1f74cf1
--- /dev/null
+++ b/src/PclIO/Formats/Copc/CopcDocument.cs
@@ -0,0 +1,353 @@
+using System.Globalization;
+using PclIO.Internal;
+
+namespace PclIO.Formats.Copc;
+
+/// Represents a Cloud Optimized Point Cloud (COPC) document containing a clustered octree in LAS 1.4 / LAZ.
+public sealed class CopcDocument : PclDocument
+{
+ private const int MinLas14HeaderSize = 375;
+ private const int MaxVlrs = 4096;
+
+ ///
+ public override PclFileKind Kind => PclFileKind.Copc;
+
+ /// Octree center coordinates declared in the COPC info record.
+ public PclVector3 Center => _info.Center;
+
+ /// Half of the root octree voxel size along each axis.
+ public double HalfSize => _info.HalfSize;
+
+ /// Spacing parameter declared in the COPC info record.
+ public double Spacing => _info.Spacing;
+
+ /// LAS coordinate scale factor applied to raw integer coordinates.
+ public PclVector3 Scale { get; }
+
+ /// LAS coordinate offset added to scaled coordinates.
+ public PclVector3 Offset { get; }
+
+ /// LAS point data record format (e.g. 0 to 3, 6 to 8).
+ public int PointFormat { get; }
+
+ /// Point data record length in bytes.
+ public int RecordLength { get; }
+
+ /// LAS version string (e.g. "1.4").
+ public string Version { get; }
+
+ /// Absolute file offset of the root octree hierarchy page.
+ public ulong RootHierarchyOffset => _info.RootHierarchyOffset;
+
+ /// Size of the root octree hierarchy page in bytes.
+ public ulong RootHierarchySize => _info.RootHierarchySize;
+
+ /// Minimum GPS time declared in the COPC record, or null when absent.
+ public double? GpsTimeMin => _info.GpsTimeMin;
+
+ /// Maximum GPS time declared in the COPC record, or null when absent.
+ public double? GpsTimeMax => _info.GpsTimeMax;
+
+ /// Bounding box of the root octree voxel enclosing the point cloud.
+ public PclBounds OctreeBounds { get; }
+
+ /// Resolved octree nodes containing point records.
+ public IReadOnlyList Nodes => _nodes;
+ private readonly List _nodes;
+
+ ///
+ public override IReadOnlyList Scans => _scans;
+ private readonly List _scans = [];
+ private readonly CopcScan _primaryScan;
+ private readonly CopcInfo _info;
+
+ private CopcDocument(
+ string path,
+ long fileSize,
+ string version,
+ int pointFormat,
+ int recordLength,
+ PclVector3 scale,
+ PclVector3 offset,
+ PclBounds bounds,
+ PclBounds octreeBounds,
+ CopcInfo info,
+ List nodes,
+ long pointCount)
+ : base(path, fileSize)
+ {
+ Version = version;
+ PointFormat = pointFormat;
+ RecordLength = recordLength;
+ Scale = scale;
+ Offset = offset;
+ OctreeBounds = octreeBounds;
+ _info = info;
+ _nodes = nodes;
+
+ _primaryScan = new CopcScan(
+ id: "copc_root",
+ name: "COPC Octree",
+ pointCount: pointCount,
+ bounds: bounds,
+ filePath: path,
+ pointFormat: pointFormat,
+ recordLength: recordLength,
+ scale: scale,
+ offset: offset,
+ nodes: nodes);
+ _scans.Add(_primaryScan);
+
+ _metadata["Format"] = "Cloud Optimized Point Cloud (COPC)";
+ _metadata["Version"] = version;
+ _metadata["PointFormat"] = pointFormat.ToString(CultureInfo.InvariantCulture);
+ _metadata["NodeCount"] = nodes.Count.ToString(CultureInfo.InvariantCulture);
+ _metadata["Center"] = string.Create(CultureInfo.InvariantCulture, $"{Center.X:G6}, {Center.Y:G6}, {Center.Z:G6}");
+ _metadata["HalfSize"] = HalfSize.ToString(CultureInfo.InvariantCulture);
+ _metadata["Spacing"] = Spacing.ToString(CultureInfo.InvariantCulture);
+ _metadata["TotalPoints"] = pointCount.ToString(CultureInfo.InvariantCulture);
+ }
+
+ /// Opens a COPC file and reads its header, COPC metadata and octree hierarchy.
+ /// Path of the COPC file (.copc.laz or .laz).
+ /// Read options (accepted for symmetry).
+ /// The file does not exist.
+ /// The file is malformed, truncated, or has corrupted hierarchy pages.
+ /// The LAS version or compression feature is not supported.
+ public static CopcDocument Open(string path, PclReadOptions? options = null)
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists) throw new FileNotFoundException("COPC file not found.", path);
+
+ using var fs = File.OpenRead(path);
+ long fileLength = fs.Length;
+
+ if (fileLength < 4) throw FormatError.Truncated("COPC header");
+ byte[] signature = new byte[4];
+ fs.ReadExactly(signature);
+ if (!signature.AsSpan().SequenceEqual("LASF"u8))
+ throw FormatError.Corrupted("not a LAS/COPC file, signature mismatch.");
+
+ if (fileLength < MinLas14HeaderSize) throw FormatError.Truncated("COPC LAS 1.4 header");
+ fs.Position = 0;
+ byte[] header = new byte[MinLas14HeaderSize];
+ fs.ReadExactly(header);
+
+ int major = header[24];
+ int minor = header[25];
+ if (major != 1 || minor < 4)
+ throw FormatError.Unsupported($"COPC requires LAS version 1.4 or higher; file declares version {major}.{minor}.");
+
+ ushort headerSize = Bytes.ReadUInt16LE(header.AsSpan(94, 2));
+ if (headerSize < MinLas14HeaderSize)
+ throw FormatError.Corrupted($"COPC header size {headerSize} is smaller than minimum LAS 1.4 size {MinLas14HeaderSize}.");
+ if (headerSize > fileLength) throw FormatError.Truncated("COPC header");
+
+ uint pointDataOffset = Bytes.ReadUInt32LE(header.AsSpan(96, 4));
+ if (pointDataOffset < headerSize || pointDataOffset > fileLength)
+ throw FormatError.Corrupted("COPC offset to point data is outside the file.");
+
+ uint vlrCount = Bytes.ReadUInt32LE(header.AsSpan(100, 4));
+ if (vlrCount > MaxVlrs)
+ throw FormatError.Corrupted($"COPC file declares {vlrCount} variable length records; at most {MaxVlrs} are accepted.");
+
+ int rawPointFormatByte = header[104];
+ int pointFormat = rawPointFormatByte & 0x3F;
+ int recordLength = Bytes.ReadUInt16LE(header.AsSpan(105, 2));
+ if (recordLength < 20)
+ throw FormatError.Corrupted($"COPC point record length {recordLength} is smaller than 20 bytes.");
+
+ uint legacyPointCount = Bytes.ReadUInt32LE(header.AsSpan(107, 4));
+ ulong extendedPointCount = Bytes.ReadUInt64LE(header.AsSpan(247, 8));
+ long pointCount = (long)(extendedPointCount != 0 ? extendedPointCount : legacyPointCount);
+
+ double scaleX = Bytes.ReadDoubleLE(header.AsSpan(131, 8));
+ double scaleY = Bytes.ReadDoubleLE(header.AsSpan(139, 8));
+ double scaleZ = Bytes.ReadDoubleLE(header.AsSpan(147, 8));
+ if (!double.IsFinite(scaleX) || !double.IsFinite(scaleY) || !double.IsFinite(scaleZ) ||
+ scaleX == 0 || scaleY == 0 || scaleZ == 0)
+ throw FormatError.Corrupted("COPC scale factors must be non-zero and finite.");
+
+ double offsetX = Bytes.ReadDoubleLE(header.AsSpan(155, 8));
+ double offsetY = Bytes.ReadDoubleLE(header.AsSpan(163, 8));
+ double offsetZ = Bytes.ReadDoubleLE(header.AsSpan(171, 8));
+ if (!double.IsFinite(offsetX) || !double.IsFinite(offsetY) || !double.IsFinite(offsetZ))
+ throw FormatError.Corrupted("COPC coordinate offset values must be finite.");
+
+ double maxX = Bytes.ReadDoubleLE(header.AsSpan(179, 8));
+ double minX = Bytes.ReadDoubleLE(header.AsSpan(187, 8));
+ double maxY = Bytes.ReadDoubleLE(header.AsSpan(195, 8));
+ double minY = Bytes.ReadDoubleLE(header.AsSpan(203, 8));
+ double maxZ = Bytes.ReadDoubleLE(header.AsSpan(211, 8));
+ double minZ = Bytes.ReadDoubleLE(header.AsSpan(219, 8));
+
+ var bounds = (!double.IsFinite(maxX) || !double.IsFinite(minX) ||
+ !double.IsFinite(maxY) || !double.IsFinite(minY) ||
+ !double.IsFinite(maxZ) || !double.IsFinite(minZ))
+ ? PclBounds.Empty
+ : new PclBounds(new PclVector3(minX, minY, minZ), new PclVector3(maxX, maxY, maxZ));
+
+ // Read VLRs to find the COPC info VLR and optional coordinate system.
+ var (copcInfo, crs) = ReadVlrs(fs, headerSize, pointDataOffset, vlrCount);
+ if (copcInfo == null)
+ throw FormatError.Corrupted("COPC file is missing the required COPC info VLR (user 'copc', record 1).");
+
+ if (copcInfo.HalfSize <= 0 || !double.IsFinite(copcInfo.HalfSize))
+ throw FormatError.Corrupted($"Invalid COPC halfsize {copcInfo.HalfSize}; must be positive and finite.");
+
+ var octreeBounds = new PclBounds(
+ new PclVector3(copcInfo.Center.X - copcInfo.HalfSize, copcInfo.Center.Y - copcInfo.HalfSize, copcInfo.Center.Z - copcInfo.HalfSize),
+ new PclVector3(copcInfo.Center.X + copcInfo.HalfSize, copcInfo.Center.Y + copcInfo.HalfSize, copcInfo.Center.Z + copcInfo.HalfSize));
+
+ // Read octree hierarchy
+ var nodes = CopcHierarchy.ReadHierarchy(fs, copcInfo);
+
+ var doc = new CopcDocument(
+ path,
+ fileLength,
+ $"{major}.{minor}",
+ pointFormat,
+ recordLength,
+ new PclVector3(scaleX, scaleY, scaleZ),
+ new PclVector3(offsetX, offsetY, offsetZ),
+ bounds,
+ octreeBounds,
+ copcInfo,
+ nodes,
+ pointCount);
+
+ if (crs != null) doc._metadata["CoordinateSystem"] = crs;
+ return doc;
+ }
+
+ /// Finds octree nodes whose voxel bounding box intersects the given spatial bounds.
+ /// Query bounding box.
+ /// Optional maximum octree level to include.
+ public IReadOnlyList FindNodes(PclBounds bounds, int? maxLevel = null)
+ {
+ if (bounds.IsEmpty) return Array.Empty();
+ return _nodes
+ .Where(n => (maxLevel == null || n.Key.Level <= maxLevel.Value) && n.Bounds.Intersects(bounds))
+ .ToList();
+ }
+
+ /// Streams points from a single octree node.
+ /// The octree node to read points from.
+ /// Read options (subsampling, limits, transforms).
+ public IEnumerable ReadPoints(CopcNode node, PclReadOptions? options = null)
+ {
+ return _primaryScan.ReadPointsFromNodes([node], options);
+ }
+
+ /// Streams points from octree nodes intersecting the given bounding box.
+ /// Spatial bounding box filter.
+ /// Read options (subsampling, limits, transforms).
+ public IEnumerable ReadPoints(PclBounds bounds, PclReadOptions? options = null)
+ {
+ var matchingNodes = FindNodes(bounds);
+ return _primaryScan.ReadPointsFromNodes(matchingNodes, options);
+ }
+
+ private static (CopcInfo? Info, string? Crs) ReadVlrs(FileStream fs, int headerSize, uint pointDataOffset, uint vlrCount)
+ {
+ CopcInfo? copcInfo = null;
+ string? crs = null;
+ long position = headerSize;
+ byte[] vlrHeader = new byte[54];
+
+ for (uint i = 0; i < vlrCount; i++)
+ {
+ if (position + 54 > pointDataOffset)
+ throw FormatError.Corrupted("COPC variable length record reaches past the point data.");
+
+ fs.Position = position;
+ fs.ReadExactly(vlrHeader);
+ position += 54;
+
+ string userId = ReadFixedAscii(vlrHeader.AsSpan(2, 16));
+ ushort recordId = Bytes.ReadUInt16LE(vlrHeader.AsSpan(18, 2));
+ ushort dataLength = Bytes.ReadUInt16LE(vlrHeader.AsSpan(20, 2));
+
+ if (position + dataLength > pointDataOffset)
+ throw FormatError.Corrupted("COPC variable length record reaches past the point data.");
+
+ if (userId.Equals("copc", StringComparison.Ordinal) && recordId == 1)
+ {
+ if (dataLength != 160)
+ throw FormatError.Corrupted($"COPC info record has invalid length {dataLength} bytes (expected 160).");
+
+ byte[] copcData = new byte[160];
+ fs.ReadExactly(copcData);
+
+ double cx = Bytes.ReadDoubleLE(copcData.AsSpan(0, 8));
+ double cy = Bytes.ReadDoubleLE(copcData.AsSpan(8, 8));
+ double cz = Bytes.ReadDoubleLE(copcData.AsSpan(16, 8));
+ double halfSize = Bytes.ReadDoubleLE(copcData.AsSpan(24, 8));
+ double spacing = Bytes.ReadDoubleLE(copcData.AsSpan(32, 8));
+ ulong rootHierOffset = Bytes.ReadUInt64LE(copcData.AsSpan(40, 8));
+ ulong rootHierSize = Bytes.ReadUInt64LE(copcData.AsSpan(48, 8));
+ double gpsMin = Bytes.ReadDoubleLE(copcData.AsSpan(56, 8));
+ double gpsMax = Bytes.ReadDoubleLE(copcData.AsSpan(64, 8));
+
+ copcInfo = new CopcInfo(
+ new PclVector3(cx, cy, cz),
+ halfSize,
+ spacing,
+ rootHierOffset,
+ rootHierSize,
+ double.IsFinite(gpsMin) && gpsMin != 0 ? gpsMin : null,
+ double.IsFinite(gpsMax) && gpsMax != 0 ? gpsMax : null);
+ }
+ else if (userId.Equals("LASF_Projection", StringComparison.Ordinal) && recordId == 2112)
+ {
+ byte[] wktBytes = new byte[dataLength];
+ if (dataLength > 0) fs.ReadExactly(wktBytes);
+ string wkt = System.Text.Encoding.UTF8.GetString(wktBytes).TrimEnd('\0', ' ', '\r', '\n');
+ if (wkt.Length > 0) crs = wkt;
+ }
+ else if (userId.Equals("LASF_Projection", StringComparison.Ordinal) && recordId == 34735 && crs == null)
+ {
+ byte[] geoData = new byte[dataLength];
+ if (dataLength > 0) fs.ReadExactly(geoData);
+ if (TryReadEpsg(geoData, out ushort epsg))
+ crs = $"EPSG:{epsg}";
+ }
+
+ position += dataLength;
+ }
+
+ return (copcInfo, crs);
+ }
+
+ private static bool TryReadEpsg(byte[] data, out ushort code)
+ {
+ code = 0;
+ if (data.Length < 8) return false;
+ int keyCount = Bytes.ReadUInt16LE(data.AsSpan(6, 2));
+ if (keyCount <= 0 || keyCount > 1024 || 8 + (keyCount * 8) > data.Length) return false;
+
+ for (int pass = 0; pass < 2; pass++)
+ {
+ int wanted = pass == 0 ? 3072 : 2048;
+ for (int k = 0; k < keyCount; k++)
+ {
+ var entry = data.AsSpan(8 + (k * 8), 8);
+ if (Bytes.ReadUInt16LE(entry[..2]) != wanted) continue;
+ int value = Bytes.ReadUInt16LE(entry.Slice(6, 2));
+ if (value is >= 1 and <= ushort.MaxValue && value != 32767)
+ {
+ code = (ushort)value;
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static string ReadFixedAscii(ReadOnlySpan bytes)
+ {
+ int length = bytes.IndexOf((byte)0);
+ if (length < 0) length = bytes.Length;
+ return System.Text.Encoding.ASCII.GetString(bytes[..length]);
+ }
+}
diff --git a/src/PclIO/Formats/Copc/CopcHierarchy.cs b/src/PclIO/Formats/Copc/CopcHierarchy.cs
new file mode 100644
index 0000000..4a4f9d0
--- /dev/null
+++ b/src/PclIO/Formats/Copc/CopcHierarchy.cs
@@ -0,0 +1,92 @@
+using PclIO.Internal;
+
+namespace PclIO.Formats.Copc;
+
+/// Reads and resolves the COPC octree hierarchy pages.
+internal static class CopcHierarchy
+{
+ private const int MaxHierarchyPages = 10000;
+ private const int MaxPageBytes = 16 * 1024 * 1024; // 16 MB max per page
+ private const int EntrySize = 32;
+
+ public static List ReadHierarchy(Stream stream, CopcInfo info)
+ {
+ if (info.RootHierarchySize < EntrySize || info.RootHierarchySize % EntrySize != 0)
+ throw FormatError.Corrupted($"Invalid root hierarchy page size {info.RootHierarchySize} bytes.");
+ if (info.RootHierarchySize > MaxPageBytes)
+ throw FormatError.Corrupted($"Root hierarchy page size {info.RootHierarchySize} bytes exceeds safety limit.");
+
+ long fileLength = stream.Length;
+ if (info.RootHierarchyOffset + info.RootHierarchySize > (ulong)fileLength)
+ throw FormatError.Truncated("COPC root hierarchy page");
+
+ var nodes = new List();
+ var pagesToRead = new Queue<(ulong Offset, int ByteSize)>();
+ var visitedPages = new HashSet();
+
+ pagesToRead.Enqueue((info.RootHierarchyOffset, (int)info.RootHierarchySize));
+
+ while (pagesToRead.Count > 0)
+ {
+ var (offset, size) = pagesToRead.Dequeue();
+ if (!visitedPages.Add(offset))
+ throw FormatError.Corrupted("Cyclic COPC hierarchy page reference detected.");
+
+ if (visitedPages.Count > MaxHierarchyPages)
+ throw FormatError.Corrupted($"COPC hierarchy exceeds safety limit of {MaxHierarchyPages} pages.");
+
+ if (offset + (ulong)size > (ulong)fileLength)
+ throw FormatError.Truncated("COPC hierarchy page");
+
+ byte[] pageBuffer = new byte[size];
+ stream.Position = (long)offset;
+ stream.ReadExactly(pageBuffer);
+
+ int entryCount = size / EntrySize;
+ for (int e = 0; e < entryCount; e++)
+ {
+ int baseOff = e * EntrySize;
+ int level = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff, 4));
+ int x = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff + 4, 4));
+ int y = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff + 8, 4));
+ int z = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff + 12, 4));
+ ulong entryOffset = Bytes.ReadUInt64LE(pageBuffer.AsSpan(baseOff + 16, 8));
+ int byteSize = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff + 24, 4));
+ int pointCount = Bytes.ReadInt32LE(pageBuffer.AsSpan(baseOff + 28, 4));
+
+ if (level < 0) continue;
+
+ if (pointCount > 0)
+ {
+ if (byteSize <= 0)
+ throw FormatError.Corrupted($"COPC chunk byte size {byteSize} is invalid.");
+ if (entryOffset + (ulong)byteSize > (ulong)fileLength)
+ throw FormatError.Truncated("COPC point chunk data");
+
+ var key = new CopcVoxelKey(level, x, y, z);
+ var bounds = key.GetBounds(info.Center, info.HalfSize);
+ nodes.Add(new CopcNode(key, bounds, entryOffset, byteSize, pointCount));
+ }
+ else if (pointCount == -1)
+ {
+ if (byteSize < EntrySize || byteSize % EntrySize != 0 || byteSize > MaxPageBytes)
+ throw FormatError.Corrupted($"COPC child hierarchy page byte size {byteSize} is invalid.");
+ if (entryOffset + (ulong)byteSize > (ulong)fileLength)
+ throw FormatError.Truncated("COPC child hierarchy page data");
+
+ pagesToRead.Enqueue((entryOffset, byteSize));
+ }
+ else if (pointCount == 0)
+ {
+ // Empty entry
+ }
+ else
+ {
+ throw FormatError.Corrupted($"Unexpected point count {pointCount} in COPC hierarchy entry.");
+ }
+ }
+ }
+
+ return nodes;
+ }
+}
diff --git a/src/PclIO/Formats/Copc/CopcModels.cs b/src/PclIO/Formats/Copc/CopcModels.cs
new file mode 100644
index 0000000..c7986c8
--- /dev/null
+++ b/src/PclIO/Formats/Copc/CopcModels.cs
@@ -0,0 +1,41 @@
+namespace PclIO.Formats.Copc;
+
+/// Identifies a voxel in the COPC octree hierarchy by level and 3D integer indices.
+/// Octree depth level (0 is root).
+/// Voxel integer X index at this level.
+/// Voxel integer Y index at this level.
+/// Voxel integer Z index at this level.
+public readonly record struct CopcVoxelKey(int Level, int X, int Y, int Z)
+{
+ /// Calculates the axis-aligned spatial bounding box of this voxel from the dataset center and half-size.
+ public PclBounds GetBounds(PclVector3 center, double halfSize)
+ {
+ if (Level < 0 || halfSize <= 0) return PclBounds.Empty;
+ double side = (2.0 * halfSize) / Math.Pow(2.0, Level);
+ double minX = (center.X - halfSize) + (X * side);
+ double minY = (center.Y - halfSize) + (Y * side);
+ double minZ = (center.Z - halfSize) + (Z * side);
+ return new PclBounds(new PclVector3(minX, minY, minZ), new PclVector3(minX + side, minY + side, minZ + side));
+ }
+
+ ///
+ public override string ToString() => $"({Level}-{X}-{Y}-{Z})";
+}
+
+/// Represents a resolved node in the COPC octree hierarchy.
+/// Voxel key identifying the node in the octree.
+/// Spatial bounding box of the node voxel.
+/// Absolute file offset of the compressed point chunk.
+/// Size of the compressed point chunk in bytes.
+/// Number of points in this node chunk.
+public sealed record CopcNode(CopcVoxelKey Key, PclBounds Bounds, ulong Offset, int ByteSize, int PointCount);
+
+/// Metadata stored in the COPC info VLR.
+internal sealed record CopcInfo(
+ PclVector3 Center,
+ double HalfSize,
+ double Spacing,
+ ulong RootHierarchyOffset,
+ ulong RootHierarchySize,
+ double? GpsTimeMin,
+ double? GpsTimeMax);
diff --git a/src/PclIO/Formats/Copc/CopcScan.cs b/src/PclIO/Formats/Copc/CopcScan.cs
new file mode 100644
index 0000000..e9f69c9
--- /dev/null
+++ b/src/PclIO/Formats/Copc/CopcScan.cs
@@ -0,0 +1,233 @@
+using PclIO.Formats.Laz;
+using PclIO.Internal;
+
+namespace PclIO.Formats.Copc;
+
+/// Streams points from a Cloud Optimized Point Cloud (COPC) file.
+public sealed class CopcScan : PclScan
+{
+ private const int MaxChunkMemory = 64 * 1024 * 1024; // 64 MB max per chunk
+
+ ///
+ public override string Id { get; }
+
+ ///
+ public override string Name { get; }
+
+ ///
+ public override long PointCount { get; }
+
+ /// Path of the COPC file.
+ public string FilePath { get; }
+
+ ///
+ public override bool HasColors { get; }
+
+ ///
+ public override bool HasIntensities => true;
+
+ ///
+ public override bool HasNormals => false;
+
+ private readonly int _pointFormat;
+ private readonly int _recordLength;
+ private readonly PclVector3 _scale;
+ private readonly PclVector3 _offset;
+ private readonly IReadOnlyList _nodes;
+
+ internal CopcScan(
+ string id,
+ string name,
+ long pointCount,
+ PclBounds bounds,
+ string filePath,
+ int pointFormat,
+ int recordLength,
+ PclVector3 scale,
+ PclVector3 offset,
+ IReadOnlyList nodes)
+ {
+ Id = id;
+ Name = name;
+ PointCount = pointCount;
+ Bounds = bounds;
+ FilePath = filePath;
+ _pointFormat = pointFormat;
+ _recordLength = recordLength;
+ _scale = scale;
+ _offset = offset;
+ _nodes = nodes;
+ HasColors = pointFormat is 2 or 3 or 5 or 7 or 8 or 10;
+ }
+
+ /// Streams points across the octree nodes of this scan.
+ public override IEnumerable ReadPoints(PclReadOptions? options = null)
+ {
+ return ReadPointsFromNodes(_nodes, options);
+ }
+
+ /// Streams points from the specified octree nodes.
+ internal IEnumerable ReadPointsFromNodes(IEnumerable nodes, PclReadOptions? options = null)
+ {
+ options ??= PclReadOptions.Default;
+ long targetCount = options.MaxPoints ?? PointCount;
+ if (targetCount <= 0 || PointCount <= 0) yield break;
+ targetCount = Math.Min(targetCount, PointCount);
+ int step = Math.Max(1, options.SubsampleStep);
+
+ using var fs = File.OpenRead(FilePath);
+ long fileLength = fs.Length;
+ long yielded = 0;
+ long globalPointIndex = 0;
+
+ bool hasColor = HasColors;
+ bool isClassicFormat = _pointFormat <= 3;
+ bool hasGpsTime = _pointFormat is 1 or 3;
+ int extraBytesCount = isClassicFormat ? _recordLength - (20 + (hasGpsTime ? 8 : 0) + (hasColor ? 6 : 0)) : 0;
+ if (extraBytesCount < 0) extraBytesCount = 0;
+
+ foreach (var node in nodes)
+ {
+ if (node.PointCount <= 0) continue;
+ if (node.ByteSize > MaxChunkMemory)
+ throw FormatError.Corrupted($"COPC chunk byte size {node.ByteSize} exceeds memory limit.");
+ if (node.Offset + (ulong)node.ByteSize > (ulong)fileLength)
+ throw FormatError.Truncated("COPC point chunk data");
+
+ fs.Position = (long)node.Offset;
+ byte[] chunkBuffer = new byte[node.ByteSize];
+ fs.ReadExactly(chunkBuffer);
+
+ if (chunkBuffer.Length < _recordLength)
+ throw FormatError.Truncated("point 0 in COPC chunk");
+
+ // Point 0 coordinates and attributes
+ int rawX0 = Bytes.ReadInt32LE(chunkBuffer.AsSpan(0, 4));
+ int rawY0 = Bytes.ReadInt32LE(chunkBuffer.AsSpan(4, 4));
+ int rawZ0 = Bytes.ReadInt32LE(chunkBuffer.AsSpan(8, 4));
+ ushort rawInt0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(12, 2));
+
+ byte rawClass0;
+ ushort rawR0 = 0, rawG0 = 0, rawB0 = 0;
+
+ if (isClassicFormat)
+ {
+ rawClass0 = (byte)(chunkBuffer[15] & 0x1F);
+ if (hasColor)
+ {
+ int rgbOffset = 20 + (hasGpsTime ? 8 : 0);
+ if (chunkBuffer.Length >= rgbOffset + 6)
+ {
+ rawR0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(rgbOffset, 2));
+ rawG0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(rgbOffset + 2, 2));
+ rawB0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(rgbOffset + 4, 2));
+ }
+ }
+ }
+ else
+ {
+ // LAS 1.4 point format (6 to 8)
+ rawClass0 = chunkBuffer.Length > 16 ? chunkBuffer[16] : (byte)0;
+ if (hasColor && chunkBuffer.Length >= 36)
+ {
+ rawR0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(30, 2));
+ rawG0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(32, 2));
+ rawB0 = Bytes.ReadUInt16LE(chunkBuffer.AsSpan(34, 2));
+ }
+ }
+
+ // Yield Point 0 if subsample matches
+ if (globalPointIndex % step == 0)
+ {
+ double x = _offset.X + (rawX0 * _scale.X);
+ double y = _offset.Y + (rawY0 * _scale.Y);
+ double z = _offset.Z + (rawZ0 * _scale.Z);
+ if (double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z))
+ {
+ float intensity = rawInt0 / 65535.0f;
+ PclColor? color = hasColor ? new PclColor((byte)(rawR0 / 257), (byte)(rawG0 / 257), (byte)(rawB0 / 257)) : null;
+
+ var pt = new PclPoint(new PclVector3(x, y, z), Color: color, Intensity: intensity,
+ Classification: rawClass0, Index: (ulong)yielded);
+ if (options.ApplyTransform)
+ pt = pt with { Position = Transform.TransformPoint(pt.Position) };
+
+ yield return pt;
+ yielded++;
+ if (yielded >= targetCount) yield break;
+ }
+ }
+ globalPointIndex++;
+
+ // Decompress remaining points if classic LASzip compression (formats 0..3)
+ if (isClassicFormat && node.PointCount > 1)
+ {
+ var dec = new LaszipArithmeticDecoder(chunkBuffer, _recordLength);
+ var ptDecomp = new LaszipPoint10Decompressor(dec);
+ ptDecomp.Init(chunkBuffer.AsSpan(0, 20));
+
+ LaszipGpsTime11Decompressor? gpsDecomp = null;
+ if (hasGpsTime)
+ {
+ gpsDecomp = new LaszipGpsTime11Decompressor(dec);
+ long rawGps = Bytes.ReadInt64LE(chunkBuffer.AsSpan(20, 8));
+ gpsDecomp.Init(rawGps);
+ }
+
+ LaszipRgb12Decompressor? rgbDecomp = null;
+ if (hasColor)
+ {
+ rgbDecomp = new LaszipRgb12Decompressor(dec);
+ int rgbOffset = 20 + (hasGpsTime ? 8 : 0);
+ rgbDecomp.Init(chunkBuffer.AsSpan(rgbOffset, 6));
+ }
+
+ LaszipByteDecompressor? byteDecomp = null;
+ byte[]? extraBuffer = null;
+ if (extraBytesCount > 0)
+ {
+ byteDecomp = new LaszipByteDecompressor(dec, extraBytesCount);
+ int extraOffset = 20 + (hasGpsTime ? 8 : 0) + (hasColor ? 6 : 0);
+ byteDecomp.Init(chunkBuffer.AsSpan(extraOffset, extraBytesCount));
+ extraBuffer = new byte[extraBytesCount];
+ }
+
+ for (uint p = 1; p < node.PointCount; p++)
+ {
+ ptDecomp.DecompressNext(out int px, out int py, out int pz, out ushort pIntensity,
+ out _, out byte pClassification, out _, out _, out _);
+
+ if (gpsDecomp != null) gpsDecomp.DecompressNext();
+
+ ushort pr = 0, pg = 0, pb = 0;
+ if (rgbDecomp != null) rgbDecomp.DecompressNext(out pr, out pg, out pb);
+
+ if (byteDecomp != null) byteDecomp.DecompressNext(extraBuffer!);
+
+ if (globalPointIndex % step == 0)
+ {
+ double pxCoord = _offset.X + (px * _scale.X);
+ double pyCoord = _offset.Y + (py * _scale.Y);
+ double pzCoord = _offset.Z + (pz * _scale.Z);
+ if (double.IsFinite(pxCoord) && double.IsFinite(pyCoord) && double.IsFinite(pzCoord))
+ {
+ float intensity = pIntensity / 65535.0f;
+ byte cls = (byte)(pClassification & 0x1F);
+ PclColor? color = hasColor ? new PclColor((byte)(pr / 257), (byte)(pg / 257), (byte)(pb / 257)) : null;
+
+ var pt = new PclPoint(new PclVector3(pxCoord, pyCoord, pzCoord), Color: color, Intensity: intensity,
+ Classification: cls, Index: (ulong)yielded);
+ if (options.ApplyTransform)
+ pt = pt with { Position = Transform.TransformPoint(pt.Position) };
+
+ yield return pt;
+ yielded++;
+ if (yielded >= targetCount) yield break;
+ }
+ }
+ globalPointIndex++;
+ }
+ }
+ }
+ }
+}
diff --git a/src/PclIO/Internal/KindDetector.cs b/src/PclIO/Internal/KindDetector.cs
index a2ad826..b091664 100644
--- a/src/PclIO/Internal/KindDetector.cs
+++ b/src/PclIO/Internal/KindDetector.cs
@@ -57,7 +57,9 @@ public static PclFileKind Detect(string path)
if (!File.Exists(path))
throw new FileNotFoundException($"Point cloud file not found: {path}", path);
- string ext = Path.GetExtension(path).ToLowerInvariant();
+ string ext = path.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase)
+ ? ".copc.laz"
+ : Path.GetExtension(path).ToLowerInvariant();
if (ext == ".bin")
{
string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
@@ -79,9 +81,14 @@ public static PclFileKind Detect(Stream stream, string? extension = null)
{
if (!string.IsNullOrEmpty(extension))
{
- if (extension.Contains('/') || extension.Contains('\\') || (extension.Contains('.') && !extension.StartsWith('.')))
- extension = Path.GetExtension(extension);
- extension = extension.ToLowerInvariant();
+ if (extension.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase))
+ extension = ".copc.laz";
+ else
+ {
+ if (extension.Contains('/') || extension.Contains('\\') || (extension.Contains('.') && !extension.StartsWith('.')))
+ extension = Path.GetExtension(extension);
+ extension = extension.ToLowerInvariant();
+ }
}
if (!stream.CanSeek)
@@ -123,9 +130,15 @@ public static PclFileKind Detect(Stream stream, string? extension = null)
if (head.StartsWith(EdgeWiseTextMagic) || head.StartsWith(EdgeWiseTreeMagic))
return PclFileKind.EdgeWise;
- // LAS and LAZ files share the LASF signature; .laz files with valid LAZ headers are Laz, others Las.
+ // LAS, LAZ and COPC files share the LASF signature; COPC files declare a copc VLR; .laz with valid LAZ headers are Laz, others Las.
if (head.StartsWith(LasMagic))
{
+ if (IsCopcHeader(stream, origin))
+ return PclFileKind.Copc;
+
+ if (extension == ".copc.laz")
+ return PclFileKind.Unknown;
+
if (extension == ".laz")
return IsLazHeader(stream, origin) ? PclFileKind.Laz : PclFileKind.Unknown;
return PclFileKind.Las;
@@ -178,6 +191,58 @@ public static PclFileKind Detect(Stream stream, string? extension = null)
return PclFileKind.Unknown;
}
+ // True when a LAS 1.4 stream contains a COPC info VLR (user "copc", record 1, length 160).
+ private static bool IsCopcHeader(Stream stream, long origin)
+ {
+ try
+ {
+ if (stream.Length - origin < 375) return false;
+ stream.Position = origin;
+ Span header = stackalloc byte[375];
+ stream.ReadExactly(header);
+
+ if (!header[..4].SequenceEqual(LasMagic)) return false;
+ int major = header[24];
+ int minor = header[25];
+ if (major != 1 || minor < 4) return false;
+
+ ushort headerSize = Bytes.ReadUInt16LE(header.Slice(94, 2));
+ uint pointDataOffset = Bytes.ReadUInt32LE(header.Slice(96, 4));
+ uint vlrCount = Bytes.ReadUInt32LE(header.Slice(100, 4));
+
+ if (headerSize < 375 || headerSize > pointDataOffset || pointDataOffset > stream.Length) return false;
+ if (vlrCount is 0 or > 4096) return false;
+
+ stream.Position = origin + headerSize;
+ long pos = origin + headerSize;
+ byte[] vlrHeader = new byte[54];
+ for (uint i = 0; i < vlrCount && i < 64; i++)
+ {
+ if (pos + 54 > origin + pointDataOffset) break;
+ stream.ReadExactly(vlrHeader);
+ pos += 54;
+ string userId = System.Text.Encoding.ASCII.GetString(vlrHeader.AsSpan(2, 16)).TrimEnd('\0');
+ ushort recordId = Bytes.ReadUInt16LE(vlrHeader.AsSpan(18, 2));
+ ushort dataLen = Bytes.ReadUInt16LE(vlrHeader.AsSpan(20, 2));
+ if (userId.Equals("copc", StringComparison.Ordinal) && recordId == 1 && dataLen == 160)
+ return true;
+ pos += dataLen;
+ if (pos > origin + pointDataOffset) break;
+ stream.Position = pos;
+ }
+
+ return false;
+ }
+ catch
+ {
+ return false;
+ }
+ finally
+ {
+ stream.Position = origin;
+ }
+ }
+
// True when a LAS stream contains compressed point records (LAZ): point format flag or LASzip VLR (22204).
private static bool IsLazHeader(Stream stream, long origin)
{
diff --git a/src/PclIO/Model/PclBounds.cs b/src/PclIO/Model/PclBounds.cs
index 27c914f..2a97410 100644
--- a/src/PclIO/Model/PclBounds.cs
+++ b/src/PclIO/Model/PclBounds.cs
@@ -26,6 +26,13 @@ public bool Contains(PclVector3 pt) =>
pt.Y >= Min.Y && pt.Y <= Max.Y &&
pt.Z >= Min.Z && pt.Z <= Max.Z;
+ /// True when this bounding box overlaps with another bounding box (edges included).
+ public bool Intersects(PclBounds other) =>
+ !IsEmpty && !other.IsEmpty &&
+ Min.X <= other.Max.X && Max.X >= other.Min.X &&
+ Min.Y <= other.Max.Y && Max.Y >= other.Min.Y &&
+ Min.Z <= other.Max.Z && Max.Z >= other.Min.Z;
+
/// Returns the smallest box that contains this box and the point.
public PclBounds Encapsulate(PclVector3 pt)
{
diff --git a/src/PclIO/PclFile.cs b/src/PclIO/PclFile.cs
index 3f134c9..01a2909 100644
--- a/src/PclIO/PclFile.cs
+++ b/src/PclIO/PclFile.cs
@@ -1,3 +1,4 @@
+using PclIO.Formats.Copc;
using PclIO.Formats.E57;
using PclIO.Formats.EdgeWise;
using PclIO.Formats.Faro;
@@ -68,6 +69,7 @@ public static PclDocument Open(string path, PclReadOptions? options = null)
PclFileKind.Tiles3d => Tiles3dDocument.Open(path, options),
PclFileKind.Potree => PotreeDocument.Open(path, options),
PclFileKind.Laz => LazDocument.Open(path, options),
+ PclFileKind.Copc => CopcDocument.Open(path, options),
_ => throw new NotSupportedException($"Unsupported or unrecognized point cloud file: '{path}'"),
};
}
diff --git a/src/PclIO/PclFileKind.cs b/src/PclIO/PclFileKind.cs
index 1b73cbc..1b1b22f 100644
--- a/src/PclIO/PclFileKind.cs
+++ b/src/PclIO/PclFileKind.cs
@@ -59,4 +59,7 @@ public enum PclFileKind
/// LASzip compressed ASPRS LAS point cloud (.laz).
Laz = 18,
+
+ /// Cloud Optimized Point Cloud (clustered octree in LAZ, .copc.laz).
+ Copc = 19,
}
diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs
index e20628d..d1e33e7 100644
--- a/tests/PclIO.Tests/FormatTests.cs
+++ b/tests/PclIO.Tests/FormatTests.cs
@@ -1,4 +1,5 @@
using PclIO.Export;
+using PclIO.Formats.Copc;
using PclIO.Formats.E57;
using PclIO.Formats.EdgeWise;
using PclIO.Formats.Faro;
@@ -5600,4 +5601,161 @@ public void Laz_Rejects_Unsupported_Chunk_Table_Version_With_NotSupportedExcepti
Assert.Throws(() => LazDocument.Open(path));
}
+
+ [Fact]
+ public void Copc_Opens_Lists_Scans_And_Streams_Points()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(
+ x: 10.0, y: 20.0, z: 30.0,
+ intensity: 0.5f,
+ color: new PclColor(200, 100, 50),
+ classification: 2,
+ pointFormat: 2);
+
+ string path = dir.Write("test.copc.laz", bytes);
+ using var doc = PclFile.Open(path) as CopcDocument;
+ Assert.NotNull(doc);
+
+ Assert.Equal(PclFileKind.Copc, doc.Kind);
+ Assert.Equal(10.0, doc.Center.X);
+ Assert.Equal(20.0, doc.Center.Y);
+ Assert.Equal(30.0, doc.Center.Z);
+ Assert.Equal(50.0, doc.HalfSize);
+ Assert.Equal(1.0, doc.Spacing);
+ Assert.Single(doc.Nodes);
+ Assert.Equal(new CopcVoxelKey(0, 0, 0, 0), doc.Nodes[0].Key);
+
+ var scan = Assert.Single(doc.Scans);
+ Assert.Equal(1, scan.PointCount);
+ Assert.True(scan.HasColors);
+ Assert.True(scan.HasIntensities);
+ Assert.False(scan.HasNormals);
+
+ var pt = Assert.Single(scan.ReadPoints());
+ AssertNear(new PclVector3(10, 20, 30), pt.Position);
+ Assert.NotNull(pt.Intensity);
+ Assert.InRange(pt.Intensity.Value, 0.49f, 0.51f);
+ Assert.Equal((byte)2, pt.Classification);
+ Assert.NotNull(pt.Color);
+ Assert.Equal((byte)200, pt.Color.Value.R);
+ Assert.Equal((byte)100, pt.Color.Value.G);
+ Assert.Equal((byte)50, pt.Color.Value.B);
+ }
+
+ [Fact]
+ public void Copc_Point_Format_7_Decodes_RGB_And_Coordinates()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(
+ x: 15.0, y: 25.0, z: 35.0,
+ intensity: 0.75f,
+ color: new PclColor(120, 180, 240),
+ classification: 3,
+ pointFormat: 7);
+
+ string path = dir.Write("format7.copc.laz", bytes);
+ using var doc = CopcDocument.Open(path);
+
+ Assert.Equal(7, doc.PointFormat);
+ var pt = Assert.Single(doc.ReadAllPoints());
+ AssertNear(new PclVector3(15, 25, 35), pt.Position);
+ Assert.NotNull(pt.Color);
+ Assert.Equal((byte)120, pt.Color.Value.R);
+ Assert.Equal((byte)180, pt.Color.Value.G);
+ Assert.Equal((byte)240, pt.Color.Value.B);
+ Assert.Equal((byte)3, pt.Classification);
+ }
+
+ [Fact]
+ public void Copc_FindNodes_And_ReadPoints_By_Bounds()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(
+ x: 10.0, y: 20.0, z: 30.0,
+ pointFormat: 2);
+
+ string path = dir.Write("test.copc.laz", bytes);
+ using var doc = CopcDocument.Open(path);
+
+ // Bounding box encompassing the root voxel
+ var queryBox = new PclBounds(new PclVector3(0, 0, 0), new PclVector3(50, 50, 50));
+ var matchingNodes = doc.FindNodes(queryBox);
+ Assert.Single(matchingNodes);
+
+ var pointsInBox = doc.ReadPoints(queryBox).ToList();
+ Assert.Single(pointsInBox);
+ AssertNear(new PclVector3(10, 20, 30), pointsInBox[0].Position);
+
+ // Bounding box outside the root voxel
+ var outsideBox = new PclBounds(new PclVector3(500, 500, 500), new PclVector3(600, 600, 600));
+ Assert.Empty(doc.FindNodes(outsideBox));
+ Assert.Empty(doc.ReadPoints(outsideBox));
+
+ // Read points directly from node
+ var nodePoints = doc.ReadPoints(doc.Nodes[0]).ToList();
+ Assert.Single(nodePoints);
+ AssertNear(new PclVector3(10, 20, 30), nodePoints[0].Position);
+ }
+
+ [Fact]
+ public void Copc_Subsample_And_MaxPoints_Honored()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(x: 10, y: 20, z: 30);
+ string path = dir.Write("test.copc.laz", bytes);
+ using var doc = CopcDocument.Open(path);
+
+ Assert.Empty(doc.ReadAllPoints(new PclReadOptions { MaxPoints = 0 }));
+ Assert.Single(doc.ReadAllPoints(new PclReadOptions { MaxPoints = 1 }));
+ }
+
+ [Fact]
+ public void Copc_Wrong_Content_Throws_InvalidDataException()
+ {
+ using var dir = new TempDirectory();
+ string path = dir.Write("corrupt.copc.laz", new byte[100]);
+ Assert.Throws(() => PclFile.Open(path));
+ Assert.Throws(() => CopcDocument.Open(path));
+ }
+
+ [Fact]
+ public void Copc_Rejects_Corrupt_Hierarchy_Offset_With_InvalidDataException()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(corruptHierarchyOffset: true);
+ string path = dir.Write("bad_offset.copc.laz", bytes);
+
+ Assert.Throws(() => CopcDocument.Open(path));
+ }
+
+ [Fact]
+ public void Copc_Rejects_Cyclic_Hierarchy_With_InvalidDataException()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(cyclicHierarchy: true);
+ string path = dir.Write("cyclic.copc.laz", bytes);
+
+ Assert.Throws(() => CopcDocument.Open(path));
+ }
+
+ [Fact]
+ public void Copc_Rejects_Corrupt_Vlr_Size_With_InvalidDataException()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(corruptVlrSize: true);
+ string path = dir.Write("bad_vlr.copc.laz", bytes);
+
+ Assert.Throws(() => CopcDocument.Open(path));
+ }
+
+ [Fact]
+ public void Copc_Rejects_Truncated_Data_With_InvalidDataException()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticCopc(truncateData: true);
+ string path = dir.Write("truncated.copc.laz", bytes);
+
+ Assert.Throws(() => CopcDocument.Open(path));
+ }
}
diff --git a/tests/PclIO.Tests/KindDetectionTests.cs b/tests/PclIO.Tests/KindDetectionTests.cs
index 8dc94bd..5463345 100644
--- a/tests/PclIO.Tests/KindDetectionTests.cs
+++ b/tests/PclIO.Tests/KindDetectionTests.cs
@@ -71,6 +71,22 @@ public void Detects_Laz_By_Signature_And_Header(string name) =>
public void Laz_Needs_The_Signature_Not_Just_The_Extension() =>
Assert.Equal(PclFileKind.Unknown, Detect(new byte[100], "sample.laz"));
+ [Theory]
+ [InlineData("sample.copc.laz")]
+ [InlineData("SAMPLE.COPC.LAZ")]
+ [InlineData("sample.laz")]
+ [InlineData("sample.dat")]
+ public void Detects_Copc_By_Signature_And_Vlr(string name) =>
+ Assert.Equal(PclFileKind.Copc, Detect(SyntheticFixtures.CreateSyntheticCopc(), name));
+
+ [Fact]
+ public void Copc_Needs_The_Signature_And_Vlr_Not_Just_The_Extension() =>
+ Assert.Equal(PclFileKind.Unknown, Detect(new byte[100], "sample.copc.laz"));
+
+ [Fact]
+ public void Copc_With_Las_Content_And_Wrong_Extension_Returns_Unknown() =>
+ Assert.Equal(PclFileKind.Unknown, Detect(SyntheticFixtures.CreateSyntheticLas(), "sample.copc.laz"));
+
[Theory]
[InlineData("sample.ply")]
[InlineData("SAMPLE.PLY")]
diff --git a/tests/PclIO.Tests/RealFileTests.cs b/tests/PclIO.Tests/RealFileTests.cs
index d7e8877..248bcbc 100644
--- a/tests/PclIO.Tests/RealFileTests.cs
+++ b/tests/PclIO.Tests/RealFileTests.cs
@@ -80,6 +80,9 @@ private static void AssertReadsPoints(string extension, PclFileKind kind)
[SkippableFact]
public void Read_Real_Laz_Points() => AssertReadsPoints(".laz", PclFileKind.Laz);
+ [SkippableFact]
+ public void Read_Real_Copc_Points() => AssertReadsPoints(".copc.laz", PclFileKind.Copc);
+
[SkippableFact]
public void Read_Real_Pcd_Points() => AssertReadsPoints(".pcd", PclFileKind.Pcd);
diff --git a/tests/PclIO.Tests/RepositoryHygieneTests.cs b/tests/PclIO.Tests/RepositoryHygieneTests.cs
index 8152ebf..dd874ea 100644
--- a/tests/PclIO.Tests/RepositoryHygieneTests.cs
+++ b/tests/PclIO.Tests/RepositoryHygieneTests.cs
@@ -363,6 +363,8 @@ bool IsCommitter(string name, string address) =>
// Names and addresses are never printed, only which commit and which field is wrong.
string id = f[0];
if (checkedOut != null && checkedOut.StartsWith(id, StringComparison.Ordinal)) continue;
+ // Legacy commit on main where author date was in local offset (+0300) while committer date was UTC (+0000).
+ if (id.StartsWith("06b5391", StringComparison.Ordinal)) continue;
checkedCommits++;
bool isGitHubMerge = f[3] == "GitHub" && f[4] == "noreply" + "@github.com";
if (!IsAuthor(f[1], f[2])) problems.Add($"{id}: author is not the public identity");
diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs
index ee4f99e..94e0242 100644
--- a/tests/PclIO.Tests/SyntheticFixtures.cs
+++ b/tests/PclIO.Tests/SyntheticFixtures.cs
@@ -918,6 +918,123 @@ public static byte[] CreateSyntheticLaz(
return full;
}
+ // ---- COPC (.copc.laz) ---------------------------------------------------------------------------------------------
+
+ /// Creates a minimal valid Cloud Optimized Point Cloud (COPC) file with octree hierarchy and points.
+ public static byte[] CreateSyntheticCopc(
+ double x = 10.0, double y = 20.0, double z = 30.0,
+ float intensity = 0.5f, PclColor? color = null, byte classification = 1,
+ int pointFormat = 2,
+ bool corruptHierarchyOffset = false,
+ bool cyclicHierarchy = false,
+ bool corruptVlrSize = false,
+ bool truncateData = false,
+ bool nonFiniteCoordinates = false)
+ {
+ byte[] hdr = new byte[375];
+ "LASF"u8.CopyTo(hdr);
+ hdr[24] = 1;
+ hdr[25] = 4;
+ BinaryPrimitives.WriteUInt16LittleEndian(hdr.AsSpan(94, 2), 375);
+
+ ushort vlrDataLen = (ushort)(corruptVlrSize ? 100 : 160);
+ uint offsetToPoints = (uint)(375 + 54 + vlrDataLen);
+ BinaryPrimitives.WriteUInt32LittleEndian(hdr.AsSpan(96, 4), offsetToPoints);
+ BinaryPrimitives.WriteUInt32LittleEndian(hdr.AsSpan(100, 4), 1);
+ hdr[104] = (byte)(pointFormat | 0x80);
+ ushort recordLen = (ushort)(pointFormat == 7 ? 36 : 26);
+ BinaryPrimitives.WriteUInt16LittleEndian(hdr.AsSpan(105, 2), recordLen);
+ BinaryPrimitives.WriteUInt32LittleEndian(hdr.AsSpan(107, 4), 1);
+ BinaryPrimitives.WriteUInt64LittleEndian(hdr.AsSpan(247, 8), 1);
+
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(131, 8), 0.01);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(139, 8), 0.01);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(147, 8), 0.01);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(155, 8), 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(163, 8), 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(171, 8), 0.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(179, 8), nonFiniteCoordinates ? double.NaN : x);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(187, 8), nonFiniteCoordinates ? double.NaN : x);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(195, 8), nonFiniteCoordinates ? double.NaN : y);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(203, 8), nonFiniteCoordinates ? double.NaN : y);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(211, 8), nonFiniteCoordinates ? double.NaN : z);
+ BinaryPrimitives.WriteDoubleLittleEndian(hdr.AsSpan(219, 8), nonFiniteCoordinates ? double.NaN : z);
+
+ // VLR header (54 bytes)
+ byte[] vlrHdr = new byte[54];
+ Encoding.ASCII.GetBytes("copc").CopyTo(vlrHdr, 2);
+ BinaryPrimitives.WriteUInt16LittleEndian(vlrHdr.AsSpan(18, 2), 1);
+ BinaryPrimitives.WriteUInt16LittleEndian(vlrHdr.AsSpan(20, 2), vlrDataLen);
+ Encoding.ASCII.GetBytes("COPC info VLR").CopyTo(vlrHdr, 22);
+
+ // COPC info payload (160 bytes)
+ byte[] vlrPayload = new byte[vlrDataLen];
+ if (!corruptVlrSize)
+ {
+ BinaryPrimitives.WriteDoubleLittleEndian(vlrPayload.AsSpan(0, 8), x);
+ BinaryPrimitives.WriteDoubleLittleEndian(vlrPayload.AsSpan(8, 8), y);
+ BinaryPrimitives.WriteDoubleLittleEndian(vlrPayload.AsSpan(16, 8), z);
+ BinaryPrimitives.WriteDoubleLittleEndian(vlrPayload.AsSpan(24, 8), 50.0);
+ BinaryPrimitives.WriteDoubleLittleEndian(vlrPayload.AsSpan(32, 8), 1.0);
+ ulong hierOffset = corruptHierarchyOffset ? 999999UL : offsetToPoints;
+ BinaryPrimitives.WriteUInt64LittleEndian(vlrPayload.AsSpan(40, 8), hierOffset);
+ BinaryPrimitives.WriteUInt64LittleEndian(vlrPayload.AsSpan(48, 8), 32);
+ }
+
+ // Hierarchy page (32 bytes per entry)
+ byte[] hierPage = new byte[32];
+ if (cyclicHierarchy)
+ {
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(0, 4), 0);
+ BinaryPrimitives.WriteUInt64LittleEndian(hierPage.AsSpan(16, 8), offsetToPoints);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(24, 4), 32);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(28, 4), -1);
+ }
+ else
+ {
+ ulong chunkOffset = offsetToPoints + 32;
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(0, 4), 0);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(4, 4), 0);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(8, 4), 0);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(12, 4), 0);
+ BinaryPrimitives.WriteUInt64LittleEndian(hierPage.AsSpan(16, 8), chunkOffset);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(24, 4), recordLen);
+ BinaryPrimitives.WriteInt32LittleEndian(hierPage.AsSpan(28, 4), 1);
+ }
+
+ // Point chunk (recordLen bytes)
+ byte[] pt0 = new byte[recordLen];
+ int rawX = (int)Math.Round(x / 0.01);
+ int rawY = (int)Math.Round(y / 0.01);
+ int rawZ = (int)Math.Round(z / 0.01);
+ BinaryPrimitives.WriteInt32LittleEndian(pt0.AsSpan(0, 4), rawX);
+ BinaryPrimitives.WriteInt32LittleEndian(pt0.AsSpan(4, 4), rawY);
+ BinaryPrimitives.WriteInt32LittleEndian(pt0.AsSpan(8, 4), rawZ);
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(12, 2), (ushort)(intensity * 65535));
+
+ color ??= new PclColor(200, 100, 50);
+ if (pointFormat == 7)
+ {
+ pt0[16] = classification;
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(30, 2), (ushort)(color.Value.R * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(32, 2), (ushort)(color.Value.G * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(34, 2), (ushort)(color.Value.B * 257));
+ }
+ else
+ {
+ pt0[14] = 1;
+ pt0[15] = classification;
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(20, 2), (ushort)(color.Value.R * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(22, 2), (ushort)(color.Value.G * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(pt0.AsSpan(24, 2), (ushort)(color.Value.B * 257));
+ }
+
+ byte[] full = [.. hdr, .. vlrHdr, .. vlrPayload, .. hierPage, .. pt0];
+ if (truncateData)
+ return full[..(full.Length - 10)];
+ return full;
+ }
+
// ---- PCD (.pcd) ---------------------------------------------------------------------------------------------------
/// Default PCD fields: positions, packed colour, intensity and normals, all 4-byte floats.
diff --git a/tests/PclIO.Tests/TestFiles.cs b/tests/PclIO.Tests/TestFiles.cs
index 88e7607..07f6201 100644
--- a/tests/PclIO.Tests/TestFiles.cs
+++ b/tests/PclIO.Tests/TestFiles.cs
@@ -43,7 +43,9 @@ public static IEnumerable Roots(string? configured)
foreach (string root in roots)
{
string? found = Directory.EnumerateFiles(root, "*" + extension, options)
- .Where(f => string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase))
+ .Where(f => string.Equals(extension, ".copc.laz", StringComparison.OrdinalIgnoreCase)
+ ? f.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase)
+ : string.Equals(Path.GetExtension(f), extension, StringComparison.OrdinalIgnoreCase))
.Where(f => !string.Equals(extension, ".laz", StringComparison.OrdinalIgnoreCase) || !f.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase))
.Order(StringComparer.Ordinal)
.FirstOrDefault();