las-laz-js 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-10-21)
4
+
5
+ Reads LAZ.
6
+
7
+ - LAZ (LASzip) point formats 0–3 and 6–8 (item versions 2 and 3; version 4 unchecked), with extra bytes, are read by `openLas` /
8
+ `readPoints` / `chunks` / `readPointsToScratch` and the worker exactly as LAS is: each chunk
9
+ is decompressed into plain LAS records, then decoded by the same code, so every option works
10
+ the same. Plain JavaScript, translated from laz-rs (Apache-2.0); the package licence is now
11
+ `MIT AND Apache-2.0` (see `NOTICE`).
12
+ - Checked against an independent encoder: fixtures compressed by PDAL decode to exactly PDAL's own
13
+ decompression, and real files to exactly their LAS twins (1 M points), or to PDAL's decompression
14
+ (10 M points).
15
+ - `reader.laz` describes the compression. Wave-packet LAZ items, LASzip item version 1 and files
16
+ without a chunk table are `UNSUPPORTED`; a LAZ cut short is `TRUNCATED`. `COMPRESSED_LAZ` is
17
+ no longer thrown.
18
+ - Breaking: `strideFor` (deprecated in 0.1.1) is removed.
19
+ - Demo: reads LAZ, and shows its compression.
20
+
21
+ ## 0.1.1 (2026-10-21)
22
+
23
+ Fixes from the 0.1.0 review. No breaking changes.
24
+
25
+ - `maxPoints` keeps exactly that many of the points that pass the filters, spread over the whole
26
+ file. It used to keep only the start of a file, and with filters set could return nothing.
27
+ - Streamed chunks are coloured by one rule for the whole file, so windows no longer show seams
28
+ (new `createChunkColourizer`; `colourize` gains `eightBit`).
29
+ - Opening a LAS 1.4 file no longer reads its EVLRs to the end of the file: a big EVLR has
30
+ `bytes: null` until `readEvlrBytes(i)`. VLRs and EVLRs report `length`.
31
+ - Browser bundlers (esbuild, webpack, Vite) can bundle the package; the lazy Node import no
32
+ longer stops them.
33
+ - `readPoints` and `writeLas` peak near the size of what they return (a 69 MB read peaked at
34
+ 233 MB, now 74 MB); Node files are read into one reused window buffer.
35
+ - `dedupe` is about 7 times faster.
36
+ - `createLasWriter` works with OPFS scratch writers and Node file handles, and with
37
+ `writePoints` calls made without waiting.
38
+ - A custom `{ size, read }` source that returns a short read is `TRUNCATED`, never fewer points.
39
+ - Point formats 6–10 write their coordinate system as WKT, as LAS 1.4 requires; an EPSG code
40
+ alone is refused for them.
41
+ - `strideFor` is deprecated (the reader no longer uses it) and goes in 0.2.0; `countKept` is new.
42
+ - Demo: bounds, dedupe, colour range, return and intensity histograms; safe on big files.
43
+
3
44
  ## 0.1.0 (2026-10-21)
4
45
 
5
46
  First release: read and write ASPRS LAS.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,51 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
37
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
38
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
39
+
40
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
41
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
42
+
43
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
44
+
45
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
46
+
47
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
48
+
49
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
50
+
51
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ las-laz-js
2
+ Copyright (c) 2026 Brent Buffham (https://kirra-design.com). MIT licence (see LICENSE).
3
+
4
+ The LAZ decoder in src/laz/ is a JavaScript translation of laz-rs
5
+ (https://github.com/laz-rs/laz-rs), which is itself a Rust port of LASzip
6
+ (https://laszip.org) by rapidlasso. Those files are licensed under the
7
+ Apache License, Version 2.0 (see LICENSE-APACHE), not the MIT licence:
8
+
9
+ (c) 2007-2015, martin isenburg, rapidlasso - fast tools to catch reality
10
+ (c) 2014, Uday Verma, Hobu, Inc.
11
+ (c) 2019-2023, Thomas Montaigu
12
+
13
+ Changes: translated from Rust to JavaScript by Brent Buffham, 2026. Each
14
+ translated file names the laz-rs source it came from in its header.
package/README.md CHANGED
@@ -1,18 +1,22 @@
1
1
  # las-laz-js
2
2
 
3
- A JavaScript reader and writer for ASPRS **LAS** point clouds (LAZ to follow), published on npm
4
- as `las-laz-js`. Plain ES modules, no dependencies, runs in the browser and in Node — and built
5
- for files far larger than memory.
3
+ A JavaScript reader and writer for ASPRS **LAS** point clouds, and a reader for **LAZ**
4
+ (LASzip-compressed LAS), published on npm as `las-laz-js`. Plain ES modules, no dependencies,
5
+ runs in the browser and in Node — and built for files far larger than memory.
6
6
 
7
7
  **Status: early (0.x).** It works and is tested, but the API may still change before 1.0.
8
8
 
9
9
  - Working: `openLas` reads the header, VLRs / EVLRs and coordinate system of LAS 1.0–1.4;
10
10
  `readPoints` and `chunks` decode every point format (0–10) a window at a time, with filters
11
11
  and thinning; `colourize` colours points; `writeLas` writes LAS 1.0–1.4.
12
- - Big files: a 1.1 GB, 34-million-point cloud reads in about 2 seconds in Node, and is never held
13
- in memory whole.
14
- - Also: a ready-made module Worker (`las-laz-js/worker`) and a Three.js demo.
15
- - Not yet: reading LAZ (0.2.0) and writing LAZ (0.3.0).
12
+ - LAZ: point formats 0–3 and 6–8, with extra bytes, read exactly like LAS — the same calls, the
13
+ same options, decoded chunk by chunk in plain JavaScript (no WebAssembly).
14
+ - Big files: a 1.1 GB, 34-million-point LAS reads in under a second in Node, and a 10-million-point
15
+ LAZ decodes at about 1.8 million points a second; neither is held in memory whole (see LAZ below
16
+ for the one exception).
17
+ - Also: a ready-made module Worker (`las-laz-js/worker`) and a
18
+ [Three.js demo](https://brentbuffham.github.io/las-laz-js/).
19
+ - Not yet: writing LAZ (0.3.0).
16
20
 
17
21
  ## Install
18
22
 
@@ -24,9 +28,13 @@ Node 22 or newer, or any current browser. No dependencies.
24
28
 
25
29
  ## Demo
26
30
 
27
- Drop a LAS file onto the page and it is read locally (never uploaded), in the library's Worker,
28
- and streamed into a Three.js viewer. The side panel runs every library function.
29
- Run it locally with `npm run demo`, then open http://localhost:8080/.
31
+ Try it in the browser: **https://brentbuffham.github.io/las-laz-js/**
32
+
33
+ Drop a LAS or LAZ file onto the page. It is read locally (never uploaded), in the library's
34
+ Worker, and streamed into a Three.js viewer. The side panel shows the header, VLRs, coordinate
35
+ system and LAZ compression; reads with class, return, bounds, thinning and dedupe filters;
36
+ colours by RGB, intensity, elevation or class; lists point statistics; and saves the points back
37
+ out as LAS. To run it locally: `npm run demo`, then open http://localhost:8080/.
30
38
 
31
39
  ## Reading
32
40
 
@@ -37,7 +45,10 @@ var las = await openLas(file); // File / Blob, ArrayBuffer, Uint8Array
37
45
  las.header; // { versionMajor, versionMinor, pointFormat, pointCount, bounds, scale, offset,
38
46
  // software, systemId, creationDay, creationYear, pointsByReturn, compressed, ... }
39
47
  las.crs; // { kind: "geokeys" | "wkt" | null, epsg, wkt?, keys? } — parsed, never reprojected
40
- las.vlrs; // [{ userId, recordId, description, bytes }]
48
+ las.vlrs; // [{ userId, recordId, description, start, length, bytes }]
49
+ las.evlrs; // the same; an EVLR over 64 KiB (waveform data) has bytes: null until
50
+ // await las.readEvlrBytes(i) — opening never reads it
51
+ las.compressed; las.laz; // true for LAZ; its compressor, chunk size and items (else null)
41
52
 
42
53
  var pts = await las.readPoints({
43
54
  fields: ["x", "y", "z", "classification", "red", "green", "blue"],
@@ -60,12 +71,31 @@ red green blue nir`. Fields a point format does not hold are left out. `scanAngl
60
71
  degrees for every format.
61
72
 
62
73
  Filters run on the raw record before it is decoded, so a filtered-out point costs a byte read.
74
+ `maxPoints` keeps exactly that many of the points that pass the filters, spread evenly over
75
+ the whole file; with filters set it first counts the passing points, which reads the file twice.
76
+
77
+ ## LAZ
78
+
79
+ A LAZ file is opened and read with the same calls as LAS. Each LASzip chunk (50,000 points in
80
+ most files) is decompressed into the plain LAS records it holds, then decoded exactly as a LAS
81
+ window is — so every option above works the same, and reading a LAZ gives the same columns as
82
+ reading the LAS it was compressed from.
83
+
84
+ - Read: point formats 0–3 (LASzip point-wise, item version 2) and 6–8 (layered, item version 3),
85
+ with extra bytes. Item version 4 follows laz-rs but has not been checked against a real file
86
+ (it differs from 3 only with several scanner channels).
87
+ - Not read: wave-packet items (formats 4, 5, 9, 10 in LAZ), item version 1 (LASzip before 2011),
88
+ and files without a chunk table (an unfinished write). Each is refused with `UNSUPPORTED`,
89
+ naming what it found — never garbage points.
90
+ - A LAZ file cut short is `TRUNCATED`.
63
91
 
64
92
  ## Files bigger than memory
65
93
 
66
- `openLas` reads only the header and the VLRs. Points are read in windows of whole records
67
- (64 MiB by default, `openLas(file, { windowSize })`), so memory holds one window plus what you
68
- keep.
94
+ `openLas` reads only the header and the VLRs. Points are read in windows (64 MiB of records by
95
+ default, `openLas(file, { windowSize })`; for LAZ, whole chunks adding up to about that much
96
+ decompressed), so memory holds one window plus what you keep. One exception: a LAZ written
97
+ point-wise without chunks (LASzip before 2.0, rare) is one chunk, so its window is the whole
98
+ decompressed file.
69
99
 
70
100
  ```js
71
101
  for await (var chunk of las.chunks({ fields: ["x", "y", "z"] })) {
@@ -87,23 +117,28 @@ Returns a `Uint8Array`, three bytes per point. LAS colour is 16-bit and is scale
87
117
  except in files that store 8-bit values in the 16-bit fields (a common writer bug), which are
88
118
  detected and used as they are instead of turning almost black. Elevation uses a blue → cyan →
89
119
  green → yellow → red ramp; intensity a greyscale over the 2nd–98th percentile; classification
90
- the usual LiDAR-viewer colours (ASPRS defines the codes, not colours).
120
+ the usual LiDAR-viewer colours (ASPRS defines the codes, not colours). For streamed chunks,
121
+ `createChunkColourizer` keeps one rule for the whole file, so windows match.
91
122
 
92
123
  ## Writing
93
124
 
94
125
  ```js
95
126
  import { writeLas, createLasWriter } from "las-laz-js";
96
127
 
97
- var bytes = await writeLas(pts, { version: "1.4", pointFormat: 7, crs: { epsg: 28350 } });
128
+ var bytes = await writeLas(pts, { version: "1.2", pointFormat: 3, crs: { epsg: 28350 } });
129
+ var v14 = await writeLas(pts, { version: "1.4", pointFormat: 7, crs: { wkt: las.crs.wkt } });
98
130
 
99
- var w = await createLasWriter(sink, { version: "1.2", pointFormat: 3, scale, offset }); // sink: { write(bytes, position) }
131
+ var w = await createLasWriter(sink, { version: "1.2", pointFormat: 3, scale, offset });
132
+ // sink: an OPFS writer from openScratchSyncWriter, a Node FileHandle, or any { write(bytes, position) }
100
133
  await w.writePoints(batch1); await w.writePoints(batch2);
101
134
  await w.close(); // patches the header totals
102
135
  ```
103
136
 
104
137
  A version and point format that do not go together (format 6 in LAS 1.2) are refused, never
105
138
  silently changed. Scale and offset are chosen from the bounds when not given. `crs.epsg`
106
- writes a GeoKey record; `crs.wkt` a WKT record.
139
+ writes a GeoKey record; `crs.wkt` a WKT record. Point formats 6–10 must carry WKT (LAS 1.4), so
140
+ an EPSG code alone is refused for them — the library has no projection database to turn a code
141
+ into WKT. Writing LAZ arrives in 0.3.0.
107
142
 
108
143
  ## In a Worker
109
144
 
@@ -120,21 +155,25 @@ The protocol is documented in `src/workers/workerProtocol.js` and can be driven
120
155
  ## Errors
121
156
 
122
157
  Every failure is a `LasError` with a stable `code` (`ERROR_CODES`) and, for byte-level problems,
123
- the file `offset`: `NOT_LAS`, `UNSUPPORTED_VERSION`, `UNSUPPORTED`, `COMPRESSED_LAZ`,
124
- `TRUNCATED`, `BAD_HEADER`, `BAD_VLR`, `INVALID_ARGUMENT`, `ABORTED`, `TOO_MANY_POINTS`.
125
- A file shorter than its header promises is `TRUNCATED`, never garbage points.
158
+ the file `offset`: `NOT_LAS`, `UNSUPPORTED_VERSION`, `UNSUPPORTED`, `TRUNCATED`, `BAD_HEADER`,
159
+ `BAD_VLR`, `INVALID_ARGUMENT`, `ABORTED`, `TOO_MANY_POINTS`. A file shorter than its header
160
+ promises is `TRUNCATED`, never garbage points. (`COMPRESSED_LAZ` is kept for 0.1 callers but is no
161
+ longer thrown: LAZ is read.)
126
162
 
127
163
  ## Scope
128
164
 
129
165
  Reprojection is out of scope (the coordinate system is reported, not changed). Waveform
130
- formats 4, 5, 9 and 10 have their point fields read; the waveform data itself is not. COPC,
131
- EPT and E57 are not read.
166
+ formats 4, 5, 9 and 10 have their point fields read from LAS; the waveform data itself is not.
167
+ COPC, EPT and E57 are not read.
132
168
 
133
169
  ## Provenance
134
170
 
135
171
  The LAS reader, writer and big-file handling come from [Kirra](https://kirra-design.com),
136
- Brent Buffham's blast-design app, rewritten as a standalone library. The LAZ codec (0.2.0) is
137
- being ported from [laz-rs](https://github.com/laz-rs/laz-rs), used under its MIT licence.
172
+ Brent Buffham's blast-design app, rewritten as a standalone library. The LAZ decoder in
173
+ `src/laz/` is a JavaScript translation of [laz-rs](https://github.com/laz-rs/laz-rs) by Thomas
174
+ Montaigu, itself a Rust port of [LASzip](https://laszip.org) by Martin Isenburg (rapidlasso).
175
+ It is checked against an independent encoder: the test fixtures were compressed by
176
+ [PDAL](https://pdal.io), and every record must equal PDAL's own decompression.
138
177
  Formats are written to the ASPRS LAS 1.4 R15 specification; see `docs/LAS_FORMAT_NOTES.md`.
139
178
 
140
179
  ## Development
@@ -144,11 +183,16 @@ npm test # node --test, every test
144
183
  npm run test:coverage # with the coverage gate
145
184
  npm run demo # the demo on http://localhost:8080/
146
185
  npm run check:private # before every push: no private sample details in the repo
186
+ node _dev/makeLazFixtures.mjs # remake test/fixtures/laz with PDAL (needs PDAL 2.x)
147
187
  ```
148
188
 
149
189
  Private sample files go in the gitignored `samples/` folder, or are listed by path in
150
- `samples/paths.txt`; the sample tests compare each file with its own header.
190
+ `samples/paths.txt`; the sample tests compare each file with its own header, and each LAZ with a
191
+ LAS twin (same count and bounds) field by field.
151
192
 
152
193
  ## Licence
153
194
 
154
- MIT © Brent Buffham
195
+ `MIT AND Apache-2.0`. The library is MIT © Brent Buffham (`LICENSE`). The LAZ decoder in
196
+ `src/laz/`, translated from laz-rs / LASzip, is under the Apache License 2.0 (`LICENSE-APACHE`,
197
+ `NOTICE`). Both are permissive: use, change and ship it in open or closed software, keeping the
198
+ notices.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "las-laz-js",
3
- "version": "0.1.0",
4
- "description": "Zero-dependency JavaScript reader and writer for ASPRS LAS point clouds (LAZ to follow), for the browser and Node, built for files larger than memory.",
3
+ "version": "0.2.0",
4
+ "description": "Zero-dependency JavaScript reader and writer for ASPRS LAS point clouds, and reader for LAZ (LASzip), for the browser and Node, built for files larger than memory.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.js",
@@ -11,6 +11,8 @@
11
11
  "src",
12
12
  "README.md",
13
13
  "LICENSE",
14
+ "LICENSE-APACHE",
15
+ "NOTICE",
14
16
  "CHANGELOG.md"
15
17
  ],
16
18
  "sideEffects": false,
@@ -36,7 +38,7 @@
36
38
  "threejs"
37
39
  ],
38
40
  "author": "Brent Buffham (https://kirra-design.com)",
39
- "license": "MIT",
41
+ "license": "MIT AND Apache-2.0",
40
42
  "repository": {
41
43
  "type": "git",
42
44
  "url": "git+https://github.com/brentbuffham/las-laz-js.git"
package/src/LasReader.js CHANGED
@@ -17,9 +17,12 @@ import { NodeFileSource } from "./io/NodeFileSource.js";
17
17
  import { parseHeader } from "./format/LasHeader.js";
18
18
  import { parseVlrs, parseEvlrs } from "./format/LasVlr.js";
19
19
  import { parseCrs } from "./format/LasCrs.js";
20
- import { decodeRecords, resolveFields } from "./read/decodeRecords.js";
21
- import { windows } from "./read/windows.js";
22
- import { makeKeep, strideFor } from "./filter/filters.js";
20
+ import { decodeRecords, resolveFields, columnType } from "./read/decodeRecords.js";
21
+ import { windows, lazWindows } from "./read/windows.js";
22
+ import { findLazVlr } from "./laz/LazVlr.js";
23
+ import { readChunks } from "./laz/chunkTable.js";
24
+ import { createChunkDecoder } from "./laz/decompressChunk.js";
25
+ import { makeKeep, countKept } from "./filter/filters.js";
23
26
  import { dedupe } from "./filter/dedupe.js";
24
27
  import { openScratchSyncWriter } from "./io/ScratchBinaryFile.js";
25
28
 
@@ -32,12 +35,27 @@ function memorySource(bytes) {
32
35
  } };
33
36
  }
34
37
 
38
+ // A caller's own { size, read } source: every read must hand back exactly
39
+ // the bytes asked for, or a short read would silently drop points
40
+ function checkedSource(src) {
41
+ function check(got, a, b) {
42
+ if (got instanceof ArrayBuffer) got = new Uint8Array(got);
43
+ if (!(got instanceof Uint8Array)) throw new LasError(ERROR_CODES.INVALID_ARGUMENT, "source.read(" + a + ", " + b + ") must return a Uint8Array or ArrayBuffer");
44
+ if (got.length !== b - a) throw new LasError(ERROR_CODES.TRUNCATED, "source.read(" + a + ", " + b + ") returned " + got.length + " bytes, not " + (b - a), a + Math.min(got.length, b - a));
45
+ return got;
46
+ }
47
+ var out = { size: src.size, read: async function (a, b) { return check(await src.read(a, b), a, b); } };
48
+ if (typeof src.readInto === "function") out.readInto = async function (a, b, t) { return check(await src.readInto(a, b, t), a, b); };
49
+ if (typeof src.close === "function") out.close = function () { return src.close(); };
50
+ return out;
51
+ }
52
+
35
53
  async function toSource(source) {
36
54
  if (source instanceof Uint8Array) return memorySource(source);
37
55
  if (source instanceof ArrayBuffer) return memorySource(new Uint8Array(source));
38
56
  if (typeof source === "string") return NodeFileSource.open(source);
39
57
  if (source && typeof source.slice === "function" && typeof source.size === "number" && typeof source.read !== "function") return new BlobSource(source);
40
- if (source && typeof source.size === "number" && typeof source.read === "function") return source;
58
+ if (source && typeof source.size === "number" && typeof source.read === "function") return checkedSource(source);
41
59
  throw new LasError(ERROR_CODES.INVALID_ARGUMENT, "openLas needs a File / Blob, ArrayBuffer, Uint8Array, file path or { size, read } source");
42
60
  }
43
61
 
@@ -59,14 +77,29 @@ export async function openLas(source, opts) {
59
77
  }
60
78
  var evlrs = [];
61
79
  if (header.numberOfEvlrs > 0 && header.evlrStart > 0 && header.evlrStart < src.size) {
62
- var evBytes = await src.read(header.evlrStart, src.size);
63
- evlrs = parseEvlrs(new MemorySource(evBytes), 0, header.numberOfEvlrs).map(function (e) {
64
- return Object.assign({}, e, { start: e.start + header.evlrStart });
65
- });
80
+ evlrs = await walkEvlrs(src, header.evlrStart, header.numberOfEvlrs);
66
81
  }
67
82
  return new LasReader(src, header, vlrs, evlrs, (opts && opts.windowSize) || DEFAULT_WINDOW);
68
83
  }
69
84
 
85
+ // EVLRs sit after the points and can be huge (waveform data): read each
86
+ // 60-byte header, keep the bytes of small and coordinate-system records,
87
+ // and leave the rest on disk for readEvlrBytes.
88
+ var EVLR_EAGER = 65536;
89
+ async function walkEvlrs(src, start, count) {
90
+ var out = [], pos = start;
91
+ for (var i = 0; i < count; i++) {
92
+ if (pos + 60 > src.size) throw new LasError(ERROR_CODES.BAD_VLR, "EVLR " + (i + 1) + " starts past the end of the file", pos);
93
+ var e = parseEvlrs(new MemorySource(await src.read(pos, pos + 60)), 0, 1, true)[0];
94
+ if (pos + 60 + e.length > src.size) throw new LasError(ERROR_CODES.BAD_VLR, "EVLR " + (i + 1) + " runs past the end of the file", pos);
95
+ e.start = pos + 60;
96
+ e.bytes = e.length <= EVLR_EAGER || e.userId === "LASF_Projection" ? new Uint8Array(await src.read(e.start, e.start + e.length)) : null;
97
+ out.push(e);
98
+ pos += 60 + e.length;
99
+ }
100
+ return out;
101
+ }
102
+
70
103
  /**
71
104
  * A LAS file opened for reading. Create with openLas().
72
105
  */
@@ -83,17 +116,48 @@ export function LasReader(src, header, vlrs, evlrs, windowSize) {
83
116
  this.crs = parseCrs(vlrs.concat(evlrs));
84
117
  /** True for LAZ (compressed points). */
85
118
  this.compressed = header.compressed;
119
+ /** The parsed LASzip VLR of a LAZ file (compressor, chunk size, items), else null. */
120
+ this.laz = null;
121
+ if (header.compressed) { try { this.laz = findLazVlr(vlrs); } catch (e) { this.laz = null; } } // a bad VLR fails on read, not open
86
122
  }
87
123
 
88
- LasReader.prototype._check = function () {
89
- var h = this.header;
90
- if (h.compressed) {
91
- throw new LasError(ERROR_CODES.COMPRESSED_LAZ, "this file is LAZ (compressed); reading LAZ points is supported from las-laz-js 0.2.0");
92
- }
93
- var end = h.offsetToPointData + h.pointCount * h.recordLength;
94
- if (end > this._src.size) {
95
- throw new LasError(ERROR_CODES.TRUNCATED, "the header promises " + h.pointCount + " points ending at byte " + end + " but the file is " + this._src.size + " bytes", this._src.size);
124
+ // How to read this file's points: the windows, and how to turn one into raw
125
+ // LAS records (a LAS window is read as it is; a LAZ window is a run of whole
126
+ // chunks, decompressed into the scan's buffer). Built once per reader.
127
+ LasReader.prototype._plan = async function () {
128
+ if (this._planned) return this._planned;
129
+ var h = this.header, src = this._src, len = h.recordLength;
130
+ var plan;
131
+ if (!h.compressed) {
132
+ var end = h.offsetToPointData + h.pointCount * len;
133
+ if (end > src.size) {
134
+ throw new LasError(ERROR_CODES.TRUNCATED, "the header promises " + h.pointCount + " points ending at byte " + end + " but the file is " + src.size + " bytes", src.size);
135
+ }
136
+ var list = windows(h, this._windowSize);
137
+ plan = {
138
+ list: list,
139
+ // a source that can fill one reused buffer gets one (no bytes outlive a window)
140
+ bufferSize: typeof src.readInto === "function" && list.length ? list[0].end - list[0].start : 0,
141
+ records: function (win, buf) { return buf ? src.readInto(win.start, win.end, buf) : src.read(win.start, win.end); }
142
+ };
143
+ } else {
144
+ var vlr = findLazVlr(this.vlrs);
145
+ if (!vlr) throw new LasError(ERROR_CODES.BAD_VLR, "this LAZ file has no LASzip VLR (user \"laszip encoded\", record 22204), so its points cannot be decompressed");
146
+ var decode = createChunkDecoder(vlr, len);
147
+ var lazList = lazWindows(await readChunks(src, h, vlr), len, this._windowSize);
148
+ plan = {
149
+ list: lazList,
150
+ bufferSize: lazList.reduce(function (m, w) { return Math.max(m, w.count * len); }, 0),
151
+ records: async function (win, buf) {
152
+ var packed = await src.read(win.start, win.end);
153
+ var view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
154
+ win.chunks.forEach(function (c) { decode(packed, c.start - win.start, c.end - win.start, c.count, view, (c.firstRecord - win.firstRecord) * len, win.start); });
155
+ return buf.subarray(0, win.count * len);
156
+ }
157
+ };
96
158
  }
159
+ this._planned = plan;
160
+ return plan;
97
161
  };
98
162
 
99
163
  /**
@@ -104,32 +168,45 @@ LasReader.prototype._check = function () {
104
168
  LasReader.prototype.chunks = async function* (opts) {
105
169
  opts = opts || {};
106
170
  if (opts.dedupe) throw new LasError(ERROR_CODES.INVALID_ARGUMENT, "dedupe needs every point at once: use readPoints, not chunks");
107
- this._check();
171
+ yield* this._scan(opts, null);
172
+ };
173
+
174
+ // The window loop behind chunks and readPoints. into(win, n) -> { cols, at }
175
+ // makes decodeRecords write straight into readPoints' result columns.
176
+ LasReader.prototype._scan = async function* (opts, into) {
108
177
  var h = this.header;
178
+ var plan = await this._plan();
109
179
  var keep = makeKeep(opts, h);
110
- var stride = strideFor(h.pointCount, opts.maxPoints);
111
- var cap = opts.maxPoints > 0 ? opts.maxPoints : Infinity;
112
180
  var fields = resolveFields(h, opts.fields);
113
- var list = windows(h, this._windowSize);
181
+ var list = plan.list;
182
+ var buf = plan.bufferSize ? new Uint8Array(plan.bufferSize) : null;
183
+ var thin = null;
184
+ if (opts.maxPoints > 0) {
185
+ // Thin the points that pass the filters; with filters set, count them first (a second read)
186
+ var passing = keep ? await this._countPassing(plan, buf, keep, opts.signal) : h.pointCount;
187
+ if (passing > opts.maxPoints) thin = { total: passing, target: opts.maxPoints, acc: 0 };
188
+ }
114
189
  var kept = 0;
115
- for (var w = 0; w < list.length && kept < cap; w++) {
190
+ for (var w = 0; w < list.length; w++) {
116
191
  if (opts.signal && opts.signal.aborted) throw new LasError(ERROR_CODES.ABORTED, "read aborted");
117
192
  var win = list[w];
118
- var bytes = await this._src.read(win.start, win.end);
119
- var cols = decodeRecords(bytes, h, { fields: fields, keep: keep, stride: stride, firstIndex: win.firstRecord, localOrigin: opts.localOrigin, float32: opts.float32 });
120
- if (kept + cols.count > cap) cols = trim(cols, fields, cap - kept);
193
+ var bytes = await plan.records(win, buf);
194
+ var cols = decodeRecords(bytes, h, { fields: fields, keep: keep, thin: thin, localOrigin: opts.localOrigin, float32: opts.float32, into: into ? into(win) : null });
121
195
  kept += cols.count;
122
- if (typeof opts.onProgress === "function") opts.onProgress(kept >= cap ? 1 : (w + 1) / list.length, "read " + kept + " points");
196
+ if (typeof opts.onProgress === "function") opts.onProgress((w + 1) / list.length, "read " + kept + " points");
123
197
  yield cols;
124
198
  }
125
199
  if (opts.signal && opts.signal.aborted) throw new LasError(ERROR_CODES.ABORTED, "read aborted");
126
200
  };
127
201
 
128
- function trim(cols, fields, n) {
129
- var out = { count: n };
130
- fields.forEach(function (f) { out[f] = cols[f].slice(0, n); });
131
- return out;
132
- }
202
+ LasReader.prototype._countPassing = async function (plan, buf, keep, signal) {
203
+ var n = 0;
204
+ for (var w = 0; w < plan.list.length; w++) {
205
+ if (signal && signal.aborted) throw new LasError(ERROR_CODES.ABORTED, "read aborted");
206
+ n += countKept(await plan.records(plan.list[w], buf), this.header.recordLength, keep);
207
+ }
208
+ return n;
209
+ };
133
210
 
134
211
  /**
135
212
  * Read the selected points into one set of columns.
@@ -142,22 +219,25 @@ LasReader.prototype.readPoints = async function (opts) {
142
219
  var chunkOpts = Object.assign({}, opts);
143
220
  delete chunkOpts.dedupe;
144
221
  var fields = resolveFields(h, opts.fields);
145
- var acc = null, n = 0;
146
- for await (var c of this.chunks(chunkOpts)) {
147
- if (!acc) {
148
- acc = {};
149
- var guess = Math.max(c.count, 1024);
150
- fields.forEach(function (f) { acc[f] = new c[f].constructor(guess); });
151
- }
152
- if (n + c.count > acc[fields[0]].length) {
153
- var size = Math.max(n + c.count, acc[fields[0]].length * 2);
222
+ // Allocate once when the count is known (no filters: every point, or
223
+ // maxPoints of them; filters + maxPoints: at most maxPoints), so the
224
+ // peak is the result itself. Filters alone: grow by doubling.
225
+ var filtered = !!makeKeep(opts, h);
226
+ var cap = !filtered ? (opts.maxPoints > 0 ? Math.min(opts.maxPoints, h.pointCount) : h.pointCount)
227
+ : (opts.maxPoints > 0 ? Math.min(opts.maxPoints, h.pointCount) : 0);
228
+ var acc = {}, n = 0;
229
+ fields.forEach(function (f) { acc[f] = new (columnType(f, opts))(cap || 1024); });
230
+ function into(win) {
231
+ // A known cap is never exceeded, so it never grows; filters alone grow by doubling
232
+ if (!cap && n + win.count > acc[fields[0]].length) {
233
+ var size = Math.max(n + win.count, acc[fields[0]].length * 2);
154
234
  fields.forEach(function (f) { var g = new acc[f].constructor(size); g.set(acc[f].subarray(0, n)); acc[f] = g; });
155
235
  }
156
- for (var i = 0; i < fields.length; i++) acc[fields[i]].set(c[fields[i]], n);
157
- n += c.count;
236
+ return { cols: acc, at: n };
158
237
  }
238
+ for await (var c of this._scan(chunkOpts, into)) n += c.count;
159
239
  var out = { count: n };
160
- fields.forEach(function (f) { out[f] = acc ? acc[f].slice(0, n) : new Float64Array(0); });
240
+ fields.forEach(function (f) { out[f] = acc[f].length === n ? acc[f] : acc[f].slice(0, n); });
161
241
  if (opts.dedupe) out = dedupe(out, opts.dedupe, { z: !!opts.dedupeZ });
162
242
  out.bounds = boundsOf(out, opts.localOrigin);
163
243
  out.stats = statsOf(out);
@@ -236,6 +316,18 @@ LasReader.prototype.readPointsToScratch = async function (opts) {
236
316
  return { count: count, fields: ids, types: types, bounds: worldBounds(b, opts.localOrigin) };
237
317
  };
238
318
 
319
+ /**
320
+ * The bytes of an EVLR — big ones are not read by openLas (bytes: null).
321
+ * @param {number} index - into reader.evlrs
322
+ * @returns {Promise<Uint8Array>}
323
+ */
324
+ LasReader.prototype.readEvlrBytes = async function (index) {
325
+ var e = this.evlrs[index];
326
+ if (!e) throw new LasError(ERROR_CODES.INVALID_ARGUMENT, "no EVLR " + index + " (the file has " + this.evlrs.length + ")");
327
+ if (e.bytes) return e.bytes;
328
+ return new Uint8Array(await this._src.read(e.start, e.start + e.length));
329
+ };
330
+
239
331
  /** Close the underlying file (Node). */
240
332
  LasReader.prototype.close = async function () {
241
333
  if (this._src && typeof this._src.close === "function") await this._src.close();