-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphicsclass.cpp
1997 lines (1657 loc) · 66.2 KB
/
Graphicsclass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
// Filename: graphicsclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "graphicsclass.h"
GraphicsClass::GraphicsClass()
{
scenario = 0;
m_Direct3D = 0;
m_Camera = 0;
m_Model = 0;
m_Model2 = 0;
m_Wire = 0;
m_ColorShader = 0;
m_Light = 0;
m_Bitmap = 0;
m_wireoffset = XMMatrixTranslation(0.0f, 0.0f, 0.0f);
m_offset = XMMatrixTranslation(-103.0f, 121.0f, 1208.0f); //translation to bring ct coordinates to world coordinates (in line with marker position)
//m_offset = XMMatrixTranslation(-95.0f, 132.0f, 1223.0f); //translation to bring ct coordinates to world coordinates (in line with marker position)
//m_offset = XMMatrixTranslation(153, 312, 1295);
m_textClass = 0;
m_fontClass = 0;
m_ct_org = XMLoadFloat3(&XMFLOAT3(-153.7f, -311.7f, 1294.f)); //origin of ct scan
m_ct_markerloc = XMLoadFloat3(&XMFLOAT3(95.f, 132.f, -1233.f)); //position of marker origin in ct coordinates
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd, ScenarioFileClass* sc)
{
m_show_model = false;
#ifdef II_SHOW_FEMUR
m_show_model = true;
#endif
scenario = sc;
m_offset = XMMatrixTranslationFromVector(XMLoadFloat3(&sc->get_modeloffset()));
bool result;
m_screenwidth = (float)screenWidth;
m_screenheight = (float)screenHeight;
// Create the Direct3D object.
m_Direct3D = new D3DClass;
if (!m_Direct3D)
{
return false;
}
// Initialize the Direct3D object.
result = m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
if (!result)
{
MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK);
return false;
}
// Create the camera object.
m_Camera = new CameraClass;
if (!m_Camera)
{
return false;
}
// Set the initial position of the camera.
m_Camera->SetPosition(0.0f, 0.0f, 0.0f);
// Create the model object.
m_Model = new ModelClass;
if (!m_Model)
{
return false;
}
// Initialize the model object.
result = m_Model->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_FEMUR, scenario->get_modelpath());
if (!result)
{
MessageBox(hwnd, L"Could not initialize the model femur object.", L"Error", MB_OK);
return false;
}
//a second model
m_Model2 = new ModelClass;
if (!m_Model2)
{
return false;
}
result = m_Model2->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_WIRE,"");
if (!result)
{
MessageBox(hwnd, L"Could not initialize the marker object.", L"Error", MB_OK);
return false;
}
m_Wire = new ModelClass;
result = m_Wire->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_WIRE,"");
if (!result)
{
MessageBox(hwnd, L"Could not initialize the guidewire object.", L"Error", MB_OK);
return false;
}
m_Screw = new ModelClass;
result = m_Screw->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_SCREW, "");
m_Cannulated = new ModelClass;
result = m_Cannulated->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_CANNULATEDSCREW, "");
//debug - load a sphere
m_Sphere = new ModelClass;
result = m_Sphere->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), MODEL_SPHERE,"");
//load a geometry class to handle primitives
m_Geometry = new GeometryClass;
m_Geometry->Initialise(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext());
/*
int error = 3.f;
//build a vector of points rotated around origin, pointing in dir
XMFLOAT3 origin = {50, -25, 400 };
XMFLOAT3 dir = {1.f, 0.f,-1.f };
XMStoreFloat3(&dir, XMVector3Normalize(XMLoadFloat3(&dir)));
float radius = 150;
vector<XMFLOAT3> points;
m_Geometry->AddSphere(origin, 0.05f, COLOUR_CYAN);
m_Geometry->AddLine(origin, { (dir.x * 50) + origin.x, (dir.y * 50) + origin.y, (dir.z * 50) + origin.z }, COLOUR_CYAN);
{
XMVECTOR up = XMVectorSet(0.f, 1.f, 0.f, 0.f);
XMVECTOR org = XMVectorSet(0.f, 0.f, 0.f, 0.f);
XMVECTOR out = XMLoadFloat3(&dir);
XMMATRIX r = XMMatrixTranspose(XMMatrixLookAtLH(org, out, up));
XMMATRIX trans;
srand(time(NULL));
//add points around origin
for (float angle = -30; angle < 30; angle += 1)
{
//XMFLOAT3 pnt = { 0, radius, 0 };
float rad = 3.14159f / 180.f * angle;
trans = XMMatrixRotationZ(rad); //rotate point
trans *= r; //orient
//add a random translation
trans *= XMMatrixTranslation(rand() % error, rand() % error, rand() % error);
trans *= XMMatrixTranslation(origin.x, origin.y, origin.z);
XMVECTOR pt = XMVectorSet(0, radius, 0, 0);
XMVECTOR pt_trans = XMVector3Transform(pt, trans);
XMFLOAT3 newpt;
XMStoreFloat3(&newpt, pt_trans);
points.push_back(newpt);
m_Geometry->AddSphere(points[points.size() - 1], .05f, COLOUR_CYAN);
}
}
//find best fitting circle to get axis of rotation and direction
//now working very well
XMFLOAT3 center = { 0,0,0 }, dir_fit = { 0,0,0 };
float r = 0.f;
this->fitCircle(points, center, dir_fit, r, m_Geometry, true);
//next - find a spherical center
//so create some spherical test data points
origin = { -50, 50, 400 };
radius = 250;
vector<XMFLOAT3>sphere;
m_Geometry->AddSphere(origin, 0.2f, COLOUR_CYAN);
for (float a1 = -90.f; a1 < 65; a1 += 5.f)
{
for (float a2 = 0.f; a2 < 65; a2 += 5.f)
{
XMMATRIX trans = XMMatrixRotationZ(a1 * (3.14159f / 180.f));
trans *= XMMatrixRotationX(a2 * (3.14159f / 180.f));
trans *= XMMatrixTranslation(rand() % error, rand() % error, rand() % error);
trans *= XMMatrixTranslation(origin.x, origin.y, origin.z);
XMVECTOR pt = XMVectorSet(0, radius, 0, 0);
XMVECTOR pt_trans = XMVector3Transform(pt, trans);
XMFLOAT3 newpt;
XMStoreFloat3(&newpt, pt_trans);
m_Geometry->AddSphere(newpt, 0.03f, COLOUR_CYAN);
sphere.push_back(newpt);
}
}
//have a set of points to fit a sphere to now
//get the centroid
XMFLOAT3 centroid = find_centroid(sphere);
//m_Geometry->AddSphere(centroid, 0.2f, COLOUR_RED);
//use the centroid as the starting center to search
this->LeastSquaresSphere(sphere, radius, centroid, 300.f, 20.f);
this->LeastSquaresSphere(sphere, radius, centroid, 20.f, 15.f);
this->LeastSquaresSphere(sphere, radius, centroid, 2.f, 20.f);
m_Geometry->AddSphere(centroid, 0.2f, COLOUR_WHITE);
*/
// Create the color shader object.
m_ColorShader = new ColorShaderClass;
if (!m_ColorShader)
{
return false;
}
// Initialize the color shader object.
result = m_ColorShader->Initialize(m_Direct3D->GetDevice(), hwnd);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK);
return false;
}
// Create the Light shader object.
m_LightShader = new LightShaderClass;
if (!m_LightShader)
{
return false;
}
// Initialize the color shader object.
result = m_LightShader->Initialize(m_Direct3D->GetDevice(), hwnd);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
return false;
}
// Create the light object.
m_Light = new LightClass;
if (!m_Light)
{
return false;
}
// Initialize the light object.
m_Light->SetAmbientColor(.10f, .10f, .10f, 1.f);
m_Light->SetDiffuseColor(.5f, .5f, .5f, 1.0f);
m_Light->SetDirection(0.3f, -1.0f, 0.5f);
m_Light->SetSpecularColor(.01f, .01f, .01f, 1.f);
m_Light->SetSpecularPower(4.f);
//initialise marker matrix
m_Direct3D->GetWorldMatrix(m_markermatrix);
m_Direct3D->GetWorldMatrix(m_modelmatrix);
m_Direct3D->GetWorldMatrix(m_wirematrix[0]);
m_Direct3D->GetWorldMatrix(m_wirematrix[1]);
m_Direct3D->GetWorldMatrix(m_wirematrix[2]);
//load offsets
result = LoadOffset();
//initialise volume class - for doing volume rendering
m_IIwidth = 512;
m_IIheight = 512;
m_Volume = new VolumeClass;
if (!m_Volume)
{
//return false;
}
m_Volume->Initialise(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), (uint) m_IIwidth, (uint)m_IIheight, scenario, m_Direct3D);
// Create the bitmap object.
m_Bitmap = new BitmapClass;
if (!m_Bitmap)
{
return false;
}
// Initialize the bitmap object.
//result = m_Bitmap->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, "tad.tga", 128, 26);
result = m_Bitmap->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), screenWidth, screenHeight, "data\\textures\\II mask.tga", 200, 200);
if (!result)
{
MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK);
return false;
}
m_tex_IIcircle = new TextureClass;
m_tex_IIcircle->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\II mask.tga");
m_selectbox = new TextureClass;
m_selectbox->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\select.tga");
m_markernotvisible = new TextureClass;
m_markernotvisible->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\marker not visible.tga");
//create a test texture
m_tex0 = new TextureClass;
m_tex0->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\tad.tga");
m_tex_apex = new TextureClass;
m_tex_apex->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\apex marker.tga");
m_tex_keys = new TextureClass;
m_tex_keys->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\key_guide.tga");
m_arrow = new TextureClass;
m_arrow->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\textures\\arrow1.tga");
m_textClass = new TextClass;
m_textClass->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), m_ColorShader, hwnd, screenWidth, screenHeight, XMMatrixIdentity());
m_fontClass = new FontClass;
m_fontClass->Initialize(m_Direct3D->GetDevice(), m_Direct3D->GetDeviceContext(), "data\\fonts\\font2.fnt", "data\\fonts\\font2_0.tga");
return true;
}
//this function takes a vector of points and returns best fit circle - center, radius and direction vector
bool GraphicsClass::fitCircle(vector<XMFLOAT3> points, XMFLOAT3& center, XMFLOAT3& dir, float& radius, GeometryClass* geom, bool display)
{
//1 -> find best fit plane and align all points onto that plane - this is direction sorted
XMFLOAT3 centroid = { 0,0,0 };
fitplane(points, dir, centroid); //find the least squares best fit plane
if(display)geom->AddSphere(centroid, 0.2f, COLOUR_PURPLE); //show centroid
//test the fit by drawing a line
// now find plane normal and centroid.
XMFLOAT3 dir_line_vector = { dir.x * 50, dir.y * 50, dir.z * 50 };
dir_line_vector.x += centroid.x;
dir_line_vector.y += centroid.y;
dir_line_vector.z += centroid.z;
if(display)geom->AddLine(centroid, dir_line_vector, COLOUR_PURPLE);
//translate to plane facing camera to drop z-axis
//XMVECTOR at = XMVectorSet(0.f, 0.f, 0.f, 0.f);
XMVECTOR at = XMLoadFloat3(¢roid);
XMVECTOR to = XMVectorSet(dir.x + centroid.x, dir.y + centroid.y, dir.z + centroid.z, 0.f);
XMVECTOR up = XMVectorSet(0.f, 1.f, 0.f, 0.f); //for now just y axis but will need modified to avoid gimbal lock
XMMATRIX m = XMMatrixLookAtLH(at, to, up);
m *= XMMatrixTranslation(0.f, 0.f, 200.f);
XMFLOAT3 newpt = { 0.f, 0.f, 0.f };
vector<XMFLOAT3> points_transformed;
for each (XMFLOAT3 point in points)
{
XMVECTOR pt = XMVector3Transform(XMLoadFloat3(&point), m);
XMStoreFloat3(&newpt, pt);
newpt.z = 200.f; //drop the z component to ensure coplanar
point = newpt; //overwrite point
//if(display)geom->AddSphere(newpt, 0.1f, COLOUR_YELLOW);
points_transformed.push_back(newpt);
}
//try the openCV fit ellipse
Mat pointsf; //array of points
vector<Point3f> pt;
Point3f av;
for each(XMFLOAT3 p in points_transformed)
{
Point3f t;
t.x = p.x;
t.y = p.y;
pt.push_back(t);
av.x += t.x; av.y += t.y;
}
av.x /= pt.size(); av.y /= pt.size();
radius = 80.f; //guess based on rough size of marker
XMFLOAT2 cent = { av.x, av.y };
Mat(pt).convertTo(pointsf, CV_32F);
// RotatedRect box = fitEllipse(pointsf);
//radius = (box.size.width + box.size.height) / 4;
//if (display)geom->AddSphere(XMFLOAT3(box.center.x, box.center.y, 200.f), 0.1f, COLOUR_YELLOW);
//the above opencv fit ellipse function gives us an approximate starting location
//from here need to use minimise least squares to reduce the error
//problem is opencv is fitting an elipse not a circle, so only works well for a full circle
//XMFLOAT2 cent = { box.center.x, box.center.y };
this->leastSquares(points_transformed, cent, radius, 300.f, 60.f);
//and again
this->leastSquares(points_transformed, cent, radius, 12.f, 15.f);
//and one last time to get really accurate
this->leastSquares(points_transformed, cent, radius, 1.f, 10.f);
//another time??
//if (display) geom->AddSphere(XMFLOAT3(cent.x, cent.y, 200.f), 0.1f, COLOUR_BLUE);
//draw the circle to illustrate
vector<XMFLOAT3> circle;
float angle = 0.f;
float x = cent.x + (radius * cos(angle));
float y = cent.y + (radius * sin(angle));
circle.push_back(XMFLOAT3(x, y, 0.f));
for (float angle = 0.1f; angle < (3.14159f * 2.f); angle += 0.2f)
{
float xold = x;
float yold = y;
x = cent.x + (radius * cos(angle));
y = cent.y + (radius * sin(angle));
// if (display)geom->AddLine(XMFLOAT3(xold, yold, 200.f), XMFLOAT3(x, y, 200.f), COLOUR_YELLOW);
circle.push_back(XMFLOAT3(x, y, 0.f));
}
//transform circle points back to original space
//build transform
XMVECTOR up2 = XMVectorSet(0.f, 1.f, 0.f, 0.f);
XMVECTOR org2 = XMVectorSet(0.f, 0.f, 0.f, 0.f);
XMVECTOR out2 = XMLoadFloat3(&dir);
XMMATRIX r2 = XMMatrixTranspose(XMMatrixLookAtLH(org2, out2, up2));
XMMATRIX trans2 = XMMatrixTranslation(centroid.x, centroid.y, centroid.z);
XMMATRIX m1 = r2 * trans2;
vector<XMFLOAT3> circle2;
for each(XMFLOAT3 c in circle)
{
XMVECTOR p = XMVector3Transform(XMLoadFloat3(&c), m1);
XMFLOAT3 tmp = { 0,0,0 };
XMStoreFloat3(&tmp, p);
circle2.push_back(tmp);
if(display)geom->AddSphere(tmp, 0.1f, COLOUR_YELLOW);
}
//transform the center back to original space
XMVECTOR c_vec = XMVector3Transform(XMLoadFloat3(&XMFLOAT3(cent.x, cent.y, 0.f)), m1);
XMStoreFloat3(¢er, c_vec);
if(display)geom->AddSphere(center, 0.05f, COLOUR_YELLOW);
dir_line_vector = { dir.x * 150, dir.y * 150, dir.z * 150 };
dir_line_vector.x += center.x;
dir_line_vector.y += center.y;
dir_line_vector.z += center.z;
if (display)geom->AddLine(center, dir_line_vector, COLOUR_PURPLE);
dir_line_vector = { dir.x * -150, dir.y * -150, dir.z * -150 };
dir_line_vector.x += center.x;
dir_line_vector.y += center.y;
dir_line_vector.z += center.z;
if (display)geom->AddLine(center, dir_line_vector, COLOUR_PURPLE);
return true;
}
void GraphicsClass::leastSquares(vector<XMFLOAT3>& points_transformed, XMFLOAT2& c, float& radius, float search_width, float steps)
{
//try a very basic method to find center to nearest 0.5
//use the estimated center
//5search within a pre-defined area for the global cost function minimum
//float search_height = 50.f;
float x1 = c.x - search_width / 2;
float y1 = c.y - search_width / 2;
float x2 = c.x + search_width / 2;
float y2 = c.y + search_width / 2;
float xsteps = steps;// 50; //set to search width for every square mm
float ysteps = steps;// 50;
float xstep = (x2 - x1) / xsteps;
float ystep = (y2 - y1) / ysteps;
float err_min = 1000000000.f;
float x_min = 0.f;
float y_min = 0.f;
float r_min = 0.f;
for (float y = y1; y < y2; y += ystep)
{
for (float x = x1; x < x2; x += xstep)
{
float r_sample = 0.f;
for each (XMFLOAT3 p in points_transformed)
{
float di = sqrt(((p.x - x)*(p.x - x)) + ((p.y - y)*(p.y - y)));
r_sample += di;
}
r_sample /= points_transformed.size();
//get error
float err = 0.f;
for each (XMFLOAT3 p in points_transformed)
{
float di = sqrt(((p.x - x)*(p.x - x)) + ((p.y - y)*(p.y - y)));
float err_tmp = (di - r_sample) * (di - r_sample);
err += err_tmp;
}
//err is sum of squares of error based on current circle
if (err < err_min)
{
err_min = err;
x_min = x;
y_min = y;
r_min = r_sample;
}
}
}
c.x = x_min;
c.y = y_min;
radius = r_min;
return;
}
//find least squares sphere within search window specied at step interval
void GraphicsClass::LeastSquaresSphere(vector<XMFLOAT3>& points, float& radius, XMFLOAT3& c, float search_width, float steps)
{
//try a very basic method to find center to nearest 0.5
//use the estimated center
//5search within a pre-defined area for the global cost function minimum
//float search_height = 50.f;
float x1 = c.x - search_width / 2;
float y1 = c.y - search_width / 2;
float x2 = c.x + search_width / 2;
float y2 = c.y + search_width / 2;
float z1 = c.z - search_width / 2;
float z2 = c.z + search_width / 2;
float xsteps = steps;// 50; //set to search width for every square mm
float ysteps = steps;// 50;
float xstep = (x2 - x1) / xsteps;
float ystep = (y2 - y1) / ysteps;
float zstep = (z2 - z1) / ysteps;
float err_min = 1000000000.f;
float x_min = 0.f;
float y_min = 0.f;
float z_min = 0.f;
float r_min = 0.f;
for (float z = z1; z < z2; z += zstep)
{
for (float y = y1; y < y2; y += ystep)
{
for (float x = x1; x < x2; x += xstep)
{
float r_sample = 0.f;
for each (XMFLOAT3 p in points)
{
float di = sqrt(((p.x - x)*(p.x - x)) + ((p.y - y)*(p.y - y)) + ((p.z - z) * (p.z - z)));
r_sample += di;
}
r_sample /= points.size();
//r_sample = 250; //debug - fix radius
//get error
float err = 0.f;
for each (XMFLOAT3 p in points)
{
float di = sqrt(((p.x - x)*(p.x - x)) + ((p.y - y)*(p.y - y)) + ((p.z - z) * (p.z - z)));
float err_tmp = (di - r_sample) * (di - r_sample);
err += err_tmp;
}
//err is sum of squares of error based on current circle
if (err < err_min)
{
err_min = err;
x_min = x;
y_min = y;
z_min = z;
r_min = r_sample;
}
}
}
}
c.x = x_min;
c.y = y_min;
c.z = z_min;
radius = r_min;
return;
}
void GraphicsClass::Shutdown()
{
// Release the light object.
if (m_Light)
{
delete m_Light;
m_Light = 0;
}
// Release the color shader object.
if (m_ColorShader)
{
m_ColorShader->Shutdown();
delete m_ColorShader;
m_ColorShader = 0;
}
// Release the model object.
if (m_Model)
{
m_Model->Shutdown();
delete m_Model;
m_Model = 0;
}
// Release the camera object.
if (m_Camera)
{
delete m_Camera;
m_Camera = 0;
}
//release volume object
if (m_Volume)
{
delete m_Volume;
m_Volume = 0;
}
// Release the Direct3D object.
if (m_Direct3D)
{
m_Direct3D->Shutdown();
delete m_Direct3D;
m_Direct3D = 0;
}
// Release the bitmap object.
if (m_Bitmap)
{
m_Bitmap->Shutdown();
delete m_Bitmap;
m_Bitmap = 0;
}
return;
}
bool GraphicsClass::Frame()
{
bool result;
// Render the graphics scene.
result = Render(0.0f);
if (!result)
{
return false;
}
return true;
}
GeometryClass* GraphicsClass::GetGeometry()
{
return m_Geometry;
}
void GraphicsClass::SetMarkerWarningVisible(bool visible)
{
m_showMarkerVisible = visible;
}
void GraphicsClass::SetModelVisible(bool visible)
{
m_modelvisible = visible;
}
void GraphicsClass::SetMarkerVisible(bool visible)
{
m_markervisible = visible;
}
void GraphicsClass::SetGuidewireVisible(bool visible)
{
m_guidewirevisible = visible;
}
void GraphicsClass::SetGuidewire2Visible(bool visible)
{
m_guidewire2visible = visible;
}
void GraphicsClass::SetActiveRectangleVisible(bool visible)
{
m_showActiveRectangle = visible;
}
void GraphicsClass::exposure_increase()
{
m_Volume->Exposure_Increase(m_AP_active);
m_AP_active ? RenderII_AP() : RenderII_lat();
}
void GraphicsClass::exposure_decrease()
{
m_Volume->Exposure_Decrease(m_AP_active);
m_AP_active ? RenderII_AP() : RenderII_lat();
}
void GraphicsClass::SetIIAngleAP(float angle)
{
m_II_AP_angle = angle;
RenderII_AP();
calculateTAD();
}
void GraphicsClass::SetIIAngleLat(float angle)
{
m_II_lat_angle = angle;
RenderII_lat();
calculateTAD();
}
float GraphicsClass::GetIIAngleAP(float angle)
{
return m_II_AP_angle;
}
float GraphicsClass::GetIIAngleLat(float angle)
{
return m_II_lat_angle;
}
void GraphicsClass::SetUseCTCoords(bool setting)
{
m_useCTWireCoords = setting;
}
void GraphicsClass::II_setwire()
{
m_wirematrixII[m_currentwire] = m_wirematrix[m_currentwire];
}
void GraphicsClass::II_setAP(bool isAP)
{
m_AP_active = isAP;
}
void GraphicsClass::setWireMatrix(XMMATRIX w)
{
m_wirematrixII[0] = w;
m_wirematrix[0] = w;
}
void GraphicsClass::SetIIView()
{
//hide second guidewire shadow
SetGuidewire2Visible(false);
//all ready running - ie femur dropped so switch to II view mode
RenderII_lat(); //dont increment
RenderII_AP(); //the counter and dont save xray
SetRenderState(GSTATE_II);
}
void GraphicsClass::RenderII_current()
{
m_AP_active ? RenderII_AP() : RenderII_lat();
m_xr_count++;
//save the output
}
HRESULT GraphicsClass::SaveII(LPCWSTR filename)
{
//save the current II texture to a file - incrementing filename number
int i = 0;
m_AP_active ? i = 0 : i = 1;
LPCWSTR ending = L".png";
wstring f = wstring(filename) + to_wstring(m_xr_count) + ending;
HRESULT result = SaveWICTextureToFile(m_Direct3D->GetDeviceContext(), m_Volume->GetResource(i), GUID_ContainerFormatPng, (LPCWSTR)f.c_str());
return result;
}
HRESULT GraphicsClass::SaveScreenshot(LPCWSTR filename, int frame)
{
LPCWSTR ending = L".png";
wstring f = wstring(filename) + ending;
HRESULT result = SaveWICTextureToFile(m_Direct3D->GetDeviceContext(), m_Volume->GetResource(frame),GUID_ContainerFormatPng, (LPCWSTR)f.c_str());
return result;
}
void GraphicsClass::RenderII_lat()
{
RenderII(false, m_II_lat_angle, 10.f);
//m_AP_active = false;
}
void GraphicsClass::RenderII_AP()
{
RenderII(true, m_II_AP_angle, 10.f);
//m_AP_active = true;
}
void GraphicsClass::RenderII(bool AP, float rot, float rot2)
{
//function to draw all II AP stuff to a texture
#ifdef DEBUG_SET_WIRE_POS
//used to set the wire from apex and offset instead of measuring wire
//alternative - do this if no cameras plugged in
//SetWireFromNeckVector(XMFLOAT3(0.f, 0.f, 0.f)); //get the new wire matrix based on neck vector and offset
#endif
//XMVECTOR v_world2ct = XMLoadFloat3(&scenario->get_world2ct());
XMVECTOR v_world2ct = XMLoadFloat3(&m_Volume->getWorld2CT()); //think this is translation to move model / subject coordinates to CT cube coordinates
D3D11_VIEWPORT vp;
XMFLOAT2 topleft = { 0,0 };
XMFLOAT2 bottomright = { 0,0 };
XMMATRIX worldMatrix = XMMatrixIdentity();
XMMATRIX orthoMatrix = XMMatrixIdentity();
bool result = false;
int vp_width = (int)m_screenwidth;
int vp_height = (int)m_screenheight;
vp.Width = m_IIwidth;
vp.Height = m_IIheight;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
m_Direct3D->GetDeviceContext()->RSSetViewports(1, &vp); //set active viewport to above
topleft = { 0,0 };
bottomright = {m_IIwidth,m_IIheight };
//spin the II viewport
m_Volume->setRotation(rot, AP, AP?0.f:-30.f);
m_Volume->Render(m_Direct3D->GetDeviceContext(), topleft, bottomright, AP);
//clear back buffer
m_Direct3D->ClearDepthStencil();
//reset normal backface culling - disabling this step stops mask from working
m_Direct3D->SetRasterizerState();
//turn on z buffer again
m_Direct3D->TurnZBufferOn();
//not sure why this doesnt work
m_Direct3D->TurnOnAlphaBlending();
#ifdef DEBUG_SHOW_FEMUR
{
//Render the femur ontop of ct scan still onto the texture - DEBUG feature
worldMatrix = XMMatrixTranslationFromVector(v_world2ct);
m_Model->Render(m_Direct3D->GetDeviceContext());
result = m_ColorShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor(), { 0.f, 1.f, 0.f, 0.5f });
//result = m_LightShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
// m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor(), m_Camera->GetPosition(), m_Light->GetSpecularColor(), m_Light->GetSpecularPower());
}
#endif
//debug - render a sphere in femoral head
#ifdef DEBUG_SHOW_FEMORAL_HEAD_SPHERE
{
float sphere_diammeter = 48.f;
sphere_diammeter -= 10.f; //take away distance want tip of screw to be under subchondral bone
sphere_diammeter /= 40.f; //the sphere has diammeter of 40
worldMatrix = XMMatrixScaling(sphere_diammeter, sphere_diammeter, sphere_diammeter);
worldMatrix *= XMMatrixTranslationFromVector(XMLoadFloat3(&scenario->sc_head_centre));
worldMatrix *= XMMatrixTranslationFromVector(v_world2ct);
m_Sphere->Render(m_Direct3D->GetDeviceContext());
result = m_ColorShader->Render(m_Direct3D->GetDeviceContext(), m_Sphere->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Sphere->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor(), { 0.f, 1.f, 0.f, 0.3f });
}
#endif
XMVECTOR v_wire_tip;
//show a line up neck - this DOESNT BELONG HERE! TEMPORARY for PROF SIMPSONS WIRES!!!!
if (m_showNeckVector)
{
}
XMVECTOR marker_offset = m_ct_markerloc - m_ct_org;
for (int i = 0; i < 3; i++)
{
XMMATRIX wire2world = m_wirematrixII[i]; //wire2world is matrix to move camera coordinates to CT volume coordinates
wire2world *= XMMatrixInverse(nullptr, m_model_pos); //subtract model position
wire2world *= XMMatrixTranspose(m_model_dir); //derotate from model direction
wire2world *= XMMatrixRotationY(3.14159f / 2.f);
wire2world *= XMMatrixRotationZ(-3.14159f); //rotate 180 degrees back
wire2world *= XMMatrixInverse(nullptr, m_offset); //finally move to marker position
wire2world *= XMMatrixTranslationFromVector(v_world2ct); //last step- translate to CT cube position from world coordinates
//render wire using solid black pixel shader onto the texture
if (!m_useCTWireCoords)
{
worldMatrix = wire2world; //using real world coordinates from sensor
}
else
{
worldMatrix = m_wirematrixII[i] * XMMatrixTranslationFromVector(v_world2ct); //using model coordinates - just need to move to CT render Cube
}
if (m_show_wire)
{
m_Wire->Render(m_Direct3D->GetDeviceContext());
m_Direct3D->TurnOffAlphaBlending();
if (i == m_currentwire)
{
result = m_ColorShader->RenderSolid(m_Direct3D->GetDeviceContext(), m_Wire->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Wire->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor());
}
else
{
result = m_ColorShader->RenderSolid(m_Direct3D->GetDeviceContext(), m_Wire->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Wire->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor());
}
}
if (m_show_DHS_screw)
{
//render the screw on top of wire
XMMATRIX tMat = XMMatrixRotationX(3.14159f) * XMMatrixTranslation(0.f, 0.f, 145.f);
if (!m_useCTWireCoords)
{
worldMatrix = tMat * wire2world; //using real world coordinates from sensor
}
else
{
worldMatrix = tMat * m_wirematrixII[i] * XMMatrixTranslationFromVector(v_world2ct); //using ct coordinates
}
m_Screw->Render(m_Direct3D->GetDeviceContext());
m_Direct3D->TurnOffAlphaBlending();
result = m_ColorShader->RenderSolid(m_Direct3D->GetDeviceContext(), m_Screw->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Screw->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor());
}
if (m_show_cannulated_screw)
{
//render a cannulated screw on top of guidewire
XMMATRIX tMat = XMMatrixRotationX(3.14159f) * XMMatrixTranslation(0.f, 0.f, 145.f);
if (!m_useCTWireCoords)
{
worldMatrix = tMat * wire2world; //using real world coordinates from sensor
}
else
{
worldMatrix = tMat * m_wirematrixII[i] * XMMatrixTranslationFromVector(v_world2ct); //using ct coordinates
}
m_Cannulated->Render(m_Direct3D->GetDeviceContext());
m_Direct3D->TurnOffAlphaBlending();
result = m_ColorShader->RenderSolid(m_Direct3D->GetDeviceContext(), m_Cannulated->GetIndexCount(), worldMatrix, m_Volume->getViewMatrix(), m_Volume->getProjectionMatrix(),
m_Cannulated->GetTexture(), m_Light->GetDirection(), m_Light->GetDiffuseColor());
}
}
//display 2d bitmaps over the top
orthoMatrix = XMMatrixOrthographicLH(m_IIwidth, m_IIheight, 100.f, 1000.f);
m_Direct3D->TurnZBufferOff();
m_Direct3D->TurnOnAlphaBlending();
//show location of tip and apex using a red cross if enabled
{
XMVECTOR v_tip_pos = XMVectorSet(0.f, 0.f, GUIDEWIRE_LENGTH, 1.f);
XMVECTOR apex_pos = XMLoadFloat3(&m_apex);
XMMATRIX wire2world = m_wirematrixII[0]; //wire2world is matrix to move camera coordinates to CT volume coordinates
if (!m_useCTWireCoords)
{
wire2world *= XMMatrixInverse(nullptr, m_model_pos); //subtract model position
wire2world *= XMMatrixTranspose(m_model_dir); //derotate from model direction
wire2world *= XMMatrixRotationY(3.14159f / 2.f);
wire2world *= XMMatrixRotationZ(-3.14159f); //rotate 180 degrees back
wire2world *= XMMatrixInverse(nullptr, m_offset);