-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathOsvrRenderManager.cs
386 lines (342 loc) · 15 KB
/
OsvrRenderManager.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
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2014 Sensics, Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </copyright>
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System;
namespace OSVR
{
namespace Unity
{
//*This class is a wrapper for the OSVR-Unity Rendering Plugin osvrUnityRenderingPlugin.dll,
// which brings in functionality from the OSVR RenderManager project. RenderManager features inculde:
// - DirectMode -- compatible with nVidia cards with a driver that has been modified to white-list the display that you are using.
// - TimeWarp
// - Distortion Correction
//
// osvrUnityRenderingPlugin.dll, osvrRenderManager.dll, SDL2.dll, and glew32.dll must be in the Plugins/x86 or x64 folders.
// Requires Unity 5.2+
//*/
public class OsvrRenderManager : MonoBehaviour
{
[StructLayout(LayoutKind.Sequential)]
private struct OSVR_ProjectionMatrix
{
public double left;
public double right;
public double top;
public double bottom;
public double nearClip; //< Cannot name "near" because Visual Studio keyword
public double farClip;
}
[StructLayout(LayoutKind.Sequential)]
private struct OSVR_ViewportDescription
{
public double left; //< Left side of the viewport in pixels
public double lower; //< First pixel in the viewport at the bottom.
public double width; //< Last pixel in the viewport at the top
public double height; //< Last pixel on the right of the viewport in pixels
}
public const int RENDER_EVENT = 0;
public const int SHUTDOWN_EVENT = 1;
public const int UPDATE_RENDERINFO_EVENT = 2;
private const string PluginName = "osvrUnityRenderingPlugin";
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
private delegate void DebugLog(string log);
private static readonly DebugLog debugLog = DebugWrapper;
private static readonly IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(debugLog);
private static void DebugWrapper(string log) { Debug.Log(log); }
//Create and Register RenderBuffers
[DllImport(PluginName)]
private static extern Byte
ConstructRenderBuffers();
//Create a RenderManager object in the plugin, passing in a ClientContext
[DllImport(PluginName)]
private static extern Byte
CreateRenderManagerFromUnity(OSVR.ClientKit.SafeClientContextHandle /*OSVR_ClientContext*/ ctx);
[DllImport(PluginName)]
private static extern OSVR.ClientKit.Pose3
GetEyePose(Byte eye);
[DllImport(PluginName)]
private static extern OSVR_ProjectionMatrix
GetProjectionMatrix(Byte eye);
//get the render event function that we'll call every frame via GL.IssuePluginEvent
[DllImport(PluginName)]
private static extern IntPtr
GetRenderEventFunc();
[DllImport(PluginName)]
private static extern OSVR_ViewportDescription
GetViewport(Byte eye);
// Allow for calling into the debug console from C++
[DllImport(PluginName)]
private static extern void
LinkDebug([MarshalAs(UnmanagedType.FunctionPtr)]IntPtr debugCal);
// OnRenderEvent is not needed
// Pass a pointer to a texture (RenderTexture.GetNativeTexturePtr()) to the plugin
// @todo native code may change the return type to OSVR_ReturnCode.
// If so, change the return type here to Byte
[DllImport(PluginName)]
private static extern int
SetColorBufferFromUnity(System.IntPtr texturePtr, Byte eye);
[DllImport(PluginName)]
private static extern void
SetFarClipDistance(double farClipPlaneDistance);
[DllImport(PluginName)]
private static extern void
SetIPD(double ipdMeters);
[DllImport(PluginName)]
private static extern void
SetNearClipDistance(double nearClipPlaneDistance);
[DllImport(PluginName)]
private static extern void
ShutdownRenderManager();
// UnityPluginLoad is not needed
// UnityPluginUnload is not needed
private bool _linkDebug = false; //causes crash on exit if true, only enable for debugging
//persistent singleton
private static OsvrRenderManager _instance;
/// <summary>
/// Use to access the single instance of this object/script in your game.
/// </summary>
/// <returns>The instance, or null in case of error</returns>
public static OsvrRenderManager instance
{
get
{
if (_instance == null)
{
_instance = GameObject.FindObjectOfType<OsvrRenderManager>();
if (_instance == null)
{
Debug.LogError("[OSVR-Unity] RenderManager not found.");
}
else
{
DontDestroyOnLoad(_instance.gameObject);
}
}
return _instance;
}
}
void Awake()
{
//if an instance of this singleton does not exist, set the instance to this object and make it persist
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(this);
}
else
{
//if an instance of this singleton already exists, destroy this one
if (_instance != this)
{
Destroy(this.gameObject);
}
}
}
void OnDisable()
{
ExitRenderManager();
}
//Initialize use of RenderManager via CreateRenderManager call
public int InitRenderManager()
{
if (_linkDebug)
{
//this will cause a crash when exiting the Unity editor or an application
//only use for debugging purposes, do not leave on for release.
LinkDebug(functionPointer); // Hook our c++ plugin into Unity's console log.
}
return CreateRenderManager(ClientKit.instance.context);
}
//Create and Register RenderBuffers in RenderManager
//Called after RM is created and after Unity RenderTexture's are created and assigned via SetEyeColorBuffer
public int ConstructBuffers()
{
return ConstructRenderBuffers();
}
public void SetNearClippingPlaneDistance(float near)
{
SetNearClipDistance((double)near);
}
public void SetFarClippingPlaneDistance(float far)
{
SetFarClipDistance((double)far);
}
public void SetIPDMeters(float ipd)
{
SetIPD((double)ipd);
}
//"Recenter" based on current head orientation
public void SetRoomRotationUsingHead()
{
#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5
ClientKit.instance.context.SetRoomRotationUsingHead();
GL.IssuePluginEvent(GetRenderEventFunc(), 3);
#endif
}
//Clear the room-to-world transform, undo a call to SetRoomRotationUsingHead
public void ClearRoomToWorldTransform()
{
#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5
ClientKit.instance.context.ClearRoomToWorldTransform();
GL.IssuePluginEvent(GetRenderEventFunc(), 4);
#endif
}
//Get the pose of a given eye from RenderManager
public OSVR.ClientKit.Pose3 GetRenderManagerEyePose(Byte eye)
{
return GetEyePose(eye);
}
//Get the viewport of a given eye from RenderManager
public OSVR.ClientKit.Viewport GetEyeViewport(Byte eye)
{
OSVR.ClientKit.Viewport v = new OSVR.ClientKit.Viewport();
OSVR_ViewportDescription viewportDescription = GetViewport((Byte)eye);
v.Left = (int)viewportDescription.left;
v.Bottom = (int)viewportDescription.lower;
v.Width = (int)viewportDescription.width;
v.Height = (int)viewportDescription.height;
return v;
}
//Get the projection matrix of a given eye from RenderManager
public Matrix4x4 GetEyeProjectionMatrix(Byte eye)
{
OSVR_ProjectionMatrix pm = GetProjectionMatrix((Byte)eye);
return PerspectiveOffCenter((float)pm.left, (float)pm.right, (float)pm.bottom, (float)pm.top, (float)pm.nearClip, (float)pm.farClip);
}
//Returns a Unity Matrix4x4 from the provided boundaries
//from http://docs.unity3d.com/ScriptReference/Camera-projectionMatrix.html
static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far)
{
if (right - left == 0 || top - bottom == 0 || far - near == 0)
{
Debug.LogError("Aborting Projection Matrix calculation to avoid DivideByZero error.");
return new Matrix4x4();
}
float x = 2.0F * near / (right - left);
float y = 2.0F * near / (top - bottom);
float a = (right + left) / (right - left);
float b = (top + bottom) / (top - bottom);
float c = -(far + near) / (far - near);
float d = -(2.0F * far * near) / (far - near);
float e = -1.0F;
Matrix4x4 m = new Matrix4x4();
m[0, 0] = x;
m[0, 1] = 0;
m[0, 2] = a;
m[0, 3] = 0;
m[1, 0] = 0;
m[1, 1] = y;
m[1, 2] = b;
m[1, 3] = 0;
m[2, 0] = 0;
m[2, 1] = 0;
m[2, 2] = c;
m[2, 3] = d;
m[3, 0] = 0;
m[3, 1] = 0;
m[3, 2] = e;
m[3, 3] = 0;
return m;
}
//Call the Unity Rendering Plugin to initialize the RenderManager
public int CreateRenderManager(OSVR.ClientKit.ClientContext clientContext)
{
int result;
try
{
result = CreateRenderManagerFromUnity(clientContext.ContextHandle);
}
catch (DllNotFoundException e)
{
result = -1;
Debug.LogError("[OSVR-Unity] Could not load " + e.Message +
"\nosvrUnityRenderingPlugin.dll, or one of its dependencies, is missing from the project " +
"or architecture doesn't match.\n");
}
return result;
}
//Pass pointer to eye-camera RenderTexture to the Unity Rendering Plugin
public void SetEyeColorBuffer(IntPtr colorBuffer, Byte eye)
{
SetColorBufferFromUnity(colorBuffer, eye);
}
//Get a pointer to the plugin's rendering function
public IntPtr GetRenderEventFunction()
{
return GetRenderEventFunc();
}
//Shutdown RenderManager and Dispose of the ClientContext we created for it
public void ExitRenderManager()
{
ShutdownRenderManager();
}
//helper functions to determine is RenderManager is supported
//Is the RenderManager supported? Requires D3D11 or OpenGL, currently.
public bool IsRenderManagerSupported()
{
bool support = true;
#if UNITY_ANDROID
Debug.Log("[OSVR-Unity] RenderManager not yet supported on Android.");
support = false;
#endif
if (!SystemInfo.graphicsDeviceVersion.Contains("OpenGL") && !SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"))
{
Debug.LogError("[OSVR-Unity] RenderManager not supported on " +
SystemInfo.graphicsDeviceVersion + ". Only Direct3D11 is currently supported.");
support = false;
}
if (!SystemInfo.supportsRenderTextures)
{
Debug.LogError("[OSVR-Unity] RenderManager not supported. RenderTexture (Unity Pro feature) is unavailable.");
support = false;
}
if (!IsUnityVersionSupported())
{
Debug.LogError("[OSVR-Unity] RenderManager not supported. Unity 5.2+ is required for RenderManager support.");
support = false;
}
return support;
}
//Unity 5.2+ is required as the plugin uses the native plugin interface introduced in Unity 5.2
public bool IsUnityVersionSupported()
{
bool support = true;
try
{
string version = new Regex(@"(\d+\.\d+)\..*").Replace(Application.unityVersion, "$1");
if (new Version(version) < new Version("5.2"))
{
support = false;
}
}
catch
{
Debug.LogWarning("[OSVR-Unity] Unable to determine Unity version from: " + Application.unityVersion);
support = false;
}
return support;
}
}
}
}