-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGPURaytrace.h
More file actions
613 lines (529 loc) · 21.2 KB
/
GPURaytrace.h
File metadata and controls
613 lines (529 loc) · 21.2 KB
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
#include <filesystem>
#include <fstream>
#include <iostream>
#include "G4AutoLock.hh"
#include "G4BooleanSolid.hh"
#include "G4Cerenkov.hh"
#include "G4Electron.hh"
#include "G4Event.hh"
#include "G4GDMLParser.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4OpBoundaryProcess.hh"
#include "G4OpticalPhoton.hh"
#include "G4PhysicalConstants.hh"
#include "G4PrimaryParticle.hh"
#include "G4PrimaryVertex.hh"
#include "G4RunManager.hh"
#include "G4RunManagerFactory.hh"
#include "G4SDManager.hh"
#include "G4Scintillation.hh"
#include "G4SubtractionSolid.hh"
#include "G4SystemOfUnits.hh"
#include "G4ThreeVector.hh"
#include "G4Track.hh"
#include "G4TrackStatus.hh"
#include "G4UserEventAction.hh"
#include "G4UserRunAction.hh"
#include "G4UserSteppingAction.hh"
#include "G4UserTrackingAction.hh"
#include "G4VPhysicalVolume.hh"
#include "G4VProcess.hh"
#include "G4VUserDetectorConstruction.hh"
#include "G4VUserPrimaryGeneratorAction.hh"
#include "g4cx/G4CXOpticks.hh"
#include "sysrap/NP.hh"
#include "sysrap/SEvt.hh"
#include "sysrap/STrackInfo.h"
#include "sysrap/spho.h"
#include "sysrap/sphoton.h"
#include "u4/U4.hh"
#include "u4/U4Random.hh"
#include "u4/U4StepPoint.hh"
#include "u4/U4Touchable.h"
#include "u4/U4Track.h"
namespace
{
G4Mutex genstep_mutex = G4MUTEX_INITIALIZER;
}
bool IsSubtractionSolid(G4VSolid *solid)
{
if (!solid)
return false;
// Check if the solid is directly a G4SubtractionSolid
if (dynamic_cast<G4SubtractionSolid *>(solid))
return true;
// If the solid is a Boolean solid, check its constituent solids
G4BooleanSolid *booleanSolid = dynamic_cast<G4BooleanSolid *>(solid);
if (booleanSolid)
{
G4VSolid *solidA = booleanSolid->GetConstituentSolid(0);
G4VSolid *solidB = booleanSolid->GetConstituentSolid(1);
// Recursively check the constituent solids
if (IsSubtractionSolid(solidA) || IsSubtractionSolid(solidB))
return true;
}
// For other solid types, return false
return false;
}
std::string str_tolower(std::string s)
{
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
return s;
}
struct PhotonHit : public G4VHit
{
PhotonHit() = default;
PhotonHit(unsigned id, G4double energy, G4double time, G4ThreeVector position, G4ThreeVector direction,
G4ThreeVector polarization)
: fid(id), fenergy(energy), ftime(time), fposition(position), fdirection(direction), fpolarization(polarization)
{
}
// Copy constructor
PhotonHit(const PhotonHit &right)
: G4VHit(right), fid(right.fid), fenergy(right.fenergy), ftime(right.ftime), fposition(right.fposition),
fdirection(right.fdirection), fpolarization(right.fpolarization)
{
}
// Assignment operator
const PhotonHit &operator=(const PhotonHit &right)
{
if (this != &right)
{
G4VHit::operator=(right);
fid = right.fid;
fenergy = right.fenergy;
ftime = right.ftime;
fposition = right.fposition;
fdirection = right.fdirection;
fpolarization = right.fpolarization;
}
return *this;
}
// Equality operator
G4bool operator==(const PhotonHit &right) const
{
return (this == &right);
}
// Print method
void Print() override
{
G4cout << "Detector id: " << fid << " energy: " << fenergy << " nm" << " time: " << ftime << " ns"
<< " position: " << fposition << " direction: " << fdirection << " polarization: " << fpolarization
<< G4endl;
}
// Member variables
G4int fid{0};
G4double fenergy{0};
G4double ftime{0};
G4ThreeVector fposition{0, 0, 0};
G4ThreeVector fdirection{0, 0, 0};
G4ThreeVector fpolarization{0, 0, 0};
};
using PhotonHitsCollection = G4THitsCollection<PhotonHit>;
struct PhotonSD : public G4VSensitiveDetector
{
PhotonSD(G4String name) : G4VSensitiveDetector(name), fHCID(-1)
{
G4String HCname = name + "_HC";
collectionName.insert(HCname);
G4cout << collectionName.size() << " PhotonSD name: " << name << " collection Name: " << HCname << G4endl;
}
void Initialize(G4HCofThisEvent *hce) override
{
fPhotonHitsCollection = new PhotonHitsCollection(SensitiveDetectorName, collectionName[0]);
if (fHCID < 0)
{
// G4cout << "PhotonSD::Initialize: " << SensitiveDetectorName << " " << collectionName[0] << G4endl;
fHCID = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
}
hce->AddHitsCollection(fHCID, fPhotonHitsCollection);
}
G4bool ProcessHits(G4Step *aStep, G4TouchableHistory *) override
{
G4Track *theTrack = aStep->GetTrack();
if (theTrack->GetDefinition() != G4OpticalPhoton::OpticalPhotonDefinition())
return false;
G4double theEnergy = theTrack->GetTotalEnergy() / CLHEP::eV;
// Create a new hit (CopyNr is set to 0 as DetectorID is omitted)
PhotonHit *newHit = new PhotonHit(
0, // CopyNr set to 0
theEnergy, theTrack->GetGlobalTime(), aStep->GetPostStepPoint()->GetPosition(),
aStep->GetPostStepPoint()->GetMomentumDirection(), aStep->GetPostStepPoint()->GetPolarization());
fPhotonHitsCollection->insert(newHit);
theTrack->SetTrackStatus(fStopAndKill);
return true;
}
void EndOfEvent(G4HCofThisEvent *) override
{
G4int NbHits = fPhotonHitsCollection->entries();
G4cout << "PhotonSD::EndOfEvent Number of PhotonHits: " << NbHits << G4endl;
}
void AddOpticksHits()
{
SEvt *sev = SEvt::Get_EGPU();
unsigned int num_hits = sev->GetNumHit(0);
for (int idx = 0; idx < int(num_hits); idx++)
{
sphoton hit;
sev->getHit(hit, idx);
G4ThreeVector position = G4ThreeVector(hit.pos.x, hit.pos.y, hit.pos.z);
G4ThreeVector direction = G4ThreeVector(hit.mom.x, hit.mom.y, hit.mom.z);
G4ThreeVector polarization = G4ThreeVector(hit.pol.x, hit.pol.y, hit.pol.z);
int theCreationProcessid;
if (OpticksPhoton::HasCerenkovFlag(hit.flagmask))
{
theCreationProcessid = 0;
}
else if (OpticksPhoton::HasScintillationFlag(hit.flagmask))
{
theCreationProcessid = 1;
}
else
{
theCreationProcessid = -1;
}
std::cout << hit.wavelength << " " << position << " " << direction << " " << polarization << std::endl;
PhotonHit *newHit = new PhotonHit(0, hit.wavelength, hit.time, position, direction, polarization);
fPhotonHitsCollection->insert(newHit);
}
}
private:
PhotonHitsCollection *fPhotonHitsCollection{nullptr};
G4int fHCID;
};
struct DetectorConstruction : G4VUserDetectorConstruction
{
DetectorConstruction(std::filesystem::path gdml_file) : gdml_file_(gdml_file)
{
}
G4VPhysicalVolume *Construct() override
{
parser_.Read(gdml_file_.string(), false);
G4VPhysicalVolume *world = parser_.GetWorldVolume();
G4CXOpticks::SetGeometry(world);
G4LogicalVolumeStore *lvStore = G4LogicalVolumeStore::GetInstance();
static G4VisAttributes invisibleVisAttr(false);
// Check if the store is not empty
if (lvStore && !lvStore->empty())
{
// Iterate over all logical volumes in the store
for (auto &logicalVolume : *lvStore)
{
G4VSolid *solid = logicalVolume->GetSolid();
// Check if the solid uses subtraction
if (IsSubtractionSolid(solid))
{
// Assign the invisible visual attributes to the logical volume
logicalVolume->SetVisAttributes(&invisibleVisAttr);
// Optionally, print out the name of the logical volume
G4cout << "Hiding logical volume: " << logicalVolume->GetName() << G4endl;
}
}
}
return world;
}
void ConstructSDandField() override
{
G4cout << "ConstructSDandField is called." << G4endl;
G4SDManager *SDman = G4SDManager::GetSDMpointer();
const G4GDMLAuxMapType *auxmap = parser_.GetAuxMap();
for (auto const &[logVol, listType] : *auxmap)
{
for (auto const &auxtype : listType)
{
if (auxtype.type == "SensDet")
{
G4cout << "Attaching sensitive detector to logical volume: " << logVol->GetName() << G4endl;
G4String name = logVol->GetName() + "_PhotonDetector";
PhotonSD *aPhotonSD = new PhotonSD(name);
SDman->AddNewDetector(aPhotonSD);
logVol->SetSensitiveDetector(aPhotonSD);
}
}
}
}
private:
std::filesystem::path gdml_file_;
G4GDMLParser parser_;
};
struct PrimaryGenerator : G4VUserPrimaryGeneratorAction
{
SEvt *sev;
PrimaryGenerator(SEvt *sev) : sev(sev)
{
}
void GeneratePrimaries(G4Event *event) override
{
G4ThreeVector position_mm(0.0 * m, 0.0 * m, 0.0 * m);
G4double time_ns = 0;
G4ThreeVector direction(0, 0.2, 0.8);
G4double wavelength_nm = 0.1;
G4PrimaryVertex *vertex = new G4PrimaryVertex(position_mm, time_ns);
G4PrimaryParticle *particle = new G4PrimaryParticle(G4Electron::Definition());
particle->SetKineticEnergy(5 * GeV);
particle->SetMomentumDirection(direction);
vertex->SetPrimary(particle);
event->AddPrimaryVertex(vertex);
}
};
struct EventAction : G4UserEventAction
{
SEvt *sev;
G4int fTotalG4Hits{0};
EventAction(SEvt *sev) : sev(sev)
{
}
void BeginOfEventAction(const G4Event *event) override
{
}
void EndOfEventAction(const G4Event *event) override
{
G4HCofThisEvent *hce = event->GetHCofThisEvent();
if (hce)
{
for (G4int i = 0; i < hce->GetNumberOfCollections(); i++)
{
G4VHitsCollection *hc = hce->GetHC(i);
if (hc)
{
fTotalG4Hits += hc->GetSize();
}
}
}
}
G4int GetTotalG4Hits() const
{
return fTotalG4Hits;
}
};
struct RunAction : G4UserRunAction
{
EventAction *fEventAction;
RunAction(EventAction *eventAction) : fEventAction(eventAction)
{
}
void BeginOfRunAction(const G4Run *run) override
{
}
void EndOfRunAction(const G4Run *run) override
{
if (G4Threading::IsMasterThread())
{
G4CXOpticks *gx = G4CXOpticks::Get();
auto start = std::chrono::high_resolution_clock::now();
gx->simulate(0, false);
cudaDeviceSynchronize();
auto end = std::chrono::high_resolution_clock::now();
// Compute duration
std::chrono::duration<double> elapsed = end - start;
std::cout << "Simulation time: " << elapsed.count() << " seconds" << std::endl;
// unsigned int num_hits = SEvt::GetNumHit(EGPU);
SEvt *sev = SEvt::Get_EGPU();
unsigned int num_hits = sev->GetNumHit(0);
std::cout << "Opticks: NumCollected: " << sev->GetNumGenstepFromGenstep(0) << std::endl;
std::cout << "Opticks: NumCollected: " << sev->GetNumPhotonCollected(0) << std::endl;
std::cout << "Opticks: NumHits: " << num_hits << std::endl;
std::cout << "Geant4: NumHits: " << fEventAction->GetTotalG4Hits() << std::endl;
std::ofstream outFile("opticks_hits_output.txt");
if (!outFile.is_open())
{
std::cerr << "Error opening output file!" << std::endl;
return;
}
for (int idx = 0; idx < int(num_hits); idx++)
{
sphoton hit;
sev->getHit(hit, idx);
G4ThreeVector position = G4ThreeVector(hit.pos.x, hit.pos.y, hit.pos.z);
G4ThreeVector direction = G4ThreeVector(hit.mom.x, hit.mom.y, hit.mom.z);
G4ThreeVector polarization = G4ThreeVector(hit.pol.x, hit.pol.y, hit.pol.z);
int theCreationProcessid;
if (OpticksPhoton::HasCerenkovFlag(hit.flagmask))
{
theCreationProcessid = 0;
}
else if (OpticksPhoton::HasScintillationFlag(hit.flagmask))
{
theCreationProcessid = 1;
}
else
{
theCreationProcessid = -1;
}
// std::cout << "Adding hit from Opticks:" << hit.wavelength << " " << position << " " << direction
// << "
// "
// << polarization << std::endl;
outFile << hit.time << " " << hit.wavelength << " " << "(" << position.x() << ", " << position.y()
<< ", " << position.z() << ") " << "(" << direction.x() << ", " << direction.y() << ", "
<< direction.z() << ") " << "(" << polarization.x() << ", " << polarization.y() << ", "
<< polarization.z() << ") " << "CreationProcessID=" << theCreationProcessid << std::endl;
}
outFile.close();
}
}
};
struct SteppingAction : G4UserSteppingAction
{
SEvt *sev;
SteppingAction(SEvt *sev) : sev(sev)
{
}
void UserSteppingAction(const G4Step *aStep)
{
G4Track *aTrack;
G4int fNumPhotons = 0;
G4StepPoint *preStep = aStep->GetPostStepPoint();
G4VPhysicalVolume *volume = preStep->GetPhysicalVolume();
if (aStep->GetTrack()->GetDefinition() == G4OpticalPhoton::OpticalPhotonDefinition())
{
// Kill if step count exceeds 10000 to avoid reflection forever
if (aStep->GetTrack()->GetCurrentStepNumber() > 10000)
{
aStep->GetTrack()->SetTrackStatus(fStopAndKill);
}
}
if (volume && volume->GetName() == "MirrorPyramid")
{
aTrack = aStep->GetTrack();
if (aTrack->GetDefinition() != G4OpticalPhoton::OpticalPhotonDefinition())
{
aTrack->SetTrackStatus(fStopAndKill);
}
}
G4SteppingManager *fpSteppingManager =
G4EventManager::GetEventManager()->GetTrackingManager()->GetSteppingManager();
G4StepStatus stepStatus = fpSteppingManager->GetfStepStatus();
if (stepStatus != fAtRestDoItProc)
{
G4ProcessVector *procPost = fpSteppingManager->GetfPostStepDoItVector();
size_t MAXofPostStepLoops = fpSteppingManager->GetMAXofPostStepLoops();
for (size_t i3 = 0; i3 < MAXofPostStepLoops; i3++)
{
if ((*procPost)[i3]->GetProcessName() == "Cerenkov")
{
aTrack = aStep->GetTrack();
const G4DynamicParticle *aParticle = aTrack->GetDynamicParticle();
G4double charge = aParticle->GetDefinition()->GetPDGCharge();
const G4Material *aMaterial = aTrack->GetMaterial();
G4MaterialPropertiesTable *MPT = aMaterial->GetMaterialPropertiesTable();
G4MaterialPropertyVector *Rindex = MPT->GetProperty(kRINDEX);
if (!Rindex || Rindex->GetVectorLength() == 0)
{
G4cout << "WARNING: Material has no valid RINDEX data. Skipping Cerenkov calculation."
<< G4endl;
return;
}
G4Cerenkov *proc = (G4Cerenkov *)(*procPost)[i3];
fNumPhotons = proc->GetNumPhotons();
G4AutoLock lock(&genstep_mutex); // <-- Mutex is locked here
if (fNumPhotons > 0)
{
G4double Pmin = Rindex->Energy(0);
G4double Pmax = Rindex->GetMaxEnergy();
G4double nMax = Rindex->GetMaxValue();
G4double beta1 = aStep->GetPreStepPoint()->GetBeta();
G4double beta2 = aStep->GetPostStepPoint()->GetBeta();
G4double beta = (beta1 + beta2) * 0.5;
G4double BetaInverse = 1. / beta;
G4double maxCos = BetaInverse / nMax;
G4double maxSin2 = (1.0 - maxCos) * (1.0 + maxCos);
G4double MeanNumberOfPhotons1 =
proc->GetAverageNumberOfPhotons(charge, beta1, aMaterial, Rindex);
G4double MeanNumberOfPhotons2 =
proc->GetAverageNumberOfPhotons(charge, beta2, aMaterial, Rindex);
U4::CollectGenstep_G4Cerenkov_modified(aTrack, aStep, fNumPhotons, BetaInverse, Pmin, Pmax,
maxCos, maxSin2, MeanNumberOfPhotons1,
MeanNumberOfPhotons2);
}
}
if ((*procPost)[i3]->GetProcessName() == "Scintillation")
{
G4Scintillation *proc1 = (G4Scintillation *)(*procPost)[i3];
fNumPhotons = proc1->GetNumPhotons();
if (fNumPhotons > 0)
{
aTrack = aStep->GetTrack();
const G4Material *aMaterial = aTrack->GetMaterial();
G4MaterialPropertiesTable *MPT = aMaterial->GetMaterialPropertiesTable();
if (!MPT || !MPT->ConstPropertyExists(kSCINTILLATIONTIMECONSTANT1))
{
G4cout << "WARNING: Material has no valid SCINTILLATIONTIMECONSTANT1 data. Skipping "
"Scintillation calculation."
<< G4endl;
return;
}
// G4 11.x supports up to 3 scintillation components
const G4int tcKeys[3] = {kSCINTILLATIONTIMECONSTANT1, kSCINTILLATIONTIMECONSTANT2,
kSCINTILLATIONTIMECONSTANT3};
const G4int yieldKeys[3] = {kSCINTILLATIONYIELD1, kSCINTILLATIONYIELD2, kSCINTILLATIONYIELD3};
G4double tc[3] = {0, 0, 0};
G4double yield[3] = {0, 0, 0};
G4double yieldSum = 0;
G4int nComp = 0;
for (G4int c = 0; c < 3; c++)
{
if (MPT->ConstPropertyExists(tcKeys[c]))
{
tc[c] = MPT->GetConstProperty(tcKeys[c]);
yield[c] = MPT->ConstPropertyExists(yieldKeys[c]) ? MPT->GetConstProperty(yieldKeys[c])
: (c == 0 ? 1.0 : 0.0);
yieldSum += yield[c];
nComp = c + 1;
}
}
G4AutoLock lock(&genstep_mutex);
G4int nRemaining = fNumPhotons;
for (G4int c = 0; c < nComp; c++)
{
G4int nPhotComp;
if (c == nComp - 1)
nPhotComp = nRemaining; // last component gets remainder
else
nPhotComp = static_cast<G4int>(fNumPhotons * yield[c] / yieldSum);
nRemaining -= nPhotComp;
if (nPhotComp > 0)
U4::CollectGenstep_DsG4Scintillation_r4695(aTrack, aStep, nPhotComp, c + 1, tc[c]);
}
}
}
}
}
}
};
struct TrackingAction : G4UserTrackingAction
{
const G4Track *transient_fSuspend_track = nullptr;
SEvt *sev;
TrackingAction(SEvt *sev) : sev(sev)
{
}
void PreUserTrackingAction_Optical_FabricateLabel(const G4Track *track)
{
}
void PreUserTrackingAction(const G4Track *track) override
{
}
void PostUserTrackingAction(const G4Track *track) override
{
}
};
struct G4App
{
G4App(std::filesystem::path gdml_file)
: sev(SEvt::CreateOrReuse_EGPU()), det_cons_(new DetectorConstruction(gdml_file)),
prim_gen_(new PrimaryGenerator(sev)), event_act_(new EventAction(sev)), run_act_(new RunAction(event_act_)),
stepping_(new SteppingAction(sev)),
tracking_(new TrackingAction(sev))
{
}
//~G4App(){ G4CXOpticks::Finalize();}
// Create "global" event
SEvt *sev;
G4VUserDetectorConstruction *det_cons_;
G4VUserPrimaryGeneratorAction *prim_gen_;
EventAction *event_act_;
RunAction *run_act_;
SteppingAction *stepping_;
TrackingAction *tracking_;
};