forked from ymartin101/RTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathray_tracer.cpp
More file actions
1364 lines (1088 loc) · 76.3 KB
/
Copy pathray_tracer.cpp
File metadata and controls
1364 lines (1088 loc) · 76.3 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
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
/* ****************** Ray Tracing Simulator (RTS) ******************
* Authors: Kate Williams (2013), Yaaseen Martin (2020)
* Contributing authors: Zhongliang Chen, Luis Tirado
* Utilises NVIDIA OptiX
* The RTS consists of the following files:
* ray_tracer.cuh (header file)
* ray_tracer.cpp (host code)
* ray_tracer.cu (OptiX kernel; context node programs)
* triangle_mesh.cu (OptiX kernel; geometry node programs)
* normal_shader.cu (OptiX kernel; material node programs)
* CMakeLists.txt (user-defined make lists)
************************************************************************************************* */
/* ****************** Host Code ******************
* Create a graph
* Context node
* Create a context
* Read in user inputs; create input/output buffers
* Set up context node programs: ray generation and miss
* Geometry node
* Create a geometry node
* Set up geometry node programs: bounding box and intersection
* Material node
* Create a material node
* Set up material node programs: closest hit
* Geometry instance node
* Create a geometry node
* Attach geometry and material nodes
* Geometry group node
* Create a geometry group node
* Attach geometry instance nodes
* Specify an acceleration structure
* Launch OptiX kernel
* Validate and compile
* Launch
* Launch ray aggregation kernel
* Save contents of PRD data (optional)
* Print timing stats to terminal
* Clean up and free resources
************************************************ */
#include <cmath>
#include "rsworld.cuh"
#include "rsradar.cuh"
#include "rstarget.cuh"
#include "rsplatform.cuh"
#include "rspath.cuh"
#include "rsgeometry.cuh"
#include "rsdebug.cuh"
#include "rsparameters.cuh"
#include "rsantenna.cuh"
#include "rsresponse.cuh"
#include "rsnoise.cuh"
#include "aggregation.cuh"
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <optix.h>
#include <sutil.h>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <set>
#include <initializer_list>
#include <limits>
#include <stdexcept>
using std::string;
using std::vector;
const char* const PROGRAM_NAME = "soars"; // Required for PTX processing to work correctly
/* Additional functions */
// Function to get mid-point between two vertices in "sphere"; calculate new vertex in sub-division and normalise it, then add it to the end of v
void getMidPoint(int t1, int t2, vector < vector < double > >& v)
{
// Calculate mid-point on unit sphere
vector < double > pm(3, 0); // Size of 3 with all elements set to zero
pm[0] = (v[t1][0] + v[t2][0])/2;
pm[1] = (v[t1][1] + v[t2][1])/2;
pm[2] = (v[t1][2] + v[t2][2])/2;
// Normalise the mid-point
double norm = sqrt(pm[0]*pm[0] + pm[1]*pm[1] + pm[2]*pm[2]);
pm[0] = pm[0]/norm;
pm[1] = pm[1]/norm;
pm[2] = pm[2]/norm;
// Add to vertices list
v.push_back(pm);
}
// Function to compute the area of a triangle from its three vertices
double triangle_area(vector < double > P1, vector < double > P2, vector < double > P3)
{
// Calculate side lengths
double L[3];
L[0] = sqrt((P1[0] - P2[0])*(P1[0] - P2[0]) + (P1[1] - P2[1])*(P1[1] - P2[1]) + (P1[2] - P2[2])*(P1[2] - P2[2]));
L[1] = sqrt((P2[0] - P3[0])*(P2[0] - P3[0]) + (P2[1] - P3[1])*(P2[1] - P3[1]) + (P2[2] - P3[2])*(P2[2] - P3[2]));
L[2] = sqrt((P3[0] - P1[0])*(P3[0] - P1[0]) + (P3[1] - P1[1])*(P3[1] - P1[1]) + (P3[2] - P1[2])*(P3[2] - P1[2]));
// Calculate area (Heron's formula)
double S = (L[0] + L[1] + L[2])/2;
double A = sqrt(S*(S - L[0])*(S - L[1])*(S - L[2]));
return A;
}
// Function to perform matrix multiplication
vector < vector < double > > matrix_multiply(vector < vector < double > > M1, vector < vector < double > > M2)
{
// Create output matrix
vector < vector < double > > M3(M1.size(), vector < double > (M2[0].size(), 0));
// Multiply M1 and M2
for (unsigned int i = 0; i < M1.size(); i++)
{
for (unsigned int j = 0; j < M2[0].size(); j++)
{
M3[i][j] = 0;
for (unsigned int k = 0; k < M2.size(); k++)
M3[i][j] += M1[i][k] * M2[k][j];
}
}
return M3;
}
// Function to transpose a matrix
vector < vector < double > > matrix_transpose(vector < vector < double > > M1)
{
// Create matrices
vector < vector < double > > M2(M1[0].size(), vector < double > (M1.size(), 0));
// Transpose M1 into M2
for (unsigned int i = 0; i < M1.size(); i++) {
for (unsigned int j = 0; j < M1[0].size(); j++)
M2[j][i] = M1[i][j];
}
return M2;
}
// Function to modify vertices due to rotational motion; can also be used to rotate vertex normals
// NOTE: All rotations occur ANTI-CLOCKWISE when looking DOWN the same axis
vector < vector < double > > vertex_rotation(vector < vector < double > > vertices, float yaw, float pitch, float roll)
{
// Form rotation matrix
vector < vector < double > > Rx = {{1, 0, 0}, {0, std::cos(roll), -std::sin(roll)}, {0, std::sin(roll), std::cos(roll)}};
vector < vector < double > > Ry = {{std::cos(pitch), 0, std::sin(pitch)}, {0, 1, 0}, {-std::sin(pitch), 0, std::cos(pitch)}};
vector < vector < double > > Rz = {{std::cos(yaw), -std::sin(yaw), 0}, {std::sin(yaw), std::cos(yaw), 0}, {0, 0, 1}};
vector < vector < double > > R_total = matrix_multiply(Rz, matrix_multiply(Ry, Rx));
// Get rotated vertices
// vertices[0][0] = 0.5; vertices[0][1] = 0; vertices[0][2] = 0;
vector < vector < double > > verts_rot = matrix_transpose(matrix_multiply(R_total, matrix_transpose(vertices)));
// printf("[%e, %e, %e];\n", verts_rot[0][0], verts_rot[0][1], verts_rot[0][2]);
return verts_rot;
}
// // Function to compute vertex normals for a "rect" mesh
// void get_vertex_normals(vector < vector < double > >& vertices, vector < vector < unsigned int > >& tris, vector < vector < double > >& vert_normals)
// {
// // Initialise zeros matrix to hold vertex normals of each vertex
// vert_normals.resize(vertices.size());
// for (unsigned int i = 0; i < vert_normals.size(); i++)
// vert_normals[i].resize(3);
// // Loop through each vertex
// for (unsigned int i = 0; i < vertices.size(); i++) {
// // Initialise/reset running total of face area of triangles sharing this vertex
// double total_area = 0;
// // Loop through triangle matrix rows
// for (unsigned int j = 0; j < tris.size(); j++) {
// // Loop through triangle matrix columns and find vertex indices
// for (unsigned int k = 0; k < tris[0].size(); k++) {
// // Check if vertex is used by current triangle
// if (i == tris[j][k]) {
// // Calculate the area of the current triangle using its three vertex points
// double tri_area = triangle_area(vertices[tris[j][0]], vertices[tris[j][1]], vertices[tris[j][2]]);
// // Add area-weighted row of face_mat to corresponding vert_normals row
// vert_normals[i][0] = vert_normals[i][0] + tri_area*face_mat[j][0];
// vert_normals[i][1] = vert_normals[i][1] + tri_area*face_mat[j][1];
// vert_normals[i][2] = vert_normals[i][2] + tri_area*face_mat[j][2];
// // Update running total of face area for this vertex
// total_area = total_area + tri_area;
// // Exit innermost loop
// break;
// }
// }
// }
// // Divide each row of vert_normals by total area of all triangles sharing vertex; weighted average
// vert_normals[i][0] = vert_normals[i][0]/total_area;
// vert_normals[i][1] = vert_normals[i][1]/total_area;
// vert_normals[i][2] = vert_normals[i][2]/total_area;
// // Normalise each row (vector) of vertex normal matrix
// double norm = sqrt(vert_normals[i][0]*vert_normals[i][0] + vert_normals[i][1]*vert_normals[i][1] + vert_normals[i][2]*vert_normals[i][2]);
// vert_normals[i][0] = vert_normals[i][0]/norm;
// vert_normals[i][1] = vert_normals[i][1]/norm;
// vert_normals[i][2] = vert_normals[i][2]/norm;
// }
// }
// Function to compute vertices and vertex normals for a "rect" mesh
void rect_mesh(float w, float h, float d, vector < vector < double > >& vertices, vector < vector < unsigned int > >& tris,
vector < vector < double > >& vert_normals, float yaw, float pitch, float roll)
{
// Set up vertices matrix for a 3-D cubic/rectangular mesh
vertices.resize(8);
for (unsigned int i = 0; i < vertices.size(); i++)
vertices[i].resize(3);
vertices[0][0] = w*+0.5f; vertices[0][1] = h*-0.5f; vertices[0][2] = d*-0.5f;
vertices[1][0] = w*+0.5f; vertices[1][1] = h*+0.5f; vertices[1][2] = d*-0.5f;
vertices[2][0] = w*+0.5f; vertices[2][1] = h*-0.5f; vertices[2][2] = d*+0.5f;
vertices[3][0] = w*+0.5f; vertices[3][1] = h*+0.5f; vertices[3][2] = d*+0.5f;
vertices[4][0] = w*-0.5f; vertices[4][1] = h*-0.5f; vertices[4][2] = d*-0.5f;
vertices[5][0] = w*-0.5f; vertices[5][1] = h*+0.5f; vertices[5][2] = d*-0.5f;
vertices[6][0] = w*-0.5f; vertices[6][1] = h*-0.5f; vertices[6][2] = d*+0.5f;
vertices[7][0] = w*-0.5f; vertices[7][1] = h*+0.5f; vertices[7][2] = d*+0.5f;
// Set up triangle face matrix
tris.resize(12);
for (unsigned int i = 0; i < tris.size(); i++)
tris[i].resize(3);
tris[0][0] = 0; tris[0][1] = 1; tris[0][2] = 2;
tris[1][0] = 1; tris[1][1] = 3; tris[1][2] = 2;
tris[2][0] = 2; tris[2][1] = 3; tris[2][2] = 7;
tris[3][0] = 2; tris[3][1] = 7; tris[3][2] = 6;
tris[4][0] = 1; tris[4][1] = 7; tris[4][2] = 3;
tris[5][0] = 1; tris[5][1] = 5; tris[5][2] = 7;
tris[6][0] = 6; tris[6][1] = 7; tris[6][2] = 4;
tris[7][0] = 7; tris[7][1] = 5; tris[7][2] = 4;
tris[8][0] = 0; tris[8][1] = 4; tris[8][2] = 1;
tris[9][0] = 1; tris[9][1] = 4; tris[9][2] = 5;
tris[10][0] = 2; tris[10][1] = 6; tris[10][2] = 4;
tris[11][0] = 0; tris[11][1] = 2; tris[11][2] = 4;
// Get rotated vertices
vertices = vertex_rotation(vertices, yaw, pitch, roll); // Rotation
// // Get vertex_normals
// get_vertex_normals(vertices, tris, vert_normals); // Invoke function to get vertex normals for "rect"
// Initialise zeros matrix to hold face normals of each triangle
vector < vector < double > > face_mat(tris.size(), vector < double > (3, 0));
// For loop to get face normal of each triangle and store in face_mat
for (unsigned int i = 0; i < face_mat.size(); i++) {
// Get vertices using triangle matrix and create vectors between points
double v1[3], v2[3];
v1[0] = vertices[tris[i][1]][0] - vertices[tris[i][0]][0]; // Vector from P1 to P2; x value
v1[1] = vertices[tris[i][1]][1] - vertices[tris[i][0]][1]; // Vector from P1 to P2; y value
v1[2] = vertices[tris[i][1]][2] - vertices[tris[i][0]][2]; // Vector from P1 to P2; z value
v2[0] = vertices[tris[i][2]][0] - vertices[tris[i][0]][0]; // Vector from P1 to P3; x value
v2[1] = vertices[tris[i][2]][1] - vertices[tris[i][0]][1]; // Vector from P1 to P3; y value
v2[2] = vertices[tris[i][2]][2] - vertices[tris[i][0]][2]; // Vector from P1 to P3; z value
// Cross product to get face normal and store in matrix
face_mat[i][0] = (v1[1]*v2[2] - v1[2]*v2[1]);
face_mat[i][1] = (v1[2]*v2[0] - v1[0]*v2[2]);
face_mat[i][2] = (v1[0]*v2[1] - v1[1]*v2[0]);
// Normalise each row (vector) of face normal matrix; don't need vertex normals for rect, so just use face normals as "vert_normals"
double norm = sqrt(face_mat[i][0]*face_mat[i][0] + face_mat[i][1]*face_mat[i][1] + face_mat[i][2]*face_mat[i][2]);
face_mat[i][0] = face_mat[i][0]/norm;
face_mat[i][1] = face_mat[i][1]/norm;
face_mat[i][2] = face_mat[i][2]/norm;
}
// Set vert_normals to the face normals for "rect"; don't need to account for curvature/interpolation
vert_normals = face_mat;
}
// Function to compute vertices and vertex normals for a "sphere" mesh
void sphere_mesh(unsigned int n, float radius, vector < vector < double > >& vertices, vector < vector < unsigned int > >& tris,
vector < vector < double > >& vert_normals, float yaw, float pitch, float roll, unsigned int& numTriangles)
{
// Regular unit icosahedron (12 vertices)
double t = (1 + sqrt(5)) / 2;
vector < vector < double > > v = {
{-1, t, 0},
{1, t, 0},
{-1, -t, 0},
{1, -t, 0},
{0, -1, t},
{0, 1, t},
{0, -1, -t},
{0, 1, -t},
{t, 0, -1},
{t, 0, 1},
{-t, 0, -1},
{-t, 0, 1}
};
// Normalise vertices to unit size
for (unsigned int i = 0; i < v.size(); i++) {
double norm = sqrt(v[i][0]*v[i][0] + v[i][1]*v[i][1] + v[i][2]*v[i][2]);
v[i][0] = v[i][0]/norm;
v[i][1] = v[i][1]/norm;
v[i][2] = v[i][2]/norm;
}
// Regular unit icosahedron (20 faces)
vector < vector < unsigned int > > f = {
{0, 11, 5},
{0, 5, 1},
{0, 1, 7},
{0, 7, 10},
{0, 10, 11},
{1, 5, 9},
{5, 11, 4},
{11, 10, 2},
{10, 7, 6},
{7, 1, 8},
{3, 9, 4},
{3, 4, 2},
{3, 2, 6},
{3, 6, 8},
{3, 8, 9},
{4, 9, 5},
{2, 4, 11},
{6, 2, 10},
{8, 6, 7},
{9, 8, 1}
};
// Recursively sub-divide triangle faces
for (unsigned int gen = 0; gen < n; gen++) {
vector < vector < unsigned int > > f_(f.size()*4, vector < unsigned int > (3, 0)); // Initialise and set all elements of f_ to zero
for (unsigned int i = 0; i < f.size(); i++) { // For each triangle
int tri[3];
tri[0] = f[i][0];
tri[1] = f[i][1];
tri[2] = f[i][2];
// Calculate mid-points and add new them to the end of v
int a = v.size();
getMidPoint(tri[0], tri[1], v);
int b = v.size();
getMidPoint(tri[1], tri[2], v);
int c = v.size();
getMidPoint(tri[2], tri[0], v);
// Generate new subdivision triangles
int nfc[4][3] = {
{tri[0], a, c},
{tri[1], b, a},
{tri[2], c, b},
{a, b, c}
};
// Replace triangle with sub-division
for (unsigned int j = 0; j < 4; j++) {
int idx = (4*i) + j;
f_[idx][0] = nfc[j][0];
f_[idx][1] = nfc[j][1];
f_[idx][2] = nfc[j][2];
}
}
// Update face matrix
f = f_;
}
// "Return" number of triangles used in the mesh
numTriangles = f.size();
// Remove duplicate vertices
std::set < vector < double > > v_unique(v.begin(), v.end());
vector < int > ix;
transform(v.begin(), v.end(),
back_inserter(ix), [&](vector < double > x) {
return std::distance(v_unique.begin(), find(v_unique.begin(), v_unique.end(), x));
});
vector < vector < double > > verts(v_unique.begin(), v_unique.end());
// Set the (unit vector) vertices after applying rotations
vertices = vertex_rotation(verts, yaw, pitch, roll); // Rotation of vertices
// Save normals matrix for this target; for a sphere centred at the origin, vertex normals are the same as the (unit vector) vertices
vert_normals = vertices;
// Reassign faces to trimmed vertex list and remove any duplicate faces
for (unsigned int i = 0; i < f.size(); i++) {
f[i][0] = ix[f[i][0]];
f[i][1] = ix[f[i][1]];
f[i][2] = ix[f[i][2]];
}
std::set < vector < unsigned int > > f_unique( f.begin(), f.end() );
tris.assign( f_unique.begin(), f_unique.end() );
// Resize the sphere vertices based on its radius; this does NOT affect the vertex normals, which should be unit vectors
for (unsigned int i = 0; i < vertices.size(); i++) {
vertices[i][0] *= radius;
vertices[i][1] *= radius;
vertices[i][2] *= radius;
}
}
// Function to compute vertices and vertex normals for a "file" mesh
void file_mesh(string v_file, string n_file, vector < vector < double > >& vertices, vector < vector < unsigned int > >& tris,
vector < vector < double > >& vert_normals, float yaw, float pitch, float roll)
{
// Open first file and get number of lines
std::ifstream inFile(v_file);
unsigned int h_numberTriangles = std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n'); // Number of lines in file
// Resize matrices for the two files
vertices.resize(h_numberTriangles*3);
vert_normals.resize(h_numberTriangles*3);
for (unsigned int i = 0; i < vertices.size(); i++)
vertices[i].resize(3);
for (unsigned int i = 0; i < vert_normals.size(); i++)
vert_normals[i].resize(3);
// Set tris matrix
tris.resize(h_numberTriangles);
for (unsigned int i = 0; i < tris.size(); i++) {
tris[i].resize(3);
tris[i][0] = i*3 + 0;
tris[i][1] = i*3 + 1;
tris[i][2] = i*3 + 2;
}
// Populate vector for triangle vertex coordinates
FILE* fp = fopen(v_file.c_str(), "r");
if (fp == NULL) {
printf("Ray tracer error: Cannot open vertex coordinates file!\n"); // Error checker
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < h_numberTriangles; i++) { // Open file and scan contents
if (fscanf(fp, "%lf %lf %lf, %lf %lf %lf, %lf %lf %lf,\n", \
&vertices[3*i][0], \
&vertices[3*i][1], \
&vertices[3*i][2], \
&vertices[3*i+1][0], \
&vertices[3*i+1][1], \
&vertices[3*i+1][2], \
&vertices[3*i+2][0], \
&vertices[3*i+2][1], \
&vertices[3*i+2][2]) == EOF)
exit(EXIT_FAILURE);
}
fclose(fp); // Close file
// Get rotated vertices
vertices = vertex_rotation(vertices, yaw, pitch, roll); // Rotation
// Populate vector for triangle vertex normals
fp = fopen(n_file.c_str(), "r");
if (fp == NULL) {
printf("Ray tracer error: Cannot open vertex normals file!\n"); // Error checker
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < h_numberTriangles; i++) { // Open file and scan contents
if (fscanf(fp, "%lf %lf %lf, %lf %lf %lf, %lf %lf %lf,\n", \
&vert_normals[3*i][0], \
&vert_normals[3*i][1], \
&vert_normals[3*i][2], \
&vert_normals[3*i+1][0], \
&vert_normals[3*i+1][1], \
&vert_normals[3*i+1][2], \
&vert_normals[3*i+2][0], \
&vert_normals[3*i+2][1], \
&vert_normals[3*i+2][2]) == EOF)
exit(EXIT_FAILURE);
}
fclose(fp); // Close file
// Get rotated vertex normals; function works for a file mesh's vertex normals too
// Basically rotating unit vector normals w.r.t. origin
// Almost like translating, rotating, then translating back; but "new point" does not matter; the VECTOR DIFFERENCE does
vert_normals = vertex_rotation(vert_normals, yaw, pitch, roll); // Rotation
}
/* Main RTS function */
namespace rs {
// Define function RTS for ray-tracing implementation; initially declared in rsworld.cuh
void RTS(World *world, unsigned int MaxThreads, unsigned int MaxBlocks)
{
// Timer for RTS set-up runtime
struct timeval timer1, timer2, timer3;
gettimeofday(&timer1, NULL);
double StartTime_PP;
double StartTime_RTS = timer1.tv_sec + (timer1.tv_usec/1000000.0);
// Indicate RTS start
printf("Setting up RTS...\n");
/* *************** CONTEXT SETUP *************** */
/* Declare context object and program objects */
RTcontext context; // Name of context node
RTprogram rtprog_ray_generation; // Name of ray generation program
RTprogram rtprog_miss; // Name of miss program
// RTprogram rtprog_exception; // Name of exception program
/* Create context */
RT_CHECK_ERROR( rtContextCreate( &context ) );
RT_CHECK_ERROR( rtContextSetRayTypeCount( context, 1 ) );
RT_CHECK_ERROR( rtContextSetEntryPointCount( context, 1 ) );
// /* Enable printing for debugging */
// RT_CHECK_ERROR( rtContextSetPrintEnabled( context, 1) );
// RT_CHECK_ERROR( rtContextSetPrintBufferSize( context, 1024*1024) );
// int temp1 = 1; int temp2 = 1; int temp3 = 0; // Choose thread to print from
// rtContextSetPrintLaunchIndex(context, temp1,temp2, temp3);
/* Declare host and program variables, including user inputs. Host variable name (left), device variable name (right) */
// Variables for OptiX programs
RTvariable rtvar_width; // Number of rays; width/height/depth of virtual screen
RTvariable rtvar_maxReflDepth; // Number of allowed ray reflections
RTvariable rtvar_maxRefrDepth; // Number of allowed ray refractions
RTvariable rtvar_maxRayTotal; // Maximum possible number of rays in total (refracted and reflected)
RTvariable rtvar_rxsize; // Number of receivers
RTvariable rtvar_interpolate_smooth; // Boolean for enabling interpolation of vertex normals
RTvariable rtvar_rayOrigin; // Coordinates of point source location
RTvariable rtvar_txSpan; // Tx boresight spans and launch range
RTvariable rtvar_txDir; // Tx boresight direction
// Set up receiver buffers
RTbuffer rtbuf_sphCentre; // Name of buffer that will contain sphCentre
double3* hbuf_sphCentre; RTvariable rtvar_sphCentre; // Variables for sphCentre buffer
RTbuffer rtbuf_sphRadius; // Name of buffer that will contain sphRadius
double* hbuf_sphRadius; RTvariable rtvar_sphRadius; // Variables for sphRadius buffer
RTbuffer rtbuf_minTheta; // Name of buffer that will contain minTheta
double* hbuf_minTheta; RTvariable rtvar_minTheta; // Variables for minTheta buffer
RTbuffer rtbuf_maxTheta; // Name of buffer that will contain maxTheta
double* hbuf_maxTheta; RTvariable rtvar_maxTheta; // Variables for maxTheta buffer
RTbuffer rtbuf_minPhi; // Name of buffer that will contain minPhi
double* hbuf_minPhi; RTvariable rtvar_minPhi; // Variables for minPhi buffer
RTbuffer rtbuf_maxPhi; // Name of buffer that will contain maxPhi
double* hbuf_maxPhi; RTvariable rtvar_maxPhi; // Variables for maxPhi buffer
// Other buffers
RTbuffer rtbuf_triangles; // Name of buffer that will contain triangles
uint3* hbuf_triangles; RTvariable rtvar_triangles; // Variables for triangles buffer
RTbuffer rtbuf_triVertices; // Name of buffer that will contain triangle vertices
double3* hbuf_triVertices; RTvariable rtvar_triVertices; // Variables for verts buffer
RTbuffer rtbuf_normals; // Name of buffer that will contain vertex normals
double3* hbuf_normals; RTvariable rtvar_normals; // Variables for normals buffer
RTbuffer rtbuf_results; // Name of buffer that will contain OptiX output results
PerRayData* hbuf_results; RTvariable rtvar_results; // Variables for output results buffer
RTbuffer rtbuf_targ_intersect; // Name of buffer that will contain OptiX output intersections
int* hbuf_targ_intersect; RTvariable rtvar_targ_intersect; // Variables for output intersections buffer
RTbuffer rtbuf_rcs_angle; // Name of buffer that will contain RCS tAngle values
double2* hbuf_rcs_angle; RTvariable rtvar_rcs_angle; // Variables for output RCS angles buffer (azi and ele)
RTbuffer rtbuf_targ_vel; // Name of buffer to hold target positions
double3* hbuf_targ_vel; RTvariable rtvar_targ_vel; // Variables for target positions array
// Set up ray count and reflection/refraction depths
uint3 rts_vars = rsParameters::GetRTSVariables();
unsigned int h_numRays = rts_vars.x; // Number of rays spawned in each dimension (x, y, z) for each target
unsigned int h_maxReflDepth = rts_vars.y; // Maximum number of reflections; user input (max. desired reflections per ray)
unsigned int h_maxRefrDepth = rts_vars.z; // Maximum number of refractions
if (h_maxRefrDepth > 0) // Maximum of 2; avoids unnecessary memory usage from a large number of "negligible" refractions
h_maxRefrDepth = 2; // 1 refraction is pointless as the refracted ray would remain "trapped" within target
// Compute the total number of possible rays (including refractions)
unsigned int rayTotal = 1; // Default is 1 (no refractions)
if (h_maxRefrDepth == 2){ // If there are refractions
// Possible refractions in each "first-hit object"
rayTotal += (h_maxReflDepth + 1) + 1; // Add extra +1 due to ray that becomes "trapped" inside object
// // Iterate through reflections at the "objects" and account for possible follow-up refractions from the initial refracted ray
// for (unsigned int i = 0; i <= h_maxReflDepth; i++){
// // E.g. For 5 reflections, could have an additional 6 + 5 + 4 + 3 + 2 + 1 = 21 refractions
// // Due to refractions caused at the "object" interface by reflections of the initial refracted ray INSIDE the "object"
// // i.e. Even after final reflection is reached, the ray can hit another object and refract (but not reflect)
// // Reflection can also occurs at a possible final object that is intersected when max reflection depth is reached
// rayTotal += (h_maxReflDepth + 1 - i);
// }
}
// Account for total number of rays being transmitted
rayTotal *= h_numRays*h_numRays*h_numRays;
/* Create output buffer */
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_results", &rtvar_results ) ); // Create device variable dbuf_results
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_OUTPUT, &rtbuf_results ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_results, RT_FORMAT_USER ) );
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_results, sizeof(PerRayData) ) ); // Set size of buffer
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_results, rayTotal ) ); // Need to account for possible refracted rays
RT_CHECK_ERROR( rtVariableSetObject( rtvar_results, rtbuf_results ) ); // Associate contents
/* Initial set-up */
// Array and parameter set-up
unsigned int txsize = (world->transmitters).size(); // Number of transmitters
unsigned int rxsize = (world->receivers).size(); // Number of receivers
unsigned int targsize = (world->targets).size(); // Number of targets
Transmitter** trans_arr = (world->transmitters).data(); // Transmitters array
Receiver** recv_arr = (world->receivers).data(); // Receivers array
Target** targ_arr = (world->targets).data(); // Targets array
double cspeed = rsParameters::c(); // Speed of propagation
double sim_starttime = rsParameters::start_time(); // Start time of the simulation
double sample_time = 1.0 / rsParameters::cw_sample_rate(); // Default CW sample rate is 1 kHz
bool h_interpolate_smooth = rsParameters::interpolate_smooth(); // Boolean to enable interpolation of vertex normals
/// Create and fill buffer tracking the paths of all rays
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_targ_intersect", &rtvar_targ_intersect ) ); // Create device variable dbuf_targ_intersect
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT_OUTPUT, &rtbuf_targ_intersect ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_targ_intersect, RT_FORMAT_INT ) ); // Set buffer to hold ints
RT_CHECK_ERROR( rtBufferSetSize2D( rtbuf_targ_intersect, (h_maxRefrDepth + h_maxReflDepth), rayTotal ) ); // Set width, height of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_targ_intersect, rtbuf_targ_intersect ) ); // Associate contents
/// Create and fill buffer tracking the RCS angles of all rays
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_rcs_angle", &rtvar_rcs_angle ) ); // Create device variable dbuf_rcs_angle
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT_OUTPUT, &rtbuf_rcs_angle ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_rcs_angle, RT_FORMAT_USER ) );
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_rcs_angle, sizeof(double2) ) ); // Set size of buffer
RT_CHECK_ERROR( rtBufferSetSize2D( rtbuf_rcs_angle, (h_maxRefrDepth + h_maxReflDepth), rayTotal ) ); // Set width, height of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_rcs_angle, rtbuf_rcs_angle ) ); // Associate contents
/// Define receiver buffers
// sphCentre
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_sphCentre", &rtvar_sphCentre ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_sphCentre ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_sphCentre, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_sphCentre, sizeof(double3) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_sphCentre, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_sphCentre, rtbuf_sphCentre ) ); // Associate contents
// sphRadius
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_sphRadius", &rtvar_sphRadius ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_sphRadius ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_sphRadius, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_sphRadius, sizeof(double) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_sphRadius, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_sphRadius, rtbuf_sphRadius ) ); // Associate contents
// minTheta
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_minTheta", &rtvar_minTheta ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_minTheta ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_minTheta, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_minTheta, sizeof(double) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_minTheta, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_minTheta, rtbuf_minTheta ) ); // Associate contents
// maxTheta
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_maxTheta", &rtvar_maxTheta ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_maxTheta ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_maxTheta, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_maxTheta, sizeof(double) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_maxTheta, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_maxTheta, rtbuf_maxTheta ) ); // Associate contents
// minPhi
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_minPhi", &rtvar_minPhi ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_minPhi ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_minPhi, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_minPhi, sizeof(double) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_minPhi, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_minPhi, rtbuf_minPhi ) ); // Associate contents
// maxPhi
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_maxPhi", &rtvar_maxPhi ) ); // Declare device variable
RT_CHECK_ERROR( rtBufferCreate( context, RT_BUFFER_INPUT, &rtbuf_maxPhi ) ); // Create buffer
RT_CHECK_ERROR( rtBufferSetFormat( rtbuf_maxPhi, RT_FORMAT_USER ) ); // Set buffer to hold double3s
RT_CHECK_ERROR( rtBufferSetElementSize( rtbuf_maxPhi, sizeof(double) ) ); // Use element size of double3
RT_CHECK_ERROR( rtBufferSetSize1D( rtbuf_maxPhi, rxsize ) ); // Set size of buffer
RT_CHECK_ERROR( rtVariableSetObject( rtvar_maxPhi, rtbuf_maxPhi ) ); // Associate contents
/* Set PTX filename for context node programs */
const char *ptx = sutil::getPtxString( PROGRAM_NAME, "ray_tracer.cu" );
/* Ray generation program setup*/
RT_CHECK_ERROR( rtProgramCreateFromPTXString( context, ptx, "ray_generation", &rtprog_ray_generation ) );
RT_CHECK_ERROR( rtContextSetRayGenerationProgram( context, 0, rtprog_ray_generation ) );
// Declare device variables for the ray generation program
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_width", &rtvar_width ) );
RT_CHECK_ERROR( rtVariableSet1ui( rtvar_width, h_numRays ) );
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_maxRayTotal", &rtvar_maxRayTotal ) );
RT_CHECK_ERROR( rtVariableSet1ui( rtvar_maxRayTotal, rayTotal ) );
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_rayOrigin", &rtvar_rayOrigin ) ); // Value set later; changes over time
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_txSpan", &rtvar_txSpan ) ); // Value set later; changes over time
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_txDir", &rtvar_txDir ) ); // Value set later; changes over time
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_rxsize", &rtvar_rxsize ) );
RT_CHECK_ERROR( rtVariableSet1ui( rtvar_rxsize, rxsize ) );
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_interpolate_smooth", &rtvar_interpolate_smooth ) );
RT_CHECK_ERROR( rtVariableSetUserData(rtvar_interpolate_smooth, sizeof(bool), &h_interpolate_smooth) );
/* Miss program setup */
RT_CHECK_ERROR( rtProgramCreateFromPTXString( context, ptx, "miss", &rtprog_miss ) );
RT_CHECK_ERROR( rtContextSetMissProgram( context, 0, rtprog_miss ) );
// /* Exception program setup */
// RT_CHECK_ERROR( rtProgramCreateFromPTXString( context, ptx, "exception", &rtprog_exception ) );
// RT_CHECK_ERROR( rtContextSetExceptionProgram( context, 0, rtprog_exception ) );
/* *************** GEOMETRY NODE SETUP *************** */
/* Declare geometry node objects */
RTgeometry rtnode_geometry; // Name of geometry node
RTprogram rtprog_intersect; // Name of intersection program
RTprogram rtprog_bound; // Name of bounding box program
/* Set PTX filename for geometry node programs */
const char *ptx_triangle_mesh = sutil::getPtxString( PROGRAM_NAME, "triangle_mesh.cu" );
/* *************** MATERIAL NODE SETUP *************** */
/* Declare material node objects */
RTmaterial rtnode_material;
RTprogram rtprog_closest_hit;
/* Create material node */
RT_CHECK_ERROR( rtMaterialCreate( context, &rtnode_material ) );
/* Set PTX filename for material node programs */
const char *ptx_normal_shader = sutil::getPtxString( PROGRAM_NAME, "normal_shader.cu" );
/* Closest hit program setup */
RT_CHECK_ERROR( rtProgramCreateFromPTXString( context, ptx_normal_shader, "closest_hit", &rtprog_closest_hit) );
RT_CHECK_ERROR( rtMaterialSetClosestHitProgram( rtnode_material, 0, rtprog_closest_hit ) );
// Declare device variables for the closest hit program
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_maxReflDepth", &rtvar_maxReflDepth ) );
RT_CHECK_ERROR( rtVariableSet1ui( rtvar_maxReflDepth, (h_maxReflDepth + 1) ) ); // reflDepth + 1 = "stop index"; max. reflections per ray = (d_maxReflDepth - 1)
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_maxRefrDepth", &rtvar_maxRefrDepth ) );
RT_CHECK_ERROR( rtVariableSet1ui( rtvar_maxRefrDepth, h_maxRefrDepth ) );
/* *************** GEOMETRY INSTANCE NODE SETUP *************** */
/* Declare geometry group node objects */
RTgeometrygroup rtnode_geoGroup; // Name of geometry group
RTacceleration rtnode_geoGroupAcc; // Name of acceleration
RTvariable rtvar_targ_index; // Target index
RTvariable rtvar_targReflCoeff; // Reflection coefficient
RTvariable rtvar_targRefrIndex; // Refractive index
RTvariable rtvar_targets_all;
/* Declare geometry instance node objects */
RTgeometryinstance rtnode_geoInst; // Name of geometry instance
/* Create geometry group node */
RT_CHECK_ERROR( rtGeometryGroupCreate( context, &rtnode_geoGroup ) );
RT_CHECK_ERROR( rtGeometryGroupSetChildCount( rtnode_geoGroup, targsize ) );
// Declare context variables for all targets
RT_CHECK_ERROR( rtContextDeclareVariable( context, "dbuf_targ_vel", &rtvar_targ_vel ) );
RT_CHECK_ERROR( rtContextDeclareVariable( context, "d_targets_all", &rtvar_targets_all ) );
/* *************** START OF TRANSMITTER LOOP *************** */
// Iterate through all transmitters
for (unsigned int tx_i = 0; tx_i < txsize; tx_i++){
// Transmitter and signal set-up
Transmitter* trans = trans_arr[tx_i]; // Each transmitter in the loop
unsigned int pulseCount = trans->GetPulseCount(); // Number of pulses to transmit
TransmitterPulse* signal = new TransmitterPulse(); // Create new signal
trans->GetPulse(signal, 0); // Define pulse signal
RadarSignal *wave = signal->wave; // Pulse wave
double carrier = wave->GetCarrier(); // Carrier frequency
double Wl = cspeed/carrier; // Wavelength
double3 h_rayOrigin; // Initialise transmitter coordinates
double2 h_txDir; // Initialise transmitter boresight direction
double3 h_txSpan = trans->GetTxSpan(); // Boresight spans and launch range
RT_CHECK_ERROR( rtVariableSetUserData(rtvar_txSpan, sizeof(double3), &h_txSpan) );
// Time set-up
vector < double > start_time_arr(pulseCount); // start_time vector varying with pulse number
/// Assign receiver buffer values; these values do NOT change over time, so no need to repeat these later in the time-step loops
RT_CHECK_ERROR( rtBufferMap(rtbuf_sphRadius, (void **)&hbuf_sphRadius) ); // Map sphRadius buffer
for (unsigned j = 0; j < rxsize; j++) {
// Set overall noise temperature for receiver (antenna + external noise); recorded later into responses
recv_arr[j]->SetNoiseTemperature(wave->GetTemp() + recv_arr[j]->GetNoiseTemperature());
// Get radius and theta and phi spans
double3 rxsphere = recv_arr[j]->GetRxSphere(); // x = radius; y = thetaSpan; z = phiSpan
hbuf_sphRadius[j] = rxsphere.x;
}
// Unmap receiver buffers
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_sphRadius) ); // Unmap buffer
/* *************** START OF TIME-STEP (PULSES) LOOP *************** */
// Iterate through all pulses
for (unsigned int k = 0; k < pulseCount; k++)
{
// Pulse start time
trans->GetPulse(signal, k); // Pulse signal
start_time_arr[k] = signal->time;
// Set up time variables
double time_t = start_time_arr[k]; // Time at the start of the sample
vector < unsigned int > numUniquePaths; // Number of unique paths for each Pulse
// Map target intersect (ray path) buffer; buffer mapped to 1-D array with ALL elements
RT_CHECK_ERROR( rtBufferMap(rtbuf_targ_intersect, (void **)&hbuf_targ_intersect) );
for (unsigned int i = 0; i < rayTotal*(h_maxRefrDepth + h_maxReflDepth); i++) {
hbuf_targ_intersect[i] = -1;
}
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_targ_intersect) ); // Unmap buffer
// Map RCS angles buffer; buffer mapped to 1-D array with ALL elements
RT_CHECK_ERROR( rtBufferMap(rtbuf_rcs_angle, (void **)&hbuf_rcs_angle) );
for (unsigned int i = 0; i < rayTotal*(h_maxRefrDepth + h_maxReflDepth); i++) {
// Use default angle of -1000000 (rad) so that it can be checked later
hbuf_rcs_angle[i].x = -1000000; // Uses a half angle approximation; stored as t_angle = inAngle + outAngle (azi)
hbuf_rcs_angle[i].y = -1000000; // Uses a half angle approximation; stored as t_angle = inAngle + outAngle (ele)
}
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_rcs_angle) ); // Unmap buffer
/// Map receiver buffers
RT_CHECK_ERROR( rtBufferMap(rtbuf_sphCentre, (void **)&hbuf_sphCentre) ); // Map buffer
RT_CHECK_ERROR( rtBufferMap(rtbuf_minTheta, (void **)&hbuf_minTheta) ); // Map buffer
RT_CHECK_ERROR( rtBufferMap(rtbuf_maxTheta, (void **)&hbuf_maxTheta) ); // Map buffer
RT_CHECK_ERROR( rtBufferMap(rtbuf_minPhi, (void **)&hbuf_minPhi) ); // Map buffer
RT_CHECK_ERROR( rtBufferMap(rtbuf_maxPhi, (void **)&hbuf_maxPhi) ); // Map buffer
/// Assign time-varying transmitter values
// Set up Tx (ray source) coordinates
Vec3 trpos = trans->GetPosition(0); // Tx position does not change with time
h_rayOrigin.x = trpos.x; // Actual Tx coordinates
h_rayOrigin.y = trpos.y;
h_rayOrigin.z = trpos.z;
RT_CHECK_ERROR( rtVariableSetUserData(rtvar_rayOrigin, sizeof(double3), &h_rayOrigin) );
// Set up initial Tx boresight and beamwidth; used to direct the spawned rays
h_txDir.x = (trans->GetRotation(time_t)).azimuth;
h_txDir.y = (trans->GetRotation(time_t)).elevation;
RT_CHECK_ERROR( rtVariableSetUserData(rtvar_txDir, sizeof(double2), &h_txDir) );
/// Assign receiver buffer values; these values change over time
for (unsigned j = 0; j < rxsize; j++) {
// Get spherical coordinates of sphere centre relative to Rx coordinates as the origin
double h_Rx_azimuth = recv_arr[j]->GetRotation(time_t).azimuth; // Rx boresight azimuth (restricted between -Pi and Pi)
double h_Rx_elevation = recv_arr[j]->GetRotation(time_t).elevation; // Rx boresight elevation (restricted between -Pi/2 and Pi/2)
// Get Cartesian coordinates of Rx sphere centre from its spherical coordinates; rho is the sphere radius
double3 rxsphere = recv_arr[j]->GetRxSphere(); // x = radius; y = thetaSpan; z = phiSpan
Vec3 repos = recv_arr[j]->GetPosition(0); // Rx position does not change with time
hbuf_sphCentre[j].x = repos.x + (rxsphere.x * cosf(h_Rx_elevation) * cosf(h_Rx_azimuth)); // Compute x-coordinate of sphere centre; add to Rx position
hbuf_sphCentre[j].y = repos.y + (rxsphere.x * cosf(h_Rx_elevation) * sinf(h_Rx_azimuth)); // Compute y-coordinate of sphere centre; add to Rx position
hbuf_sphCentre[j].z = repos.z + (rxsphere.x * sinf(h_Rx_elevation)); // Compute z-coordinate of sphere centre; add to Rx position
// Get Rx position in spherical coordinates RELATIVE to the sphere centre as the origin; elevation always between -Pi/2 and Pi/2 since "r" uses +sqrt(...)
h_Rx_azimuth = atan2f((repos.y - hbuf_sphCentre[j].y), (repos.x - hbuf_sphCentre[j].x));
h_Rx_elevation = atan2f((repos.z - hbuf_sphCentre[j].z), sqrt((repos.x - hbuf_sphCentre[j].x)*(repos.x - hbuf_sphCentre[j].x) + \
(repos.y - hbuf_sphCentre[j].y)*(repos.y - hbuf_sphCentre[j].y)));
// Get min and max theta and phi
hbuf_minTheta[j] = h_Rx_azimuth - rxsphere.y/2;
hbuf_maxTheta[j] = h_Rx_azimuth + rxsphere.y/2;
hbuf_minPhi[j] = h_Rx_elevation - rxsphere.z/2;
hbuf_maxPhi[j] = h_Rx_elevation + rxsphere.z/2;
}
// Unmap receiver buffers
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_sphCentre) ); // Unmap buffer
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_minTheta) ); // Unmap buffer
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_maxTheta) ); // Unmap buffer
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_minPhi) ); // Unmap buffer
RT_CHECK_ERROR( rtBufferUnmap(rtbuf_maxPhi) ); // Unmap buffer
/* *************** START OF TARGETS LOOP *************** */
// Set up target position vectors
vector < double3 > targ_positions(targsize); // Target positions array
vector < double3 > targ_positions_end(targsize); // Target positions array, one sample later
// Iterate through all targets
for (unsigned int targ_i = 0; targ_i < targsize; targ_i++) {
// Populate target intersect buffer
// Get and save target centre positions
targ_positions[targ_i].x = targ_arr[targ_i]->GetPosition(time_t).x;
targ_positions[targ_i].y = targ_arr[targ_i]->GetPosition(time_t).y;
targ_positions[targ_i].z = targ_arr[targ_i]->GetPosition(time_t).z;
// Get and save "next" target centre positions (one sample later); used for Doppler calculation
targ_positions_end[targ_i].x = targ_arr[targ_i]->GetPosition(time_t + sample_time).x;
targ_positions_end[targ_i].y = targ_arr[targ_i]->GetPosition(time_t + sample_time).y;
targ_positions_end[targ_i].z = targ_arr[targ_i]->GetPosition(time_t + sample_time).z;
// Create target vertex matrices
vector < vector < unsigned int > > tris; // Target's triangles matrix
vector < vector < double > > verts; // Target's vertices matrix
vector < vector < double > > vert_normals; // Target's vertex normals matrix
// Get the initial rotation/orientation of the target (i.e. at time t = 0)
float yaw = (targ_arr[targ_i]->GetTargetRotation(0)).yaw;
float pitch = (targ_arr[targ_i]->GetTargetRotation(0)).pitch;
float roll = (targ_arr[targ_i]->GetTargetRotation(0)).roll;
/* Apply target shape */
// Get target's shape parameters; gets tris, vertices and vert_normals for time t = 0 */
string targShape = (targ_arr[targ_i])->GetShape(); // Shape of target mesh; "rect", "sphere", or "file"
// For cubic/rectangular mesh object
if (targShape == "rect") { // Set width, height and depth of "rect" object
float w, h, d;
(targ_arr[targ_i])->GetRect(w, h, d);
rect_mesh(w, h, d, verts, tris, vert_normals, yaw, pitch, roll); // Get vertex normals and apply rotation at time t = 0
}
// For spherical mesh object
else if (targShape == "sphere") {
unsigned int subdivs; // Number of subdivisions for "sphere" object
float radius; // Sphere radius
(targ_arr[targ_i])->GetSphere(subdivs, radius); // Modify subdivs and radius
unsigned int numTriangles; // Number of triangles in this "sphere" mesh
sphere_mesh(subdivs, radius, verts, tris, vert_normals, \
yaw, pitch, roll, numTriangles); // Get vertex normals and apply rotation at time t = 0
}
// User-defined file mesh
else if (targShape == "file") {
string v_file, n_file;
(targ_arr[targ_i])->GetFile(v_file, n_file); // Gets mesh's half-span
file_mesh(v_file, n_file, verts, tris, vert_normals, yaw, pitch, roll); // Get vertex normals and apply rotation at time t = 0
}
/* Now have tris, verts and vert_normals for current target; unchanging UNLESS there are time-varying target rotations; apply them now */
// Check if there are time-varying rotations for the current target
if (targ_arr[targ_i]->GetRotating() == true) {
// Create backups of the target vertex matrices; used to "reset" rotations performed
vector < vector < double > > verts_backup = verts; // Backup of target's vertices matrix
vector < vector < double > > vert_normals_backup = vert_normals; // Backup of target's vertex normals matrix
// Rotation at t = 0 has already been processed, so only process rotations for time > (simulation start time)
if ((targ_arr[targ_i]->GetRotating() == true) && (time_t > sim_starttime)) {