forked from sencercoltu/steamvr-undistort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
1657 lines (1416 loc) · 79.9 KB
/
Program.cs
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
using FastJsonLib;
using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Mathematics.Interop;
using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Valve.VR;
namespace Undistort
{
public static class Program
{
private static void Log(string fmt, params object[] args)
{
File.AppendAllText("Debug.log", string.Format(fmt + "\n", args));
}
private struct VertexShaderData
{
public Matrix WorldViewProj;
public Vector2 ActiveEyeCenter;
public float ActiveAspect;
public float Reserved1;
}
public struct PixelShaderData
{
public Vector3 LightPosition;
public float Reserved;
public int _Undistort; //bool is 1 byte inside struct, we use int to convert to 4 bytes and use getter setter
public bool Undistort { get { return _Undistort > 0; } }
private int _Wireframe;
public bool Wireframe { get { return _Wireframe == 1; } set { _Wireframe = value ? 1 : 0; } }
private int _Controller;
public bool Controller { get { return _Controller == 1; } set { _Controller = value ? 1 : 0; } }
public int ActiveColor;
}
public struct DistortShaderData
{
public Vector4 RedCoeffs;
public Vector4 GreenCoeffs;
public Vector4 BlueCoeffs;
public Vector4 RedCenter;
public Vector4 GreenCenter;
public Vector4 BlueCenter;
public Vector2 EyeCenter;
public float GrowToUndistort;
public float UndistortR2Cutoff;
public float Aspect;
public float FocalX;
public float FocalY;
public int ActiveEye;
//public Matrix Extrinsics;
public Matrix3x3 Intrinsics;
public Vector3 Reserved2;
}
//public static bool Undistort;
//public static bool Wireframe;
public static bool RenderHiddenMesh = true;
private static CVRSystem vrSystem;
private static CVRCompositor vrCompositor;
private static uint maxTrackedDeviceCount;
private static uint hmdID;
private static Dictionary<uint, ETrackedControllerRole> controllers;
private static uint[] controllerIDs = new uint[0];
private static TrackedDevicePose_t[] currentPoses;
private static TrackedDevicePose_t[] nextPoses;
public static SharpDX.Direct3D11.Device d3dDevice;
private static DeviceContext d3dDeviceContext;
public static SwapChain d3dSwapChain;
public static RawColor4 d3dClearColor;
private static RasterizerState WireFrameRasterizerState;
private static RasterizerState SolidRasteizerState;
private static RasterizerState ncWireFrameRasterizerState;
private static RasterizerState ncRasterizerState;
public static DepthStencilState DepthStencilState;
public static DepthStencilState ControllerDepthStencilState;
private static BlendState blendState;
private static SamplerState samplerState;
private static Matrix headMatrix;
public static Texture2D UndistortTexture;
public static RenderTargetView UndistortTextureView;
public static ShaderResourceView UndistortShaderView;
private static Shader hmaShader;
private static VertexBufferBinding hmaVertexBufferBinding;
private static IDictionary<string, object> lightHouseConfigJson;
private static VertexShaderData vertexShaderData = default(VertexShaderData);
public static PixelShaderData pixelShaderData = default(PixelShaderData);
private static SharpDX.Direct3D11.Buffer vertexConstantBuffer;
private static SharpDX.Direct3D11.Buffer pixelConstantBuffer;
private static SharpDX.Direct3D11.Buffer coefficientConstantBuffer;
public static Size WindowSize;
public static Texture2D BackBufferTexture;
public static RenderTargetView BackBufferTextureView;
public static Texture2D BackBufferDepthTexture;
public static DepthStencilView BackBufferDepthStencilView;
public static SharpDX.Direct3D11.Buffer BackBufferIndexBuffer;
public static int RenderMode = 0;
public class EyeData
{
public const float Near = 0.01f;
public const float Far = 1000f;
public EyeData(EVREye eye)
{
Eye = eye;
ResetDistortionCoefficients();
}
public EVREye Eye;
public SizeF PanelSize;
public SizeF FrameSize;
public IDictionary<string, object> Json;
public Matrix OriginalProjection;
public Matrix EyeToHeadView;
public HiddenAreaMesh_t HiddenAreaMesh;
public SharpDX.Direct3D11.Buffer HiddenAreaMeshVertexBuffer;
public Texture2D Texture;
public RenderTargetView TextureView;
public ShaderResourceView ShaderView;
public Texture2D DepthTexture;
public DepthStencilView DepthStencilView;
public DistortShaderData DistortionData;
public DistortShaderData OriginalDistortionData;
public DistortShaderData GetData(bool original)
{
return original ? OriginalDistortionData : DistortionData;
}
public SharpDX.Direct3D11.Buffer BackBufferVertexBuffer;
public string EyeName
{
get
{
switch (Eye)
{
case EVREye.Eye_Left:
return "LEFT";
case EVREye.Eye_Right:
return "RIGHT";
default:
return "WTF";
}
}
}
public void ResetDistortionCoefficients()
{
DistortionData.RedCoeffs = Vector4.Zero; DistortionData.RedCoeffs.W = 1;
DistortionData.GreenCoeffs = Vector4.Zero; DistortionData.GreenCoeffs.W = 1;
DistortionData.BlueCoeffs = Vector4.Zero; DistortionData.BlueCoeffs.W = 1;
DistortionData.RedCenter = Vector4.Zero;
DistortionData.GreenCenter = Vector4.Zero;
DistortionData.BlueCenter = Vector4.Zero;
}
public void UpdateIntrinsicsFromFocusAndCenter()
{
DistortionData.Intrinsics.M11 = 2.0f * DistortionData.FocalX / PanelSize.Width;
DistortionData.Intrinsics.M31 = DistortionData.EyeCenter.X;
DistortionData.Intrinsics.M22 = 2.0f * DistortionData.FocalY / PanelSize.Height;
DistortionData.Intrinsics.M32 = DistortionData.EyeCenter.Y;
}
public void CalcFocusCenterAspect()
{
DistortionData.FocalX = PanelSize.Width / 2 * DistortionData.Intrinsics.M11;
DistortionData.FocalY = PanelSize.Height / 2 * DistortionData.Intrinsics.M22;
DistortionData.EyeCenter.X = DistortionData.Intrinsics.M31;
DistortionData.EyeCenter.Y = DistortionData.Intrinsics.M32;
DistortionData.Aspect = DistortionData.Intrinsics.M11 / DistortionData.Intrinsics.M22;
}
public Matrix GetProjectionFromIntrinsics()
{
var scale = 1.0f + DistortionData.GrowToUndistort;
var matrix = Matrix.Zero;
matrix.M11 = DistortionData.Intrinsics.M11 / scale;
matrix.M31 = DistortionData.Intrinsics.M31 / scale;
matrix.M22 = DistortionData.Intrinsics.M22 / scale;
matrix.M32 = DistortionData.Intrinsics.M32 / scale;
matrix.M34 = -1f;
matrix.M33 = (Near + Far) / (Near - Far);
matrix.M43 = (Far * Near) / (Near - Far);
return matrix;
}
internal void ResetEyeCenters()
{
DistortionData.EyeCenter.X = DistortionData.EyeCenter.Y = 0;
}
}
public static EyeData leftEye;
public static EyeData rightEye;
private static Model environmentModel;
private static Model controllerModel;
public static Shader environmentShader;
public static Shader backbufferShader;
[Flags]
public enum RenderFlag
{
RedActive = 1 << 0,
GreenActive = 1 << 1,
BlueActive = 1 << 2,
Left = 1 << 3,
Right = 1 << 4,
K1 = 1 << 5,
K2 = 1 << 6,
K3 = 1 << 7,
RenderRed = 1 << 8,
RenderGreen = 1 << 9,
RenderBlue = 1 << 10,
ALL = RedActive | GreenActive | BlueActive | Left | Right | K1 | K2 | K3 | RenderRed | RenderGreen | RenderBlue
}
//public static float zoomLevel = 1.0f;
public static RenderFlag RenderFlags = RenderFlag.ALL;
private static void IntPtrToStructArray<T>(IntPtr unmanagedArray, int length, out T[] mangagedArray)
{
var size = Marshal.SizeOf(typeof(T));
mangagedArray = new T[length];
for (int i = 0; i < length; i++)
{
IntPtr ins = new IntPtr(unmanagedArray.ToInt64() + i * size);
mangagedArray[i] = (T)Marshal.PtrToStructure(ins, typeof(T));
}
}
public static float AdjustStep = 0.001f;
public static string OvrPath;
private static RenderForm MainForm;
private static uint ScreenWidth;
private static uint ScreenHeight;
public static float ScreenAspect;
[STAThread]
private static void Main()
{
if (File.Exists("Debug.log")) File.Delete("Debug.log");
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
var initError = EVRInitError.None;
vrSystem = OpenVR.Init(ref initError);
if (initError != EVRInitError.None)
{
Log("Error: Initialize OpenVR, {0}", initError.ToString());
return;
}
OvrPath = OpenVR.RuntimePath() + "\\";
OvrPath = OvrPath.Replace("\\\\","\\");
if (!LoadLHSettings(OvrPath))
return;
vrCompositor = OpenVR.Compositor;
vrCompositor.CompositorBringToFront();
vrCompositor.FadeGrid(5.0f, false);
maxTrackedDeviceCount = OpenVR.k_unMaxTrackedDeviceCount;
currentPoses = new TrackedDevicePose_t[maxTrackedDeviceCount];
nextPoses = new TrackedDevicePose_t[maxTrackedDeviceCount];
controllers = new Dictionary<uint, ETrackedControllerRole>();
vrSystem.GetRecommendedRenderTargetSize(ref ScreenWidth, ref ScreenHeight);
//update aspect with recommended sizes
ScreenAspect = (float)ScreenWidth / (float)ScreenHeight;
leftEye.FrameSize = rightEye.FrameSize = new Size((int)ScreenWidth, (int)ScreenHeight);
ScreenWidth *= 2;
//scale down proportionally to fit
while (ScreenWidth > Screen.PrimaryScreen.Bounds.Width || ScreenHeight > Screen.PrimaryScreen.Bounds.Height)
{
ScreenWidth /= 2;
ScreenHeight /= 2;
}
WindowSize = new Size((int)ScreenWidth, (int)ScreenHeight);
leftEye.OriginalProjection = Convert(vrSystem.GetProjectionMatrix(EVREye.Eye_Left, EyeData.Near, EyeData.Far));
rightEye.OriginalProjection = Convert(vrSystem.GetProjectionMatrix(EVREye.Eye_Right, EyeData.Near, EyeData.Far));
leftEye.EyeToHeadView = Convert(vrSystem.GetEyeToHeadTransform(EVREye.Eye_Left));
rightEye.EyeToHeadView = Convert(vrSystem.GetEyeToHeadTransform(EVREye.Eye_Right));
leftEye.HiddenAreaMesh = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Left, EHiddenAreaMeshType.k_eHiddenAreaMesh_Standard);
rightEye.HiddenAreaMesh = vrSystem.GetHiddenAreaMesh(EVREye.Eye_Right, EHiddenAreaMeshType.k_eHiddenAreaMesh_Standard);
int adapterIndex = 0;
vrSystem.GetDXGIOutputInfo(ref adapterIndex);
using (MainForm = new RenderForm())
{
using (var factory = new Factory4())
{
MainForm.StartPosition = FormStartPosition.CenterScreen;
MainForm.Text = "SteamVR Lens Adjustment Utility";
MainForm.ClientSize = WindowSize;
MainForm.FormBorderStyle = FormBorderStyle.FixedSingle;
MainForm.MinimizeBox = false;
MainForm.MaximizeBox = false;
MainForm.KeyDown += (s, e) =>
{
if (e.Control)
ToggleHiddenMesh();
switch (e.KeyCode)
{
case Keys.NumPad5:
ToggleDistortion();
break;
case Keys.PageUp:
ChangeRenderMode();
break;
case Keys.Escape:
MainForm.Close();
break;
case Keys.NumPad7:
RenderFlags ^= RenderFlag.RedActive;
break;
case Keys.NumPad8:
RenderFlags ^= RenderFlag.GreenActive;
break;
case Keys.NumPad9:
RenderFlags ^= RenderFlag.BlueActive;
break;
case Keys.NumPad1:
RenderFlags ^= RenderFlag.K1;
break;
case Keys.NumPad2:
RenderFlags ^= RenderFlag.K2;
break;
case Keys.NumPad3:
RenderFlags ^= RenderFlag.K3;
break;
case Keys.NumPad4:
RenderFlags ^= RenderFlag.Left;
break;
case Keys.NumPad6:
RenderFlags ^= RenderFlag.Right;
break;
case Keys.Subtract:
AdjustFocus(-AdjustStep, -AdjustStep);
break;
case Keys.Add:
AdjustFocus(AdjustStep, AdjustStep);
break;
case Keys.Home:
ResetEyes();
break;
case Keys.Left:
if (e.Shift)
AdjustEyeCenters(-AdjustStep, 0);
else
IncreaseAdjustStep();
break;
case Keys.Right:
if (e.Shift)
AdjustEyeCenters(AdjustStep, 0);
else
DecreaseAdjustStep();
break;
case Keys.Up:
case Keys.Down:
if (e.Shift)
{
if (e.KeyCode == Keys.Down && e.Shift)
AdjustEyeCenters(0, -AdjustStep);
if (e.KeyCode == Keys.Up && e.Shift)
AdjustEyeCenters(0, AdjustStep);
break;
}
var step = AdjustStep;
if (e.KeyCode == Keys.Down) step *= -1f;
AdjustCoefficients(step);
break;
}
};
var adapter = factory.GetAdapter(adapterIndex);
var swapChainDescription = new SwapChainDescription
{
BufferCount = 1,
Flags = SwapChainFlags.None,
IsWindowed = true,
ModeDescription = new ModeDescription
{
Format = Format.B8G8R8A8_UNorm,
Width = WindowSize.Width,
Height = WindowSize.Height,
RefreshRate = new Rational(90, 1)
},
OutputHandle = MainForm.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, DeviceCreationFlags.BgraSupport /*| DeviceCreationFlags.Debug*/, swapChainDescription, out d3dDevice, out d3dSwapChain);
factory.MakeWindowAssociation(MainForm.Handle, WindowAssociationFlags.None);
d3dDeviceContext = d3dDevice.ImmediateContext;
BackBufferTexture = d3dSwapChain.GetBackBuffer<Texture2D>(0);
BackBufferTextureView = new RenderTargetView(d3dDevice, BackBufferTexture);
var depthBufferDescription = new Texture2DDescription
{
Format = Format.D16_UNorm,
ArraySize = 1,
MipLevels = 1,
Width = WindowSize.Width,
Height = WindowSize.Height,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default,
BindFlags = BindFlags.DepthStencil,
CpuAccessFlags = CpuAccessFlags.None,
OptionFlags = ResourceOptionFlags.None
};
BackBufferDepthTexture = new Texture2D(d3dDevice, depthBufferDescription);
BackBufferDepthStencilView = new DepthStencilView(d3dDevice, BackBufferDepthTexture);
// Create Eye Textures
var eyeTextureDescription = new Texture2DDescription
{
ArraySize = 1,
BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
CpuAccessFlags = CpuAccessFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = (int)leftEye.FrameSize.Width,
Height = (int)leftEye.FrameSize.Height,
MipLevels = 1,
OptionFlags = ResourceOptionFlags.None,
SampleDescription = new SampleDescription(1, 0),
Usage = ResourceUsage.Default
};
leftEye.Texture = rightEye.Texture = new Texture2D(d3dDevice, eyeTextureDescription);
leftEye.TextureView = rightEye.TextureView = new RenderTargetView(d3dDevice, leftEye.Texture);
leftEye.ShaderView = rightEye.ShaderView = new ShaderResourceView(d3dDevice, leftEye.Texture);
UndistortTexture = new Texture2D(d3dDevice, eyeTextureDescription);
UndistortTextureView = new RenderTargetView(d3dDevice, UndistortTexture);
UndistortShaderView = new ShaderResourceView(d3dDevice, UndistortTexture);
// Create Eye Depth Buffer
eyeTextureDescription.BindFlags = BindFlags.DepthStencil;
eyeTextureDescription.Format = Format.D32_Float;
leftEye.DepthTexture = rightEye.DepthTexture = new Texture2D(d3dDevice, eyeTextureDescription);
leftEye.DepthStencilView = rightEye.DepthStencilView = new DepthStencilView(d3dDevice, leftEye.DepthTexture);
var modelLoader = new ModelLoader(d3dDevice);
environmentShader = new Shader(d3dDevice, "Model_VS", "Model_PS", new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
});
backbufferShader = new Shader(d3dDevice, "Backbuffer_VS", "Backbuffer_PS", new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
});
BackBufferIndexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.IndexBuffer, new int[] { 0, 2, 3, 0, 1, 2 });
leftEye.BackBufferVertexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, new float[] {
-1f, -1f, 0f, 0, 1, //0
0f, -1f, 0f, 1, 1, //1
0f, 1f, 0f, 1, 0, //2
-1f, 1f, 0f, 0, 0 //3
});
rightEye.BackBufferVertexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, new float[] {
0f, -1f, 0f, 0, 1, //0
1f, -1f, 0f, 1, 1, //1
1f, 1f, 0f, 1, 0, //2
0f, 1f, 0f, 0, 0 //3
});
UndistortShader.Load(d3dDevice);
//var fileName = ovrPath + @"..\..\workshop\content\250820\928165436\spacecpod\spacecpod.obj";
//var fileName = ovrPath + @"..\..\workshop\content\250820\716774474\VertigoRoom\VertigoRoom.obj";
//var fileName = ovrPath + @"..\..\workshop\content\250820\686754013\holochamber\holochamber.obj";
//var fileName = OvrPath + @"..\..\workshop\content\250820\717646476\TheCube\TheCube.obj";
var fileName = @"environment\environment.obj";
environmentModel = modelLoader.Load(fileName);
environmentModel.SetInputLayout(d3dDevice, ShaderSignature.GetInputSignature(environmentShader.vertexShaderByteCode));
fileName = OvrPath + "\\resources\\rendermodels\\vr_controller_vive_1_5\\vr_controller_vive_1_5.obj";
controllerModel = modelLoader.Load(fileName);
controllerModel.SetInputLayout(d3dDevice, ShaderSignature.GetInputSignature(environmentShader.vertexShaderByteCode));
QueryDevices();
vertexShaderData.Reserved1 = 0f; //prevent compiler warning
vertexConstantBuffer = new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<VertexShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
pixelConstantBuffer = new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<PixelShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
coefficientConstantBuffer = new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<DistortShaderData>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
var rasterizerStateDescription = RasterizerStateDescription.Default();
rasterizerStateDescription.IsFrontCounterClockwise = true;
rasterizerStateDescription.FillMode = FillMode.Solid;
rasterizerStateDescription.IsAntialiasedLineEnabled = false;
rasterizerStateDescription.IsMultisampleEnabled = true;
SolidRasteizerState = new RasterizerState(d3dDevice, rasterizerStateDescription);
rasterizerStateDescription.CullMode = CullMode.None;
ncRasterizerState = new RasterizerState(d3dDevice, rasterizerStateDescription);
rasterizerStateDescription.CullMode = CullMode.Back;
rasterizerStateDescription.FillMode = FillMode.Wireframe;
WireFrameRasterizerState = new RasterizerState(d3dDevice, rasterizerStateDescription);
rasterizerStateDescription.CullMode = CullMode.None;
ncWireFrameRasterizerState = new RasterizerState(d3dDevice, rasterizerStateDescription);
var blendStateDescription = BlendStateDescription.Default();
blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.One;
blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.One;
blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
blendState = new BlendState(d3dDevice, blendStateDescription);
var depthStateDescription = DepthStencilStateDescription.Default();
depthStateDescription.DepthComparison = Comparison.LessEqual;
depthStateDescription.IsDepthEnabled = true;
depthStateDescription.IsStencilEnabled = false;
DepthStencilState = new DepthStencilState(d3dDevice, depthStateDescription);
depthStateDescription.DepthComparison = Comparison.Less;
ControllerDepthStencilState = new DepthStencilState(d3dDevice, depthStateDescription);
var samplerStateDescription = SamplerStateDescription.Default();
samplerStateDescription.Filter = Filter.MinMagMipLinear;
samplerStateDescription.BorderColor = d3dClearColor;
samplerStateDescription.AddressU = TextureAddressMode.Border;
samplerStateDescription.AddressV = TextureAddressMode.Border;
samplerState = new SamplerState(d3dDevice, samplerStateDescription);
d3dClearColor = new RawColor4(0.0f, 0.0f, 0.0f, 1);
var vrEvent = new VREvent_t();
var eventSize = (uint)Utilities.SizeOf<VREvent_t>();
headMatrix = Matrix.Identity;
d3dDeviceContext.VertexShader.SetConstantBuffer(0, vertexConstantBuffer);
d3dDeviceContext.PixelShader.SetConstantBuffer(1, pixelConstantBuffer);
d3dDeviceContext.PixelShader.SetConstantBuffer(2, coefficientConstantBuffer);
AdjustmentPanelModel.Init(d3dDevice);
CrossHairModel.Init(d3dDevice);
PointerModel.Init(d3dDevice);
AdjustCenter(0, 0, 0, 0);
hmaShader = new Shader(d3dDevice, "HiddenMesh_VS", "HiddenMesh_PS", new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0)
});
IntPtrToStructArray<HmdVector2_t>(leftEye.HiddenAreaMesh.pVertexData, (int)(leftEye.HiddenAreaMesh.unTriangleCount * 3), out var leftHAMVertices);
IntPtrToStructArray<HmdVector2_t>(rightEye.HiddenAreaMesh.pVertexData, (int)(rightEye.HiddenAreaMesh.unTriangleCount * 3), out var rightHAMVertices);
//convert 0/1 range to -1/1
for (var i = 0; i < leftHAMVertices.Length; i++)
{
var vert = leftHAMVertices[i];
vert.v0 -= 0.5f; vert.v0 *= 2;
vert.v1 -= 0.5f; vert.v1 *= 2;
leftHAMVertices[i] = vert;
}
for (var i = 0; i < rightHAMVertices.Length; i++)
{
var vert = rightHAMVertices[i];
vert.v0 -= 0.5f; vert.v0 *= 2;
vert.v1 -= 0.5f; vert.v1 *= 2;
rightHAMVertices[i] = vert;
}
leftEye.HiddenAreaMeshVertexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, leftHAMVertices);
rightEye.HiddenAreaMeshVertexBuffer = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, rightHAMVertices);
//SetProjectionZoomLevel();
RenderLoop.Run(MainForm, () =>
{
while (vrSystem.PollNextEvent(ref vrEvent, eventSize))
{
//Debug.WriteLine("VR Event: " + (EVREventType)vrEvent.eventType);
switch ((EVREventType)vrEvent.eventType)
{
case EVREventType.VREvent_IpdChanged:
//modify projection??
break;
case EVREventType.VREvent_PropertyChanged:
{
QueryDevices();
}
break;
case EVREventType.VREvent_TrackedDeviceUpdated:
{
QueryDevices();
}
break;
case EVREventType.VREvent_TrackedDeviceRoleChanged:
{
//controllers.Remove(vrEvent.trackedDeviceIndex);
QueryDevices();
}
break;
case EVREventType.VREvent_TrackedDeviceActivated:
QueryDevices();
//if (!controllers.ContainsKey(vrEvent.trackedDeviceIndex))
//{
// //var pError = ETrackedPropertyError.TrackedProp_Success;
// //var newrole = (ETrackedControllerRole)vrSystem.GetInt32TrackedDeviceProperty(vrEvent.trackedDeviceIndex, ETrackedDeviceProperty.Prop_ControllerRoleHint_Int32, ref pError);
// var newrole = vrSystem.GetControllerRoleForTrackedDeviceIndex(vrEvent.trackedDeviceIndex);
// if (newrole == ETrackedControllerRole.LeftHand || newrole == ETrackedControllerRole.RightHand)
// {
// controllers.Add(vrEvent.trackedDeviceIndex, vrSystem.GetControllerRoleForTrackedDeviceIndex(vrEvent.trackedDeviceIndex));
// controllerIDs = controllers.Keys.ToArray();
// }
//}
break;
case EVREventType.VREvent_TrackedDeviceDeactivated:
controllers.Remove(vrEvent.trackedDeviceIndex);
controllerIDs = controllers.Keys.ToArray();
break;
case EVREventType.VREvent_Quit:
//case EVREventType.VREvent_ProcessQuit:
MainForm.Close();
break;
case EVREventType.VREvent_ButtonPress:
{
var role = vrSystem.GetControllerRoleForTrackedDeviceIndex(vrEvent.trackedDeviceIndex);
var button = vrEvent.data.controller.button;
var state = default(VRControllerState_t);
vrSystem.GetControllerState(vrEvent.trackedDeviceIndex, ref state, (uint)Utilities.SizeOf<VRControllerState_t>());
ButtonPressed(role, ref state, (EVRButtonId)vrEvent.data.controller.button);
}
break;
case EVREventType.VREvent_ButtonUntouch:
case EVREventType.VREvent_ButtonUnpress:
{
var role = vrSystem.GetControllerRoleForTrackedDeviceIndex(vrEvent.trackedDeviceIndex);
var button = vrEvent.data.controller.button;
var state = default(VRControllerState_t);
vrSystem.GetControllerState(vrEvent.trackedDeviceIndex, ref state, (uint)Utilities.SizeOf<VRControllerState_t>());
ButtonUnPressed(role, ref state, (EVRButtonId)vrEvent.data.controller.button);
}
break;
default:
//System.Diagnostics.Debug.WriteLine((EVREventType)vrEvent.eventType);
break;
}
}
// Update Device Tracking
vrCompositor.WaitGetPoses(currentPoses, nextPoses);
if (currentPoses[hmdID].bPoseIsValid)
Convert(ref currentPoses[hmdID].mDeviceToAbsoluteTracking, ref headMatrix);
d3dDeviceContext.ClearRenderTargetView(BackBufferTextureView, d3dClearColor); // clear backbuffer once
d3dDeviceContext.ClearDepthStencilView(BackBufferDepthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);
#region Render LeftEye
RenderView(ref leftEye);
#endregion
#region Render RightEye
RenderView(ref rightEye);
#endregion
// Show Backbuffer
d3dSwapChain.Present(0, PresentFlags.None);
});
}
}
}
private static void QueryDevices()
{
controllers.Clear();
for (uint cdevice = 0; cdevice < maxTrackedDeviceCount; cdevice++)
{
var deviceClass = vrSystem.GetTrackedDeviceClass(cdevice);
switch (deviceClass)
{
case ETrackedDeviceClass.HMD:
hmdID = cdevice;
break;
case ETrackedDeviceClass.Controller:
if (!controllers.ContainsKey(cdevice))
{
//var pError = ETrackedPropertyError.TrackedProp_Success;
//var newrole = (ETrackedControllerRole) vrSystem.GetInt32TrackedDeviceProperty(cdevice, ETrackedDeviceProperty.Prop_ControllerRoleHint_Int32, ref pError);
var newrole = vrSystem.GetControllerRoleForTrackedDeviceIndex(cdevice);
if (newrole == ETrackedControllerRole.LeftHand || newrole == ETrackedControllerRole.RightHand)
{
controllers.Add(cdevice, newrole);
controllerIDs = controllers.Keys.ToArray();
}
}
break;
}
}
}
private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
Log("Exception: {0}", e.ToString());
MessageBox.Show(e.Exception.Message);
Application.Exit();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = (e.ExceptionObject as Exception);
Log("Exception: {0} {1} {2}", e.ToString(), ex.StackTrace, ex.InnerException?.ToString());
MessageBox.Show(ex.Message);
Application.Exit();
}
public static void ToggleHiddenMesh()
{
RenderHiddenMesh = !RenderHiddenMesh;
}
public static void DecreaseAdjustStep()
{
AdjustStep /= 10;
if (AdjustStep < 0.00000001f) AdjustStep = 0.00000001f;
}
public static void IncreaseAdjustStep()
{
AdjustStep *= 10;
if (AdjustStep > 1) AdjustStep = 1;
}
public static void AdjustEyeCenters(float xStep, float yStep)
{
AdjustCenter(RenderFlags.HasFlag(RenderFlag.Left) ? xStep : 0, RenderFlags.HasFlag(RenderFlag.Left) ? yStep : 0, RenderFlags.HasFlag(RenderFlag.Right) ? xStep : 0, RenderFlags.HasFlag(RenderFlag.Right) ? yStep : 0);
if (RenderFlags.HasFlag(RenderFlag.Left))
{
leftEye.DistortionData.RedCenter.X =
leftEye.DistortionData.GreenCenter.X =
leftEye.DistortionData.BlueCenter.X = -leftEye.DistortionData.EyeCenter.X;
leftEye.DistortionData.RedCenter.Y =
leftEye.DistortionData.GreenCenter.Y =
leftEye.DistortionData.BlueCenter.Y = -leftEye.DistortionData.EyeCenter.Y;
}
if (RenderFlags.HasFlag(RenderFlag.Right))
{
rightEye.DistortionData.RedCenter.X =
rightEye.DistortionData.GreenCenter.X =
rightEye.DistortionData.BlueCenter.X = -rightEye.DistortionData.EyeCenter.X;
rightEye.DistortionData.RedCenter.Y =
rightEye.DistortionData.GreenCenter.Y =
rightEye.DistortionData.BlueCenter.Y = -rightEye.DistortionData.EyeCenter.Y;
}
}
private static void AdjustCenter(double lx, double ly, double rx, double ry)
{
leftEye.DistortionData.EyeCenter.X += (float)lx;
leftEye.DistortionData.EyeCenter.Y += (float)ly;
leftEye.UpdateIntrinsicsFromFocusAndCenter();
rightEye.DistortionData.EyeCenter.X += (float)rx;
rightEye.DistortionData.EyeCenter.Y += (float)ry;
rightEye.UpdateIntrinsicsFromFocusAndCenter();
}
public static void AdjustColorCenters(float xStep, float yStep)
{
if (RenderFlags.HasFlag(RenderFlag.Left))
{
if (RenderFlags.HasFlag(RenderFlag.RedActive))
{
leftEye.DistortionData.RedCenter.X += xStep;
leftEye.DistortionData.RedCenter.Y += yStep;
}
if (RenderFlags.HasFlag(RenderFlag.GreenActive))
{
leftEye.DistortionData.GreenCenter.X += xStep;
leftEye.DistortionData.GreenCenter.Y += yStep;
}
if (RenderFlags.HasFlag(RenderFlag.BlueActive))
{
leftEye.DistortionData.BlueCenter.X += xStep;
leftEye.DistortionData.BlueCenter.Y += yStep;
}
}
if (RenderFlags.HasFlag(RenderFlag.Right))
{
if (RenderFlags.HasFlag(RenderFlag.RedActive))
{
rightEye.DistortionData.RedCenter.X += xStep;
rightEye.DistortionData.RedCenter.Y += yStep;
}
if (RenderFlags.HasFlag(RenderFlag.GreenActive))
{
rightEye.DistortionData.GreenCenter.X += xStep;
rightEye.DistortionData.GreenCenter.Y += yStep;
}
if (RenderFlags.HasFlag(RenderFlag.BlueActive))
{
rightEye.DistortionData.BlueCenter.X += xStep;
rightEye.DistortionData.BlueCenter.Y += yStep;
}
}
}
public static void ResetEyes()
{
if (RenderFlags.HasFlag(RenderFlag.Left)) { leftEye.ResetDistortionCoefficients(); leftEye.CalcFocusCenterAspect(); leftEye.ResetEyeCenters(); }
if (RenderFlags.HasFlag(RenderFlag.Right)) { rightEye.ResetDistortionCoefficients(); rightEye.CalcFocusCenterAspect(); rightEye.ResetEyeCenters(); }
AdjustCenter(0, 0, 0, 0);
}
public static void AdjustCoefficients(float step)
{
if (RenderFlags.HasFlag(RenderFlag.Left))
{
if (RenderFlags.HasFlag(RenderFlag.RedActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) leftEye.DistortionData.RedCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) leftEye.DistortionData.RedCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) leftEye.DistortionData.RedCoeffs.Z += step;
}
if (RenderFlags.HasFlag(RenderFlag.GreenActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) leftEye.DistortionData.GreenCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) leftEye.DistortionData.GreenCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) leftEye.DistortionData.GreenCoeffs.Z += step;
}
if (RenderFlags.HasFlag(RenderFlag.BlueActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) leftEye.DistortionData.BlueCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) leftEye.DistortionData.BlueCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) leftEye.DistortionData.BlueCoeffs.Z += step;
}
}
if (RenderFlags.HasFlag(RenderFlag.Right))
{
if (RenderFlags.HasFlag(RenderFlag.RedActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) rightEye.DistortionData.RedCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) rightEye.DistortionData.RedCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) rightEye.DistortionData.RedCoeffs.Z += step;
}
if (RenderFlags.HasFlag(RenderFlag.GreenActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) rightEye.DistortionData.GreenCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) rightEye.DistortionData.GreenCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) rightEye.DistortionData.GreenCoeffs.Z += step;
}
if (RenderFlags.HasFlag(RenderFlag.BlueActive))
{
if (RenderFlags.HasFlag(RenderFlag.K1)) rightEye.DistortionData.BlueCoeffs.X += step;
if (RenderFlags.HasFlag(RenderFlag.K2)) rightEye.DistortionData.BlueCoeffs.Y += step;
if (RenderFlags.HasFlag(RenderFlag.K3)) rightEye.DistortionData.BlueCoeffs.Z += step;
}
}
}
public static void ChangeRenderMode()
{
RenderMode = (RenderMode + 1) % 3;
pixelShaderData.Wireframe = (RenderMode == 1);
}
public static void ToggleDistortion()
{
pixelShaderData._Undistort++;
if (pixelShaderData._Undistort >= 3) pixelShaderData._Undistort = 0;
CrossHairModel.ModifyCircles(d3dDevice, 0);
//pixelShaderData.Undistort = !pixelShaderData.Undistort;
}
public static void AdjustFocus(float stepX, float stepY)
{
if (RenderFlags.HasFlag(RenderFlag.Left))
{
leftEye.DistortionData.FocalX += stepX;
leftEye.DistortionData.FocalY += stepY;
leftEye.UpdateIntrinsicsFromFocusAndCenter();
}
if (RenderFlags.HasFlag(RenderFlag.Right))
{
rightEye.DistortionData.FocalX += stepX;
rightEye.DistortionData.FocalY += stepY;
rightEye.UpdateIntrinsicsFromFocusAndCenter();
}
}
public static void AdjustGrow(float adjustStep)
{
if (RenderFlags.HasFlag(RenderFlag.Left))
{
leftEye.DistortionData.GrowToUndistort += adjustStep;
leftEye.UpdateIntrinsicsFromFocusAndCenter();
}
if (RenderFlags.HasFlag(RenderFlag.Right))
{
rightEye.DistortionData.GrowToUndistort += adjustStep;
rightEye.UpdateIntrinsicsFromFocusAndCenter();
}
}
public static void ResetToOriginalValues()
{
if (RenderFlags.HasFlag(RenderFlag.Left))
{
leftEye.DistortionData = leftEye.OriginalDistortionData;
leftEye.CalcFocusCenterAspect();
}