-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcx_core.cu
3173 lines (2840 loc) · 146 KB
/
mcx_core.cu
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
/***************************************************************************//**
** \mainpage Monte Carlo eXtreme - GPU accelerated Monte Carlo Photon Migration
**
** \author Qianqian Fang <q.fang at neu.edu>
** \copyright Qianqian Fang, 2009-2021
**
** \section sref Reference:
** \li \c (\b Fang2009) Qianqian Fang and David A. Boas,
** <a href="http://www.opticsinfobase.org/abstract.cfm?uri=oe-17-22-20178">
** "Monte Carlo Simulation of Photon Migration in 3D Turbid Media Accelerated
** by Graphics Processing Units,"</a> Optics Express, 17(22) 20178-20190 (2009).
** \li \c (\b Yu2018) Leiming Yu, Fanny Nina-Paravecino, David Kaeli, and Qianqian Fang,
** "Scalable and massively parallel Monte Carlo photon transport
** simulations for heterogeneous computing platforms," J. Biomed. Optics,
** 23(1), 010504, 2018. https://doi.org/10.1117/1.JBO.23.1.010504
** \li \c (\b Yan2020) Shijie Yan and Qianqian Fang* (2020), "Hybrid mesh and voxel
** based Monte Carlo algorithm for accurate and efficient photon transport
** modeling in complex bio-tissues," Biomed. Opt. Express, 11(11)
** pp. 6262-6270. https://doi.org/10.1364/BOE.409468
**
** \section slicense License
** GPL v3, see LICENSE.txt for details
*******************************************************************************/
/***************************************************************************//**
\file mcx_core.cu
@brief GPU kernel for MC simulations and CUDA host code
This unit contains both the GPU kernels (running on the GPU device) and host code
(running on the host) that initializes GPU buffers, calling kernels, retrieving
all computed results (fluence, diffuse reflectance detected photon data) from GPU,
and post processing, such as normalization, saving data to file etc. The main
function of the GPU kernel is \c mcx_main_loop and the main function of the
host code is \c mcx_run_simulation.
This unit is written with CUDA-C and shall be compiled using nvcc in cuda-toolkit.
*******************************************************************************/
#define _USE_MATH_DEFINES
#include <cmath>
#include "br2cu.h"
#include "mcx_core.h"
#include "tictoc.h"
#include "mcx_const.h"
//#ifdef USE_HALF //< use half-precision for ray-tracing
#include "cuda_fp16.h"
//#endif
#ifdef USE_DOUBLE
typedef double OutputType;
#define SHADOWCOUNT 1
#define ZERO 0.0
#else
typedef float OutputType;
#define SHADOWCOUNT 2
#define ZERO 0.f
#endif
#if defined(USE_XOROSHIRO128P_RAND)
#include "xoroshiro128p_rand.cu" //< Use USE_XOROSHIRO128P_RAND macro to enable xoroshiro128p+ RNG (XORSHIFT128P)
#elif defined(USE_LL5_RAND)
#include "logistic_rand.cu" //< Use USE_LL5_RAND macro to enable Logistic Lattice ring 5 RNG (LL5), used in the original MCX paper but depreciated
#elif defined(USE_POSIX_RAND)
#include "posix_rand.cu" //< Use USE_POSIX_RAND to enable POSIX erand48 RNG (POSIX)
#else //< The default RNG method is use xorshift128+ RNG (XORSHIFT128P)
#include "xorshift128p_rand.cu"
#endif
#ifdef _OPENMP //< If compiled with -fopenmp with GCC, this enables OpenMP multi-threading for running simulation on multiple GPUs
#include <omp.h>
#endif
#define CUDA_ASSERT(a) mcx_cu_assess((a),__FILE__,__LINE__) //< macro to report CUDA errors
#define FL3(f) make_float3(f,f,f)
/**
* @brief Adding two float3 vectors c=a+b
*/
__device__ float3 operator +(const float3 &a, const float3 &b){
return make_float3(a.x + b.x, a.y + b.y, a.z + b.z);
}
/**
* @brief Increatment a float3 vector by another float3, a+=b
*/
__device__ void operator +=(float3 &a, const float3 &b){
a.x += b.x;
a.y += b.y;
a.z += b.z;
}
/**
* @brief Subtracting two float3 vectors c=a+b
*/
__device__ float3 operator -(const float3 &a, const float3 &b){
return make_float3(a.x - b.x, a.y - b.y, a.z - b.z);
}
/**
* @brief Negating a float3 vector c=-a
*/
__device__ float3 operator -(const float3 &a){
return make_float3(-a.x, -a.y, -a.z);
}
/**
* @brief Front-multiplying a float3 with a scalar c=a*b
*/
__device__ float3 operator *(const float &a, const float3 &b){
return make_float3(a * b.x, a * b.y, a * b.z);
}
/**
* @brief Post-multiplying a float3 with a scalar c=a*b
*/
__device__ float3 operator *(const float3 &a, const float &b){
return make_float3(a.x * b, a.y * b, a.z * b);
}
/**
* @brief Multiplying two float3 vectors c=a*b
*/
__device__ float3 operator *(const float3 &a, const float3 &b){
return make_float3(a.x*b.x, a.y*b.y, a.z*b.z);
}
/**
* @brief Dot-product of two float3 vectors c=a*b
*/
__device__ float dot(const float3 &a, const float3 &b){
return a.x * b.x + a.y * b.y + a.z * b.z;
}
/**
* @brief Concatenated optical properties and det positions, stored in constant memory
*
* The first cfg.maxmedia elements of this array contain the optical properties of the
* domains. Format: {x}:mua,{y}:mus,{z}:anisotropy (g),{w}:refractive index (n).
* The following cfg.detnum elements of this array contains the detector information.
* Format: {x,y,z}: the x/y/z coord. of the detector, and {w}: radius; all in grid unit.
* The total length (both media properties and detector) is defined by
* MAX_PROP_AND_DETECTORS, which is 4000 to fully utilize the constant memory space
* (64kb=4096 float4)
*/
__constant__ float4 gproperty[MAX_PROP_AND_DETECTORS];
/**
* @brief Simulation constant parameters stored in the constant memory
*
* This variable stores all constants used in the simulation.
*/
__constant__ MCXParam gcfg[1];
/**
* @brief Global variable to store the number of photon movements for debugging purposes
*/
__device__ uint gjumpdebug[1];
/**
* @brief Pointer to the shared memory (storing photon data and spilled registers)
*/
extern __shared__ char sharedmem[];
/**
* @brief Texture memory for storing media indices
*
* Tested with texture memory for media, only improved 1% speed
* to keep code portable, use global memory for now
* also need to change all media[idx1d] to tex1Dfetch() below
*/
//texture<uchar, 1, cudaReadModeElementType> texmedia;
/**
* @brief Floating-point atomic addition
*/
__device__ inline OutputType atomicadd(OutputType* address, OutputType value){
#if ! defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 200 //< for Fermi, atomicAdd supports floats
return atomicAdd(address,value);
#else
// float-atomic-add from
// http://forums.nvidia.com/index.php?showtopic=158039&view=findpost&p=991561
float old = value;
while ((old = atomicExch(address, atomicExch(address, 0.0f)+old))!=0.0f);
return old;
#endif
}
/**
* @brief Reset shared memory buffer to store photon partial-path data for a new photon
* @param[in] p: pointer to the partial-path buffer
* @param[in] maxmediatype: length of the buffer to be reset
*/
__device__ inline void clearpath(float *p,int maxmediatype){
uint i;
for(i=0;i<maxmediatype;i++)
p[i]=0.f;
}
#ifdef SAVE_DETECTORS
/**
* @brief Testing which detector detects an escaping photon
* @param[in] p0: the position of the escaping photon
* @return the index of the photon that captures this photon; 0 if none.
*/
__device__ inline uint finddetector(MCXpos *p0){
uint i;
for(i=gcfg->maxmedia+1;i<gcfg->maxmedia+gcfg->detnum+1;i++){
if((gproperty[i].x-p0->x)*(gproperty[i].x-p0->x)+
(gproperty[i].y-p0->y)*(gproperty[i].y-p0->y)+
(gproperty[i].z-p0->z)*(gproperty[i].z-p0->z) < gproperty[i].w*gproperty[i].w){
return i-gcfg->maxmedia;
}
}
return 0;
}
__device__ inline void saveexitppath(float n_det[],float *ppath,MCXpos *p0,uint *idx1d){
if(gcfg->issaveref>1){
if(*idx1d>=gcfg->maxdetphoton)
return;
uint baseaddr=(*idx1d)*gcfg->reclen;
n_det[baseaddr]+=p0->w;
for(int i=0;i<gcfg->maxmedia;i++)
n_det[baseaddr+i]+=ppath[i]*p0->w;
}
}
/**
* @brief Recording detected photon information at photon termination
* @param[in] n_det: pointer to the detector position array
* @param[in] detectedphoton: variable in the global-mem recording the total detected photons
* @param[in] ppath: buffer in the shared-mem to store the photon partial-pathlengths
* @param[in] p0: the position/weight of the current photon packet
* @param[in] v: the direction vector of the current photon packet
* @param[in] t: random number generator (RNG) states
* @param[in] seeddata: the RNG seed of the photon at launch, need to save for replay
*/
__device__ inline void savedetphoton(float n_det[],uint *detectedphoton,float *ppath,MCXpos *p0,MCXdir *v,RandType t[RAND_BUF_LEN],RandType *seeddata,uint isdet){
int detid;
detid=(isdet==OUTSIDE_VOLUME_MIN)?-1:(int)finddetector(p0);
if(detid){
uint baseaddr=atomicAdd(detectedphoton,1);
if(baseaddr<gcfg->maxdetphoton){
uint i;
for(i=0;i<gcfg->issaveseed*RAND_BUF_LEN;i++)
seeddata[baseaddr*RAND_BUF_LEN+i]=t[i]; //< save photon seed for replay
baseaddr*=gcfg->reclen;
if(SAVE_DETID(gcfg->savedetflag))
n_det[baseaddr++]=detid;
for(i=0;i<gcfg->partialdata;i++)
n_det[baseaddr++]=ppath[i]; //< save partial pathlength to the memory
if(SAVE_PEXIT(gcfg->savedetflag)){
*((float3*)(n_det+baseaddr))=float3(p0->x,p0->y,p0->z);
baseaddr+=3;
}
if(SAVE_VEXIT(gcfg->savedetflag)){
*((float3*)(n_det+baseaddr))=float3(v->x,v->y,v->z);
baseaddr+=3;
}
if(SAVE_W0(gcfg->savedetflag))
n_det[baseaddr++]=ppath[gcfg->w0offset-1];
}
}
}
#endif
/**
* @brief Saving photon trajectory data for debugging purposes
* @param[in] p: the position/weight of the current photon packet
* @param[in] id: the global index of the photon
* @param[in] gdebugdata: pointer to the global-memory buffer to store the trajectory info
*/
__device__ inline void savedebugdata(MCXpos *p,uint id,float *gdebugdata){
uint pos=atomicAdd(gjumpdebug,1);
if(pos<gcfg->maxjumpdebug){
pos*=MCX_DEBUG_REC_LEN;
((uint *)gdebugdata)[pos++]=id;
gdebugdata[pos++]=p->x;
gdebugdata[pos++]=p->y;
gdebugdata[pos++]=p->z;
gdebugdata[pos++]=p->w;
gdebugdata[pos++]=0;
}
}
/**
* @brief A simplified nextafterf() to ensure a photon moves outside of the current voxel after each move
* @param[in] a: a floating point number
* @param[in] dir: 1: change 1 bit in the positive direction; 0: no change, -1: change 1 bit in the negative direction
*/
__device__ inline float mcx_nextafterf(float a, int dir){
union{
float f;
uint i;
} num;
num.f=a+gcfg->maxvoidstep; /** First, shift coordinate by 1000 to make sure values are always positive */
num.i+=dir ^ (num.i & SIGN_BIT);/** Then make 1 bit difference along the direction indicated by dir */
return num.f-gcfg->maxvoidstep; /** Last, undo the offset, and return */
}
#ifndef USE_HALF
/**
* @brief Core function for photon-voxel ray-tracing
*
* This is the heart of the MCX simulation algorithm. It calculates the nearest intersection
* of the ray inside the current cubic voxel.
*
* @param[in] p0: the x/y/z position of the current photon
* @param[in] v: the direction vector of the photon
* @param[out] htime: the intersection x/y/z position on the bounding box, right outside of this voxel
* @param[in] rv: pre-computed reciprocal of the velocity vector (v)
* @param[out] id: 0: intersect with x=x0 plane; 1: intersect with y=y0 plane; 2: intersect with z=z0 plane first
* @return the distance to the intersection to the voxel bounding box
*/
__device__ inline float hitgrid(float3 *p0, float3 *v, float *htime,float* rv,int *id){
float dist;
//< time-of-flight to hit the wall in each direction
htime[0]=fabs((floorf(p0->x)+(v->x>0.f)-p0->x)*rv[0]); //< time-of-flight in x
htime[1]=fabs((floorf(p0->y)+(v->y>0.f)-p0->y)*rv[1]);
htime[2]=fabs((floorf(p0->z)+(v->z>0.f)-p0->z)*rv[2]);
//< get the direction with the smallest time-of-flight
dist=fminf(fminf(htime[0],htime[1]),htime[2]);
(*id)=(dist==htime[0]?0:(dist==htime[1]?1:2));
//< p0 is inside, htime is the 1st intersection point
htime[0]=p0->x+dist*v->x;
htime[1]=p0->y+dist*v->y;
htime[2]=p0->z+dist*v->z;
//< make sure the intersection point htime is immediately outside of the current voxel (i.e. not within the current voxel)
int index = (*id & (int)3);
if(index == 0) htime[0] = mcx_nextafterf(roundf(htime[0]), (v->x > 0.f)-(v->x < 0.f));
if(index == 1) htime[1] = mcx_nextafterf(roundf(htime[1]), (v->y > 0.f)-(v->y < 0.f));
if(index == 2) htime[2] = mcx_nextafterf(roundf(htime[2]), (v->z > 0.f)-(v->z < 0.f));
return dist;
}
#else
/**
* @brief Half-precision version of the simplified nextafter
*
* @param[in] a: a half-precision floating point number
* @param[in] dir: 1: change 1 bit in the positive direction; 0: no change, -1: change 1 bit in the negative direction
*/
__device__ inline half mcx_nextafter_half(const half a, const short dir){
union{
#if ! defined(__CUDACC_VER_MAJOR__) || __CUDACC_VER_MAJOR__ >= 9
__half_raw f;
#else
half f;
#endif
short i;
} num;
num.f=a;
((num.i & 0x7FFFU) == 0) ? (num.i = ((dir & 0x8000U) ) | 1) : ((num.i & 0x8000U) ? num.i-= dir: num.i+= dir);
return num.f;
}
/**
* @brief Core function for photon-voxel ray-tracing (half-precision version)
*
* This is the heart of the MCX simulation algorithm. It calculates the nearest intersection
* of the ray inside the current cubic voxel.
*
* @param[in] p0: the x/y/z position of the current photon
* @param[in] v: the direction vector of the photon
* @param[out] htime: the intersection x/y/z position on the bounding box, right outside of this voxel
* @param[in] rv: pre-computed reciprocal of the velocity vector (v)
* @param[out] id: 0: intersect with x=x0 plane; 1: intersect with y=y0 plane; 2: intersect with z=z0 plane first
* @return the distance to the intersection to the voxel bounding box
*/
__device__ inline float hitgrid(float3 *p0, float3 *v, float *htime,float* rv,int *id){
float dist;
union {
unsigned int i;
float f;
#if ! defined(__CUDACC_VER_MAJOR__) || __CUDACC_VER_MAJOR__ >= 9
__half2_raw h2;
__half_raw h[2];
#else
half2 h2;
half h[2];
#endif
} pxy, pzw, vxy, vzw, h1, h2, temp;
pxy.h2=__floats2half2_rn(floorf(p0->x) - p0->x, floorf(p0->y) - p0->y);
pzw.h2=__floats2half2_rn(floorf(p0->z) - p0->z, 1e5f);
vxy.h2=__floats2half2_rn(rv[0],rv[1]);
vzw.h2=__floats2half2_rn(rv[2],1.f);
temp.h2 = __floats2half2_rn(0.f, 0.f);
h1.h2 = __hmul2(__hadd2(pxy.h2,__hgt2(vxy.h2, temp.h2 )), vxy.h2);
h2.h2 = __hmul2(__hadd2(pzw.h2,__hgt2(vzw.h2, temp.h2 )), vzw.h2);
// abs
h1.i &= 0x7FFF7FFF;
h2.i &= 0x7FFF7FFF;
temp.h[0]=(__hlt(h1.h[0], h1.h[1])) ? (*id=0,h1.h[0]) : (*id=1,h1.h[1]);
temp.h[1]=(__hlt(temp.h[0], h2.h[0])) ? temp.h[0] : (*id=2,h2.h[0]);
dist=__half2float(temp.h[1]);
//p0 is inside, p is outside, move to the 1st intersection pt, now in the air side, to be corrected in the else block
vxy.h2=__floats2half2_rn(v->x,v->y);
vzw.h2=__floats2half2_rn(v->z,0.f);
pxy.h2=__floats2half2_rn(p0->x, p0->y);
pzw.h2=__floats2half2_rn(p0->z, 0.f);
h1.h2 =__hfma2(vxy.h2,__floats2half2_rn(dist,dist),pxy.h2);
h2.h2 =__hfma2(vzw.h2,__floats2half2_rn(dist,dist),pzw.h2);
htime[0]=__half2float(h1.h[0]);
htime[1]=__half2float(h1.h[1]);
htime[2]=__half2float(h2.h[0]);
temp.h2 = __floats2half2_rn(0.f, 0.f);
pxy.h2=__hgt2(vxy.h2, temp.h2 );
pzw.h2=__hlt2(vxy.h2, temp.h2 );
pxy.h2=__hsub2(pxy.h2, pzw.h2 );
pzw.h2=__hlt2(vzw.h2, temp.h2 );
temp.h2=__hgt2(vzw.h2, temp.h2 );
pzw.h2=__hsub2(temp.h2,pzw.h2 );
if((*id) == 0) htime[0] = __half2float(mcx_nextafter_half(hrint(h1.h[0]), __half2short_rn(pxy.h[0])));
if((*id) == 1) htime[1] = __half2float(mcx_nextafter_half(hrint(h1.h[1]), __half2short_rn(pxy.h[1])));
if((*id) == 2) htime[2] = __half2float(mcx_nextafter_half(hrint(h2.h[0]), __half2short_rn(pzw.h[0])));
return dist;
}
#endif
/**
* @brief Calculating the direction vector after transmission
*
* This function updates the direction vector after the photon passing
* an interface of different refrective indicex (n1/n2). Because MCX only
* handles voxelated domain, transmission is applied only to 1 of the components,
* and then the vector is normalized.
*
* @param[in,out] v: the direction vector of the photon
* @param[in] n1: the refrective index of the voxel the photon leaves
* @param[in] n2: the refrective index of the voxel the photon enters
* @param[in] flipdir: 0: transmit through x=x0 plane; 1: through y=y0 plane; 2: through z=z0 plane
*/
__device__ inline void transmit(MCXdir *v, float n1, float n2,int flipdir){
float tmp0=n1/n2;
v->x*=tmp0;
v->y*=tmp0;
v->z*=tmp0;
(flipdir==0) ?
(v->x= ((tmp0 = v->y*v->y + v->z*v->z) <1.f) ? sqrtf(1.f - tmp0)*((v->x>0.f)-(v->x<0.f)) : 0.f):
((flipdir==1) ?
(v->y=((tmp0 = v->x*v->x + v->z*v->z) <1.f) ? sqrtf(1.f - tmp0)*((v->y>0.f)-(v->y<0.f)) : 0.f):
(v->z=((tmp0 = v->x*v->x + v->y*v->y) <1.f) ? sqrtf(1.f - tmp0)*((v->z>0.f)-(v->z<0.f)) : 0.f));
tmp0=rsqrtf(v->x*v->x + v->y*v->y + v->z*v->z);
v->x*=tmp0;
v->y*=tmp0;
v->z*=tmp0;
}
/**
* @brief Calculating the reflection coefficient at an interface
*
* This function calculates the reflection coefficient at
* an interface of different refrective indicex (n1/n2)
*
* @param[in] v: the direction vector of the photon
* @param[in] n1: the refrective index of the voxel the photon leaves
* @param[in] n2: the refrective index of the voxel the photon enters
* @param[in] flipdir: 0: transmit through x=x0 plane; 1: through y=y0 plane; 2: through z=z0 plane
* @return the reflection coefficient R=(Rs+Rp)/2, Rs: R of the perpendicularly polarized light, Rp: parallelly polarized light
*/
__device__ inline float reflectcoeff(MCXdir *v, float n1, float n2, int flipdir){
float Icos=fabs((flipdir==0) ? v->x : (flipdir==1 ? v->y : v->z));
float tmp0=n1*n1;
float tmp1=n2*n2;
float tmp2=1.f-tmp0/tmp1*(1.f-Icos*Icos); /** 1-[n1/n2*sin(si)]^2 = cos(ti)^2*/
if(tmp2>0.f){ //< partial reflection
float Re,Im,Rtotal;
Re=tmp0*Icos*Icos+tmp1*tmp2;
tmp2=sqrtf(tmp2); /** to save one sqrt*/
Im=2.f*n1*n2*Icos*tmp2;
Rtotal=(Re-Im)/(Re+Im); /** Rp*/
Re=tmp1*Icos*Icos+tmp0*tmp2*tmp2;
Rtotal=(Rtotal+(Re-Im)/(Re+Im))*0.5f; /** (Rp+Rs)/2*/
return Rtotal;
}else{ //< total reflection
return 1.f;
}
}
/**
* @brief Loading optical properties from constant memory
*
* This function parses the media input and load optical properties
* from GPU memory
*
* @param[out] prop: pointer to the current optical properties {mua, mus, g, n}
* @param[in] mediaid: the media ID (32 bit) of the current voxel, format is specified in gcfg->mediaformat or cfg->mediabyte
*/
template <const int islabel, const int issvmc>
__device__ void updateproperty(Medium *prop, unsigned int& mediaid, RandType t[RAND_BUF_LEN], unsigned int idx1d,
uint media[], float3 *p, MCXsp *nuvox){
/**
* The default mcx input volume is assumed to be 4-byte per voxel
* (SVMC mode requires 2x 4-byte voxels for 8 data points)
*
* The data encoded in the voxel are parsed based on the gcfg->mediaformat flag.
* Below, we use [s*] to represent 2-byte short integers; [h*] to represent a
* 2-byte half-precision floating point number; [c*] to represent
* 1-byte unsigned char integers and [i*] to represent 4-byte integers;
* [f*] for 4-byte floating point number
* index 0 starts from the lowest (least significant bit) end
*/
if(islabel){ //< [i0]: traditional MCX input type - voxels store integer labels, islabel is a template const for speed
*((float4*)(prop))=gproperty[mediaid & MED_MASK];
}else if(gcfg->mediaformat==MEDIA_LABEL_HALF){ //< [h1][s0]: h1: half-prec property value; highest 2bit in s0: index 0-3, low 14bit: tissue label
union{
unsigned int i;
#if ! defined(__CUDACC_VER_MAJOR__) || __CUDACC_VER_MAJOR__ >= 9
__half_raw h[2];
#else
half h[2];
#endif
unsigned short s[2]; /**s[1]: half-prec property; s[0]: high 2bits: idx 0-3, low 14bits: tissue label*/
} val;
val.i=mediaid & MED_MASK;
*((float4*)(prop))=gproperty[val.s[0] & 0x3FFF];
float *p=(float*)(prop);
p[(val.s[0] & 0xC000)>>14]=fabs(__half2float(val.h[1]));
}else if(gcfg->mediaformat==MEDIA_MUA_FLOAT){ //< [f0]: single-prec mua every voxel; mus/g/n uses 2nd row in gcfg.prop
prop->mua=fabs(*((float *)&mediaid));
prop->n=gproperty[!(mediaid & MED_MASK)==0].w;
}else if(gcfg->mediaformat==MEDIA_AS_F2H||gcfg->mediaformat==MEDIA_AS_HALF){ //< [h1][h0]: h1/h0: single-prec mua/mus for every voxel; g/n uses those in cfg.prop(2,:)
union {
unsigned int i;
#if ! defined(__CUDACC_VER_MAJOR__) || __CUDACC_VER_MAJOR__ >= 9
__half_raw h[2];
#else
half h[2];
#endif
} val;
val.i=mediaid & MED_MASK;
prop->mua=fabs(__half2float(val.h[0]));
prop->mus=fabs(__half2float(val.h[1]));
prop->n=gproperty[!(mediaid & MED_MASK)==0].w;
}else if(gcfg->mediaformat==MEDIA_2LABEL_MIX){ //< [s1][c1][c0]: s1: (volume fraction of tissue 1)*(2^16-1), c1: tissue 1 label, c0: tissue 0 label
union {
unsigned int i;
unsigned short h[2];
unsigned char c[4];
} val;
val.i=mediaid & MED_MASK;
if(val.h[1]>0){
if((rand_uniform01(t)*32767.f)<val.h[1]){
*((float4*)(prop))=gproperty[val.c[1]];
mediaid>>=8;
}else
*((float4*)(prop))=gproperty[val.c[0]];
mediaid &= 0xFFFF;
}else
*((float4*)(prop))=gproperty[val.c[0]];
}else if(gcfg->mediaformat==MEDIA_ASGN_BYTE){//< [c3][c2][c1][c0]: c0/c1/c2/c3: interpolation ratios (scaled to 0-255) of mua/mus/g/n between cfg.prop(1,:) and cfg.prop(2,:)
union {
unsigned int i;
unsigned char h[4];
} val;
val.i=mediaid & MED_MASK;
prop->mua=val.h[0]*(1.f/255.f)*(gproperty[2].x-gproperty[1].x)+gproperty[1].x;
prop->mus=val.h[1]*(1.f/255.f)*(gproperty[2].y-gproperty[1].y)+gproperty[1].y;
prop->g =val.h[2]*(1.f/255.f)*(gproperty[2].z-gproperty[1].z)+gproperty[1].z;
prop->n =val.h[3]*(1.f/127.f)*(gproperty[2].w-gproperty[1].w)+gproperty[1].w;
}else if(gcfg->mediaformat==MEDIA_AS_SHORT){//< [s1][s0]: s0/s1: interpolation ratios (scaled to 0-65535) of mua/mus between cfg.prop(1,:) and cfg.prop(2,:)
union {
unsigned int i;
unsigned short h[2];
} val;
val.i=mediaid & MED_MASK;
prop->mua=val.h[0]*(1.f/65535.f)*(gproperty[2].x-gproperty[1].x)+gproperty[1].x;
prop->mus=val.h[1]*(1.f/65535.f)*(gproperty[2].y-gproperty[1].y)+gproperty[1].y;
prop->n=gproperty[!(mediaid & MED_MASK)==0].w;
}else if(issvmc){ //< SVMC mode [c7][c6][c5][c4] and [c3][c2][c1][c0] stored as two 4-byte records;
if(idx1d==OUTSIDE_VOLUME_MIN || idx1d==OUTSIDE_VOLUME_MAX){
*((float4*)(prop))=gproperty[0]; // out-of-bounds
return;
}
union {
unsigned char c[8];
unsigned int i[2];
} val; // c[7-6]: lower & upper label, c[5-3]: reference point, c[2-0]: normal vector
val.i[0]=media[idx1d+gcfg->dimlen.z];
val.i[1]=mediaid & MED_MASK;
nuvox->sv.lower=val.c[7];
nuvox->sv.upper=val.c[6];
if(val.c[6]){ // if upper label is not zero, the photon is inside a mixed voxel
/** Extract the reference point of the intra-voxel interface*/
nuvox->rp=float3(val.c[5]*(1.f/255.f),val.c[4]*(1.f/255.f),val.c[3]*(1.f/255.f));
(nuvox->rp)+=float3(floorf(p->x),floorf(p->y),floorf(p->z));
/** Extract the normal vector of the intra-voxel interface*/
nuvox->nv=float3(val.c[2]*(2.f/255.f)-1,val.c[1]*(2.f/255.f)-1,val.c[0]*(2.f/255.f)-1);
nuvox->nv=nuvox->nv*rsqrtf(dot(nuvox->nv,nuvox->nv));
/** Determine tissue label corresponding to the current photon position*/
if(dot(nuvox->rp-*p,nuvox->nv)<0){
*((float4*)(prop))=gproperty[nuvox->sv.upper]; // upper label
nuvox->sv.isupper=1;
nuvox->nv=-nuvox->nv; // normal vector always points to the other side (outward-pointing)
}else{
*((float4*)(prop))=gproperty[nuvox->sv.lower]; // lower label
nuvox->sv.isupper=0;
}
nuvox->sv.issplit=1;
}else{ // if upper label is zero, the photon is inside a regular voxel
*((float4*)(prop))=gproperty[val.c[7]]; // voxel uniquely labeled
nuvox->sv.issplit=0;
nuvox->sv.isupper=0;
}
}
}
/**
* @brief Compute intersection point between a photon path and the intra-voxel interface if present
*
* This function tests if a ray intersects with an in-voxel marching-cube boundary (a plane) in SVMC mode
*
* @param[in] p0: current position
* @param[in] v: current photon direction
* @param[in] prop: optical properties
* @param[in,out] len: photon movement length, updated if intersection is found
* @param[in,out] slen: remaining unitless scattering length, updated if intersection is found
* @param[in] nuvox: a struct storing normal direction (nv) and a point on the plane
* @param[in] f: photon state including total time-of-flight, number of scattering etc
* @param[in] htime: nearest intersection of the enclosing voxel, returned by hitgrid
*/
__device__ int ray_plane_intersect(float3 *p0, MCXdir *v, Medium *prop, float &len, float &slen,
MCXsp *nuvox, MCXtime f, float3 &htime, int &flipdir){
if(dot(*(float3*)v,nuvox->nv)<=0){ // no intersection, as nv always points to the other side
return 0;
}else{
float3 p1=(gcfg->faststep || slen==f.pscat) ? (*p0+len*(*(float3*)v)) : float3(flipdir==0 ? roundf(htime.x) : htime.x,
flipdir==1 ? roundf(htime.y) : htime.y, flipdir==2 ? roundf(htime.z) : htime.z);
float3 rp0=*p0-nuvox->rp;
float3 rp1=p1-nuvox->rp;
float d0=dot(rp0,nuvox->nv); // signed perpendicular distance from p0 to patch
float d1=dot(rp1,nuvox->nv); // signed perpendicular distance from p1 to patch
if(d0*d1>0.f){ // p0 and p1 are on the same side, no interection
return 0;
}else{
float len0=len*d0/(d0-d1);
len=(len0 > 0) ? len0 : len;
slen=len*prop->mus*(v->nscat+1.f > gcfg->gscatter ? (1.f-prop->g) : 1.f);
return 1;
}
}
}
/**
* @brief Perform reflection/refraction computation along mismatched intra-voxel interface
*
* This function returns a new direction when a ray is reflected/transmitted
* through an in-voxel marching-cube boundary in the SVMC mode
*
* @param[in] n1: refractive index of the current subvolume in a split-voxel
* @param[in,out] c0: current photon direction
* @param[out] rv: reciprocated direction vector rv={1/c0.x,1/c0.y,1/c0.z}
* @param[in] prop: optical properties
* @param[in] nuvox: a struct storing normal direction (nv) and a point on the plane
* @param[in] t: random number state for deciding reflection/transmission
*/
__device__ int reflectray(float n1, float3 *c0, float3 *rv, MCXsp *nuvox, Medium *prop, RandType t[RAND_BUF_LEN]){
/*to handle refractive index mismatch*/
float Icos,Re,Im,Rtotal,tmp0,tmp1,tmp2,n2;
Icos=fabs(dot(*c0,nuvox->nv));
n2=(nuvox->sv.isupper)? gproperty[nuvox->sv.upper].w : gproperty[nuvox->sv.lower].w;
tmp0=n1*n1;
tmp1=n2*n2;
tmp2=1.f-tmp0/tmp1*(1.f-Icos*Icos); /*1-[n1/n2*sin(si)]^2 = cos(ti)^2*/
if(tmp2>0.f){ /*if no total internal reflection*/
Re=tmp0*Icos*Icos+tmp1*tmp2; /*transmission angle*/
tmp2=sqrtf(tmp2); /*to save one sqrt*/
Im=2.f*n1*n2*Icos*tmp2;
Rtotal=(Re-Im)/(Re+Im); /*Rp*/
Re=tmp1*Icos*Icos+tmp0*tmp2*tmp2;
Rtotal=(Rtotal+(Re-Im)/(Re+Im))*0.5f; /*(Rp+Rs)/2*/
if(rand_next_reflect(t)<=Rtotal){ /*do reflection*/
*c0+=(FL3(-2.f*Icos))*nuvox->nv;
nuvox->sv.isupper=!nuvox->sv.isupper;
}else{ /*do transmission*/
*c0+=(FL3(-Icos))*nuvox->nv;
*c0=(FL3(tmp2))*nuvox->nv+FL3(n1/n2)*(*c0);
nuvox->nv=-nuvox->nv;
if(((nuvox->sv.isupper)? nuvox->sv.isupper:nuvox->sv.lower)==0) /*transmit to background medium*/
return 1;
*((float4*)prop)=gproperty[nuvox->sv.isupper ? nuvox->sv.upper:nuvox->sv.lower];
}
}else{ /*total internal reflection*/
*c0+=(FL3(-2.f*Icos))*nuvox->nv;
nuvox->sv.isupper=!nuvox->sv.isupper;
}
tmp0=rsqrtf(dot(*c0,*c0));
(*c0)=(*c0)*FL3(tmp0);
(*rv)=float3(__fdividef(1.f,c0->x),__fdividef(1.f,c0->y),__fdividef(1.f,c0->z));
return 0;
}
/**
* @brief Loading optical properties from constant memory
*
* This function parses the media input and load optical properties
* from GPU memory
*
* @param[in] mediaid: the media ID (32 bit) of the current voxel, format is specified in gcfg->mediaformat or cfg->mediabyte
*/
__device__ float getrefractiveidx(unsigned int mediaid){
if((mediaid& MED_MASK)==0)
return gproperty[0].w;
if(gcfg->mediaformat<=4)
return gproperty[mediaid & MED_MASK].w;
else if(gcfg->mediaformat==MEDIA_ASGN_BYTE)
return 0.9f;
else
return gproperty[1].w;
}
/**
* @brief Advance photon to the 1st non-zero voxel if launched in the backgruond
*
* This function advances the photon to the 1st non-zero voxel along the direction
* of v if the photon is launched outside of the cubic domain or in a zero-voxel.
* To avoid large overhead, photon can only advance gcfg->minaccumtime steps, which
* can be set using the --maxvoidstep flag; by default, this limit is 1000.
*
* @param[in] v: the direction vector of the photon
* @param[in] n1: the refrective index of the voxel the photon leaves
* @param[in] n2: the refrective index of the voxel the photon enters
* @param[in] flipdir: 0: transmit through x=x0 plane; 1: through y=y0 plane; 2: through z=z0 plane
* @return the reflection coefficient R=(Rs+Rp)/2, Rs: R of the perpendicularly polarized light, Rp: parallelly polarized light
*/
template <const int islabel, const int issvmc>
__device__ inline int skipvoid(MCXpos *p,MCXdir *v,MCXtime *f,float3* rv,uint media[],RandType t[RAND_BUF_LEN],
MCXsp *nuvox){
int count=1,idx1d;
while(1){
if(p->x>=0.f && p->y>=0.f && p->z>=0.f && p->x < gcfg->maxidx.x
&& p->y < gcfg->maxidx.y && p->z < gcfg->maxidx.z){
idx1d=(int(floorf(p->z))*gcfg->dimlen.y+int(floorf(p->y))*gcfg->dimlen.x+int(floorf(p->x)));
if(media[idx1d] & MED_MASK){ //< if enters a non-zero voxel
GPUDEBUG(("inside volume [%f %f %f] v=<%f %f %f>\n",p->x,p->y,p->z,v->x,v->y,v->z));
float4 htime;
int flipdir;
p->x-=v->x;
p->y-=v->y;
p->z-=v->z;
f->t-=gcfg->minaccumtime;
idx1d=(int(floorf(p->z))*gcfg->dimlen.y+int(floorf(p->y))*gcfg->dimlen.x+int(floorf(p->x)));
GPUDEBUG(("look for entry p0=[%f %f %f] rv=[%f %f %f]\n",p->x,p->y,p->z,rv->x,rv->y,rv->z));
count=0;
while(!(p->x>=0.f && p->y>=0.f && p->z>=0.f && p->x < gcfg->maxidx.x
&& p->y < gcfg->maxidx.y && p->z < gcfg->maxidx.z) || !(media[idx1d] & MED_MASK)){ // at most 3 times
f->t+=gcfg->minaccumtime*hitgrid((float3*)p,(float3*)v,&htime.x,&rv->x,&flipdir);
*((float4*)(p))=float4(htime.x,htime.y,htime.z,p->w);
idx1d=(int(floorf(p->z))*gcfg->dimlen.y+int(floorf(p->y))*gcfg->dimlen.x+int(floorf(p->x)));
GPUDEBUG(("entry p=[%f %f %f] flipdir=%d\n",p->x,p->y,p->z,flipdir));
if(count++>3){
GPUDEBUG(("fail to find entry point after 3 iterations, something is wrong, abort!!"));
break;
}
}
f->t= (gcfg->voidtime) ? f->t : 0.f;
updateproperty<islabel, issvmc>((Medium *)&htime,media[idx1d],t,idx1d,media,(float3*)p,nuvox);
if(gcfg->isspecular && htime.w!=gproperty[0].w){
p->w*=1.f-reflectcoeff(v, gproperty[0].w,htime.w,flipdir);
GPUDEBUG(("transmitted intensity w=%e\n",p->w));
if(p->w>EPS){
transmit(v, gproperty[0].w,htime.w,flipdir);
GPUDEBUG(("transmit into volume v=<%f %f %f>\n",v->x,v->y,v->z));
}
}
GPUDEBUG(("entry from voxel [%d]\n",idx1d));
return idx1d;
}
}
if( (p->x<0.f) && (v->x<=0.f) || (p->x >= gcfg->maxidx.x) && (v->x>=0.f)
|| (p->y<0.f) && (v->y<=0.f) || (p->y >= gcfg->maxidx.y) && (v->y>=0.f)
|| (p->z<0.f) && (v->z<=0.f) || (p->z >= gcfg->maxidx.z) && (v->z>=0.f))
return -1;
*((float4*)(p))=float4(p->x+v->x,p->y+v->y,p->z+v->z,p->w);
GPUDEBUG(("inside void [%f %f %f]\n",p->x,p->y,p->z));
f->t+=gcfg->minaccumtime;
if(count++>gcfg->maxvoidstep)
return -1;
}
}
/**
* @brief Compute 2D-scattering if the domain has a dimension of 1 in x/y or z
*
* This function performs 2D scattering calculation if the domain is only a sheet of voxels
*
* @param[in,out] v: the direction vector of the photon
* @param[in] stheta: the sine of the rotation angle
* @param[in] ctheta: the cosine of the rotation angle
*/
__device__ inline void rotatevector2d(MCXdir *v, float stheta, float ctheta){
if(gcfg->is2d==1)
*((float4*)v)=float4(
0.f,
v->y*ctheta - v->z*stheta,
v->y*stheta + v->z*ctheta,
v->nscat
);
else if(gcfg->is2d==2)
*((float4*)v)=float4(
v->x*ctheta - v->z*stheta,
0.f,
v->x*stheta + v->z*ctheta,
v->nscat
);
else if(gcfg->is2d==3)
*((float4*)v)=float4(
v->x*ctheta - v->y*stheta,
v->x*stheta + v->y*ctheta,
0.f,
v->nscat
);
GPUDEBUG(("new dir: %10.5e %10.5e %10.5e\n",v->x,v->y,v->z));
}
/**
* @brief Compute 3D-scattering direction vector
*
* This function updates the direction vector after a 3D scattering event
*
* @param[in,out] v: the direction vector of the photon
* @param[in] stheta: the sine of the azimuthal angle
* @param[in] ctheta: the cosine of the azimuthal angle
* @param[in] sphi: the sine of the zenith angle
* @param[in] cphi: the cosine of the zenith angle
*/
__device__ inline void rotatevector(MCXdir *v, float stheta, float ctheta, float sphi, float cphi){
if( v->z>-1.f+EPS && v->z<1.f-EPS ) {
float tmp0=1.f-v->z*v->z;
float tmp1=stheta*rsqrtf(tmp0);
*((float4*)v)=float4(
tmp1*(v->x*v->z*cphi - v->y*sphi) + v->x*ctheta,
tmp1*(v->y*v->z*cphi + v->x*sphi) + v->y*ctheta,
-tmp1*tmp0*cphi + v->z*ctheta,
v->nscat
);
}else{
*((float4*)v)=float4(stheta*cphi,stheta*sphi,(v->z>0.f)?ctheta:-ctheta,v->nscat);
}
GPUDEBUG(("new dir: %10.5e %10.5e %10.5e\n",v->x,v->y,v->z));
}
/**
* @brief Terminate a photon and launch a new photon according to specified source form
*
* This function terminates the current photon and launches a new photon according
* to the source type selected. Currently, over a dozen source types are supported,
* including pencil, isotropic, planar, fourierx, gaussian, zgaussian etc.
*
* @param[in,out] p: the 3D position and weight of the photon
* @param[in,out] v: the direction vector of the photon
* @param[in,out] f: the parameter vector of the photon
* @param[in,out] rv: the reciprocal direction vector of the photon (rv[i]=1/v[i])
* @param[out] prop: the optical properties of the voxel the photon is launched into
* @param[in,out] idx1d: the linear index of the voxel containing the photon at launch
* @param[in] field: the 3D array to store photon weights
* @param[in,out] mediaid: the medium index at the voxel at launch
* @param[in,out] w0: initial weight, reset here after launch
* @param[in] isdet: whether the previous photon being terminated lands at a detector
* @param[in,out] ppath: pointer to the shared-mem buffer to store photon partial-path data
* @param[in,out] n_det: array in the constant memory where detector positions are stored
* @param[in,out] dpnum: global-mem variable where the count of detected photons are stored
* @param[in] t: RNG state
* @param[in,out] photonseed: RNG state stored at photon's launch time if replay is needed
* @param[in] media: domain medium index array, read-only
* @param[in] srcpattern: user-specified source pattern array if pattern source is used
* @param[in] threadid: the global index of the current thread
* @param[in] rngseed: in the replay mode, pointer to the saved detected photon seed data
* @param[in,out] seeddata: pointer to the buffer to save detected photon seeds
* @param[in,out] gdebugdata: pointer to the buffer to save photon trajectory positions
* @param[in,out] gprogress: pointer to the host variable to update progress bar
*/
template <const int ispencil, const int isreflect, const int islabel, const int issvmc>
__device__ inline int launchnewphoton(MCXpos *p,MCXdir *v,MCXtime *f,float3* rv,Medium *prop,uint *idx1d, OutputType *field,
uint *mediaid,OutputType *w0,uint isdet, float ppath[],float n_det[],uint *dpnum,
RandType t[RAND_BUF_LEN],RandType photonseed[RAND_BUF_LEN],
uint media[],float srcpattern[],int threadid,RandType rngseed[],RandType seeddata[],float gdebugdata[],volatile int gprogress[],
float photontof[],MCXsp *nuvox){
*w0=1.f; //< reuse to count for launchattempt
int canfocus=1; //< non-zero: focusable, zero: not focusable
/**
* First, let's terminate the current photon and perform detection calculations
*/
if(p->w>=0.f){
ppath[gcfg->partialdata]+=p->w; //< sum all the remaining energy
if(gcfg->debuglevel & MCX_DEBUG_MOVE)
savedebugdata(p,((uint)f->ndone)+threadid*gcfg->threadphoton+umin(threadid,(threadid<gcfg->oddphotons)*threadid),gdebugdata);
if(*mediaid==0 && *idx1d!=OUTSIDE_VOLUME_MIN && *idx1d!=OUTSIDE_VOLUME_MAX && gcfg->issaveref){
if(gcfg->issaveref==1){
int tshift=MIN(gcfg->maxgate-1,(int)(floorf((f->t-gcfg->twin0)*gcfg->Rtstep)));
if(gcfg->srctype!=MCX_SRC_PATTERN && gcfg->srctype!=MCX_SRC_PATTERN3D){
#ifdef USE_ATOMIC
atomicAdd(& field[*idx1d+tshift*gcfg->dimlen.z],-p->w);
#else
field[*idx1d+tshift*gcfg->dimlen.z]+=-p->w;
#endif
}else{
for(int i=0;i<gcfg->srcnum;i++){
if(ppath[gcfg->w0offset+i]>0.f){
#ifdef USE_ATOMIC
atomicAdd(& field[(*idx1d+tshift*gcfg->dimlen.z)*gcfg->srcnum+i],-((gcfg->srcnum==1)?p->w:p->w*ppath[gcfg->w0offset+i]));
#else
field[(*idx1d+tshift*gcfg->dimlen.z)*gcfg->srcnum+i]+=-((gcfg->srcnum==1)?p->w:p->w*ppath[gcfg->w0offset+i]);
#endif
}
}
}
}else{
saveexitppath(n_det,ppath,p,idx1d);
}
}
#ifdef SAVE_DETECTORS
// let's handle detectors here
if(gcfg->savedet){
if((isdet&DET_MASK)==DET_MASK && (*mediaid==0 || (issvmc &&
(nuvox->sv.isupper ? nuvox->sv.upper : nuvox->sv.lower)==0)) && gcfg->issaveref<2)
savedetphoton(n_det,dpnum,ppath,p,v,photonseed,seeddata,isdet);
clearpath(ppath,gcfg->partialdata);
}
#endif