QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgscopcupdate.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscopcupdate.cpp
3 ---------------------
4 begin : January 2025
5 copyright : (C) 2025 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgscopcupdate.h"
17
18#include <fstream>
19#include <iostream>
20
21#include "lazperf/Extractor.hpp"
22#include "lazperf/filestream.hpp"
23#include "lazperf/header.hpp"
24#include "lazperf/readers.hpp"
25#include "lazperf/vlr.hpp"
26#include "lazperf/writers.hpp"
27#include "qgslazdecoder.h"
28
29#include <QString>
30
31using namespace Qt::StringLiterals;
32
35{
38
44 uint64_t offset;
45
51 int32_t byteSize;
52
58 int32_t pointCount;
59};
60
61typedef QVector<HierarchyEntry> HierarchyEntries;
62
63
64HierarchyEntries getHierarchyPage( std::ifstream &file, uint64_t offset, uint64_t size )
65{
67 std::vector<char> buf( 32 );
68 int numEntries = static_cast<int>( size / 32 );
69 file.seekg( static_cast<int64_t>( offset ) );
70 while ( numEntries-- )
71 {
72 file.read( buf.data(), static_cast<long>( buf.size() ) );
73 lazperf::LeExtractor s( buf.data(), buf.size() );
74
76 int d, x, y, z;
77 s >> d >> x >> y >> z;
78 s >> e.offset >> e.byteSize >> e.pointCount;
79 e.key = QgsPointCloudNodeId( d, x, y, z );
80
81 page.push_back( e );
82 }
83 return page;
84}
85
86
87bool QgsCopcUpdate::write( const QString &outputFilename, const QHash<QgsPointCloudNodeId, UpdatedChunk> &updatedChunks )
88{
89 std::ofstream m_f;
90 m_f.open( QgsLazDecoder::toNativePath( outputFilename ), std::ios::out | std::ios::binary );
91
92 // write header and all VLRs all the way to point offset
93 // (then we patch what we need)
94 mFile.seekg( 0 );
95 std::vector<char> allHeaderData;
96 allHeaderData.resize( mHeader.point_offset );
97 mFile.read( allHeaderData.data(), static_cast<long>( allHeaderData.size() ) );
98 m_f.write( allHeaderData.data(), static_cast<long>( allHeaderData.size() ) );
99
100 m_f.write( "XXXXXXXX", 8 ); // placeholder for chunk table offset
101
102 uint64_t currentChunkOffset = mHeader.point_offset + 8;
103 mFile.seekg( static_cast<long>( currentChunkOffset ) ); // this is where first chunk starts
104
105 // now, let's write chunks:
106 // - iterate through original chunk table, write out chunks
107 // - if chunk is updated, use that instead
108 // - keep updating hierarchy as we go
109 // - keep updating chunk table as we go
110
111 QHash<QgsPointCloudNodeId, uint64_t> voxelToNewOffset;
112
113 int chIndex = 0;
114 for ( lazperf::chunk ch : mChunks )
115 {
116 Q_ASSERT( mOffsetToVoxel.contains( currentChunkOffset ) );
117 QgsPointCloudNodeId n = mOffsetToVoxel[currentChunkOffset];
118
119 uint64_t newOffset = m_f.tellp();
120 voxelToNewOffset[n] = newOffset;
121
122 // check whether the chunk is modified
123 if ( updatedChunks.contains( n ) )
124 {
125 const UpdatedChunk &updatedChunk = updatedChunks[n];
126
127 // use updated one and skip in the original file
128 mFile.seekg( static_cast<long>( mFile.tellg() ) + static_cast<long>( ch.offset ) );
129
130 m_f.write( updatedChunk.chunkData.constData(), updatedChunk.chunkData.size() );
131
132 // update sizes
133 mChunks[chIndex].offset = updatedChunk.chunkData.size();
134 }
135 else
136 {
137 // use as is
138 std::vector<char> originalChunkData;
139 originalChunkData.resize( ch.offset );
140 mFile.read( originalChunkData.data(), static_cast<long>( originalChunkData.size() ) );
141 m_f.write( originalChunkData.data(), static_cast<long>( originalChunkData.size() ) );
142 }
143
144 currentChunkOffset += ch.offset;
145 ++chIndex;
146 }
147
148 // write chunk table: size in bytes + point count of each chunk
149
150 const uint64_t newChunkTableOffset = m_f.tellp();
151
152 m_f.write( "\0\0\0\0", 4 ); // chunk table version
153 m_f.write( reinterpret_cast<const char *>( &mChunkCount ), sizeof( mChunkCount ) );
154
155 lazperf::OutFileStream outStream( m_f );
156 lazperf::compress_chunk_table( outStream.cb(), mChunks, true );
157
158 // update hierarchy
159
160 // NOTE: one big assumption we're doing here is that existing hierarchy pages
161 // are packed one after another, with no gaps. if that's not the case, things
162 // will break apart
163
164 const long hierPositionShift = static_cast<long>( m_f.tellp() ) + 60 - static_cast<long>( mHierarchyOffset );
165
166 HierarchyEntry *oldCopcHierarchyBlobEntries = reinterpret_cast<HierarchyEntry *>( mHierarchyBlob.data() );
167 const int nEntries = static_cast<int>( mHierarchyBlob.size() / 32 );
168 for ( int i = 0; i < nEntries; ++i )
169 {
170 HierarchyEntry &e = oldCopcHierarchyBlobEntries[i];
171 if ( e.pointCount > 0 )
172 {
173 // update entry to new offset
174 Q_ASSERT( voxelToNewOffset.contains( e.key ) );
175 e.offset = voxelToNewOffset[e.key];
176
177 if ( updatedChunks.contains( e.key ) )
178 {
179 uint64_t newByteSize = updatedChunks[e.key].chunkData.size();
180 e.byteSize = static_cast<int>( newByteSize );
181 }
182 }
183 else if ( e.pointCount < 0 )
184 {
185 // move hierarchy pages to new offset
186 e.offset += hierPositionShift;
187 }
188 else // pointCount == 0
189 {
190 // nothing to do - byte size and offset should be zero
191 }
192 }
193
194 // write hierarchy eVLR
195
196 const uint64_t newEvlrOffset = m_f.tellp();
197
198 lazperf::evlr_header outCopcHierEvlr;
199 outCopcHierEvlr.reserved = 0;
200 outCopcHierEvlr.user_id = "copc";
201 outCopcHierEvlr.record_id = 1000;
202 outCopcHierEvlr.data_length = mHierarchyBlob.size();
203 outCopcHierEvlr.description = "EPT Hierarchy";
204
205 outCopcHierEvlr.write( m_f );
206 m_f.write( mHierarchyBlob.data(), static_cast<long>( mHierarchyBlob.size() ) );
207
208 // write other eVLRs
209
210 for ( size_t i = 0; i < mEvlrHeaders.size(); ++i )
211 {
212 lazperf::evlr_header evlrHeader = mEvlrHeaders[i];
213 std::vector<char> evlrBody = mEvlrData[i];
214
215 evlrHeader.write( m_f );
216 m_f.write( evlrBody.data(), static_cast<long>( evlrBody.size() ) );
217 }
218
219 // patch header
220
221 m_f.seekp( 235 );
222 m_f.write( reinterpret_cast<const char *>( &newEvlrOffset ), 8 );
223
224 const uint64_t newRootHierOffset = mCopcVlr.root_hier_offset + hierPositionShift;
225 m_f.seekp( 469 );
226 m_f.write( reinterpret_cast<const char *>( &newRootHierOffset ), 8 );
227
228 m_f.seekp( mHeader.point_offset );
229 m_f.write( reinterpret_cast<const char *>( &newChunkTableOffset ), 8 );
230
231 return true;
232}
233
234
235bool QgsCopcUpdate::read( const QString &inputFilename )
236{
237 mInputFilename = inputFilename;
238
239 mFile.open( QgsLazDecoder::toNativePath( inputFilename ), std::ios::binary | std::ios::in );
240 if ( mFile.fail() )
241 {
242 mErrorMessage = u"Could not open file for reading: %1"_s.arg( inputFilename );
243 return false;
244 }
245
246 if ( !readHeader() )
247 return false;
248
249 readChunkTable();
250 readHierarchy();
251
252 return true;
253}
254
255
256bool QgsCopcUpdate::readHeader()
257{
258 // read header and COPC VLR
259 mHeader = lazperf::header14::create( mFile );
260 if ( !mFile )
261 {
262 mErrorMessage = u"Error reading COPC header"_s;
263 return false;
264 }
265
266 lazperf::vlr_header vh = lazperf::vlr_header::create( mFile );
267 mCopcVlr = lazperf::copc_info_vlr::create( mFile );
268
269 int baseCount = lazperf::baseCount( mHeader.point_format_id );
270 if ( baseCount == 0 )
271 {
272 mErrorMessage = u"Bad point record format: %1"_s.arg( mHeader.point_format_id );
273 return false;
274 }
275
276 return true;
277}
278
279
280void QgsCopcUpdate::readChunkTable()
281{
282 uint64_t chunkTableOffset;
283
284 mFile.seekg( mHeader.point_offset );
285 mFile.read( reinterpret_cast<char *>( &chunkTableOffset ), sizeof( chunkTableOffset ) );
286 mFile.seekg( static_cast<long>( chunkTableOffset ) + 4 ); // The first 4 bytes are the version, then the chunk count.
287 mFile.read( reinterpret_cast<char *>( &mChunkCount ), sizeof( mChunkCount ) );
288
289 //
290 // read chunk table
291 //
292
293 bool variable = true;
294
295 // TODO: not sure why, but after decompress_chunk_table() the input stream seems to be dead, so we create a temporary one
296 std::ifstream copcFileTmp;
297 copcFileTmp.open( QgsLazDecoder::toNativePath( mInputFilename ), std::ios::binary | std::ios::in );
298 copcFileTmp.seekg( mFile.tellg() );
299 lazperf::InFileStream copcInFileStream( copcFileTmp );
300
301 mChunks = lazperf::decompress_chunk_table( copcInFileStream.cb(), mChunkCount, variable );
302 std::vector<lazperf::chunk> chunksWithAbsoluteOffsets;
303 uint64_t nextChunkOffset = mHeader.point_offset + 8;
304 for ( lazperf::chunk ch : mChunks )
305 {
306 chunksWithAbsoluteOffsets.push_back( { nextChunkOffset, ch.count } );
307 nextChunkOffset += ch.offset;
308 }
309}
310
311
312void QgsCopcUpdate::readHierarchy()
313{
314 // get all hierarchy pages
315
316 HierarchyEntries childEntriesToProcess;
317 childEntriesToProcess.push_back( HierarchyEntry { QgsPointCloudNodeId( 0, 0, 0, 0 ), mCopcVlr.root_hier_offset, static_cast<int32_t>( mCopcVlr.root_hier_size ), -1 } );
318
319 while ( !childEntriesToProcess.empty() )
320 {
321 HierarchyEntry childEntry = childEntriesToProcess.back();
322 childEntriesToProcess.pop_back();
323
324 HierarchyEntries page = getHierarchyPage( mFile, childEntry.offset, childEntry.byteSize );
325
326 for ( const HierarchyEntry &e : page )
327 {
328 if ( e.pointCount > 0 ) // it's a non-empty node
329 {
330 Q_ASSERT( !mOffsetToVoxel.contains( e.offset ) );
331 mOffsetToVoxel[e.offset] = e.key;
332 }
333 else if ( e.pointCount < 0 ) // referring to a child page
334 {
335 childEntriesToProcess.push_back( e );
336 }
337 }
338 }
339
340 lazperf::evlr_header evlr1;
341 mFile.seekg( static_cast<long>( mHeader.evlr_offset ) );
342
343 mHierarchyOffset = 0; // where the hierarchy eVLR payload starts
344
345 for ( uint32_t i = 0; i < mHeader.evlr_count; ++i )
346 {
347 evlr1.read( mFile );
348 if ( evlr1.user_id == "copc" && evlr1.record_id == 1000 )
349 {
350 mHierarchyBlob.resize( evlr1.data_length );
351 mHierarchyOffset = mFile.tellg();
352 mFile.read( mHierarchyBlob.data(), static_cast<long>( evlr1.data_length ) );
353 }
354 else
355 {
356 // keep for later
357 mEvlrHeaders.push_back( evlr1 );
358 std::vector<char> evlrBlob;
359 evlrBlob.resize( evlr1.data_length );
360 mFile.read( evlrBlob.data(), static_cast<long>( evlrBlob.size() ) );
361 mEvlrData.emplace_back( std::move( evlrBlob ) );
362 }
363 }
364
365 Q_ASSERT( !mHierarchyBlob.empty() );
366}
367
368
369bool QgsCopcUpdate::writeUpdatedFile( const QString &inputFilename, const QString &outputFilename, const QHash<QgsPointCloudNodeId, UpdatedChunk> &updatedChunks, QString *errorMessage )
370{
371 QgsCopcUpdate copcUpdate;
372 if ( !copcUpdate.read( inputFilename ) )
373 {
374 if ( errorMessage )
375 *errorMessage = copcUpdate.errorMessage();
376 return false;
377 }
378
379 if ( !copcUpdate.write( outputFilename, updatedChunks ) )
380 {
381 if ( errorMessage )
382 *errorMessage = copcUpdate.errorMessage();
383 return false;
384 }
385
386 return true;
387}
Handles update operations to a COPC file.
QString errorMessage() const
Returns error message.
static bool writeUpdatedFile(const QString &inputFilename, const QString &outputFilename, const QHash< QgsPointCloudNodeId, UpdatedChunk > &updatedChunks, QString *errorMessage=nullptr)
Convenience function to do the whole process in one go: load a COPC file, then write a new COPC file ...
bool read(const QString &inputFilename)
Reads input COPC file and initializes all the members.
bool write(const QString &outputFilename, const QHash< QgsPointCloudNodeId, UpdatedChunk > &updatedChunks)
Writes a COPC file with updated chunks.
Represents an indexed point cloud node's position in octree.
QVector< HierarchyEntry > HierarchyEntries
HierarchyEntries getHierarchyPage(std::ifstream &file, uint64_t offset, uint64_t size)
Keeps one entry of COPC hierarchy.
QgsPointCloudNodeId key
Key of the data to which this entry corresponds.
uint64_t offset
Absolute offset to the data chunk if the pointCount > 0.
int32_t pointCount
If > 0, represents the number of points in the data chunk.
int32_t byteSize
Size of the data chunk in bytes (compressed size) if the pointCount > 0.
Keeps information how points of a single chunk has been modified.
QByteArray chunkData
Data of the chunk (compressed already with LAZ compressor).