Debian Codegraph @

src/thirdparty/PoissonRecon/FEMTree.LevelSet.2D.inl

raw
1 /*
2 Copyright (c) 2022, 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 // Specialized level-set curve extraction
30 template< bool HasData , typename Real , typename Data >
31 struct _LevelSetExtractor< HasData , Real , 2 , Data >
32 {
33 static const unsigned int Dim = 2;
34 // Store the position, the (interpolated) gradient, the weight, and possibly data
35 typedef std::conditional_t
36 <
37 HasData ,
38 DirectSum< Real , Point< Real , Dim > , Point< Real , Dim > , Real , Data > ,
39 DirectSum< Real , Point< Real , Dim > , Point< Real , Dim > , Real >
40 > Vertex;
41
42 using OutputVertexStream = std::conditional_t
43 <
44 HasData ,
45 OutputDataStream< Point< Real , Dim > , Point< Real , Dim > , Real , Data > ,
46 OutputDataStream< Point< Real , Dim > , Point< Real , Dim > , Real >
47 >;
48
49 protected:
50 static std::atomic< size_t > _BadRootCount;
51 public:
52
53 using LocalDepth = typename FEMTree< Dim , Real >::LocalDepth;
54 using LocalOffset = typename FEMTree< Dim , Real >::LocalOffset;
55 using ConstOneRingNeighborKey = typename FEMTree< Dim , Real >::ConstOneRingNeighborKey;
56 using ConstOneRingNeighbors = typename FEMTree< Dim , Real >::ConstOneRingNeighbors;
57 using TreeNode = RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >;
58 template< unsigned int WeightDegree > using DensityEstimator = typename FEMTree< Dim , Real >::template DensityEstimator< WeightDegree >;
59 template< typename FEMSigPack , unsigned int PointD > using _Evaluator = typename FEMTree< Dim , Real >::template _Evaluator< FEMSigPack , PointD >;
60
61 using Key = LevelSetExtraction::Key< Dim >;
62 using IsoEdge = LevelSetExtraction::IsoEdge< Dim >;
63 template< unsigned int D , unsigned int ... Ks >
64 using HyperCubeTables = typename LevelSetExtraction::template HyperCubeTables< D , Ks ... >;
65
66 ////////////////
67 // FaceEdges //
68 ////////////////
69 struct FaceEdges
70 {
71 IsoEdge edges[2];
72 int count;
73 FaceEdges( void ) : count(-1){}
74 };
75
76 /////////////////
77 // SliceValues //
78 /////////////////
79 struct SliceValues
80 {
81 struct Scratch
82 {
83 using FKeyValues = std::vector< std::vector< std::pair< Key , std::vector< IsoEdge > > > >;
84 using EKeyValues = std::vector< std::vector< std::pair< Key , node_index_type > > >;
85 using VKeyValues = std::vector< std::vector< std::pair< Key , Key > > >;
86
87 FKeyValues fKeyValues;
88 EKeyValues eKeyValues;
89 VKeyValues vKeyValues;
90
91 #ifdef SANITIZED_PR
92 Pointer( std::atomic< char > ) cSet;
93 Pointer( std::atomic< char > ) eSet;
94 #else // !SANITIZED_PR
95 Pointer( char ) cSet;
96 Pointer( char ) eSet;
97 #endif // SANITIZED_PR
98
99 Scratch( void )
100 {
101 vKeyValues.resize( ThreadPool::NumThreads() );
102 eKeyValues.resize( ThreadPool::NumThreads() );
103 fKeyValues.resize( ThreadPool::NumThreads() );
104 #ifdef SANITIZED_PR
105 cSet = NullPointer( std::atomic< char > );
106 eSet = NullPointer( std::atomic< char > );
107 #else // !SANITIZED_PR
108 cSet = NullPointer( char );
109 eSet = NullPointer( char );
110 #endif // SANITIZED_PR
111 }
112
113 ~Scratch( void )
114 {
115 #ifdef SANITIZED_PR
116 DeletePointer( cSet );
117 DeletePointer( eSet );
118 #else // !SANITIZED_PR
119 FreePointer( cSet );
120 FreePointer( eSet );
121 #endif // SANITIZED_PR
122 }
123
124 void reset( const LevelSetExtraction::FullCellIndexData< Dim > &cellIndices )
125 {
126 for( size_t i=0 ; i<vKeyValues.size() ; i++ ) vKeyValues[i].clear();
127 for( size_t i=0 ; i<eKeyValues.size() ; i++ ) eKeyValues[i].clear();
128 for( size_t i=0 ; i<fKeyValues.size() ; i++ ) fKeyValues[i].clear();
129 #ifdef SANITIZED_PR
130 DeletePointer( cSet );
131 DeletePointer( eSet );
132 if( cellIndices.counts[0] )
133 {
134 cSet = NewPointer< std::atomic< char > >( cellIndices.counts[0] );
135 for( unsigned int i=0 ; i<cellIndices.counts[0] ; i++ ) cSet[i] = 0;
136 }
137 if( cellIndices.counts[1] )
138 {
139 eSet = NewPointer< std::atomic< char > >( cellIndices.counts[1] );
140 for( unsigned int i=0 ; i<cellIndices.counts[1] ; i++ ) eSet[i] = 0;
141 }
142 #else // !SANITIZED_PR
143 FreePointer( cSet );
144 FreePointer( eSet );
145 if( cellIndices.counts[0] )
146 {
147 cSet = AllocPointer< char >( cellIndices.counts[0] );
148 memset( cSet , 0 , sizeof( char ) * cellIndices.counts[0] );
149 }
150 if( cellIndices.counts[1] )
151 {
152 eSet = AllocPointer< char >( cellIndices.counts[1] );
153 memset( eSet , 0 , sizeof( char ) * cellIndices.counts[1] );
154 }
155 #endif // SANITIZED_PR
156 }
157 };
158
159 // A data-structure for taking the a node index and the local index of a cell within the node and returning the global index for that cell
160 LevelSetExtraction::FullCellIndexData< Dim > cellIndices;
161
162 // A table taking a node index and returning the associated marching squares index
163 Pointer( char ) mcIndices;
164
165 // Tables taking a corner index and returning the value (and possibly the gradient) at the corresponding location
166 Pointer( Real ) cornerValues ; Pointer( Point< Real , Dim > ) cornerGradients;
167
168 // A table taking an edge index and returning the associated key
169 Pointer( Key ) edgeKeys;
170
171 // A table taking a face index and returning the associated key
172 Pointer( FaceEdges ) faceEdges;
173
174 // A map taking a key for a face and returning the iso-edges within that face
175 LevelSetExtraction::KeyMap< Dim , std::vector< IsoEdge > > faceEdgeMap;
176 // A map taking a key for an edge and returning the index of the iso-vertex along that edge
177 LevelSetExtraction::KeyMap< Dim , node_index_type > edgeVertexMap;
178 // A map linking an iso-vertex to its pair
179 LevelSetExtraction::KeyMap< Dim , Key > vertexPairMap;
180
181 SliceValues( void )
182 {
183 cornerValues = NullPointer( Real ) ; cornerGradients = NullPointer( Point< Real , Dim > );
184 edgeKeys = NullPointer( Key );
185 faceEdges = NullPointer( FaceEdges );
186 mcIndices = NullPointer( char );
187 }
188
189 ~SliceValues( void ){ clear(); }
190
191 void clear( void )
192 {
193 cellIndices.clear();
194 FreePointer( cornerValues ) ; FreePointer( cornerGradients );
195 DeletePointer( edgeKeys );
196 DeletePointer( faceEdges );
197 FreePointer( mcIndices );
198 }
199
200 void read( BinaryStream &stream )
201 {
202 clear();
203
204 cellIndices.read( stream );
205
206 if( cellIndices.size() )
207 {
208 mcIndices = AllocPointer< char >( cellIndices.size() );
209 if( !stream.read( mcIndices , cellIndices.size() ) ) MK_THROW( "Failed to read mc indices" );
210 }
211 if( cellIndices.counts[0] )
212 {
213 cornerValues = AllocPointer< Real >( cellIndices.counts[0] );
214 if( !stream.read( cornerValues , cellIndices.counts[0] ) ) MK_THROW( "Failed to read corner values" );
215 char hasCornerGradients;
216 if( !stream.read( hasCornerGradients ) ) MK_THROW( "Could not read corner gradient state" );
217 if( hasCornerGradients )
218 {
219 cornerGradients = AllocPointer< Point< Real , Dim > >( cellIndices.counts[0] );
220 if( !stream.read( cornerGradients , cellIndices.counts[0] ) ) MK_THROW( "Could not read corner gradients" );
221 }
222 }
223
224 if( cellIndices.counts[1] )
225 {
226 edgeKeys = NewPointer< Key >( cellIndices.counts[1] );
227 if( !stream.read( edgeKeys , cellIndices.counts[1]) ) MK_THROW( "Could not read edge keys" );
228 }
229
230 if( cellIndices.counts[2] )
231 {
232 faceEdges = NewPointer< FaceEdges >( cellIndices.counts[2] );
233 if( !stream.read( faceEdges , cellIndices.counts[2] ) ) MK_THROW( "Could not read face edges" );
234 }
235
236 auto ReadIsoEdgeVector = [&]( BinaryStream &stream , std::vector< IsoEdge > &edges )
237 {
238 size_t sz;
239 if( !stream.read( sz ) ) MK_THROW( "Could not read iso-edge vector size" );
240 edges.resize( sz );
241 if( sz && !stream.read( GetPointer( edges ) , sz ) ) MK_THROW( "Could not read iso-edges" );
242 };
243 {
244 size_t sz;
245 if( !stream.read( sz ) ) MK_THROW( "Could not read face-edge-map size" );
246 for( unsigned int i=0 ; i<sz ; i++ )
247 {
248 Key key;
249 if( !stream.read( key ) ) MK_THROW( "Could not read face-edge-map key" );
250 ReadIsoEdgeVector( stream , faceEdgeMap[key] );
251 }
252 }
253 {
254 size_t sz;
255 if( !stream.read( sz ) ) MK_THROW( "Could not read edge-vertex-map size" );
256 for( unsigned int i=0 ; i<sz ; i++ )
257 {
258 Key key;
259 if( !stream.read( key ) ) MK_THROW( "Could not read edge-vertex-map key" );
260 if( !stream.read( edgeVertexMap[key] ) ) MK_THROW( "Could not read edge-vertex-map value" );
261 }
262 }
263 {
264 size_t sz;
265 if( !stream.read( sz ) ) MK_THROW( "Could not read vertex-pair-map size" );
266 for( unsigned int i=0 ; i<sz ; i++ )
267 {
268 Key key;
269 if( !stream.read( key ) ) MK_THROW( "Could not read vertex-pair-map key" );
270 if( !stream.read( vertexPairMap[key] ) ) MK_THROW( "Could not read vertex-pair-map value" );
271 }
272 }
273 }
274
275 void write( BinaryStream &stream , bool serialize ) const
276 {
277 cellIndices.write( stream );
278
279 if( cellIndices.size() ) stream.write( mcIndices , cellIndices.size() );
280 if( cellIndices.counts[0] )
281 {
282 stream.write( cornerValues , cellIndices.counts[0] );
283 char hasCornerGradients = cornerGradients==NullPointer( char ) ? 0 : 1;
284 stream.write( hasCornerGradients );
285 if( hasCornerGradients ) stream.write( cornerGradients , cellIndices.counts[0] );
286 }
287 if( cellIndices.counts[1] ) stream.write( edgeKeys , cellIndices.counts[1] );
288 if( cellIndices.counts[2] ) stream.write( faceEdges , cellIndices.counts[2] );
289
290 auto WriteIsoEdgeVector = [&]( BinaryStream &stream , const std::vector< IsoEdge > &edges )
291 {
292 size_t sz = edges.size();
293 stream.write( sz );
294 if( sz ) stream.write( GetPointer( edges ) , sz );
295 };
296
297 auto SerializeFaceEdgeMap = [&]( size_t &sz )
298 {
299 using map = LevelSetExtraction::KeyMap< Dim , std::vector< IsoEdge > >;
300
301 sz = 0;
302 for( typename map::const_iterator iter=faceEdgeMap.begin() ; iter!=faceEdgeMap.end() ; iter++ )
303 sz += sizeof( typename LevelSetExtraction::Key< Dim > ) + sizeof( size_t ) + sizeof( IsoEdge ) * iter->second.size();
304
305 Pointer( char ) buffer = NewPointer< char >( sz );
306 Pointer( char ) _buffer = buffer;
307 for( typename map::const_iterator iter=faceEdgeMap.begin() ; iter!=faceEdgeMap.end() ; iter++ )
308 {
309 memcpy( _buffer , &iter->first , sizeof( typename LevelSetExtraction::Key< Dim > ) ) ; _buffer += sizeof( typename LevelSetExtraction::Key< Dim > );
310 size_t num = iter->second.size();
311 memcpy( _buffer , &num , sizeof( size_t ) ) ; _buffer += sizeof( size_t );
312 if( num ) memcpy( _buffer , &iter->second[0] , sizeof(IsoEdge) * iter->second.size() ) ; _buffer += sizeof(IsoEdge) * iter->second.size();
313 }
314 return buffer;
315 };
316
317 {
318 using map = LevelSetExtraction::KeyMap< Dim , std::vector< IsoEdge > >;
319 if( serialize )
320 {
321 size_t sz = faceEdgeMap.size();
322 stream.write( sz );
323 if( sz )
324 {
325 Pointer( char ) buffer = SerializeFaceEdgeMap( sz );
326 stream.write( buffer , sz );
327 DeletePointer( buffer );
328 }
329 }
330 else
331 {
332 size_t sz = faceEdgeMap.size();
333 stream.write( sz );
334 for( typename map::const_iterator iter=faceEdgeMap.begin() ; iter!=faceEdgeMap.end() ; iter++ )
335 {
336 stream.write( iter->first );
337 WriteIsoEdgeVector( stream , iter->second );
338 }
339 }
340 }
341
342 {
343 using map = LevelSetExtraction::KeyMap< Dim , node_index_type >;
344 if( serialize )
345 {
346 size_t sz = edgeVertexMap.size();
347 stream.write( sz );
348 if( sz )
349 {
350 size_t elementSize = sizeof( typename LevelSetExtraction::Key< Dim > ) + sizeof( node_index_type );
351 Pointer( char ) buffer = NewPointer< char >( edgeVertexMap.size() * elementSize );
352 {
353 Pointer( char ) _buffer = buffer;
354 for( typename map::const_iterator iter=edgeVertexMap.begin() ; iter!=edgeVertexMap.end() ; iter++ )
355 {
356 memcpy( _buffer , &iter->first , sizeof( typename LevelSetExtraction::Key< Dim > ) ) ; _buffer += sizeof( typename LevelSetExtraction::Key< Dim > );
357 memcpy( _buffer , &iter->second , sizeof( node_index_type ) ) ; _buffer += sizeof( node_index_type );
358 }
359 }
360 stream.write( buffer , edgeVertexMap.size() * elementSize );
361 DeletePointer( buffer );
362 }
363 }
364 else
365 {
366 size_t sz = edgeVertexMap.size();
367 stream.write( sz );
368 for( typename map::const_iterator iter=edgeVertexMap.begin() ; iter!=edgeVertexMap.end() ; iter++ )
369 {
370 stream.write( iter->first );
371 stream.write( iter->second );
372 }
373 }
374 }
375
376 {
377 using map = LevelSetExtraction::KeyMap< Dim , Key >;
378 if( serialize )
379 {
380 std::vector< std::pair< typename LevelSetExtraction::Key< Dim > , Key > > pairs;
381 pairs.reserve( vertexPairMap.size() );
382 for( typename map::const_iterator iter=vertexPairMap.begin() ; iter!=vertexPairMap.end() ; iter++ )
383 pairs.push_back( std::pair< typename LevelSetExtraction::Key< Dim > , Key >( iter->first , iter->second ) );
384 stream.write( pairs );
385 }
386 else
387 {
388 size_t sz = vertexPairMap.size();
389 stream.write( sz );
390 for( typename map::const_iterator iter=vertexPairMap.begin() ; iter!=vertexPairMap.end() ; iter++ )
391 {
392 stream.write( iter->first );
393 stream.write( iter->second );
394 }
395 }
396 }
397 }
398
399 void setFromScratch( typename Scratch::EKeyValues &scratch )
400 {
401 for( node_index_type i=0 ; i<(node_index_type)scratch.size() ; i++ )
402 {
403 for( int j=0 ; j<scratch[i].size() ; j++ ) edgeVertexMap[ scratch[i][j].first ] = scratch[i][j].second;
404 scratch[i].clear();
405 }
406 }
407
408 void setFromScratch( typename Scratch::VKeyValues &scratch )
409 {
410 for( node_index_type i=0 ; i<(node_index_type)scratch.size() ; i++ )
411 {
412 for( int j=0 ; j<scratch[i].size() ; j++ )
413 {
414 // Note that both vertices are added as keys
415 vertexPairMap[ scratch[i][j].first ] = scratch[i][j].second;
416 vertexPairMap[ scratch[i][j].second ] = scratch[i][j].first;
417 }
418 scratch[i].clear();
419 }
420 }
421
422 void setFromScratch( typename Scratch::FKeyValues &scratch )
423 {
424 for( node_index_type i=0 ; i<(node_index_type)scratch.size() ; i++ )
425 {
426 for( int j=0 ; j<scratch[i].size() ; j++ )
427 {
428 std::vector< IsoEdge > &faceEdges = faceEdgeMap[ scratch[i][j].first ];
429 faceEdges.insert( faceEdges.end() , scratch[i][j].second.begin() , scratch[i][j].second.end() );
430 }
431 scratch[i].clear();
432 }
433 }
434
435 void reset( bool computeGradients )
436 {
437 faceEdgeMap.clear() , edgeVertexMap.clear() , vertexPairMap.clear();
438
439 FreePointer( mcIndices );
440 if( cellIndices.size()>0 ) mcIndices = AllocPointer< char >( cellIndices.size() );
441
442 FreePointer( cornerValues ) ; FreePointer( cornerGradients );
443 if( cellIndices.counts[0]>0 )
444 {
445 cornerValues = AllocPointer< Real >( cellIndices.counts[0] );
446 if( computeGradients ) cornerGradients = AllocPointer< Point< Real , Dim > >( cellIndices.counts[0] );
447 }
448
449 DeletePointer( edgeKeys );
450 edgeKeys = NewPointer< Key >( cellIndices.counts[1] );
451
452 DeletePointer( faceEdges );
453 faceEdges = NewPointer< FaceEdges >( cellIndices.counts[2] );
454
455 }
456
457 bool setVertexPair( Key current , Key &pair ) const
458 {
459 typename LevelSetExtraction::KeyMap< Dim , Key >::const_iterator iter;
460
461 if( (iter=vertexPairMap.find(current))!=vertexPairMap.end() )
462 {
463 pair = iter->second;
464 return true;
465 }
466 else return false;
467 }
468 };
469
470 struct TreeSliceValuesAndVertexPositions
471 {
472 const FEMTree< Dim , Real > sliceTree;
473 std::vector< SliceValues > sliceValues;
474 // [WARNING] Should really be using Vertex instead of Point< Real , Dim >
475 std::vector< Point< Real , Dim > > vertexPositions;
476
477 TreeSliceValuesAndVertexPositions( void ) : sliceTree(NULL){}
478 TreeSliceValuesAndVertexPositions( BinaryStream &stream , XForm< Real , Dim+1 > &xForm , size_t blockSize ) : sliceTree( stream , blockSize )
479 {
480 stream.read( xForm );
481
482 size_t sz;
483 if( !stream.read( sz ) ) MK_THROW( "Could not read slice count" );
484 sliceValues.resize( sz );
485 for( unsigned int i=0 ; i<sliceValues.size() ; i++ ) sliceValues[i].read( stream );
486 if( !stream.read( sz ) ) MK_THROW( "Could not read iso-vertex count" );
487 if( sz )
488 {
489 vertexPositions.resize( sz );
490 if( sz && !stream.read( GetPointer( vertexPositions ) , sz ) ) MK_THROW( "Could not read iso-vertex positions" );
491 }
492 }
493
494 std::vector< Key > vertexKeys( void ) const
495 {
496 std::vector< Key > keys( vertexPositions.size() );
497 for( unsigned int i=0 ; i<sliceValues.size() ; i++ )
498 for( typename LevelSetExtraction::KeyMap< Dim , node_index_type >::const_iterator iter=sliceValues[i].edgeVertexMap.cbegin() ; iter!=sliceValues[i].edgeVertexMap.cend() ; iter++ )
499 {
500 if( iter->second>=(node_index_type)vertexPositions.size() ) MK_THROW( "Unexpected vertex index: " , iter->second , " <= " , vertexPositions.size() );
501 keys[iter->second] = iter->first;
502 }
503 return keys;
504 };
505
506 static void Write( BinaryStream &stream , const FEMTree< Dim , Real > *sliceTree , XForm< Real , Dim+1 > xForm , const std::vector< SliceValues > &sliceValues , const std::vector< Point< Real , Dim > > &vertices , bool serialize )
507 {
508 sliceTree->write( stream , serialize );
509 stream.write( xForm );
510
511 size_t sz = sliceValues.size();
512 stream.write( sz );
513 for( unsigned int i=0 ; i<sliceValues.size() ; i++ ) sliceValues[i].write( stream , serialize );
514
515 stream.write( vertices );
516 }
517
518 void write( BinaryStream &stream , XForm< Real , Dim+1 > xForm , bool serialize ) const
519 {
520 Write( stream , &sliceTree , xForm , sliceValues , vertexPositions , serialize );
521 }
522 };
523
524
525 template< unsigned int ... FEMSigs >
526 static void SetSCornerValues( const FEMTree< Dim , Real >& tree , ConstPointer( Real ) coefficients , ConstPointer( Real ) coarseCoefficients , Real isoValue , LocalDepth depth , LocalDepth fullDepth , std::vector< SliceValues >& sliceValues , std::vector< typename SliceValues::Scratch > &scratchValues , const _Evaluator< UIntPack< FEMSigs ... > , 1 >& evaluator )
527 {
528 static const unsigned int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... };
529 SliceValues& sValues = sliceValues[depth];
530 #ifdef SANITIZED_PR
531 Pointer( std::atomic< char > ) cornerSet = scratchValues[depth].cSet;
532 #else // !SANITIZED_PR
533 Pointer( char ) cornerSet = scratchValues[depth].cSet;
534 #endif // SANITIZED_PR
535 bool useBoundaryEvaluation = false;
536 for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 || ( FEMDegrees[d]==1 && sValues.cornerGradients ) ) useBoundaryEvaluation = true;
537 std::vector< ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > neighborKeys( ThreadPool::NumThreads() );
538 std::vector< ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > > > bNeighborKeys( ThreadPool::NumThreads() );
539 if( useBoundaryEvaluation ) for( size_t i=0 ; i<neighborKeys.size() ; i++ ) bNeighborKeys[i].set( tree._localToGlobal( depth ) );
540 else for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) );
541 ThreadPool::ParallelFor( tree._sNodesBegin(depth) , tree._sNodesEnd(depth) , [&]( unsigned int thread , size_t i )
542 {
543 if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
544 {
545 Real squareValues[ HyperCube::Cube< Dim >::template ElementNum< 0 >() ];
546 ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey = neighborKeys[ thread ];
547 ConstCornerSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bNeighborKey = bNeighborKeys[ thread ];
548 TreeNode* leaf = tree._sNodes.treeNodes[i];
549 // Iterate over all leaf nodes
550 if( !IsActiveNode< Dim >( leaf->children ) )
551 {
552 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<0> &cIndices = sValues.cellIndices.template indices<0>( leaf );
553
554 bool isInterior = tree._isInteriorlySupported( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , leaf->parent );
555 if( useBoundaryEvaluation ) bNeighborKey.getNeighbors( leaf );
556 else neighborKey.getNeighbors( leaf );
557
558 // Iterate over the corners of the cell
559 for( typename HyperCube::Cube< Dim >::template Element< 0 > c ; c<HyperCube::Cube< Dim >::template ElementNum< 0 >() ; c++ )
560 {
561 // Grab the global corner index, and if its value hasn't been set yet get the values (and gradients) and store them
562 node_index_type vIndex = cIndices[c.index];
563 if( !cornerSet[vIndex] )
564 {
565 if( sValues.cornerGradients )
566 {
567 CumulativeDerivativeValues< Real , Dim , 1 > p;
568 if( useBoundaryEvaluation ) p = tree.template _getCornerValues< Real , 1 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior );
569 else p = tree.template _getCornerValues< Real , 1 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior );
570 sValues.cornerValues[vIndex] = p[0] , sValues.cornerGradients[vIndex] = Point< Real , Dim >( p[1] , p[2] );
571 }
572 else
573 {
574 if( useBoundaryEvaluation ) sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( bNeighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0];
575 else sValues.cornerValues[vIndex] = tree.template _getCornerValues< Real , 0 >( neighborKey , leaf , c.index , coefficients , coarseCoefficients , evaluator , tree._maxDepth , isInterior )[0];
576 }
577 cornerSet[vIndex] = 1;
578 }
579 squareValues[c.index] = sValues.cornerValues[ vIndex ];
580
581 // Copy from the finer depth to the coarser depth
582 TreeNode* node = leaf;
583 LocalDepth _depth = depth;
584 // Iterate to the parents as long as they contain the corner
585 while( _depth>fullDepth && tree._isValidSpaceNode( node->parent ) && (node-node->parent->children)==c.index )
586 {
587 node = node->parent , _depth--;
588 SliceValues& _sValues = sliceValues[_depth];
589 #ifdef SANITIZED_PR
590 Pointer( std::atomic< char > ) _cornerSet = scratchValues[_depth].cSet;
591 #else // !SANITIZED_PR
592 Pointer( char ) _cornerSet = scratchValues[_depth].cSet;
593 #endif // SANITIZED_PR
594 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<0> &_cIndices = _sValues.cellIndices.template indices<0>( node );
595 node_index_type _vIndex = _cIndices[c.index];
596 _sValues.cornerValues[_vIndex] = sValues.cornerValues[vIndex];
597 if( _sValues.cornerGradients ) _sValues.cornerGradients[_vIndex] = sValues.cornerGradients[vIndex];
598 _cornerSet[_vIndex] = 1;
599 }
600 }
601
602 // Set the marching squares index for the face
603 sValues.mcIndices[ i - sValues.cellIndices.nodeOffset ] = HyperCube::Cube< Dim >::MCIndex( squareValues , isoValue );
604 }
605 }
606 }
607 );
608 }
609
610
611 template< unsigned int WeightDegree , unsigned int DataSig , typename VertexStream >
612 static void SetIsoVertices
613 (
614 const LevelSetExtraction::KeyGenerator< Dim > &keyGenerator ,
615 const FEMTree< Dim , Real >& tree ,
616 bool nonLinearFit ,
617 bool outputGradients ,
618 typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > > *pointEvaluator ,
619 const DensityEstimator< WeightDegree > *densityWeights ,
620 const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data ,
621 Real isoValue ,
622 LocalDepth depth ,
623 LocalDepth fullDepth ,
624 VertexStream &vertexStream ,
625 std::vector< SliceValues > &sliceValues ,
626 std::vector< typename SliceValues::Scratch > &scratchValues ,
627 const Data &zeroData
628 )
629 {
630 auto _EdgeIndex = [&]( const TreeNode *node , typename HyperCube::Cube< Dim >::template Element< 1 > e )
631 {
632 int depth , offset[Dim];
633 tree.depthAndOffset( node , depth , offset );
634 return keyGenerator( depth , offset , e );
635 };
636 static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
637
638 SliceValues &sValues = sliceValues[depth];
639 typename SliceValues::Scratch &scValues = scratchValues[depth];
640 // [WARNING] In the case Degree=2, these two keys are the same, so we don't have to maintain them separately.
641 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
642 std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > > > weightKeys( ThreadPool::NumThreads() );
643 std::vector< ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > > > dataKeys( ThreadPool::NumThreads() );
644 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) ) , weightKeys[i].set( tree._localToGlobal( depth ) ) , dataKeys[i].set( tree._localToGlobal( depth ) );
645
646 ThreadPool::ParallelFor( tree._sNodesBegin(depth) , tree._sNodesEnd(depth) , [&]( unsigned int thread , size_t i )
647 {
648 if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
649 {
650 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
651 ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey = weightKeys[ thread ];
652 ConstPointSupportKey< IsotropicUIntPack< Dim , DataDegree > >& dataKey = dataKeys[ thread ];
653 TreeNode* leaf = tree._sNodes.treeNodes[i];
654
655 // Iterate over all leaf nodes in the tree
656 if( !IsActiveNode< Dim >( leaf->children ) )
657 {
658 node_index_type idx = (node_index_type)i - sValues.cellIndices.nodeOffset;
659 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<1> eIndices = sValues.cellIndices.template indices<1>( leaf );
660
661 // Check if the face has zero-crossings
662 if( HyperCube::Cube< Dim >::HasMCRoots( sValues.mcIndices[idx] ) )
663 {
664 neighborKey.getNeighbors( leaf );
665 if( densityWeights ) weightKey.getNeighbors( leaf );
666 if constexpr( HasData ) if( data ) dataKey.getNeighbors( leaf );
667
668 // Check if the individual edges have zero-crossings
669 for( typename HyperCube::Cube< Dim >::template Element< 1 > e ; e<HyperCube::Cube< Dim >::template ElementNum< 1 >() ; e++ )
670 if( HyperCube::Cube< 1 >::HasMCRoots( HyperCube::Cube< Dim >::ElementMCIndex( e , sValues.mcIndices[idx] ) ) )
671 {
672 node_index_type vIndex = eIndices[e.index];
673 #ifdef SANITIZED_PR
674 std::atomic< char > &edgeSet = scValues.eSet[vIndex];
675 #else // !SANITIZED_PR
676 volatile char &edgeSet = scValues.eSet[vIndex];
677 #endif // SANITIZED_PR
678 // If the edge hasn't been set already (e.g. either by another thread or from a finer resolution)
679 if( !edgeSet )
680 {
681 Vertex vertex;
682 Key key = _EdgeIndex( leaf , e );
683 GetIsoVertex< WeightDegree , DataSig >( tree , nonLinearFit , outputGradients , pointEvaluator , densityWeights , data , isoValue , weightKey , dataKey , leaf , e , sValues , vertex , zeroData );
684 bool stillOwner = false;
685 std::pair< node_index_type , Vertex > hashed_vertex;
686
687 {
688 char desired = 1 , expected = 0;
689 #ifdef SANITIZED_PR
690 if( edgeSet.compare_exchange_weak( expected , desired ) )
691 #else // !SANITIZED_PR
692 if( SetAtomic( edgeSet , desired , expected ) )
693 #endif // SANITIZED_PR
694 {
695 hashed_vertex = std::pair< node_index_type , Vertex >( (node_index_type)vertexStream.write( thread , vertex ) , vertex );
696 stillOwner = true;
697 }
698 }
699
700 if( stillOwner ) // If this edge is the one generating the iso-vertex
701 {
702 sValues.edgeKeys[ vIndex ] = key;
703 scValues.eKeyValues[ thread ].push_back( std::pair< Key , node_index_type >( key , hashed_vertex.first ) );
704
705 // We only need to pass the iso-vertex down if the edge it lies on is adjacent to a coarser leaf
706 const typename HyperCube::Cube< Dim >::template Element< Dim > *f = HyperCubeTables< Dim , 1 , Dim >::OverlapElements[e.index];
707 // Note that this is a trivial loop of size 1
708 for( int k=0 ; k<HyperCubeTables< Dim , 1 , Dim >::OverlapElementNum ; k++ )
709 {
710 TreeNode *node = leaf;
711 LocalDepth _depth = depth;
712 while( _depth>fullDepth && tree._isValidSpaceNode( node->parent ) && HyperCubeTables< Dim , Dim , 0 >::Overlap[f[k].index][(unsigned int)(node-node->parent->children) ] )
713 {
714 node = node->parent , _depth--;
715 typename SliceValues::Scratch &_scValues = scratchValues[_depth];
716 _scValues.eKeyValues[ thread ].push_back( std::pair< Key , node_index_type >( key , hashed_vertex.first ) );
717 }
718 }
719 }
720 }
721 }
722 }
723 }
724 }
725 }
726 );
727 }
728
729 static void CopyFinerSliceIsoEdgeKeys( const FEMTree< Dim , Real >& tree , LocalDepth depth , LocalDepth fullDepth , std::vector< SliceValues >& sliceValues , std::vector< typename SliceValues::Scratch > &scratchValues )
730 {
731 SliceValues& pSliceValues = sliceValues[depth ];
732 SliceValues& cSliceValues = sliceValues[depth+1];
733 typename SliceValues::Scratch &pScratchSliceValues = scratchValues[depth ];
734 typename SliceValues::Scratch &cScratchSliceValues = scratchValues[depth+1];
735 LevelSetExtraction::FullCellIndexData< Dim > &pCellIndices = pSliceValues.cellIndices;
736 LevelSetExtraction::FullCellIndexData< Dim > &cCellIndices = cSliceValues.cellIndices;
737 ThreadPool::ParallelFor( tree._sNodesBegin(depth) , tree._sNodesEnd(depth) , [&]( unsigned int thread , size_t i )
738 {
739 if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) ) if( IsActiveNode< Dim >( tree._sNodes.treeNodes[i]->children ) )
740 {
741 // Get the mapping from local edge indices to global edge indices
742 typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<1> &pIndices = pCellIndices.template indices<1>( (node_index_type)i );
743 // Copy the edges that overlap the coarser edges
744 for( typename HyperCube::Cube< Dim >::template Element< 1 > e ; e<HyperCube::Cube< Dim >::template ElementNum< 1 >() ; e++ )
745 {
746 // The global (coarse) edge index
747 node_index_type pIndex = pIndices[e.index];
748 if( !pScratchSliceValues.eSet[ pIndex ] )
749 {
750 // The corner indices incident on the edeg
751 const typename HyperCube::Cube< Dim >::template Element< 0 > *c = HyperCubeTables< Dim , 1 , 0 >::OverlapElements[e.index];
752 // [SANITY CHECK]
753 // if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index )!=tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) MK_THROW( "Finer edges should both be valid or invalid" );
754 // Can only copy edge information from the finer nodes incident on the edge if they are valid (note since we refine in broods, we can't have one child in and the other out)
755 if( !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[0].index ) || !tree._isValidSpaceNode( tree._sNodes.treeNodes[i]->children + c[1].index ) ) continue;
756
757
758 // The global (fine) edge indices
759 node_index_type cIndex1 = cCellIndices.template indices<1>( tree._sNodes.treeNodes[i]->children + c[0].index )[e.index];
760 node_index_type cIndex2 = cCellIndices.template indices<1>( tree._sNodes.treeNodes[i]->children + c[1].index )[e.index];
761
762 // If only one of the finer edges has a zero-crossing, then the coarse edge will as well
763 if( cScratchSliceValues.eSet[cIndex1] != cScratchSliceValues.eSet[cIndex2] )
764 {
765 Key key;
766 if( cScratchSliceValues.eSet[cIndex1] ) key = cSliceValues.edgeKeys[cIndex1];
767 else key = cSliceValues.edgeKeys[cIndex2];
768 pSliceValues.edgeKeys[pIndex] = key;
769 pScratchSliceValues.eSet[pIndex] = 1;
770 }
771 // If both of the finer edges have a zero-crossing, those will form a pair (but the coarser edge will not have a zero crossing)
772 else if( cScratchSliceValues.eSet[cIndex1] && cScratchSliceValues.eSet[cIndex2] )
773 {
774 Key key1 = cSliceValues.edgeKeys[cIndex1] , key2 = cSliceValues.edgeKeys[cIndex2];
775 pScratchSliceValues.vKeyValues[ thread ].push_back( std::pair< Key , Key >( key1 , key2 ) );
776
777 const TreeNode* node = tree._sNodes.treeNodes[i];
778 LocalDepth _depth = depth;
779 while( _depth>fullDepth && tree._isValidSpaceNode( node->parent ) && HyperCubeTables< Dim , 1 , 0 >::Overlap[e.index][(unsigned int)(node-node->parent->children) ] )
780 {
781 node = node->parent , _depth--;
782 typename SliceValues::Scratch &_pScratchSliceValues = scratchValues[_depth];
783 _pScratchSliceValues.vKeyValues[ thread ].push_back( std::pair< Key , Key >( key1 , key2 ) );
784 }
785 }
786 }
787 }
788 }
789 }
790 );
791 }
792
793
794 static void SetIsoEdges( const LevelSetExtraction::KeyGenerator< Dim > &keyGenerator , const FEMTree< Dim , Real >& tree , LocalDepth depth , LocalDepth fullDepth , std::vector< SliceValues >& sliceValues , std::vector< typename SliceValues::Scratch > &scratchValues )
795 {
796 auto _FaceIndex = [&]( const TreeNode *node , typename HyperCube::Cube< Dim >::template Element< 2 > f )
797 {
798 int depth , offset[Dim];
799 tree.depthAndOffset( node , depth , offset );
800 return keyGenerator( depth , offset , f );
801 };
802
803 SliceValues& sValues = sliceValues[depth];
804 #ifdef SANITIZED_PR
805 Pointer( std::atomic< char > ) edgeSet = scratchValues[depth].eSet;
806 #else // !SANITIZED_PR
807 Pointer( char ) edgeSet = scratchValues[depth].eSet;
808 #endif // SANITIZED_PR
809 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
810 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( tree._localToGlobal( depth ) );
811 ThreadPool::ParallelFor( tree._sNodesBegin(depth) , tree._sNodesEnd(depth) , [&]( unsigned int thread , size_t i )
812 {
813 if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
814 {
815 int isoEdges[ 2 * HyperCube::MarchingSquares::MAX_EDGES ];
816 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
817 TreeNode* leaf = tree._sNodes.treeNodes[i];
818 // Process the face if it is on a leaf node
819 if( !IsActiveNode< Dim >( leaf->children ) )
820 {
821 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<1> &eIndices = sValues.cellIndices.template indices<1>( leaf );
822 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<2> &fIndices = sValues.cellIndices.template indices<2>( leaf );
823 unsigned char mcIndex = sValues.mcIndices[ (node_index_type)i - sValues.cellIndices.nodeOffset ];
824
825 // [NOTE] We do not add the vector of iso-edges at the depth where they are generate (as there can be at most two).
826 // We only add them to the coarser resolutions.
827 // Calculate the iso-edges for the face
828 FaceEdges fe;
829 fe.count = HyperCube::MarchingSquares::AddEdgeIndices( mcIndex , isoEdges );
830 for( int j=0 ; j<fe.count ; j++ ) for( int k=0 ; k<2 ; k++ )
831 {
832 if( !edgeSet[ eIndices[ isoEdges[2*j+k] ] ] ) MK_THROW( "Edge not set: " , 1<<depth );
833 fe.edges[j][k] = sValues.edgeKeys[ eIndices[ isoEdges[2*j+k] ] ];
834 }
835 sValues.faceEdges[ fIndices[0] ] = fe;
836 // Pass the information to the parents
837 // [NOTE] For the 3D case we ony pass up to the parents if the face-adjacent neighbor does not exists.
838 // That could be bad if we want to use the information to extract from a sub-tree
839 TreeNode *node = leaf;
840 LocalDepth _depth = depth;
841 typename HyperCube::Cube< Dim >::template Element< Dim > f( 0u );
842
843 // Add the edges to the vector of iso-edges associated with a face
844 std::vector< IsoEdge > edges( fe.count );
845 for( int j=0 ; j<fe.count ; j++ ) edges[j] = fe.edges[j];
846 // Add the edges to all ancestors
847 while( _depth>fullDepth && tree._isValidSpaceNode( node->parent ) && HyperCubeTables< Dim , 2 , 0 >::Overlap[f.index][(unsigned int)(node-node->parent->children) ] )
848 {
849 node = node->parent , _depth--;
850 Key key = _FaceIndex( node , f );
851 typename SliceValues::Scratch &_scValues = scratchValues[_depth];
852 _scValues.fKeyValues[ thread ].push_back( std::pair< Key , std::vector< IsoEdge > >( key , edges ) );
853 }
854 }
855 }
856 }
857 );
858 }
859
860 static void SetLevelSet( const LevelSetExtraction::KeyGenerator< Dim > &keyGenerator , const FEMTree< Dim , Real >& tree , LocalDepth depth , const SliceValues &sValues , OutputDataStream< std::pair< node_index_type , node_index_type > >& edgeStream , bool flipOrientation )
861 {
862 auto _FaceIndex = [&]( const TreeNode *node , typename HyperCube::Cube< Dim >::template Element< 2 > f )
863 {
864 int depth , offset[Dim];
865 tree.depthAndOffset( node , depth , offset );
866 return keyGenerator( depth , offset , f );
867 };
868
869 auto AddEdge = [&]( unsigned int thread , IsoEdge e )
870 {
871 typename LevelSetExtraction::KeyMap< Dim , node_index_type >::const_iterator iter;
872 node_index_type idx1 , idx2;
873 if( ( iter=sValues.edgeVertexMap.find( e[0] ) )!=sValues.edgeVertexMap.end() ) idx1 = iter->second;
874 else MK_THROW( "Couldn't find vertex in edge map" );
875 if( ( iter=sValues.edgeVertexMap.find( e[1] ) )!=sValues.edgeVertexMap.end() ) idx2 = iter->second;
876 else MK_THROW( "Couldn't find vertex in edge map" );
877 if( flipOrientation ) edgeStream.write( thread , std::make_pair( idx2 , idx1 ) );
878 else edgeStream.write( thread , std::make_pair( idx1 , idx2 ) );
879 };
880
881 ThreadPool::ParallelFor( tree._sNodesBegin(depth) , tree._sNodesEnd(depth) , [&]( unsigned int thread , size_t i )
882 {
883 if( tree._isValidSpaceNode( tree._sNodes.treeNodes[i] ) )
884 {
885 TreeNode *leaf = tree._sNodes.treeNodes[i];
886 int res = 1<<depth;
887 LocalDepth d ; LocalOffset off;
888 tree._localDepthAndOffset( leaf , d , off );
889 bool inBounds = off[0]>=0 && off[0]<res && off[1]>=0 && off[1]<res;
890
891 if( inBounds && !IsActiveNode< Dim >( leaf->children ) )
892 {
893 // Gather the edges from the faces
894 for( typename HyperCube::Cube< Dim >::template Element< 2 > f ; f<HyperCube::Cube< Dim >::template ElementNum< 2 >() ; f++ )
895 {
896 node_index_type fIdx = sValues.cellIndices.template indices<2>((node_index_type)i)[0];
897 {
898 const FaceEdges& fe = sValues.faceEdges[ fIdx ];
899 for( int j=0 ; j<fe.count ; j++ ) AddEdge( thread , IsoEdge( fe.edges[j][0] , fe.edges[j][1] ) );
900 }
901 }
902 }
903 }
904 }
905 );
906 }
907
908
909 template< unsigned int WeightDegree , unsigned int DataSig >
910 static bool GetIsoVertex( const FEMTree< Dim , Real >& tree , bool nonLinearFit , bool outputGradients , typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , Real isoValue , ConstPointSupportKey< IsotropicUIntPack< Dim , WeightDegree > >& weightKey , ConstPointSupportKey< IsotropicUIntPack< Dim , FEMSignature< DataSig >::Degree > >& dataKey , const TreeNode* node , typename HyperCube::template Cube< Dim >::template Element< 1 > e , const SliceValues& sValues , Vertex& vertex , const Data &zeroData )
911 {
912 static const unsigned int DataDegree = FEMSignature< DataSig >::Degree;
913 Point< Real , Dim > position , gradient;
914 int c0 , c1;
915 const typename HyperCube::Cube< Dim >::template Element< 0 > *c = HyperCubeTables< Dim , 1 , 0 >::OverlapElements[e.index];
916 c0 = c[0].index , c1 = c[1].index;
917
918 const typename LevelSetExtraction::FullCellIndexData< Dim >::template CellIndices<0> &idx = sValues.cellIndices.template indices<0>( node );
919 Real x0 = sValues.cornerValues[idx[c0]] , x1 = sValues.cornerValues[idx[c1]];
920 Point< Real , Dim > dx0 , dx1;
921 if( outputGradients ) dx0 = sValues.cornerGradients[idx[c0]] , dx1 = sValues.cornerGradients[idx[c1]];
922 Point< Real , Dim > s;
923 Real start , width;
924 tree._startAndWidth( node , s , width );
925 int o;
926 {
927 const HyperCube::Direction* dirs = HyperCubeTables< Dim , 1 >::Directions[ e.index ];
928 for( int d=0 ; d<Dim ; d++ ) if( dirs[d]==HyperCube::CROSS )
929 {
930 o = d;
931 start = s[d];
932 for( int dd=1 ; dd<Dim ; dd++ ) position[(d+dd)%Dim] = s[(d+dd)%Dim] + width * ( dirs[(d+dd)%Dim]==HyperCube::BACK ? 0 : 1 );
933 }
934 }
935
936 double averageRoot;
937 bool rootFound = false;
938 if( nonLinearFit )
939 {
940 double dx0 = sValues.cornerGradients[idx[c0]][o] * width , dx1 = sValues.cornerGradients[idx[c1]][o] * width;
941
942 // The scaling will turn the Hermite Spline into a quadratic
943 double scl = (x1-x0) / ( (dx1+dx0 ) / 2 );
944 dx0 *= scl , dx1 *= scl;
945
946 // Hermite Spline
947 Polynomial< 2 > P;
948 P.coefficients[0] = x0;
949 P.coefficients[1] = dx0;
950 P.coefficients[2] = 3*(x1-x0)-dx1-2*dx0;
951
952 double roots[2];
953 int rCount = 0 , rootCount = P.getSolutions( isoValue , roots , 0 );
954 averageRoot = 0;
955 for( int i=0 ; i<rootCount ; i++ ) if( roots[i]>=0 && roots[i]<=1 ) averageRoot += roots[i] , rCount++;
956 if( rCount ) rootFound = true;
957 averageRoot /= rCount;
958 }
959 if( !rootFound )
960 {
961 // We have a linear function L, with L(0) = x0 and L(1) = x1
962 // => L(t) = x0 + t * (x1-x0)
963 // => L(t) = isoValue <=> t = ( isoValue - x0 ) / ( x1 - x0 )
964 if( x0==x1 ) MK_THROW( "Not a zero-crossing root: " , x0 , " " , x1 );
965 averageRoot = ( isoValue - x0 ) / ( x1 - x0 );
966 }
967 if( averageRoot<=0 || averageRoot>=1 )
968 {
969 _BadRootCount++;
970 if( averageRoot<0 ) averageRoot = 0;
971 if( averageRoot>1 ) averageRoot = 1;
972 }
973 position[o] = Real( start + width*averageRoot );
974 gradient = dx0 * (Real)( 1.-averageRoot ) + dx1 * (Real)averageRoot;
975 Real depth = (Real)1.;
976 Data dataValue;
977 if( densityWeights )
978 {
979 Real weight;
980 tree._getSampleDepthAndWeight( *densityWeights , node , position , weightKey , depth , weight );
981 }
982 if constexpr( HasData ) if( data )
983 {
984 if( DataDegree==0 )
985 {
986 Point< Real , 2 > center( s[0] + width/2 , s[1] + width/2 );
987 ProjectiveData< Data , Real > pValue( zeroData );
988 tree.template _addEvaluation< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , center , *pointEvaluator , dataKey , pValue );
989 dataValue = pValue.weight ? pValue.value() : zeroData;
990 }
991 else
992 {
993 ProjectiveData< Data , Real > pValue( zeroData );
994 tree.template _addEvaluation< ProjectiveData< Data , Real > , SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > , 0 >( *data , position , *pointEvaluator , dataKey , pValue );
995 dataValue = pValue.weight ? pValue.value() : zeroData;
996 }
997 }
998 vertex.template get<0>() = position;
999 vertex.template get<1>() = gradient;
1000 vertex.template get<2>() = depth;
1001 if constexpr( HasData ) vertex.template get<3>() = dataValue;
1002 return true;
1003 }
1004
1005 struct Stats
1006 {
1007 double cornersTime , verticesTime , edgesTime , curveTime;
1008 double copyFinerTime , setTableTime;
1009 Stats( void ) : cornersTime(0) , verticesTime(0) , edgesTime(0) , curveTime(0), copyFinerTime(0) , setTableTime(0) {;}
1010 std::string toString( void ) const
1011 {
1012 std::stringstream stream;
1013 stream << "Corners / Vertices / Edges / Curve / Set Table / Copy Finer: ";
1014 stream << std::fixed << std::setprecision(1) << cornersTime << " / " << verticesTime << " / " << edgesTime << " / " << curveTime << " / " << setTableTime << " / " << copyFinerTime;
1015 stream << " (s)";
1016 return stream.str();
1017 }
1018 };
1019
1020 protected:
1021 enum _SetFlag
1022 {
1023 CORNER_VALUES = 1,
1024 ISO_VERTICES = 2,
1025 ISO_EDGES = 4
1026 };
1027
1028 public:
1029 static int SetCornerValuesFlag( void ){ return _SetFlag::CORNER_VALUES; }
1030 static int SetIsoVerticesFlag ( void ){ return _SetFlag::CORNER_VALUES | _SetFlag::ISO_VERTICES; }
1031 static int SetIsoEdgesFlag ( void ){ return _SetFlag::CORNER_VALUES | _SetFlag::ISO_VERTICES | _SetFlag::ISO_EDGES; }
1032
1033 template< unsigned int WeightDegree , unsigned int DataSig , typename VertexStream , unsigned int ... FEMSigs >
1034 static Stats SetSliceValues( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real > &tree , int maxKeyDepth , const DensityEstimator< WeightDegree > *densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > *data , const DenseNodeData< Real , UIntPack< FEMSigs ... > > &coefficients , Real isoValue , VertexStream &vertexStream , const Data &zeroData , bool nonLinearFit , bool outputGradients , std::vector< SliceValues > &sliceValues , int setFlag )
1035 {
1036 if( maxKeyDepth<tree._maxDepth ) MK_THROW( "Max key depth has to be at least tree depth: " , tree._maxDepth , " <= " , maxKeyDepth );
1037 LevelSetExtraction::KeyGenerator< Dim > keyGenerator( maxKeyDepth );
1038 unsigned int slabStart = 0 , slabEnd = 1<<tree._maxDepth;
1039 LocalDepth fullDepth = tree.getFullDepth( UIntPack< FEMSignature< FEMSigs >::Degree ... >() );
1040
1041 _BadRootCount = 0u;
1042 Stats stats;
1043
1044 static_assert( sizeof...(FEMSigs)==Dim , "[ERROR] Number of signatures should match dimension" );
1045 tree._setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
1046 static const int FEMDegrees[] = { FEMSignature< FEMSigs >::Degree ... };
1047 for( int d=0 ; d<Dim ; d++ ) if( FEMDegrees[d]==0 && nonLinearFit ) MK_THROW( "Constant B-Splines do not support gradient estimation" );
1048
1049 LevelSetExtraction::SetHyperCubeTables< Dim >();
1050
1051 typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >* pointEvaluator = NULL;
1052 if constexpr( HasData ) if( data ) pointEvaluator = new typename FEMIntegrator::template PointEvaluator< IsotropicUIntPack< Dim , DataSig > , ZeroUIntPack< Dim > >( tree._maxDepth );
1053 DenseNodeData< Real , UIntPack< FEMSigs ... > > coarseCoefficients( tree._sNodesEnd( tree._maxDepth-1 ) );
1054 memset( coarseCoefficients() , 0 , sizeof(Real)*tree._sNodesEnd( tree._maxDepth-1 ) );
1055 ThreadPool::ParallelFor( tree._sNodesBegin(0) , tree._sNodesEnd( tree._maxDepth-1 ) , [&]( unsigned int, size_t i ){ coarseCoefficients[i] = coefficients[i]; } );
1056 typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp;
1057 for( LocalDepth d=1 ; d<tree._maxDepth ; d++ ) tree._upSample( UIntPack< FEMSigs ... >() , rp , d , ( ConstPointer(Real) )coarseCoefficients()+tree._sNodesBegin(d-1) , coarseCoefficients()+tree._sNodesBegin(d) );
1058
1059 std::vector< _Evaluator< UIntPack< FEMSigs ... > , 1 > > evaluators( tree._maxDepth+1 );
1060 for( LocalDepth d=0 ; d<=tree._maxDepth ; d++ ) evaluators[d].set( tree._maxDepth );
1061
1062 sliceValues.resize( tree._maxDepth+1 );
1063 std::vector< typename SliceValues::Scratch > scratchValues( tree._maxDepth+1 );
1064
1065 // Initialize the slice
1066 for( LocalDepth d=tree._maxDepth ; d>=fullDepth ; d-- )
1067 {
1068 double t = Time();
1069 sliceValues[d].cellIndices.set( tree._sNodes , tree._localToGlobal( d ) );
1070 stats.setTableTime += Time()-t;
1071 sliceValues[d].reset( nonLinearFit || outputGradients );
1072 scratchValues[d].reset( sliceValues[d].cellIndices );
1073 }
1074
1075 for( LocalDepth d=tree._maxDepth; d>=fullDepth ; d-- )
1076 {
1077 // Copy edges from finer
1078 if( setFlag & _SetFlag::ISO_EDGES )
1079 {
1080 double t = Time();
1081 if( d<tree._maxDepth ) CopyFinerSliceIsoEdgeKeys( tree , d , fullDepth , sliceValues , scratchValues );
1082 stats.copyFinerTime += Time()-t;
1083 }
1084
1085 if( setFlag & _SetFlag::CORNER_VALUES )
1086 {
1087 double t = Time();
1088 SetSCornerValues< FEMSigs ... >( tree , coefficients() , coarseCoefficients() , isoValue , d , fullDepth , sliceValues , scratchValues , evaluators[d] );
1089 stats.cornersTime += Time()-t;
1090 }
1091
1092 if( setFlag & _SetFlag::ISO_VERTICES )
1093 {
1094 double t = Time();
1095 SetIsoVertices< WeightDegree , DataSig >( keyGenerator , tree , nonLinearFit , outputGradients , pointEvaluator , densityWeights , data , isoValue , d , fullDepth , vertexStream , sliceValues , scratchValues , zeroData );
1096 stats.verticesTime += Time()-t;
1097 }
1098
1099 if( setFlag & _SetFlag::ISO_EDGES )
1100 {
1101 double t = Time();
1102 SetIsoEdges( keyGenerator , tree , d , fullDepth , sliceValues , scratchValues );
1103 stats.edgesTime += Time()-t , t = Time();
1104 }
1105 }
1106
1107 for( LocalDepth d=tree._maxDepth ; d>=fullDepth ; d-- )
1108 {
1109 ThreadPool::ParallelSections
1110 (
1111 [ &sliceValues , &scratchValues , d ]( void ){ sliceValues[d].setFromScratch( scratchValues[d].vKeyValues ); } ,
1112 [ &sliceValues , &scratchValues , d ]( void ){ sliceValues[d].setFromScratch( scratchValues[d].eKeyValues ); } ,
1113 [ &sliceValues , &scratchValues , d ]( void ){ sliceValues[d].setFromScratch( scratchValues[d].fKeyValues ); }
1114 );
1115 if( ( setFlag & _SetFlag::ISO_VERTICES) && d<tree._maxDepth ) for( auto iter=sliceValues[d+1].vertexPairMap.begin() ; iter!=sliceValues[d+1].vertexPairMap.end() ; iter++ ) sliceValues[d].vertexPairMap[ iter->first ] = iter->second;
1116 }
1117
1118 size_t badRootCount = _BadRootCount;
1119 if( badRootCount!=0 ) MK_WARN( "bad average roots: " , badRootCount );
1120 return stats;
1121 }
1122
1123 static void SetLevelSets( const LevelSetExtraction::KeyGenerator< Dim > &keyGenerator , const FEMTree< Dim , Real >& tree , LocalDepth fullDepth , const std::vector< SliceValues > &sliceValues , OutputDataStream< std::pair< node_index_type , node_index_type > >& edgeStream , bool flipOrientation )
1124 {
1125 for( LocalDepth d=tree._maxDepth ; d>=fullDepth ; d-- ) SetLevelSet( keyGenerator , tree , d , sliceValues[d] , edgeStream , flipOrientation );
1126 }
1127
1128 template< unsigned int WeightDegree , unsigned int DataSig , typename VertexStream , unsigned int ... FEMSigs >
1129 static Stats Extract( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real >& tree , const DensityEstimator< WeightDegree >* densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > >* data , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , Real isoValue , VertexStream &vertexStream , OutputDataStream< std::pair< node_index_type , node_index_type > > &edgeStream , const Data &zeroData , bool nonLinearFit , bool outputGradients , bool flipOrientation )
1130 {
1131 std::vector< SliceValues > sliceValues;
1132
1133 Stats stats = SetSliceValues( UIntPack< FEMSigs ... >() , UIntPack< WeightDegree >() , UIntPack< DataSig >() , tree , tree.maxDepth() , densityWeights , data , coefficients , isoValue , vertexStream , zeroData , nonLinearFit , outputGradients , sliceValues , SetIsoEdgesFlag() );
1134 LevelSetExtraction::KeyGenerator< Dim > keyGenerator( tree.maxDepth() );
1135 {
1136 double t = Time();
1137 SetLevelSets( keyGenerator , tree , tree.getFullDepth( UIntPack< FEMSignature< FEMSigs >::Degree ... >() ) , sliceValues , edgeStream , flipOrientation );
1138 stats.curveTime += Time()-t;
1139 }
1140 return stats;
1141 }
1142 };
1143
1144 template< bool HasData , typename Real , typename Data > std::atomic< size_t > _LevelSetExtractor< HasData , Real , 2 , Data >::_BadRootCount;
1145
1146 template< typename Real >
1147 struct LevelSetExtractor< Real , 2 >
1148 {
1149 static const unsigned int Dim = 2;
1150 static const bool HasData = false;
1151 typedef unsigned char Data;
1152 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::Stats Stats;
1153 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::Vertex Vertex;
1154 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::SliceValues SliceValues;
1155 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::TreeSliceValuesAndVertexPositions TreeSliceValuesAndVertexPositions;
1156 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::TreeNode TreeNode;
1157 using OutputVertexStream = typename _LevelSetExtractor< HasData , Real , Dim , Data >::OutputVertexStream;
1158 template< unsigned int WeightDegree > using DensityEstimator = typename _LevelSetExtractor< HasData , Real , Dim , Data >::template DensityEstimator< WeightDegree >;
1159 static int SetCornerValuesFlag( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetCornerValuesFlag(); }
1160 static int SetIsoVerticesFlag ( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetIsoVerticesFlag (); }
1161 static int SetIsoEdgesFlag ( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetIsoEdgesFlag (); }
1162
1163 template< unsigned int WeightDegree , unsigned int ... FEMSigs >
1164 static Stats Extract( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , const FEMTree< Dim , Real >& tree , const DensityEstimator< WeightDegree >* densityWeights , const DenseNodeData< Real , UIntPack< FEMSigs ... > >& coefficients , Real isoValue , OutputVertexStream &vertexStream , OutputDataStream< std::pair< node_index_type , node_index_type > > &edgeStream , bool nonLinearFit , bool outputGradients , bool flipOrientation )
1165 {
1166 Data zeroData = 0;
1167 static const unsigned int DataSig = FEMDegreeAndBType< 0 , BOUNDARY_FREE >::Signature;
1168 const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > *data = NULL;
1169 return _LevelSetExtractor< HasData , Real , Dim , Data >::template Extract< WeightDegree , DataSig , OutputVertexStream , FEMSigs ... >( UIntPack< FEMSigs ... >() , UIntPack< WeightDegree >() , UIntPack< DataSig >() , tree , densityWeights , data , coefficients , isoValue , vertexStream , edgeStream , zeroData , nonLinearFit , outputGradients , flipOrientation );
1170 }
1171
1172 template< unsigned int WeightDegree , unsigned int ... FEMSigs >
1173 static Stats SetSliceValues( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , const FEMTree< Dim , Real > &tree , int maxKeyDepth , const DensityEstimator< WeightDegree > *densityWeights , const DenseNodeData< Real , UIntPack< FEMSigs ... > > &coefficients , Real isoValue , OutputVertexStream &vertexStream , bool nonLinearFit , bool outputGradients , std::vector< SliceValues > &sliceValues , int setFlag )
1174 {
1175 Data zeroData = 0;
1176 static const unsigned int DataSig = FEMDegreeAndBType< 0 , BOUNDARY_FREE >::Signature;
1177 const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > *data = NULL;
1178 return _LevelSetExtractor< HasData , Real , Dim , Data >::template SetSliceValues< WeightDegree , DataSig , OutputVertexStream , FEMSigs ... >( UIntPack< FEMSigs ... >() , UIntPack< WeightDegree >() , UIntPack< DataSig >() , tree , maxKeyDepth , densityWeights , data , coefficients , isoValue , vertexStream , zeroData , nonLinearFit , outputGradients , sliceValues , setFlag );
1179 }
1180 };
1181
1182 template< typename Real , typename Data >
1183 struct LevelSetExtractor< Real , 2 , Data >
1184 {
1185 static const unsigned int Dim = 2;
1186 static const bool HasData = true;
1187 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::Stats Stats;
1188 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::Vertex Vertex;
1189 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::SliceValues SliceValues;
1190 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::TreeSliceValuesAndVertexPositions TreeSliceValuesAndVertexPositions;
1191 typedef typename _LevelSetExtractor< HasData , Real , Dim , Data >::TreeNode TreeNode;
1192 using OutputVertexStream = typename _LevelSetExtractor< HasData , Real , Dim , Data >::OutputVertexStream;
1193 template< unsigned int WeightDegree > using DensityEstimator = typename _LevelSetExtractor< HasData , Real , Dim , Data >::template DensityEstimator< WeightDegree >;
1194 static int SetCornerValuesFlag( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetCornerValuesFlag(); }
1195 static int SetIsoVerticesFlag ( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetIsoVerticesFlag (); }
1196 static int SetIsoEdgesFlag ( void ){ return _LevelSetExtractor< HasData , Real , Dim , Data >::SetIsoEdgesFlag (); }
1197
1198 template< unsigned int WeightDegree , unsigned int DataSig , unsigned int ... FEMSigs >
1199 static Stats Extract( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real >& tree , const DensityEstimator< WeightDegree > *densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > *data , const DenseNodeData< Real , UIntPack< FEMSigs ... > > &coefficients , Real isoValue , OutputVertexStream &vertexStream , OutputDataStream< std::pair< node_index_type , node_index_type > > &edgeStream , const Data &zeroData , bool nonLinearFit , bool outputGradients , bool flipOrientation )
1200 {
1201 return _LevelSetExtractor< HasData , Real , Dim , Data >::template Extract< WeightDegree , DataSig , OutputVertexStream , FEMSigs ... >( UIntPack< FEMSigs ... >() , UIntPack< WeightDegree >() , UIntPack< DataSig >() , tree , densityWeights , data , coefficients , isoValue , vertexStream , edgeStream , zeroData , nonLinearFit , outputGradients , flipOrientation );
1202 }
1203
1204 template< unsigned int WeightDegree , unsigned int DataSig , unsigned int ... FEMSigs >
1205 static Stats SetSliceValues( UIntPack< FEMSigs ... > , UIntPack< WeightDegree > , UIntPack< DataSig > , const FEMTree< Dim , Real > &tree , int maxKeyDepth , const DensityEstimator< WeightDegree > *densityWeights , const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim , DataSig > > *data , const DenseNodeData< Real , UIntPack< FEMSigs ... > > &coefficients , Real isoValue , OutputVertexStream &vertexStream , const Data &zeroData , bool nonLinearFit , bool outputGradients , std::vector< SliceValues > &sliceValues , int setFlag )
1206 {
1207 return _LevelSetExtractor< HasData , Real , Dim , Data >::template SetSliceValues< WeightDegree , DataSig , OutputVertexStream , FEMSigs ... >( UIntPack< FEMSigs ... >() , UIntPack< WeightDegree >() , UIntPack< DataSig >() , tree , maxKeyDepth , densityWeights , data , coefficients , isoValue , vertexStream , zeroData , nonLinearFit , outputGradients , sliceValues , setFlag );
1208 }
1209 };