Beispiel #1
0
    private void UpdateParameters()
    {
        // update raytracing scene, in case something moved
        _rtas.Build();

        // frustum corners for current camera transform
        Vector3 bottomLeft  = _camera.ViewportToWorldPoint(new Vector3(0, 0, _camera.farClipPlane)).normalized;
        Vector3 topLeft     = _camera.ViewportToWorldPoint(new Vector3(0, 1, _camera.farClipPlane)).normalized;
        Vector3 bottomRight = _camera.ViewportToWorldPoint(new Vector3(1, 0, _camera.farClipPlane)).normalized;
        Vector3 topRight    = _camera.ViewportToWorldPoint(new Vector3(1, 1, _camera.farClipPlane)).normalized;

        // update camera, environment parameters
        _rayTracingShader.SetVector("_SkyColor", SkyColor.gamma);
        _rayTracingShader.SetVector("_GroundColor", GroundColor.gamma);

        _rayTracingShader.SetVector("_TopLeftFrustumDir", topLeft);
        _rayTracingShader.SetVector("_TopRightFrustumDir", topRight);
        _rayTracingShader.SetVector("_BottomLeftFrustumDir", bottomLeft);
        _rayTracingShader.SetVector("_BottomRightFrustumDir", bottomRight);

        _rayTracingShader.SetVector("_CameraPos", _camera.transform.position);

        _cameraWorldMatrix = _camera.transform.localToWorldMatrix;

        // reset accumulation frame counter
        _frameIndex = 0;
    }
Beispiel #2
0
    void Update()
    {
        HDRenderPipeline hdrp = RenderPipelineManager.currentPipeline is HDRenderPipeline ? (HDRenderPipeline)RenderPipelineManager.currentPipeline : null;

        if (hdrp != null)
        {
            // Get the HDCamera for the current camera
            var hdCamera = HDCamera.GetOrCreate(GetComponent <Camera>());

            // Evaluate the effect params
            HDEffectsParameters hdEffectParams = HDRenderPipeline.EvaluateEffectsParameters(hdCamera, true, false);

            // Clear the rtas from the previous frame
            if (rtas != null)
            {
                rtas.Dispose();
            }

            // Create the RTAS
            rtas = new RayTracingAccelerationStructure();

            // Add all the objects individually
            int numGameObjects = gameObjects.Count;
            for (int i = 0; i < numGameObjects; ++i)
            {
                HDRenderPipeline.AddInstanceToRAS(rtas, gameObjects[i].GetComponent <Renderer>(), hdEffectParams, ref hdCamera.transformsDirty, ref hdCamera.materialsDirty);
            }

            // Build the RTAS
            rtas.Build(transform.position);

            // Assign it to the camera
            hdCamera.rayTracingAccelerationStructure = rtas;
        }
    }
Beispiel #3
0
    private void InitRaytracingAccelerationStructure()
    {
        RayTracingAccelerationStructure.RASSettings settings = new RayTracingAccelerationStructure.RASSettings();
        // include all layers
        settings.layerMask = ~0;
        // enable automatic updates
        settings.managementMode = RayTracingAccelerationStructure.ManagementMode.Automatic;
        // include all renderer types
        settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;

        _rtas = new RayTracingAccelerationStructure(settings);

        // not necessary in automatic mode
        // collect all objects in scene and add them to raytracing scene
        // Renderer[] renderers = FindObjectsOfType<Renderer>();
        // foreach(Renderer r in renderers)
        //  _rtas.AddInstance(r);

        // build raytracing scene
        _rtas.Build();

        // RTAS could also be the one from (internal)
        // HDRenderPipeline.RequestAccelerationStructure();
        // reset with
        // HDRenderPipeline.ResetPathTracing();
    }
 void Start()
 {
     if (!SystemInfo.supportsRayTracing)
     {
         Debug.Log("Ray Tracing not supported !");
     }
     _Camera        = GetComponent <Camera>();
     _RenderTarget0 = new RenderTexture(_Camera.pixelWidth, _Camera.pixelHeight, 0, RenderTextureFormat.ARGBFloat);
     _RenderTarget0.enableRandomWrite = true;
     _RenderTarget0.Create();
     _RenderTarget1 = new RenderTexture(_RenderTarget0);
     _RenderTarget2 = new RenderTexture(_RenderTarget0);
     RayTracingAccelerationStructure.RASSettings settings = new RayTracingAccelerationStructure.RASSettings();
     settings.layerMask          = ~0;
     settings.managementMode     = RayTracingAccelerationStructure.ManagementMode.Automatic;
     settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;
     _AccelerationStructure      = new RayTracingAccelerationStructure(settings);
     Renderer[] renderers = FindObjectsOfType <Renderer>();
     for (int i = 0; i < renderers.Length; i++)
     {
         Material[] materials = renderers[i].sharedMaterials;
         for (int j = 0; j < materials.Length; j++)
         {
             materials[j] = new Material(IndirectDiffuseShader);
         }
         renderers[i].sharedMaterials = materials;
         _AccelerationStructure.AddInstance(renderers[i]);
     }
     _AccelerationStructure.Build();
     PathTracingShader.SetAccelerationStructure("_AccelerationStructure", _AccelerationStructure);
     PathTracingShader.SetTexture("_RenderTarget", _RenderTarget0);
     PathTracingShader.SetShaderPass("PathTracingRTX");
     _Material = new Material(ProgressiveShader);
     Reset();
 }
Beispiel #5
0
    private void InitRaytracingAccelerationStructure()
    {
        RayTracingAccelerationStructure.RASSettings settings = new RayTracingAccelerationStructure.RASSettings();
        // include default layer, not lights
        settings.layerMask = -1;
        // enable automatic updates
        settings.managementMode = RayTracingAccelerationStructure.ManagementMode.Manual;
        // include all renderer types
        settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;

        _accelerationStructure = new RayTracingAccelerationStructure(settings);

        // collect all objects in scene and add them to raytracing scene
        Renderer[] renderers = FindObjectsOfType <Renderer>();
        foreach (Renderer r in renderers)
        {
            if (r.CompareTag("Light"))
            {
                // mask for lights is 0x10 (for shadow rays - dont want to check for intersection in some cases)
                _accelerationStructure.AddInstance(r, null, null, true, false, 0x10);
            }
            else
            {
                _accelerationStructure.AddInstance(r, null, null, true, false, 0x01);
            }
        }

        // build raytracing AS
        _accelerationStructure.Build();
    }
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (!SystemInfo.supportsRayTracing || !rayTracingShader)
        {
            Debug.Log("The RayTracing API is not supported by this GPU or by the current graphics API.");
            Graphics.Blit(src, dest);
            return;
        }

        if (rayTracingAccelerationStructure == null)
        {
            return;
        }

        if (prevCameraMatrix != Camera.main.cameraToWorldMatrix)
        {
            convergenceStep = 0;
        }

        if (prevBounceCountOpaque != bounceCountOpaque)
        {
            convergenceStep = 0;
        }

        if (prevBounceCountTransparent != bounceCountTransparent)
        {
            convergenceStep = 0;
        }

        // Not really needed per frame if the scene is static.
        rayTracingAccelerationStructure.Build();

        rayTracingShader.SetShaderPass("PathTracing");

        Shader.SetGlobalInt(Shader.PropertyToID("g_BounceCountOpaque"), (int)bounceCountOpaque);
        Shader.SetGlobalInt(Shader.PropertyToID("g_BounceCountTransparent"), (int)bounceCountTransparent);

        // Input
        rayTracingShader.SetAccelerationStructure(Shader.PropertyToID("g_AccelStruct"), rayTracingAccelerationStructure);
        rayTracingShader.SetFloat(Shader.PropertyToID("g_Zoom"), Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView * 0.5f));
        rayTracingShader.SetFloat(Shader.PropertyToID("g_AspectRatio"), cameraWidth / (float)cameraHeight);
        rayTracingShader.SetInt(Shader.PropertyToID("g_ConvergenceStep"), convergenceStep);
        rayTracingShader.SetInt(Shader.PropertyToID("g_FrameIndex"), Time.frameCount);
        rayTracingShader.SetTexture(Shader.PropertyToID("g_EnvTex"), envTexture);

        // Output
        rayTracingShader.SetTexture(Shader.PropertyToID("g_Radiance"), rayTracingOutput);

        rayTracingShader.Dispatch("MainRayGenShader", (int)cameraWidth, (int)cameraHeight, 1, Camera.main);

        Graphics.Blit(rayTracingOutput, dest);

        convergenceStep++;

        prevCameraMatrix           = Camera.main.cameraToWorldMatrix;
        prevBounceCountOpaque      = bounceCountOpaque;
        prevBounceCountTransparent = bounceCountTransparent;
    }
Beispiel #7
0
        private void InitRTMannager()
        {
            InfinityRenderPipelineAsset PipelineAsset = (InfinityRenderPipelineAsset)GraphicsSettings.currentRenderPipeline;

            if (TracingAccelerationStructure == null && PipelineAsset.EnableRayTracing == true)
            {
                RayTracingAccelerationStructure.RASSettings TracingAccelerationStructureSetting = new RayTracingAccelerationStructure.RASSettings(RayTracingAccelerationStructure.ManagementMode.Automatic, RayTracingAccelerationStructure.RayTracingModeMask.Everything, -1 ^ (1 << 9));
                TracingAccelerationStructure = new RayTracingAccelerationStructure(TracingAccelerationStructureSetting);
                TracingAccelerationStructure.Build();//
            }
        }
Beispiel #8
0
		private void DoRayTracingOutline(CustomPassContext ctx)
		{
			ctx.cmd.SetRayTracingShaderPass(rayTracingOutlineShader, "JTRPRayTracingOutline");
			if (ShaderConfig.s_CameraRelativeRendering != 0)
				_outlineRAS.Build(ctx.hdCamera.camera.transform.position);
			else
				_outlineRAS.Build();
			if (outlineRenderers != null)
				foreach (var renderer in outlineRenderers)
					if (renderer != null)
						_outlineRAS.UpdateInstanceTransform(renderer);
			ctx.cmd.SetRayTracingAccelerationStructure(rayTracingOutlineShader, "_RaytracingAccelerationStructure",
													   _outlineRAS);
			ctx.cmd.SetRayTracingTextureParam(rayTracingOutlineShader, "RenderTarget", ctx.cameraColorBuffer);
			ctx.cmd.SetRayTracingTextureParam(rayTracingOutlineShader, "_DepthTexture", ctx.cameraDepthBuffer);
			ctx.cmd.SetRayTracingTextureParam(rayTracingOutlineShader, "_OutlineMask", _outlineMask);
			ctx.cmd.DispatchRays(rayTracingOutlineShader, "RayTracingOutlineRaygen",
								 (uint)ctx.cameraColorBuffer.rt.width,
								 (uint)ctx.cameraColorBuffer.rt.height, 1);
		}
    private void InitRaytracingAccelerationStructure()
    {
        _rtas = new RayTracingAccelerationStructure();

        // collect all objects in scene and add them to raytracing scene
        Renderer[] renderers = FindObjectsOfType <Renderer>();
        foreach (Renderer r in renderers)
        {
            _rtas.AddInstance(r);
        }

        // build raytrasing scene
        _rtas.Build();
    }
    //build the ray tracing acceleration structure.
    private void BuildAccelerationStructure()
    {
        if (null == SceneManager.Instance || !SceneManager.Instance._isDirty)
        {
            return;
        }

        _rayTracingAccelerationStructure.Dispose();
        _rayTracingAccelerationStructure = new RayTracingAccelerationStructure();
        SceneManager.Instance.FillAccelerationStructure(ref _rayTracingAccelerationStructure);

        _rayTracingAccelerationStructure.Build();

        SceneManager.Instance._isDirty = false;
    }
    /// <summary>
    /// build acceleration structure.
    /// </summary>
    public void BuildAccelerationStructure()
    {
        accelerationStructure?.Dispose();
        accelerationStructure = new RayTracingAccelerationStructure();

        var subMeshFlagArray   = new bool[32];
        var subMeshCutoffArray = new bool[32];

        for (var i = 0; i < 32; ++i)
        {
            subMeshFlagArray[i]   = true;
            subMeshCutoffArray[i] = false;
        }
        foreach (var r in colliders)
        {
            accelerationStructure.AddInstance(r, subMeshFlagArray, subMeshCutoffArray);
        }
        accelerationStructure.Build();
    }
    void CreateRTAS()
    {
        RayTracingAccelerationStructure.RASSettings settings = new RayTracingAccelerationStructure.RASSettings();

        settings.layerMask = ~0;

        settings.managementMode = RayTracingAccelerationStructure.ManagementMode.Automatic;

        settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;



        _RTAS = new RayTracingAccelerationStructure(settings);

        renderers = FindObjectsOfType <Renderer>();
        for (int i = 0; i < renderers.Length; i++)
        {
            _RTAS.AddInstance(renderers[i]);
        }
        _RTAS.Build();
    }
    private void InitRaytracingAccelerationStructure()
    {
        RayTracingAccelerationStructure.RASSettings settings = new RayTracingAccelerationStructure.RASSettings();
        // include all layers
        settings.layerMask = ~0;
        // enable automatic updates
        settings.managementMode = RayTracingAccelerationStructure.ManagementMode.Automatic;
        // include all renderer types
        settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;

        _rtas = new RayTracingAccelerationStructure(settings);

        // collect all objects in scene and add them to raytracing scene
        Renderer[] renderers = FindObjectsOfType <Renderer>();
        foreach (Renderer r in renderers)
        {
            _rtas.AddInstance(r);
        }

        // build raytrasing scene
        _rtas.Build();
    }
    public void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        var cam = Camera.main;

        if (!CheckResources(cam))
        {
            Graphics.Blit(src, dest);
            return;
        }

        //-- shader pass "RTPass" in material shaders
        rtShader.SetShaderPass("RTPass");

        //- set global variables, used in all material shaders
        Shader.SetGlobalVector(ShaderID._T_minmax, new Vector2(tMin, tMax));

        //-- set local RT raygen shader variables
        _rtAccStructure.Build();
        rtShader.SetAccelerationStructure(ShaderID._SceneAccelerationStructure, _rtAccStructure);

        rtShader.SetTexture(ShaderID._RenderTarget, _rtTargetTexture);
        rtShader.SetMatrix(ShaderID._InvViewMatrix, cam.cameraToWorldMatrix);
        rtShader.SetTexture(ShaderID._EnvironmentTex, environmentCubemap);
        rtShader.SetFloat(ShaderID._EnvironmentGamma, Mathf.GammaToLinearSpace(environmentExposure));
        rtShader.SetFloat(ShaderID._ShadowBrightness, shadowBrightness);

        var camOrigin = cam.transform.position;
        var frustumBottomLeftDirWS  = (cam.ViewportToWorldPoint(new Vector3(0, 0, cam.nearClipPlane)) - camOrigin).normalized;
        var frustumBottomRightDirWS = (cam.ViewportToWorldPoint(new Vector3(1, 0, cam.nearClipPlane)) - camOrigin).normalized;
        var frustumTopLeftDirWS     = (cam.ViewportToWorldPoint(new Vector3(0, 1, cam.nearClipPlane)) - camOrigin).normalized;

        rtShader.SetVector(ShaderID._FrustumBottomLeftDirWS, frustumBottomLeftDirWS);
        rtShader.SetVector(ShaderID._FrustumHorizDirWS, frustumBottomRightDirWS - frustumBottomLeftDirWS);
        rtShader.SetVector(ShaderID._FrustumVertDirWS, frustumTopLeftDirWS - frustumBottomLeftDirWS);

        //-- dispatch ray tracing
        rtShader.Dispatch("RaygenShader", cam.pixelWidth, cam.pixelHeight, 1);
        Graphics.Blit(_rtTargetTexture, dest);
    }
Beispiel #15
0
        internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera)
        {
            // Clear all the per frame-data
            m_RayTracingRendererReference.Clear();
            m_RayTracingLights.hdDirectionalLightArray.Clear();
            m_RayTracingLights.hdPointLightArray.Clear();
            m_RayTracingLights.hdLineLightArray.Clear();
            m_RayTracingLights.hdRectLightArray.Clear();
            m_RayTracingLights.hdLightArray.Clear();
            m_RayTracingLights.reflectionProbeArray.Clear();
            m_RayTracingLights.lightCount = 0;
            m_CurrentRAS.Dispose();
            m_CurrentRAS             = new RayTracingAccelerationStructure();
            m_ValidRayTracingState   = false;
            m_ValidRayTracingCluster = false;

            bool rayTracedShadow = false;

            // fetch all the lights in the scene
            HDAdditionalLightData[] hdLightArray = UnityEngine.GameObject.FindObjectsOfType <HDAdditionalLightData>();

            for (int lightIdx = 0; lightIdx < hdLightArray.Length; ++lightIdx)
            {
                HDAdditionalLightData hdLight = hdLightArray[lightIdx];
                if (hdLight.enabled)
                {
                    // Check if there is a ray traced shadow in the scene
                    rayTracedShadow |= (hdLight.useRayTracedShadows || (hdLight.useContactShadow.@override && hdLight.rayTraceContactShadow));

                    switch (hdLight.type)
                    {
                    case HDLightType.Directional:
                        m_RayTracingLights.hdDirectionalLightArray.Add(hdLight);
                        break;

                    case HDLightType.Point:
                    case HDLightType.Spot:
                        m_RayTracingLights.hdPointLightArray.Add(hdLight);
                        break;

                    case HDLightType.Area:
                        switch (hdLight.areaLightShape)
                        {
                        case AreaLightShape.Rectangle:
                            m_RayTracingLights.hdRectLightArray.Add(hdLight);
                            break;

                        case AreaLightShape.Tube:
                            m_RayTracingLights.hdLineLightArray.Add(hdLight);
                            break;
                            //TODO: case AreaLightShape.Disc:
                        }
                        break;
                    }
                }
            }

            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdPointLightArray);
            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdLineLightArray);
            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdRectLightArray);

            HDAdditionalReflectionData[] reflectionProbeArray = UnityEngine.GameObject.FindObjectsOfType <HDAdditionalReflectionData>();
            for (int reflIdx = 0; reflIdx < reflectionProbeArray.Length; ++reflIdx)
            {
                HDAdditionalReflectionData reflectionProbe = reflectionProbeArray[reflIdx];
                // Add it to the list if enabled
                if (reflectionProbe.enabled)
                {
                    m_RayTracingLights.reflectionProbeArray.Add(reflectionProbe);
                }
            }

            m_RayTracingLights.lightCount = m_RayTracingLights.hdPointLightArray.Count
                                            + m_RayTracingLights.hdLineLightArray.Count
                                            + m_RayTracingLights.hdRectLightArray.Count
                                            + m_RayTracingLights.reflectionProbeArray.Count;

            AmbientOcclusion      aoSettings          = hdCamera.volumeStack.GetComponent <AmbientOcclusion>();
            ScreenSpaceReflection reflSettings        = hdCamera.volumeStack.GetComponent <ScreenSpaceReflection>();
            GlobalIllumination    giSettings          = hdCamera.volumeStack.GetComponent <GlobalIllumination>();
            RecursiveRendering    recursiveSettings   = hdCamera.volumeStack.GetComponent <RecursiveRendering>();
            PathTracing           pathTracingSettings = hdCamera.volumeStack.GetComponent <PathTracing>();

            LODGroup[] lodGroupArray = UnityEngine.GameObject.FindObjectsOfType <LODGroup>();
            for (var i = 0; i < lodGroupArray.Length; i++)
            {
                // Grab the current LOD group
                LODGroup lodGroup = lodGroupArray[i];

                // Get the set of LODs
                LOD[] lodArray = lodGroup.GetLODs();
                for (int lodIdx = 0; lodIdx < lodArray.Length; ++lodIdx)
                {
                    LOD currentLOD = lodArray[lodIdx];
                    // We only want to push to the acceleration structure the lod0, we do not have defined way to select the right LOD at the moment
                    if (lodIdx == 0)
                    {
                        for (int rendererIdx = 0; rendererIdx < currentLOD.renderers.Length; ++rendererIdx)
                        {
                            // Fetch the renderer that we are interested in
                            Renderer currentRenderer = currentLOD.renderers[rendererIdx];

                            // This objects should but included into the RAS
                            AddInstanceToRAS(currentRenderer,
                                             rayTracedShadow,
                                             aoSettings.rayTracing.value, aoSettings.layerMask.value,
                                             reflSettings.rayTracing.value, reflSettings.layerMask.value,
                                             giSettings.rayTracing.value, giSettings.layerMask.value,
                                             recursiveSettings.enable.value, recursiveSettings.layerMask.value,
                                             pathTracingSettings.enable.value, pathTracingSettings.layerMask.value);
                        }
                    }

                    // Add them to the processed set so that they are not taken into account when processing all the renderers
                    for (int rendererIdx = 0; rendererIdx < currentLOD.renderers.Length; ++rendererIdx)
                    {
                        Renderer currentRenderer = currentLOD.renderers[rendererIdx];
                        // Add this fella to the renderer list
                        m_RayTracingRendererReference.Add(currentRenderer.GetInstanceID(), 1);
                    }
                }
            }

            // Grab all the renderers from the scene
            var rendererArray = UnityEngine.GameObject.FindObjectsOfType <Renderer>();

            for (var i = 0; i < rendererArray.Length; i++)
            {
                // Fetch the current renderer
                Renderer currentRenderer = rendererArray[i];

                // If it is not active skip it
                if (currentRenderer.enabled == false)
                {
                    continue;
                }

                // Grab the current game object
                GameObject gameObject = currentRenderer.gameObject;

                // Has this object already been processed, just skip it
                if (m_RayTracingRendererReference.ContainsKey(currentRenderer.GetInstanceID()))
                {
                    continue;
                }

                // Does this object have a reflection probe component? if yes we do not want to have it in the acceleration structure
                if (gameObject.TryGetComponent <ReflectionProbe>(out reflectionProbe))
                {
                    continue;
                }

                // This objects should but included into the RAS
                AddInstanceToRAS(currentRenderer,
                                 rayTracedShadow,
                                 aoSettings.rayTracing.value, aoSettings.layerMask.value,
                                 reflSettings.rayTracing.value, reflSettings.layerMask.value,
                                 giSettings.rayTracing.value, giSettings.layerMask.value,
                                 recursiveSettings.enable.value, recursiveSettings.layerMask.value,
                                 pathTracingSettings.enable.value, pathTracingSettings.layerMask.value);
            }

            // build the acceleration structure
            m_CurrentRAS.Build();

            // tag the structures as valid
            m_ValidRayTracingState = true;
        }
        internal void BuildRayTracingAccelerationStructure(HDCamera hdCamera)
        {
            // Clear all the per frame-data
            m_RayTracingRendererReference.Clear();
            m_RayTracingLights.hdDirectionalLightArray.Clear();
            m_RayTracingLights.hdPointLightArray.Clear();
            m_RayTracingLights.hdLineLightArray.Clear();
            m_RayTracingLights.hdRectLightArray.Clear();
            m_RayTracingLights.hdLightArray.Clear();
            m_RayTracingLights.reflectionProbeArray.Clear();
            m_RayTracingLights.lightCount = 0;
            m_CurrentRAS.Dispose();
            m_CurrentRAS                      = new RayTracingAccelerationStructure();
            m_ValidRayTracingState            = false;
            m_ValidRayTracingCluster          = false;
            m_ValidRayTracingClusterCulling   = false;
            m_RayTracedShadowsRequired        = false;
            m_RayTracedContactShadowsRequired = false;

            // If the camera does not have a ray tracing frame setting
            // or it is a preview camera (due to the fact that the sphere does not exist as a game object we can't create the RTAS)
            // we do not want to build a RTAS
            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) || hdCamera.camera.cameraType == CameraType.Preview)
            {
                return;
            }

            // We only support ray traced shadows if the camera supports ray traced shadows
            bool screenSpaceShadowsSupported = hdCamera.frameSettings.IsEnabled(FrameSettingsField.ScreenSpaceShadows);

            // fetch all the lights in the scene
            HDAdditionalLightData[] hdLightArray = UnityEngine.GameObject.FindObjectsOfType <HDAdditionalLightData>();

            for (int lightIdx = 0; lightIdx < hdLightArray.Length; ++lightIdx)
            {
                HDAdditionalLightData hdLight = hdLightArray[lightIdx];
                if (hdLight.enabled)
                {
                    // Check if there is a ray traced shadow in the scene
                    m_RayTracedShadowsRequired        |= (hdLight.useRayTracedShadows && screenSpaceShadowsSupported);
                    m_RayTracedContactShadowsRequired |= (hdLight.useContactShadow.@override && hdLight.rayTraceContactShadow);

                    switch (hdLight.type)
                    {
                    case HDLightType.Directional:
                        m_RayTracingLights.hdDirectionalLightArray.Add(hdLight);
                        break;

                    case HDLightType.Point:
                    case HDLightType.Spot:
                        m_RayTracingLights.hdPointLightArray.Add(hdLight);
                        break;

                    case HDLightType.Area:
                        switch (hdLight.areaLightShape)
                        {
                        case AreaLightShape.Rectangle:
                            m_RayTracingLights.hdRectLightArray.Add(hdLight);
                            break;

                        case AreaLightShape.Tube:
                            m_RayTracingLights.hdLineLightArray.Add(hdLight);
                            break;
                            //TODO: case AreaLightShape.Disc:
                        }
                        break;
                    }
                }
            }

            // Aggregate the shadow requirement
            bool rayTracedShadows = m_RayTracedShadowsRequired || m_RayTracedContactShadowsRequired;

            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdPointLightArray);
            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdLineLightArray);
            m_RayTracingLights.hdLightArray.AddRange(m_RayTracingLights.hdRectLightArray);

            HDAdditionalReflectionData[] reflectionProbeArray = UnityEngine.GameObject.FindObjectsOfType <HDAdditionalReflectionData>();
            for (int reflIdx = 0; reflIdx < reflectionProbeArray.Length; ++reflIdx)
            {
                HDAdditionalReflectionData reflectionProbe = reflectionProbeArray[reflIdx];
                // Add it to the list if enabled
                if (reflectionProbe.enabled)
                {
                    m_RayTracingLights.reflectionProbeArray.Add(reflectionProbe);
                }
            }

            m_RayTracingLights.lightCount = m_RayTracingLights.hdPointLightArray.Count
                                            + m_RayTracingLights.hdLineLightArray.Count
                                            + m_RayTracingLights.hdRectLightArray.Count
                                            + m_RayTracingLights.reflectionProbeArray.Count;

            AmbientOcclusion      aoSettings          = hdCamera.volumeStack.GetComponent <AmbientOcclusion>();
            bool                  rtAOEnabled         = aoSettings.rayTracing.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSAO);
            ScreenSpaceReflection reflSettings        = hdCamera.volumeStack.GetComponent <ScreenSpaceReflection>();
            bool                  rtREnabled          = reflSettings.enabled.value && reflSettings.rayTracing.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSR);
            GlobalIllumination    giSettings          = hdCamera.volumeStack.GetComponent <GlobalIllumination>();
            bool                  rtGIEnabled         = giSettings.enable.value && giSettings.rayTracing.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SSGI);
            RecursiveRendering    recursiveSettings   = hdCamera.volumeStack.GetComponent <RecursiveRendering>();
            bool                  rrEnabled           = recursiveSettings.enable.value;
            SubSurfaceScattering  sssSettings         = hdCamera.volumeStack.GetComponent <SubSurfaceScattering>();
            bool                  rtSSSEnabled        = sssSettings.rayTracing.value && hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering);
            PathTracing           pathTracingSettings = hdCamera.volumeStack.GetComponent <PathTracing>();
            bool                  ptEnabled           = pathTracingSettings.enable.value;

            // We need to check if we should be building the ray tracing acceleration structure (if required by any effect)
            bool rayTracingRequired = rtAOEnabled || rtREnabled || rtGIEnabled || rrEnabled || rtSSSEnabled || ptEnabled || rayTracedShadows;

            if (!rayTracingRequired)
            {
                return;
            }

            // We need to process the emissive meshes of the rectangular area lights
            for (var i = 0; i < m_RayTracingLights.hdRectLightArray.Count; i++)
            {
                // Fetch the current renderer of the rectangular area light (if any)
                MeshRenderer currentRenderer = m_RayTracingLights.hdRectLightArray[i].emissiveMeshRenderer;

                // If there is none it means that there is no emissive mesh for this light
                if (currentRenderer == null)
                {
                    continue;
                }

                // This objects should be included into the RAS
                AddInstanceToRAS(currentRenderer,
                                 rayTracedShadows,
                                 rtAOEnabled, aoSettings.layerMask.value,
                                 rtREnabled, reflSettings.layerMask.value,
                                 rtGIEnabled, giSettings.layerMask.value,
                                 rrEnabled, recursiveSettings.layerMask.value,
                                 ptEnabled, pathTracingSettings.layerMask.value);
            }

            int matCount = m_MaterialCRCs.Count;

            LODGroup[] lodGroupArray = UnityEngine.GameObject.FindObjectsOfType <LODGroup>();
            for (var i = 0; i < lodGroupArray.Length; i++)
            {
                // Grab the current LOD group
                LODGroup lodGroup = lodGroupArray[i];

                // Get the set of LODs
                LOD[] lodArray = lodGroup.GetLODs();
                for (int lodIdx = 0; lodIdx < lodArray.Length; ++lodIdx)
                {
                    LOD currentLOD = lodArray[lodIdx];
                    // We only want to push to the acceleration structure the lod0, we do not have defined way to select the right LOD at the moment
                    if (lodIdx == 0)
                    {
                        for (int rendererIdx = 0; rendererIdx < currentLOD.renderers.Length; ++rendererIdx)
                        {
                            // Fetch the renderer that we are interested in
                            Renderer currentRenderer = currentLOD.renderers[rendererIdx];

                            // This objects should but included into the RAS
                            AddInstanceToRAS(currentRenderer,
                                             rayTracedShadows,
                                             aoSettings.rayTracing.value, aoSettings.layerMask.value,
                                             reflSettings.rayTracing.value, reflSettings.layerMask.value,
                                             giSettings.rayTracing.value, giSettings.layerMask.value,
                                             recursiveSettings.enable.value, recursiveSettings.layerMask.value,
                                             pathTracingSettings.enable.value, pathTracingSettings.layerMask.value);
                        }
                    }

                    // Add them to the processed set so that they are not taken into account when processing all the renderers
                    for (int rendererIdx = 0; rendererIdx < currentLOD.renderers.Length; ++rendererIdx)
                    {
                        Renderer currentRenderer = currentLOD.renderers[rendererIdx];
                        // Add this fella to the renderer list
                        // Unfortunately, we need to check that this renderer was not already pushed into the list (happens if the user uses the same mesh renderer
                        // for two LODs)
                        if (!m_RayTracingRendererReference.ContainsKey(currentRenderer.GetInstanceID()))
                        {
                            m_RayTracingRendererReference.Add(currentRenderer.GetInstanceID(), 1);
                        }
                    }
                }
            }

            // Grab all the renderers from the scene
            var rendererArray = UnityEngine.GameObject.FindObjectsOfType <Renderer>();

            for (var i = 0; i < rendererArray.Length; i++)
            {
                // Fetch the current renderer
                Renderer currentRenderer = rendererArray[i];

                // If it is not active skip it
                if (currentRenderer.enabled == false)
                {
                    continue;
                }

                // Grab the current game object
                GameObject gameObject = currentRenderer.gameObject;

                // Has this object already been processed, just skip it
                if (m_RayTracingRendererReference.ContainsKey(currentRenderer.GetInstanceID()))
                {
                    continue;
                }

                // Does this object have a reflection probe component? if yes we do not want to have it in the acceleration structure
                if (gameObject.TryGetComponent <ReflectionProbe>(out reflectionProbe))
                {
                    continue;
                }

                // This objects should be included into the RAS
                AddInstanceToRAS(currentRenderer,
                                 rayTracedShadows,
                                 aoSettings.rayTracing.value, aoSettings.layerMask.value,
                                 reflSettings.rayTracing.value, reflSettings.layerMask.value,
                                 giSettings.rayTracing.value, giSettings.layerMask.value,
                                 recursiveSettings.enable.value, recursiveSettings.layerMask.value,
                                 pathTracingSettings.enable.value, pathTracingSettings.layerMask.value);
            }

            // Check if the amount of materials being tracked has changed
            m_MaterialsDirty |= (matCount != m_MaterialCRCs.Count);

            // build the acceleration structure
            m_CurrentRAS.Build();

            // tag the structures as valid
            m_ValidRayTracingState = true;
        }
Beispiel #17
0
 private void Update()
 {
     Render();
     _rtas.Build();
     DispatchRays();
 }
Beispiel #18
0
    public void Update()
    {
        // if loading world is not enabled, build AS and return
        if (!Settings.Instance.loadWorld)
        {
            if (_accelerationStructure != null)
            {
                _accelerationStructure.UpdateInstanceTransform(sun.GetComponent <Renderer>());
                _accelerationStructure.Build();
            }

            return;
        }

        _radius = Settings.Instance.WorldRadius;

        if (runningJobs > 0)
        {
            runningJobs = 0;
            JobHandle.CompleteAll(_jobHandles);
        }
        if (_jobHandlesAlocated)
        {
            _jobHandles.Dispose();
        }
        _jobHandles         = new NativeList <JobHandle>(Allocator.Persistent);
        _jobHandlesAlocated = true;

        // If camera moved to another chunk, generate new chunks in multiple phases
        Vector3Int chunkWherePlayerStands = ChunkWherePlayerStands();

        if ((!chunkWherePlayerStands.Equals(_chunkWherePlayerStood) || _prevRadius != _radius) && phase == Phase.Resting)
        {
            _chunkWherePlayerStood = chunkWherePlayerStands;

            int radiusInChunks = _chunkSize * _radius;
            FindMissingChunks(chunkWherePlayerStands, radiusInChunks);

            if (_toGenerate.Count > 0)
            {
                _iter = _toGenerate.Count - 1;
                phase = Phase.GeneratingBlocks;
            }
            else if (_prevRadius != _radius)
            {
                phase = Phase.RemovingChunks;
            }
            else
            {
                phase = Phase.Resting;
            }

            _prevRadius = _radius;
        }
        else if (phase == Phase.GeneratingBlocks)
        {
            for (; _iter >= 0 && runningJobs < _maxJobsAtOnce * 5; _iter--)
            {
                _jobHandles.Add(_toGenerate[_iter].GenerateBlocks(centroids));
                runningJobs++;
            }

            if (_iter < 0)
            {
                phase = Phase.GeneratingMeshData;
                _iter = _toGenerate.Count - 1;
            }
        }
        else if (phase == Phase.GeneratingMeshData)
        {
            for (; _iter >= 0 && runningJobs <= _maxJobsAtOnce * 4; _iter--)
            {
                if (!_toGenerate[_iter].IsEmpty())
                {
                    _jobHandles.Add(_toGenerate[_iter].GenerateMeshData());
                    _toGenerate[_iter].PrepareMesh();
                    runningJobs++;
                }
            }

            if (_iter < 0)
            {
                phase = Phase.GeneratingFlora;
                _iter = _toGenerate.Count - 1;
            }
        }
        else if (phase == Phase.GeneratingFlora)
        {
            for (; _iter >= 0 && runningJobs <= _maxJobsAtOnce * 4; _iter--)
            {
                if (_toGenerate[_iter].AreTrees())
                {
                    _jobHandles.Add(_toGenerate[_iter].GenerateTrees());
                    runningJobs++;
                }
            }

            if (_iter < 0)
            {
                phase = Phase.FillingMeshes;
                _iter = _toGenerate.Count - 1;
            }
        }
        else if (phase == Phase.FillingMeshes)
        {
            int runningFinishes = 0;

            for (; _iter >= 0 && runningFinishes < 2; _iter--)
            {
                if (!_toGenerate[_iter].IsEmpty())
                {
                    runningFinishes += _toGenerate[_iter].FinishCreatingChunk();
                    _accelerationStructure.AddInstance(_toGenerate[_iter].chunk.GetComponent <Renderer>(), null, null, true, false, 0x01);
                }
            }

            if (_iter < 0)
            {
                phase = Phase.RemovingChunks;
                _toGenerate.Clear();
            }
        }
        else if (phase == Phase.RemovingChunks)
        {
            int radiusInChunks = _chunkSize * _radius;
            RemoveChunks(chunkWherePlayerStands, radiusInChunks);
            phase = Phase.Resting;
        }
        else
        {
            phase = Phase.Resting;
        }

        // Update sun transform and build AS
        if (_accelerationStructure != null)
        {
            _accelerationStructure.UpdateInstanceTransform(sun.GetComponent <Renderer>());
            _accelerationStructure.Build();
        }

        if (phase == Phase.Resting)
        {
            Settings.Instance.reprojectWithIDs = true;
        }
        else
        {
            Settings.Instance.reprojectWithIDs = false;
        }
    }