Przeglądaj źródła

fix some problems with raytracing

Kolja Strohm 3 tygodni temu
rodzic
commit
c6ba5e7d08

+ 113 - 113
FactoryCraft/Chunk.cpp

@@ -22,75 +22,75 @@ Chunk::Chunk(Framework::Point location)
 {
     blocks = new Block*[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
     memset(blocks, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(Block*));
-    FactoryCraftModel* ground = new FactoryCraftModel();
-    Model3DData* chunkModel
-        = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
-            Text("chunk_ground_") + location.x + location.y);
-    if (!chunkModel)
-    {
-        chunkModel
-            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
-                Text("chunk_ground_") + location.x + location.y);
-    }
-    chunkModel->setAmbientFactor(0.f);
-    chunkModel->setDiffusFactor(1.f);
-    chunkModel->setSpecularFactor(0.f);
-    chunkModel->setVertecies(0, 0);
-    ground->setModelData(chunkModel);
-    ground->setPosition(
-        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
-    ground->tick(0);
-    ChunkModelBuilder* groundModel = new ChunkGroundModel(ground, this);
-    modelBuilders.add(groundModel);
-    FactoryCraftModel* transparentGround = new FactoryCraftModel();
-    chunkModel = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
-        Text("transparent_chunk_ground_") + location.x + location.y);
-    if (!chunkModel)
-    {
-        chunkModel
-            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
-                Text("transparent_chunk_ground_") + location.x + location.y);
-    }
-    chunkModel->setAmbientFactor(0.f);
-    chunkModel->setDiffusFactor(1.f);
-    chunkModel->setSpecularFactor(0.f);
-    chunkModel->setVertecies(0, 0);
-    transparentGround->setModelData(chunkModel);
-    transparentGround->setPosition(
-        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
-    transparentGround->tick(0);
-    ChunkModelBuilder* transparentGroundModel
-        = new TransparentChunkGroundModel(transparentGround, this);
-    modelBuilders.add(transparentGroundModel);
-    FactoryCraftModel* fluids = new FactoryCraftModel();
-    chunkModel = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
-        Text("chunk_fluids_") + location.x + location.y);
-    if (!chunkModel)
-    {
-        chunkModel
-            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
-                Text("chunk_fluids_") + location.x + location.y);
-    }
-    chunkModel->setAmbientFactor(0.f);
-    chunkModel->setDiffusFactor(1.f);
-    chunkModel->setSpecularFactor(0.f);
-    chunkModel->setVertecies(0, 0);
-    fluids->setModelData(chunkModel);
-    fluids->setPosition(
-        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
-    fluids->tick(0);
-    ChunkModelBuilder* fluidModel = new ChunkFluidModel(fluids, this);
-    modelBuilders.add(fluidModel);
+    // FactoryCraftModel* ground = new FactoryCraftModel();
+    // Model3DData* chunkModel
+    //    = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
+    // Text("chunk_ground_") + location.x + location.y);
+    // if (!chunkModel)
+    // {
+    //     chunkModel
+    //         = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
+    //             Text("chunk_ground_") + location.x + location.y);
+    // }
+    // chunkModel->setAmbientFactor(0.f);
+    // chunkModel->setDiffusFactor(1.f);
+    // chunkModel->setSpecularFactor(0.f);
+    // chunkModel->setVertecies(0, 0);
+    // ground->setModelData(chunkModel);
+    // ground->setPosition(
+    //     (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
+    // ground->tick(0);
+    // ChunkModelBuilder* groundModel = new ChunkGroundModel(ground, this);
+    // modelBuilders.add(groundModel);
+    // FactoryCraftModel* transparentGround = new FactoryCraftModel();
+    // chunkModel = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
+    //    Text("transparent_chunk_ground_") + location.x + location.y);
+    // if (!chunkModel)
+    //{
+    //    chunkModel
+    //        = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
+    //            Text("transparent_chunk_ground_") + location.x + location.y);
+    //}
+    // chunkModel->setAmbientFactor(0.f);
+    // chunkModel->setDiffusFactor(1.f);
+    // chunkModel->setSpecularFactor(0.f);
+    // chunkModel->setVertecies(0, 0);
+    // transparentGround->setModelData(chunkModel);
+    // transparentGround->setPosition(
+    //    (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
+    // transparentGround->tick(0);
+    // ChunkModelBuilder* transparentGroundModel
+    //    = new TransparentChunkGroundModel(transparentGround, this);
+    // modelBuilders.add(transparentGroundModel);
+    // FactoryCraftModel* fluids = new FactoryCraftModel();
+    // chunkModel = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
+    //    Text("chunk_fluids_") + location.x + location.y);
+    // if (!chunkModel)
+    //{
+    //    chunkModel
+    //        = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
+    //            Text("chunk_fluids_") + location.x + location.y);
+    //}
+    // chunkModel->setAmbientFactor(0.f);
+    // chunkModel->setDiffusFactor(1.f);
+    // chunkModel->setSpecularFactor(0.f);
+    // chunkModel->setVertecies(0, 0);
+    // fluids->setModelData(chunkModel);
+    // fluids->setPosition(
+    //    (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
+    // fluids->tick(0);
+    // ChunkModelBuilder* fluidModel = new ChunkFluidModel(fluids, this);
+    // modelBuilders.add(fluidModel);
 }
 
 Chunk::Chunk(Framework::Point location, Framework::StreamReader* zReader)
     : Chunk(location)
 {
     load(zReader);
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        buildModel(builder);
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     buildModel(builder);
+    // }
 }
 
 Chunk::~Chunk()
@@ -350,25 +350,25 @@ void Chunk::load(Framework::StreamReader* zReader)
     isLoading = 0;
 }
 
-void Chunk::buildModel(ChunkModelBuilder* builder)
-{
-    modelChanged &= ~builder->getType();
-    lightChanged &= ~builder->getType();
-    builder->buildModel();
-}
+// void Chunk::buildModel(ChunkModelBuilder* builder)
+//{
+//     modelChanged &= ~builder->getType();
+//     lightChanged &= ~builder->getType();
+//     builder->buildModel();
+// }
 
-void Chunk::updateLight(ChunkModelBuilder* builder)
-{
-    lightChanged &= ~builder->getType();
-    builder->updateLightning();
-}
+// void Chunk::updateLight(ChunkModelBuilder* builder)
+//{
+//     lightChanged &= ~builder->getType();
+//     builder->updateLightning();
+// }
 
 void Chunk::forAll(std::function<void(Model3D*)> f)
 {
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        f(builder->zModel());
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     f(builder->zModel());
+    // }
     vLock.lockRead();
     for (Block* b : visibleBlocks)
     {
@@ -379,21 +379,21 @@ void Chunk::forAll(std::function<void(Model3D*)> f)
 
 bool Chunk::tick(std::function<void(Model3D*)> f, double time)
 {
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        if ((modelChanged | builder->getType()) == modelChanged)
-            buildModel(builder);
-    }
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        if ((lightChanged | builder->getType()) == lightChanged)
-            updateLight(builder);
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     if ((modelChanged | builder->getType()) == modelChanged)
+    //         buildModel(builder);
+    // }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     if ((lightChanged | builder->getType()) == lightChanged)
+    //         updateLight(builder);
+    // }
     bool res = 0;
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        res |= builder->zModel()->tick(time);
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     res |= builder->zModel()->tick(time);
+    // }
     aLock.lockRead();
     auto iterator = animations.begin();
     while (iterator)
@@ -424,16 +424,16 @@ bool Chunk::tick(std::function<void(Model3D*)> f, double time)
 
 void Chunk::destroy()
 {
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        Model3DData* chunkModel = builder->zModel()->zModelData();
-        // remove old model
-        while (chunkModel->getPolygonCount() > 0)
-        {
-            chunkModel->removePolygon(0);
-        }
-        chunkModel->setVertecies(0, 0);
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     Model3DData* chunkModel = builder->zModel()->zModelData();
+    //     // remove old model
+    //     while (chunkModel->getPolygonCount() > 0)
+    //     {
+    //         chunkModel->removePolygon(0);
+    //     }
+    //     chunkModel->setVertecies(0, 0);
+    // }
 }
 
 void Chunk::api(char* message)
@@ -537,17 +537,17 @@ void Chunk::setBlock(Block* block)
     int affectsGround = 0;
     int newAffectsGround = 0;
     bLock.lockWrite();
-    for (ChunkModelBuilder* builder : modelBuilders)
-    {
-        if (block && builder->isPartOfModel(block))
-        {
-            newAffectsGround |= builder->getType();
-        }
-        if (blocks[index] && builder->isPartOfModel(blocks[index]))
-        {
-            affectsGround |= builder->getType();
-        }
-    }
+    // for (ChunkModelBuilder* builder : modelBuilders)
+    //{
+    //     if (block && builder->isPartOfModel(block))
+    //     {
+    //         newAffectsGround |= builder->getType();
+    //     }
+    //     if (blocks[index] && builder->isPartOfModel(blocks[index]))
+    //     {
+    //         affectsGround |= builder->getType();
+    //     }
+    // }
     if (blocks[index])
     {
         vLock.lockWrite();

+ 4 - 5
FactoryCraft/Chunk.h

@@ -10,7 +10,6 @@
 #include "Area.h"
 #include "Block.h"
 #include "BlockAnimation.h"
-#include "ChunkModelBuilder.h"
 #include "Constants.h"
 #include "FactoryCraftModel.h"
 
@@ -30,7 +29,7 @@ private:
     // TODO: use native array for bedder performance?
     Block** blocks;
     Framework::Array<Block*> visibleBlocks;
-    Framework::RCArray<ChunkModelBuilder> modelBuilders;
+    // Framework::RCArray<ChunkModelBuilder> modelBuilders;
     bool isLoading;
     Framework::ReadWriteLock bLock;
     Framework::ReadWriteLock vLock;
@@ -42,8 +41,8 @@ private:
     void appendAnimation(
         Block* zB, int boneId, double time, Vec3<float> pos, Vec3<float> rot);
     void load(Framework::StreamReader* zReader);
-    void buildModel(ChunkModelBuilder* builder);
-    void updateLight(ChunkModelBuilder* builder);
+    // void buildModel(ChunkModelBuilder* builder);
+    // void updateLight(ChunkModelBuilder* builder);
 
 public:
     Chunk(Framework::Point location);
@@ -72,5 +71,5 @@ public:
              + localLocation.z;
     }
 
-    friend ChunkModelBuilder;
+    // friend ChunkModelBuilder;
 };

+ 15 - 12
FactoryCraft/ChunkModelBuilder.cpp

@@ -1,4 +1,5 @@
 #include "ChunkModelBuilder.h"
+
 #include "Chunk.h"
 
 ChunkModelBuilder::ChunkModelBuilder(
@@ -16,26 +17,28 @@ ChunkModelBuilder::~ChunkModelBuilder()
 
 Block** ChunkModelBuilder::blocks()
 {
-    return zChunk->blocks;
+    return 0;
+    // return zChunk->blocks;
 }
 
 void ChunkModelBuilder::setBlockPartOfModel(Block* zBlock, bool partOfModel)
 {
-    int state = zBlock->getPartOfModels();
-    if (!state && partOfModel)
-    {
-        zChunk->visibleBlocks.removeValue(zBlock);
-    }
-    zBlock->setPartOfModel(type, partOfModel);
-    if (state && !zBlock->getPartOfModels())
-    {
-        zChunk->visibleBlocks.add(zBlock);
-    }
+    // int state = zBlock->getPartOfModels();
+    // if (!state && partOfModel)
+    //{
+    //     zChunk->visibleBlocks.removeValue(zBlock);
+    // }
+    // zBlock->setPartOfModel(type, partOfModel);
+    // if (state && !zBlock->getPartOfModels())
+    //{
+    //     zChunk->visibleBlocks.add(zBlock);
+    // }
 }
 
 Framework::Point ChunkModelBuilder::chunkCenter()
 {
-    return zChunk->location;
+    return {0, 0};
+    // return zChunk->location;
 }
 
 FactoryCraftModel* ChunkModelBuilder::zModel() const

+ 2 - 2
FactoryCraft/ClosestHit.hlsl

@@ -1,7 +1,7 @@
 #include "Common.hlsl"
 
 [shader("closesthit")]
-void ClosestHit(inout HitInfo payload, Attributes attrib)
+void ClosestHit(inout HitInfo rayPayload : SV_RayPayload, Attributes attrib)
 {
-    payload.colorAndDistance = float4(1, 1, 0, RayTCurrent());
+    rayPayload.colorAndDistance = float4(0.f, 0.f, 1.f, RayTCurrent());
 }

+ 6 - 3
FactoryCraft/CustomDX12API.cpp

@@ -24,9 +24,10 @@ void CustomDX12API::initializePipeline()
         0, DX12_SHADER_REGISTER_U_UNORDERED_ACCESS, 0);
     rayGenSignature->addRegisterUsageLinkedToDescriptorHeap(
         1, DX12_SHADER_REGISTER_U_UNORDERED_ACCESS, 1);
-    tlasInputOffset
-        = rayGenSignature->addRegisterUsageLinkedToShaderBindingTable(
-            DX12_SHADER_REGISTER_T_SHADER_RESOURCE, 0);
+    rayGenSignature->addRegisterUsageLinkedToDescriptorHeap(
+        2, DX12_SHADER_REGISTER_B_CONST_BUFFER, 0);
+    rayGenSignature->addRegisterUsageLinkedToDescriptorHeap(
+        3, DX12_SHADER_REGISTER_T_SHADER_RESOURCE, 0);
     defaultRayGenerationShaderFunction = new DX12ShaderFunction(
         "RayGen", rayGenSignature, DX12_SHADER_FUNCTION_TYPE_RAY_GEN);
     rayGenShader->addFunction(defaultRayGenerationShaderFunction);
@@ -55,6 +56,8 @@ void CustomDX12API::initializePipeline()
     defaultHitGroup->setClosestHitShaderFunction(closestHitFunction);
     pipeline->addHitGroup(defaultHitGroup);
 
+    pipeline->setMaxRecursionDepth(10);
+
     pipeline->createPipelineState(device, pfnD3D12SerializeRootSignature);
 }
 

+ 39 - 24
FactoryCraft/FactoryClient.cpp

@@ -720,11 +720,19 @@ void FactoryClient::loadServerInfo()
     kam->setPosition(Vec3<float>(0, 0, 0));
     kam->setRotation(
         {(float)PI / 2.f, 0.f, std::atan2(0.f, -1.f) + (float)PI / 2});
+    renderThread->writeLock().lock();
     for (int i = 0; i < itemTypeCount; i++)
     {
+        if (i + 1 % 10 == 0)
+        {
+            renderThread->writeLock().unlock();
+            Sleep(1); // render thread needs to render the world, otherwise the
+                      // rendering will be stuck
+            renderThread->writeLock().lock();
+        }
         Model3D* mdl = new Model3D();
         Model3DData* data = itemTypes[i]->getItemModel();
-        if (data)
+        /* if (data)
         {
             Vec3<float> min = data->getMinPos();
             Vec3<float> max = data->getMaxPos();
@@ -732,34 +740,41 @@ void FactoryClient::loadServerInfo()
                 MAX(MAX(abs(min.x), abs(max.x)), MAX(abs(min.y), abs(max.y))),
                 MAX(abs(min.z), abs(max.z)));
             kam->setPosition(Vec3<float>(maxX * 3.5f, 0.f, 0.f));
+            mdl->setModelData(data);
+            mdl->setModelTextur(itemTypes[i]->getItemTextur());
+            mdl->setPosition(Vec3<float>(0.f, 0.f, 0.f));
+            mdl->setRotation(0.25f, 0.25f, 0.55f);
+            mdl->setAmbientFactor(0.8f);
+            mdl->setDiffusFactor(0.1f);
+            mdl->setSpecularFactor(0.1f);
+            mdl->setSize(itemTypes[i]->getSize());
+            w->addDrawable(mdl);
+            w->tick(0);
+            Image* b = new Image();
+            b->newImage(50, 50, 0);
+            DX12Texture* t
+                = (DX12Texture*)window->zScreen()
+                      ->zGraphicsApi()
+                      ->createOrGetTexture(
+                          Text("rendered/items/") + itemTypes[i]->getId(),
+                          b,
+                          GPU_TO_RAM);
+            window->zScreen()->zGraphicsApi()->renderKamera(kam, t);
+            t->updateTextur();
+            itemTypes[i]->setBild(dynamic_cast<Image*>(b->getThis()));
+            t->release();
+            w->removeDrawable(mdl);
         }
-        mdl->setModelData(data);
-        mdl->setModelTextur(itemTypes[i]->getItemTextur());
-        mdl->setPosition(Vec3<float>(0.f, 0.f, 0.f));
-        mdl->setRotation(0.25f, 0.25f, 0.55f);
-        mdl->setAmbientFactor(0.8f);
-        mdl->setDiffusFactor(0.1f);
-        mdl->setSpecularFactor(0.1f);
-        mdl->setSize(itemTypes[i]->getSize());
-        w->addDrawable(mdl);
-        w->tick(0);
+        else
+        {*/
         Image* b = new Image();
         b->newImage(50, 50, 0);
-        DX12Texture* t = (DX12Texture*)window->zScreen()
-                             ->zGraphicsApi()
-                             ->createOrGetTexture(Text("rendered/items/")
-                                                      + itemTypes[i]->getId(),
-                                 b,
-                                 GPU_TO_RAM);
-        renderThread->writeLock().lock();
-        window->zScreen()->zGraphicsApi()->renderKamera(kam, t);
-        renderThread->writeLock().unlock();
-        t->updateTextur();
-        itemTypes[i]->setBild(dynamic_cast<Image*>(b->getThis()));
-        t->release();
-        w->removeDrawable(mdl);
+        b->fillRegion(0, 0, 50, 50, 0xFF000000);
+        itemTypes[i]->setBild(b);
+        //}
         loadMenu->stageProgress(1);
     }
+    renderThread->writeLock().unlock();
     kam->release();
     loadMenu->allProgress(1);
 }

+ 3 - 3
FactoryCraft/FactoryCraft.vcxproj

@@ -303,7 +303,7 @@ copy "..\..\..\..\..\Allgemein\Network\x64\Release\Network.dll" "network.dll"</C
       <HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Custom%(Filename)Shader.h</HeaderFileOutput>
       <ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
       </ObjectFileOutput>
-      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd $(OutDir)%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
+      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd Custom%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
     </FxCompile>
     <None Include="Common.hlsl">
       <FileType>Document</FileType>
@@ -315,7 +315,7 @@ copy "..\..\..\..\..\Allgemein\Network\x64\Release\Network.dll" "network.dll"</C
       <HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Custom%(Filename)Shader.h</HeaderFileOutput>
       <ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
       </ObjectFileOutput>
-      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd $(OutDir)%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
+      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd Custom%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
     </FxCompile>
     <FxCompile Include="RayGen.hlsl">
       <ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Library</ShaderType>
@@ -324,7 +324,7 @@ copy "..\..\..\..\..\Allgemein\Network\x64\Release\Network.dll" "network.dll"</C
       <HeaderFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Custom%(Filename)Shader.h</HeaderFileOutput>
       <ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
       </ObjectFileOutput>
-      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd $(OutDir)%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
+      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">-Fd Custom%(Filename).pdb %(AdditionalOptions)</AdditionalOptions>
     </FxCompile>
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

+ 2 - 2
FactoryCraft/Miss.hlsl

@@ -1,7 +1,7 @@
 #include "Common.hlsl"
 
 [shader("miss")]
-void Miss(inout HitInfo payload : SV_RayPayload)
+void Miss(inout HitInfo rayPayload : SV_RayPayload)
 {
-    payload.colorAndDistance = float4(0.2f, 0.2f, 0.8f, -1.f);
+    rayPayload.colorAndDistance = float4(0.5f, 0.f, 0.f, -1.f);
 }

+ 44 - 9
FactoryCraft/RayGen.hlsl

@@ -6,20 +6,55 @@ RWTexture2D<float4> gOutput : register(u0);
 RWTexture2D<float4> guiTexture : register(u1);
 
 // Raytracing acceleration structure, accessed as a SRV
-RaytracingAccelerationStructure SceneBVH : register(t0);
+RaytracingAccelerationStructure TLAS : register(t0);
+
+cbuffer RayGenerationSettings : register(b0)
+{
+    int renderGui;
+    int useRays;
+    float minDistance;
+    float maxDistance;
+    float4x4 inverseView;
+    float4x4 inverseProjection;
+}
 
 [shader("raygeneration")]
 void RayGen()
 {
   // Initialize the ray payload
-    HitInfo payload;
-    payload.colorAndDistance = float4(0, 0, 0, 1.0);
+    HitInfo rayPayload;
+    rayPayload.colorAndDistance = float4(0, 0, !useRays ? 1 : 0, 1.0);
 
-  // Get the location within the dispatched 2D grid of work items
-  // (often maps to pixels, so this could represent a pixel coordinate).
-    uint2 launchIndex = DispatchRaysIndex().xy;
-  
-    float4 guiColor = guiTexture[launchIndex];
-    gOutput[launchIndex] = float4(payload.colorAndDistance.rgb * (1 - guiColor.a) + guiColor.rgb * guiColor.a, 1.f);
+    // Get the location within the dispatched 2D grid of work items
+    // (often maps to pixels, so this could represent a pixel coordinate).
+    float2 dispatchDimensions = float2(DispatchRaysDimensions().xy);
+    uint2 dispatchIndex = DispatchRaysIndex().xy;
+    float2 dispatchPercentage = (dispatchIndex + 0.5f) / dispatchDimensions;
     
+    if (useRays)
+    {
+        float2 d = (((dispatchIndex.xy + 0.5f) / dispatchDimensions.xy) * 2.f - 1.f);
+        RayDesc ray;
+        ray.Origin = mul(inverseView, float4(0, 0, 0, 1)).xyz;
+        float4 target = mul(inverseProjection, float4(d.x, -d.y, 1, 1));
+        ray.Direction = mul(inverseView, float4(target.xyz, 0)).xyz;
+        ray.TMin = minDistance;
+        ray.TMax = maxDistance;
+        TraceRay(TLAS, /*RayFlags*/0, /*InstanceInclusionMask*/0xFF, /*RayContributionToHitGroupIndex*/0,
+          /*MultiplierForGeometryContributionToHitGroupIndex*/0, /*MissShaderIndex*/0, ray, rayPayload);
+    }
+    
+    uint outWidth, outHeight;
+    gOutput.GetDimensions(outWidth, outHeight);
+    uint2 outputIndex = uint2(dispatchPercentage * float2(outWidth, outHeight));
+    if (renderGui)
+    {
+        uint guiWidth, guiHeight;
+        guiTexture.GetDimensions(guiWidth, guiHeight);
+        uint2 guiIndex = uint2(dispatchPercentage * float2(guiWidth, guiHeight));
+        float4 guiColor = guiTexture[guiIndex];
+        rayPayload.colorAndDistance.rgb = rayPayload.colorAndDistance.rgb * (1 - guiColor.a) + guiColor.rgb * guiColor.a;
+    }
+    gOutput[outputIndex] = float4(rayPayload.colorAndDistance.rgb, 1.f);
+
 }