Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ The library targets .NET 8 and .NET 10. It is managed code with no dependencies
| Format | Extensions | Support level |
| --- | --- | --- |
| ASTM E57 | `.e57` | Points decoded for a defined subset: uncompressed bit-packed streams with single or double precision Cartesian coordinates or scaled-integer coordinates (raw value times scale plus offset), or spherical range, azimuth and elevation converted to Cartesian points, with 8-bit colour and 8-bit intensity, or colour with a wider Integer range from zero and intensity as a wider Integer, a Float or a scaled integer. Pose translation and rotation are applied. Only plain bit-packing is decoded: a scan whose codecs vector names another codec lists normally and fails when its points are read, and the message names it. Per-point validity flags skip invalid points and clear invalid channels when their streams hold one flag byte per record; other shapes are not interpreted. Images are not read, so a scan with them still lists and reads its points. Page checksums are verified. |
| ReCap scan | `.rcs` | Experimental. The header is read; point decoding covers the node layouts that are described in the code, which is the one of major version 3. A file of another version is listed with its header, but reading its points fails with a message that names the version. A further layout is described only when the files of that version may be used for the tests, so that its offsets can be verified. The channels of the points follow from the size of the payload of the nodes: colour and intensity when the records are long enough, and normals when the node holds the plane of them. |
| ReCap scan | `.rcs` | Experimental. The header is read; point decoding covers the node layouts that are described in the code, which is the one of major version 3. A file of another version is listed with its header, but reading its points fails with a message that names the version. A further layout is described only when the files of that version may be used for the tests, so that its offsets can be verified. The channels of the points follow from the size of the payload of the nodes: colour and intensity when the records are long enough, and normals when the node holds the plane of them. A node payload whose byte count is not a whole multiple of a known record size, as in BLK360 exports (container 3.2) whose records are variable-length, is rejected with a message that names the container version instead of being guessed. |
| ReCap project | `.rcp` | Lists the scans of the project manifest and opens the `.rcs` files it finds next to the project. The transform of a scan node places the scan in the project and is applied to its points unless `ApplyTransform` is false; when the manifest states no transform, the transform of the scan file is used. |
| Leica scan container | `.lgsx`, `.lgs` | Experimental. Points are decoded from the compressed point blocks: position, and colour, intensity and normals when the block has them. When the container assigns its points to its setups, there is one scan per setup, named after the setup, with the pose and the bounds of the setup when its record holds them; the pose is applied unless `ApplyTransform` is false. When the container does not assign its points, all points of the container form one scan and a warning says so. The point count is taken from the container when it states one; otherwise it is found by decoding the data, which is slow on large files. `PclReadOptions.Blocks` reads only the blocks of the scan in that file-order range (per scan, so a setup scan ranges over its own blocks); `PclReadOptions.MaxDegreeOfParallelism` above 1 decodes those blocks in parallel and still yields the points in file order with consecutive `Index` values. |
| FARO scan | `.fls`, or a FARO scan folder | Experimental. The scan grid and angles are read from the stored parameters and points are projected from the range grid; a file without them fails to open. The point count is the number of valid returns, which is counted on the first access; `FaroScan.GridSize` is the size of the scan grid. For a scan folder the layout of the samples is derived from the size of the data stream and the size of the grid, and the scale of the intensity from the values that are stored; when the sizes do not fit, the layout is assumed and a warning says so. |
| PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental. The manifest (scan names, ids, poses, counts) is read. Points come from the referenced `.bin` files, in either of two layouts: a table of named channels, or numbered sections with a property table and Snappy-compressed channels, which PclIO decodes itself. Colour, intensity and normals are reported only when the file has that channel; in the second layout positions, colours, intensities, normals (`Normals`, three float32 components per point) and the per-point flags (`FilterBits`, one byte per point) are read, while the grid indices stored beside them are not interpreted, so by default every stored point that passes the plausibility rule below is returned. With `PclReadOptions.ExcludeFilteredPoints` the points with a non-zero flag are not returned. A manifest with a scan position list takes the point count from the manifest, else from the data file; a manifest with a data object list takes it from the data file the object refers to, and every location that shares one file reports its full count, because the shares are not recorded. |
| PinPoint project | `.srf`, `.smf`, or a folder with `ScanProject.json` or `.smf`/`.srf` files | Experimental. The manifest (scan names, ids, poses, counts) is read. Points come from the referenced `.bin` files, in either of two layouts: a table of named channels, or numbered sections with a property table and Snappy-compressed channels, which PclIO decodes itself. Colour, intensity and normals are reported only when the file has that channel; in the second layout positions, colours, intensities, normals (`Normals`, three float32 components per point) and the per-point flags (`FilterBits`, one byte per point) are read, while the grid indices stored beside them are not interpreted, so by default every stored point that passes the plausibility rule below is returned. With `PclReadOptions.ExcludeFilteredPoints` the points with a non-zero flag are not returned. A manifest with a scan position list takes the point count from the manifest, else from the data file; a manifest with a data object list takes it from the data file the object refers to, and every location that shares one file reports its full count, because the shares are not recorded. A project shell whose data files are absent lists no scans, and a manifest whose referenced data files are missing reads no points; neither is a readable fixture. |
| EdgeWise | `.c3db`, `.c3ptx` | Experimental. A `.c3db` point database lists the scan clusters and a `.c3ptx` is one cluster file; the cluster files give positions only, as three 16-bit offsets from the cluster centre per point. The scale of the offsets is not stored in the files, so the reader assumes 32768 units = 0.128 m unless the caller states it with `PclReadOptions.EdgeWiseCoordinateScale`. |
| LAS | `.las` | Points decoded from versions 1.0 to 1.4 with point formats 0 to 10: XYZ with scale and offset, intensity, classification and RGB for the colour formats (2, 3, 5, 7, 8, 10). GPS time, return numbers, scan angles, point source ids, near infrared and waveform packet descriptors are not interpreted; extra bytes past a format's base size are skipped. The extended point counts of 1.4 are used when stated. Coordinate system records name an `EPSG:` code from a GeoTIFF key directory when it holds one, else the OGC WKT when one is stored. |
| 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. |
Expand Down
13 changes: 7 additions & 6 deletions src/PclIO/Formats/Recap/RcsScanDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ internal RcsScan(RcsScanDocument document, string filePath)
try
{
using var fs = File.OpenRead(_filePath);
var nodes = ReadNodeTable(fs, layout, out _);
var nodes = ReadNodeTable(fs, layout, _document.MinorVersion, out _);

bool colors = false, intensities = false, normals = false;
foreach (var node in nodes)
Expand All @@ -277,9 +277,9 @@ internal RcsScan(RcsScanDocument document, string filePath)

return (colors, intensities, normals);
}
catch (InvalidDataException)
catch (Exception e) when (e is InvalidDataException or NotSupportedException)
{
// A damaged node table leaves the channels unknown.
// A damaged node table or an undecoded payload leaves the channels unknown.
return (false, false, false);
}
}
Expand All @@ -304,7 +304,7 @@ public override IEnumerable<PclPoint> ReadPoints(PclReadOptions? options = null)
long yielded = 0;

using var fs = File.OpenRead(_filePath);
var nodes = ReadNodeTable(fs, layout, out long payloadStart);
var nodes = ReadNodeTable(fs, layout, _document.MinorVersion, out long payloadStart);

long curOffset = payloadStart;
byte[] chunkBuf = new byte[65536];
Expand Down Expand Up @@ -411,7 +411,7 @@ public override IEnumerable<PclPoint> ReadPoints(PclReadOptions? options = null)
}

// Reads and validates the node table; payloadStart is where the first node payload begins.
private static List<Node> ReadNodeTable(FileStream fs, RcsLayout layout, out long payloadStart)
private static List<Node> ReadNodeTable(FileStream fs, RcsLayout layout, uint minorVersion, out long payloadStart)
{
if (fs.Length < layout.NodeTableOffset + 8) throw FormatError.Truncated("RCS node table");

Expand Down Expand Up @@ -455,7 +455,8 @@ private static List<Node> ReadNodeTable(FileStream fs, RcsLayout layout, out lon
if (nbytes != (long)npts * PositionRecordSize &&
nbytes != (long)npts * PointRecordSize &&
nbytes != (long)npts * (PointRecordSize + NormalRecordSize))
throw FormatError.Unsupported("RCS node payload does not match a known point record layout.");
throw FormatError.Unsupported(
$"RCS container version {layout.MajorVersion}.{minorVersion}: node payload does not match a known point record layout.");
}

nodes.Add(new Node(new PclVector3(tMinX, tMinY, tMinZ), npts, nbytes));
Expand Down
65 changes: 50 additions & 15 deletions tests/PclIO.Tests/RealFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,63 @@
namespace PclIO.Tests;

/// <summary>Reads private scan files that are not part of the repository (see <see cref="TestFiles"/>). A test is skipped
/// when no file with the extension is available. The assertions are generic invariants only: nothing here depends on the
/// content, size or identifiers of any particular file.</summary>
/// when no file with the extension is available, or when none of the candidates is a readable fixture: a corpus can hold
/// project shells without data and variants the reader does not decode beside the readable files. The assertions are
/// generic invariants only: nothing here depends on the content, size or identifiers of any particular file.</summary>
public sealed class RealFileTests
{
private const int SampleSize = 100;

private static void AssertReadsPoints(string extension, PclFileKind kind)
{
string path = TestFiles.FindByExtension(extension);

Assert.Equal(kind, PclFile.DetectKind(path));

using var doc = PclFile.Open(path);
Assert.Equal(kind, doc.Kind);
Assert.True(doc.Scans.Count > 0, "the document lists at least one scan");
Assert.True(doc.FileSize > 0);

long totalPoints = doc.Scans.Sum(s => s.PointCount);
int expected = (int)Math.Min(SampleSize, totalPoints > 0 ? totalPoints : SampleSize);
var options = new PclReadOptions { MaxPoints = SampleSize };
var points = doc.ReadAllPoints(options).ToList();
var candidates = TestFiles.TryFindAllByExtension(extension, TestFiles.Roots());
foreach (string path in candidates)
{
if (PclFile.DetectKind(path) != kind) continue;

PclDocument doc;
try
{
doc = PclFile.Open(path);
}
catch (Exception e) when (e is InvalidDataException or NotSupportedException)
{
continue;
}

using (doc)
{
Assert.Equal(kind, doc.Kind);
// A shell without scan data lists no scans; a manifest whose data files are missing reads no points.
if (doc.Scans.Count == 0) continue;
Assert.True(doc.FileSize > 0);

long totalPoints = doc.Scans.Sum(s => s.PointCount);
int expected = (int)Math.Min(SampleSize, totalPoints > 0 ? totalPoints : SampleSize);
var options = new PclReadOptions { MaxPoints = SampleSize };
List<PclPoint> points;
try
{
points = doc.ReadAllPoints(options).ToList();
}
catch (Exception e) when (e is InvalidDataException or NotSupportedException)
{
continue;
}
if (points.Count == 0) continue;

AssertReadable(doc, points, expected, options);
return;
}
}

throw candidates.Count == 0
? TestFiles.Missing(extension)
: new SkipException($"No private '{extension}' fixture with readable points is available: the candidates hold no scans, hold no points, or use a layout the reader does not decode. Set {TestFiles.EnvironmentVariable} to a folder that holds private scan files, or create a test_files folder.");
}

private static void AssertReadable(PclDocument doc, List<PclPoint> points, int expected, PclReadOptions options)
{
// The requested number of points comes back, and every coordinate is a real number.
Assert.Equal(expected, points.Count);
Assert.All(points, p =>
Expand Down
19 changes: 19 additions & 0 deletions tests/PclIO.Tests/SkippableFactTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,23 @@ public void TheConfiguredFolderComesFirstAndOneThatDoesNotExistIsIgnored()
Assert.DoesNotContain(dir.Root, TestFiles.Roots(""));
Assert.DoesNotContain(dir.Root, TestFiles.Roots(null));
}

[Fact]
public void TemporaryAndScratchArtifactsBelowTheRootAreNeverFixtures()
{
using var dir = new TempDirectory();
dir.Write("Temp/aaa.e57", []);
dir.Write("appdata/Local/TMP/bbb.e57", []);
dir.Write("ccc.tmp.e57", []);
dir.Write("pc/ddd.e57", []);

// The Temp folders and the .tmp. infix sort before the real sample in ordinal order; none of them may win.
Assert.Equal(Path.Combine(dir.Root, "pc", "ddd.e57"), TestFiles.TryFindByExtension(".e57", [dir.Root]));
Assert.Equal([Path.Combine(dir.Root, "pc", "ddd.e57")], TestFiles.TryFindAllByExtension(".e57", [dir.Root]));

// A corpus the caller places under a temporary folder still works: only the part below the root is inspected.
using var nested = new TempDirectory();
nested.Write("real.e57", []);
Assert.Equal(nested.PathOf("real.e57"), TestFiles.TryFindByExtension(".e57", [nested.Root]));
}
}
42 changes: 34 additions & 8 deletions tests/PclIO.Tests/TestFiles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ namespace PclIO.Tests;
/// <summary>Where the tests find private scan files that are not part of the repository. The folder is named by the
/// environment variable PCLIO_TEST_FILES; when it is not set, a folder test_files in the repository root (or in an ancestor of
/// the test binary) is used. A fixture is found by its extension, anywhere up to three folder levels below the root, so no file
/// name is ever written into a test. A test that needs a file which is not there is reported as skipped with the reason,
/// never passed.</summary>
/// name is ever written into a test. Temporary and scratch artifacts below the root are never fixtures. A test that needs a
/// file which is not there is reported as skipped with the reason, never passed.</summary>
internal static class TestFiles
{
public const string EnvironmentVariable = "PCLIO_TEST_FILES";
Expand All @@ -30,7 +30,13 @@ public static IEnumerable<string> Roots(string? configured)
public static string? TryFindByExtension(string extension) => TryFindByExtension(extension, Roots());

/// <summary>The first file with this extension in the first of the given folders that holds one, or null.</summary>
public static string? TryFindByExtension(string extension, IEnumerable<string> roots)
public static string? TryFindByExtension(string extension, IEnumerable<string> roots) =>
TryFindAllByExtension(extension, roots).FirstOrDefault();

/// <summary>Every file with this extension, in ordinal path order, across the given folders in order. A caller that
/// needs a fixture the reader can actually read walks this list: a corpus can hold shells without data and variants
/// the reader does not decode beside the readable files.</summary>
public static IReadOnlyList<string> TryFindAllByExtension(string extension, IEnumerable<string> roots)
{
var options = new EnumerationOptions
{
Expand All @@ -40,21 +46,41 @@ public static IEnumerable<string> Roots(string? configured)
MatchCasing = MatchCasing.CaseInsensitive,
};

var found = new List<string>();
foreach (string root in roots)
{
string? found = Directory.EnumerateFiles(root, "*" + extension, options)
found.AddRange(Directory.EnumerateFiles(root, "*" + extension, options)
.Where(f => string.Equals(extension, ".copc.laz", StringComparison.OrdinalIgnoreCase)
? f.EndsWith(".copc.laz", StringComparison.OrdinalIgnoreCase)
: string.Equals(extension, "ept.json", StringComparison.OrdinalIgnoreCase)
? f.EndsWith("ept.json", 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();
if (found != null) return found;
.Where(f => !IsTemporaryArtifact(f, root))
.Order(StringComparer.Ordinal));
}

return found;
}

/// <summary>Temporary and scratch artifacts are never fixtures: a mirrored Temp folder holds truncated downloads and
/// crafted fuzz files that a reader is right to reject. Only the part of the path below the search root is inspected, so a
/// corpus the caller places under a temporary folder still works.</summary>
private static bool IsTemporaryArtifact(string path, string root)
{
if (Path.GetFileName(path).Contains(".tmp.", StringComparison.OrdinalIgnoreCase))
return true;

for (var directory = Path.GetDirectoryName(path);
directory != null && directory.Length > root.Length;
directory = Path.GetDirectoryName(directory))
{
string name = Path.GetFileName(directory);
if (name.Equals("temp", StringComparison.OrdinalIgnoreCase) || name.Equals("tmp", StringComparison.OrdinalIgnoreCase))
return true;
}

return null;
return false;
}

/// <summary>The path of a fixture with this extension, or a <see cref="SkipException"/> when none is available.</summary>
Expand Down
Loading