forked from svalinn/mcnp2cad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcnp2cad.cpp
1328 lines (1063 loc) · 44.8 KB
/
mcnp2cad.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cctype>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include <algorithm>
#include <cassert>
#include "iGeom.h"
#include "geometry.hpp"
#include "MCNPInput.hpp"
#include "options.hpp"
#include "volumes.hpp"
#include "ProgOptions.hpp"
#include "version.hpp"
/* mcnp2cad should be compatible with any implementation of the iGeom library.
* But when we know that CGM is the implementation of iGeom that we're using,
* we can do a few other useful things. Those extra things are confined to this
* file and guarded by this macro.
*/
#ifdef USING_CGMA
#include <RefEntityFactory.hpp>
#include <Body.hpp>
#include <GeometryQueryTool.hpp>
#include <CubitMessage.hpp>
static bool CGMA_opt_inhibit_intersect_errs = false;
/* CubitMessage doesn't provide a way to shut up error messages.
* For those rare cases when we really want that behavior, we set up
* a message handler that just drops messages.
*/
class SilentCubitMessageHandler : public CubitMessageHandler
{
public:
static int num_dropped_errors;
SilentCubitMessageHandler() {}
virtual void print_message_prefix(const char *){}
virtual void print_message(const char *){}
virtual void print_error_prefix(const char *){}
virtual void print_error(const char *){num_dropped_errors++;}
};
int SilentCubitMessageHandler::num_dropped_errors = 0;
/* RAII class to set up and shut down a SilentCubitMessageHandler */
class CubitSilence
{
protected:
CubitMessageHandler* old_handler;
SilentCubitMessageHandler silencer;
public:
CubitSilence() :
old_handler( CubitMessage::instance()->get_message_handler() )
{
CubitMessage::instance()->set_message_handler( &silencer );
}
~CubitSilence(){
CubitMessage::instance()->set_message_handler( old_handler );
}
};
#endif /* USING_CGMA */
typedef std::vector<iBase_EntityHandle> entity_collection_t;
// intersect two volumes that may or may not overlap; return true on success.
static bool intersectIfPossible( iGeom_Instance igm,
iBase_EntityHandle h1, iBase_EntityHandle h2, iBase_EntityHandle* result,
bool delete_on_failure = true)
{
int igm_result;
#ifdef USING_CGMA
if( CGMA_opt_inhibit_intersect_errs ){
CubitSilence s;
iGeom_intersectEnts( igm, h1, h2, result, &igm_result);
} else
#endif
{
iGeom_intersectEnts( igm, h1, h2, result, &igm_result);
}
if( igm_result == iBase_SUCCESS ){
return true;
}
else{
if( delete_on_failure ){
iGeom_deleteEnt( igm, h1, &igm_result);
CHECK_IGEOM(igm_result, "deleting an intersection candidate");
iGeom_deleteEnt( igm, h2, &igm_result);
CHECK_IGEOM(igm_result, "deleting an intersection candidate");
}
return false;
}
}
// determine whether the bounding boxes of two volumes overlap.
// this can save an expensive call to intersectIfPossible()
static bool boundBoxesIntersect( iGeom_Instance igm, iBase_EntityHandle h1, iBase_EntityHandle h2 ){
Vector3d h1_min, h1_max, h2_min, h2_max;
int igm_result;
iGeom_getEntBoundBox( igm, h1, h1_min.v, h1_min.v+1, h1_min.v+2, h1_max.v, h1_max.v+1, h1_max.v+2, &igm_result );
CHECK_IGEOM( igm_result, "Getting bounding box h1" );
iGeom_getEntBoundBox( igm, h2, h2_min.v, h2_min.v+1, h2_min.v+2, h2_max.v, h2_max.v+1, h2_max.v+2, &igm_result );
CHECK_IGEOM( igm_result, "Getting bounding box h2" );
bool ret = false;
for( int i = 0; i < 3 && ret == false; ++i ){
ret = ret || ( h1_min.v[i] > h2_max.v[i] );
ret = ret || ( h2_min.v[i] > h1_max.v[i] );
}
return !ret;
}
/**
* Contains geometry functions and the shared data members they all reference.
*/
class GeometryContext {
/**
* Metadata and naming:
* The NamedGroup and NamedEntity mappings are used to keep track of metadata
* on particular entity handles that map to MCNP cells.
* EntityHandles change frequently as CSG operations are performed on volumes,
* so these mappings must be updated, by calling updateMaps(), whenever an
* EntityHandle changes.
*/
protected:
// note: this appears slow, since it's called for all cells and constructs a string
// for each. A lookup table would probably be faster, but there are never more than
// a few thousand cells.
std::string materialName( int mat, double rho ){
std::string ret;
std::stringstream formatter;
if(Gopt.uwuw_names){
bool mass_density = false;
if (rho <= 0){
mass_density = true;
rho = -rho;
}
char rho_formatted [50];
sprintf(rho_formatted, "%E", rho);
formatter << "mat:m" << mat;
if(mass_density)
formatter << "/rho:" <<rho_formatted;
else
formatter << "/atom:" << rho_formatted;
}
else
formatter << "mat_" << mat << "_rho_" << rho;
formatter >> ret;
return ret;
}
std::string importanceName( char impchar, double imp ){
std::string ret;
std::stringstream formatter;
formatter << "imp." << impchar << "_" << imp;
formatter >> ret;
return ret;
}
class NamedGroup {
protected:
std::string name;
entity_collection_t entities;
public:
NamedGroup( ) : name("") {}
NamedGroup( std::string name_p ):
name(name_p)
{}
const std::string& getName() const { return name; }
const entity_collection_t& getEntities() const { return entities; }
void add( iBase_EntityHandle new_handle ){
entities.push_back(new_handle);
}
void update( iBase_EntityHandle old_h, iBase_EntityHandle new_h ){
entity_collection_t::iterator i = std::find( entities.begin(), entities.end(), old_h );
if( i != entities.end() ){
if( new_h ){
*i = new_h;
}
else {
entities.erase( i );
}
}
}
bool contains( iBase_EntityHandle handle ) const {
return std::find( entities.begin(), entities.end(), handle ) != entities.end();
}
};
class NamedEntity {
protected:
iBase_EntityHandle handle;
std::string name;
public:
NamedEntity( iBase_EntityHandle handle_p, std::string name_p = "" ):
handle(handle_p), name(name_p)
{}
virtual ~NamedEntity(){}
const std::string& getName() const { return name; }
iBase_EntityHandle getHandle() const{ return handle; }
void setHandle( iBase_EntityHandle new_h ) {
handle = new_h;
}
static NamedEntity* makeCellIDName( iBase_EntityHandle h, int ident ){
NamedEntity* e = new NamedEntity(h);
std::stringstream formatter;
formatter << "MCNP_ID_" << ident;
formatter >> e->name;
return e;
}
};
protected:
iGeom_Instance& igm;
InputDeck& deck;
double world_size;
int universe_depth;
std::map< std::string, NamedGroup* > named_groups;
std::vector< NamedEntity* > named_cells;
NamedGroup* getNamedGroup( const std::string& name ){
if( named_groups.find( name ) == named_groups.end() ){
named_groups[ name ] = new NamedGroup( name );
if( OPT_DEBUG ) std::cout << "New named group: " << name
<< "num groups now " << named_groups.size() << std::endl;
}
return named_groups[ name ];
}
public:
GeometryContext( iGeom_Instance& igm_p, InputDeck& deck_p ) :
igm(igm_p), deck(deck_p), world_size(0.0), universe_depth(0)
{}
bool defineLatticeNode( CellCard& cell, iBase_EntityHandle cell_shell, iBase_EntityHandle lattice_shell,
int x, int y, int z, entity_collection_t& accum );
entity_collection_t defineCell( CellCard& cell, bool defineEmbedded, iBase_EntityHandle lattice_shell );
entity_collection_t populateCell( CellCard& cell, iBase_EntityHandle cell_shell, iBase_EntityHandle lattice_shell );
entity_collection_t defineUniverse( int universe, iBase_EntityHandle container, const Transform* transform );
void addToVolumeGroup( iBase_EntityHandle cell, const std::string& groupname );
void setVolumeCellID( iBase_EntityHandle cell, int ident);
void setMaterial( iBase_EntityHandle cell, int material, double density ){
if( Gopt.tag_materials ){
addToVolumeGroup( cell, materialName(material,density) );
}
}
void setImportances( iBase_EntityHandle cell, const std::map<char, double>& imps ){
if( Gopt.tag_importances ){
for( std::map<char, double>::const_iterator i = imps.begin();
i != imps.end(); ++i )
{
char impchar = (*i).first;
double imp = (*i).second;
addToVolumeGroup( cell, importanceName( impchar, imp ) );
}
}
}
void updateMaps ( iBase_EntityHandle old_cell, iBase_EntityHandle new_cell );
bool mapSanityCheck( iBase_EntityHandle* cells, size_t count );
void tagGroups( );
void tagCellIDsAsEntNames();
std::string uprefix() {
return std::string( universe_depth, ' ' );
}
iBase_EntityHandle createGraveyard( iBase_EntityHandle& boundary );
void createGeometry( );
};
void GeometryContext::addToVolumeGroup( iBase_EntityHandle cell, const std::string& name ){
NamedGroup* group = getNamedGroup( name );
group->add( cell );
if( OPT_DEBUG ){ std::cout << uprefix()
<< "Added cell to volgroup " << group->getName() << std::endl; }
}
void GeometryContext::setVolumeCellID( iBase_EntityHandle cell, int ident ){
named_cells.push_back( NamedEntity::makeCellIDName(cell, ident) );
}
/** Inform metadata system that a cell has changed handled, as from a CSG operation */
void GeometryContext::updateMaps( iBase_EntityHandle old_cell, iBase_EntityHandle new_cell ){
/* update named_groups. handling of new_cell == NULL case is performed within NamedGroup class */
for( std::map<std::string,NamedGroup*>::iterator i = named_groups.begin();
i != named_groups.end(); ++i )
{
NamedGroup* group = (*i).second;
group->update( old_cell, new_cell );
}
/* update named entities.*/
if( new_cell != NULL ){
for( std::vector< NamedEntity* >::iterator i = named_cells.begin();
i != named_cells.end(); ++i )
{
NamedEntity* ne = *i;
if( ne->getHandle() == old_cell ){
ne->setHandle( new_cell );
}
}
}
else{ /* new_cell == NULL (i.e. cell has disappeared) */
// this case is expected to be uncommon in most geometries, so the fact that erasing
// from a std::vector is slow should not be a problem.
std::vector< NamedEntity* >::iterator i = named_cells.begin();
while( i != named_cells.end() ){
if( (*i)->getHandle() == old_cell ){
delete (*i);
named_cells.erase(i);
}
else{
++i;
}
}
}
}
/** Create and name groups of entities; only called after all cells have their final handles */
void GeometryContext::tagGroups( ){
// the NamedGroup system used to be used solely to create groups for material specification,
// but it has since been expanded for importance groups. Some of the old messages that
// talk about material groups could be confusing.
int igm_result;
std::string name_tag_id = "NAME";
int name_tag_maxlength = 64;
iBase_TagHandle name_tag;
iGeom_getTagHandle( igm, name_tag_id.c_str(), &name_tag, &igm_result, name_tag_id.length() );
CHECK_IGEOM( igm_result, "Looking up NAME tag" );
iGeom_getTagSizeBytes( igm, name_tag, &name_tag_maxlength, &igm_result );
CHECK_IGEOM( igm_result, "Querying NAME tag length" );
if( OPT_DEBUG ) std::cout << "Name tag length: " << name_tag_maxlength << " actual id " << name_tag << std::endl;
for( std::map<std::string,NamedGroup*>::iterator i = named_groups.begin(); i != named_groups.end(); ++i ){
NamedGroup* group = (*i).second;
if(OPT_VERBOSE){
std::cout << "Creating volume group " << group->getName() << " of size " << group->getEntities().size() << std::endl;
}
iBase_EntitySetHandle set;
iGeom_createEntSet( igm, 0, &set, &igm_result );
CHECK_IGEOM( igm_result, "Creating a new entity set " );
const entity_collection_t& group_list = group->getEntities();
for( entity_collection_t::const_iterator j = group_list.begin(); j != group_list.end(); ++j ){
iGeom_addEntToSet( igm, *j, set, &igm_result );
CHECK_IGEOM( igm_result, "Adding entity to material set" );
}
std::string name = group->getName();
if( name.length() > (unsigned)name_tag_maxlength ){
name.resize( name_tag_maxlength - 1);
std::cerr << "Warning: trimmed material name " << group->getName()
<< " to length " << name_tag_maxlength << std::endl;
}
iGeom_setEntSetData( igm, set, name_tag, name.c_str(), name.length(), &igm_result );
CHECK_IGEOM( igm_result, "Naming a material group's EntitySet" );
}
}
/** Set the names of cells; only called after cells have their final handles */
void GeometryContext::tagCellIDsAsEntNames(){
int igm_result;
std::string name_tag_id = "NAME";
int name_tag_maxlength = 64;
iBase_TagHandle name_tag;
iGeom_getTagHandle( igm, name_tag_id.c_str(), &name_tag, &igm_result, name_tag_id.length() );
CHECK_IGEOM( igm_result, "Looking up NAME tag" );
iGeom_getTagSizeBytes( igm, name_tag, &name_tag_maxlength, &igm_result );
CHECK_IGEOM( igm_result, "Querying NAME tag length" );
if( OPT_DEBUG ) std::cout << "Name tag length: " << name_tag_maxlength << " actual id " << name_tag << std::endl;
if( OPT_VERBOSE ){ std::cout << "Naming " << named_cells.size() << " volumes." << std::endl; }
for( std::vector< NamedEntity* >::iterator i = named_cells.begin(); i!=named_cells.end(); ++i){
std::string name = (*i)->getName();
iBase_EntityHandle entity = (*i)->getHandle();
if( name.length() > (unsigned)name_tag_maxlength ){
name.resize( name_tag_maxlength - 1);
std::cerr << "Warning: trimmed entity name " << (*i)->getName()
<< " to length " << name_tag_maxlength << std::endl;
}
if( entity == NULL ){ std::cerr << "Error: NULL in named_cells" << std::endl; continue; }
iGeom_setData( igm, entity, name_tag, name.c_str(), name.length(), &igm_result );
CHECK_IGEOM( igm_result, "Naming an NamedEntity" );
}
}
/** debugging functions to check sanity of named group mappings. Called only if -D enabled */
bool GeometryContext::mapSanityCheck( iBase_EntityHandle* cells, size_t count){
bool good = true;
int igm_result;
iBase_EntitySetHandle rootset;
iGeom_getRootSet( igm, &rootset, &igm_result );
CHECK_IGEOM( igm_result, "Getting root set for sanity check" );
int num_regions;
iGeom_getNumOfType( igm, rootset, iBase_REGION, &num_regions, &igm_result );
CHECK_IGEOM( igm_result, "Getting num regions for sanity check" );
iBase_EntityHandle * handle_vector = new iBase_EntityHandle[ num_regions ];
int size = 0;
std::cout << "Map sanity check: num_regions = " << num_regions << std::endl;
iGeom_getEntities( igm, rootset, iBase_REGION, &handle_vector, &num_regions, &size, &igm_result );
CHECK_IGEOM( igm_result, "Getting entities for sanity check" );
std::cout << "Map sanity check: root set size = " << size << " (" << num_regions << ")" << std::endl;
std::cout << "Cell count: " << count << std::endl;
// sanity conditions: all the entityhandles in the naming lists are part of the cells list
std::set< iBase_EntityHandle > allRegions;
for( size_t i = 0; i < count; ++i ){
allRegions.insert( cells[i] );
}
int named_group_volume_count = 0;
for( std::map<std::string, NamedGroup*>::iterator i = named_groups.begin(); i!=named_groups.end(); ++i){
NamedGroup* group = (*i).second;
named_group_volume_count += group->getEntities().size();
// graveyard cells are not present in allRegions
if( group->getName() == "graveyard" )
continue;
entity_collection_t group_cells = group->getEntities();
for( entity_collection_t::iterator j = group_cells.begin(); j != group_cells.end(); ++j ){
bool check = allRegions.find( *j ) != allRegions.end();
if( ! check ){
std::cout << "Entity handle " << *j << " is not in allRegions!" << std::endl;
}
good = good && check;
}
}
std::cout << "Num EntityHandles in NamedGroups: " << named_group_volume_count << std::endl;
if( good ){ std::cout << "Map sanity check: pass!" << std::endl; }
else{ std::cout << "WARNING: Failed map sanity check!" << std::endl; }
return good;
}
/** Define node x,y,z in a lattice.
*
* cell_shell is a volume representing lattice node (0,0,0)
* lattice_shell is the volume into which the node must be intersected
*/
bool GeometryContext::defineLatticeNode( CellCard& cell, iBase_EntityHandle cell_shell, iBase_EntityHandle lattice_shell,
int x, int y, int z, entity_collection_t& accum )
{
const Lattice& lattice = cell.getLattice();
int lattice_universe = cell.getUniverse();
const FillNode* fn = &(lattice.getFillForNode( x, y, z ));
Transform t = lattice.getTxForNode( x, y, z );
int igm_result;
iBase_EntityHandle cell_copy;
iGeom_copyEnt( igm, cell_shell, &cell_copy, &igm_result );
CHECK_IGEOM( igm_result, "Copying a lattice cell shell" );
cell_copy = applyTransform( t, igm, cell_copy );
if( !boundBoxesIntersect( igm, cell_copy, lattice_shell ) ){
iGeom_deleteEnt( igm, cell_copy, &igm_result);
CHECK_IGEOM( igm_result, "Deleting a lattice cell shell" );
if( OPT_DEBUG ) std::cout << uprefix() << " node failed bbox check" << std::endl;
return false;
}
entity_collection_t node_subcells;
if( fn->getFillingUniverse() == 0 ){
// this node of the lattice was assigned universe zero, meaning it's
// defined to be emtpy. Delete the shell and return true.
iGeom_deleteEnt( igm, cell_copy, &igm_result );
CHECK_IGEOM( igm_result, "Deleting a universe-0 lattice cell" );
return true;
}
else if( fn->getFillingUniverse() == lattice_universe ){
// this node is just a translated copy of the origin element in the lattice
setVolumeCellID(cell_copy, cell.getIdent());
if( cell.getMat() != 0 ){ setMaterial( cell_copy, cell.getMat(), cell.getRho() ); }
if( cell.getImportances().size() ){ setImportances( cell_copy, cell.getImportances()); }
node_subcells.push_back( cell_copy );
}
else{
// this node has an embedded universe
iBase_EntityHandle cell_copy_unmoved;
iGeom_copyEnt( igm, cell_shell, &cell_copy_unmoved, &igm_result );
CHECK_IGEOM( igm_result, "Re-copying a lattice cell shell" );
node_subcells = defineUniverse( fn->getFillingUniverse(), cell_copy_unmoved, (fn->hasTransform() ? &(fn->getTransform()) : NULL ) );
for( size_t i = 0; i < node_subcells.size(); ++i ){
node_subcells[i] = applyTransform( t, igm, node_subcells[i] );
}
iGeom_deleteEnt( igm, cell_copy, &igm_result );
CHECK_IGEOM( igm_result, "Deleting lattice cell copy" );
}
// bound the node with the enclosing lattice shell
bool success = false;
for( size_t i = 0; i < node_subcells.size(); ++i ){
iBase_EntityHandle lattice_shell_copy;
iGeom_copyEnt( igm, lattice_shell, &lattice_shell_copy, &igm_result );
iBase_EntityHandle result;
if( intersectIfPossible( igm, lattice_shell_copy, node_subcells[i], &result, true ) ){
updateMaps( node_subcells[i], result );
if( OPT_DEBUG ) std::cout << " node defined successfully" << std::endl;
accum.push_back( result );
success = true;
}
else{
// lattice_shell_copy and node_subcells[i] were deleted by intersectIfPossible(),
// so there's no need to delete them explicitly
updateMaps( node_subcells[i], NULL );
if( OPT_DEBUG ) std::cout << " node failed intersection" << std::endl;
}
}
return success;
}
typedef struct{ int v[3]; } int_triple;
static std::vector<int_triple> makeGridShellOfRadius( int r, int dimensions ){
if( r == 0 ){
int_triple v; v.v[0] = v.v[1] = v.v[2] = 0;
return std::vector<int_triple>(1,v);
}
else{
std::vector<int_triple> ret;
int jmin = dimensions > 1 ? -r : 0;
int jmax = dimensions > 1 ? r : 0;
int kmin = dimensions > 2 ? -r : 0;
int kmax = dimensions > 2 ? r : 0;
for( int i = -r; i <= r; ++i ){
for( int j = jmin;j <= jmax; ++j ){
for( int k = kmin; k <= kmax; ++k ){
if( i == -r || i == r ||
j == -r || j == r ||
k == -r || k == r ){
int_triple v;
v.v[0] = i;
v.v[1] = j;
v.v[2] = k;
ret.push_back(v);
}
}
}
}
return ret;
}
}
/** fill a cell with its contents. The cell's boundary is already defined in cell_shell. */
entity_collection_t GeometryContext::populateCell( CellCard& cell, iBase_EntityHandle cell_shell,
iBase_EntityHandle lattice_shell = NULL )
{
if( OPT_DEBUG ) std::cout << uprefix() << "Populating cell " << cell.getIdent() << std::endl;
if( !cell.hasFill() && !cell.isLattice() ){
// no further geometry inside this cell; set its material
setVolumeCellID(cell_shell, cell.getIdent());
if( cell.getMat() != 0 ){ setMaterial( cell_shell, cell.getMat(), cell.getRho() ); }
if( cell.getImportances().size() ){ setImportances( cell_shell, cell.getImportances()); }
return entity_collection_t(1, cell_shell );
}
else if(cell.hasFill() && !cell.isLattice()){
// define a simple (non-lattice) fill
const FillNode& n = cell.getFill().getOriginNode();
int filling_universe = n.getFillingUniverse();
if( OPT_DEBUG ){
std::cout << uprefix() << "Creating cell " << cell.getIdent()
<< ", which is filled with universe " << filling_universe << std::endl;
}
// the contained universe is transformed by the FillNode's transform, if any, or
// else by the cell's TRCL value, if any.
const Transform* t;
if( n.hasTransform() ){
t = &(n.getTransform());
} else if( cell.getTrcl().hasData() ){
t = &(cell.getTrcl().getData() );
} else {
t = NULL;
}
if( OPT_DEBUG && t ) std::cout << uprefix() << " ... and has transform: " << *t << std::endl;
entity_collection_t subcells = defineUniverse( filling_universe, cell_shell, t );
return subcells;
}
else {
// cell is a lattice, bounded by lattice_shell. cell_shell is the origin element of the lattice and
// cell->getLattice() has the lattice parameters.
assert(lattice_shell);
if( OPT_VERBOSE ) std::cout << uprefix() << "Creating cell " << cell.getIdent() << "'s lattice" << std::endl;
entity_collection_t subcells;
const Lattice& lattice = cell.getLattice();
int num_dims = lattice.numFiniteDirections();
if( OPT_DEBUG ) std::cout << uprefix() << " lattice num dims: " << num_dims << std::endl;
if( lattice.isFixedSize() ){
if( OPT_DEBUG ) std::cout << uprefix() << "Defining fixed lattice" << std::endl;
irange xrange = lattice.getXRange(), yrange = lattice.getYRange(), zrange = lattice.getZRange();
for( int i = xrange.first; i <= xrange.second; ++i){
for( int j = yrange.first; j <= yrange.second; ++j ){
for( int k = zrange.first; k <= zrange.second; ++k ){
if( OPT_DEBUG ) std::cout << uprefix() << "Defining lattice node " << i << ", " << j << ", " << k << std::endl;
/* bool success = */ defineLatticeNode( cell, cell_shell, lattice_shell, i, j, k, subcells );
if( num_dims < 3 ) break; // from z loop
}
if( num_dims < 2 ) break; // from y loop
}
}
}
else{
if( OPT_DEBUG ) std::cout << uprefix() << "Defining infinite lattice" << std::endl;
if( OPT_VERBOSE && Gopt.infinite_lattice_extra_effort )
std::cout << uprefix() << "Infinite lattice extra effort enabled." << std::endl;
// when extra effort is enabled, initialize done_one to false;
// the code will keep trying to create lattice elements until at least one
// element has been successfully created.
bool done = false, done_one = !Gopt.infinite_lattice_extra_effort;
int radius = 0;
while( !done ){
done = done_one;
std::vector<int_triple> shell = makeGridShellOfRadius(radius++, num_dims);
for( std::vector<int_triple>::iterator i = shell.begin(); i!=shell.end(); ++i){
int x = (*i).v[0];
int y = (*i).v[1];
int z = (*i).v[2];
if( OPT_DEBUG ) std::cout << uprefix() << "Defining lattice node " << x << ", " << y << ", " << z << std::endl;
bool success = defineLatticeNode( cell, cell_shell, lattice_shell, x, y, z, subcells );
if( success ){
done = false;
done_one = true;
}
}
}
}
int igm_result;
iGeom_deleteEnt( igm, cell_shell, &igm_result );
CHECK_IGEOM( igm_result, "Deleting cell shell after building lattice" );
iGeom_deleteEnt( igm, lattice_shell, &igm_result );
CHECK_IGEOM( igm_result, "Deleting lattice shell after building lattice" );
return subcells;
}
}
/** Define a geometric cell from a card
*
* @param defineEmbedded If true, also define the contents of the cell, not just its boundary surfaces.
* @param lattice_shell
*/
entity_collection_t GeometryContext::defineCell( CellCard& cell, bool defineEmbedded = true,
iBase_EntityHandle lattice_shell = NULL )
{
int ident = cell.getIdent();
const CellCard::geom_list_t& geom = cell.getGeom();
if( OPT_VERBOSE ) std::cout << uprefix() << "Defining cell " << ident << std::endl;
int igm_result;
entity_collection_t tmp;
std::vector<iBase_EntityHandle> stack;
for(CellCard::geom_list_t::const_iterator i = geom.begin(); i!=geom.end(); ++i){
const CellCard::geom_list_entry_t& token = (*i);
switch(token.first){
case CellCard::CELLNUM:
// a cell number appears in a geometry list only because it is being complemented with the # operator
// thus, when defineCell is called on it, set defineEmbedded to false
tmp = defineCell( *(deck.lookup_cell_card(token.second)), false);
assert(tmp.size() == 1);
stack.push_back( tmp.at(0) );
break;
case CellCard::SURFNUM:
{
int surface = token.second;
bool positive = true;
if( surface < 0){
positive = false; surface = -surface;
}
try{
SurfaceVolume& surf = makeSurface( deck.lookup_surface_card( surface ) );
iBase_EntityHandle surf_handle = surf.define( positive, igm, world_size );
stack.push_back(surf_handle);
}
catch(std::runtime_error& e) { std::cerr << e.what() << std::endl; }
}
break;
case CellCard::MBODYFACET:
{
int identifier = -std::abs( token.second );
int surfacenum = -identifier / 10;
int facet = -identifier - ( surfacenum * 10 );
try{
SurfaceVolume& surf = makeSurface( deck.lookup_surface_card( identifier ) );
const std::string& mnemonic = deck.lookup_surface_card( identifier )->getMnemonic();
bool positive = true;
if( mnemonic == "rcc" || mnemonic == "rec" ){
if( ( token.second < 0 ) ^ ( facet == 3 ) ){
positive = false;
}
}
else if( mnemonic == "box" || mnemonic == "rpp" ){
if( ( token.second < 0 ) ^ ( facet == 2 || facet == 4 || facet == 6 ) ){
positive = false;
}
}
else if( mnemonic == "hex" || mnemonic == "rhp" ){
if( ( token.second < 0 ) ^ ( facet == 8 ) ){
positive = false;
}
}
iBase_EntityHandle surf_handle = surf.define ( positive, igm, world_size );
stack.push_back(surf_handle);
}
catch(std::runtime_error& e) { std::cerr << e.what() << std::endl; }
}
break;
case CellCard::INTERSECT:
{
assert( stack.size() >= 2 );
iBase_EntityHandle s1 = stack.back(); stack.pop_back();
iBase_EntityHandle s2 = stack.back(); stack.pop_back();
iBase_EntityHandle result;
if( intersectIfPossible( igm, s1, s2, &result ) ){
stack.push_back(result);
}
else{
std::cout << "FAILED INTERSECTION CELL #" << cell.getIdent() << std::endl;
throw std::runtime_error("Intersection failed");
}
}
break;
case CellCard::UNION:
{
assert( stack.size() >= 2 );
iBase_EntityHandle s[2];
s[0] = stack.back(); stack.pop_back();
s[1] = stack.back(); stack.pop_back();
iBase_EntityHandle result;
iGeom_uniteEnts( igm, s, 2, &result, &igm_result);
CHECK_IGEOM( igm_result, "Uniting two entities" );
stack.push_back(result);
}
break;
case CellCard::COMPLEMENT:
{
assert (stack.size() >= 1 );
iBase_EntityHandle world_sphere = makeWorldSphere(igm, world_size);
iBase_EntityHandle s = stack.back(); stack.pop_back();
iBase_EntityHandle result;
iGeom_subtractEnts( igm, world_sphere, s, &result, &igm_result);
CHECK_IGEOM( igm_result, "Complementing an entity" );
stack.push_back(result);
}
break;
default:
throw std::runtime_error( "Unexpected token while evaluating cell geometry");
break;
}
}
assert( stack.size() == 1);
iBase_EntityHandle cellHandle = stack[0];
if( cell.getTrcl().hasData() ){
cellHandle = applyTransform( cell.getTrcl().getData(), igm, cellHandle );
}
if( defineEmbedded ){
return populateCell( cell, cellHandle, lattice_shell );
}
else{
return entity_collection_t( 1, cellHandle );
}
}
/** Define all the cells in a universe.
*
* @param container If non-null, intersect the universe with this boundary volume
* @param transform If non-null, transform the universe thus.
*/
entity_collection_t GeometryContext::defineUniverse( int universe, iBase_EntityHandle container = NULL,
const Transform* transform = NULL )
{
if( OPT_VERBOSE ) std::cout << uprefix() << "Defining universe " << universe << std::endl;
universe_depth++;
InputDeck::cell_card_list u_cells = deck.getCellsOfUniverse( universe );
entity_collection_t subcells;
iBase_EntityHandle lattice_shell = NULL;
if( u_cells.size() == 1 && u_cells[0]->isLattice() ){
lattice_shell = container;
// reverse-transform the containing volume before using it as a lattice boundary
if(transform){
lattice_shell = applyReverseTransform( *transform, igm, lattice_shell );
}
}
// define all the cells of this universe
for( InputDeck::cell_card_list::iterator i = u_cells.begin(); i!=u_cells.end(); ++i){
entity_collection_t tmp = defineCell( *(*i), true, lattice_shell );
for( size_t i = 0; i < tmp.size(); ++i){
subcells.push_back( tmp[i] );
}
}
if( transform ){
for( size_t i = 0; i < subcells.size(); ++i){
subcells[i] = applyTransform( *transform, igm, subcells[i] );
}
}
if( container && !lattice_shell ){
int igm_result;
for( size_t i = 0; i < subcells.size(); ++i ){
if( OPT_DEBUG ) std::cout << uprefix() << "Bounding a universe cell..." << std::flush;
bool subcell_removed = false;
if( boundBoxesIntersect( igm, subcells[i], container )){
iBase_EntityHandle container_copy;
iGeom_copyEnt( igm, container, &container_copy, &igm_result);
CHECK_IGEOM( igm_result, "Copying a universe-bounding cell" );
iBase_EntityHandle subcell_bounded;
bool valid_result = intersectIfPossible( igm, container_copy, subcells[i], &subcell_bounded );
if( valid_result ){
updateMaps( subcells[i], subcell_bounded );
subcells[i] = subcell_bounded;
if( OPT_DEBUG ) std::cout << " ok." << std::endl;
}
else{
subcell_removed = true;
}
}
else{
// bounding boxes didn't intersect, delete subcells[i].
// this suggests invalid geometry, but we can continue anyway.
iGeom_deleteEnt( igm, subcells[i], &igm_result );
CHECK_IGEOM( igm_result, "Deleting a subcell that didn't intersect a parent's bounding box (strange!)" );
subcell_removed = true;
}
if( subcell_removed ){
updateMaps( subcells[i], NULL );
subcells.erase( subcells.begin()+i );
i--;
if( OPT_DEBUG ) std::cout << " removed." << std::endl;
}
}
iGeom_deleteEnt( igm, container, &igm_result );
CHECK_IGEOM( igm_result, "Deleting a bounding cell" );
}
universe_depth--;
if( OPT_VERBOSE ) std::cout << uprefix() << "Done defining universe " << universe << std::endl;
return subcells;
}
/**
* Create the graveyard bounding cell. The actual graveyard entity is returned.
* A copy of the inner surface of the graveyard cell
* is returned in the argument, to be used as the boundary of all further geometry.
*/
iBase_EntityHandle GeometryContext::createGraveyard( iBase_EntityHandle& inner_copy ) {
iBase_EntityHandle inner, outer, graveyard;
int igm_result;
double inner_size = 2.0 * world_size;
iGeom_createBrick( igm, inner_size, inner_size, inner_size, &inner, &igm_result );
CHECK_IGEOM( igm_result, "Making graveyard" );
iGeom_copyEnt( igm, inner, &inner_copy, &igm_result );