Debian Codegraph @

src/thirdparty/PoissonRecon/PoissonRecon.client.inl

raw
1 /*
2 Copyright (c) 2023, Michael Kazhdan
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8 Redistributions of source code must retain the above copyright notice, this list of
9 conditions and the following disclaimer. Redistributions in binary form must reproduce
10 the above copyright notice, this list of conditions and the following disclaimer
11 in the documentation and/or other materials provided with the distribution.
12
13 Neither the name of the Johns Hopkins University nor the names of its contributors
14 may be used to endorse or promote products derived from this software without specific
15 prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
18 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
20 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
22 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 DAMAGE.
27 */
28
29 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
30 struct Client
31 {
32 typedef typename FEMTree< Dim , Real >::template DensityEstimator< Reconstructor::WeightDegree > DensityEstimator;
33 typedef typename FEMTree< Dim , Real >::template ApproximatePointInterpolationInfo< Real , 0 , Reconstructor::Poisson::ConstraintDual< Dim , Real > , Reconstructor::Poisson::SystemDual< Dim , Real > > ApproximatePointInterpolationInfo;
34 typedef IsotropicUIntPack< Dim , FEMDegreeAndBType< Degree , BType >::Signature > Sigs;
35 typedef IsotropicUIntPack< Dim , Degree > Degrees;
36 typedef IsotropicUIntPack< Dim , FEMDegreeAndBType< Reconstructor::Poisson::NormalDegree , DerivativeBoundary< BType , 1 >::BType >::Signature > NormalSigs;
37 static const unsigned int DataSig = FEMDegreeAndBType< Reconstructor::DataDegree , BOUNDARY_FREE >::Signature;
38 typedef VertexFactory::DynamicFactory< Real > AuxDataFactory;
39 typedef typename AuxDataFactory::VertexType AuxData;
40 typedef VertexFactory::Factory< Real , VertexFactory::PositionFactory< Real , Dim > , VertexFactory::Factory< Real , VertexFactory::NormalFactory< Real , Dim > , AuxDataFactory > > InputSampleFactory;
41 typedef VertexFactory::Factory< Real , VertexFactory::NormalFactory< Real , Dim > , AuxDataFactory > InputSampleDataFactory;
42 typedef DirectSum< Real , Point< Real , Dim > , typename AuxDataFactory::VertexType > InputSampleDataType;
43 typedef DirectSum< Real , Point< Real , Dim > , InputSampleDataType > InputSampleType;
44 typedef InputDataStream< InputSampleType > InputPointStream;
45 typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > FEMTreeNode;
46 using BoundaryData = std::conditional_t< Dim==3 , typename LevelSetExtractor< Real , 2 , Point< Real , 2 > >::TreeSliceValuesAndVertexPositions , char >;
47
48 ~Client( void );
49
50 static std::function< int ( Point< Real , Dim > ) > PointDepthFunctor( Real begin , Real end , unsigned int padSize , unsigned int minDepth , unsigned int maxDepth );
51 protected:
52 unsigned int _index;
53 SocketStream _serverSocket;
54 std::pair< unsigned int , unsigned int > _range;
55 XForm< Real , Dim+1 > _modelToUnitCube;
56 FEMTree< Dim , Real > _tree;
57
58 DensityEstimator *_density; // Phases [1,7]
59 SparseNodeData< Point< Real , Dim > , NormalSigs > *_normalInfo , *_paddedNormalInfo; // Phases [1,3]
60 std::vector< typename FEMTree< Dim , Real >::PointSample > _samples; // Phases [1,5]
61 std::vector< typename FEMTree< Dim , Real >::PointSample > _paddedSamples; // Phases [1,3]
62 std::vector< InputSampleDataType > _sampleData , _paddedSampleData; // Phases [1,3]
63 DenseNodeData< Real , Sigs > _constraints; // Phases [3,5]
64 DenseNodeData< Real , Sigs > _solution; // Phases [5,7]
65 ApproximatePointInterpolationInfo *_iInfo; // Phases [3,5]
66 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > _auxDataField; // Phases [3,7]
67
68 static std::pair< unsigned int , unsigned int > _PaddedRange( std::pair< unsigned int , unsigned int > range , unsigned int depth , unsigned int padSize );
69
70 struct _State3
71 {
72 _State3( void ) : subNodes( NullPointer( FEMTreeNode ) ) {}
73 ~_State3( void ){ DeletePointer( subNodes ); }
74 Pointer( FEMTreeNode ) subNodes;
75 size_t subNodeCount;
76 DenseNodeData< Real , Sigs > constraints;
77 ApproximatePointInterpolationInfo iInfo;
78 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > auxDataField;
79 };
80 struct _State5
81 {
82 using Data = ProjectiveData< AuxData , Real >;
83
84 _State5( void ) : auxDataField(NULL) , subNodes( NullPointer( FEMTreeNode ) ) {}
85 ~_State5( void )
86 {
87 DeletePointer( subNodes );
88 delete auxDataField;
89 }
90
91 struct BoundaryInfo
92 {
93 using SliceSigs = typename Sigs::Transpose::Rest::Transpose;
94 FEMTree< Dim-1 , Real > *tree;
95 DenseNodeData< Real , SliceSigs > solution , dSolution;
96 BoundaryInfo( void ) : tree(NULL) {}
97 ~BoundaryInfo( void ){ delete tree; }
98 };
99
100 Pointer( FEMTreeNode ) subNodes;
101 DenseNodeData< Real , Sigs > solution;
102 SparseNodeData< Data , IsotropicUIntPack< Dim , DataSig > > *auxDataField;
103 std::pair< BoundaryInfo , BoundaryInfo > boundaryInfo;
104 };
105 struct _State7
106 {
107 BoundaryData *backBoundary , *frontBoundary;
108 std::vector< std::vector< Real > > backDValues , frontDValues;
109 Real isoValue;
110
111 _State7( void ) : backBoundary(NULL) , frontBoundary(NULL) , isoValue((Real)0.5){}
112 ~_State7( void )
113 {
114 delete backBoundary;
115 delete frontBoundary;
116 }
117 };
118
119 PhaseInfo _phase1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo, Profiler &profiler );
120 PhaseInfo _phase3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State3 &state3 , Profiler &profiler );
121 PhaseInfo _phase5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler );
122 PhaseInfo _phase7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler );
123
124 size_t _receive1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler );
125 void _process1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Point< Real , 2 > , Real > &pointDepthAndWeight , std::pair< size_t , size_t > &nodeCounts , Profiler &profiler );
126 size_t _send1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > pointWeight , std::pair< size_t , size_t > nodeCounts , Profiler &profiler );
127
128 size_t _receive3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > &cumulativePointWeight , Profiler &profiler );
129 void _process3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > cumulativePointWeight , _State3 &state3 , Profiler &profiler );
130 size_t _send3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , const _State3 &state3 , Profiler &profiler );
131
132 size_t _receive5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State5 &state5 , Profiler &profiler );
133 std::pair< double , double > _process5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State5 &state5 , Profiler &profiler );
134 size_t _send5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , const _State5 &state5 , Profiler &profiler );
135
136 size_t _receive7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , Profiler &profiler );
137 void _process7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , Profiler &profiler );
138
139 Client( void );
140 Client( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , BinaryStream &stream , unsigned int phase );
141 void _write( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , BinaryStream &stream , unsigned int phase ) const;
142
143 template< typename _Real , unsigned int _Dim , BoundaryType _BType , unsigned int _Degree >
144 friend void RunClient( std::vector< Socket > &serverSockets , unsigned int sampleMS );
145
146 template< bool HasGradients , bool HasDensity >
147 void _writeMeshWithData( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , XForm< Real , Dim+1 > unitCubeToModel );
148 };
149
150 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
151 void RunClient( std::vector< Socket > &serverSockets , unsigned int sampleMS )
152 {
153 std::vector< SocketStream > serverSocketStreams( serverSockets.size() );
154 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ ) serverSocketStreams[i] = SocketStream( serverSockets[i] );
155 Profiler profiler( sampleMS );
156 std::vector< FileStream > cacheFiles;
157 ClientReconstructionInfo< Real , Dim > clientReconInfo;
158 std::vector< unsigned int > clientIndices( serverSocketStreams.size() );
159
160 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ ) clientReconInfo = ClientReconstructionInfo< Real , Dim >( serverSocketStreams[i] );
161 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ ) serverSocketStreams[i].read( clientIndices[i] );
162
163 if( serverSocketStreams.size()>1 ) for( unsigned int idx=0 ; idx<serverSocketStreams.size() ; idx++ ) cacheFiles.emplace_back( std::tmpfile() );
164
165 Client< Real , Dim , BType , Degree > *client = NULL;
166 if( serverSocketStreams.size()==1 )
167 {
168 client = new Client< Real , Dim , BType , Degree >();
169 client->_serverSocket = serverSocketStreams[0];
170 client->_index = clientIndices[0];
171 }
172
173 // Phase 1
174 {
175 PhaseInfo phaseInfo;
176 double cacheTime = 0;
177 size_t cacheBytes = 0;
178
179 profiler.reset();
180 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ )
181 {
182 if( serverSocketStreams.size()>1 )
183 {
184 client = new Client< Real , Dim , BType , Degree >();
185 client->_serverSocket = serverSocketStreams[i];
186 client->_index = clientIndices[i];
187 }
188
189 phaseInfo += client->_phase1( clientReconInfo , profiler );
190
191 if( serverSocketStreams.size()>1 )
192 {
193 Timer timer;
194
195 cacheFiles[i].reset();
196 cacheFiles[i].ioBytes = 0;
197 client->_write( clientReconInfo , cacheFiles[i] , 1 );
198 cacheBytes += cacheFiles[i].ioBytes;
199 delete client;
200 client = NULL;
201
202 cacheTime += timer.wallTime();
203 }
204 }
205 if( clientReconInfo.verbose>0 )
206 {
207 StreamFloatPrecision sfp( std::cout , 1 );
208 std::cout << ReceiveDataString( 1 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
209 std::cout << "[PROCESS 1] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
210 std::cout << SendDataString( 1 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
211 if( serverSocketStreams.size()>1 ) std::cout << "[CACHE 1] : " << cacheTime << " (s) , " << (cacheBytes>>20) << " (MB)" << std::endl;
212 }
213 }
214
215 // Phase 3
216 {
217 PhaseInfo phaseInfo;
218 double cacheTime = 0;
219 size_t cacheBytes = 0;
220
221 profiler.reset();
222 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ )
223 {
224 typename Client< Real , Dim , BType , Degree >::_State3 state3;
225
226 if( serverSocketStreams.size()>1 )
227 {
228 Timer timer;
229 cacheFiles[i].ioBytes = 0;
230 cacheFiles[i].reset();
231 client = new Client< Real , Dim , BType , Degree >( clientReconInfo , cacheFiles[i] , 3 );
232 cacheTime += timer.wallTime();
233 cacheBytes += cacheFiles[i].ioBytes;
234 client->_serverSocket = serverSocketStreams[i];
235 }
236
237 phaseInfo += client->_phase3( clientReconInfo , state3 , profiler );
238
239 if( serverSocketStreams.size()>1 )
240 {
241 Timer timer;
242 cacheFiles[i].ioBytes = 0;
243 cacheFiles[i].reset();
244 client->_write( clientReconInfo , cacheFiles[i] , 3 );
245 delete client;
246 client = NULL;
247 cacheTime += timer.wallTime();
248 cacheBytes += cacheFiles[i].ioBytes;
249 }
250 }
251
252 if( clientReconInfo.verbose>0 )
253 {
254 StreamFloatPrecision sfp( std::cout , 1 );
255 std::cout << ReceiveDataString( 3 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
256 std::cout << "[PROCESS 3] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
257 std::cout << SendDataString( 3 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
258 if( serverSocketStreams.size()>1 ) std::cout << "[CACHE 3] : " << cacheTime << " (s) , " << (cacheBytes>>20) << " (MB)" << std::endl;
259 }
260 }
261
262 // Phase 5
263 {
264 PhaseInfo phaseInfo;
265 double cacheTime = 0;
266 size_t cacheBytes = 0;
267
268 profiler.reset();
269 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ )
270 {
271 if( serverSocketStreams.size()>1 )
272 {
273 Timer timer;
274 cacheFiles[i].ioBytes = 0;
275 cacheFiles[i].reset();
276 client = new Client< Real , Dim , BType , Degree >( clientReconInfo , cacheFiles[i] , 5 );
277 cacheTime += timer.wallTime();
278 cacheBytes += cacheFiles[i].ioBytes;
279 client->_serverSocket = serverSocketStreams[i];
280 }
281
282 phaseInfo += client->_phase5( clientReconInfo , profiler );
283
284 if( serverSocketStreams.size()>1 )
285 {
286 Timer timer;
287 cacheFiles[i].ioBytes = 0;
288 cacheFiles[i].reset();
289 client->_write( clientReconInfo , cacheFiles[i] , 5 );
290 delete client;
291 client = NULL;
292 cacheTime += timer.wallTime();
293 cacheBytes += cacheFiles[i].ioBytes;
294 }
295 }
296
297 if( clientReconInfo.verbose>0 )
298 {
299 StreamFloatPrecision sfp( std::cout , 1 );
300 std::cout << ReceiveDataString( 5 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
301 std::cout << "[PROCESS 5] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
302 std::cout << SendDataString( 5 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
303 if( serverSocketStreams.size()>1 ) std::cout << "[CACHE 5] : " << cacheTime << " (s) , " << (cacheBytes>>20) << " (MB)" << std::endl;
304 }
305 }
306 // Phase 7
307 {
308 PhaseInfo phaseInfo;
309 double cacheTime = 0;
310 size_t cacheBytes = 0;
311
312 profiler.reset();
313 for( unsigned int i=0 ; i<serverSocketStreams.size() ; i++ )
314 {
315 if( serverSocketStreams.size()>1 )
316 {
317 Timer timer;
318 cacheFiles[i].ioBytes = 0;
319 cacheFiles[i].reset();
320 client = new Client< Real , Dim , BType , Degree >( clientReconInfo , cacheFiles[i] , 7 );
321 cacheTime += timer.wallTime();
322 cacheBytes += cacheFiles[i].ioBytes;
323 client->_serverSocket = serverSocketStreams[i];
324 }
325
326 phaseInfo += client->_phase7( clientReconInfo , profiler );
327
328 if( serverSocketStreams.size()>1 )
329 {
330 delete client;
331 client = NULL;
332 }
333 }
334
335 if( clientReconInfo.verbose>0 )
336 {
337 StreamFloatPrecision sfp( std::cout , 1 );
338 std::cout << ReceiveDataString( 7 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
339 std::cout << "[PROCESS 7] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
340 if( serverSocketStreams.size()>1 ) std::cout << "[CACHE 7] : " << cacheTime << " (s) , " << (cacheBytes>>20) << " (MB)" << std::endl;
341 }
342 }
343 if( serverSocketStreams.size()==1 ) delete client;
344 }
345
346 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
347 Client< Real , Dim , BType , Degree >::Client( void )
348 : _serverSocket( _INVALID_SOCKET_ ) , _tree( MEMORY_ALLOCATOR_BLOCK_SIZE ) , _density(NULL) , _normalInfo(NULL) , _paddedNormalInfo(NULL) , _iInfo(NULL) , _index(-1)
349 {
350 }
351
352 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
353 Client< Real , Dim , BType , Degree >::~Client( void )
354 {
355 if( _density ) delete _density;
356 if( _normalInfo ) delete _normalInfo;
357 if( _paddedNormalInfo ) delete _paddedNormalInfo;
358 if( _iInfo ) delete _iInfo;
359 }
360
361 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
362 std::pair< unsigned int , unsigned int > Client< Real , Dim , BType , Degree >::_PaddedRange( std::pair< unsigned int , unsigned int > range , unsigned int depth , unsigned int padSize )
363 {
364 std::pair< unsigned int , unsigned int > paddedRange;
365 if( range.first<=padSize ) paddedRange.first = 0;
366 else paddedRange.first = range.first - padSize;
367 if( range.second+padSize>(1u<<depth) ) paddedRange.second = (1<<depth);
368 else paddedRange.second = range.second + padSize;
369 return paddedRange;
370 }
371
372 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
373 std::function< int ( Point< Real , Dim > ) > Client< Real , Dim , BType , Degree >::PointDepthFunctor( Real begin , Real end , unsigned int padSize , unsigned int minDepth , unsigned int maxDepth )
374 {
375 // Using a padding size of two should do the trick. And it does, but only if we don't use adaptive
376 const double Log2 = log(2.);
377 return [begin,end,padSize,minDepth,maxDepth,Log2]( Point< Real , Dim > p )
378 {
379 // For interior points, add to the full depth
380 if( p[Dim-1]>=begin && p[Dim-1]<=end ) return (int)maxDepth;
381 else if( p[Dim-1]<begin )
382 {
383 // Solve for the largest d s.t.:
384 // p[Dim-1] >= b-padSize/(1<<d)
385 // b-p[Dim-1] <= padSize/(1<<d)
386 // (b-p[Dim-1])/padSize <= 1/(1<<d)
387 // padSize/(b-p[Dim-1]) >= (1<<d)
388 // log_2( padSize/(b-p[Dim-1]) ) >= d
389 // => d = floor( log_2( padSize/(b-p[Dim-1]) ) )
390 return std::max< int >( std::min< int >( (int)floor( log( padSize/( begin - p[Dim-1] ) ) / Log2 ) , (int)maxDepth ) , (int)minDepth );
391 }
392 else if( p[Dim-1]>end )
393 {
394 // Solve for the largest d s.t.:
395 // p[Dim-1] <= e+padSize/(1<<d)
396 // p[Dim-1]-e <= padSize/(1<<d)
397 // (p[Dim-1]-d)/padSize <= 1/(1<<d)
398 // padSize/(p[Dim-1]-e) >= (1<<d)
399 // log_2( padSize/(p[Dim-1]-e) ) >= d
400 // => d = floor( log_2( padSize/(p[Dim-1]-e) ) )
401 return std::max< int >( std::min< int >( (int)floor( log( padSize/( p[Dim-1] - end ) ) / Log2 ) , (int)maxDepth ) , (int)minDepth );
402 }
403 else return -1;
404 };
405 }
406
407 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
408 PhaseInfo Client< Real , Dim , BType , Degree >::_phase1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler )
409 {
410 PhaseInfo phaseInfo;
411 ProjectiveData< Point< Real , 2 > , Real > pointDepthAndWeight;
412 std::pair< size_t , size_t > nodeCounts;
413
414 {
415 Timer timer;
416 phaseInfo.readBytes += _receive1( clientReconInfo , profiler );
417 phaseInfo.readTime += timer.wallTime();
418 }
419 if( clientReconInfo.verbose>1 ) std::cout << "Range[" << _index << "]: [ " << _range.first << " , " << _range.second << " ) +/- " << clientReconInfo.padSize << std::endl;
420
421 {
422 Timer timer;
423 _process1( clientReconInfo , pointDepthAndWeight , nodeCounts , profiler );
424 phaseInfo.processTime += timer.wallTime();
425 }
426
427 ProjectiveData< Real , Real > pointWeight;
428 pointWeight.data = pointDepthAndWeight.data[1];
429 pointWeight.weight = pointDepthAndWeight.weight;
430 {
431 Timer timer;
432 phaseInfo.writeBytes += _send1( clientReconInfo , pointWeight , nodeCounts , profiler );
433 phaseInfo.writeTime += timer.wallTime();
434 }
435 return phaseInfo;
436 }
437
438 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
439 size_t Client< Real , Dim , BType , Degree >::_receive1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler )
440 {
441 ClientServerStream< true > serverStream( _serverSocket , _index , clientReconInfo );
442 serverStream.ioBytes = 0;
443
444 if( !serverStream.read( _modelToUnitCube ) ) MK_THROW( "Failed to read model-to-unit-cube transform" );
445 serverStream.read( _range );
446 profiler.update();
447
448 return serverStream.ioBytes;
449 }
450
451 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
452 size_t Client< Real , Dim , BType , Degree >::_send1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > pointWeight , std::pair< size_t , size_t > nodeCounts , Profiler &profiler )
453 {
454 ClientServerStream< false > serverStream( _serverSocket , _index , clientReconInfo );
455 serverStream.ioBytes = 0;
456 serverStream.write( pointWeight );
457 serverStream.write( nodeCounts );
458 profiler.update();
459 return serverStream.ioBytes;
460 }
461
462 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
463 void Client< Real , Dim , BType , Degree >::_process1( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Point< Real , 2 > , Real > &pointDepthAndWeight , std::pair< size_t , size_t > &nodeCounts , Profiler &profiler )
464 {
465 std::pair< unsigned int , unsigned int > paddedRange = _PaddedRange( _range , clientReconInfo.sharedDepth , clientReconInfo.padSize );
466 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
467 InputSampleFactory inputSampleFactory( VertexFactory::PositionFactory< Real , Dim >() , InputSampleDataFactory( VertexFactory::NormalFactory< Real , Dim >() , auxDataFactory ) );
468 InputSampleDataFactory inputSampleDataFactory( VertexFactory::NormalFactory< Real , Dim >() , auxDataFactory );
469
470 size_t pointCount = 0 , paddedPointCount = 0;
471 ProjectiveData< Point< Real , 2 > , Real > paddedPointDepthAndWeight;
472 paddedPointDepthAndWeight.data = Point< Real , 2 >();
473 paddedPointDepthAndWeight.weight = 0;
474
475 unsigned int beginIndex=_range.first , endIndex = _range.second;
476 unsigned int beginPaddedIndex = paddedRange.first , endPaddedIndex = paddedRange.second;
477
478 pointDepthAndWeight.data = Point< Real , 2 >();
479 pointDepthAndWeight.weight = 0;
480
481 FEMTreeInitializer< Dim , Real >::Initialize( _tree.spaceRoot() , clientReconInfo.baseDepth , []( int , int[] ){ return true; } , _tree.nodeAllocators[0] , _tree.initializer() );
482
483
484 #ifdef ADAPTIVE_PADDING
485 std::function< int ( Point< Real , Dim > ) > pointDepthFunctor = PointDepthFunctor( (Real)_range.first/(1<<clientReconInfo.sharedDepth) , (Real)_range.second/(1<<clientReconInfo.sharedDepth) , clientReconInfo.padSize , clientReconInfo.kernelDepth , clientReconInfo.reconstructionDepth );
486 #endif // ADAPTIVE_PADDING
487 // Read in the samples (and color data)
488 {
489 Timer timer;
490 auto ProcessData = [&]( const Point< Real , Dim > &p , InputSampleDataType &d )
491 {
492 Real l = (Real)Length( d.template get<0>() );
493 if( !l || !std::isfinite( l ) ) return (Real)-1.;
494 d.template get<0>() /= l;
495 return clientReconInfo.confidence ? l : (Real)1.;
496 };
497
498 std::vector< InputDataStream< typename InputSampleFactory::VertexType > * > pointStreams( endPaddedIndex - beginPaddedIndex , NULL );
499 auto PointStreamFunctor = [&]( unsigned int idx )
500 {
501 std::string fileName = PointPartition::FileName( clientReconInfo.header , idx , 1<<clientReconInfo.sharedDepth , clientReconInfo.filesPerDir );
502
503 fileName = PointPartition::FileDir( clientReconInfo.inDir , fileName );
504 pointStreams[idx-beginPaddedIndex] = new PointPartition::BufferedBinaryInputDataStream< InputSampleFactory >( fileName.c_str() , inputSampleFactory , clientReconInfo.bufferSize );
505 };
506 {
507 std::vector< std::thread > pointStreamThreads;
508 pointStreamThreads.reserve( endPaddedIndex - beginPaddedIndex );
509 for( unsigned int i=beginPaddedIndex ; i<endPaddedIndex ; i++ ) pointStreamThreads.emplace_back( PointStreamFunctor , i );
510 for( unsigned int i=0 ; i<( endPaddedIndex - beginPaddedIndex ) ; i++ ) pointStreamThreads[i].join();
511 }
512
513 using MultiPointStream = MultiInputDataStream< typename InputSampleFactory::VertexType >;
514
515 using ExternalType = std::tuple< Point< Real , Dim > , InputSampleDataType >;
516 using InternalType = std::tuple< typename InputSampleFactory::VertexType >;
517 auto converter = []( const InternalType &iType )
518 {
519 ExternalType xType;
520 std::get< 0 >( xType ) = std::get< 0 >( iType ).template get<0>();
521 std::get< 1 >( xType ).template get<0>() = std::get< 0 >( iType ).template get<1>().template get<0>();
522 std::get< 1 >( xType ).template get<1>() = std::get< 0 >( iType ).template get<1>().template get<1>();
523 return xType;
524 };
525
526 auto ProcessInteriorPointSlabs = [&]( typename FEMTreeInitializer< Dim , Real >::StreamInitializationData &sid , unsigned int start , unsigned int end )
527 {
528 if( start==end ) return;
529 MultiPointStream pointStream( &pointStreams[start-beginPaddedIndex] , end - start );
530 typename InputSampleDataFactory::VertexType zeroData = inputSampleDataFactory();
531 InputDataStreamConverter< InternalType , ExternalType > _pointStream( pointStream , converter , inputSampleFactory() );
532 pointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , _samples , _sampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
533 profiler.update();
534 };
535 auto ProcessPadPointSlabs = [&]( typename FEMTreeInitializer< Dim , Real >::StreamInitializationData &sid , unsigned int start , unsigned int end )
536 {
537 if( start==end ) return;
538 MultiPointStream pointStream( &pointStreams[start-beginPaddedIndex] , end - start );
539 typename InputSampleDataFactory::VertexType zeroData = inputSampleDataFactory();
540 InputDataStreamConverter< InternalType , ExternalType > _pointStream( pointStream , converter , inputSampleFactory() );
541 #ifdef ADAPTIVE_PADDING
542 paddedPointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , pointDepthFunctor , _paddedSamples , _paddedSampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
543 #else // !ADAPTIVE_PADDING
544 paddedPointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , _paddedSamples , _paddedSampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
545 #endif // ADAPTIVE_PADDING
546 profiler.update();
547 };
548
549 auto ProcessPointSlab = [&]( typename FEMTreeInitializer< Dim , Real >::StreamInitializationData &sid , unsigned int idx )
550 {
551 InputDataStream< typename InputSampleFactory::VertexType > &pointStream = *pointStreams[idx-beginPaddedIndex];
552
553 if( idx>=beginIndex && idx<endIndex )
554 {
555 typename InputSampleDataFactory::VertexType zeroData = inputSampleDataFactory();
556 InputDataStreamConverter< InternalType , ExternalType > _pointStream( pointStream , converter , inputSampleFactory() );
557 pointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , _samples , _sampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
558 }
559 else
560 {
561 typename InputSampleDataFactory::VertexType zeroData = inputSampleDataFactory();
562 InputDataStreamConverter< InternalType , ExternalType > _pointStream( pointStream , converter , inputSampleFactory() );
563 #ifdef ADAPTIVE_PADDING
564 paddedPointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , pointDepthFunctor , _paddedSamples , _paddedSampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
565 #else // !ADAPTIVE_PADDING
566 paddedPointCount += FEMTreeInitializer< Dim , Real >::template Initialize< InputSampleDataType >( sid , _tree.spaceRoot() , _pointStream , zeroData , clientReconInfo.reconstructionDepth , _paddedSamples , _paddedSampleData , _tree.nodeAllocators[0] , _tree.initializer() , ProcessData );
567 #endif // ADAPTIVE_PADDING
568 }
569 profiler.update();
570 };
571
572 {
573 typename FEMTreeInitializer< Dim , Real >::StreamInitializationData sid;
574 ProcessInteriorPointSlabs( sid , beginIndex , endIndex );
575 }
576 nodeCounts.first = _tree.spaceRoot().nodes();
577
578 {
579 typename FEMTreeInitializer< Dim , Real >::StreamInitializationData sid;
580 ProcessPadPointSlabs( sid , beginPaddedIndex , beginIndex );
581 ProcessPadPointSlabs( sid , endIndex , endPaddedIndex );
582 }
583 for( unsigned int i=0 ; i<pointStreams.size() ; i++ ) delete pointStreams[i];
584
585
586
587 nodeCounts.second = _tree.spaceRoot().nodes();
588
589 if( clientReconInfo.verbose>1 ) std::cout << "Input Points / Padded Input Points / Samples / Padded Samples: " << pointCount << " / " << paddedPointCount << " / " << _samples.size() << " / " << _paddedSamples.size() << std::endl;
590 if( clientReconInfo.verbose>1 ) std::cout << "# Read input into tree: " << timer << std::endl;
591 }
592
593 if( clientReconInfo.verbose>1 ) std::cout << "Nodes [Initialized]: " << _tree.allNodes() << std::endl;
594
595 // Get the kernel density estimator
596 {
597 Timer timer;
598 _density = _tree.template setDensityEstimator< 1 , Reconstructor::WeightDegree >( _samples , clientReconInfo.kernelDepth , clientReconInfo.samplesPerNode );
599 #ifdef ADAPTIVE_PADDING
600 _tree.template updateDensityEstimator< 1 , Reconstructor::WeightDegree >( *_density , _paddedSamples , 0 , clientReconInfo.kernelDepth , pointDepthFunctor );
601 #else // !ADAPTIVE_PADDING
602 _tree.template updateDensityEstimator< 1 , Reconstructor::WeightDegree >( *_density , _paddedSamples , 0 , clientReconInfo.kernelDepth );
603 #endif // ADAPTIVE_PADDING
604 profiler.update();
605 if( clientReconInfo.verbose>1 ) std::cout << "# Got kernel density: " << timer << std::endl;
606 }
607
608 if( clientReconInfo.verbose>1 ) std::cout << "Nodes [Density Estimator]: " << _tree.allNodes() << std::endl;
609
610 // Transform the Hermite samples into a vector field
611 {
612 Timer timer;
613 _normalInfo = new SparseNodeData< Point< Real , Dim > , NormalSigs >();
614 _paddedNormalInfo = new SparseNodeData< Point< Real , Dim > , NormalSigs >();
615
616 std::function< bool ( InputSampleDataType , Point< Real , Dim >& ) > ConversionFunction = []( InputSampleDataType in , Point< Real , Dim > &out )
617 {
618 Point< Real , Dim > n = in.template get<0>();
619 Real l = (Real)Length( n );
620 // It is possible that the samples have non-zero normals but there are two co-located samples with negative normals...
621 if( !l ) return false;
622 out = n / l;
623 return true;
624 };
625
626 {
627 *_normalInfo = _tree.setInterpolatedDataField( Point< Real , Dim >() , NormalSigs() , _samples , _sampleData , _density , clientReconInfo.sharedDepth , clientReconInfo.reconstructionDepth , (Real)0 , pointDepthAndWeight , ConversionFunction );
628 if( clientReconInfo.verbose>1 ) std::cout << "Nodes [Interior Data Field " << _normalInfo->size() << " / " << _normalInfo->reserved() << "]: " << _tree.allNodes() << std::endl;
629 #ifdef ADAPTIVE_PADDING
630 *_paddedNormalInfo = _tree.setInterpolatedDataField( Point< Real , Dim >() , NormalSigs() , _paddedSamples , _paddedSampleData , _density , clientReconInfo.sharedDepth , clientReconInfo.reconstructionDepth , pointDepthFunctor , (Real)0 , paddedPointDepthAndWeight , ConversionFunction );
631 #else // !ADAPTIVE_PADDING
632 *_paddedNormalInfo = _tree.setInterpolatedDataField( Point< Real , Dim >() , NormalSigs() , _paddedSamples , _paddedSampleData , _density , clientReconInfo.sharedDepth , clientReconInfo.reconstructionDepth , (Real)0 , paddedPointDepthAndWeight , ConversionFunction );
633 #endif // ADAPTIVE_PADDING
634 }
635
636 ThreadPool::ParallelFor( 0 , _normalInfo->size() , [&]( unsigned int , size_t i ){ (*_normalInfo)[i] *= (Real)-1.; } );
637 ThreadPool::ParallelFor( 0 , _paddedNormalInfo->size() , [&]( unsigned int , size_t i ){ (*_paddedNormalInfo)[i] *= (Real)-1.; } );
638 profiler.update();
639 if( clientReconInfo.verbose>1 )
640 {
641 std::cout << "# Got normal field: " << timer << std::endl;
642 std::cout << "Point Depth / Point Weight / Padded Point Depth / Padded Point Weight / Estimated Measure / Estimated Padded Measure: " << pointDepthAndWeight.value()[0] << " / " << pointDepthAndWeight.value()[1] << " / " << paddedPointDepthAndWeight.value()[0] << " / " << paddedPointDepthAndWeight.value()[1] << " / " << pointCount* pointDepthAndWeight.value()[1] << " / " << paddedPointCount* paddedPointDepthAndWeight.value()[1] << std::endl;
643 }
644 }
645 if( clientReconInfo.verbose>1 ) std::cout << "Nodes [Padded Data Field " << _paddedNormalInfo->size() << " / " << _paddedNormalInfo->reserved() << "]: " << _tree.allNodes() << std::endl;
646
647 _tree.resetNodeIndices( 0 , std::make_tuple( _density , _normalInfo , _paddedNormalInfo ) );
648
649 if( clientReconInfo.verbose>1 ) std::cout << "Memory Usage: " << float( MemoryInfo::Usage() )/(1<<20) << " MB" << std::endl;
650 profiler.update();
651 }
652
653 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
654 PhaseInfo Client< Real , Dim , BType , Degree >::_phase3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State3 &state3 , Profiler &profiler )
655 {
656 PhaseInfo phaseInfo;
657 ProjectiveData< Real , Real > cumulativePointWeight;
658
659 {
660 Timer timer;
661 phaseInfo.readBytes += _receive3( clientReconInfo , cumulativePointWeight , profiler );
662 phaseInfo.readTime += timer.wallTime();
663 }
664
665 {
666 Timer timer;
667 _process3( clientReconInfo , cumulativePointWeight , state3 , profiler );
668 phaseInfo.processTime += timer.wallTime();
669 }
670
671 {
672 Timer timer;
673 phaseInfo.writeBytes += _send3( clientReconInfo , state3 , profiler );
674 phaseInfo.writeTime += timer.wallTime();
675 }
676
677 return phaseInfo;
678 }
679
680 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
681 size_t Client< Real , Dim , BType , Degree >::_receive3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > &cumulativePointWeight , Profiler &profiler )
682 {
683 ClientServerStream< true > serverStream( _serverSocket , _index , clientReconInfo );
684 serverStream.ioBytes = 0;
685 if( !serverStream.read( cumulativePointWeight ) ) MK_THROW( "Could not read cumulative point weight" );
686 profiler.update();
687 return serverStream.ioBytes;
688 }
689
690 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
691 size_t Client< Real , Dim , BType , Degree >::_send3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , const _State3 &state3 , Profiler &profiler )
692 {
693 size_t ioBytes = 0;
694 {
695 ClientServerStream< false > serverStream( _serverSocket , _index , clientReconInfo , ClientReconstructionInfo< Real , Dim >::BACK );
696 serverStream.ioBytes = 0;
697
698 serverStream.write( state3.subNodeCount );
699 TreeAddressesToIndices( state3.subNodes , state3.subNodeCount );
700 serverStream.write( state3.subNodes , state3.subNodeCount );
701 ioBytes += serverStream.ioBytes;
702 profiler.update();
703 }
704 {
705 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
706 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
707
708 ClientServerStream< false > serverStream( _serverSocket , _index , clientReconInfo , ClientReconstructionInfo< Real , Dim >::FRONT );
709 serverStream.ioBytes = 0;
710
711 state3.constraints.write( serverStream );
712 state3.iInfo.write( serverStream );
713
714 if( needAuxData )
715 {
716 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
717 {
718 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
719 state3.auxDataField.write( serverStream , serializer );
720 }
721 else state3.auxDataField.write( serverStream );
722 }
723 ioBytes += serverStream.ioBytes;
724 profiler.update();
725 }
726 return ioBytes;
727 }
728
729 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
730 void Client< Real , Dim , BType , Degree >::_process3( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > cumulativePointWeight , _State3 &state3 , Profiler &profiler )
731 {
732 std::pair< unsigned int , unsigned int > paddedRange = _PaddedRange( _range , clientReconInfo.sharedDepth , clientReconInfo.padSize );
733 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
734
735 InputSampleFactory inputSampleFactory( VertexFactory::PositionFactory< Real , Dim >() , InputSampleDataFactory( VertexFactory::NormalFactory< Real , Dim >() , auxDataFactory ) );
736 InputSampleDataFactory inputSampleDataFactory( VertexFactory::NormalFactory< Real , Dim >() , auxDataFactory );
737
738 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
739
740 Real targetValue = clientReconInfo.targetValue;
741
742 unsigned int beginIndex = _range.first , endIndex = _range.second;
743 unsigned int beginPaddedIndex = paddedRange.first , endPaddedIndex = paddedRange.second;
744
745 ApproximatePointInterpolationInfo *iInfo = NULL;
746 ApproximatePointInterpolationInfo *paddedIInfo = NULL;
747
748 // Add the interpolation constraints
749 {
750 Timer timer;
751 iInfo = FEMTree< Dim , Real >::template InitializeApproximatePointInterpolationInfo< Real , 0 > ( _tree , _samples , Reconstructor::Poisson::ConstraintDual< Dim , Real >( targetValue , clientReconInfo.pointWeight * cumulativePointWeight.value() ) , Reconstructor::Poisson::SystemDual< Dim , Real >( clientReconInfo.pointWeight * cumulativePointWeight.value() ) , true , clientReconInfo.reconstructionDepth , 1 );
752 paddedIInfo = FEMTree< Dim , Real >::template InitializeApproximatePointInterpolationInfo< Real , 0 > ( _tree , _paddedSamples , Reconstructor::Poisson::ConstraintDual< Dim , Real >( targetValue , clientReconInfo.pointWeight * cumulativePointWeight.value() ) , Reconstructor::Poisson::SystemDual< Dim , Real >( clientReconInfo.pointWeight * cumulativePointWeight.value() ) , true , clientReconInfo.reconstructionDepth , 1 );
753 profiler.update();
754
755 if( clientReconInfo.verbose>1 ) std::cout << "# Set interpolation constraints: " << timer << std::endl;
756 }
757
758 // Trim the tree and prepare for multigrid
759 {
760 Timer timer;
761
762 constexpr int MaxDegree = Reconstructor::Poisson::NormalDegree > Degrees::Max() ? Reconstructor::Poisson::NormalDegree : Degrees::Max();
763 typename FEMTree< Dim , Real >::template HasNormalDataFunctor< NormalSigs > hasNormalDataFunctor( *_normalInfo );
764 typename FEMTree< Dim , Real >::template HasNormalDataFunctor< NormalSigs > hasPaddedNormalDataFunctor( *_paddedNormalInfo );
765 auto hasDataFunctor = [&]( const FEMTreeNode *node ){ return hasNormalDataFunctor( node ) || hasPaddedNormalDataFunctor( node ); };
766
767 const int StartOffset = BSplineSupportSizes< MaxDegree >::SupportStart;
768 const int EndOffset = BSplineSupportSizes< MaxDegree >::SupportEnd+1;
769 auto addNodeFunctor = [&]( int d , const int off[Dim] )
770 {
771 if( d<0 ) return true;
772 else if( d>(int)clientReconInfo.baseDepth ) return false;
773 else
774 {
775 int start = ( off[Dim-1] + StartOffset )<<(clientReconInfo.sharedDepth-d);
776 int end = ( off[Dim-1] + EndOffset )<<(clientReconInfo.sharedDepth-d);
777 return start<(int)endPaddedIndex && end>(int)beginPaddedIndex;
778 }
779 };
780 _tree.template finalizeForMultigrid< MaxDegree , Degrees::Max() >( clientReconInfo.baseDepth , addNodeFunctor , hasDataFunctor , std::make_tuple( iInfo , paddedIInfo ) , std::make_tuple( _normalInfo , _paddedNormalInfo , _density ) );
781 profiler.update();
782 if( clientReconInfo.verbose>1 )
783 {
784 std::cout << "All Nodes / Active Nodes / Ghost Nodes: " << _tree.allNodes() << " / " << _tree.activeNodes() << " / " << _tree.ghostNodes() << std::endl;
785 std::cout << "# Finalized tree: " << timer << std::endl;
786 }
787 }
788
789 // Compute the FEM constraints for the points interior to the slab
790 {
791 _constraints = _tree.initDenseNodeData( Sigs() );
792
793 // Add Poisson constraints
794 {
795 Timer timer;
796 typename FEMIntegrator::template Constraint< Sigs , IsotropicUIntPack< Dim , 1 > , NormalSigs , IsotropicUIntPack< Dim , 0 > , Dim > F;
797 unsigned int derivatives2[Dim];
798 for( int d=0 ; d<Dim ; d++ ) derivatives2[d] = 0;
799 typedef IsotropicUIntPack< Dim , 1 > Derivatives1;
800 typedef IsotropicUIntPack< Dim , 0 > Derivatives2;
801 for( int d=0 ; d<Dim ; d++ )
802 {
803 unsigned int derivatives1[Dim];
804 for( int dd=0 ; dd<Dim ; dd++ ) derivatives1[dd] = dd==d ? 1 : 0;
805 F.weights[d][ TensorDerivatives< Derivatives1 >::Index( derivatives1 ) ][ TensorDerivatives< Derivatives2 >::Index( derivatives2 ) ] = 1;
806 }
807 _tree.addFEMConstraints( F , *_normalInfo , _constraints , clientReconInfo.reconstructionDepth );
808 if( clientReconInfo.verbose>1 ) std::cout << "# Set interior FEM constraints: " << timer << std::endl;
809 }
810 profiler.update();
811
812 // Free up the normal info
813 delete _normalInfo , _normalInfo = NULL;
814
815 {
816 Timer timer;
817 _tree.addInterpolationConstraints( _constraints , clientReconInfo.reconstructionDepth , std::make_tuple( iInfo ) );
818 profiler.update();
819 if( clientReconInfo.verbose>1 ) std::cout << "#Set interior point constraints: " << timer << std::endl;
820 }
821 }
822 if( needAuxData ) _auxDataField = _tree.template setExtrapolatedDataField< DataSig , false , Reconstructor::WeightDegree , AuxData >( auxDataFactory() , _samples.size() , [&]( size_t i ) -> const typename FEMTree< Dim , Real >::PointSample & { return _samples[i]; } , [&]( size_t i ) -> const AuxData & { return _sampleData[i].template get<1>(); } , (DensityEstimator*)NULL );
823
824 // Get the shared tree, constraints, interpolation info, and data-field
825 {
826 auto keepNodeFunctor = [&]( const FEMTreeNode *node )
827 {
828 int d , off[Dim];
829 _tree.depthAndOffset( node , d , off );
830
831 return d<=(int)clientReconInfo.sharedDepth;
832 };
833 state3.subNodes = _tree.tree().serializeSubTree( keepNodeFunctor , state3.subNodeCount );
834 state3.constraints = _tree.trimToDepth( _constraints , clientReconInfo.sharedDepth );
835 state3.iInfo = _tree.trimToDepth( *iInfo , clientReconInfo.sharedDepth );
836 if( needAuxData ) state3.auxDataField = _tree.trimToDepth( _auxDataField , clientReconInfo.sharedDepth );
837 }
838
839 if( needAuxData )
840 {
841 _tree.template updateExtrapolatedDataField< DataSig , false >( auxDataFactory() , _auxDataField , _paddedSamples.size() , [&]( size_t i ) -> const typename FEMTree< Dim , Real >::PointSample & { return _paddedSamples[i]; } , [&]( size_t i ) -> const AuxData & { return _paddedSampleData[i].template get<1>(); } , (DensityEstimator*)NULL );
842 auto nodeFunctor = [&]( const RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > *n )
843 {
844 ProjectiveData< AuxData , Real >* clr = _auxDataField( n );
845 if( clr ) (*clr) *= (Real)pow( clientReconInfo.dataX , _tree.depth( n ) );
846 };
847 _tree.tree().processNodes( nodeFunctor );
848 }
849
850 // Add the FEM constraints for the points in the padding region
851 {
852 Timer timer;
853 // Add Poisson constraints
854 {
855 typename FEMIntegrator::template Constraint< Sigs , IsotropicUIntPack< Dim , 1 > , NormalSigs , IsotropicUIntPack< Dim , 0 > , Dim > F;
856 unsigned int derivatives2[Dim];
857 for( int d=0 ; d<Dim ; d++ ) derivatives2[d] = 0;
858 typedef IsotropicUIntPack< Dim , 1 > Derivatives1;
859 typedef IsotropicUIntPack< Dim , 0 > Derivatives2;
860 for( int d=0 ; d<Dim ; d++ )
861 {
862 unsigned int derivatives1[Dim];
863 for( int dd=0 ; dd<Dim ; dd++ ) derivatives1[dd] = dd==d ? 1 : 0;
864 F.weights[d][ TensorDerivatives< Derivatives1 >::Index( derivatives1 ) ][ TensorDerivatives< Derivatives2 >::Index( derivatives2 ) ] = 1;
865 }
866 _tree.addFEMConstraints( F , *_paddedNormalInfo , _constraints , clientReconInfo.reconstructionDepth );
867 }
868 if( clientReconInfo.verbose>1 ) std::cout << "# Set padded FEM constraints: " << timer << std::endl;
869
870 profiler.update();
871
872 // Free up the normal info
873 delete _paddedNormalInfo , _paddedNormalInfo = NULL;
874
875 {
876 Timer timer;
877 _tree.addInterpolationConstraints( _constraints , clientReconInfo.reconstructionDepth , std::make_tuple( paddedIInfo ) );
878 profiler.update();
879 if( clientReconInfo.verbose>1 ) std::cout << "# Set padded point constraints: " << timer << std::endl;
880 }
881 }
882
883 // Merge the interpolation information
884 {
885 Timer timer;
886 using InterpolationData = typename ApproximatePointInterpolationInfo::Data;
887 auto preMergeFunctor = []( InterpolationData data ){ data.position *= data.weight ; return data; };
888 auto postMergeFunctor = []( InterpolationData data ){ data.position /= data.weight ; return data; };
889
890 _iInfo = new ApproximatePointInterpolationInfo( Reconstructor::Poisson::ConstraintDual< Dim , Real >( targetValue , clientReconInfo.pointWeight * cumulativePointWeight.value() ) , Reconstructor::Poisson::SystemDual< Dim , Real >( clientReconInfo.pointWeight * cumulativePointWeight.value() ) , true );
891 _iInfo->iData.reserve( _tree.nodesSize() );
892
893 _iInfo->iData.merge( iInfo->iData , preMergeFunctor );
894 _iInfo->iData.merge( paddedIInfo->iData , preMergeFunctor );
895
896 for( unsigned int i=0 ; i<_iInfo->iData.size() ; i++ ) _iInfo->iData[i] = postMergeFunctor( _iInfo->iData[i] );
897
898 if( clientReconInfo.verbose>1 ) std::cout << "# Merged interpolation: " << timer << std::endl;
899 }
900 if( clientReconInfo.verbose>1 ) std::cout << "Memory Usage: " << float( MemoryInfo::Usage() )/(1<<20) << " MB" << std::endl;
901 profiler.update();
902 delete iInfo;
903 delete paddedIInfo;
904 }
905
906 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
907 PhaseInfo Client< Real , Dim , BType , Degree >::_phase5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler )
908 {
909 PhaseInfo phaseInfo;
910 std::pair< double , double > isoInfo;
911
912 typename Client< Real , Dim , BType , Degree >::_State5 state5;
913 {
914 Timer timer;
915 phaseInfo.readBytes += _receive5( clientReconInfo , state5 , profiler );
916 phaseInfo.readTime += timer.wallTime();
917 }
918
919 {
920 Timer timer;
921 isoInfo = _process5( clientReconInfo , state5 , profiler );
922 phaseInfo.processTime += timer.wallTime();
923 }
924
925 {
926 Timer timer;
927 _serverSocket.write( isoInfo );
928 phaseInfo.writeBytes += _send5( clientReconInfo , state5 , profiler );
929 phaseInfo.writeTime += timer.wallTime();
930 }
931 return phaseInfo;
932 }
933
934
935 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
936 size_t Client< Real , Dim , BType , Degree >::_receive5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State5 &state5 , Profiler &profiler )
937 {
938 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
939 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
940
941 ClientServerStream< true > serverStream( _serverSocket , _index , clientReconInfo );
942 serverStream.ioBytes = 0;
943 size_t subNodeCount;
944 serverStream.read( subNodeCount );
945 state5.subNodes = NewPointer< FEMTreeNode >( subNodeCount );
946 serverStream.read( state5.subNodes , subNodeCount );
947 TreeIndicesToAddresses( state5.subNodes , subNodeCount );
948 state5.solution.read( serverStream );
949
950 if( needAuxData )
951 {
952 using Data = typename _State5::Data;
953 Data defaultValue;
954
955 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
956 {
957 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
958 state5.auxDataField = new SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > >( serverStream , serializer );
959 }
960 else state5.auxDataField = new SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > >( serverStream );
961 }
962 profiler.update();
963
964 return serverStream.ioBytes;
965 }
966
967 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
968 size_t Client< Real , Dim , BType , Degree >::_send5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , const _State5 &state5 , Profiler &profiler )
969 {
970 size_t ioBytes = 0;
971
972 auto Send = [&]( const typename Client::_State5::BoundaryInfo &bInfo , typename ClientReconstructionInfo< Real , Dim >::ShareType st )
973 {
974 ClientServerStream< false > serverStream( _serverSocket , _index , clientReconInfo , st );
975 serverStream.ioBytes=0;
976
977 XForm< Real , Dim > sliceModelToUnitCube;
978 {
979 for( unsigned int i=0 ; i<Dim-1 ; i++ )
980 {
981 for( unsigned int j=0 ; j<Dim-1 ; j++ ) sliceModelToUnitCube(i,j) = _modelToUnitCube(i,j);
982 sliceModelToUnitCube(Dim-1,i) = _modelToUnitCube(Dim,i);
983 }
984 sliceModelToUnitCube(Dim-1,Dim-1) = 1;
985 }
986
987 if( bInfo.tree )
988 {
989 bInfo.tree->write( serverStream , true );
990 serverStream.write( sliceModelToUnitCube );
991 bInfo.solution.write( serverStream );
992 bInfo.dSolution.write( serverStream );
993 }
994 profiler.update();
995 return serverStream.ioBytes;
996 };
997 if( _range.first!=0 ) ioBytes += Send( state5.boundaryInfo.first , ClientReconstructionInfo< Real , Dim >::BACK );
998 if( _range.second!=(1<<clientReconInfo.sharedDepth) ) ioBytes += Send( state5.boundaryInfo.second , ClientReconstructionInfo< Real , Dim >::FRONT );
999
1000 return ioBytes;
1001 }
1002
1003 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1004 std::pair< double , double > Client< Real , Dim , BType , Degree >::_process5( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State5 &state5 , Profiler &profiler )
1005 {
1006 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
1007 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
1008
1009 // Refine the client's tree so that it contains the server's subtree
1010 {
1011 Timer timer;
1012 // Refine client nodes as needed
1013 std::function< void ( const FEMTreeNode * , FEMTreeNode * ) > ProcessIndices = [&]( const FEMTreeNode *serverNode , FEMTreeNode *clientNode )
1014 {
1015 if( serverNode->children )
1016 {
1017 if( !clientNode->children ) clientNode->template initChildren< false >( _tree.nodeAllocators[0] , _tree.initializer() );
1018 for( int c=0 ; c<(1<<Dim) ; c++ ) ProcessIndices( serverNode->children+c , clientNode->children+c );
1019 }
1020 };
1021 ProcessIndices( &state5.subNodes[0] , const_cast< FEMTreeNode * >( &_tree.tree() ) );
1022 // Re-finalize and re-index
1023 auto addNodeFunctor = [&]( int d , const int off[Dim] ){ return d<=(int)clientReconInfo.baseDepth; };
1024 auto hasDataFunctor = []( const FEMTreeNode * ){ return true; };
1025
1026 constexpr int MaxDegree = Reconstructor::Poisson::NormalDegree > Degrees::Max() ? Reconstructor::Poisson::NormalDegree : Degrees::Max();
1027 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > *auxDataField = needAuxData ? &_auxDataField : NULL;
1028 DenseNodeData< Real , Sigs > *constraints = &_constraints;
1029
1030 // [WARNING] This assumes that nothing needs to be done with the Dirichlet flags
1031 _tree.setSortedTreeNodes( std::make_tuple( _iInfo ) , std::make_tuple( _density , constraints , auxDataField ) );
1032 profiler.update();
1033
1034 if( clientReconInfo.verbose>1 ) std::cout << "# Updated client tree: " << timer << std::endl;
1035 }
1036
1037 {
1038 Timer timer;
1039 _solution = _tree.initDenseNodeData( Sigs() );
1040 std::vector< node_index_type > clientToServer( _tree.nodesSize() , -1 );
1041 {
1042 std::function< void ( const FEMTreeNode * , const FEMTreeNode * ) > ProcessIndices = [&]( const FEMTreeNode *serverNode , const FEMTreeNode *clientNode )
1043 {
1044 if( clientNode->nodeData.nodeIndex!=-1 )
1045 {
1046 if( clientNode->nodeData.nodeIndex>=(node_index_type)clientToServer.size() ) MK_THROW( "More client nodes than server nodes" );
1047 clientToServer[ clientNode->nodeData.nodeIndex ] = serverNode->nodeData.nodeIndex;
1048 }
1049 if( _tree.depth( clientNode )<(int)clientReconInfo.sharedDepth && clientNode->children )
1050 {
1051 if( serverNode->children ) for( int c=0 ; c<(1<<Dim) ; c++ ) ProcessIndices( serverNode->children+c , clientNode->children+c );
1052 }
1053 };
1054 ProcessIndices( &state5.subNodes[0] , &_tree.tree() );
1055 }
1056 profiler.update();
1057 if( clientReconInfo.verbose>1 ) std::cout << "# Set client-to-server: " << timer << std::endl;
1058
1059 if( needAuxData )
1060 {
1061 Timer timer;
1062 using Data = ProjectiveData< AuxData , Real >;
1063 Data defaultValue = auxDataFactory();
1064
1065 // Clearing the low freqeuncy
1066 auto nodeFunctor = [&]( const FEMTreeNode *n )
1067 {
1068 if( n->nodeData.nodeIndex!=-1 )
1069 {
1070 node_index_type idx = state5.auxDataField->index( clientToServer[ n->nodeData.nodeIndex ] );
1071 if( idx!=-1 ) _auxDataField[n] = (*state5.auxDataField)[idx];
1072 }
1073 return _tree.depth( n )<(int)clientReconInfo.sharedDepth;
1074 };
1075 _tree.tree().processNodes( nodeFunctor );
1076 profiler.update();
1077 if( clientReconInfo.verbose>1 ) std::cout << "# Copied aux data: " << profiler << std::endl;
1078 }
1079
1080 // (Over-)write coarse solution
1081 for( unsigned int i=0 ; i<_solution.size() ; i++ ) if( clientToServer[i]!=-1 ) _solution[i] = state5.solution[ clientToServer[i] ];
1082 profiler.update();
1083 if( clientReconInfo.verbose>1 ) std::cout << "# Copied solution: " << timer << std::endl;
1084 }
1085
1086 // Solve the linear system
1087 {
1088 Timer timer;
1089 typename FEMTree< Dim , Real >::SolverInfo sInfo;
1090 sInfo.cgDepth = 0 , sInfo.cascadic = true , sInfo.vCycles = 1 , sInfo.iters = clientReconInfo.iters , sInfo.cgAccuracy = 0 , sInfo.verbose = clientReconInfo.verbose>1 , sInfo.showResidual = clientReconInfo.verbose>2 , sInfo.showGlobalResidual = SHOW_GLOBAL_RESIDUAL_NONE , sInfo.sliceBlockSize = 1;
1091 sInfo.baseVCycles = 0 , sInfo.clearSolution = false;
1092 typename FEMIntegrator::template System< Sigs , IsotropicUIntPack< Dim , 1 > > F( { 0. , 1. } );
1093 _tree.solveSystem( Sigs() , F , _constraints , _solution , []( Real v , Real w ){ return v*w; } , clientReconInfo.sharedDepth+1 , clientReconInfo.solveDepth , sInfo , std::make_tuple( _iInfo ) );
1094
1095 profiler.update();
1096 if( _iInfo ) delete _iInfo , _iInfo = NULL;
1097
1098 if( clientReconInfo.verbose>1 ) std::cout << "# Linear system solved: " << timer << std::endl;
1099 }
1100
1101 std::pair< double , double > isoInfo(0.,0.);
1102 // Compute the average iso-value
1103 {
1104 Timer timer;
1105 typename FEMTree< Dim , Real >::template MultiThreadedEvaluator< Sigs , 0 > evaluator( &_tree , _solution );
1106 std::vector< double > valueSums( ThreadPool::NumThreads() , 0 ) , weightSums( ThreadPool::NumThreads() , 0 );
1107 ThreadPool::ParallelFor( 0 , _samples.size() , [&]( unsigned int thread , size_t j )
1108 {
1109 ProjectiveData< Point< Real , Dim > , Real > &sample = _samples[j].sample;
1110 Real w = sample.weight;
1111 if( w>0 ) weightSums[thread] += w , valueSums[thread] += evaluator.values( sample.data / sample.weight , thread , _samples[j].node )[0] * w;
1112 }
1113 );
1114 for( size_t t=0 ; t<valueSums.size() ; t++ ) isoInfo.first += valueSums[t] , isoInfo.second += weightSums[t];
1115 profiler.update();
1116 if( clientReconInfo.verbose>1 ) std::cout << "# Got iso-value: " << timer << std::endl;
1117 }
1118
1119 // Set the boundary information
1120 if constexpr( Dim==3 )
1121 {
1122 Timer timer;
1123 using SliceSigs = typename Sigs::Transpose::Rest::Transpose;
1124 static const unsigned int CrossSig = Sigs::Transpose::First;
1125
1126 auto SetBoundary = [&]( unsigned int index , typename _State5::BoundaryInfo &boundaryInfo )
1127 {
1128 bool needsPadding = !clientReconInfo.linearFit && FEMSignature< CrossSig >::Degree==1;
1129 if( needsPadding ) boundaryInfo.tree = FEMTree< Dim-1 , Real >::template Slice< FEMSignature< CrossSig >::Degree , 1 >( _tree , clientReconInfo.sharedDepth , index , true , MEMORY_ALLOCATOR_BLOCK_SIZE );
1130 else boundaryInfo.tree = FEMTree< Dim-1 , Real >::template Slice< FEMSignature< CrossSig >::Degree , 0 >( _tree , clientReconInfo.sharedDepth , index , true , MEMORY_ALLOCATOR_BLOCK_SIZE );
1131 boundaryInfo.solution = boundaryInfo.tree->initDenseNodeData( SliceSigs() );
1132 boundaryInfo.dSolution = boundaryInfo.tree->initDenseNodeData( SliceSigs() );
1133 boundaryInfo.tree->template slice< 0 , CrossSig >( _tree , 0 , _solution , boundaryInfo.solution , clientReconInfo.sharedDepth , index );
1134 if( needsPadding ) boundaryInfo.tree->template slice< 1 , CrossSig >( _tree , 1 , _solution , boundaryInfo.dSolution , clientReconInfo.sharedDepth , index );
1135 else boundaryInfo.tree->template slice< 0 , CrossSig >( _tree , 1 , _solution , boundaryInfo.dSolution , clientReconInfo.sharedDepth , index );
1136 };
1137 if( _range.first !=0 ) SetBoundary( _range.first , state5.boundaryInfo.first );
1138 if( _range.second!=(1<<clientReconInfo.sharedDepth) ) SetBoundary( _range.second , state5.boundaryInfo.second );
1139 profiler.update();
1140 if( clientReconInfo.verbose>1 ) std::cout << "# Set boundary info: " << timer << std::endl;
1141 }
1142
1143 if( clientReconInfo.outputSolution )
1144 {
1145 std::string outFileName = std::string( "solution." ) + std::to_string(_index) + std::string( ".tree" );
1146 if( clientReconInfo.outDir.length() ) outFileName = PointPartition::FileDir( clientReconInfo.outDir , outFileName );
1147
1148 FILE* fp = fopen( outFileName.c_str() , "wb" );
1149 if( !fp ) MK_THROW( "Failed to open file for writing: " , outFileName );
1150 FileStream fs(fp);
1151 FEMTree< Dim , Real >::WriteParameter( fs );
1152 DenseNodeData< Real , Sigs >::WriteSignatures( fs );
1153 XForm< Real , Dim+1 > voxelToUnitCube = XForm< Real , Dim+1 >::Identity();
1154 _tree.write( fs , false );
1155 fs.write( voxelToUnitCube );
1156 _solution.write( fs );
1157 fclose( fp );
1158 }
1159
1160 return isoInfo;
1161 }
1162
1163 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1164 PhaseInfo Client< Real , Dim , BType , Degree >::_phase7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler )
1165 {
1166 PhaseInfo phaseInfo;
1167
1168 typename Client< Real , Dim , BType , Degree >::_State7 state7;
1169 if constexpr( Dim==3 ) if( clientReconInfo.mergeType!=ClientReconstructionInfo< Real , Dim >::MergeType::NONE )
1170 {
1171 Timer timer;
1172 phaseInfo.readBytes += _receive7( clientReconInfo , state7 , profiler );
1173 phaseInfo.readTime += timer.wallTime();
1174 }
1175
1176 {
1177 Timer timer;
1178 _process7( clientReconInfo , state7 , profiler );
1179 phaseInfo.processTime += timer.wallTime();
1180 }
1181 return phaseInfo;
1182 }
1183
1184 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1185 size_t Client< Real , Dim , BType , Degree >::_receive7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , Profiler &profiler )
1186 {
1187 size_t ioBytes = 0;
1188 auto Receive = [&]( BoundaryData *&boundary , std::vector< std::vector< Real > > &dValues , typename ClientReconstructionInfo< Real , Dim >::ShareType st )
1189 {
1190 ClientServerStream< true > serverStream( _serverSocket , _index , clientReconInfo , st );
1191 serverStream.ioBytes = 0;
1192 serverStream.read( state7.isoValue );
1193 if( clientReconInfo.mergeType!=ClientReconstructionInfo< Real , Dim >::MergeType::NONE )
1194 {
1195 XForm< Real , Dim > modelToUnitCube;
1196 boundary = new BoundaryData( serverStream , modelToUnitCube , MEMORY_ALLOCATOR_BLOCK_SIZE );
1197 if( !clientReconInfo.linearFit )
1198 {
1199 dValues.resize( boundary->sliceValues.size() );
1200 for( unsigned int i=0 ; i<dValues.size() ; i++ ) serverStream.read( dValues[i] );
1201 }
1202 }
1203 profiler.update();
1204 return serverStream.ioBytes;
1205 };
1206
1207 if( _range.first!=0 ) ioBytes += Receive( state7.backBoundary , state7.backDValues , ClientReconstructionInfo< Real , Dim >::BACK );
1208 if( _range.second!=(1<<clientReconInfo.sharedDepth) ) ioBytes += Receive( state7.frontBoundary , state7.frontDValues , ClientReconstructionInfo< Real , Dim >::FRONT );
1209
1210 return ioBytes;
1211 }
1212
1213 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1214 template< bool HasGradients , bool HasDensity >
1215 void Client< Real , Dim , BType , Degree >::_writeMeshWithData( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , XForm< Real , Dim+1 > unitCubeToModel )
1216 {
1217 Timer timer;
1218 std::string tempHeader( "PR_" );
1219 using AuxData = typename AuxDataFactory::VertexType;
1220 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
1221 if( clientReconInfo.tempDir.length() ) tempHeader = PointPartition::FileDir( clientReconInfo.tempDir , tempHeader );
1222
1223 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > *auxDataField = NULL;
1224 if( _auxDataField.size() ) auxDataField = &_auxDataField;
1225
1226 std::string outFileName;
1227 {
1228 std::stringstream ss;
1229 ss << clientReconInfo.header << "." << _index << ".ply";
1230 outFileName = ss.str();
1231 }
1232
1233 if( clientReconInfo.outDir.length() ) outFileName = PointPartition::FileDir( clientReconInfo.outDir , outFileName );
1234
1235
1236 // A description of the output vertex information
1237 using VInfo = Reconstructor::OutputVertexInfo< Real , Dim , HasGradients , HasDensity , AuxDataFactory >;
1238
1239 // A factory generating the output vertices
1240 using Factory = typename VInfo::Factory;
1241 Factory factory = VInfo::GetFactory( auxDataFactory );
1242
1243 // A backing stream for the vertices
1244 Reconstructor::OutputInputFactoryTypeStream< Real , Dim , Factory , false , true , AuxData > vertexStream( factory , VInfo::Convert );
1245 Reconstructor::OutputInputFaceStream< Dim-1 , false , true > faceStream;
1246
1247 typename LevelSetExtractor< Real , Dim , AuxData >::Stats stats;
1248
1249 {
1250 // The transformed stream
1251 Reconstructor::TransformedOutputLevelSetVertexStream< Real , Dim , AuxData > __vertexStream( unitCubeToModel , vertexStream );
1252
1253 // Extract the mesh
1254 stats = LevelSetExtractor< Real , Dim , AuxData >::template Extract< Reconstructor::WeightDegree , DataSig >
1255 (
1256 Sigs() ,
1257 UIntPack< Reconstructor::WeightDegree >() ,
1258 UIntPack< DataSig >() ,
1259 _tree ,
1260 clientReconInfo.reconstructionDepth ,
1261 _density ,
1262 auxDataField ,
1263 _solution ,
1264 state7.isoValue ,
1265 clientReconInfo.sharedDepth ,
1266 _range.first ,
1267 _range.second ,
1268 __vertexStream ,
1269 faceStream ,
1270 auxDataFactory() ,
1271 !clientReconInfo.linearFit ,
1272 HasGradients , false , true , false ,
1273 state7.backBoundary ,
1274 state7.frontBoundary ,
1275 state7.backDValues ,
1276 state7.frontDValues ,
1277 clientReconInfo.mergeType==ClientReconstructionInfo< Real , Dim >::MergeType::TOPOLOGY_AND_FUNCTION
1278 );
1279 }
1280
1281 if( clientReconInfo.verbose>1 )
1282 {
1283 std::cout << "Vertices / Faces: " << vertexStream.size() << " / " << faceStream.size() << std::endl;
1284 std::cout << stats.toString() << std::endl;
1285 std::cout << "# Got faces: " << timer << std::endl;
1286 }
1287
1288 // Write the mesh to a .ply file
1289 std::vector< std::string > noComments;
1290 vertexStream.reset();
1291 PLY::Write< Factory , node_index_type , Real , Dim >( outFileName.c_str() , factory , vertexStream.size() , faceStream.size() , vertexStream , faceStream , PLY_BINARY_NATIVE , noComments );
1292 }
1293
1294 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1295 void Client< Real , Dim , BType , Degree >::_process7( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , _State7 &state7 , Profiler &profiler )
1296 {
1297 static const bool HasAuxData = !std::is_same< AuxDataFactory , VertexFactory::EmptyFactory< Real > >::value;
1298 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
1299
1300 // Extract the mesh
1301 if constexpr( Dim==3 )
1302 {
1303 XForm< Real , Dim+1 > unitCubeToModel;
1304 if( clientReconInfo.gridCoordinates )
1305 {
1306 unitCubeToModel = XForm< Real , Dim+1 >::Identity();
1307 unsigned int res = 1<<clientReconInfo.reconstructionDepth;
1308 for( unsigned int d=0 ; d<Dim ; d++ ) unitCubeToModel(d,d) = (Real)res;
1309 }
1310 else unitCubeToModel = _modelToUnitCube.inverse();
1311 if( clientReconInfo.density ) _writeMeshWithData< false , true >( clientReconInfo , state7 , unitCubeToModel );
1312 else _writeMeshWithData< false , false >( clientReconInfo , state7 , unitCubeToModel );
1313 }
1314
1315 if( clientReconInfo.ouputVoxelGrid )
1316 {
1317 std::string outFileName;
1318 {
1319 std::stringstream ss;
1320 ss << clientReconInfo.header << "." << _index << ".grid";
1321 outFileName = ss.str();
1322 }
1323
1324 if( clientReconInfo.outDir.length() ) outFileName = PointPartition::FileDir( clientReconInfo.outDir , outFileName );
1325
1326 unsigned int begin[Dim] , end[Dim] , res[Dim];
1327 for( unsigned int d=0 ; d<Dim-1 ; d++ ) begin[d] = 0 , end[d] = 1<<clientReconInfo.reconstructionDepth;
1328 begin[Dim-1] = _range.first<<( clientReconInfo.reconstructionDepth - clientReconInfo.sharedDepth ) , end[Dim-1] = _range.second<<( clientReconInfo.reconstructionDepth - clientReconInfo.sharedDepth );
1329
1330 Pointer( Real ) values = _tree.template regularGridEvaluate< true >( _solution , begin , end , res );
1331
1332 XForm< Real , Dim+1 > voxelToUnitCube = XForm< Real , Dim+1 >::Identity();
1333 for( int d=0 ; d<Dim ; d++ ) voxelToUnitCube( d , d ) = (Real)( 1. / res[d] ) , voxelToUnitCube( Dim , d ) = (Real)( 0.5 / res[d] );
1334 XForm< Real , Dim+1 > unitCubeToModel = _modelToUnitCube.inverse();
1335 RegularGrid< Real , Dim >::Write( outFileName , res , values , unitCubeToModel * voxelToUnitCube );
1336
1337 DeletePointer( values );
1338 }
1339
1340 profiler.update();
1341 }
1342
1343
1344 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1345 Client< Real , Dim , BType , Degree >::Client( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , BinaryStream &stream , unsigned int phase )
1346 : _serverSocket( _INVALID_SOCKET_ ) , _tree( stream , MEMORY_ALLOCATOR_BLOCK_SIZE ) , _density(NULL) , _normalInfo(NULL) , _paddedNormalInfo(NULL) , _iInfo(NULL) , _index(-1)
1347 {
1348 stream.read( _modelToUnitCube );
1349
1350 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
1351 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
1352
1353 if( phase!=3 && phase!=5 && phase!=7 ) MK_THROW( "Only phases 3, 5, and 7 supported: " , phase );
1354
1355 stream.read( _index );
1356 stream.read( _range );
1357
1358 _density = new DensityEstimator( stream );
1359
1360 auto readSamples = [&]( BinaryStream &stream , std::vector< typename FEMTree< Dim , Real >::PointSample > &samples )
1361 {
1362 using SampleType = ProjectiveData< Point< Real , Dim > , Real >;
1363 struct T{ SampleType sample; node_index_type index; };
1364
1365 {
1366 std::vector< FEMTreeNode * > nodes( _tree.spaceRoot().nodes() , NULL );
1367 size_t idx = 0;
1368 _tree.spaceRoot().processNodes( [&]( FEMTreeNode *node ){ nodes[idx++] = node; } );
1369 if( idx!=nodes.size() ) MK_THROW( "uhoh" );
1370
1371 std::vector< T > _samples;
1372 if( !stream.read( _samples ) ) MK_THROW( "Failed to read samples" );
1373 samples.resize( _samples.size() );
1374 // Convert indices to node pointers
1375 for( size_t i=0 ; i<samples.size() ; i++ ) samples[i].sample = _samples[i].sample , samples[i].node = nodes[ _samples[i].index ];
1376 }
1377 };
1378
1379 if( phase==3 )
1380 {
1381 std::vector< FEMTreeNode * > nodes;
1382 auto readSamplesAndData = [&]( BinaryStream &stream , std::vector< typename FEMTree< Dim , Real >::PointSample > &samples , std::vector< InputSampleDataType > &sampleData )
1383 {
1384 using SampleType = ProjectiveData< Point< Real , Dim > , Real >;
1385 struct T
1386 {
1387 SampleType sample;
1388 node_index_type index;
1389 };
1390 {
1391 std::vector< T > _samples;
1392 if( !stream.read( _samples ) ) MK_THROW( "Failed to read samples" );
1393 size_t sz = _samples.size();
1394 SampleDataTypeSerializer< Real , Dim > serializer( clientReconInfo.auxProperties );
1395 samples.resize( sz );
1396 sampleData.resize( sz );
1397 size_t serializedSize = serializer.size();
1398 {
1399 Pointer( char ) buffer = NewPointer< char >( sz * serializedSize );
1400 if( !stream.read( buffer , sz*serializedSize ) ) MK_THROW( "Failed to read sample data" );
1401 for( unsigned int i=0 ; i<sz ; i++ ) serializer.deserialize( buffer+i*serializedSize , sampleData[i] );
1402 DeletePointer( buffer );
1403 }
1404 // Convert indices to node pointers
1405 for( size_t i=0 ; i<samples.size() ; i++ ) samples[i].sample = _samples[i].sample , samples[i].node = nodes[ _samples[i].index ];
1406 }
1407 };
1408
1409 // Get the mapping from indices to node pointers
1410 {
1411 FEMTreeNode *root = &_tree.spaceRoot();
1412 while( root->parent ) root = root->parent;
1413 nodes.reserve( _tree.tree().nodes() );
1414 root->processNodes( [&]( FEMTreeNode *node ){ nodes.push_back( node ); } );
1415 }
1416 _normalInfo = new SparseNodeData< Point< Real , Dim > , NormalSigs >( stream );
1417 _paddedNormalInfo = new SparseNodeData< Point< Real , Dim > , NormalSigs >( stream );
1418 readSamplesAndData( stream , _samples , _sampleData );
1419 readSamplesAndData( stream , _paddedSamples , _paddedSampleData );
1420 }
1421 else if( phase==5 )
1422 {
1423 _constraints.read( stream );
1424
1425 _iInfo = new ApproximatePointInterpolationInfo( stream );
1426
1427 readSamples( stream , _samples );
1428
1429 if( needAuxData )
1430 {
1431 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
1432 {
1433 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
1434 _auxDataField.read( stream , serializer );
1435 }
1436 else _auxDataField.read( stream );
1437 }
1438 }
1439 else if( phase==7 )
1440 {
1441 _solution.read( stream );
1442
1443 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
1444 if( needAuxData )
1445 {
1446 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
1447 {
1448 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
1449 _auxDataField.read( stream , serializer );
1450 }
1451 else _auxDataField.read( stream );
1452 }
1453 }
1454 }
1455
1456 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
1457 void Client< Real , Dim , BType , Degree >::_write( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , BinaryStream &stream , unsigned int phase ) const
1458 {
1459 AuxDataFactory auxDataFactory( clientReconInfo.auxProperties );
1460 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
1461
1462 if( phase!=1 && phase!=3 && phase!=5 ) MK_THROW( "Only phases 1, 3, and 5 supported: " , phase );
1463
1464 _tree.write( stream , false );
1465 stream.write( _modelToUnitCube );
1466
1467 stream.write( _index );
1468 stream.write( _range );
1469
1470 _density->write( stream );
1471
1472 auto writeSamples = [&]( BinaryStream &stream , const std::vector< typename FEMTree< Dim , Real >::PointSample > &samples )
1473 {
1474 // [NOTE] The samples may be assigned to ghost nodes, so we can't just use the node index
1475 using SampleType = ProjectiveData< Point< Real , Dim > , Real >;
1476 struct T { SampleType sample ; node_index_type index; };
1477
1478 std::vector< node_index_type > oldIndices( _tree.spaceRoot().nodes() , -1 );
1479 std::vector< T > _samples( samples.size() );
1480
1481 // Grab the old indices and over-write
1482 {
1483 size_t idx = 0;
1484 const_cast< FEMTree< Dim , Real > & >( _tree ).spaceRoot().processNodes( [&]( FEMTreeNode *node ){ oldIndices[idx] = node->nodeData.nodeIndex ; node->nodeData.nodeIndex = idx++; } );
1485 }
1486
1487 for( size_t i=0 ; i<samples.size() ; i++ ) _samples[i].sample = samples[i].sample , _samples[i].index = samples[i].node->nodeData.nodeIndex;
1488 stream.write( _samples );
1489
1490 // Set the node indices back
1491 {
1492 size_t idx = 0;
1493 const_cast< FEMTree< Dim , Real > & >( _tree ).spaceRoot().processNodes( [&]( FEMTreeNode *node ){ node->nodeData.nodeIndex = oldIndices[ idx++ ]; } );
1494 }
1495 };
1496
1497 if( phase==1 )
1498 {
1499 auto writeSamplesAndData = [&]( BinaryStream &stream , const std::vector< typename FEMTree< Dim , Real >::PointSample > &samples , const std::vector< InputSampleDataType > &sampleData )
1500 {
1501 using SampleType = ProjectiveData< Point< Real , Dim > , Real >;
1502 struct T
1503 {
1504 SampleType sample;
1505 node_index_type index;
1506 };
1507 std::vector< T > _samples( samples.size() );
1508 for( size_t i=0 ; i<samples.size() ; i++ ) _samples[i].sample = samples[i].sample , _samples[i].index = samples[i].node->nodeData.nodeIndex;
1509 stream.write( _samples );
1510
1511 SampleDataTypeSerializer< Real , Dim > serializer( clientReconInfo.auxProperties );
1512 size_t serializedSize = serializer.size();
1513 {
1514 Pointer( char ) buffer = NewPointer< char >( samples.size() * serializedSize );
1515 for( unsigned int i=0 ; i<samples.size() ; i++ ) serializer.serialize( sampleData[i] , buffer+i*serializedSize );
1516 stream.write( buffer , samples.size()*serializedSize );
1517 DeletePointer( buffer );
1518 }
1519 };
1520 _normalInfo->write( stream );
1521 _paddedNormalInfo->write( stream );
1522 writeSamplesAndData( stream , _samples , _sampleData );
1523 writeSamplesAndData( stream , _paddedSamples , _paddedSampleData );
1524 }
1525 else if( phase==3 )
1526 {
1527 _constraints.write( stream );
1528
1529 _iInfo->write( stream );
1530
1531 writeSamples( stream , _samples );
1532
1533 if( needAuxData )
1534 {
1535 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
1536 {
1537 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
1538 _auxDataField.write( stream , serializer );
1539 }
1540 else _auxDataField.write( stream );
1541 }
1542 }
1543 else if( phase==5 )
1544 {
1545 _solution.write( stream );
1546
1547 if( _auxDataField.size() )
1548 {
1549 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
1550 {
1551 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
1552 _auxDataField.write( stream , serializer );
1553 }
1554 else _auxDataField.write( stream );
1555 }
1556 }
1557 }