/// <summary>
        /// Starts up and selects a device's camera, and finds appropriate picture settings
        /// based on the provided resolution!
        /// </summary>
        /// <param name="preferGPUTexture">Do you prefer GPU textures, or do you prefer a NativeArray of colors? Certain optimizations may be present to take advantage of this preference.</param>
        /// <param name="resolution">Preferred resolution for taking pictures, note that resolutions are not guaranteed! Refer to CameraResolution for details.</param>
        /// <param name="onInitialized">When the camera is initialized, this callback is called! Some cameras may return immediately, others may take a while. Can be null.</param>
        public void Initialize(bool aPreferGPUTexture, CameraResolution aResolution, Action aOnInitialized)
        {
            resolution = aResolution;
            Resolution cameraResolution = resolution.nativeResolution == NativeResolutionMode.Smallest ?
                                          PhotoCapture.SupportedResolutions.OrderBy((res) => res.width * res.height).First() :
                                          PhotoCapture.SupportedResolutions.OrderBy((res) => - res.width * res.height).First();

            cacheTex = new Texture2D(cameraResolution.width, cameraResolution.height);

            // Create a PhotoCapture object
            PhotoCapture.CreateAsync(false, delegate(PhotoCapture captureObject)
            {
                camera       = captureObject;
                cameraParams = new CameraParameters();
                cameraParams.hologramOpacity        = 0.0f;
                cameraParams.cameraResolutionWidth  = cameraResolution.width;
                cameraParams.cameraResolutionHeight = cameraResolution.height;
                cameraParams.pixelFormat            = CapturePixelFormat.BGRA32;

                IntPtr unknown = camera.GetUnsafePointerToVideoDeviceController();
                using (VideoDeviceControllerWrapperUWP wrapper = new VideoDeviceControllerWrapperUWP(unknown))
                {
                    wrapper.SetExposure(-7);
                    wrapper.SetWhiteBalance(5000);
                    wrapper.SetISO(80);
                }

                if (aOnInitialized != null)
                {
                    aOnInitialized();
                }

                isReady = true;
            });
        }
        private void OnEnable()
        {
            // Save initial settings in case we wish to restore them
            startSky = RenderSettings.skybox;
            // Save initial light settings
            if (directionalLight != null)
            {
                startLightColor      = directionalLight.color;
                startLightRot        = directionalLight.transform.rotation;
                startLightBrightness = directionalLight.intensity;
                UpdateDirectionalLight();
            }

            probe.mode = UnityEngine.Rendering.ReflectionProbeMode.Custom;

            CameraResolution resolution = new CameraResolution();

            resolution.nativeResolution = NativeResolutionMode.Smallest;
            resolution.resize           = ResizeWhen.Never;

            captureCamera.Initialize(true, resolution, () =>
            {
                if (map == null)
                {
                    map = new CubeMapper();
                    map.Create(captureCamera.FieldOfView * stampFovMultiplier, mapResolution);
                    map.StampExpireDistance = stampExpireDistance;
                }
                probe.customBakedTexture   = map.Map;
                RenderSettings.skybox      = map.SkyMaterial;
                RenderSettings.ambientMode = AmbientMode.Skybox;
            });

            DynamicGI.UpdateEnvironment();
        }
        private void OnEnable()
        {
            // Save initial settings in case we wish to restore them
            startSky = RenderSettings.skybox;

            probe.mode = UnityEngine.Rendering.ReflectionProbeMode.Custom;

            CameraResolution resolution = new CameraResolution();

            resolution.nativeResolution = NativeResolutionMode.Smallest;
            resolution.resize           = ResizeWhen.Never;

            captureCamera.Initialize(true, resolution, () =>
            {
                if (map == null)
                {
                    map = new CubeMapper();
                    map.Create(captureCamera.FieldOfView * stampFovMultiplier, mapResolution);
                    map.StampExpireDistance = stampExpireDistance;
                }
                probe.customBakedTexture   = map.Map;
                RenderSettings.skybox      = map.SkyMaterial;
                RenderSettings.ambientMode = AmbientMode.Skybox;
            });
        }
        /// <summary>
        /// Starts up and selects a device's camera, and finds appropriate picture settings
        /// based on the provided resolution!
        /// </summary>
        /// <param name="preferGPUTexture">Do you prefer GPU textures, or do you prefer a NativeArray of colors? Certain optimizations may be present to take advantage of this preference.</param>
        /// <param name="resolution">Preferred resolution for taking pictures, note that resolutions are not guaranteed! Refer to CameraResolution for details.</param>
        /// <param name="onInitialized">When the camera is initialized, this callback is called! Some cameras may return immediately, others may take a while. Can be null.</param>
        public void Initialize(bool aPreferGPUTexture, CameraResolution aResolution, Action aOnInitialized)
        {
            resolution        = aResolution;
            lastProjMatrix    = Matrix4x4.identity;
            lastDisplayMatrix = Matrix4x4.identity;

            Action <ARSessionStateChangedEventArgs> handler = null;

            handler = (aState) =>
            {
                // Camera and orientation data aren't ready until ARFoundation is actually tracking!
                if (aState.state == ARSessionState.SessionTracking)
                {
                    ARSession.stateChanged -= handler;
                    ready = true;
                    if (aOnInitialized != null)
                    {
                        aOnInitialized();
                    }
                }
            };
            ARSession.stateChanged += handler;

            cameraManager = GameObject.FindObjectOfType <ARCameraManager>();
            if (cameraManager == null)
            {
                Debug.LogError("CameraCapture needs an ARCameraManager to be present in the scene!");
                return;
            }
            cameraManager.frameReceived += OnFrameReceived;
        }
        /// <summary>
        /// Internal version of initialize. Should not be called more than once unless Shutdown has been called.
        /// </summary>
        /// <param name="preferGPUTexture">
        /// Whether GPU textures are preferred over NativeArray of colors. Certain optimizations may be present to take advantage of this preference.
        /// </param>
        /// <param name="preferredResolution">
        /// Preferred resolution for taking pictures. Note that resolutions are not guaranteed! Refer to CameraResolution for details.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that represents the operation.
        /// </returns>
        private async Task InnerInitializeAsync(bool preferGPUTexture, CameraResolution preferredResolution)
        {
            // Store preferred resolution
            resolution = preferredResolution;

            // Find the nearest supported camera resolution to the preferred one
            Resolution cameraResolution = resolution.nativeResolution == NativeResolutionMode.Smallest ?
                                          PhotoCapture.SupportedResolutions.OrderBy((res) => res.width * res.height).First() :
                                          PhotoCapture.SupportedResolutions.OrderBy((res) => - res.width * res.height).First();

            // Create the texture cache
            cacheTex = new Texture2D(cameraResolution.width, cameraResolution.height);

            // Setup parameters for the camera
            cameraParams = new CameraParameters();
            cameraParams.hologramOpacity        = 0.0f;
            cameraParams.cameraResolutionWidth  = cameraResolution.width;
            cameraParams.cameraResolutionHeight = cameraResolution.height;
            cameraParams.pixelFormat            = CapturePixelFormat.BGRA32;

            // Create the PhotoCapture camera
            camera = await CameraExtensions.CreateAsync(false);

            // Create the wrapper
            IntPtr unknown = camera.GetUnsafePointerToVideoDeviceController();

            wrapper = new VideoDeviceControllerWrapperUWP(unknown);
        }
Beispiel #6
0
        /// <inheritdoc/>
        public Task InitializeAsync(bool preferGPUTexture, CameraResolution preferredResolution)
        {
            // Store
            resolution = preferredResolution;
            ready      = true;

            // Already complete
            return(Task.CompletedTask);
        }
Beispiel #7
0
        /// <inheritdoc/>
        public async Task InitializeAsync(bool preferGPUTexture, CameraResolution preferredResolution)
        {
            // Avoid double initialization
            if (webcamTex != null)
            {
                throw new InvalidOperationException($"{nameof(CameraCaptureWebcam)} {nameof(InitializeAsync)} should only be called once unless it is shut down.");
            }

            // No cameras? Ditch out!
            if (WebCamTexture.devices.Length <= 0)
            {
                Debug.LogWarning($"Could not initialize {nameof(CameraCaptureWebcam)} because there are no webcams attached to the system.");
                return;
            }

            // Store parameters
            resolution = preferredResolution;

            // Find a rear facing camera we can use, or use the first one
            WebCamDevice[] devices = WebCamTexture.devices;
            device = devices[0];
            for (int i = 0; i < devices.Length; i++)
            {
                if (!devices[i].isFrontFacing || devices[i].name.ToLower().Contains("rear"))
                {
                    device = devices[i];
                }
            }

            // Pick a camera resolution
            if (resolution.nativeResolution == NativeResolutionMode.Largest)
            {
                webcamTex = new WebCamTexture(device.name, 10000, 10000, 2);
            }
            else if (resolution.nativeResolution == NativeResolutionMode.Smallest)
            {
                webcamTex = new WebCamTexture(device.name, 1, 1, 2);
            }
            else if (resolution.nativeResolution == NativeResolutionMode.Closest)
            {
                webcamTex = new WebCamTexture(device.name, resolution.size.x, resolution.size.y, 2);
            }
            else
            {
                throw new NotImplementedException(resolution.nativeResolution.ToString());
            }

            // Start the webcam playing
            webcamTex.Play();

            // Bookmark the start time
            startTime = Time.time;

            // Wait for camera to initialize
            await Task.Delay(TimeSpan.FromSeconds(CAMERA_START_DELAY));
        }
        /// <summary>
        /// Starts up and selects a device's camera, and finds appropriate picture settings
        /// based on the provided resolution!
        /// </summary>
        /// <param name="preferGPUTexture">Do you prefer GPU textures, or do you prefer a NativeArray of colors? Certain optimizations may be present to take advantage of this preference.</param>
        /// <param name="resolution">Preferred resolution for taking pictures, note that resolutions are not guaranteed! Refer to CameraResolution for details.</param>
        /// <param name="onInitialized">When the camera is initialized, this callback is called! Some cameras may return immediately, others may take a while. Can be null.</param>
        public void Initialize(bool aPreferGPUTexture, CameraResolution aResolution, Action aOnInitialized)
        {
            resolution = aResolution;
            ready      = true;

            if (aOnInitialized != null)
            {
                aOnInitialized();
            }
        }
        /// <summary>
        /// Starts up and selects a device's camera, and finds appropriate picture settings
        /// based on the provided resolution!
        /// </summary>
        /// <param name="preferGPUTexture">Do you prefer GPU textures, or do you prefer a NativeArray of colors? Certain optimizations may be present to take advantage of this preference.</param>
        /// <param name="resolution">Preferred resolution for taking pictures, note that resolutions are not guaranteed! Refer to CameraResolution for details.</param>
        /// <param name="onInitialized">When the camera is initialized, this callback is called! Some cameras may return immediately, others may take a while. Can be null.</param>
        public void Initialize(bool aPreferGPUTexture, CameraResolution aResolution, Action aOnInitialized)
        {
            if (webcamTex != null)
            {
                throw new Exception("[CameraCapture] Only need to initialize once!");
            }
            // No cameras? Ditch out!
            if (WebCamTexture.devices.Length <= 0)
            {
                return;
            }

            resolution = aResolution;

            // Find a rear facing camera we can use, or use the first one
            WebCamDevice[] devices = WebCamTexture.devices;
            device = devices[0];
            for (int i = 0; i < devices.Length; i++)
            {
                if (!devices[i].isFrontFacing || devices[i].name.ToLower().Contains("rear"))
                {
                    device = devices[i];
                }
            }

            // Pick a camera resolution
            if (resolution.nativeResolution == NativeResolutionMode.Largest)
            {
                webcamTex = new WebCamTexture(device.name, 10000, 10000, 2);
            }
            else if (resolution.nativeResolution == NativeResolutionMode.Smallest)
            {
                webcamTex = new WebCamTexture(device.name, 1, 1, 2);
            }
            else if (resolution.nativeResolution == NativeResolutionMode.Closest)
            {
                webcamTex = new WebCamTexture(device.name, resolution.size.x, resolution.size.y, 2);
            }
            else
            {
                throw new NotImplementedException(resolution.nativeResolution.ToString());
            }

            webcamTex.Play();

            if (aOnInitialized != null)
            {
                aOnInitialized();
            }
            startTime = Time.time;
        }
        /// <inheritdoc/>
        public Task InitializeAsync(bool preferGPUTexture, CameraResolution preferredResolution)
        {
            // Make sure not initialized or initializing
            if (initializeTask != null)
            {
                throw new InvalidOperationException("Already initializing.");
            }

            // Now initializing
            initializeTask = InnerInitializeAsync(preferGPUTexture, preferredResolution);

            // Return task in process
            return(initializeTask);
        }
        /// <inheritdoc/>
        public Task InitializeAsync(bool preferGPUTexture, CameraResolution preferredResolution)
        {
            // Store values
            resolution        = preferredResolution;
            lastProjMatrix    = Matrix4x4.identity;
            lastDisplayMatrix = Matrix4x4.identity;

            // Before moving on, make sure we have an AR camera manager
            cameraManager = GameObject.FindObjectOfType <ARCameraManager>();
            if (cameraManager == null)
            {
                throw new InvalidOperationException("CameraCapture needs an ARCameraManager to be present in the scene!");
            }

            // Subscribe to camera frame changes
            cameraManager.frameReceived += OnFrameReceived;

            // Create a completion source to handle AR Foundation initializing asynchronously
            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();

            // Create a handler for the AR Session to start
            Action <ARSessionStateChangedEventArgs> handler = null;

            handler = (aState) =>
            {
                // Camera and orientation data aren't ready until ARFoundation is actually tracking!
                if (aState.state == ARSessionState.SessionTracking)
                {
                    // Now that we're tracking, the handler is no longer needed
                    ARSession.stateChanged -= handler;

                    // And we're ready
                    ready = true;

                    // Signal complete
                    tcs.SetResult(true);
                }
            };

            // Subscribe to session state changes
            ARSession.stateChanged += handler;

            // Return the completion source task to allow someone to await initialization
            return(tcs.Task);
        }
        private async void OnEnable()
        {
            Texture2D tex = new Texture2D(1, 1);

            tex.hideFlags = HideFlags.HideAndDontSave;
            tex.SetPixels(new Color[] { new Color(1, 1, 1, 0) });
            tex.Apply();

            previewStyle = new GUIStyle();
            previewStyle.normal.background = tex;

            cam = new CameraCaptureWebcam(null, Camera.main.fieldOfView);

            CameraResolution resolution = new CameraResolution();

            resolution.nativeResolution = NativeResolutionMode.Largest;
            resolution.resize           = ResizeWhen.Never;

            await cam.InitializeAsync(true, resolution);
        }
Beispiel #13
0
        /// <summary>
        /// Starts up and selects a device's camera, and finds appropriate picture settings
        /// based on the provided resolution!
        /// </summary>
        /// <param name="preferGPUTexture">Do you prefer GPU textures, or do you prefer a NativeArray of colors? Certain optimizations may be present to take advantage of this preference.</param>
        /// <param name="resolution">Preferred resolution for taking pictures, note that resolutions are not guaranteed! Refer to CameraResolution for details.</param>
        /// <param name="onInitialized">When the camera is initialized, this callback is called! Some cameras may return immediately, others may take a while. Can be null.</param>
        public void Initialize(bool aPreferGPUTexture, CameraResolution aResolution, Action aOnInitialized)
        {
            resolution = aResolution;

            Action <ARSystemStateChangedEventArgs> handler = null;

            handler = (aState) =>
            {
                // Camera and orientation data aren't ready until ARFoundation is actually tracking!
                if (aState.state == ARSystemState.SessionTracking)
                {
                    ARSubsystemManager.systemStateChanged -= handler;
                    ready = true;
                    if (aOnInitialized != null)
                    {
                        aOnInitialized();
                    }
                }
            };
            ARSubsystemManager.systemStateChanged += handler;
        }