Updated oculus stuff

This commit is contained in:
Chris Midkiff
2018-10-09 20:59:57 -04:00
parent 1e7362c19f
commit 9b7f63739e
957 changed files with 128988 additions and 588 deletions

View File

@@ -0,0 +1,166 @@
/************************************************************************************
Filename : ONSPAmbisonicsNative.cs
Content : Native interface into the Oculus Ambisonics
Created : November 14, 2016
Authors : Peter Giokaris
Copyright : Copyright 2016 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class ONSPAmbisonicsNative : MonoBehaviour
{
#if !UNITY_5
static int numFOAChannels = 4; // we are only dealing with 1st order Ambisonics at this time
static int paramVSpeakerMode = 6; // set speaker mode (OculusAmbi or VSpeaker)
static int paramAmbiStat = 7; // use this to return internal Ambisonic status
// Staus codes that may return from Ambisonic engine
public enum ovrAmbisonicsNativeStatus
{
Uninitialized = -1, // Ambisonic stream not initialized (inital status)
NotEnabled, // Ambisonic has not been enabled on clip
Success, // Stream initialized and playing
StreamError, // Something wrong with input stream (not a 4-channel AmbiX format stream?)
ProcessError, // Handling of stream error
MaxStatValue
};
// current status
ovrAmbisonicsNativeStatus currentStatus = ovrAmbisonicsNativeStatus.Uninitialized;
// true to use Virtual Speaker output. Otherwise use OculusAmbi
[SerializeField]
private bool useVirtualSpeakers = false;
public bool UseVirtualSpeakers
{
get
{
return useVirtualSpeakers;
}
set
{
useVirtualSpeakers = value;
}
}
#endif
/// <summary>
/// OnEnable this instance.
/// </summary>
void OnEnable()
{
// Unity 4 is deprecated; UNITY_5 still valid with plug-in
#if UNITY_5
Debug.Log("Ambisonic ERROR: Ambisonic support in Unity 2017 or higher");
#else
AudioSource source = GetComponent<AudioSource>();
currentStatus = ovrAmbisonicsNativeStatus.Uninitialized;
if (source == null)
{
Debug.Log("Ambisonic ERROR: AudioSource does not exist.");
}
else
{
if(source.spatialize == true)
{
Debug.Log("Ambisonic WARNING: Turning spatialize field off for Ambisonic sources.");
source.spatialize = false;
}
if (source.clip == null)
{
Debug.Log("Ambisonic ERROR: AudioSource does not contain an audio clip.");
}
else
{
if(source.clip.channels != numFOAChannels)
{
Debug.Log("Ambisonic ERROR: AudioSource clip does not have correct number of channels.");
}
}
}
#endif
}
// Unity 4 is deprecated; UNITY_5 still valid with plug-in
#if !UNITY_5
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
AudioSource source = GetComponent<AudioSource>();
if (source == null)
{
// We already caught the error in Awake so bail
return;
}
// Set speaker mode
if(useVirtualSpeakers == true)
source.SetAmbisonicDecoderFloat(paramVSpeakerMode, 1.0f); // VSpeakerMode
else
source.SetAmbisonicDecoderFloat(paramVSpeakerMode, 0.0f); // OclusAmbi
float statusF = 0.0f;
// PGG 5/25/2017 There is a bug in the 2017.2 beta that does not
// allow for ambisonic params to be passed through to native
// from C# Get latest editor from Unity when available
source.GetAmbisonicDecoderFloat(paramAmbiStat, out statusF);
ovrAmbisonicsNativeStatus status = (ovrAmbisonicsNativeStatus)statusF;
// TODO: Add native result/error codes
if (status != currentStatus)
{
switch(status)
{
case (ovrAmbisonicsNativeStatus.NotEnabled):
Debug.Log("Ambisonic Native: Ambisonic not enabled on clip. Check clip field and turn it on");
break;
case (ovrAmbisonicsNativeStatus.Uninitialized):
Debug.Log("Ambisonic Native: Stream uninitialized");
break;
case (ovrAmbisonicsNativeStatus.Success):
Debug.Log("Ambisonic Native: Stream successfully initialized and playing/playable");
break;
case (ovrAmbisonicsNativeStatus.StreamError):
Debug.Log("Ambisonic Native WARNING: Stream error (bad input format?)");
break;
case (ovrAmbisonicsNativeStatus.ProcessError):
Debug.Log("Ambisonic Native WARNING: Stream process error (check default speaker setup)");
break;
default:
break;
}
}
currentStatus = status;
}
#endif
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: bb001ad917b86f148a2c85acdd0d5c6a
timeCreated: 1479161980
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,324 @@
/************************************************************************************
Filename : ONSPAudioSource.cs
Content : Interface into the Oculus Native Spatializer Plugin
Created : September 14, 2015
Authors : Peter Giokaris
Copyright : Copyright 2015 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
// Uncomment below to test access of read-only spatializer parameters
//#define TEST_READONLY_PARAMETERS
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
public class ONSPAudioSource : MonoBehaviour
{
#if TEST_READONLY_PARAMETERS
// Spatializer read-only system parameters (global)
static int readOnly_GlobalRelectionOn = 8;
static int readOnly_NumberOfUsedSpatializedVoices = 9;
#endif
// Import functions
public const string strONSPS = "AudioPluginOculusSpatializer";
[DllImport(strONSPS)]
private static extern void ONSP_GetGlobalRoomReflectionValues(ref bool reflOn, ref bool reverbOn,
ref float width, ref float height, ref float length);
// Public
[SerializeField]
private bool enableSpatialization = true;
public bool EnableSpatialization
{
get
{
return enableSpatialization;
}
set
{
enableSpatialization = value;
}
}
[SerializeField]
private float gain = 0.0f;
public float Gain
{
get
{
return gain;
}
set
{
gain = Mathf.Clamp(value, 0.0f, 24.0f);
}
}
[SerializeField]
private bool useInvSqr = false;
public bool UseInvSqr
{
get
{
return useInvSqr;
}
set
{
useInvSqr = value;
}
}
[SerializeField]
private float near = 1.0f;
public float Near
{
get
{
return near;
}
set
{
near = Mathf.Clamp(value, 0.0f, 1000000.0f);
}
}
[SerializeField]
private float far = 10.0f;
public float Far
{
get
{
return far;
}
set
{
far = Mathf.Clamp(value, 0.0f, 1000000.0f);
}
}
[SerializeField]
private float volumetricRadius = 0.0f;
public float VolumetricRadius
{
get
{
return volumetricRadius;
}
set
{
volumetricRadius = Mathf.Clamp(value, 0.0f, 1000.0f);
}
}
[SerializeField]
private bool enableRfl = false;
public bool EnableRfl
{
get
{
return enableRfl;
}
set
{
enableRfl = value;
}
}
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
// We might iterate through multiple sources / game object
var source = GetComponent<AudioSource>();
SetParameters(ref source);
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
// We might iterate through multiple sources / game object
var source = GetComponent<AudioSource>();
// READ-ONLY PARAMETER TEST
#if TEST_READONLY_PARAMETERS
float rfl_enabled = 0.0f;
source.GetSpatializerFloat(readOnly_GlobalRelectionOn, out rfl_enabled);
float num_voices = 0.0f;
source.GetSpatializerFloat(readOnly_NumberOfUsedSpatializedVoices, out num_voices);
String readOnly = System.String.Format
("Read only values: refl enabled: {0:F0} num voices: {1:F0}", rfl_enabled, num_voices);
Debug.Log(readOnly);
#endif
// Check to see if we should disable spatializion
if ((Application.isPlaying == false) ||
(AudioListener.pause == true) ||
(source.isPlaying == false) ||
(source.isActiveAndEnabled == false)
)
{
source.spatialize = false;
return;
}
else
{
SetParameters(ref source);
}
}
/// <summary>
/// Sets the parameters.
/// </summary>
/// <param name="source">Source.</param>
public void SetParameters(ref AudioSource source)
{
// See if we should enable spatialization
source.spatialize = enableSpatialization;
source.SetSpatializerFloat(0, gain);
// All inputs are floats; convert bool to 0.0 and 1.0
if(useInvSqr == true)
source.SetSpatializerFloat(1, 1.0f);
else
source.SetSpatializerFloat(1, 0.0f);
source.SetSpatializerFloat(2, near);
source.SetSpatializerFloat(3, far);
source.SetSpatializerFloat(4, volumetricRadius);
if(enableRfl == true)
source.SetSpatializerFloat(5, 0.0f);
else
source.SetSpatializerFloat(5, 1.0f);
}
private static ONSPAudioSource RoomReflectionGizmoAS = null;
/// <summary>
///
/// </summary>
void OnDrawGizmos()
{
// Are we the first one created? make sure to set our static ONSPAudioSource
// for drawing out room parameters once
if(RoomReflectionGizmoAS == null)
{
RoomReflectionGizmoAS = this;
}
Color c;
const float colorSolidAlpha = 0.1f;
// Draw the near/far spheres
// Near (orange)
c.r = 1.0f;
c.g = 0.5f;
c.b = 0.0f;
c.a = 1.0f;
Gizmos.color = c;
Gizmos.DrawWireSphere(transform.position, Near);
c.a = colorSolidAlpha;
Gizmos.color = c;
Gizmos.DrawSphere(transform.position, Near);
// Far (red)
c.r = 1.0f;
c.g = 0.0f;
c.b = 0.0f;
c.a = 1.0f;
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, Far);
c.a = colorSolidAlpha;
Gizmos.color = c;
Gizmos.DrawSphere(transform.position, Far);
// VolumetricRadius (purple)
c.r = 1.0f;
c.g = 0.0f;
c.b = 1.0f;
c.a = 1.0f;
Gizmos.color = c;
Gizmos.DrawWireSphere(transform.position, VolumetricRadius);
c.a = colorSolidAlpha;
Gizmos.color = c;
Gizmos.DrawSphere(transform.position, VolumetricRadius);
// Draw room parameters ONCE only, provided reflection engine is on
if (RoomReflectionGizmoAS == this)
{
// Get global room parameters (write new C api to get reflection values)
bool reflOn = false;
bool reverbOn = false;
float width = 1.0f;
float height = 1.0f;
float length = 1.0f;
ONSP_GetGlobalRoomReflectionValues(ref reflOn, ref reverbOn, ref width, ref height, ref length);
// TO DO: Get the room reflection values and render those out as well (like we do in the VST)
if((Camera.main != null) && (reflOn == true))
{
// Set color of cube (cyan is early reflections only, white is with reverb on)
if(reverbOn == true)
c = Color.white;
else
c = Color.cyan;
Gizmos.color = c;
Gizmos.DrawWireCube(Camera.main.transform.position, new Vector3(width, height, length));
c.a = colorSolidAlpha;
Gizmos.color = c;
Gizmos.DrawCube(Camera.main.transform.position, new Vector3(width, height, length));
}
}
}
/// <summary>
///
/// </summary>
void OnDestroy()
{
// We will null out single pointer instance
// of the room reflection gizmo since we are being destroyed.
// Any ONSPAS that is alive or born will re-set this pointer
// so that we only draw it once
if(RoomReflectionGizmoAS == this)
{
RoomReflectionGizmoAS = null;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e503ea6418d27594caa33b93cac1b06a
timeCreated: 1442244775
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,36 @@
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;
public class ONSPProfiler : MonoBehaviour
{
public bool profilerEnabled = false;
const int DEFAULT_PORT = 2121;
public int port = DEFAULT_PORT;
void Start()
{
Application.runInBackground = true;
}
void Update()
{
if (port < 0 || port > 65535)
{
port = DEFAULT_PORT;
}
ONSP_SetProfilerPort(port);
ONSP_SetProfilerEnabled(profilerEnabled);
}
// Import functions
public const string strONSPS = "AudioPluginOculusSpatializer";
[DllImport(strONSPS)]
private static extern int ONSP_SetProfilerEnabled(bool enabled);
[DllImport(strONSPS)]
private static extern int ONSP_SetProfilerPort(int port);
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c02d0725e6d42214c99b03a3b162f0e8
timeCreated: 1504817842
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
/************************************************************************************
Filename : ONSPVersion.cs
Content : Get version number of plug-in
Created : March 30, 2016
Authors : Peter Giokaris
Copyright : Copyright 2016 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
using UnityEngine;
using System;
using System.Runtime.InteropServices;
public class ONSPVersion : MonoBehaviour
{
// Import functions
public const string strONSPS = "AudioPluginOculusSpatializer";
[DllImport(strONSPS)]
private static extern void ONSP_GetVersion(ref int Major, ref int Minor, ref int Patch);
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
int major = 0;
int minor = 0;
int patch = 0;
ONSP_GetVersion(ref major, ref minor, ref patch);
String version = System.String.Format
("ONSP Version: {0:F0}.{1:F0}.{2:F0}", major, minor, patch);
Debug.Log(version);
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 46821b10458428648878b1b4a9113c40
timeCreated: 1459353580
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,346 @@
/************************************************************************************
Filename : OculusSpatializerUnity.cs
Content : Interface into real-time geometry reflection engine for native Unity
Created : November 27, 2017
Copyright : Copyright 2017 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
public class OculusSpatializerUnity : MonoBehaviour
{
public LayerMask layerMask = -1;
public bool visualizeRoom = true;
bool roomVisualizationInitialized = false;
public int raysPerSecond = 256;
public float roomInterpSpeed = 0.9f;
public float maxWallDistance = 50.0f;
public int rayCacheSize = 512;
public bool dynamicReflectionsEnabled = true;
AudioRaycastCallback _raycastCallback; // cache an instance of the delegate so the GC doesn't nuke it!
float particleSize = 0.2f;
float particleOffset = 0.1f;
GameObject room;
Renderer[] wallRenderer = new Renderer[6];
float[] dims = new float[3] { 1.0f, 1.0f, 1.0f };
float[] coefs = new float[6];
const int HIT_COUNT = 2048;
Vector3[] points = new Vector3[HIT_COUNT];
Vector3[] normals = new Vector3[HIT_COUNT];
ParticleSystem sys;
ParticleSystem.Particle[] particles = new ParticleSystem.Particle[HIT_COUNT];
static LayerMask gLayerMask = -1;
static Vector3 swapHandedness(Vector3 vec) { return new Vector3(vec.x, vec.y, -vec.z); }
static void AudioRaycast(Vector3 origin, Vector3 direction, out Vector3 point, out Vector3 normal, System.IntPtr data)
{
point = Vector3.zero;
normal = Vector3.zero;
RaycastHit hitInfo;
if (Physics.Raycast(swapHandedness(origin), swapHandedness(direction), out hitInfo, 1000.0f, gLayerMask.value))
{
point = swapHandedness(hitInfo.point);
normal = swapHandedness(hitInfo.normal);
}
}
void Start()
{
_raycastCallback = new AudioRaycastCallback(AudioRaycast);
OSP_Unity_AssignRaycastCallback(_raycastCallback, System.IntPtr.Zero);
}
void OnDestroy()
{
OSP_Unity_AssignRaycastCallback(System.IntPtr.Zero, System.IntPtr.Zero);
}
void Update()
{
if (dynamicReflectionsEnabled)
{
OSP_Unity_AssignRaycastCallback(_raycastCallback, System.IntPtr.Zero);
}
else
{
OSP_Unity_AssignRaycastCallback(System.IntPtr.Zero, System.IntPtr.Zero);
}
OSP_Unity_SetDynamicRoomRaysPerSecond(raysPerSecond);
OSP_Unity_SetDynamicRoomInterpSpeed(roomInterpSpeed);
OSP_Unity_SetDynamicRoomMaxWallDistance(maxWallDistance);
OSP_Unity_SetDynamicRoomRaysRayCacheSize(rayCacheSize);
gLayerMask = layerMask;
OSP_Unity_UpdateRoomModel(1.0f);
if (visualizeRoom)
{
if (!roomVisualizationInitialized)
{
inititalizeRoomVisualization();
roomVisualizationInitialized = true;
}
Vector3 pos;
OSP_Unity_GetRoomDimensions(dims, coefs, out pos);
pos.z *= -1; // swap to left-handed
var size = new Vector3(dims[0], dims[1], dims[2]);
float magSqrd = size.sqrMagnitude;
if (!float.IsNaN(magSqrd) && 0.0f < magSqrd && magSqrd < 1000000.0f)
{
transform.localScale = size * 0.999f;
}
transform.position = pos;
OSP_Unity_GetRaycastHits(points, normals, HIT_COUNT);
for (int i = 0; i < HIT_COUNT; ++i)
{
if (points[i] == Vector3.zero)
points[i].y = -10000.0f; // hide it
// swap to left-handed
points[i].z *= -1;
normals[i].z *= -1;
particles[i].position = points[i] + normals[i] * particleOffset;
if (normals[i] != Vector3.zero)
particles[i].rotation3D = Quaternion.LookRotation(normals[i]).eulerAngles;
particles[i].startSize = particleSize;
particles[i].startColor = new Color(208 / 255f, 38 / 255f, 174 / 255f, 1.0f);
}
for (int wall = 0; wall < 6; ++wall)
{
var color = Color.Lerp(Color.red, Color.green, coefs[wall]);
wallRenderer[wall].material.SetColor("_TintColor", color);
}
sys.SetParticles(particles, particles.Length);
}
}
private void inititalizeRoomVisualization()
{
Debug.Log("Oculus Audio dynamic room estimation visualization enabled");
transform.position = Vector3.zero; // move to the origin otherwise things are displaced
// Create a particle system to visualize the ray cast hits
GameObject decalManager = new GameObject("DecalManager");
decalManager.transform.parent = transform;
sys = decalManager.AddComponent<ParticleSystem>();
{
var main = sys.main;
main.simulationSpace = ParticleSystemSimulationSpace.World;
main.loop = false;
main.playOnAwake = false;
var emission = sys.emission;
emission.enabled = false;
var shape = sys.shape;
shape.enabled = false;
var renderer = sys.GetComponent<ParticleSystemRenderer>();
renderer.renderMode = ParticleSystemRenderMode.Mesh;
renderer.material.shader = Shader.Find("Particles/Additive");
Texture2D decalTex;
{
const int SIZE = 64;
const int RING_COUNT = 2;
decalTex = new Texture2D(SIZE, SIZE);
const int HALF_SIZE = SIZE / 2;
for (int i = 0; i < SIZE / 2; ++i)
{
for (int j = 0; j < SIZE / 2; ++j)
{
// distance from center
float deltaX = (float)(HALF_SIZE - i);
float deltaY = (float)(HALF_SIZE - j);
float dist = Mathf.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
float t = (RING_COUNT * dist) / HALF_SIZE;
float alpha = (dist < HALF_SIZE) ? Mathf.Clamp01(Mathf.Sin(Mathf.PI * 2.0f * t)) : 0.0f;
Color col = new Color(1.0f, 1.0f, 1.0f, alpha);
// Two way symmetry
decalTex.SetPixel(i, j, col);
decalTex.SetPixel(SIZE - i, j, col);
decalTex.SetPixel(i, SIZE - j, col);
decalTex.SetPixel(SIZE - i, SIZE - j, col);
}
}
decalTex.Apply();
}
renderer.material.mainTexture = decalTex;
// Make a quad
var m = new Mesh();
m.name = "ParticleQuad";
const float size = 0.5f;
m.vertices = new Vector3[] {
new Vector3(-size, -size, 0.0f),
new Vector3( size, -size, 0.0f),
new Vector3( size, size, 0.0f),
new Vector3(-size, size, 0.0f)
};
m.uv = new Vector2[] {
new Vector2(0, 0),
new Vector2(0, 1),
new Vector2(1, 1),
new Vector2(1, 0)
};
m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
m.RecalculateNormals();
renderer.mesh = m;
}
sys.Emit(HIT_COUNT);
// Construct the visual representation of the room
room = new GameObject("RoomVisualizer");
room.transform.parent = transform;
room.transform.localPosition = Vector3.zero;
Texture2D wallTex;
{
const int SIZE = 32;
wallTex = new Texture2D(SIZE, SIZE);
Color transparent = new Color(0.0f, 0.0f, 0.0f, 0.0f);
for (int i = 0; i < SIZE; ++i)
{
for (int j = 0; j < SIZE; ++j)
{
wallTex.SetPixel(i, j, transparent);
}
}
for (int i = 0; i < SIZE; ++i)
{
Color color1 = Color.white * 0.125f;
wallTex.SetPixel(SIZE / 4, i, color1);
wallTex.SetPixel(i, SIZE / 4, color1);
wallTex.SetPixel(3 * SIZE / 4, i, color1);
wallTex.SetPixel(i, 3 * SIZE / 4, color1);
color1 *= 2.0f;
wallTex.SetPixel(SIZE / 2, i, color1);
wallTex.SetPixel(i, SIZE / 2, color1);
color1 *= 2.0f;
wallTex.SetPixel(0, i, color1);
wallTex.SetPixel(i, 0, color1);
}
wallTex.Apply();
}
for (int wall = 0; wall < 6; ++wall)
{
var m = new Mesh();
m.name = "Plane" + wall;
const float size = 0.5f;
var verts = new Vector3[4];
int axis = wall / 2;
int sign = (wall % 2 == 0) ? 1 : -1;
for (int i = 0; i < 4; ++i)
{
verts[i][axis] = sign * size;
verts[i][(axis + 1) % 3] = size * ((i == 1 || i == 2) ? 1 : -1);
verts[i][(axis + 2) % 3] = size * ((i == 2 || i == 3) ? 1 : -1);
}
m.vertices = verts;
m.uv = new Vector2[]
{
new Vector2(0, 0),
new Vector2(0, 1),
new Vector2(1, 1),
new Vector2(1, 0)
};
m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
m.RecalculateNormals();
var go = new GameObject("Wall_" + wall);
go.AddComponent<MeshFilter>().mesh = m;
var renderer = go.AddComponent<MeshRenderer>();
wallRenderer[wall] = renderer;
renderer.material.shader = Shader.Find("Particles/Additive");
renderer.material.mainTexture = wallTex;
renderer.material.mainTextureScale = new Vector2(8, 8);
go.transform.parent = room.transform;
room.transform.localPosition = Vector3.zero;
}
}
// * * * * * * * * * * * * *
// Import functions
public delegate void AudioRaycastCallback(Vector3 origin, Vector3 direction,
out Vector3 point, out Vector3 normal,
System.IntPtr data);
private const string strOSP = "AudioPluginOculusSpatializer";
[DllImport(strOSP)]
private static extern int OSP_Unity_AssignRaycastCallback(System.MulticastDelegate callback, System.IntPtr data);
[DllImport(strOSP)]
private static extern int OSP_Unity_AssignRaycastCallback(System.IntPtr callback, System.IntPtr data);
[DllImport(strOSP)]
private static extern int OSP_Unity_SetDynamicRoomRaysPerSecond(int RaysPerSecond);
[DllImport(strOSP)]
private static extern int OSP_Unity_SetDynamicRoomInterpSpeed(float InterpSpeed);
[DllImport(strOSP)]
private static extern int OSP_Unity_SetDynamicRoomMaxWallDistance(float MaxWallDistance);
[DllImport(strOSP)]
private static extern int OSP_Unity_SetDynamicRoomRaysRayCacheSize(int RayCacheSize);
[DllImport(strOSP)]
private static extern int OSP_Unity_UpdateRoomModel(float wetLevel); // call from main thread!!
[DllImport(strOSP)]
private static extern int OSP_Unity_GetRoomDimensions(float[] roomDimensions, float[] reflectionsCoefs, out Vector3 position);
[DllImport(strOSP)]
private static extern int OSP_Unity_GetRaycastHits(Vector3[] points, Vector3[] normals, int length);
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 1e7e1ee1878326a4ea99cdd376569203
timeCreated: 1536271779
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 09f814575468d81448e92cb264792b5b
folderAsset: yes
timeCreated: 1479154551
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,166 @@
/************************************************************************************
Filename : ONSPReflectionZone.cs
Content : Add reflection zone volumes to set reflection parameters via snapshots.
Created : September 8, 2016
Authors : Peter Giokaris
Copyright : Copyright 2016 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
using System.Collections.Generic;
public struct ReflectionSnapshot
{
public AudioMixerSnapshot mixerSnapshot;
public float fadeTime;
}
public class ONSPReflectionZone : MonoBehaviour
{
public AudioMixerSnapshot mixerSnapshot = null;
public float fadeTime = 0.0f;
// Push/pop list
private static Stack<ReflectionSnapshot> snapshotList = new Stack<ReflectionSnapshot>();
private static ReflectionSnapshot currentSnapshot = new ReflectionSnapshot();
/// <summary>
/// Start this instance.
/// </summary>
void Start ()
{
}
/// <summary>
/// Update this instance.
/// </summary>
void Update ()
{
}
/// <summary>
/// Raises the trigger enter event.
/// </summary>
/// <param name="other">Other.</param>
void OnTriggerEnter(Collider other)
{
if(CheckForAudioListener(other.gameObject) == true)
{
PushCurrentMixerShapshot();
}
}
/// <summary>
/// Raises the trigger exit event.
/// </summary>
/// <param name="other">Other.</param>
void OnTriggerExit(Collider other)
{
if(CheckForAudioListener(other.gameObject) == true)
{
PopCurrentMixerSnapshot();
}
}
// * * * * * * * * * * * * *
// Private functions
/// <summary>
/// Checks for audio listener.
/// </summary>
/// <returns><c>true</c>, if for audio listener was checked, <c>false</c> otherwise.</returns>
/// <param name="gameObject">Game object.</param>
bool CheckForAudioListener(GameObject gameObject)
{
AudioListener al = gameObject.GetComponentInChildren<AudioListener>();
if(al != null)
return true;
return false;
}
/// <summary>
/// Pushs the current mixer snapshot onto the snapshot stack
/// </summary>
void PushCurrentMixerShapshot()
{
ReflectionSnapshot css = currentSnapshot;
snapshotList.Push(css);
// Set the zone reflection values
// NOTE: There will be conditions that might need resolution when dealing with volumes that
// overlap. Best practice is to never have volumes half-way inside other volumes; larger
// volumes should completely contain smaller volumes
SetReflectionValues();
}
/// <summary>
/// Pops the current reflection values from reflectionsList stack.
/// </summary>
void PopCurrentMixerSnapshot()
{
ReflectionSnapshot snapshot = snapshotList.Pop();
// Set the popped reflection values
SetReflectionValues(ref snapshot);
}
/// <summary>
/// Sets the reflection values. This is done when entering a zone (use zone values).
/// </summary>
void SetReflectionValues()
{
if (mixerSnapshot != null)
{
Debug.Log("Setting off snapshot " + mixerSnapshot.name);
mixerSnapshot.TransitionTo(fadeTime);
// Set the current snapshot to be equal to this one
currentSnapshot.mixerSnapshot = mixerSnapshot;
currentSnapshot.fadeTime = fadeTime;
}
else
{
Debug.Log("Mixer snapshot not set - Please ensure play area has at least one encompassing snapshot.");
}
}
/// <summary>
/// Sets the reflection values. This is done when exiting a zone (use popped values).
/// </summary>
/// <param name="rm">Rm.</param>
void SetReflectionValues(ref ReflectionSnapshot mss)
{
if(mss.mixerSnapshot != null)
{
Debug.Log("Setting off snapshot " + mss.mixerSnapshot.name);
mss.mixerSnapshot.TransitionTo(mss.fadeTime);
// Set the current snapshot to be equal to this one
currentSnapshot.mixerSnapshot = mss.mixerSnapshot;
currentSnapshot.fadeTime = mss.fadeTime;
}
else
{
Debug.Log("Mixer snapshot not set - Please ensure play area has at least one encompassing snapshot.");
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: cfc03cf517e91a64ba53fc31e61657ea
timeCreated: 1473375383
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: