void CheckRenderTexture()
 {
     if (cs == null)
     {
         cs = new RenderTexture(Screen.width / (int)resolution, Screen.height / (int)resolution, 16);
         cs.enableRandomWrite = true;
         cs.Create();
         blend = new RenderTexture(Screen.width, Screen.height, 16);
         blend.Create();
         shader.SetTexture("RenderTarget", cs);
         cmd = new CommandBuffer();
         sun.AddCommandBuffer(LightEvent.AfterScreenspaceMask, cmd);
         cmd.CopyTexture(BuiltinRenderTextureType.CurrentActive, blend);
         combine.SetTexture("_SSS", blend);
         cmd.Blit(cs, BuiltinRenderTextureType.CurrentActive, combine);
     }
     else if (cs.width != Screen.width / (int)resolution || cs.height != Screen.height / (int)resolution)
     {
         cs.Release();
         cs = new RenderTexture(Screen.width / (int)resolution, Screen.height / (int)resolution, 16);
         cs.enableRandomWrite = true;
         cs.Create();
         blend.Release();
         blend = new RenderTexture(Screen.width, Screen.height, 16);
         blend.Create();
         shader.SetTexture("RenderTarget", cs);
         cmd.Clear();
         sun.RemoveAllCommandBuffers();
         sun.AddCommandBuffer(LightEvent.AfterScreenspaceMask, cmd);
         cmd.CopyTexture(BuiltinRenderTextureType.CurrentActive, blend);
         combine.SetTexture("_SSS", blend);
         cmd.Blit(cs, BuiltinRenderTextureType.CurrentActive, combine);
     }
 }
Example #2
0
    private void OnEnable()
    {
        Debug.Log("Raytracing support: " + SystemInfo.supportsRayTracing);

        _camera = GetComponent <Camera>();

        _dxrTarget = new RenderTexture(textureWidth, textureHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Default);
        _dxrTarget.enableRandomWrite = true;
        _dxrTarget.Create();
        _dxrTarget.hideFlags = HideFlags.DontSave;

        _accumulationTarget1           = new RenderTexture(_dxrTarget);
        _accumulationTarget2           = new RenderTexture(_dxrTarget);
        _accumulationTarget1.hideFlags = HideFlags.DontSave;
        _accumulationTarget2.hideFlags = HideFlags.DontSave;

        // build scene for raytracing
        InitRaytracingAccelerationStructure();

        // _rayTracingShader = Resources.Load<RayTracingShader>("RayTracingShader");

        _rayTracingShader.SetAccelerationStructure("_RaytracingAccelerationStructure", _rtas);
        _rayTracingShader.SetTexture("_DxrTarget", _dxrTarget);
        // set shader pass name that will be used during raytracing
        _rayTracingShader.SetShaderPass("DxrPass");

        // update raytracing parameters
        UpdateParameters();

        _accumulationMaterial = new Material(Shader.Find("Hidden/Accumulation"));

        // _nvidiaDevice = GraphicsDevice.CreateGraphicsDevice();
    }
    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;
    }
 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();
 }
    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);
    }
Example #6
0
    private void SetShaderParameters()
    {
        // for camera
        RayTracingShader.SetTexture(0, "_SkyboxTexture", SkyboxTexture);
        RayTracingShader.SetMatrix("_CameraToWorld", _camera.cameraToWorldMatrix);
        RayTracingShader.SetMatrix("_CameraInverseProjection", _camera.projectionMatrix.inverse);
        // light
        Vector3 l = DirectionalLight.transform.forward;

        RayTracingShader.SetVector("_DirectionalLight", new Vector4(l.x, l.y, l.z, DirectionalLight.intensity));
        // for antialiasing
        RayTracingShader.SetVector("_PixelOffset", new Vector2(Random.value, Random.value));
        // Spheres
        if (_sphereBuffer != null)
        {
            RayTracingShader.SetBuffer(0, "_Spheres", _sphereBuffer);
        }
    }
    /// <summary>
    /// Ray tracing to check whether plane1 can see plane2 by GPU.
    /// </summary>
    /// <param name="plane1">the plane1.</param>
    /// <param name="plane2">the plane2.</param>
    /// <returns>the result.</returns>
    public bool RayTracingPlane2PlaneGPU(Plane plane1, Plane plane2)
    {
        var viewRect     = new Rect(0F, 0F, math.ceil(plane1.size.x / rayTracingStep.x), math.ceil(plane1.size.y / rayTracingStep.x));
        var renderTarget = RequireRenderTarget(ref viewRect);
        var resultBuffer = RequireResultBuffer();

        bakeRayTraceShader.SetShaderPass("PVS");
        bakeRayTraceShader.SetAccelerationStructure(_accelerationStructureShaderId, accelerationStructure);
        bakeRayTraceShader.SetTexture(_resultShaderId, renderTarget);
        bakeRayTraceShader.SetVector(_viewLeftBottomCornerShaderId, plane1.leftBottomCorner);
        bakeRayTraceShader.SetVector(_viewRightDirShaderId, plane1.rightDir);
        bakeRayTraceShader.SetVector(_viewUpDirShaderId, plane1.upDir);
        bakeRayTraceShader.SetVector(_viewSizeShaderId, plane1.size);
        bakeRayTraceShader.SetVector(_targetLeftBottomCornerShaderId, plane2.leftBottomCorner);
        bakeRayTraceShader.SetVector(_targetRightDirShaderId, plane2.rightDir);
        bakeRayTraceShader.SetVector(_targetUpDirShaderId, plane2.upDir);
        bakeRayTraceShader.SetVector(_targetSizeShaderId, plane2.size);
        bakeRayTraceShader.SetVector(_rayTracingStepShaderId, rayTracingStep);
        bakeRayTraceShader.Dispatch("BakeRaygenShader", (int)viewRect.width, (int)viewRect.height, 1);

        var data = new byte[]
        {
            0, 0, 0, 0
        };

        resultBuffer.SetData(data);

        var kernelId = countPixelComputeShader.FindKernel("CSMain");

        countPixelComputeShader.SetTexture(kernelId, _pixelsShaderId, renderTarget);
        countPixelComputeShader.SetInt(_widthShaderId, (int)viewRect.width);
        countPixelComputeShader.SetInt(_heightShaderId, (int)viewRect.height);
        countPixelComputeShader.SetBuffer(kernelId, _resultShaderId, resultBuffer);
        countPixelComputeShader.GetKernelThreadGroupSizes(kernelId, out var grpSizeX, out var grpSizeY, out var _);
        countPixelComputeShader.Dispatch(kernelId, (int)math.ceil(viewRect.width / grpSizeX), (int)math.ceil(viewRect.height / grpSizeY), 1);

        resultBuffer.GetData(data);

        return(data[0] > 0);
    }