From e95660a1982faa2b2c25094641848a0ed3bb4930 Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Mon, 16 Nov 2026 04:18:39 +0000
Subject: [PATCH 1/2] Write LAS 1.4 with point formats 6 to 8, scale, offset
and coordinate system
---
CHANGELOG.md | 3 +
README.md | 6 +-
docs/getting-started.md | 2 +-
docs/public-api.md | 2 +-
src/PclIO/Export/PclLasExporter.cs | 223 ++++++++++++++++++-----
src/PclIO/Export/PclLasOptions.cs | 68 +++++++
tests/PclIO.Tests/ExportTests.cs | 214 ++++++++++++++++++++++
tests/PclIO.Tests/OptionsAndPathTests.cs | 29 +++
8 files changed, 496 insertions(+), 51 deletions(-)
create mode 100644 src/PclIO/Export/PclLasOptions.cs
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b248d17..b578be2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -51,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
prototype limit is the packet header bound of 65535 fields.
- The EdgeWise cluster position scale is now `PclReadOptions.EdgeWiseCoordinateScale`, so the caller states it; the
default keeps the long-standing assumption (32768 units = 0.128 m).
+- The LAS exporter writes 1.4 with point formats 6 to 8 (`PclLasOptions` selects version, format, scale, offset and an
+ optional GeoTIFF coordinate system record for an `EPSG:NNNN` source); 1.2 with point format 2 stays the default and is
+ byte-identical to before.
## [0.1.0] - 2026-11-15
diff --git a/README.md b/README.md
index 78c9e66..977c99e 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ PclIO is a .NET library and command line tool that reads point cloud files from
- Detects the format of a file or folder from its content, extension or layout (`PclFile.DetectKind`).
- Opens a file as a `PclDocument` with its scans, bounds, transforms, metadata and warnings, and streams the points (`ReadAllPoints`, `PclScan.ReadPoints`) with a point limit, a subsampling step and an optional scan transform.
-- Exports to ASPRS LAS 1.2 (point format 2), ASCII XYZ, ASCII PTS and JSON.
+- Exports to ASPRS LAS 1.2 (point format 2) and 1.4 (point formats 6 to 8), ASCII XYZ, ASCII PTS and JSON.
- Ships the command line tool `pclio` with `info`, `scans`, `points` and `export`.
## Install
@@ -125,7 +125,7 @@ outside the file is fetched.
| Output | Class | Notes |
| --- | --- | --- |
-| LAS 1.2, point format 2 | `PclLasExporter` | Position, intensity, classification, RGB. Fixed 1 mm scale. |
+| LAS 1.2, point format 2
LAS 1.4, point formats 6 to 8 | `PclLasExporter` (`PclLasOptions` selects version, format, scale, offset and coordinate system record) | Position, intensity, classification, RGB (formats 2 and 7/8; format 8 adds a zero near infrared). 1 mm scale and offset from the data by default. An `EPSG:NNNN` coordinate system of the source is written as a GeoTIFF record only when asked. |
| XYZ | `PclXyzExporter` | `X Y Z R G B` when the point has a colour, else `X Y Z I` when it has an intensity, else `X Y Z`. |
| PTS | `PclPtsExporter` | A line with the point count, then `X Y Z Intensity R G B` per point. |
| JSON | `PclJsonExporter` | Metadata and scans; sample points only when a point limit above zero is given. |
@@ -203,7 +203,7 @@ See the [public API](docs/public-api.md) for the supported surface and [dependen
- Readers limit the sizes and counts that a file declares; the numbers are listed under Limits. A file that exceeds a limit is rejected, with the exceptions described there. Some readers drop points that fail a plausibility rule; see Data filters.
- `SubsampleStep` is applied inside each format's internal blocks, so the spacing is approximate. `MaxPoints` limits one read call.
- A scan transform is scale and translation, or a 4x4 matrix when the format gives one. Rotation values of a `PclTransform` are stored for information and are not applied by `TransformPoint`.
-- LAS and PTS export read the source twice (the header needs the count), so the source must be re-enumerable; memory does not depend on the number of points. A point without intensity is written with full intensity and a point without colour as white, because these formats have no "missing" value. LAS stores coordinates with a 1 mm scale, so the extent of each axis must not exceed about 2147 km.
+- LAS and PTS export read the source twice (the header needs the count), so the source must be re-enumerable; memory does not depend on the number of points. A point without intensity is written with full intensity and a point without colour as white, because these formats have no "missing" value. LAS stores coordinates with the configured scale (1 mm by default), so the extent of each axis must fit 32-bit integers at that scale; the default offset is the minimum of the data.
- Normals are read where a format has them, but no exporter writes them.
- There is no support for writing or modifying scan files.
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 9ecad39..6613526 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -105,7 +105,7 @@ file that exceeds a limit is rejected with `InvalidDataException`, with the exce
and counts are listed in the repository README.
- `SubsampleStep` is applied inside each format's internal blocks, so the spacing is approximate; `MaxPoints` limits one read call.
- LAS and PTS export read the source twice; memory does not depend on the number of points. A point without intensity is written with full
- intensity and a point without colour as white. LAS uses a 1 mm scale, so the extent of each axis must not exceed about 2147 km.
+ intensity and a point without colour as white. LAS uses a 1 mm scale by default, so the extent of each axis must fit 32-bit integers at the configured scale.
- Normals are read where a format has them but no exporter writes them.
- Rotation values of a `PclTransform` are stored for information and are not applied by `TransformPoint`.
diff --git a/docs/public-api.md b/docs/public-api.md
index a1676a8..d034f9b 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -96,7 +96,7 @@ is empty, rooted, contains invalid characters or resolves outside the folder is
| Type | Use |
|---|---|
-| `PclLasExporter` | `Export(doc, stream, options)` writes ASPRS LAS 1.2, point format 2, with a 1 mm scale. Returns the number of points written. |
+| `PclLasExporter` / `PclLasOptions` / `LasVersion` | `Export(doc, stream, options, lasOptions)` writes ASPRS LAS 1.2 (point format 2) or 1.4 (point formats 6 to 8), with a configurable scale (default 1 mm), offset (default the minimum of the data) and an optional GeoTIFF coordinate system record for an `EPSG:NNNN` source. Returns the number of points written. |
| `PclXyzExporter` | `Export(doc, writer, options)` writes `X Y Z R G B`, or `X Y Z I`, or `X Y Z` per point. |
| `PclPtsExporter` | `Export(doc, writer, options)` writes the point count, then `X Y Z Intensity R G B` per point. |
| `PclJsonExporter` | `Export(doc, writer, indented, maxPoints)` writes metadata, scans and, when `maxPoints` is above zero, sample points. |
diff --git a/src/PclIO/Export/PclLasExporter.cs b/src/PclIO/Export/PclLasExporter.cs
index f214b68..a6ba14f 100644
--- a/src/PclIO/Export/PclLasExporter.cs
+++ b/src/PclIO/Export/PclLasExporter.cs
@@ -1,31 +1,31 @@
using System.Buffers.Binary;
+using System.Text;
namespace PclIO.Export;
///
-/// Exports point clouds to the ASPRS LAS 1.2 binary format (point format 2: XYZ, intensity, classification, RGB).
+/// Exports point clouds to the ASPRS LAS binary format: version 1.2 with point format 2 (XYZ, intensity,
+/// classification, RGB), or version 1.4 with point formats 6 to 8, selected by .
///
///
/// The header needs the point count and bounds before the first record, so the source is enumerated twice
/// ( is re-enumerable): pass one computes count and bounds, pass two writes
/// the records. Memory use does not depend on the number of points. The output stream does not need to be seekable.
-/// Coordinates are stored with a fixed 1 mm scale, so the extent of each axis must not exceed about 2147 km.
/// Points with non-finite coordinates are skipped. Intensity is clamped to 0..1 and stored as 16 bit;
/// a point without intensity is written with full intensity, a point without colour is written white
/// (the format has no "missing" value). Return number is always 1 of 1; normals are not exported.
///
public static class PclLasExporter
{
- private const int HeaderSize = 227;
- private const int RecordSize = 26;
- private const double Scale = 0.001; // 1 millimetre
+ private const int HeaderSize12 = 227;
+ private const int HeaderSize14 = 375;
/// Writes the document's points to and returns the number of points written.
/// Source document.
/// Destination stream.
/// Read options (limit, subsampling, transform); null for defaults.
/// Number of point records written.
- /// The point count or the coordinate extent does not fit the LAS 1.2 limits.
+ /// The point count or the coordinate extent does not fit the LAS limits.
/// The source returned different points in the two passes.
public static long Export(PclDocument doc, Stream output, PclReadOptions? options = null) =>
Export(doc, output, options, out _);
@@ -36,13 +36,50 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
/// Read options (limit, subsampling, transform); null for defaults.
/// Number of points skipped because a coordinate was NaN or infinite.
/// Number of point records written.
- /// The point count or the coordinate extent does not fit the LAS 1.2 limits.
+ /// The point count or the coordinate extent does not fit the LAS limits.
/// The source returned different points in the two passes.
- public static long Export(PclDocument doc, Stream output, PclReadOptions? options, out long skippedPoints)
+ public static long Export(PclDocument doc, Stream output, PclReadOptions? options, out long skippedPoints) =>
+ Export(doc, output, options, null, out skippedPoints);
+
+ /// Writes the document's points with the given LAS options and returns the number of points written.
+ /// Source document.
+ /// Destination stream.
+ /// Read options (limit, subsampling, transform); null for defaults.
+ /// LAS version, point format, scale, offset and coordinate system; null for defaults.
+ /// Number of point records written.
+ /// The version and point format do not match, or the point count or the
+ /// coordinate extent does not fit the LAS limits.
+ /// The source returned different points in the two passes.
+ public static long Export(PclDocument doc, Stream output, PclReadOptions? options, PclLasOptions? lasOptions) =>
+ Export(doc, output, options, lasOptions, out _);
+
+ /// Writes the document's points with the given LAS options and also reports how many points were skipped.
+ /// Source document.
+ /// Destination stream.
+ /// Read options (limit, subsampling, transform); null for defaults.
+ /// LAS version, point format, scale, offset and coordinate system; null for defaults.
+ /// Number of points skipped because a coordinate was NaN or infinite.
+ /// Number of point records written.
+ /// The version and point format do not match, or the point count or the
+ /// coordinate extent does not fit the LAS limits.
+ /// The source returned different points in the two passes.
+ public static long Export(PclDocument doc, Stream output, PclReadOptions? options, PclLasOptions? lasOptions, out long skippedPoints)
{
ArgumentNullException.ThrowIfNull(doc);
ArgumentNullException.ThrowIfNull(output);
options ??= PclReadOptions.Default;
+ lasOptions ??= PclLasOptions.Default;
+
+ bool is14 = lasOptions.Version == LasVersion.V14;
+ int format = lasOptions.PointFormat;
+ if (format == 2 && is14 || format is 6 or 7 or 8 && !is14)
+ throw new NotSupportedException($"LAS point format {format} cannot be written with LAS {(is14 ? "1.4" : "1.2")}.");
+ if (lasOptions.Version is not (LasVersion.V12 or LasVersion.V14))
+ throw new NotSupportedException($"LAS version {lasOptions.Version:d} is not supported.");
+
+ double scale = lasOptions.Scale;
+ int headerSize = is14 ? HeaderSize14 : HeaderSize12;
+ int recordSize = format switch { 2 => 26, 6 => 30, 7 => 36, _ => 38 };
// Pass 1: count and bounds.
long count = 0;
@@ -55,38 +92,44 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
skippedPoints++;
continue;
}
- if (++count > uint.MaxValue)
+ if (!is14 && count >= uint.MaxValue)
throw new NotSupportedException("LAS 1.2 cannot hold more than 4294967295 points.");
+ count++;
bounds = bounds.Encapsulate(pt.Position);
}
if (bounds.IsEmpty) bounds = new PclBounds(PclVector3.Zero, PclVector3.Zero);
- // Record coordinates are int32 multiples of the scale.
- if ((bounds.Max.X - bounds.Min.X) / Scale > int.MaxValue ||
- (bounds.Max.Y - bounds.Min.Y) / Scale > int.MaxValue ||
- (bounds.Max.Z - bounds.Min.Z) / Scale > int.MaxValue)
- throw new NotSupportedException("The coordinate extent is too large for LAS 1.2 with a 1 mm scale.");
+ double offsetX = lasOptions.Offset?.X ?? bounds.Min.X;
+ double offsetY = lasOptions.Offset?.Y ?? bounds.Min.Y;
+ double offsetZ = lasOptions.Offset?.Z ?? bounds.Min.Z;
+
+ // Record coordinates are int32 multiples of the scale; with an explicit offset both ends must fit.
+ if ((bounds.Max.X - offsetX) / scale > int.MaxValue || (bounds.Min.X - offsetX) / scale < int.MinValue ||
+ (bounds.Max.Y - offsetY) / scale > int.MaxValue || (bounds.Min.Y - offsetY) / scale < int.MinValue ||
+ (bounds.Max.Z - offsetZ) / scale > int.MaxValue || (bounds.Min.Z - offsetZ) / scale < int.MinValue)
+ throw new NotSupportedException($"The coordinates do not fit int32 with LAS {(is14 ? "1.4" : "1.2")} and the configured scale and offset.");
- double offsetX = bounds.Min.X;
- double offsetY = bounds.Min.Y;
- double offsetZ = bounds.Min.Z;
+ byte[] vlrs = lasOptions.WriteCoordinateSystem ? CoordinateSystemVlr(doc.CoordinateSystem) : [];
+ uint pointDataOffset = checked((uint)headerSize + (uint)vlrs.Length);
- byte[] header = new byte[HeaderSize];
+ byte[] header = new byte[headerSize];
"LASF"u8.CopyTo(header.AsSpan(0, 4));
- header[24] = 1; // version 1.2
- header[25] = 2;
- BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(94, 2), HeaderSize);
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(96, 4), HeaderSize); // offset to point data
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(100, 4), 0); // no variable length records
- header[104] = 2; // point data format 2
- BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(105, 2), RecordSize);
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(107, 4), (uint)count);
- BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(111, 4), (uint)count); // points of return 1
-
- BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(131, 8), Scale);
- BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(139, 8), Scale);
- BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(147, 8), Scale);
+ header[24] = 1; // version 1.x
+ header[25] = (byte)lasOptions.Version;
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(94, 2), (ushort)headerSize);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(96, 4), pointDataOffset); // offset to point data
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(100, 4), (uint)(vlrs.Length / VlrSize)); // variable length records
+ header[104] = (byte)format; // point data format
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(105, 2), (ushort)recordSize);
+
+ uint legacyCount = (is14 && count > uint.MaxValue) ? 0 : (uint)count;
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(107, 4), legacyCount);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(111, 4), legacyCount); // points of return 1
+
+ BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(131, 8), scale);
+ BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(139, 8), scale);
+ BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(147, 8), scale);
BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(155, 8), offsetX);
BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(163, 8), offsetY);
@@ -99,10 +142,17 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(211, 8), bounds.Max.Z);
BinaryPrimitives.WriteDoubleLittleEndian(header.AsSpan(219, 8), bounds.Min.Z);
+ if (is14)
+ {
+ BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(247, 8), (ulong)count);
+ BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(255, 8), (ulong)count); // points of return 1
+ }
+
output.Write(header, 0, header.Length);
+ if (vlrs.Length > 0) output.Write(vlrs, 0, vlrs.Length);
// Pass 2: records, written in chunks to avoid one small write per point.
- byte[] buf = new byte[RecordSize * 2048];
+ byte[] buf = new byte[recordSize * 2048];
int used = 0;
long written = 0;
foreach (var pt in doc.ReadAllPoints(options))
@@ -111,26 +161,50 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
if (++written > count)
throw new InvalidOperationException("The point source changed between the two export passes.");
- var rec = buf.AsSpan(used, RecordSize);
- BinaryPrimitives.WriteInt32LittleEndian(rec[..4], checked((int)Math.Round((pt.Position.X - offsetX) / Scale)));
- BinaryPrimitives.WriteInt32LittleEndian(rec.Slice(4, 4), checked((int)Math.Round((pt.Position.Y - offsetY) / Scale)));
- BinaryPrimitives.WriteInt32LittleEndian(rec.Slice(8, 4), checked((int)Math.Round((pt.Position.Z - offsetZ) / Scale)));
+ var rec = buf.AsSpan(used, recordSize);
+ BinaryPrimitives.WriteInt32LittleEndian(rec[..4], checked((int)Math.Round((pt.Position.X - offsetX) / scale)));
+ BinaryPrimitives.WriteInt32LittleEndian(rec.Slice(4, 4), checked((int)Math.Round((pt.Position.Y - offsetY) / scale)));
+ BinaryPrimitives.WriteInt32LittleEndian(rec.Slice(8, 4), checked((int)Math.Round((pt.Position.Z - offsetZ) / scale)));
float intensity = ExportValues.Intensity01(pt.Intensity) ?? 1.0f;
BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(12, 2), (ushort)MathF.Round(intensity * 65535f));
- rec[14] = 0x09; // return number 1 of 1
- rec[15] = (byte)((pt.Classification ?? 0) & 0x1F); // upper bits are flags in LAS 1.2
- rec[16] = 0; // scan angle
- rec[17] = 0; // user data
- BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(18, 2), 0); // point source id
+ if (format == 2)
+ {
+ rec[14] = 0x09; // return number 1 of 1
+ rec[15] = (byte)((pt.Classification ?? 0) & 0x1F); // upper bits are flags in LAS 1.2
+ rec[16] = 0; // scan angle
+ rec[17] = 0; // user data
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(18, 2), 0); // point source id
+
+ // Scale 8-bit channels to the full 16-bit range (255 -> 65535).
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(20, 2), (ushort)((pt.Color?.R ?? 255) * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(22, 2), (ushort)((pt.Color?.G ?? 255) * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(24, 2), (ushort)((pt.Color?.B ?? 255) * 257));
+ }
+ else
+ {
+ rec[14] = 0x11; // return number 1 of 1
+ rec[15] = 0; // classification flags
+ rec[16] = pt.Classification ?? 0;
+ rec[17] = 0; // user data
+ BinaryPrimitives.WriteInt16LittleEndian(rec.Slice(18, 2), 0); // scan angle
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(20, 2), 0); // point source id
+ BinaryPrimitives.WriteDoubleLittleEndian(rec.Slice(22, 8), 0); // GPS time
+
+ if (format >= 7)
+ {
+ // Scale 8-bit channels to the full 16-bit range (255 -> 65535).
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(30, 2), (ushort)((pt.Color?.R ?? 255) * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(32, 2), (ushort)((pt.Color?.G ?? 255) * 257));
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(34, 2), (ushort)((pt.Color?.B ?? 255) * 257));
- // Scale 8-bit channels to the full 16-bit range (255 -> 65535).
- BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(20, 2), (ushort)((pt.Color?.R ?? 255) * 257));
- BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(22, 2), (ushort)((pt.Color?.G ?? 255) * 257));
- BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(24, 2), (ushort)((pt.Color?.B ?? 255) * 257));
+ if (format == 8)
+ BinaryPrimitives.WriteUInt16LittleEndian(rec.Slice(36, 2), 0); // near infrared
+ }
+ }
- used += RecordSize;
+ used += recordSize;
if (used == buf.Length)
{
output.Write(buf, 0, used);
@@ -145,4 +219,61 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
return written;
}
+
+ // A variable length record holds the whole GeoTIFF key directory, so its size is fixed.
+ private const int VlrSize = 54 + 24;
+
+ ///
+ /// A GeoTIFF variable length record naming the EPSG code of the source, or empty when the source has none that
+ /// fits in 16 bits. Only the EPSG:NNNN form is recognised and it is transcribed as a projected reference;
+ /// anything else is skipped without a record.
+ ///
+ private static byte[] CoordinateSystemVlr(string? coordinateSystem)
+ {
+ if (!TryParseEpsg(coordinateSystem, out ushort code)) return [];
+
+ byte[] vlr = new byte[VlrSize];
+ BinaryPrimitives.WriteUInt16LittleEndian(vlr.AsSpan(0, 2), 0); // reserved
+ Encoding.ASCII.GetBytes("LASF_Projection").CopyTo(vlr, 2);
+ BinaryPrimitives.WriteUInt16LittleEndian(vlr.AsSpan(18, 2), 34735); // GeoTIFF key directory
+ BinaryPrimitives.WriteUInt32LittleEndian(vlr.AsSpan(20, 4), (uint)(VlrSize - 54)); // record length after header
+ Encoding.ASCII.GetBytes("GeoTIFF").CopyTo(vlr, 24);
+
+ Span keys = vlr.AsSpan(54);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys[..2], 1); // key directory version
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(2, 2), 1); // key revision
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(4, 2), 0); // minor revision
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(6, 2), 2); // number of keys
+
+ // GTModelTypeGeoKey = ModelTypeProjected.
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(8, 2), 1024);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(10, 2), 0);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(12, 2), 1);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(14, 2), 1);
+
+ // ProjectedCSTypeGeoKey = the EPSG code.
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(16, 2), 3072);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(18, 2), 0);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(20, 2), 1);
+ BinaryPrimitives.WriteUInt16LittleEndian(keys.Slice(22, 2), code);
+
+ return vlr;
+ }
+
+ private static bool TryParseEpsg(string? coordinateSystem, out ushort code)
+ {
+ code = 0;
+ if (coordinateSystem == null) return false;
+
+ string text = coordinateSystem.Trim();
+ const string prefix = "EPSG:";
+ if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return false;
+ if (!ulong.TryParse(text.AsSpan(prefix.Length), System.Globalization.NumberStyles.None,
+ System.Globalization.CultureInfo.InvariantCulture, out ulong value))
+ return false;
+
+ if (value is < 1 or > ushort.MaxValue) return false;
+ code = (ushort)value;
+ return true;
+ }
}
diff --git a/src/PclIO/Export/PclLasOptions.cs b/src/PclIO/Export/PclLasOptions.cs
new file mode 100644
index 0000000..d81cddd
--- /dev/null
+++ b/src/PclIO/Export/PclLasOptions.cs
@@ -0,0 +1,68 @@
+namespace PclIO.Export;
+
+/// LAS version written by .
+public enum LasVersion : byte
+{
+ /// ASPRS LAS 1.2.
+ V12 = 2,
+
+ /// ASPRS LAS 1.4.
+ V14 = 4,
+}
+
+/// Options selecting the LAS version, point format, scale, offset and coordinate system of .
+public sealed record PclLasOptions
+{
+ private int _pointFormat = 2;
+ private double _scale = 0.001;
+
+ /// Default options: LAS 1.2, point format 2, 1 mm scale, offset from the data, no coordinate system record.
+ public static PclLasOptions Default { get; } = new();
+
+ /// LAS version to write: 1.2 or 1.4.
+ public LasVersion Version { get; init; } = LasVersion.V12;
+
+ ///
+ /// Point format to write: 2 with LAS 1.2; 6, 7 or 8 with LAS 1.4. Format 6 holds XYZ, intensity, classification and
+ /// GPS time; format 7 adds RGB, format 8 adds near infrared (always zero, points carry none).
+ ///
+ /// The value is not 2, 6, 7 or 8.
+ public int PointFormat
+ {
+ get => _pointFormat;
+ init
+ {
+ if (value is not (2 or 6 or 7 or 8))
+ throw new ArgumentOutOfRangeException(nameof(value), "The LAS point format must be 2, 6, 7 or 8.");
+ _pointFormat = value;
+ }
+ }
+
+ ///
+ /// Metres per stored coordinate unit, applied to every axis. Record coordinates are 32-bit integers, so the extent
+ /// of each axis must not exceed about 2147 km times the scale in millimetres. Must be finite and above zero.
+ ///
+ /// The value is not finite or not above zero.
+ public double Scale
+ {
+ get => _scale;
+ init
+ {
+ if (!double.IsFinite(value) || value <= 0)
+ throw new ArgumentOutOfRangeException(nameof(value), "The LAS scale must be finite and above zero.");
+ _scale = value;
+ }
+ }
+
+ ///
+ /// Coordinate offset subtracted before scaling, or null to use the minimum of the data on every axis.
+ ///
+ public PclVector3? Offset { get; init; }
+
+ ///
+ /// Whether to write the coordinate system of the source as a GeoTIFF variable length record when it names an
+ /// EPSG code that fits in 16 bits (the EPSG:NNNN form, transcribed as a projected reference). Sources carry
+ /// only the code, so anything else is skipped without a record. The default is false.
+ ///
+ public bool WriteCoordinateSystem { get; init; }
+}
diff --git a/tests/PclIO.Tests/ExportTests.cs b/tests/PclIO.Tests/ExportTests.cs
index fc80c2e..dac7f13 100644
--- a/tests/PclIO.Tests/ExportTests.cs
+++ b/tests/PclIO.Tests/ExportTests.cs
@@ -12,6 +12,9 @@ internal sealed class FakeDocument(Func> source, string fi
{
private readonly FakeScan _scan = new(source, declaredCount);
+ public FakeDocument(Func> source, string filePath, long declaredCount, string? coordinateSystem)
+ : this(source, filePath, declaredCount) => CoordinateSystem = coordinateSystem;
+
public override PclFileKind Kind => PclFileKind.RecapScan;
public override IReadOnlyList Scans => [_scan];
@@ -181,6 +184,13 @@ private static byte[] Las(PclDocument doc, PclReadOptions? options = null)
return ms.ToArray();
}
+ private static byte[] Las(PclDocument doc, PclLasOptions lasOptions)
+ {
+ using var ms = new MemoryStream();
+ PclLasExporter.Export(doc, ms, null, lasOptions);
+ return ms.ToArray();
+ }
+
[Fact]
public void Las_Header_Describes_The_Records_That_Follow()
{
@@ -315,6 +325,210 @@ public void Las_Of_Real_Synthetic_Rcs_Points_Matches_What_Was_Written()
Assert.Equal(2u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(107, 4)));
}
+ [Fact]
+ public void Las14_Header_Describes_Version_Format_Scale_Offset_And_Counts()
+ {
+ var points = new[]
+ {
+ new PclPoint(new PclVector3(1, 2, 3), new PclColor(10, 20, 30), 0.25f, null, 5),
+ new PclPoint(new PclVector3(-4.5, 5.25, 6.125), null, 0.5f),
+ new PclPoint(new PclVector3(7, 8, 9)),
+ };
+ using var doc = new FakeDocument(() => points, "sample.xyz", points.Length, "EPSG:3857");
+ var las = new PclLasOptions
+ {
+ Version = LasVersion.V14,
+ PointFormat = 7,
+ Scale = 0.01,
+ Offset = new PclVector3(1, 2, 3),
+ WriteCoordinateSystem = true,
+ };
+ byte[] bytes = Las(doc, las);
+
+ Assert.Equal(1, bytes[24]);
+ Assert.Equal(4, bytes[25]);
+ Assert.Equal(375, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(94, 2)));
+ Assert.Equal(375 + 78u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(96, 4)));
+ Assert.Equal(1u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(100, 4)));
+ Assert.Equal(7, bytes[104]);
+ Assert.Equal(36, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(105, 2)));
+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(107, 4)));
+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(111, 4)));
+ Assert.Equal(3ul, BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(247, 8)));
+ Assert.Equal(3ul, BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(255, 8)));
+
+ Assert.Equal(0.01, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(131, 8)));
+ Assert.Equal(1.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(155, 8)));
+ Assert.Equal(2.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(163, 8)));
+ Assert.Equal(3.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(171, 8)));
+ Assert.Equal(7.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(179, 8)));
+ Assert.Equal(-4.5, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(187, 8)));
+
+ Assert.Equal(375 + 78 + (3 * 36), bytes.Length);
+ }
+
+ [Fact]
+ public void Las14_Coordinate_System_Writes_A_Geotiff_Record()
+ {
+ using var doc = new FakeDocument(() => [], "sample.xyz", 0, "EPSG:3857");
+ byte[] bytes = Las(doc, new PclLasOptions { Version = LasVersion.V14, PointFormat = 6, WriteCoordinateSystem = true });
+
+ Assert.Equal(375 + 78, bytes.Length);
+ Assert.Equal(0, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(375, 2)));
+ Assert.Equal("LASF_Projection", Encoding.ASCII.GetString(bytes, 377, 15));
+ Assert.Equal(34735, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(393, 2)));
+ Assert.Equal(24u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(395, 4)));
+ Assert.Equal("GeoTIFF", Encoding.ASCII.GetString(bytes, 399, 7));
+
+ Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(429, 2)));
+ Assert.Equal(2, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(435, 2)));
+ Assert.Equal(1024, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(437, 2)));
+ Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(443, 2)));
+ Assert.Equal(3072, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(445, 2)));
+ Assert.Equal(3857, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(451, 2)));
+ }
+
+ [Theory]
+ [InlineData("LOCAL_GRID_SYSTEM")]
+ [InlineData("EPSG:999999")]
+ [InlineData("EPSG:12x4")]
+ [InlineData("epsg:3857")]
+ public void Las_Coordinate_System_Record_Needs_An_Epsg_Code_That_Fits(string? coordinateSystem)
+ {
+ bool written = coordinateSystem is "epsg:3857";
+ using var doc = new FakeDocument(() => [], "sample.xyz", 0, coordinateSystem);
+ byte[] bytes = Las(doc, new PclLasOptions { WriteCoordinateSystem = true });
+
+ Assert.Equal(written ? LasHeaderSize + 78 : LasHeaderSize, bytes.Length);
+ Assert.Equal(written ? 1u : 0u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(100, 4)));
+ }
+
+ [Fact]
+ public void Las_Writes_No_Coordinate_System_Record_By_Default()
+ {
+ using var doc = new FakeDocument(() => [], "sample.xyz", 0, "EPSG:3857");
+
+ Assert.Equal(LasHeaderSize, Las(doc).Length);
+ }
+
+ [Fact]
+ public void Las14_Round_Trip_Reads_Back_Positions_Intensity_Colour_And_Classification()
+ {
+ var points = new[]
+ {
+ new PclPoint(new PclVector3(1, 2, 3), new PclColor(10, 20, 30), 0.25f, null, 5),
+ new PclPoint(new PclVector3(-4.5, 5.25, 6.125), null, 0.5f),
+ new PclPoint(new PclVector3(7, 8, 9)),
+ };
+ using var doc = new FakeDocument(() => points);
+ var las = new PclLasOptions { Version = LasVersion.V14, PointFormat = 7, Scale = 0.01, Offset = new PclVector3(1, 2, 3) };
+ byte[] bytes = Las(doc, las);
+
+ const int recordSize = 36;
+ const int dataStart = 375;
+ Assert.Equal(dataStart + (3 * recordSize), bytes.Length);
+
+ // Raw stored integers, then the decoded values.
+ int[] rawX = [0, -550, 600];
+ int[] rawY = [0, 325, 600];
+ int[] rawZ = [0, 312, 600];
+ ushort[] rawIntensity = [16384, 32768, 65535];
+
+ for (int i = 0; i < 3; i++)
+ {
+ ReadOnlySpan rec = bytes.AsSpan(dataStart + (i * recordSize), recordSize);
+
+ Assert.Equal(rawX[i], BinaryPrimitives.ReadInt32LittleEndian(rec[..4]));
+ Assert.Equal(rawY[i], BinaryPrimitives.ReadInt32LittleEndian(rec.Slice(4, 4)));
+ Assert.Equal(rawZ[i], BinaryPrimitives.ReadInt32LittleEndian(rec.Slice(8, 4)));
+ Assert.Equal(rawIntensity[i], BinaryPrimitives.ReadUInt16LittleEndian(rec.Slice(12, 2)));
+
+ Assert.Equal(0x11, rec[14]);
+ Assert.Equal(0, rec[15]);
+ Assert.Equal(0.0, BinaryPrimitives.ReadDoubleLittleEndian(rec.Slice(22, 8)));
+
+ double x = (BinaryPrimitives.ReadInt32LittleEndian(rec[..4]) * 0.01) + 1;
+ double y = (BinaryPrimitives.ReadInt32LittleEndian(rec.Slice(4, 4)) * 0.01) + 2;
+ double z = (BinaryPrimitives.ReadInt32LittleEndian(rec.Slice(8, 4)) * 0.01) + 3;
+ Assert.Equal(points[i].X, x, 0.006);
+ Assert.Equal(points[i].Y, y, 0.006);
+ Assert.Equal(points[i].Z, z, 0.006);
+ }
+
+ Assert.Equal(new PclColor(10, 20, 30),
+ new PclColor((byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 30, 2)) / 257),
+ (byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 32, 2)) / 257),
+ (byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 34, 2)) / 257)));
+ Assert.Equal(5, bytes[dataStart + 16]);
+ Assert.Equal(new PclColor(255, 255, 255),
+ new PclColor((byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 36 + 30, 2)) / 257),
+ (byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 36 + 32, 2)) / 257),
+ (byte)(BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(dataStart + 36 + 34, 2)) / 257)));
+ }
+
+ [Fact]
+ public void Las14_Format_6_Has_No_Colour_And_Format_8_Has_Zero_Nir()
+ {
+ var points = new[] { new PclPoint(new PclVector3(1, 2, 3), new PclColor(10, 20, 30), 0.5f, null, 200) };
+ using var doc = new FakeDocument(() => points);
+
+ byte[] six = Las(doc, new PclLasOptions { Version = LasVersion.V14, PointFormat = 6 });
+ byte[] eight = Las(doc, new PclLasOptions { Version = LasVersion.V14, PointFormat = 8 });
+
+ Assert.Equal(375 + 30, six.Length);
+ Assert.Equal(375 + 38, eight.Length);
+ Assert.Equal(30, BinaryPrimitives.ReadUInt16LittleEndian(six.AsSpan(105, 2)));
+ Assert.Equal(38, BinaryPrimitives.ReadUInt16LittleEndian(eight.AsSpan(105, 2)));
+
+ // A full classification byte, not the five bits of LAS 1.2.
+ Assert.Equal(200, six[375 + 16]);
+ Assert.Equal(200, eight[375 + 16]);
+
+ // Format 8 stores no near infrared from points.
+ Assert.Equal(0, BinaryPrimitives.ReadUInt16LittleEndian(eight.AsSpan(375 + 36, 2)));
+
+ // The colour of format 8 defaults to white without a colour.
+ using var plain = new FakeDocument(() => [new PclPoint(new PclVector3(1, 2, 3))]);
+ byte[] white = Las(plain, new PclLasOptions { Version = LasVersion.V14, PointFormat = 8 });
+ Assert.Equal(65535, BinaryPrimitives.ReadUInt16LittleEndian(white.AsSpan(375 + 30, 2)));
+ }
+
+ [Theory]
+ [InlineData(LasVersion.V12, 6)]
+ [InlineData(LasVersion.V12, 7)]
+ [InlineData(LasVersion.V12, 8)]
+ [InlineData(LasVersion.V14, 2)]
+ public void Las_Rejects_A_Version_And_Format_That_Do_Not_Match(LasVersion version, int format)
+ {
+ using var doc = FakeDocument.Of(At(1, 2, 3));
+
+ Assert.Throws(() =>
+ PclLasExporter.Export(doc, new MemoryStream(), null, new PclLasOptions { Version = version, PointFormat = format }));
+ }
+
+ [Fact]
+ public void Las_Writes_The_Configured_Scale_And_Offset()
+ {
+ using var doc = FakeDocument.Of(new PclPoint(new PclVector3(11, 21, 31)));
+ var las = new PclLasOptions { Scale = 1.0, Offset = new PclVector3(10, 20, 30) };
+ byte[] bytes = Las(doc, las);
+
+ Assert.Equal(1.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(131, 8)));
+ Assert.Equal(10.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(155, 8)));
+ Assert.Equal(1, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(LasHeaderSize, 4)));
+ Assert.Equal(1, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(LasHeaderSize + 4, 4)));
+ Assert.Equal(1, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(LasHeaderSize + 8, 4)));
+ }
+
+ [Fact]
+ public void Las_Rejects_An_Offset_The_Coordinates_Do_Not_Fit()
+ {
+ using var doc = FakeDocument.Of(new PclPoint(new PclVector3(0, 0, 0)));
+ var las = new PclLasOptions { Offset = new PclVector3(1e15, 0, 0) };
+
+ Assert.Throws(() => PclLasExporter.Export(doc, new MemoryStream(), null, las));
+ }
+
// ---- JSON ------------------------------------------------------------------------------------------------
[Fact]
diff --git a/tests/PclIO.Tests/OptionsAndPathTests.cs b/tests/PclIO.Tests/OptionsAndPathTests.cs
index 4f896b0..82f9dc2 100644
--- a/tests/PclIO.Tests/OptionsAndPathTests.cs
+++ b/tests/PclIO.Tests/OptionsAndPathTests.cs
@@ -1,3 +1,4 @@
+using PclIO.Export;
using PclIO.Internal;
using Xunit;
@@ -79,6 +80,34 @@ public void A_Non_Positive_Or_Non_Finite_EdgeWise_Scale_Is_Rejected(double value
public void A_Positive_Finite_EdgeWise_Scale_Is_Accepted() =>
Assert.Equal(0.001, new PclReadOptions { EdgeWiseCoordinateScale = 0.001 }.EdgeWiseCoordinateScale);
+ [Theory]
+ [InlineData(5)]
+ [InlineData(0)]
+ [InlineData(-2)]
+ public void A_Las_Point_Format_Outside_2_6_7_8_Is_Rejected(int format) =>
+ Assert.Throws(() => new PclLasOptions { PointFormat = format });
+
+ [Theory]
+ [InlineData(0.0)]
+ [InlineData(-1.0)]
+ [InlineData(double.NaN)]
+ [InlineData(double.PositiveInfinity)]
+ public void A_Las_Scale_That_Is_Not_Positive_And_Finite_Is_Rejected(double scale) =>
+ Assert.Throws(() => new PclLasOptions { Scale = scale });
+
+ [Fact]
+ public void Las_Options_Default_To_1_2_Format_2_And_A_Millimetre()
+ {
+ var options = new PclLasOptions();
+
+ Assert.Equal(LasVersion.V12, options.Version);
+ Assert.Equal(2, options.PointFormat);
+ Assert.Equal(0.001, options.Scale);
+ Assert.Null(options.Offset);
+ Assert.False(options.WriteCoordinateSystem);
+ Assert.Equal(options, PclLasOptions.Default);
+ }
+
[Fact]
public void A_Limit_Applies_To_The_Total_Across_All_Scans()
{
From 4e9bf94b800de6611eb4f8ca8a894a76d18aee6f Mon Sep 17 00:00:00 2001
From: mahach666 <79989386+mahach666@users.noreply.github.com>
Date: Tue, 17 Nov 2026 13:26:18 +0000
Subject: [PATCH 2/2] Write spec-conformant LAS 1.4 headers and validate the
offset and the projected EPSG code
---
CHANGELOG.md | 7 +--
README.md | 2 +-
docs/public-api.md | 2 +-
src/PclIO/Export/PclLasExporter.cs | 18 +++++---
src/PclIO/Export/PclLasOptions.cs | 24 +++++++---
tests/PclIO.Tests/ExportTests.cs | 71 ++++++++++++++++++++++--------
6 files changed, 90 insertions(+), 34 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b578be2..934532a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -51,9 +51,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
prototype limit is the packet header bound of 65535 fields.
- The EdgeWise cluster position scale is now `PclReadOptions.EdgeWiseCoordinateScale`, so the caller states it; the
default keeps the long-standing assumption (32768 units = 0.128 m).
-- The LAS exporter writes 1.4 with point formats 6 to 8 (`PclLasOptions` selects version, format, scale, offset and an
- optional GeoTIFF coordinate system record for an `EPSG:NNNN` source); 1.2 with point format 2 stays the default and is
- byte-identical to before.
+- The LAS exporter writes 1.4 with point formats 6 to 8 (`PclLasOptions` selects version, format, scale and offset);
+ 1.2 with point format 2 stays the default and is byte-identical to before. A projected `EPSG:NNNN` coordinate system
+ of the source is written as a GeoTIFF record for LAS 1.2 when asked; LAS 1.4 point formats 6 and above require WKT,
+ which the exporter does not produce, so a 1.4 file carries no coordinate system record.
## [0.1.0] - 2026-11-15
diff --git a/README.md b/README.md
index 977c99e..07ae215 100644
--- a/README.md
+++ b/README.md
@@ -125,7 +125,7 @@ outside the file is fetched.
| Output | Class | Notes |
| --- | --- | --- |
-| LAS 1.2, point format 2
LAS 1.4, point formats 6 to 8 | `PclLasExporter` (`PclLasOptions` selects version, format, scale, offset and coordinate system record) | Position, intensity, classification, RGB (formats 2 and 7/8; format 8 adds a zero near infrared). 1 mm scale and offset from the data by default. An `EPSG:NNNN` coordinate system of the source is written as a GeoTIFF record only when asked. |
+| LAS 1.2, point format 2
LAS 1.4, point formats 6 to 8 | `PclLasExporter` (`PclLasOptions` selects version, format, scale, offset and coordinate system record) | Position, intensity, classification, RGB (formats 2 and 7/8; format 8 adds a zero near infrared). 1 mm scale and offset from the data by default. A projected `EPSG:NNNN` coordinate system of the source is written as a GeoTIFF record for LAS 1.2 only when asked; LAS 1.4 requires WKT, which the exporter does not produce, so a 1.4 file carries no coordinate system record. |
| XYZ | `PclXyzExporter` | `X Y Z R G B` when the point has a colour, else `X Y Z I` when it has an intensity, else `X Y Z`. |
| PTS | `PclPtsExporter` | A line with the point count, then `X Y Z Intensity R G B` per point. |
| JSON | `PclJsonExporter` | Metadata and scans; sample points only when a point limit above zero is given. |
diff --git a/docs/public-api.md b/docs/public-api.md
index d034f9b..6ab84f7 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -96,7 +96,7 @@ is empty, rooted, contains invalid characters or resolves outside the folder is
| Type | Use |
|---|---|
-| `PclLasExporter` / `PclLasOptions` / `LasVersion` | `Export(doc, stream, options, lasOptions)` writes ASPRS LAS 1.2 (point format 2) or 1.4 (point formats 6 to 8), with a configurable scale (default 1 mm), offset (default the minimum of the data) and an optional GeoTIFF coordinate system record for an `EPSG:NNNN` source. Returns the number of points written. |
+| `PclLasExporter` / `PclLasOptions` / `LasVersion` | `Export(doc, stream, options, lasOptions)` writes ASPRS LAS 1.2 (point format 2) or 1.4 (point formats 6 to 8), with a configurable scale (default 1 mm) and offset (default the minimum of the data). A projected `EPSG:NNNN` coordinate system of the source is written as a GeoTIFF record for LAS 1.2 when asked; LAS 1.4 requires WKT, which the exporter does not produce, so a 1.4 file carries no coordinate system record. Returns the number of points written. |
| `PclXyzExporter` | `Export(doc, writer, options)` writes `X Y Z R G B`, or `X Y Z I`, or `X Y Z` per point. |
| `PclPtsExporter` | `Export(doc, writer, options)` writes the point count, then `X Y Z Intensity R G B` per point. |
| `PclJsonExporter` | `Export(doc, writer, indented, maxPoints)` writes metadata, scans and, when `maxPoints` is above zero, sample points. |
diff --git a/src/PclIO/Export/PclLasExporter.cs b/src/PclIO/Export/PclLasExporter.cs
index a6ba14f..cd4b335 100644
--- a/src/PclIO/Export/PclLasExporter.cs
+++ b/src/PclIO/Export/PclLasExporter.cs
@@ -110,7 +110,9 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
(bounds.Max.Z - offsetZ) / scale > int.MaxValue || (bounds.Min.Z - offsetZ) / scale < int.MinValue)
throw new NotSupportedException($"The coordinates do not fit int32 with LAS {(is14 ? "1.4" : "1.2")} and the configured scale and offset.");
- byte[] vlrs = lasOptions.WriteCoordinateSystem ? CoordinateSystemVlr(doc.CoordinateSystem) : [];
+ // The GeoTIFF record is the coordinate system carrier of LAS 1.2. LAS 1.4 point formats 6 and above require
+ // WKT, which the exporter does not produce, so a 1.4 file is written without a coordinate system record.
+ byte[] vlrs = (!is14 && lasOptions.WriteCoordinateSystem) ? CoordinateSystemVlr(doc.CoordinateSystem) : [];
uint pointDataOffset = checked((uint)headerSize + (uint)vlrs.Length);
byte[] header = new byte[headerSize];
@@ -123,7 +125,9 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
header[104] = (byte)format; // point data format
BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(105, 2), (ushort)recordSize);
- uint legacyCount = (is14 && count > uint.MaxValue) ? 0 : (uint)count;
+ // LAS 1.4 keeps the legacy counts at zero when the point format is 6 or above, or when the count does not
+ // fit 32 bits; the extended counts at the end of the header carry the number instead.
+ uint legacyCount = (is14 && (format >= 6 || count > uint.MaxValue)) ? 0 : (uint)count;
BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(107, 4), legacyCount);
BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(111, 4), legacyCount); // points of return 1
@@ -224,9 +228,9 @@ public static long Export(PclDocument doc, Stream output, PclReadOptions? option
private const int VlrSize = 54 + 24;
///
- /// A GeoTIFF variable length record naming the EPSG code of the source, or empty when the source has none that
- /// fits in 16 bits. Only the EPSG:NNNN form is recognised and it is transcribed as a projected reference;
- /// anything else is skipped without a record.
+ /// A GeoTIFF variable length record naming the projected EPSG code of the source, or empty when the source has
+ /// none that fits in 16 bits. Only the EPSG:NNNN form is recognised; geographic codes and anything else
+ /// are skipped without a record.
///
private static byte[] CoordinateSystemVlr(string? coordinateSystem)
{
@@ -260,6 +264,8 @@ private static byte[] CoordinateSystemVlr(string? coordinateSystem)
return vlr;
}
+ // Recognises a projected EPSG code. The record writes a projected reference, so a geographic code (the
+ // 4000-4999 block) would name a CRS of the wrong kind and is skipped, as is the user-defined sentinel 32767.
private static bool TryParseEpsg(string? coordinateSystem, out ushort code)
{
code = 0;
@@ -273,6 +279,8 @@ private static bool TryParseEpsg(string? coordinateSystem, out ushort code)
return false;
if (value is < 1 or > ushort.MaxValue) return false;
+ if (value is >= 4000 and <= 4999) return false;
+ if (value == 32767) return false;
code = (ushort)value;
return true;
}
diff --git a/src/PclIO/Export/PclLasOptions.cs b/src/PclIO/Export/PclLasOptions.cs
index d81cddd..80a7a42 100644
--- a/src/PclIO/Export/PclLasOptions.cs
+++ b/src/PclIO/Export/PclLasOptions.cs
@@ -15,6 +15,7 @@ public sealed record PclLasOptions
{
private int _pointFormat = 2;
private double _scale = 0.001;
+ private PclVector3? _offset;
/// Default options: LAS 1.2, point format 2, 1 mm scale, offset from the data, no coordinate system record.
public static PclLasOptions Default { get; } = new();
@@ -55,14 +56,27 @@ public double Scale
}
///
- /// Coordinate offset subtracted before scaling, or null to use the minimum of the data on every axis.
+ /// Coordinate offset subtracted before scaling, or null to use the minimum of the data on every axis. Every
+ /// component must be finite.
///
- public PclVector3? Offset { get; init; }
+ /// A component is not finite.
+ public PclVector3? Offset
+ {
+ get => _offset;
+ init
+ {
+ if (value is { } v && (!double.IsFinite(v.X) || !double.IsFinite(v.Y) || !double.IsFinite(v.Z)))
+ throw new ArgumentOutOfRangeException(nameof(value), "The LAS offset must be finite on every axis.");
+ _offset = value;
+ }
+ }
///
- /// Whether to write the coordinate system of the source as a GeoTIFF variable length record when it names an
- /// EPSG code that fits in 16 bits (the EPSG:NNNN form, transcribed as a projected reference). Sources carry
- /// only the code, so anything else is skipped without a record. The default is false.
+ /// Whether to write the coordinate system of the source as a GeoTIFF variable length record when it names a
+ /// projected EPSG code that fits in 16 bits (the EPSG:NNNN form). Geographic codes and anything else are
+ /// skipped without a record. Only LAS 1.2 carries the record: LAS 1.4 point formats 6 and above require WKT,
+ /// which the exporter does not produce, so a 1.4 file is written without a coordinate system record. The default
+ /// is false.
///
public bool WriteCoordinateSystem { get; init; }
}
diff --git a/tests/PclIO.Tests/ExportTests.cs b/tests/PclIO.Tests/ExportTests.cs
index dac7f13..283e150 100644
--- a/tests/PclIO.Tests/ExportTests.cs
+++ b/tests/PclIO.Tests/ExportTests.cs
@@ -348,12 +348,13 @@ public void Las14_Header_Describes_Version_Format_Scale_Offset_And_Counts()
Assert.Equal(1, bytes[24]);
Assert.Equal(4, bytes[25]);
Assert.Equal(375, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(94, 2)));
- Assert.Equal(375 + 78u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(96, 4)));
- Assert.Equal(1u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(100, 4)));
+ Assert.Equal(375u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(96, 4)));
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(100, 4)));
Assert.Equal(7, bytes[104]);
Assert.Equal(36, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(105, 2)));
- Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(107, 4)));
- Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(111, 4)));
+ // Format 7 keeps the legacy counts at zero; the extended counts carry the number.
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(107, 4)));
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(111, 4)));
Assert.Equal(3ul, BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(247, 8)));
Assert.Equal(3ul, BinaryPrimitives.ReadUInt64LittleEndian(bytes.AsSpan(255, 8)));
@@ -364,36 +365,51 @@ public void Las14_Header_Describes_Version_Format_Scale_Offset_And_Counts()
Assert.Equal(7.0, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(179, 8)));
Assert.Equal(-4.5, BinaryPrimitives.ReadDoubleLittleEndian(bytes.AsSpan(187, 8)));
- Assert.Equal(375 + 78 + (3 * 36), bytes.Length);
+ Assert.Equal(375 + (3 * 36), bytes.Length);
}
[Fact]
- public void Las14_Coordinate_System_Writes_A_Geotiff_Record()
+ public void Las14_Writes_No_Coordinate_System_Record_Even_When_Requested()
{
+ // LAS 1.4 point formats 6 and above require WKT, which the exporter does not produce, so the record is
+ // skipped rather than written in the GeoTIFF form that only LAS 1.2 may carry.
using var doc = new FakeDocument(() => [], "sample.xyz", 0, "EPSG:3857");
byte[] bytes = Las(doc, new PclLasOptions { Version = LasVersion.V14, PointFormat = 6, WriteCoordinateSystem = true });
- Assert.Equal(375 + 78, bytes.Length);
- Assert.Equal(0, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(375, 2)));
- Assert.Equal("LASF_Projection", Encoding.ASCII.GetString(bytes, 377, 15));
- Assert.Equal(34735, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(393, 2)));
- Assert.Equal(24u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(395, 4)));
- Assert.Equal("GeoTIFF", Encoding.ASCII.GetString(bytes, 399, 7));
+ Assert.Equal(375, bytes.Length);
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(100, 4)));
+ }
+
+ [Fact]
+ public void Las12_Coordinate_System_Writes_A_Geotiff_Record()
+ {
+ using var doc = new FakeDocument(() => [], "sample.xyz", 0, "EPSG:3857");
+ byte[] bytes = Las(doc, new PclLasOptions { WriteCoordinateSystem = true });
+
+ Assert.Equal(LasHeaderSize + 78, bytes.Length);
+ Assert.Equal(0, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(LasHeaderSize, 2)));
+ Assert.Equal("LASF_Projection", Encoding.ASCII.GetString(bytes, LasHeaderSize + 2, 15));
+ Assert.Equal(34735, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(LasHeaderSize + 18, 2)));
+ Assert.Equal(24u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(LasHeaderSize + 20, 4)));
+ Assert.Equal("GeoTIFF", Encoding.ASCII.GetString(bytes, LasHeaderSize + 24, 7));
- Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(429, 2)));
- Assert.Equal(2, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(435, 2)));
- Assert.Equal(1024, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(437, 2)));
- Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(443, 2)));
- Assert.Equal(3072, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(445, 2)));
- Assert.Equal(3857, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(451, 2)));
+ int keys = LasHeaderSize + 54;
+ Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys, 2)));
+ Assert.Equal(2, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys + 6, 2)));
+ Assert.Equal(1024, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys + 8, 2)));
+ Assert.Equal(1, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys + 14, 2)));
+ Assert.Equal(3072, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys + 16, 2)));
+ Assert.Equal(3857, BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(keys + 22, 2)));
}
[Theory]
[InlineData("LOCAL_GRID_SYSTEM")]
[InlineData("EPSG:999999")]
[InlineData("EPSG:12x4")]
+ [InlineData("EPSG:4326")]
+ [InlineData("EPSG:32767")]
[InlineData("epsg:3857")]
- public void Las_Coordinate_System_Record_Needs_An_Epsg_Code_That_Fits(string? coordinateSystem)
+ public void Las_Coordinate_System_Record_Needs_A_Projected_Epsg_Code_That_Fits(string? coordinateSystem)
{
bool written = coordinateSystem is "epsg:3857";
using var doc = new FakeDocument(() => [], "sample.xyz", 0, coordinateSystem);
@@ -529,6 +545,23 @@ public void Las_Rejects_An_Offset_The_Coordinates_Do_Not_Fit()
Assert.Throws(() => PclLasExporter.Export(doc, new MemoryStream(), null, las));
}
+ [Theory]
+ [InlineData(double.NaN, 0, 0)]
+ [InlineData(0, double.PositiveInfinity, 0)]
+ [InlineData(0, 0, double.NegativeInfinity)]
+ public void Las_Rejects_A_Non_Finite_Offset_Before_Writing(double x, double y, double z)
+ {
+ // A non-finite offset would slip through the extent check and write a corrupt header, so it is rejected
+ // when the options are built, before anything reaches the output.
+ Assert.Throws(() => new PclLasOptions { Offset = new PclVector3(x, y, z) });
+
+ using var doc = FakeDocument.Of();
+ using var output = new MemoryStream();
+ Assert.Throws(() =>
+ PclLasExporter.Export(doc, output, null, new PclLasOptions { Offset = new PclVector3(x, y, z) }));
+ Assert.Equal(0, output.Length);
+ }
+
// ---- JSON ------------------------------------------------------------------------------------------------
[Fact]