Exemple #1
0
        protected override void OnUpdate()
        {
            foreach (var camera in Camera.allCameras.Except(_CheckedCameras).ToList())
            {
                _CheckedCameras.Add(camera);
                var judgement = VR.Interpreter.JudgeCamera(camera);
                VRLog.Debug("Detected new camera {0} Action: {1}", camera.name, judgement);
                switch (judgement)
                {
                case CameraJudgement.MainCamera:
                    VR.Camera.Copy(camera, true);
                    if (_IsEnabledEffects)
                    {
                        ApplyEffects();
                    }
                    break;

                case CameraJudgement.SubCamera:
                    VR.Camera.Copy(camera, false);
                    break;

                case CameraJudgement.GUI:
                    VR.GUI.AddCamera(camera);
                    break;

                case CameraJudgement.GUIAndCamera:
                    VR.Camera.Copy(camera, false, true);
                    VR.GUI.AddCamera(camera);
                    break;

                case CameraJudgement.Ignore:
                    break;
                }
            }
        }
Exemple #2
0
        private void CopyFX(GameObject source, GameObject target, bool disabledSourceFx = false)
        {
            // Clean
            foreach (var fx in target.GetCameraEffects())
            {
                DestroyImmediate(fx);
            }
            int comps = target.GetComponents <Component>().Length;

            VRLog.Info("Copying FX to {0}...", target.name);
            // Rebuild
            foreach (var fx in source.GetCameraEffects())
            {
                if (VR.Interpreter.IsAllowedEffect(fx))
                {
                    VRLog.Info("Copy FX: {0} (enabled={1})", fx.GetType().Name, fx.enabled);
                    var attachedFx = target.CopyComponentFrom(fx);
                    if (attachedFx)
                    {
                        VRLog.Info("Attached!");
                    }
                    attachedFx.enabled = fx.enabled;
                }
                else
                {
                    VRLog.Info("Skipping image effect {0}", fx.GetType().Name);
                }

                if (disabledSourceFx)
                {
                    fx.enabled = false;
                }
            }
            VRLog.Info("{0} components before the additions, {1} after", comps, target.GetComponents <Component>().Length);
        }
Exemple #3
0
        protected override void OnAwake()
        {
            base.OnAwake();

            var camera = Camera;

            if (!camera)
            {
                VRLog.Error("No camera found! {0}", name);
                Destroy(this);
                return;
            }

            nearClipPlane = camera.nearClipPlane;
            farClipPlane  = camera.farClipPlane;
            clearFlags    = camera.clearFlags;
            renderingPath = camera.renderingPath;
            clearStencilAfterLightingPass = camera.clearStencilAfterLightingPass;
            depthTextureMode    = camera.depthTextureMode;
            layerCullDistances  = camera.layerCullDistances;
            layerCullSpherical  = camera.layerCullSpherical;
            useOcclusionCulling = camera.useOcclusionCulling;
            backgroundColor     = camera.backgroundColor;
            cullingMask         = camera.cullingMask;
        }
Exemple #4
0
 /// <summary>
 /// Loads the settings from a file. Generic to enable handling of sub classes.
 /// </summary>
 /// <typeparam name="T">Type of the settings</typeparam>
 /// <param name="path"></param>
 /// <returns></returns>
 public static T Load <T>(string path) where T : VRSettings
 {
     try
     {
         if (!File.Exists(path))
         {
             var settings = Activator.CreateInstance <T>();
             settings.Save(path);
             return(settings);
         }
         else
         {
             var serializer = new XmlSerializer(typeof(T));
             using (var stream = new FileStream(path, FileMode.Open))
             {
                 var settings = serializer.Deserialize(stream) as T;
                 settings.Path = path;
                 return(settings);
             }
         }
     } catch (Exception e)
     {
         VRLog.Error("Fatal exception occured while loading XML! (Make sure System.Xml exists!) {0}", e);
         throw e;
     }
 }
Exemple #5
0
        /// <summary>
        /// Doesn't really work yet.
        /// </summary>
        /// <param name="blueprint"></param>
        public void CopyFX(Camera blueprint)
        {
            // Clean
            foreach (var fx in gameObject.GetCameraEffects())
            {
                DestroyImmediate(fx);
            }
            int comps = gameObject.GetComponents <Component>().Length;

            VRLog.Info("Copying FX to {0}...", gameObject.name);
            // Rebuild
            foreach (var fx in blueprint.gameObject.GetCameraEffects())
            {
                VRLog.Info("Copy FX: {0} (enabled={1})", fx.GetType().Name, fx.enabled);
                var attachedFx = gameObject.CopyComponentFrom(fx);
                if (attachedFx)
                {
                    VRLog.Info("Attached!");
                }
                attachedFx.enabled = fx.enabled;
            }

            VRLog.Info("That's all.");

            if (!SteamCam)
            {
                SteamCam = GetComponent <SteamVR_Camera>();
            }
            SteamCam.ForceLast();
            SteamCam = GetComponent <SteamVR_Camera>();
            VRLog.Info("{0} components before the additions, {1} after", comps, gameObject.GetComponents <Component>().Length);
        }
Exemple #6
0
 public void OnDisable()
 {
     try
     {
         VR.Camera.UnregisterSlave(this);
     } catch (Exception e)
     {
         VRLog.Error(e);
     }
 }
Exemple #7
0
        protected void CatchCanvas()
        {
            _VRGUICamera.targetTexture = uGuiTexture;
            var canvasList = (_Registry.Keys as ICollection <Canvas>).Where(c => c).ToList();

            //var canvasList = GameObject.FindObjectsOfType<Canvas>();
            foreach (var canvas in canvasList.Where(IsUnprocessed))
            {
                if (VR.Interpreter.IsIgnoredCanvas(canvas))
                {
                    continue;
                }

                VRLog.Debug("Add {0} [Layer: {1}, SortingLayer: {2}, SortingOrder: {3}, RenderMode: {4}, Camera: {5}, Position: {6} ]", canvas.name, LayerMask.LayerToName(canvas.gameObject.layer), canvas.sortingLayerName, canvas.sortingOrder, canvas.renderMode, canvas.worldCamera, canvas.transform.position);

                //if (canvas.name.Contains("TexFade")) continue;
                canvas.renderMode  = RenderMode.ScreenSpaceCamera;
                canvas.worldCamera = _VRGUICamera;

                // Make sure that all Canvas are in the UI layer
                if (((1 << canvas.gameObject.layer) & VR.Context.UILayerMask) == 0)
                {
                    var uiLayer = LayerMask.NameToLayer(VR.Context.UILayer);
                    canvas.gameObject.layer = uiLayer;
                    foreach (var child in canvas.gameObject.GetComponentsInChildren <Transform>())
                    {
                        child.gameObject.layer = uiLayer;
                    }
                }

                if (VR.Context.EnforceDefaultGUIMaterials)
                {
                    foreach (var child in canvas.gameObject.GetComponentsInChildren <Graphic>())
                    {
                        child.material = child.defaultMaterial;
                    }
                }

                if (VR.Context.GUIAlternativeSortingMode)
                {
                    var raycaster = canvas.GetComponent <GraphicRaycaster>();
                    if (raycaster)
                    {
                        GameObject.DestroyImmediate(raycaster);
                        var newRaycaster = canvas.gameObject.AddComponent <SortingAwareGraphicRaycaster>();

                        // These fields turned into properties in Unity 4.7+
                        UnityHelper.SetPropertyOrField(newRaycaster, "ignoreReversedGraphics", UnityHelper.GetPropertyOrField(raycaster, "ignoreReversedGraphics"));
                        UnityHelper.SetPropertyOrField(newRaycaster, "blockingObjects", UnityHelper.GetPropertyOrField(raycaster, "blockingObjects"));
                        UnityHelper.SetPropertyOrField(newRaycaster, "m_BlockingMask", UnityHelper.GetPropertyOrField(raycaster, "m_BlockingMask"));
                    }
                }
            }
        }
Exemple #8
0
        private void UpdateCameraConfig()
        {
            int cullingMask = Slaves.Aggregate(0, (cull, cam) => cull | cam.cullingMask);

            // Remove layers that are captured by other cameras (see VRGUI)
            cullingMask |= VR.Interpreter.DefaultCullingMask;
            cullingMask &= ~(LayerMask.GetMask(VR.Context.UILayer, VR.Context.InvisibleLayer));
            cullingMask &= ~(VR.Context.IgnoreMask);

            VRLog.Info("The camera sees {0} ({1})", string.Join(", ", UnityHelper.GetLayerNames(cullingMask)), string.Join(", ", Slaves.Select(s => s.name).ToArray()));
            GetComponent <Camera>().cullingMask = cullingMask;
        }
Exemple #9
0
        private IEnumerator _Invoke(Action action, float delay)
        {
            yield return(new WaitForSeconds(delay));

            try
            {
                action();
            } catch (Exception e)
            {
                VRLog.Error(e);
            }
        }
Exemple #10
0
        private IEnumerator ExecuteDelayed(Action action)
        {
            yield return(null);

            try
            {
                action();
            }
            catch (Exception e)
            {
                VRLog.Error(e);
            }
        }
Exemple #11
0
        public void AddCamera(Camera camera)
        {
            VRLog.Debug("Trying to find a GUI mapping for camera {0}", camera.name);
            var grabber = FindCameraMapping(camera);

            if (grabber != null)
            {
                _CameraMappings[camera] = grabber;
                grabber.OnAssign(camera);

                VRLog.Debug("Assigned camera {0} to {1}", camera.name, grabber);
            }
            _CheckedCameras.Add(camera);
        }
Exemple #12
0
        public static void DumpTable()
        {
            VRLog.Debug("DUMP");
            var builder = new StringBuilder();

            var enumerator = PerformanceTable.GetEnumerator();

            while (enumerator.MoveNext())
            {
                builder.AppendFormat("{1}ms: {0}\n", enumerator.Current.Key, enumerator.Current.Value / Time.realtimeSinceStartup);
            }

            File.WriteAllText("performance.txt", builder.ToString());
        }
Exemple #13
0
        private bool UseNewCamera(Camera blueprint)
        {
            if (_Blueprint && _Blueprint != _Camera && _Blueprint != blueprint)
            {
                // We already have a main camera
                if (_Blueprint.name == "Main Camera")
                {
                    VRLog.Info("Using {0} over {1} as main camera", _Blueprint.name, blueprint.name);
                    return(false);
                }
            }

            return(true);
        }
Exemple #14
0
 public void ToggleFX()
 {
     m_bFxEnabled = !m_bFxEnabled;
     foreach (var comp in SteamCam.GetComponents <MonoBehaviour>())
     {
         if (VR.Interpreter.IsAllowedEffect(comp))
         {
             comp.enabled = m_bFxEnabled;
             VRLog.Debug("Toggling FX : {0}, Enabled: {1}", comp.GetType().Name, comp.enabled);
         }
         else if (comp.GetType().Name.Equals("PostProcessingBehaviour"))
         {
             comp.enabled = m_bFxEnabled;
         }
     }
 }
Exemple #15
0
        private void UpdateCameras()
        {
            foreach (var camera in Camera.allCameras.Except(_CheckedCameras).ToList())
            {
                VRLog.Info("Judging camera {0}", camera.name);
                var grabber = FindCameraMapping(camera);
                if (grabber != null)
                {
                    _CameraMappings[camera] = grabber;
                    grabber.OnAssign(camera);

                    VRLog.Info("Assigned camera {0} to {1}", camera.name, grabber);
                }
                _CheckedCameras.Add(camera);
            }
        }
Exemple #16
0
        protected override void OnAwake()
        {
            var trackingSystem = SteamVR.instance.hmd_TrackingSystemName;

            VRLog.Debug("------------------------------------");
            VRLog.Debug(" Booting VR [{0}]", trackingSystem);
            VRLog.Debug("------------------------------------");
            HMD = trackingSystem == "oculus" ? HMDType.Oculus : trackingSystem == "lighthouse" ? HMDType.Vive : HMDType.Other;

            Application.targetFrameRate = 90;
            Time.fixedDeltaTime         = 1 / 90f;
            Application.runInBackground = true;

            GameObject.DontDestroyOnLoad(SteamVR_Render.instance.gameObject);
            GameObject.DontDestroyOnLoad(gameObject);
#if UNITY_4_5
            SteamVR_Render.instance.helpSeconds = 0;
#endif
        }
Exemple #17
0
        protected override void OnUpdate()
        {
#if !UNITY_4_5
            if (VR.Context.ConfineMouse)
            {
                Cursor.lockState = CursorLockMode.Confined;
            }
#endif
            EnsureCameraTargets();

            if (_Listeners > 0)
            {
                //Logger.Info(Time.time);
                //var watch = System.Diagnostics.Stopwatch.StartNew();
                CatchCanvas();
                //Logger.Info(watch.ElapsedTicks);
            }
            if (_Listeners < 0)
            {
                VRLog.Warn("Numbers don't add up!");
            }
        }
Exemple #18
0
        protected override void OnAwake()
        {
            VRLog.Info("Creating VR Camera");
            _Camera = gameObject.AddComponent <Camera>();
            gameObject.AddComponent <SteamVR_Camera>();
            SteamCam = GetComponent <SteamVR_Camera>();
            SteamCam.Expand(); // Expand immediately!

            if (!VR.Settings.MirrorScreen)
            {
                Destroy(SteamCam.head.GetComponent <SteamVR_GameView>());
                Destroy(SteamCam.head.GetComponent <Camera>()); // Save GPU power
            }

            // Set render scale to the value defined by the user
            SteamVR_Camera.sceneResolutionScale = VR.Settings.RenderScale;

            // Needed for the Camera Modifications mod to work. It's an artifact from DK2 days
            var legacyAnchor = new GameObject("CenterEyeAnchor");

            legacyAnchor.transform.SetParent(SteamCam.head);

            DontDestroyOnLoad(SteamCam.origin.gameObject);
        }
Exemple #19
0
        private void SafelyCall(Action action)
        {
            try
            {
                //StackFrame frame = new StackFrame(1);
                //var method = frame.GetMethod();
                //var key = GetKey(method.Name);

                //var stopWatch = Stopwatch.StartNew();

                action();

                //stopWatch.Stop();
                //if (!PerformanceTable.ContainsKey(key))
                //{
                //    PerformanceTable[key] = 0L;
                //}
                //PerformanceTable[key] += stopWatch.Elapsed.TotalMilliseconds;
            }
            catch (Exception ex)
            {
                VRLog.Error(ex);
            }
        }
Exemple #20
0
 protected virtual void Initialize(T actor)
 {
     this.Actor = actor;
     VRLog.Info("Creating character {0}", actor.name);
 }
Exemple #21
0
        protected override void OnLevel(int level)
        {
            base.OnLevel(level);

            VRLog.Info("Loaded level {0}", level);
        }
Exemple #22
0
        /// <summary>
        /// Copies the values of a in-game camera to the VR camera.
        /// </summary>
        /// <param name="blueprint">The camera to copy.</param>
        public void Copy(Camera blueprint)
        {
            VRLog.Info("Copying camera: {0}", blueprint ? blueprint.name : "NULL");
            Blueprint = blueprint ?? GetComponent <Camera>();

            int cullingMask = Blueprint.cullingMask;

            // If the camera is blind, set it to see everything instead
            if (cullingMask == 0)
            {
                cullingMask = int.MaxValue;
            }
            else
            {
                // Apply additional culling masks
                foreach (var subCamera in VR.Interpreter.FindSubCameras())
                {
                    if (!subCamera.name.Contains(SteamCam.baseName))
                    {
                        cullingMask |= subCamera.cullingMask;
                    }
                }
            }

            // Remove layers that are captured by other cameras (see VRGUI)
            cullingMask |= LayerMask.GetMask("Default");
            cullingMask &= ~(LayerMask.GetMask(VR.Context.UILayer, VR.Context.InvisibleLayer));
            cullingMask &= ~(VR.Context.IgnoreMask);
            VRLog.Info("The camera sees {0}", string.Join(", ", UnityHelper.GetLayerNames(cullingMask)));

            // Apply to both the head camera and the VR camera
            ApplyToCameras(targetCamera =>
            {
                targetCamera.nearClipPlane = 0.01f;
                targetCamera.farClipPlane  = Blueprint.farClipPlane;
                targetCamera.cullingMask   = cullingMask;
                targetCamera.clearFlags    = Blueprint.clearFlags == CameraClearFlags.Skybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;

                targetCamera.backgroundColor = Blueprint.backgroundColor;

                var skybox = Blueprint.GetComponent <Skybox>();
                if (skybox != null)
                {
                    var vrSkybox = targetCamera.gameObject.GetComponent <Skybox>();
                    if (vrSkybox == null)
                    {
                        vrSkybox = vrSkybox.gameObject.AddComponent <Skybox>();
                    }

                    vrSkybox.material = skybox.material;
                }

                // Hook
                InitializeCamera(this, new InitializeCameraEventArgs(targetCamera, Blueprint));
            });

            // Only execute this code when the blueprint is a different camera
            HasValidBlueprint = Blueprint != GetComponent <Camera>();
            if (HasValidBlueprint)
            {
                //StartCoroutine(ExecuteDelayed(delegate { CopyFX(Blueprint); }));
                //CopyFX(Blueprint);

                Blueprint.cullingMask   = 0;
                Blueprint.nearClipPlane = Blueprint.farClipPlane = 0;

                //Blueprint.targetTexture = _MiniTexture;
                //Blueprint.gameObject.AddComponent<BlacklistThrottler>();

                // Highlander principle
                var listener = Blueprint.GetComponent <AudioListener>();
                if (listener)
                {
                    Destroy(listener);
                }
            }
        }
 protected virtual void Initialize(T actor)
 {
     Actor = actor;
     VRLog.Debug("Creating character {0}", actor.name);
 }
Exemple #24
0
 internal void UnregisterSlave(CameraSlave slave)
 {
     VRLog.Info("Camera went offline: {0}", slave.name);
     Slaves.Remove(slave);
     UpdateCameraConfig();
 }
Exemple #25
0
 internal void RegisterSlave(CameraSlave slave)
 {
     VRLog.Info("Camera went online: {0}", slave.name);
     Slaves.Add(slave);
     UpdateCameraConfig();
 }
Exemple #26
0
        /// <summary>
        /// Copies the values of a in-game camera to the VR camera.
        /// </summary>
        /// <param name="blueprint">The camera to copy.</param>
        public void Copy(Camera blueprint, bool master = false, bool hasOtherConsumers = false)
        {
            VRLog.Info("Copying camera: {0}", blueprint ? blueprint.name : "NULL");

            if (blueprint && blueprint.GetComponent <CameraSlave>())
            {
                VRLog.Warn("Is already slave -- NOOP");
                return;
            }

            if (master && UseNewCamera(blueprint))
            {
                _Blueprint = blueprint ?? _Camera;

                // Apply to both the head camera and the VR camera
                ApplyToCameras(targetCamera =>
                {
                    targetCamera.nearClipPlane = VR.Context.NearClipPlane / 100;
                    targetCamera.farClipPlane  = Mathf.Max(Blueprint.farClipPlane, MIN_FAR_CLIP_PLANE);
                    targetCamera.clearFlags    = Blueprint.clearFlags == CameraClearFlags.Skybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
                    targetCamera.renderingPath = Blueprint.renderingPath;
                    targetCamera.clearStencilAfterLightingPass = Blueprint.clearStencilAfterLightingPass;
                    targetCamera.depthTextureMode    = Blueprint.depthTextureMode;
                    targetCamera.layerCullDistances  = Blueprint.layerCullDistances;
                    targetCamera.layerCullSpherical  = Blueprint.layerCullSpherical;
                    targetCamera.useOcclusionCulling = Blueprint.useOcclusionCulling;
                    targetCamera.hdr = false;

                    targetCamera.backgroundColor = Blueprint.backgroundColor;

                    var skybox = Blueprint.GetComponent <Skybox>();
                    if (skybox != null)
                    {
                        var vrSkybox = targetCamera.gameObject.GetComponent <Skybox>();
                        if (vrSkybox == null)
                        {
                            vrSkybox = targetCamera.gameObject.AddComponent <Skybox>();
                        }

                        vrSkybox.material = skybox.material;
                    }

                    foreach (var comp in blueprint.GetComponents <MonoBehaviour>())
                    {
                        if (targetCamera.gameObject.GetComponent(comp.GetType()) == null)
                        {
                            if (VR.Interpreter.IsAllowedEffect(comp))
                            {
                                VRLog.Debug("Copy FX " + comp.GetType().Name);
                                var cp       = targetCamera.gameObject.CopyComponentFrom(comp);
                                cp.enabled   = comp.enabled;
                                m_bFxEnabled = true;
                                FixEffectOrder();
                            }
                        }
                    }
                });
            }

            if (blueprint)
            {
                blueprint.gameObject.AddComponent <CameraSlave>();

                // Highlander principle
                var listener = blueprint.GetComponent <AudioListener>();
                if (listener)
                {
                    Destroy(listener);
                }

                if (!hasOtherConsumers && blueprint.targetTexture == null && VR.Interpreter.IsIrrelevantCamera(blueprint))
                {
                    //StartCoroutine(ExecuteDelayed(delegate { CopyFX(Blueprint); }));
                    //CopyFX(Blueprint);

                    blueprint.gameObject.AddComponent <CameraKiller>();
                    //blueprint.enabled = false;
                    //blueprint.nearClipPlane = Blueprint.farClipPlane = 0;

                    //Blueprint.targetTexture = _MiniTexture;
                    //Blueprint.gameObject.AddComponent<BlacklistThrottler>();
                }
            }

            if (master)
            {
                // Hook
                InitializeCamera(this, new InitializeCameraEventArgs(GetComponent <Camera>(), Blueprint));
            }

            CopiedCamera(this, new CopiedCameraEventArgs(blueprint));
        }