From 32e26ad8ee5afc0b3ee2584eddf8f3661bda9c4e Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Mon, 16 Nov 2026 10:00:00 +0000
Subject: [PATCH 1/2] Read PLY files with ASCII and binary vertices
---
CHANGELOG.md | 3 +
README.md | 5 +-
docs/getting-started.md | 4 +-
docs/public-api.md | 6 +-
src/PclIO.Cli/Program.cs | 1 +
src/PclIO/Formats/Ply/PlyDocument.cs | 586 ++++++++++++++++++++++++
src/PclIO/Internal/KindDetector.cs | 84 ++++
src/PclIO/PclFile.cs | 2 +
src/PclIO/PclFileKind.cs | 3 +
tests/PclIO.Tests/FormatTests.cs | 254 ++++++++++
tests/PclIO.Tests/KindDetectionTests.cs | 11 +
tests/PclIO.Tests/RealFileTests.cs | 3 +
tests/PclIO.Tests/SyntheticFixtures.cs | 175 +++++++
13 files changed, 1133 insertions(+), 4 deletions(-)
create mode 100644 src/PclIO/Formats/Ply/PlyDocument.cs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7da648f..0c5e569 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -65,6 +65,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- PCD files are read (`PclFileKind.Pcd`): ASCII, binary and binary compressed (LZF, decoded by a decoder of its own)
point data with the declared fields, organised and unorganised clouds, and the viewpoint as metadata. Points with
non-finite coordinates are not returned.
+- PLY files are read (`PclFileKind.Ply`): ASCII and binary little and big endian vertices with positions, 8-bit
+ colour, intensity and normals by conventional names; faces and other elements are ignored. Vertices with
+ non-finite coordinates are not returned.
- 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 ef154f8..aed1206 100644
--- a/README.md
+++ b/README.md
@@ -44,6 +44,7 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies
| 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. |
| PCD | `.pcd` | Points decoded from the 0.7 header in ASCII, binary and binary compressed (LZF) form: XYZ from x, y and z, colour from packed rgb or rgba, intensity, and normals from normal_x, normal_y and normal_z. Points with non-finite coordinates are not returned. The viewpoint is kept as metadata and not applied. |
+| PLY | `.ply` | Vertices decoded from ASCII and binary little and big endian files: XYZ from x, y and z, 8-bit colour from red, green and blue (with alpha when present), intensity, and normals from nx, ny and nz. Faces and other elements are ignored. Points with non-finite coordinates are not returned. |
### Format detection
@@ -53,7 +54,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`, which shares the signature and stays unknown. A PCD file is recognised by its header structure with any extension.
+ A LAS file is recognised by the `LASF` signature with any extension except `.laz`, which shares the signature and stays unknown. 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 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
@@ -102,6 +103,7 @@ These readers drop data without an error or a warning, so a scan can yield fewer
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.
- PCD: a point with a NaN or infinite coordinate is not returned.
+- PLY: a vertex with a NaN or infinite coordinate is not returned.
### Limits
A file that exceeds one of these limits, or whose declared sizes and counts do not fit the file, is rejected with
@@ -125,6 +127,7 @@ outside the file is fetched.
| EdgeWise | 1,048,576 characters per database line; 1,000,000 nodes. Patterns that parse a line have a time limit. |
| LAS | Header of at least 227 bytes (375 for 1.4); at most 4096 variable length records of at most 1 MiB each; point records at most 1 MiB. |
| PCD | 4096 header lines of at most 1 MiB each; at most 1024 fields with an element count of at most 65536; decompressed binary data at most 1 GiB. |
+| PLY | 4096 header lines of at most 1 MiB each; at most 1024 elements with at most 1024 properties each; vertex records at most 1 MiB. |
## Exporters
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 02ad521..2a01a68 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -89,11 +89,13 @@ reading), `NotSupportedException` (unrecognised format or unsupported feature) o
| 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. |
| PCD | `.pcd` | ASCII, binary and binary compressed (LZF) data; positions, colour, intensity and normals from the declared fields. |
+| PLY | `.ply` | ASCII and binary little and big endian; vertices with positions, 8-bit colour, intensity and normals by conventional names. Faces are ignored. |
A file is detected from its content, its extension or, for a folder, its layout. E57, ReCap scan and Leica files are recognised
by content, `.fls` needs an OLE2 compound file, `.rcp` a ZIP archive, `.srf` and `.smf` a JSON text file, `.las` the `LASF`
signature (a `.laz` file shares it and stays unknown), and `.c3db` and `.c3ptx`
-are decided by extension alone, without a content check. A `.pcd` file is recognised by its header structure. Anything else is `PclFileKind.Unknown`. The rules are in
+are decided by extension alone, without a content check. A `.pcd` file is recognised by its header structure,
+and a `.ply` file by its magic word and header structure. Anything else is `PclFileKind.Unknown`. The rules are in
[Public API](public-api.md#format-detection).
Anything a decoder does not support fails instead of being guessed, apart from the assumptions named in the README (the FARO folder
record layout, the EdgeWise position scale and the ReCap scan channel flags). The sizes and counts a reader accepts are limited; a
diff --git a/docs/public-api.md b/docs/public-api.md
index cfbcd61..959bbff 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` and `Pcd`. |
+| `PclFileKind` | `Unknown`, `E57`, `RecapProject`, `RecapScan`, `LeicaLgsx`, `LeicaLgs`, `FaroFls`, `PinPoint`, `EdgeWise`, `Las`, `Pcd` and `Ply`. |
| `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) and `ExcludeFilteredPoints` (default false: points the file marks as filtered are excluded; currently the `FilterBits` channel of the PinPoint sectioned layout). Negative `MaxPoints`, a negative magnitude limit, a negative block start or count, a non-positive or non-finite EdgeWise 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). |
@@ -34,6 +34,7 @@ is the argument, which may also be a file name.
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`, which shares the signature and stays unknown.
`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.
- `FaroFls` needs an OLE2 compound file with the extension `.fls`, `RecapProject` a ZIP archive with the extension `.rcp`, and
`PinPoint` a JSON text file with the extension `.smf` or `.srf`.
- The extensions `.c3db` and `.c3ptx` select `EdgeWise` without a content check, so a damaged file with one of these extensions is
@@ -71,6 +72,7 @@ drop points that fail a plausibility rule (see the README), so a scan can yield
| EdgeWise | A `.c3db` database node: the count the database declares. A `.c3ptx` file: computed by walking the cluster headers when the file is opened. |
| LAS | The header count (the extended 1.4 count when it states one). It is not checked against the point data until the points are read; a truncated read fails then. |
| PCD | WIDTH times HEIGHT, validated against POINTS when the file is opened. Points with non-finite coordinates are skipped, so a read can yield fewer points. |
+| PLY | The vertex count the header declares. It is not checked against the vertex data until the vertices are read; a truncated read fails then. Vertices with non-finite coordinates are skipped, so a read can yield fewer points. |
`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
@@ -80,7 +82,7 @@ no colour.
## Format documents
`E57Document`/`E57Scan`, `RcsScanDocument`/`RcsScan`, `RcpProjectDocument`/`RcpScan`, `LgsxDocument`/`LgsxScan`/`LgsxEntry`/`LgsxSetup`,
-`FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan` and `PcdDocument`/`PcdScan` are the readers behind
+`FaroFlsDocument`/`FaroScan`, `PinPointDocument`/`PinPointScan`, `EdgeWiseDocument`/`EdgeWiseScan`, `LasDocument`/`LasScan`, `PcdDocument`/`PcdScan` and `PlyDocument`/`PlyScan` 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.Cli/Program.cs b/src/PclIO.Cli/Program.cs
index 60f91ce..499e0a7 100644
--- a/src/PclIO.Cli/Program.cs
+++ b/src/PclIO.Cli/Program.cs
@@ -83,6 +83,7 @@ ReCap project a ZIP archive with the extension .rcp
EdgeWise the extension .c3db or .c3ptx, or a text or tree signature in another file
LAS by signature (.las)
PCD by header structure (.pcd)
+ PLY by header structure (.ply)
Output formats (--format, or the output extension; any other extension needs --format):
las ASPRS LAS 1.2, point data record format 2 (XYZ, intensity, RGB)
diff --git a/src/PclIO/Formats/Ply/PlyDocument.cs b/src/PclIO/Formats/Ply/PlyDocument.cs
new file mode 100644
index 0000000..35e7ed5
--- /dev/null
+++ b/src/PclIO/Formats/Ply/PlyDocument.cs
@@ -0,0 +1,586 @@
+using PclIO.Internal;
+
+namespace PclIO.Formats.Ply;
+
+/// Represents a Stanford polygon file with point cloud data (.ply).
+///
+///
+/// Supported: ASCII and binary little and big endian files whose header declares a vertex element; positions from
+/// the x, y and z properties, colour from red, green and blue (with alpha when present), intensity from an
+/// intensity property, and normals from nx, ny and nz, by those conventional names in any numeric type. Faces and
+/// all other elements are ignored. Points whose coordinates are not finite are not returned.
+///
+///
+/// Not read (reported with when the file is opened): files without a vertex
+/// element or without x, y and z properties, vertex elements with list properties, and files whose first vertex
+/// element is preceded by an element of unpredictable size.
+///
+///
+public sealed class PlyDocument : PclDocument
+{
+ // Bounds for data taken from an untrusted file.
+ private const int MaxHeaderLines = 4096;
+ private const int MaxLineLength = 1 << 20;
+ private const int MaxElements = 1024;
+ private const int MaxProperties = 1024;
+ private const int MaxVertexStride = 1 << 20;
+
+ ///
+ public override PclFileKind Kind => PclFileKind.Ply;
+
+ /// Version string from the format line.
+ public string Version { get; }
+
+ /// How the vertex data is stored: ascii, binary_little_endian or binary_big_endian.
+ public string Data { get; }
+
+ ///
+ public override IReadOnlyList Scans => _scans;
+ private readonly List _scans = [];
+
+ private PlyDocument(string path, long fileSize, string version, string data)
+ : base(path, fileSize)
+ {
+ Version = version;
+ Data = data;
+ _metadata["Format"] = "Stanford PLY";
+ _metadata["Version"] = version;
+ _metadata["Data"] = data;
+ }
+
+ /// Opens a PLY file and reads its header.
+ /// Path of the .ply file.
+ /// Currently unused; accepted for symmetry with the other readers.
+ /// The file does not exist.
+ /// The header is damaged or truncated, or declares sizes outside the file.
+ /// The file has no usable positions.
+ public static PlyDocument Open(string path, PclReadOptions? options = null)
+ {
+ var fi = new FileInfo(path);
+ if (!fi.Exists) throw new FileNotFoundException("PLY file not found.", path);
+
+ using var fs = File.OpenRead(path);
+ var header = ReadHeader(fs);
+
+ var vertex = header.Elements.FirstOrDefault(e => e.Name.Equals("vertex", StringComparison.Ordinal));
+ if (vertex == null) throw FormatError.Unsupported("PLY file has no vertex element.");
+
+ int x = Find(vertex, "x");
+ int y = Find(vertex, "y");
+ int z = Find(vertex, "z");
+ if (x < 0 || y < 0 || z < 0)
+ throw FormatError.Unsupported("PLY file has no x, y and z properties.");
+
+ if (vertex.Properties.Any(p => p.IsList))
+ throw FormatError.Unsupported("PLY vertex element has list properties.");
+
+ // Elements before the vertices are skipped; only fixed-size ones can be.
+ long vertexDataOffset = header.DataStart;
+ long vertexLineSkip = 0;
+ foreach (var element in header.Elements)
+ {
+ if (element == vertex) break;
+ if (element.Properties.Any(p => p.IsList))
+ throw FormatError.Unsupported($"PLY element '{element.Name}' before the vertices has list properties.");
+ vertexDataOffset += element.Count * (long)element.Stride;
+ vertexLineSkip += element.Count;
+ if (vertexDataOffset < 0) throw FormatError.Corrupted("PLY elements declare more bytes than can be counted.");
+ }
+
+ if (header.Data != PlyData.Ascii)
+ {
+ long need = vertex.Count * (long)vertex.Stride;
+ if (need > fs.Length - vertexDataOffset) throw FormatError.Truncated("vertex data");
+ }
+
+ var document = new PlyDocument(path, fs.Length, header.Version, header.Data switch
+ {
+ PlyData.Ascii => "ascii",
+ PlyData.LittleEndian => "binary_little_endian",
+ _ => "binary_big_endian",
+ });
+
+ string name = Path.GetFileNameWithoutExtension(path);
+ document._scans.Add(new PlyScan("0", name, vertex.Count, path, header, vertex, vertexDataOffset, vertexLineSkip));
+ return document;
+ }
+
+ private static int Find(PlyElement element, string name)
+ {
+ for (int i = 0; i < element.Properties.Length; i++)
+ if (element.Properties[i].Name.Equals(name, StringComparison.Ordinal)) return i;
+ return -1;
+ }
+
+ /// How the vertex data is stored.
+ internal enum PlyData
+ {
+ Ascii,
+ LittleEndian,
+ BigEndian,
+ }
+
+ /// One property: its name, size, kind, signedness, list shape and byte offset in a record.
+ internal sealed record PlyProperty(string Name, int Size, bool IsFloat, bool IsSigned, bool IsList, int Offset);
+
+ /// One element: its name, record count, properties and record stride.
+ internal sealed record PlyElement(string Name, long Count, PlyProperty[] Properties, int Stride);
+
+ /// The parsed header: everything a read needs.
+ internal sealed record PlyHeader(string Version, PlyData Data, PlyElement[] Elements, long DataStart);
+
+ // Reads the ASCII header up to end_header: ply first, then the format line, then elements, properties
+ // and comments in any order. Returns the header and the offset where the data starts.
+ private static PlyHeader ReadHeader(FileStream fs)
+ {
+ PlyData? data = null;
+ var elements = new List();
+ PlyElementBuilder? current = null;
+ int lines = 0;
+
+ string first = ReadHeaderLine(fs);
+ if (!first.Equals("ply", StringComparison.Ordinal)) throw FormatError.Corrupted("not a PLY file, signature mismatch.");
+
+ while (true)
+ {
+ if (++lines > MaxHeaderLines) throw FormatError.Corrupted("PLY header has too many lines.");
+ string line = ReadHeaderLine(fs);
+ if (line.Length == 0 || line.StartsWith("comment", StringComparison.Ordinal)) continue;
+ if (line.StartsWith("obj_info", StringComparison.Ordinal)) continue;
+
+ if (line.Equals("end_header", StringComparison.Ordinal)) break;
+
+ if (line.StartsWith("format ", StringComparison.Ordinal))
+ {
+ if (data != null) throw FormatError.Corrupted("PLY header names the format twice.");
+ string[] parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length != 3) throw FormatError.Corrupted("PLY format line needs a value and a version.");
+ if (!parts[2].Equals("1.0", StringComparison.Ordinal))
+ throw FormatError.Unsupported($"PLY version {parts[2]} is not supported; version 1.0 is read.");
+ data = parts[1] switch
+ {
+ "ascii" => PlyData.Ascii,
+ "binary_little_endian" => PlyData.LittleEndian,
+ "binary_big_endian" => PlyData.BigEndian,
+ _ => throw FormatError.Corrupted($"PLY data type '{parts[1]}' is not ascii or binary."),
+ };
+
+ continue;
+ }
+
+ if (line.StartsWith("element ", StringComparison.Ordinal))
+ {
+ if (data == null) throw FormatError.Corrupted("PLY element comes before the format line.");
+ string[] parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length != 3) throw FormatError.Corrupted("PLY element line needs a name and a count.");
+ if (elements.Count >= MaxElements) throw FormatError.Corrupted("PLY header declares too many elements.");
+ if (!long.TryParse(parts[2], System.Globalization.NumberStyles.None,
+ System.Globalization.CultureInfo.InvariantCulture, out long count) || count < 0)
+ throw FormatError.Corrupted($"PLY element count '{parts[2]}' is not a count.");
+ current = new PlyElementBuilder(parts[1]);
+ elements.Add(current.ToElement(count));
+ continue;
+ }
+
+ if (line.StartsWith("property ", StringComparison.Ordinal))
+ {
+ if (current == null) throw FormatError.Corrupted("PLY property comes before any element.");
+ current.Add(ParseProperty(line));
+ elements[^1] = current.ToElement(elements[^1].Count);
+ continue;
+ }
+
+ throw FormatError.Corrupted($"PLY header line '{line}' is not recognised.");
+ }
+
+ if (data == null) throw FormatError.Corrupted("PLY header misses the format line.");
+ return new PlyHeader("1.0", data.Value, [.. elements], fs.Position);
+ }
+
+ // One property line: a scalar type and name, or a list with count and item types.
+ private static (string Name, int Size, bool IsFloat, bool IsSigned, bool IsList) ParseProperty(string line)
+ {
+ string[] parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ if (parts is ["property", "list", _, _, _])
+ {
+ int countSize = ScalarSize(parts[2]);
+ int itemSize = ScalarSize(parts[3]);
+ if (countSize == 0 || itemSize == 0)
+ throw FormatError.Corrupted($"PLY list property '{line}' has an unknown type.");
+ return (parts[4], itemSize, false, false, true);
+ }
+
+ if (parts is ["property", _, _])
+ {
+ int size = ScalarSize(parts[1]);
+ if (size == 0) throw FormatError.Corrupted($"PLY property type '{parts[1]}' is not supported.");
+ return (parts[2], size, IsFloatType(parts[1]), IsSignedType(parts[1]), false);
+ }
+
+ throw FormatError.Corrupted($"PLY property line '{line}' is not recognised.");
+ }
+
+ // The byte size of a scalar type, with the common fixed-width aliases; 0 for anything else.
+ private static int ScalarSize(string type) => type switch
+ {
+ "char" or "int8" => 1,
+ "uchar" or "uint8" => 1,
+ "short" or "int16" => 2,
+ "ushort" or "uint16" => 2,
+ "int" or "int32" => 4,
+ "uint" or "uint32" => 4,
+ "float" or "float32" => 4,
+ "double" or "float64" => 8,
+ _ => 0,
+ };
+
+ private static bool IsFloatType(string type) => type is "float" or "float32" or "double" or "float64";
+
+ private static bool IsSignedType(string type) => type is "char" or "int8" or "short" or "int16" or "int" or "int32";
+
+ private sealed class PlyElementBuilder(string name)
+ {
+ private readonly List<(string Name, int Size, bool IsFloat, bool IsSigned, bool IsList)> _properties = [];
+
+ public void Add((string Name, int Size, bool IsFloat, bool IsSigned, bool IsList) property)
+ {
+ if (_properties.Count >= MaxProperties) throw FormatError.Corrupted("PLY element declares too many properties.");
+ if (_properties.Any(p => p.Name.Equals(property.Name, StringComparison.Ordinal)))
+ throw FormatError.Corrupted($"PLY property '{property.Name}' is declared twice.");
+ _properties.Add(property);
+ }
+
+ public PlyElement ToElement(long count)
+ {
+ var properties = new PlyProperty[_properties.Count];
+ int offset = 0;
+ for (int i = 0; i < _properties.Count; i++)
+ {
+ var (propName, size, isFloat, isSigned, isList) = _properties[i];
+ // List properties have no fixed stride; the reader rejects them where it cannot skip them.
+ properties[i] = new PlyProperty(propName, size, isFloat, isSigned, isList, offset);
+ if (!isList)
+ {
+ offset += size;
+ if (offset < 0 || offset > MaxVertexStride)
+ throw FormatError.Corrupted("PLY properties declare more bytes than can be counted.");
+ }
+ }
+
+ return new PlyElement(name, count, properties, offset);
+ }
+ }
+
+ // One ASCII header line without its line break; the file position ends after the break.
+ private static string ReadHeaderLine(FileStream fs)
+ {
+ var bytes = new List(128);
+ while (true)
+ {
+ int b = fs.ReadByte();
+ if (b < 0) throw FormatError.Truncated("PLY header");
+ if (b == '\n') break;
+ if (b != '\r')
+ {
+ if (b > 127) throw FormatError.Corrupted("PLY header is not ASCII.");
+ bytes.Add((byte)b);
+ if (bytes.Count > MaxLineLength) throw FormatError.Corrupted("PLY header line is too long.");
+ }
+ }
+
+ return System.Text.Encoding.ASCII.GetString(bytes.ToArray());
+ }
+}
+
+/// The single scan of a PLY file: its vertex element.
+public sealed class PlyScan : PclScan
+{
+ // Binary records stream in chunks of at most this many bytes; memory use does not depend on the point count.
+ private const int MaxChunkBytes = 64 * 1024;
+
+ ///
+ public override string Id { get; }
+
+ ///
+ public override string Name { get; }
+
+ /// Number of vertices the header declares.
+ public override long PointCount { get; }
+
+ /// Path of the PLY file.
+ public string FilePath { get; }
+
+ ///
+ public override bool HasColors { get; }
+
+ ///
+ public override bool HasIntensities { get; }
+
+ ///
+ public override bool HasNormals { get; }
+
+ private readonly PlyDocument.PlyHeader _header;
+ private readonly PlyDocument.PlyElement _vertex;
+ private readonly long _vertexDataOffset;
+ private readonly long _vertexLineSkip;
+ private readonly int _x;
+ private readonly int _y;
+ private readonly int _z;
+ private readonly int _red;
+ private readonly int _green;
+ private readonly int _blue;
+ private readonly int _alpha;
+ private readonly int _intensity;
+ private readonly int _normalX;
+ private readonly int _normalY;
+ private readonly int _normalZ;
+
+ internal PlyScan(string id, string name, long pointCount, string filePath,
+ PlyDocument.PlyHeader header, PlyDocument.PlyElement vertex, long vertexDataOffset, long vertexLineSkip)
+ {
+ Id = id;
+ Name = name;
+ PointCount = pointCount;
+ FilePath = filePath;
+ _header = header;
+ _vertex = vertex;
+ _vertexDataOffset = vertexDataOffset;
+ _vertexLineSkip = vertexLineSkip;
+ _x = Find("x");
+ _y = Find("y");
+ _z = Find("z");
+ _red = Find("red");
+ _green = Find("green");
+ _blue = Find("blue");
+ _alpha = Find("alpha");
+ _intensity = Find("intensity");
+ _normalX = Find("nx");
+ _normalY = Find("ny");
+ _normalZ = Find("nz");
+
+ var props = vertex.Properties;
+ bool ByteChannel(int i) => i >= 0 && props[i].Size == 1 && !props[i].IsFloat;
+ HasColors = _red >= 0 && _green >= 0 && _blue >= 0 && ByteChannel(_red) && ByteChannel(_green) && ByteChannel(_blue) &&
+ (_alpha < 0 || ByteChannel(_alpha));
+ HasIntensities = _intensity >= 0;
+ HasNormals = _normalX >= 0 && _normalY >= 0 && _normalZ >= 0;
+ }
+
+ private int Find(string name)
+ {
+ for (int i = 0; i < _vertex.Properties.Length; i++)
+ if (_vertex.Properties[i].Name.Equals(name, StringComparison.Ordinal)) return i;
+ return -1;
+ }
+
+ /// Streams the vertices of the file; faces and other elements are ignored.
+ ///
+ /// Vertices whose coordinates are not finite are not returned.
+ /// and are ignored:
+ /// the vertex stream has no independent blocks to select or decode in parallel.
+ ///
+ /// The vertex data is truncated or malformed.
+ public override IEnumerable ReadPoints(PclReadOptions? options = null)
+ {
+ options ??= PclReadOptions.Default;
+ long targetCount = options.MaxPoints ?? PointCount;
+ if (targetCount <= 0) yield break;
+ targetCount = Math.Min(targetCount, PointCount);
+ int step = Math.Max(1, options.SubsampleStep);
+
+ using var fs = File.OpenRead(FilePath);
+ long yielded = 0;
+
+ if (_header.Data == PlyDocument.PlyData.Ascii)
+ {
+ fs.Position = _header.DataStart;
+ using var reader = new StreamReader(fs, System.Text.Encoding.ASCII, detectEncodingFromByteOrderMarks: false,
+ bufferSize: 65536, leaveOpen: true);
+ for (long s = 0; s < _vertexLineSkip; s++)
+ if (reader.ReadLine() == null) throw FormatError.Truncated("vertex data");
+ for (long i = 0; i < targetCount; i++)
+ {
+ string? line = reader.ReadLine();
+ if (line == null) throw FormatError.Truncated("vertex data");
+ if ((i % step) != 0) continue;
+
+ var point = ParseAsciiVertex(line, out bool valid);
+ if (!valid) continue;
+ point = point with { Index = (ulong)yielded };
+ if (options.ApplyTransform)
+ point = point with { Position = Transform.TransformPoint(point.Position) };
+
+ yield return point;
+ yielded++;
+ if (yielded >= targetCount) yield break;
+ }
+
+ yield break;
+ }
+
+ bool littleEndian = _header.Data == PlyDocument.PlyData.LittleEndian;
+ int stride = _vertex.Stride;
+ int recordsPerChunk = Math.Max(1, MaxChunkBytes / Math.Max(1, stride));
+ byte[] chunk = new byte[(long)recordsPerChunk * stride];
+ var record = new byte[stride];
+
+ for (long start = 0; start < targetCount; start += recordsPerChunk)
+ {
+ int want = (int)Math.Min(recordsPerChunk, targetCount - start);
+ long byteOffset = _vertexDataOffset + (start * (long)stride);
+ if (byteOffset < 0 || want > (fs.Length - byteOffset) / stride)
+ throw FormatError.Truncated("vertex data");
+
+ fs.Position = byteOffset;
+ fs.ReadExactly(chunk, 0, want * stride);
+
+ for (int i = 0; i < want; i++)
+ {
+ if ((start + i) % step != 0) continue;
+ Array.Copy(chunk, i * stride, record, 0, stride);
+
+ var point = ParseBinaryVertex(record, littleEndian, out bool valid);
+ if (!valid) continue;
+ point = point with { Index = (ulong)yielded };
+ if (options.ApplyTransform)
+ point = point with { Position = Transform.TransformPoint(point.Position) };
+
+ yield return point;
+ yielded++;
+ if (yielded >= targetCount) yield break;
+ }
+ }
+ }
+
+ // Parses one ASCII vertex line with exactly one value per property.
+ private PclPoint ParseAsciiVertex(string line, out bool valid)
+ {
+ string[] tokens = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ if (tokens.Length != _vertex.Properties.Length)
+ throw FormatError.Corrupted("PLY vertex line holds the wrong number of values.");
+
+ double[] numbers = new double[tokens.Length];
+ for (int i = 0; i < tokens.Length; i++)
+ numbers[i] = ParseNumber(tokens[i], _vertex.Properties[i]);
+
+ return AssemblePoint(numbers, out valid);
+ }
+
+ private static double ParseNumber(string token, PlyDocument.PlyProperty property)
+ {
+ if (property.IsFloat)
+ {
+ if (token.Equals("inf", StringComparison.OrdinalIgnoreCase)) return double.PositiveInfinity;
+ if (token.Equals("+inf", StringComparison.OrdinalIgnoreCase)) return double.PositiveInfinity;
+ if (token.Equals("-inf", StringComparison.OrdinalIgnoreCase)) return double.NegativeInfinity;
+ if (!double.TryParse(token, System.Globalization.NumberStyles.Float,
+ System.Globalization.CultureInfo.InvariantCulture, out double value))
+ throw FormatError.Corrupted($"PLY value '{token}' is not a number.");
+ return value;
+ }
+
+ if (!long.TryParse(token, System.Globalization.NumberStyles.Integer,
+ System.Globalization.CultureInfo.InvariantCulture, out long integer))
+ throw FormatError.Corrupted($"PLY value '{token}' is not an integer.");
+
+ (long min, long max) = IntegerRange(property);
+ if (integer < min || integer > max) throw FormatError.Corrupted($"PLY value '{token}' does not fit its property.");
+ return integer;
+ }
+
+ // The value range of an integer property from its width and signedness.
+ private static (long Min, long Max) IntegerRange(PlyDocument.PlyProperty property) =>
+ (property.Size, property.IsSigned) switch
+ {
+ (1, true) => (sbyte.MinValue, sbyte.MaxValue),
+ (2, true) => (short.MinValue, short.MaxValue),
+ (4, true) => (int.MinValue, int.MaxValue),
+ (8, true) => (long.MinValue, long.MaxValue),
+ (1, false) => (byte.MinValue, byte.MaxValue),
+ (2, false) => (ushort.MinValue, ushort.MaxValue),
+ (4, false) => (uint.MinValue, uint.MaxValue),
+ _ => (long.MinValue, long.MaxValue),
+ };
+
+ // Reads one binary vertex: every property in declared order.
+ private PclPoint ParseBinaryVertex(byte[] record, bool littleEndian, out bool valid)
+ {
+ double[] numbers = new double[_vertex.Properties.Length];
+ for (int i = 0; i < _vertex.Properties.Length; i++)
+ {
+ var property = _vertex.Properties[i];
+ numbers[i] = ReadValue(record.AsSpan(property.Offset, property.Size), property, littleEndian);
+ }
+
+ return AssemblePoint(numbers, out valid);
+ }
+
+ private static double ReadValue(ReadOnlySpan bytes, PlyDocument.PlyProperty property, bool littleEndian)
+ {
+ if (property.IsFloat)
+ {
+ if (property.Size == 4)
+ return littleEndian ? Bytes.ReadSingleLE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadSingleBigEndian(bytes);
+ return littleEndian ? Bytes.ReadDoubleLE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadDoubleBigEndian(bytes);
+ }
+
+ if (property.IsSigned)
+ {
+ return property.Size switch
+ {
+ 1 => (sbyte)bytes[0],
+ 2 => littleEndian ? Bytes.ReadInt16LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadInt16BigEndian(bytes),
+ 4 => littleEndian ? Bytes.ReadInt32LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(bytes),
+ _ => littleEndian ? Bytes.ReadInt64LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadInt64BigEndian(bytes),
+ };
+ }
+
+ return property.Size switch
+ {
+ 1 => bytes[0],
+ 2 => littleEndian ? Bytes.ReadUInt16LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(bytes),
+ 4 => littleEndian ? Bytes.ReadUInt32LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(bytes),
+ _ => (double)(littleEndian ? Bytes.ReadUInt64LE(bytes) : System.Buffers.Binary.BinaryPrimitives.ReadUInt64BigEndian(bytes)),
+ };
+ }
+
+ // Builds a point from the flat values: x, y and z decide validity, the rest fills the channels.
+ private PclPoint AssemblePoint(double[] numbers, out bool valid)
+ {
+ valid = true;
+ double x = numbers[_x];
+ double y = numbers[_y];
+ double z = numbers[_z];
+ if (!double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z))
+ {
+ valid = false;
+ return default;
+ }
+
+ PclColor? color = null;
+ if (HasColors)
+ {
+ byte alpha = _alpha >= 0 ? ClampByte(numbers[_alpha]) : (byte)255;
+ color = new PclColor(ClampByte(numbers[_red]), ClampByte(numbers[_green]), ClampByte(numbers[_blue]), alpha);
+ }
+
+ float? intensity = _intensity >= 0 ? (float)numbers[_intensity] : null;
+
+ PclVector3? normal = null;
+ if (HasNormals)
+ {
+ var n = new PclVector3(numbers[_normalX], numbers[_normalY], numbers[_normalZ]);
+ if (double.IsFinite(n.X) && double.IsFinite(n.Y) && double.IsFinite(n.Z)) normal = n;
+ }
+
+ return new PclPoint(new PclVector3(x, y, z), Color: color, Intensity: intensity, Normal: normal);
+ }
+
+ private static byte ClampByte(double value)
+ {
+ if (double.IsNaN(value)) return 0;
+ if (value <= 0) return 0;
+ if (value >= 255) return 255;
+ return (byte)Math.Round(value);
+ }
+}
diff --git a/src/PclIO/Internal/KindDetector.cs b/src/PclIO/Internal/KindDetector.cs
index 1185afc..53691f5 100644
--- a/src/PclIO/Internal/KindDetector.cs
+++ b/src/PclIO/Internal/KindDetector.cs
@@ -101,6 +101,10 @@ public static PclFileKind Detect(Stream stream, string? extension = null)
if (IsPcdHeader(stream, origin))
return PclFileKind.Pcd;
+ // PLY files start with the magic word; the header structure decides, like PCD.
+ if (IsPlyHeader(stream, origin))
+ return PclFileKind.Ply;
+
return PclFileKind.Unknown;
}
@@ -177,4 +181,84 @@ private static bool IsPcdHeader(Stream stream, long origin)
stream.Position = origin;
}
}
+
+ // True when the stream starts with a PLY header: the magic word, a format line and end_header in order.
+ // At most the first 256 KiB are inspected; the position is restored.
+ private static bool IsPlyHeader(Stream stream, long origin)
+ {
+ const int maxProbeBytes = 256 * 1024;
+
+ long length = stream.CanSeek ? stream.Length : long.MaxValue;
+ int toRead = (int)Math.Min(maxProbeBytes, Math.Max(0, length - origin));
+ if (toRead < 7) return false;
+
+ byte[] buffer = new byte[toRead];
+ stream.Position = origin;
+ try
+ {
+ int got = 0;
+ while (got < toRead)
+ {
+ int n = stream.Read(buffer, got, toRead - got);
+ if (n == 0) break;
+ got += n;
+ }
+
+ int position = 0;
+ int lines = 0;
+ bool first = true;
+ bool format = false;
+ while (position < got)
+ {
+ int end = Array.IndexOf(buffer, (byte)'\n', position, got - position);
+ if (end < 0) return false;
+ int lineLength = end - position;
+ if (lineLength > 0 && buffer[end - 1] == (byte)'\r') lineLength--;
+ if (lineLength > 4096) return false;
+
+ string line = System.Text.Encoding.ASCII.GetString(buffer, position, lineLength);
+ if (first)
+ {
+ if (!line.Equals("ply", StringComparison.Ordinal)) return false;
+ first = false;
+ }
+ else if (line.Length != 0 && !line.StartsWith("comment", StringComparison.Ordinal) &&
+ !line.StartsWith("obj_info", StringComparison.Ordinal))
+ {
+ if (!format)
+ {
+ if (!IsPlyFormatLine(line)) return false;
+ format = true;
+ }
+ else if (line.Equals("end_header", StringComparison.Ordinal))
+ {
+ return true;
+ }
+ else if (!IsPlyHeaderLine(line))
+ {
+ return false;
+ }
+ }
+
+ position = end + 1;
+ if (++lines > 4096) return false;
+ }
+
+ return false;
+ }
+ finally
+ {
+ stream.Position = origin;
+ }
+ }
+
+ private static bool IsPlyFormatLine(string line)
+ {
+ string[] parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
+ return parts is ["format", "ascii" or "binary_little_endian" or "binary_big_endian", _];
+ }
+
+ private static bool IsPlyHeaderLine(string line) =>
+ line.StartsWith("element ", StringComparison.Ordinal) ||
+ line.StartsWith("property ", StringComparison.Ordinal);
}
diff --git a/src/PclIO/PclFile.cs b/src/PclIO/PclFile.cs
index 7db4065..168ac4f 100644
--- a/src/PclIO/PclFile.cs
+++ b/src/PclIO/PclFile.cs
@@ -5,6 +5,7 @@
using PclIO.Formats.Leica;
using PclIO.Formats.Pcd;
using PclIO.Formats.PinPoint;
+using PclIO.Formats.Ply;
using PclIO.Formats.Recap;
using PclIO.Internal;
@@ -52,6 +53,7 @@ public static PclDocument Open(string path, PclReadOptions? options = null)
PclFileKind.EdgeWise => EdgeWiseDocument.Open(path, options),
PclFileKind.Las => LasDocument.Open(path, options),
PclFileKind.Pcd => PcdDocument.Open(path, options),
+ PclFileKind.Ply => PlyDocument.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 3b8f2ce..12ecfc8 100644
--- a/src/PclIO/PclFileKind.cs
+++ b/src/PclIO/PclFileKind.cs
@@ -35,4 +35,7 @@ public enum PclFileKind
/// Point Cloud Library point cloud file (.pcd).
Pcd = 10,
+
+ /// Stanford polygon file with point cloud data (.ply).
+ Ply = 11,
}
diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs
index ca41f76..a4ef320 100644
--- a/tests/PclIO.Tests/FormatTests.cs
+++ b/tests/PclIO.Tests/FormatTests.cs
@@ -2896,4 +2896,258 @@ public void Pcd_Detection_Accepts_A_Long_Comment_Line()
Assert.Equal(PclFileKind.Pcd, PclFile.DetectKind(dir.Write("sample.pcd", bytes)));
}
+
+ // ---- PLY ----------------------------------------------------------------------------------------------------
+
+ [Fact]
+ public void PclFile_Opens_Ply_With_Count_Channels_And_Metadata()
+ {
+ using var dir = new TempDirectory();
+ using var doc = PclFile.Open(dir.Write("sample.ply", SyntheticFixtures.CreateSyntheticPly()));
+
+ Assert.Equal(PclFileKind.Ply, doc.Kind);
+ var scan = Assert.Single(doc.Scans);
+ Assert.Equal("0", scan.Id);
+ Assert.Equal("sample", scan.Name);
+ Assert.Equal(3, scan.PointCount);
+ Assert.Equal(3, doc.TotalPointCount);
+ Assert.True(scan.HasColors);
+ Assert.True(scan.HasIntensities);
+ Assert.True(scan.HasNormals);
+ Assert.True(scan.Bounds.IsEmpty);
+ Assert.Equal("1.0", ((PlyDocument)doc).Version);
+ Assert.Equal("ascii", ((PlyDocument)doc).Data);
+ Assert.Equal("Stanford PLY", doc.Metadata["Format"]);
+ Assert.Null(doc.CoordinateSystem);
+ Assert.Empty(doc.Warnings);
+ }
+
+ [Theory]
+ [InlineData("ascii")]
+ [InlineData("binary_little_endian")]
+ [InlineData("binary_big_endian")]
+ public void Ply_Round_Trip_Positions_Intensity_Colour_And_Normals(string format)
+ {
+ using var dir = new TempDirectory();
+ using var doc = PlyDocument.Open(dir.Write("sample.ply", SyntheticFixtures.CreateSyntheticPly(format: format)));
+
+ var points = doc.Scans[0].ReadPoints(NoTransform).ToList();
+
+ Assert.Equal(3, points.Count);
+ Assert.Equal([0UL, 1UL, 2UL], points.Select(p => p.Index));
+ AssertNear(new PclVector3(1, 2, 3), points[0].Position);
+ AssertNear(new PclVector3(-4.5, 5.25, 6.125), points[1].Position);
+ AssertNear(new PclVector3(7, 8, 9), points[2].Position);
+ Assert.Equal(0.25f, points[0].Intensity);
+ Assert.Equal(0.5f, points[1].Intensity);
+ Assert.Equal(0f, points[2].Intensity);
+ Assert.Equal(new PclColor(10, 20, 30), points[0].Color);
+ Assert.Equal(new PclColor(255, 255, 255), points[1].Color);
+ Assert.Equal(new PclColor(255, 255, 255), points[2].Color);
+ Assert.Equal(new PclVector3(0, 0, 1), points[0].Normal);
+ Assert.Equal(new PclVector3(0, 0, 0), points[1].Normal);
+ Assert.All(points, p => Assert.Null(p.Classification));
+ }
+
+ [Fact]
+ public void Ply_Faces_Are_Ignored()
+ {
+ foreach (string format in new[] { "ascii", "binary_little_endian", "binary_big_endian" })
+ {
+ using var dir = new TempDirectory();
+ using var doc = PlyDocument.Open(dir.Write("sample.ply",
+ SyntheticFixtures.CreateSyntheticPly(format: format, withFaces: true)));
+
+ Assert.Equal(3, doc.Scans[0].ReadPoints(NoTransform).Count());
+ }
+ }
+
+ [Fact]
+ public void Ply_Points_Without_Finite_Coordinates_Are_Not_Returned()
+ {
+ var points = new[]
+ {
+ new PlySamplePoint(1, 2, 3),
+ new PlySamplePoint(double.NaN, 0, 0),
+ new PlySamplePoint(4, 5, 6),
+ };
+ foreach (string format in new[] { "ascii", "binary_little_endian", "binary_big_endian" })
+ {
+ using var dir = new TempDirectory();
+ using var doc = PlyDocument.Open(dir.Write("sample.ply",
+ SyntheticFixtures.CreateSyntheticPly(points, format: format)));
+
+ var read = doc.Scans[0].ReadPoints(NoTransform).ToList();
+ Assert.Equal(2, read.Count);
+ Assert.Equal([0UL, 1UL], read.Select(p => p.Index));
+ }
+ }
+
+ [Fact]
+ public void Ply_Honours_Limit_And_Step_And_Ignores_Blocks_And_Parallelism()
+ {
+ var points = Enumerable.Range(0, 8).Select(i => new PlySamplePoint(i, 0, 0)).ToList();
+ using var dir = new TempDirectory();
+ using var doc = PlyDocument.Open(dir.Write("sample.ply", SyntheticFixtures.CreateSyntheticPly(points)));
+ var scan = doc.Scans[0];
+
+ Assert.Equal(3, scan.ReadPoints(new PclReadOptions { MaxPoints = 3 }).Count());
+ Assert.Equal(4, scan.ReadPoints(new PclReadOptions { SubsampleStep = 2 }).Count());
+ Assert.Empty(scan.ReadPoints(new PclReadOptions { MaxPoints = 0 }));
+
+ var ranged = scan.ReadPoints(new PclReadOptions
+ {
+ Blocks = new BlockRange { StartBlock = 1, BlockCount = 1 },
+ MaxDegreeOfParallelism = 4,
+ }).ToList();
+ Assert.Equal(8, ranged.Count);
+ }
+
+ [Fact]
+ public void Ply_Without_X_Y_Or_Z_Is_Not_Read()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly(
+ properties: [("y", "float"), ("z", "float"), ("red", "uchar")]);
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", bytes)));
+ }
+
+ [Fact]
+ public void Ply_Without_A_Vertex_Element_Is_Not_Read()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreatePlyFile(
+ [
+ "ply",
+ "format ascii 1.0",
+ "element face 1",
+ "property list uchar int vertex_indices",
+ "end_header",
+ "3 0 1 2",
+ ], []);
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", bytes)));
+ }
+
+ [Fact]
+ public void Ply_Unsupported_Version_Is_Rejected()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly();
+ byte[] patched = System.Text.Encoding.ASCII.GetBytes(
+ System.Text.Encoding.ASCII.GetString(bytes).Replace("format ascii 1.0", "format ascii 2.0"));
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", patched)));
+ }
+
+ [Fact]
+ public void Ply_Elements_Before_Vertices_Are_Skipped()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreatePlyFile(
+ [
+ "ply",
+ "format ascii 1.0",
+ "comment Skipped elements come first",
+ "element range_grid 2",
+ "property int min",
+ "property int max",
+ "element vertex 1",
+ "property float x",
+ "property float y",
+ "property float z",
+ "end_header",
+ "0 10",
+ "20 30",
+ "1 2 3",
+ ], []);
+
+ var point = Assert.Single(PlyDocument.Open(dir.Write("sample.ply", bytes)).Scans[0].ReadPoints(NoTransform));
+ AssertNear(new PclVector3(1, 2, 3), point.Position);
+ }
+
+ [Fact]
+ public void Ply_Variable_Element_Before_Vertices_Is_Not_Read()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreatePlyFile(
+ [
+ "ply",
+ "format ascii 1.0",
+ "element face 1",
+ "property list uchar int vertex_indices",
+ "element vertex 1",
+ "property float x",
+ "property float y",
+ "property float z",
+ "end_header",
+ "3 0 1 2",
+ "1 2 3",
+ ], []);
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", bytes)));
+ }
+
+ [Theory]
+ [InlineData("ascii")]
+ [InlineData("binary_little_endian")]
+ [InlineData("binary_big_endian")]
+ public void Ply_Truncated_Vertex_Data_Is_Rejected_When_Read(string format)
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly(format: format);
+ // Binary layouts state their size up front, so a short file is rejected at open.
+ if (format != "ascii")
+ {
+ Assert.Throws(() => PlyDocument.Open(dir.Write("cut.ply", bytes[..(bytes.Length - 5)])));
+ return;
+ }
+
+ using var doc = PlyDocument.Open(dir.Write("cut.ply", bytes[..(bytes.Length - 5)]));
+ Assert.Equal(3, doc.Scans[0].PointCount);
+ Assert.Throws(() => doc.Scans[0].ReadPoints().ToList());
+ }
+
+ [Fact]
+ public void Ply_Vertex_Line_With_The_Wrong_Value_Count_Is_Rejected()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreatePlyFile(
+ [
+ "ply",
+ "format ascii 1.0",
+ "element vertex 1",
+ "property float x",
+ "property float y",
+ "property float z",
+ "end_header",
+ "1 2",
+ ], []);
+ using var doc = PlyDocument.Open(dir.Write("sample.ply", bytes));
+
+ Assert.Throws(() => doc.Scans[0].ReadPoints().ToList());
+ }
+
+ [Fact]
+ public void Ply_Unknown_Property_Type_Is_Rejected()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly(
+ properties: [("x", "float"), ("y", "float"), ("z", "float"), ("label", "string")]);
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", bytes)));
+ }
+
+ [Fact]
+ public void Ply_Wrong_Signature_Is_Rejected()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly();
+ bytes[0] = (byte)'X';
+
+ Assert.Throws(() => PlyDocument.Open(dir.Write("sample.ply", bytes)));
+ Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(dir.Write("other.ply", bytes)));
+ Assert.Throws(() => PclFile.Open(dir.PathOf("other.ply")));
+ }
}
diff --git a/tests/PclIO.Tests/KindDetectionTests.cs b/tests/PclIO.Tests/KindDetectionTests.cs
index 163d537..140574c 100644
--- a/tests/PclIO.Tests/KindDetectionTests.cs
+++ b/tests/PclIO.Tests/KindDetectionTests.cs
@@ -60,6 +60,17 @@ public void Las_Needs_The_Signature_Not_Just_The_Extension() =>
public void A_Laz_File_Is_Not_Detected_As_Las() =>
Assert.Equal(PclFileKind.Unknown, Detect(SyntheticFixtures.CreateSyntheticLas(), "sample.laz"));
+ [Theory]
+ [InlineData("sample.ply")]
+ [InlineData("SAMPLE.PLY")]
+ [InlineData("sample.dat")]
+ public void Detects_Ply_By_Header_Structure(string name) =>
+ Assert.Equal(PclFileKind.Ply, Detect(SyntheticFixtures.CreateSyntheticPly(), name));
+
+ [Fact]
+ public void Ply_Needs_The_Header_Structure_Not_Just_The_Extension() =>
+ Assert.Equal(PclFileKind.Unknown, Detect("just some text"u8.ToArray(), "sample.ply"));
+
[Theory]
[InlineData("sample.pcd")]
[InlineData("SAMPLE.PCD")]
diff --git a/tests/PclIO.Tests/RealFileTests.cs b/tests/PclIO.Tests/RealFileTests.cs
index 09cc8e5..e9a7d67 100644
--- a/tests/PclIO.Tests/RealFileTests.cs
+++ b/tests/PclIO.Tests/RealFileTests.cs
@@ -78,6 +78,9 @@ private static void AssertReadsPoints(string extension, PclFileKind kind)
[SkippableFact]
public void Read_Real_Pcd_Points() => AssertReadsPoints(".pcd", PclFileKind.Pcd);
+ [SkippableFact]
+ public void Read_Real_Ply_Points() => AssertReadsPoints(".ply", PclFileKind.Ply);
+
[SkippableFact]
public void Export_Real_File_To_Las_Matches_The_Requested_Count()
{
diff --git a/tests/PclIO.Tests/SyntheticFixtures.cs b/tests/PclIO.Tests/SyntheticFixtures.cs
index 50f2c21..c141275 100644
--- a/tests/PclIO.Tests/SyntheticFixtures.cs
+++ b/tests/PclIO.Tests/SyntheticFixtures.cs
@@ -20,6 +20,9 @@ namespace PclIO.Tests;
/// One point of a synthetic PCD file: position, intensity, colour and normal.
public readonly record struct PcdSamplePoint(double X, double Y, double Z, float? Intensity = null, PclColor? Color = null, PclVector3? Normal = null);
+/// One vertex of a synthetic PLY file: position, colour, intensity and normal.
+public readonly record struct PlySamplePoint(double X, double Y, double Z, PclColor? Color = null, float? Intensity = null, PclVector3? Normal = null, byte Alpha = 255);
+
/// Generates small synthetic scan files for the tests. Every layout is written from what the readers implement;
/// no byte of any of them comes from a real scan.
internal static class SyntheticFixtures
@@ -1028,4 +1031,176 @@ void FlushLiterals(int from, int count)
FlushLiterals(i - literals, literals);
return [.. output];
}
+
+ // ---- PLY (.ply) ---------------------------------------------------------------------------------------------------
+
+ /// Default PLY vertex properties: positions, 8-bit colour, intensity and normals.
+ public static IReadOnlyList<(string Name, string Type)> DefaultPlyProperties =>
+ [
+ ("x", "float"), ("y", "float"), ("z", "float"),
+ ("red", "uchar"), ("green", "uchar"), ("blue", "uchar"),
+ ("intensity", "float"), ("nx", "float"), ("ny", "float"), ("nz", "float"),
+ ];
+
+ /// Default PLY vertices: three points with mixed channels.
+ public static IReadOnlyList DefaultPlyPoints =>
+ [
+ new(1, 2, 3, new PclColor(10, 20, 30), 0.25f, new PclVector3(0, 0, 1)),
+ new(-4.5, 5.25, 6.125, null, 0.5f),
+ new(7, 8, 9, new PclColor(255, 255, 255)),
+ ];
+
+ /// A synthetic PLY file with one vertex element.
+ /// Vertices to store.
+ /// Vertex properties; null uses .
+ /// Storage: ascii, binary_little_endian or binary_big_endian.
+ /// True appends a face element with one triangle after the vertices.
+ public static byte[] CreateSyntheticPly(IReadOnlyList? points = null,
+ IReadOnlyList<(string Name, string Type)>? properties = null, string format = "ascii", bool withFaces = false)
+ {
+ points ??= DefaultPlyPoints;
+ properties ??= DefaultPlyProperties;
+
+ var header = new List
+ {
+ "ply",
+ $"format {format} 1.0",
+ "comment Created by PclIO tests",
+ $"element vertex {points.Count}",
+ };
+ header.AddRange(properties.Select(p => $"property {p.Type} {p.Name}"));
+ if (withFaces)
+ {
+ header.Add("element face 1");
+ header.Add("property list uchar int vertex_indices");
+ }
+
+ header.Add("end_header");
+
+ byte[] body = format switch
+ {
+ "ascii" => PlyAsciiBody(points, properties),
+ "binary_little_endian" => PlyBinaryBody(points, properties, littleEndian: true, withFaces),
+ "binary_big_endian" => PlyBinaryBody(points, properties, littleEndian: false, withFaces),
+ _ => throw new ArgumentException($"Unknown PLY format '{format}'.", nameof(format)),
+ };
+
+ byte[] headerBytes = System.Text.Encoding.ASCII.GetBytes(string.Join('\n', header) + "\n");
+ return [.. headerBytes, .. body];
+ }
+
+ /// A PLY file from raw header lines and a body.
+ public static byte[] CreatePlyFile(IEnumerable headerLines, byte[] body)
+ {
+ byte[] headerBytes = System.Text.Encoding.ASCII.GetBytes(string.Join('\n', headerLines) + "\n");
+ return [.. headerBytes, .. body];
+ }
+
+ private static int PlyTypeSize(string type) => type switch
+ {
+ "char" or "int8" or "uchar" or "uint8" => 1,
+ "short" or "int16" or "ushort" or "uint16" => 2,
+ "int" or "int32" or "uint" or "uint32" or "float" or "float32" => 4,
+ "double" or "float64" => 8,
+ _ => 0,
+ };
+
+ private static byte[] PlyAsciiBody(IReadOnlyList points,
+ IReadOnlyList<(string Name, string Type)> properties)
+ {
+ var sb = new StringBuilder();
+ foreach (var p in points)
+ {
+ sb.Append(string.Join(' ', properties.Select(prop => PlyAsciiValue(p, prop))));
+ sb.Append('\n');
+ }
+
+ return System.Text.Encoding.ASCII.GetBytes(sb.ToString());
+ }
+
+ private static string PlyAsciiValue(PlySamplePoint p, (string Name, string Type) property)
+ {
+ double value = PlyPropertyValue(p, property.Name);
+ if (property.Type is "float" or "float32" or "double" or "float64")
+ return double.IsNaN(value) ? "nan" : value.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
+ return ((long)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ }
+
+ private static byte[] PlyBinaryBody(IReadOnlyList points,
+ IReadOnlyList<(string Name, string Type)> properties, bool littleEndian, bool withFaces)
+ {
+ using var ms = new MemoryStream();
+ foreach (var p in points)
+ foreach (var prop in properties)
+ ms.Write(PlyPropertyBytes(p, prop, littleEndian));
+
+ if (withFaces)
+ {
+ // One triangle over the first three vertices.
+ ms.WriteByte(3);
+ foreach (int index in new[] { 0, 1, 2 })
+ {
+ byte[] indexBytes = new byte[4];
+ if (littleEndian)
+ BinaryPrimitives.WriteInt32LittleEndian(indexBytes, index);
+ else
+ BinaryPrimitives.WriteInt32BigEndian(indexBytes, index);
+ ms.Write(indexBytes);
+ }
+ }
+
+ return ms.ToArray();
+ }
+
+ private static double PlyPropertyValue(PlySamplePoint p, string name) => name switch
+ {
+ "x" => p.X,
+ "y" => p.Y,
+ "z" => p.Z,
+ "red" => p.Color?.R ?? 255,
+ "green" => p.Color?.G ?? 255,
+ "blue" => p.Color?.B ?? 255,
+ "alpha" => p.Alpha,
+ "intensity" => p.Intensity ?? 0,
+ "nx" => p.Normal?.X ?? 0,
+ "ny" => p.Normal?.Y ?? 0,
+ "nz" => p.Normal?.Z ?? 0,
+ _ => 0,
+ };
+
+ private static byte[] PlyPropertyBytes(PlySamplePoint p, (string Name, string Type) property, bool littleEndian)
+ {
+ double value = PlyPropertyValue(p, property.Name);
+ int size = PlyTypeSize(property.Type);
+ byte[] bytes = new byte[size];
+ bool signed = property.Type is "char" or "int8" or "short" or "int16" or "int" or "int32";
+ if (property.Type is "float" or "float32")
+ {
+ if (littleEndian)
+ BinaryPrimitives.WriteSingleLittleEndian(bytes, (float)value);
+ else
+ BinaryPrimitives.WriteSingleBigEndian(bytes, (float)value);
+ }
+ else if (property.Type is "double" or "float64")
+ {
+ if (littleEndian)
+ BinaryPrimitives.WriteDoubleLittleEndian(bytes, value);
+ else
+ BinaryPrimitives.WriteDoubleBigEndian(bytes, value);
+ }
+ else if (signed)
+ {
+ long signedValue = (long)value;
+ for (int i = 0; i < size; i++)
+ bytes[littleEndian ? i : size - 1 - i] = (byte)(signedValue >> (8 * i));
+ }
+ else
+ {
+ ulong unsigned = (ulong)(long)value;
+ for (int i = 0; i < size; i++)
+ bytes[littleEndian ? i : size - 1 - i] = (byte)(unsigned >> (8 * i));
+ }
+
+ return bytes;
+ }
}
From 2162851d5e2999aee2310cdb20adddad3111ae15 Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Tue, 17 Nov 2026 14:05:37 +0000
Subject: [PATCH 2/2] Harden the PLY reader: checked element skips and a
reported colour drop
---
README.md | 4 +-
src/PclIO/Formats/Ply/PlyDocument.cs | 54 +++++++++++++++---
tests/PclIO.Tests/FormatTests.cs | 82 ++++++++++++++++++++++++++++
3 files changed, 129 insertions(+), 11 deletions(-)
diff --git a/README.md b/README.md
index aed1206..f4bfb13 100644
--- a/README.md
+++ b/README.md
@@ -102,8 +102,8 @@ These readers drop data without an error or a warning, so a scan can yield fewer
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.
-- PCD: a point with a NaN or infinite coordinate is not returned.
-- PLY: a vertex with a NaN or infinite coordinate is not returned.
+- PCD: a point with a NaN or infinite coordinate is not returned; a colour, intensity or normal field whose shape the reader does not convert stays unread, so the points come without that channel.
+- PLY: a vertex with a NaN or infinite coordinate is not returned; colour that is not stored as 8-bit integers is left unread, with a warning.
### Limits
A file that exceeds one of these limits, or whose declared sizes and counts do not fit the file, is rejected with
diff --git a/src/PclIO/Formats/Ply/PlyDocument.cs b/src/PclIO/Formats/Ply/PlyDocument.cs
index 35e7ed5..4a780b4 100644
--- a/src/PclIO/Formats/Ply/PlyDocument.cs
+++ b/src/PclIO/Formats/Ply/PlyDocument.cs
@@ -6,9 +6,10 @@ namespace PclIO.Formats.Ply;
///
///
/// Supported: ASCII and binary little and big endian files whose header declares a vertex element; positions from
-/// the x, y and z properties, colour from red, green and blue (with alpha when present), intensity from an
-/// intensity property, and normals from nx, ny and nz, by those conventional names in any numeric type. Faces and
-/// all other elements are ignored. Points whose coordinates are not finite are not returned.
+/// the x, y and z properties, intensity from an intensity property, and normals from nx, ny and nz, by those
+/// conventional names in any numeric type. Colour is read from red, green and blue (with alpha when present)
+/// only when they are 8-bit integers; a wider or float colour is left unread with a warning. Faces and all other
+/// elements are ignored. Points whose coordinates are not finite are not returned.
///
///
/// Not read (reported with when the file is opened): files without a vertex
@@ -82,14 +83,34 @@ public static PlyDocument Open(string path, PclReadOptions? options = null)
if (element == vertex) break;
if (element.Properties.Any(p => p.IsList))
throw FormatError.Unsupported($"PLY element '{element.Name}' before the vertices has list properties.");
- vertexDataOffset += element.Count * (long)element.Stride;
- vertexLineSkip += element.Count;
- if (vertexDataOffset < 0) throw FormatError.Corrupted("PLY elements declare more bytes than can be counted.");
+ try
+ {
+ checked
+ {
+ vertexDataOffset += element.Count * (long)element.Stride;
+ vertexLineSkip += element.Count;
+ }
+ }
+ catch (OverflowException)
+ {
+ throw FormatError.Corrupted("PLY elements declare more bytes than can be counted.");
+ }
+ if (vertexDataOffset < 0 || vertexLineSkip < 0)
+ throw FormatError.Corrupted("PLY elements declare more bytes than can be counted.");
}
if (header.Data != PlyData.Ascii)
{
- long need = vertex.Count * (long)vertex.Stride;
+ if (vertexDataOffset > fs.Length) throw FormatError.Truncated("vertex data");
+ long need;
+ try
+ {
+ checked { need = vertex.Count * (long)vertex.Stride; }
+ }
+ catch (OverflowException)
+ {
+ throw FormatError.Corrupted("PLY vertices declare more bytes than can be counted.");
+ }
if (need > fs.Length - vertexDataOffset) throw FormatError.Truncated("vertex data");
}
@@ -101,10 +122,19 @@ public static PlyDocument Open(string path, PclReadOptions? options = null)
});
string name = Path.GetFileNameWithoutExtension(path);
- document._scans.Add(new PlyScan("0", name, vertex.Count, path, header, vertex, vertexDataOffset, vertexLineSkip));
+ document._scans.Add(new PlyScan("0", name, vertex.Count, path, header, vertex, vertexDataOffset, vertexLineSkip, document));
return document;
}
+ /// Adds a warning to the document, once per distinct message.
+ internal void AddWarning(string message)
+ {
+ lock (_warnings)
+ {
+ if (!_warnings.Contains(message, StringComparer.Ordinal)) _warnings.Add(message);
+ }
+ }
+
private static int Find(PlyElement element, string name)
{
for (int i = 0; i < element.Properties.Length; i++)
@@ -336,7 +366,8 @@ public sealed class PlyScan : PclScan
private readonly int _normalZ;
internal PlyScan(string id, string name, long pointCount, string filePath,
- PlyDocument.PlyHeader header, PlyDocument.PlyElement vertex, long vertexDataOffset, long vertexLineSkip)
+ PlyDocument.PlyHeader header, PlyDocument.PlyElement vertex, long vertexDataOffset, long vertexLineSkip,
+ PlyDocument? document = null)
{
Id = id;
Name = name;
@@ -364,6 +395,11 @@ internal PlyScan(string id, string name, long pointCount, string filePath,
(_alpha < 0 || ByteChannel(_alpha));
HasIntensities = _intensity >= 0;
HasNormals = _normalX >= 0 && _normalY >= 0 && _normalZ >= 0;
+
+ // Colour is read only from 8-bit integer channels; a wider or float colour is left unread, and the drop
+ // is reported so it is not silent.
+ if ((_red >= 0 || _green >= 0 || _blue >= 0) && !HasColors)
+ document?.AddWarning("PLY colour is not stored as 8-bit integers; colour is not read.");
}
private int Find(string name)
diff --git a/tests/PclIO.Tests/FormatTests.cs b/tests/PclIO.Tests/FormatTests.cs
index a4ef320..5ea2137 100644
--- a/tests/PclIO.Tests/FormatTests.cs
+++ b/tests/PclIO.Tests/FormatTests.cs
@@ -6,6 +6,7 @@
using PclIO.Formats.Leica;
using PclIO.Formats.Pcd;
using PclIO.Formats.PinPoint;
+using PclIO.Formats.Ply;
using PclIO.Formats.Recap;
using Xunit;
@@ -3150,4 +3151,85 @@ public void Ply_Wrong_Signature_Is_Rejected()
Assert.Equal(PclFileKind.Unknown, PclFile.DetectKind(dir.Write("other.ply", bytes)));
Assert.Throws(() => PclFile.Open(dir.PathOf("other.ply")));
}
+
+ [Theory]
+ [InlineData("binary_little_endian", true)]
+ [InlineData("binary_big_endian", false)]
+ public void Ply_Binary_Elements_Before_Vertices_Are_Skipped(string format, bool littleEndian)
+ {
+ // A fixed-size camera element precedes the vertices; its bytes are skipped, not read as points.
+ using var dir = new TempDirectory();
+ var header = new[]
+ {
+ "ply", $"format {format} 1.0", "element camera 1", "property double value",
+ "element vertex 1", "property float x", "property float y", "property float z", "end_header",
+ };
+ byte[] body = new byte[20];
+ Span cam = body.AsSpan(0, 8);
+ Span vx = body.AsSpan(8, 4), vy = body.AsSpan(12, 4), vz = body.AsSpan(16, 4);
+ if (littleEndian)
+ {
+ System.Buffers.Binary.BinaryPrimitives.WriteDoubleLittleEndian(cam, 12345.6789);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(vx, 1f);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(vy, 2f);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleLittleEndian(vz, 3f);
+ }
+ else
+ {
+ System.Buffers.Binary.BinaryPrimitives.WriteDoubleBigEndian(cam, 12345.6789);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleBigEndian(vx, 1f);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleBigEndian(vy, 2f);
+ System.Buffers.Binary.BinaryPrimitives.WriteSingleBigEndian(vz, 3f);
+ }
+ using var doc = PlyDocument.Open(dir.Write("sample.ply", SyntheticFixtures.CreatePlyFile(header, body)));
+
+ AssertNear(new PclVector3(1, 2, 3), Assert.Single(doc.Scans[0].ReadPoints(NoTransform)).Position);
+ }
+
+ [Fact]
+ public void Ply_Huge_Preceding_Element_Count_Is_Rejected_At_Open()
+ {
+ // count * stride wraps past zero unchecked; the checked product rejects the file at open instead of
+ // reading the camera bytes as vertices.
+ using var dir = new TempDirectory();
+ var header = new[]
+ {
+ "ply", "format binary_little_endian 1.0", "element camera 2305843009213693952", "property double value",
+ "element vertex 1", "property float x", "property float y", "property float z", "end_header",
+ };
+ byte[] body = new byte[20];
+ Assert.Throws(() =>
+ PlyDocument.Open(dir.Write("sample.ply", SyntheticFixtures.CreatePlyFile(header, body))));
+ }
+
+ [Fact]
+ public void Ply_Ascii_Preceding_Element_Counts_That_Wrap_Are_Rejected()
+ {
+ // Two preceding counts sum past long.MaxValue; the wrapped line skip would read the wrong lines.
+ using var dir = new TempDirectory();
+ var header = new[]
+ {
+ "ply", "format ascii 1.0",
+ "element camera 9223372036854775807", "property float x", "property float y", "property float z",
+ "element edge 1", "property float x", "property float y", "property float z",
+ "element vertex 1", "property float x", "property float y", "property float z", "end_header",
+ };
+ Assert.Throws(() =>
+ PlyDocument.Open(dir.Write("sample.ply", SyntheticFixtures.CreatePlyFile(header, "1 2 3\n"u8.ToArray()))));
+ }
+
+ [Fact]
+ public void Ply_Float_Colour_Is_Left_Unread_With_A_Warning()
+ {
+ using var dir = new TempDirectory();
+ byte[] bytes = SyntheticFixtures.CreateSyntheticPly(
+ properties: [("x", "float"), ("y", "float"), ("z", "float"), ("red", "float"), ("green", "float"), ("blue", "float")]);
+ using var doc = PlyDocument.Open(dir.Write("sample.ply", bytes));
+
+ var scan = Assert.Single(doc.Scans);
+ Assert.False(scan.HasColors);
+ Assert.Equal(3, scan.ReadPoints(NoTransform).Count());
+ Assert.All(scan.ReadPoints(NoTransform), p => Assert.Null(p.Color));
+ Assert.Contains(doc.Warnings, w => w.Contains("colour is not stored as 8-bit integers", StringComparison.Ordinal));
+ }
}