compiles again

This commit is contained in:
Dynamitos
2023-11-05 10:36:01 +01:00
parent 4746c0f838
commit 77eb92838c
112 changed files with 1717 additions and 1540 deletions
+25 -1
View File
@@ -1,7 +1,31 @@
import Common; import Common;
import LightEnv;
import Material;
import MaterialParameter;
struct LightCullingData
{
RWStructuredBuffer<uint> oLightIndexList;
RWStructuredBuffer<uint> tLightIndexList;
RWTexture2D<uint2> oLightGrid;
RWTexture2D<uint2> tLightGrid;
};
ParameterBuffer<LightCullingData> gLightCullingData;
[shader("pixel")] [shader("pixel")]
void pixelMain(in VertexAttributes attribs, out float4 baseColor) void pixelMain(in VertexAttributes attribs, out float4 baseColor)
{ {
BRDF brdf = gMaterial.prepare(); MaterialParameter params = MaterialParameter.create(attribs);
BRDF brdf = gMaterial.prepare(params);
float3 result = float3(0, 0, 0);
for(int i = 0; i < gLightEnv.numDirectionalLights; ++i)
{
result += gLightEnv.directionalLights[i].illuminate(params, brdf);
}
for(int i = 0; i < gLightEnv.numPointLights; ++i)
{
result += gLightEnv.pointLights[i].illuminate(params, brdf);
}
return float4(result, 1.0f);
} }
+5 -6
View File
@@ -8,16 +8,15 @@ struct ComputeShaderInput
uint groupIndex : SV_GroupIndex; uint groupIndex : SV_GroupIndex;
}; };
layout(set = 0, binding = 1, std430) struct DispatchParams
cbuffer DispatchParams
{ {
uint3 numThreadGroups; uint3 numThreadGroups;
uint pad0; uint pad0;
uint3 numThreads; uint3 numThreads;
uint pad1; uint pad1;
RWShaderBuffer<Frustum> frustums;
} }
layout(set = 0, binding = 2, std430) ParameterBuffer<DispatchParams> dispatchParams;
RWShaderBuffer<Frustum> out_Frustums;
[numthreads(BLOCK_SIZE, BLOCK_SIZE, 1)] [numthreads(BLOCK_SIZE, BLOCK_SIZE, 1)]
@@ -49,9 +48,9 @@ void computeFrustums(ComputeShaderInput in)
frustum.planes[2] = computePlane(eyePos, viewSpace[0], viewSpace[1]); frustum.planes[2] = computePlane(eyePos, viewSpace[0], viewSpace[1]);
frustum.planes[3] = computePlane(eyePos, viewSpace[3], viewSpace[2]); frustum.planes[3] = computePlane(eyePos, viewSpace[3], viewSpace[2]);
if(in.dispatchThreadID.x < numThreads.x && in.dispatchThreadID.y < numThreads.y) if(in.dispatchThreadID.x < dispatchParams.numThreads.x && in.dispatchThreadID.y < dispatchParams.numThreads.y)
{ {
uint index = in.dispatchThreadID.x + (in.dispatchThreadID.y * numThreads.x); uint index = in.dispatchThreadID.x + (in.dispatchThreadID.y * numThreads.x);
out_Frustums[index] = frustum; dispatchParams.frustums[index] = frustum;
} }
} }
+1 -4
View File
@@ -1,5 +1,5 @@
import LightEnv;
import Common; import Common;
import LightEnv;
struct ComputeShaderInput struct ComputeShaderInput
{ {
@@ -27,13 +27,10 @@ struct CullingParams
RWTexture2D<uint2> tLightGrid; RWTexture2D<uint2> tLightGrid;
StructuredBuffer<Frustum> frustums; StructuredBuffer<Frustum> frustums;
}; };
ParameterBlock<CullingParams> gCullingParams; ParameterBlock<CullingParams> gCullingParams;
// Debug // Debug
//layout(set = INDEX_VIEW_PARAMS, binding = 10)
//Texture2D lightCountHeatMap; //Texture2D lightCountHeatMap;
//layout(set = INDEX_VIEW_PARAMS, binding = 11)
//RWTexture2D<float4> debugTexture; //RWTexture2D<float4> debugTexture;
groupshared uint uMinDepth; groupshared uint uMinDepth;
+3 -3
View File
@@ -2,7 +2,7 @@ import Common;
import BRDF; import BRDF;
import Meshlet; import Meshlet;
import Scene; import Scene;
import StaticMeshVertexData; import VertexData;
struct MeshPayload struct MeshPayload
{ {
@@ -61,7 +61,7 @@ void taskMain(
DispatchMesh(head, 1, 1, p); DispatchMesh(head, 1, 1, p);
} }
groupshared StaticMeshVertexAttributes gs_vertices[MAX_VERTICES]; groupshared VertexAttributes gs_vertices[MAX_VERTICES];
groupshared uint3 gs_indices[MAX_PRIMITIVES]; groupshared uint3 gs_indices[MAX_PRIMITIVES];
groupshared uint gs_numVertices; groupshared uint gs_numVertices;
groupshared uint gs_numPrimitives; groupshared uint gs_numPrimitives;
@@ -78,7 +78,7 @@ void meshMain(
in uint threadID: SV_GroupIndex, in uint threadID: SV_GroupIndex,
in uint groupID: SV_GroupID, in uint groupID: SV_GroupID,
in payload MeshPayload meshPayload, in payload MeshPayload meshPayload,
out Vertices<StaticMeshVertexAttributes, MAX_VERTICES> vertices, out Vertices<VertexAttributes, MAX_VERTICES> vertices,
out Indices<uint3, MAX_PRIMITIVES> indices out Indices<uint3, MAX_PRIMITIVES> indices
){ ){
InstanceData inst = scene.instances[meshPayload.instanceId[groupID]]; InstanceData inst = scene.instances[meshPayload.instanceId[groupID]];
+17 -17
View File
@@ -10,9 +10,12 @@ struct VertexShaderOutput
float4 clipPos : SV_Position; float4 clipPos : SV_Position;
float3 texCoords; float3 texCoords;
}; };
struct SkyboxData
[[vk::push_constant]] {
ConstantBuffer<float4x4> transformMatrix; float4x4 transformMatrix;
float4 fogBlend;
};
ParameterBuffer<SkyboxData> gSkyboxData;
[shader("vertex")] [shader("vertex")]
VertexShaderOutput vertexMain( VertexShaderOutput vertexMain(
@@ -27,16 +30,13 @@ VertexShaderOutput vertexMain(
return output; return output;
} }
[[vk::push_constant]] struct TextureData
ConstantBuffer<float4> fogBlend; {
TextureCube cubeMap;
layout(set = 0, binding = 1) TextureCube cubeMap2;
TextureCube cubeMap; SamplerState sampler;
layout(set = 0, binding = 2) };
TextureCube cubeMap2; ParameterBuffer<TextureData> textures;
layout(set = 0, binding = 3)
SamplerState sampler;
static const float lowerLimit = 0.0; static const float lowerLimit = 0.0;
static const float upperLimit = 0.1; static const float upperLimit = 0.1;
@@ -44,11 +44,11 @@ static const float upperLimit = 0.1;
float4 fragmentMain( float4 fragmentMain(
VertexShaderOutput output) : SV_Target VertexShaderOutput output) : SV_Target
{ {
float4 texture1 = cubeMap.Sample(sampler, output.texCoords); float4 texture1 = textures.cubeMap.Sample(textures.sampler, output.texCoords);
float4 texture2 = cubeMap2.Sample(sampler, output.texCoords); float4 texture2 = textures.cubeMap2.Sample(textures.sampler, output.texCoords);
float4 finalColor = lerp(texture1, texture2, fogBlend.w); float4 finalColor = lerp(texture1, texture2, gSkyboxData.fogBlend.w);
float factor = (output.texCoords.y - lowerLimit) / (upperLimit - lowerLimit); float factor = (output.texCoords.y - lowerLimit) / (upperLimit - lowerLimit);
factor = clamp(factor, 0.0, 1.0); factor = clamp(factor, 0.0, 1.0);
return lerp(float4(fogBlend.xyz, 1), finalColor, factor); return lerp(float4(gSkyboxData.fogBlend.xyz, 1), finalColor, factor);
} }
+4 -11
View File
@@ -1,26 +1,19 @@
import Common;
struct GlyphData struct GlyphData
{ {
float4 bearingSize; float4 bearingSize;
}; };
struct ViewData
{
float4x4 projectionMatrix;
}
struct TextData struct TextData
{ {
float4 textColor; float4 textColor;
float scale; float scale;
} }
layout(set = 0, binding = 0) ParameterBuffer<SamplerState> glyphSampler;
ConstantBuffer<ViewData> viewData;
layout(set = 0, binding = 1)
SamplerState glyphSampler;
//layout(set = 1) //layout(set = 1)
//ShaderBuffer<GlyphData> glyphData; //ShaderBuffer<GlyphData> glyphData;
layout(set = 1) ParameterBuffer<Texture2D<uint>[]> glyphTextures;
Texture2D<uint> glyphTextures[]; [[vk::push_constant]]
layout(push_constant)
ConstantBuffer<TextData> textData; ConstantBuffer<TextData> textData;
struct VertexStageInput struct VertexStageInput
+8 -14
View File
@@ -1,3 +1,5 @@
import Common;
struct RenderElementStyle struct RenderElementStyle
{ {
float3 position; float3 position;
@@ -15,22 +17,14 @@ struct RenderElementStyle
float2 dimensions; float2 dimensions;
}; };
struct ViewData struct UIParameter
{ {
float4x4 projectionMatrix; SamplerState backgroundSampler;
}; uint numBackgroundTextures;
Texture2D<float4> backgroundTextures[];
}
layout(set = 0, binding = 0) ParameterBuffer<UIParameter> params;
ConstantBuffer<ViewData> viewData;
layout(set = 0, binding = 1)
SamplerState backgroundSampler;
layout(set = 0, binding = 2)
ConstantBuffer<uint> numBackgroundTextures;
layout(set = 0, binding = 3)
Texture2D<float4> backgroundTextures[];
struct VertexStageOutput struct VertexStageOutput
{ {
-9
View File
@@ -70,12 +70,3 @@ struct LightEnv
}; };
ParameterBlock<LightEnv> gLightEnv; ParameterBlock<LightEnv> gLightEnv;
//layout(set = INDEX_LIGHT_ENV, binding = 0, std430)
//ShaderBuffer<DirectionalLight> directionalLights;
//layout(set = INDEX_LIGHT_ENV, binding = 1, std430)
//ConstantBuffer<uint> numDirectionalLights;
//layout(set = INDEX_LIGHT_ENV, binding = 2, std430)
//ShaderBuffer<PointLight> pointLights;
//layout(set = INDEX_LIGHT_ENV, binding = 3, std430)
//ConstantBuffer<uint> numPointLights;
+2 -3
View File
@@ -1,12 +1,11 @@
import Common; import Common;
import BRDF; import BRDF;
import MaterialParameter;
interface IMaterial interface IMaterial
{ {
associatedtype BRDF : IBRDF; associatedtype BRDF : IBRDF;
BRDF prepare(MaterialFragmentParameter input); BRDF prepare(MaterialParameter input);
}; };
layout(set = INDEX_MATERIAL)
ParameterBlock<IMaterial> gMaterial; ParameterBlock<IMaterial> gMaterial;
-1
View File
@@ -37,6 +37,5 @@ struct Scene
StructuredBuffer<uint32_t> vertexIndices; StructuredBuffer<uint32_t> vertexIndices;
}; };
layout(set = INDEX_SCENE_DATA)
ParameterBlock<Scene> scene; ParameterBlock<Scene> scene;
View File
@@ -63,5 +63,3 @@ struct SkinnedMeshVertexData : VertexData
StructuredBuffer<float4> boneWeights; StructuredBuffer<float4> boneWeights;
StructuredBuffer<float4x4> bones; StructuredBuffer<float4x4> bones;
} }
layout(set = INDEX_VERTEX_DATA)
ParameterBlock<SkinnedMeshVertexData> vertexData;
@@ -55,5 +55,3 @@ struct StaticMeshVertexData : VertexData
StructuredBuffer<float3> tangents; StructuredBuffer<float3> tangents;
StructuredBuffer<float3> biTangents; StructuredBuffer<float3> biTangents;
} }
layout(set = INDEX_VERTEX_DATA)
ParameterBlock<StaticMeshVertexData> vertexData;
+1
View File
@@ -13,3 +13,4 @@ interface VertexData
{ {
VertexAttributes getAttributes(uint index, float4x4 transform); VertexAttributes getAttributes(uint index, float4x4 transform);
}; };
ParameterBlock<VertexData> vertexData;
-1
View File
@@ -4,7 +4,6 @@
#include "Asset/TextureAsset.h" #include "Asset/TextureAsset.h"
#include "Asset/MaterialAsset.h" #include "Asset/MaterialAsset.h"
#include "Asset/MaterialInstanceAsset.h" #include "Asset/MaterialInstanceAsset.h"
#include "Graphics/Vulkan/VulkanGraphics.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
using namespace Seele; using namespace Seele;
+6 -4
View File
@@ -2,7 +2,7 @@
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Asset/FontAsset.h" #include "Asset/FontAsset.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Graphics/GraphicsResources.h" #include "Graphics/Resources.h"
#include <ft2build.h> #include <ft2build.h>
#include FT_FREETYPE_H #include FT_FREETYPE_H
@@ -22,10 +22,12 @@ void FontLoader::importAsset(FontImportArgs args)
{ {
std::filesystem::path assetPath = args.filePath.filename(); std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset"); assetPath.replace_extension("asset");
PFontAsset asset = new FontAsset(args.importPath, assetPath.stem().string()); OFontAsset asset = new FontAsset(args.importPath, assetPath.stem().string());
asset->setStatus(Asset::Status::Loading); asset->setStatus(Asset::Status::Loading);
AssetRegistry::get().registerFont(asset); // the registry takes ownership, but we need to edit the reference
import(args, asset); PFontAsset ref = asset;
AssetRegistry::get().registerFont(std::move(asset));
import(args, ref);
} }
// in case of the space character there is no bitmap // in case of the space character there is no bitmap
+74 -75
View File
@@ -7,6 +7,7 @@
#include "Material/ShaderExpression.h" #include "Material/ShaderExpression.h"
#include "Asset/TextureAsset.h" #include "Asset/TextureAsset.h"
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <format>
using namespace Seele; using namespace Seele;
using json = nlohmann::json; using json = nlohmann::json;
@@ -14,12 +15,12 @@ using json = nlohmann::json;
MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) MaterialLoader::MaterialLoader(Gfx::PGraphics graphics)
: graphics(graphics) : graphics(graphics)
{ {
PMaterialAsset placeholderAsset = new MaterialAsset(); OMaterialAsset placeholderAsset = new MaterialAsset();
import(MaterialImportArgs{ import(MaterialImportArgs{
.filePath = std::filesystem::absolute("./shaders/Placeholder.asset"), .filePath = std::filesystem::absolute("./shaders/Placeholder.asset"),
.importPath = "", .importPath = "",
}, placeholderAsset); }, placeholderAsset);
AssetRegistry::get().assetRoot->materials[""] = placeholderAsset; AssetRegistry::get().assetRoot->materials[""] = std::move(placeholderAsset);
} }
MaterialLoader::~MaterialLoader() MaterialLoader::~MaterialLoader()
@@ -30,10 +31,11 @@ void MaterialLoader::importAsset(MaterialImportArgs args)
{ {
std::filesystem::path assetPath = args.filePath.filename(); std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset"); assetPath.replace_extension("asset");
PMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string()); OMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string());
asset->setStatus(Asset::Status::Loading); asset->setStatus(Asset::Status::Loading);
AssetRegistry::get().registerMaterial(asset); PMaterialAsset ref = asset;
import(args, asset); AssetRegistry::get().registerMaterial(std::move(asset));
import(args, ref);
} }
void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
@@ -42,7 +44,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
json j; json j;
jsonstream >> j; jsonstream >> j;
std::string materialName = j["name"].get<std::string>() + "Material"; std::string materialName = j["name"].get<std::string>() + "Material";
Gfx::PDescriptorLayout layout = graphics->createDescriptorLayout(materialName + "Layout"); Gfx::ODescriptorLayout layout = graphics->createDescriptorLayout(materialName + "Layout");
//Shader file needs to conform to the slang standard, which prohibits _ //Shader file needs to conform to the slang standard, which prohibits _
materialName.erase(std::remove(materialName.begin(), materialName.end(), '_'), materialName.end()); materialName.erase(std::remove(materialName.begin(), materialName.end(), '_'), materialName.end());
materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), materialName.end()); materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), materialName.end());
@@ -50,19 +52,18 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
uint32 uniformBufferOffset = 0; uint32 uniformBufferOffset = 0;
uint32 bindingCounter = 0; // Uniform buffers are always binding 0 uint32 bindingCounter = 0; // Uniform buffers are always binding 0
uint32 uniformBinding = -1; uint32 uniformBinding = -1;
Map<int32, PShaderExpression> expressions; Map<std::string, OShaderExpression> expressions;
int32 key = 0; uint32 key = 0;
int32 auxKey = -1; uint32 auxKey = 0;
Map<std::string, PShaderParameter> parameters; Array<std::string> parameters;
for(auto param : j["params"].items()) for(auto& param : j["params"].items())
{ {
std::string type = param.value()["type"].get<std::string>(); std::string type = param.value()["type"].get<std::string>();
auto defaultValue = param.value().find("default"); auto defaultValue = param.value().find("default");
// TODO: ALIGNMENT RULES // TODO: ALIGNMENT RULES
if(type.compare("float") == 0) if(type.compare("float") == 0)
{ {
PFloatParameter p = new FloatParameter(param.key(), uniformBufferOffset, 0); OFloatParameter p = new FloatParameter(param.key(), uniformBufferOffset, 0);
p->key = auxKey;
if(uniformBinding == -1) if(uniformBinding == -1)
{ {
layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
@@ -73,14 +74,13 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
{ {
p->data = std::stof(defaultValue.value().get<std::string>()); p->data = std::stof(defaultValue.value().get<std::string>());
} }
expressions[auxKey--] = p; parameters.add(p->key);
parameters[param.key()] = p; expressions[p->key] = std::move(p);
} }
// TODO: ALIGNMENT RULES // TODO: ALIGNMENT RULES
else if(type.compare("float3") == 0) else if(type.compare("float3") == 0)
{ {
PVectorParameter p = new VectorParameter(param.key(), uniformBufferOffset, 0); OVectorParameter p = new VectorParameter(param.key(), uniformBufferOffset, 0);
p->key = auxKey;
if(uniformBinding == -1) if(uniformBinding == -1)
{ {
layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); layout->addDescriptorBinding(bindingCounter, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
@@ -91,13 +91,12 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
{ {
p->data = parseVector(defaultValue.value().get<std::string>().c_str()); p->data = parseVector(defaultValue.value().get<std::string>().c_str());
} }
expressions[auxKey--] = p; parameters.add(p->key);
parameters[param.key()] = p; expressions[p->key] = std::move(p);
} }
else if(type.compare("Texture2D") == 0) else if(type.compare("Texture2D") == 0)
{ {
PTextureParameter p = new TextureParameter(param.key(), 0, bindingCounter); OTextureParameter p = new TextureParameter(param.key(), 0, bindingCounter);
p->key = auxKey;
layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE); layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
if(defaultValue != param.value().end()) if(defaultValue != param.value().end())
{ {
@@ -108,17 +107,16 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
{ {
p->data = AssetRegistry::findTexture(""); // this will return placeholder texture p->data = AssetRegistry::findTexture(""); // this will return placeholder texture
} }
expressions[auxKey--] = p; parameters.add(p->key);
parameters[param.key()] = p; expressions[p->key] = std::move(p);
} }
else if(type.compare("SamplerState") == 0) else if(type.compare("SamplerState") == 0)
{ {
PSamplerParameter p = new SamplerParameter(param.key(), 0, bindingCounter); OSamplerParameter p = new SamplerParameter(param.key(), 0, bindingCounter);
p->key = auxKey;
layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLER); layout->addDescriptorBinding(bindingCounter++, Gfx::SE_DESCRIPTOR_TYPE_SAMPLER);
p->data = graphics->createSamplerState({}); p->data = graphics->createSamplerState({});
expressions[auxKey--] = p; parameters.add(p->key);
parameters[param.key()] = p; expressions[p->key] = std::move(p);
} }
else else
{ {
@@ -126,99 +124,100 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
} }
} }
uint32 uniformDataSize = uniformBufferOffset; uint32 uniformDataSize = uniformBufferOffset;
auto referenceExpression = [&auxKey, &expressions](json obj) -> PShaderExpression auto referenceExpression = [&auxKey, &expressions](json obj) -> std::string
{ {
if(obj.is_string()) if(obj.is_string())
{ {
PConstantExpression c = new ConstantExpression(obj.get<std::string>(), ExpressionType::UNKNOWN); std::string str = obj.get<std::string>();
c->key = auxKey; if (expressions.contains(str))
expressions[auxKey--] = c; {
return c; return str;
}
OConstantExpression c = new ConstantExpression(str, ExpressionType::UNKNOWN);
std::string name = std::format("Const{0}", auxKey++);
c->key = name;
expressions[c->key] = std::move(c);
return name;
} }
else else
{ {
return expressions[obj.get<uint32>()]; return std::format("{0}", obj.get<uint32>());
} }
}; };
MaterialNode mat; MaterialNode mat;
for(auto param : j["code"].items()) for(auto& param : j["code"].items())
{ {
auto obj = param.value(); auto& obj = param.value();
std::string exp = obj["exp"].get<std::string>(); std::string exp = obj["exp"].get<std::string>();
if(exp.compare("Add") == 0) if(exp.compare("Add") == 0)
{ {
PAddExpression p = new AddExpression(); OAddExpression p = new AddExpression();
p->key = key; std::string name = std::format("{0}", key++);
p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; p->key = name;
p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; p->inputs["lhs"].source = referenceExpression(obj["lhs"]);
expressions[key++] = p; p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions[name] = std::move(p);
} }
if(exp.compare("Sub") == 0) if(exp.compare("Sub") == 0)
{ {
PSubExpression p = new SubExpression(); OSubExpression p = new SubExpression();
p->key = key; std::string name = std::format("{0}", key++);
p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; p->key = name;
p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; p->inputs["lhs"].source = referenceExpression(obj["lhs"]);
expressions[key++] = p; p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions[name] = std::move(p);
} }
if(exp.compare("Mul") == 0) if(exp.compare("Mul") == 0)
{ {
PMulExpression p = new MulExpression(); OMulExpression p = new MulExpression();
p->key = key; std::string name = std::format("{0}", key++);
p->inputs["lhs"].source = referenceExpression(obj["lhs"])->key; p->key = name;
p->inputs["rhs"].source = referenceExpression(obj["rhs"])->key; p->inputs["lhs"].source = referenceExpression(obj["lhs"]);
expressions[key++] = p; p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions[name] = std::move(p);
} }
if(exp.compare("Swizzle") == 0) if(exp.compare("Swizzle") == 0)
{ {
PSwizzleExpression p = new SwizzleExpression(); OSwizzleExpression p = new SwizzleExpression();
p->key = key; std::string name = std::format("{0}", key);
p->inputs["target"].source = referenceExpression(obj["target"])->key; p->key = name;
p->inputs["target"].source = referenceExpression(obj["target"]);
int32 i = 0; int32 i = 0;
for(auto c : obj["comp"].items()) for(auto& c : obj["comp"].items())
{ {
p->comp[i++] = c.value().get<uint32>(); p->comp[i++] = c.value().get<uint32>();
} }
expressions[key++] = p; expressions[name] = std::move(p);
} }
if(exp.compare("Sample") == 0) if(exp.compare("Sample") == 0)
{ {
PSampleExpression p = new SampleExpression(); OSampleExpression p = new SampleExpression();
p->key = key; std::string name = std::format("{0}", key);
p->inputs["texture"].source = parameters[obj["texture"].get<std::string>()]->key; p->key = name;
p->inputs["sampler"].source = parameters[obj["sampler"].get<std::string>()]->key; p->inputs["texture"].source = referenceExpression(obj["texture"]);
p->inputs["coords"].source = referenceExpression(obj["coords"])->key; p->inputs["sampler"].source = referenceExpression(obj["sampler"]);
expressions[key++] = p; p->inputs["coords"].source = referenceExpression(obj["coords"]);
expressions[name] = std::move(p);
} }
if(exp.compare("BRDF") == 0) if(exp.compare("BRDF") == 0)
{ {
mat.profile = obj["profile"].get<std::string>(); mat.profile = obj["profile"].get<std::string>();
for(auto val : obj["values"].items()) for(auto& val : obj["values"].items())
{ {
mat.variables[val.key()] = referenceExpression(val.value()); mat.variables[val.key()] = val.value();
} }
} }
} }
layout->create(); layout->create();
Array<PShaderExpression> codeExp;
for(const auto& [_, e] : expressions)
{
codeExp.add(e);
}
Array<PShaderParameter> params;
for(const auto& [_, p] : parameters)
{
params.add(p);
}
asset->material = new Material( asset->material = new Material(
graphics, graphics,
std::move(params),
std::move(layout), std::move(layout),
uniformDataSize, uniformDataSize,
uniformBinding, uniformBinding,
materialName, materialName,
std::move(codeExp), std::move(expressions),
std::move(parameters),
std::move(mat) std::move(mat)
); );
+9 -6
View File
@@ -33,10 +33,11 @@ void MeshLoader::importAsset(MeshImportArgs args)
{ {
std::filesystem::path assetPath = args.filePath.filename(); std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset"); assetPath.replace_extension("asset");
PMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string()); OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
PMeshAsset ref = asset;
asset->setStatus(Asset::Status::Loading); asset->setStatus(Asset::Status::Loading);
AssetRegistry::get().registerMesh(asset); AssetRegistry::get().registerMesh(std::move(asset));
import(args, asset); import(args, ref);
} }
void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialAsset>& globalMaterials) void MeshLoader::loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialAsset>& globalMaterials)
@@ -133,7 +134,7 @@ void findMeshRoots(aiNode *node, List<aiNode *> &meshNodes)
} }
} }
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialAsset>& materials, Array<PMesh>& globalMeshes, Component::Collider& collider) void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider)
{ {
for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) for (uint32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{ {
@@ -318,20 +319,22 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset)
loadTextures(scene, args.filePath.parent_path(), args.importPath); loadTextures(scene, args.filePath.parent_path(), args.importPath);
loadMaterials(scene, args.filePath.stem().string(), args.filePath.parent_path(), args.importPath, globalMaterials); loadMaterials(scene, args.filePath.stem().string(), args.filePath.parent_path(), args.importPath, globalMaterials);
Array<PMesh> globalMeshes(scene->mNumMeshes); Array<OMesh> globalMeshes(scene->mNumMeshes);
Component::Collider collider; Component::Collider collider;
loadGlobalMeshes(scene, globalMaterials, globalMeshes, collider); loadGlobalMeshes(scene, globalMaterials, globalMeshes, collider);
List<aiNode *> meshNodes; List<aiNode *> meshNodes;
findMeshRoots(scene->mRootNode, meshNodes); findMeshRoots(scene->mRootNode, meshNodes);
Array<OMesh> meshes;
for (auto meshNode : meshNodes) for (auto meshNode : meshNodes)
{ {
for(uint32 i = 0; i < meshNode->mNumMeshes; ++i) for(uint32 i = 0; i < meshNode->mNumMeshes; ++i)
{ {
meshAsset->addMesh(globalMeshes[meshNode->mMeshes[i]]); meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]]));
} }
} }
meshAsset->meshes = std::move(meshes);
meshAsset->physicsMesh = std::move(collider); meshAsset->physicsMesh = std::move(collider);
+1 -1
View File
@@ -26,7 +26,7 @@ public:
private: private:
void loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialAsset>& globalMaterials); void loadMaterials(const aiScene* scene, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialAsset>& globalMaterials);
void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath); void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath);
void loadGlobalMeshes(const aiScene* scene, const Array<PMaterialAsset>& materials, Array<PMesh>& globalMeshes, Component::Collider& collider); void loadGlobalMeshes(const aiScene* scene, const Array<PMaterialAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider);
void convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels); void convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels);
void import(MeshImportArgs args, PMeshAsset meshAsset); void import(MeshImportArgs args, PMeshAsset meshAsset);
+9 -10
View File
@@ -2,7 +2,7 @@
#include "Asset/TextureAsset.h" #include "Asset/TextureAsset.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Graphics/Vulkan/VulkanGraphicsEnums.h" #include "Graphics/Vulkan/Enums.h"
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h> #include <stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION
@@ -14,15 +14,13 @@ using namespace Seele;
TextureLoader::TextureLoader(Gfx::PGraphics graphics) TextureLoader::TextureLoader(Gfx::PGraphics graphics)
: graphics(graphics) : graphics(graphics)
{ {
//(std::filesystem::absolute("./textures/placeholder.ktx")); OTextureAsset placeholder = new TextureAsset();
//placeholderAsset->load(graphics); placeholderAsset = placeholder;
//AssetRegistry::get().assetRoot.textures[""] = placeholderAsset;
placeholderAsset = new TextureAsset();
import(TextureImportArgs{ import(TextureImportArgs{
.filePath = std::filesystem::absolute("./textures/placeholder.png"), .filePath = std::filesystem::absolute("./textures/placeholder.png"),
.importPath = "", .importPath = "",
}, placeholderAsset); }, placeholderAsset);
AssetRegistry::get().assetRoot->textures[""] = placeholderAsset; AssetRegistry::get().assetRoot->textures[""] = std::move(placeholder);
} }
TextureLoader::~TextureLoader() TextureLoader::~TextureLoader()
@@ -33,11 +31,12 @@ void TextureLoader::importAsset(TextureImportArgs args)
{ {
std::filesystem::path assetPath = args.filePath.filename(); std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset"); assetPath.replace_extension("asset");
PTextureAsset asset = new TextureAsset(args.importPath, assetPath.stem().string());
OTextureAsset asset = new TextureAsset(args.importPath, assetPath.stem().string());
PTextureAsset ref = asset;
asset->setStatus(Asset::Status::Loading); asset->setStatus(Asset::Status::Loading);
asset->setTexture(placeholderAsset->getTexture()); AssetRegistry::get().registerTexture(std::move(asset));
AssetRegistry::get().registerTexture(asset); import(args, ref);
import(args, asset);
} }
PTextureAsset TextureLoader::getPlaceholderTexture() PTextureAsset TextureLoader::getPlaceholderTexture()
+6 -10
View File
@@ -11,13 +11,13 @@ using namespace Seele::Editor;
InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo) InspectorView::InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo)
: View(graphics, std::move(window), std::move(createInfo), "InspectorView") : View(graphics, std::move(window), std::move(createInfo), "InspectorView")
, renderGraph(RenderGraphBuilder::build( //, renderGraph(RenderGraphBuilder::build(
UIPass(graphics), // UIPass(graphics),
TextPass(graphics) // TextPass(graphics)
)) //))
, uiSystem(new UI::System()) , uiSystem(new UI::System())
{ {
renderGraph.updateViewport(viewport); //renderGraph.updateViewport(viewport);
uiSystem->updateViewport(viewport); uiSystem->updateViewport(viewport);
} }
@@ -41,15 +41,11 @@ void InspectorView::commitUpdate()
void InspectorView::prepareRender() void InspectorView::prepareRender()
{ {
renderGraph.updatePassData(
uiSystem->getUIPassData(),
uiSystem->getTextPassData()
);
} }
void InspectorView::render() void InspectorView::render()
{ {
renderGraph.render(uiSystem->getVirtualCamera());
} }
void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier)
-6
View File
@@ -24,12 +24,6 @@ public:
virtual void render() override; virtual void render() override;
void selectActor(); void selectActor();
protected: protected:
RenderGraph<
UIPass,
TextPass> renderGraph;
UIPassData uiPassData;
TextPassData textPassData;
UI::PSystem uiSystem; UI::PSystem uiSystem;
PActor selectedActor; PActor selectedActor;
+4 -8
View File
@@ -7,7 +7,7 @@
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Actor/CameraActor.h" #include "Actor/CameraActor.h"
#include "Component/Camera.h" #include "Component/Camera.h"
#include "Component/StaticMesh.h" #include "Component/Mesh.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Editor; using namespace Seele::Editor;
@@ -16,9 +16,9 @@ SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreat
: View(graphics, owner, createInfo, "SceneView") : View(graphics, owner, createInfo, "SceneView")
, scene(new Scene(graphics)) , scene(new Scene(graphics))
, renderGraph(RenderGraphBuilder::build( , renderGraph(RenderGraphBuilder::build(
DepthPrepass(graphics), DepthPrepass(graphics, scene),
LightCullingPass(graphics), LightCullingPass(graphics, scene),
BasePass(graphics) BasePass(graphics, scene)
)) ))
, cameraSystem(createInfo.dimensions, Vector(0, 0, 10)) , cameraSystem(createInfo.dimensions, Vector(0, 0, 10))
{ {
@@ -49,14 +49,10 @@ void SceneView::update()
void SceneView::commitUpdate() void SceneView::commitUpdate()
{ {
depthPrepassData.staticDrawList = scene->getStaticMeshes();
lightCullingPassData.lightEnv = scene->getLightBuffer();
basePassData.staticDrawList = scene->getStaticMeshes();
} }
void SceneView::prepareRender() void SceneView::prepareRender()
{ {
renderGraph.updatePassData(depthPrepassData, lightCullingPassData, basePassData);
} }
void SceneView::render() void SceneView::render()
+1 -5
View File
@@ -26,7 +26,7 @@ public:
PScene getScene() const { return scene; } PScene getScene() const { return scene; }
private: private:
PScene scene; OScene scene;
Component::Camera viewportCamera; Component::Camera viewportCamera;
RenderGraph< RenderGraph<
@@ -34,10 +34,6 @@ private:
LightCullingPass, LightCullingPass,
BasePass> renderGraph; BasePass> renderGraph;
DepthPrepassData depthPrepassData;
LightCullingPassData lightCullingPassData;
BasePassData basePassData;
dp::thread_pool<> pool; dp::thread_pool<> pool;
ViewportControl cameraSystem; ViewportControl cameraSystem;
+3
View File
@@ -2,6 +2,9 @@
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Math/Vector.h" #include "Math/Vector.h"
#include "Component/Camera.h" #include "Component/Camera.h"
#include "Math/Math.h"
#include "Graphics/Enums.h"
#include "Containers/Array.h"
namespace Seele namespace Seele
{ {
+2 -2
View File
@@ -5,7 +5,7 @@
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Asset/AssetImporter.h" #include "Asset/AssetImporter.h"
#include "Asset/TextureLoader.h" #include "Asset/TextureLoader.h"
#include "Graphics/Vulkan/VulkanGraphics.h" #include "Graphics/Vulkan/Graphics.h"
#include "Asset/MeshLoader.h" #include "Asset/MeshLoader.h"
#include "Asset/TextureLoader.h" #include "Asset/TextureLoader.h"
#include "Asset/MaterialLoader.h" #include "Asset/MaterialLoader.h"
@@ -25,7 +25,7 @@ int main()
std::string sourcePath = "C:/Users/Dynamitos/TrackClear/"; std::string sourcePath = "C:/Users/Dynamitos/TrackClear/";
std::string binaryPath = "C:/Users/Dynamitos/TrackClear/bin/TrackClear.dll"; std::string binaryPath = "C:/Users/Dynamitos/TrackClear/bin/TrackClear.dll";
Gfx::PGraphics graphics = new Vulkan::Graphics(); Gfx::OGraphics graphics = new Vulkan::Graphics();
GraphicsInitializer initializer; GraphicsInitializer initializer;
graphics->init(initializer); graphics->init(initializer);
+33 -24
View File
@@ -193,28 +193,28 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer)
AssetFolder* folder = getOrCreateFolder(folderPath); AssetFolder* folder = getOrCreateFolder(folderPath);
PAsset asset; OAsset asset;
switch (identifier) switch (identifier)
{ {
case TextureAsset::IDENTIFIER: case TextureAsset::IDENTIFIER:
asset = new TextureAsset(folderPath, name); asset = new TextureAsset(folderPath, name);
folder->textures[asset->getName()] = asset; folder->textures[name] = std::move(asset);
break; break;
case MeshAsset::IDENTIFIER: case MeshAsset::IDENTIFIER:
asset = new MeshAsset(folderPath, name); asset = new MeshAsset(folderPath, name);
folder->meshes[asset->getName()] = asset; folder->meshes[name] = std::move(asset);
break; break;
case MaterialAsset::IDENTIFIER: case MaterialAsset::IDENTIFIER:
asset = new MaterialAsset(folderPath, name); asset = new MaterialAsset(folderPath, name);
folder->materials[asset->getName()] = asset; folder->materials[name] = std::move(asset);
break; break;
case MaterialInstanceAsset::IDENTIFIER: case MaterialInstanceAsset::IDENTIFIER:
asset = new MaterialInstanceAsset(folderPath, name); asset = new MaterialInstanceAsset(folderPath, name);
// TODO folder->instances[name] = std::move(asset);
break; break;
case FontAsset::IDENTIFIER: case FontAsset::IDENTIFIER:
asset = new FontAsset(folderPath, name); asset = new FontAsset(folderPath, name);
folder->fonts[asset->getName()] = asset; folder->fonts[name] = std::move(asset);
break; break;
default: default:
throw new std::logic_error("Unknown Identifier"); throw new std::logic_error("Unknown Identifier");
@@ -241,20 +241,19 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer)
switch (identifier) switch (identifier)
{ {
case TextureAsset::IDENTIFIER: case TextureAsset::IDENTIFIER:
asset = folder->textures.at(name); asset = PTextureAsset(folder->textures.at(name));
break; break;
case MeshAsset::IDENTIFIER: case MeshAsset::IDENTIFIER:
asset = folder->meshes.at(name); asset = PMeshAsset(folder->meshes.at(name));
break; break;
case MaterialAsset::IDENTIFIER: case MaterialAsset::IDENTIFIER:
asset = folder->materials.at(name); asset = PMaterialAsset(folder->materials.at(name));
break; break;
case MaterialInstanceAsset::IDENTIFIER: case MaterialInstanceAsset::IDENTIFIER:
//asset = new MaterialInstanceAsset(path); asset = PMaterialInstanceAsset(folder->instances.at(name));
// TODO
break; break;
case FontAsset::IDENTIFIER: case FontAsset::IDENTIFIER:
asset = folder->fonts.at(name); asset = PFontAsset(folder->fonts.at(name));
break; break;
default: default:
throw new std::logic_error("Unknown Identifier"); throw new std::logic_error("Unknown Identifier");
@@ -272,19 +271,23 @@ void AssetRegistry::saveFolder(const std::filesystem::path& folderPath, AssetFol
std::filesystem::create_directory(rootFolder / folderPath); std::filesystem::create_directory(rootFolder / folderPath);
for (const auto& [name, texture] : folder->textures) for (const auto& [name, texture] : folder->textures)
{ {
saveAsset(texture, TextureAsset::IDENTIFIER, folderPath, name); saveAsset(PTextureAsset(texture), TextureAsset::IDENTIFIER, folderPath, name);
} }
for (const auto& [name, mesh] : folder->meshes) for (const auto& [name, mesh] : folder->meshes)
{ {
saveAsset(mesh, MeshAsset::IDENTIFIER, folderPath, name); saveAsset(PMeshAsset(mesh), MeshAsset::IDENTIFIER, folderPath, name);
} }
for (const auto& [name, material] : folder->materials) for (const auto& [name, material] : folder->materials)
{ {
saveAsset(material, MaterialAsset::IDENTIFIER, folderPath, name); saveAsset(PMaterialAsset(material), MaterialAsset::IDENTIFIER, folderPath, name);
}
for (const auto& [name, material] : folder->instances)
{
saveAsset(PMaterialInstanceAsset(material), MaterialInstanceAsset::IDENTIFIER, folderPath, name);
} }
for (const auto& [name, font] : folder->fonts) for (const auto& [name, font] : folder->fonts)
{ {
saveAsset(font, FontAsset::IDENTIFIER, folderPath, name); saveAsset(PFontAsset(font), FontAsset::IDENTIFIER, folderPath, name);
} }
for (auto& [name, child] : folder->children) for (auto& [name, child] : folder->children)
{ {
@@ -316,28 +319,34 @@ std::filesystem::path AssetRegistry::getRootFolder()
return get().rootFolder; return get().rootFolder;
} }
void AssetRegistry::registerMesh(PMeshAsset mesh) void AssetRegistry::registerMesh(OMeshAsset mesh)
{ {
AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath()); AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath());
folder->meshes[mesh->getName()] = mesh; folder->meshes[mesh->getName()] = std::move(mesh);
} }
void AssetRegistry::registerTexture(PTextureAsset texture) void AssetRegistry::registerTexture(OTextureAsset texture)
{ {
AssetFolder* folder = getOrCreateFolder(texture->getFolderPath()); AssetFolder* folder = getOrCreateFolder(texture->getFolderPath());
folder->textures[texture->getName()] = texture; folder->textures[texture->getName()] = std::move(texture);
} }
void AssetRegistry::registerFont(PFontAsset font) void AssetRegistry::registerFont(OFontAsset font)
{ {
AssetFolder* folder = getOrCreateFolder(font->getFolderPath()); AssetFolder* folder = getOrCreateFolder(font->getFolderPath());
folder->fonts[font->getName()] = font; folder->fonts[font->getName()] = std::move(font);
} }
void AssetRegistry::registerMaterial(PMaterialAsset material) void AssetRegistry::registerMaterial(OMaterialAsset material)
{ {
AssetFolder* folder = getOrCreateFolder(material->getFolderPath()); AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
folder->materials[material->getName()] = material; folder->materials[material->getName()] = std::move(material);
}
void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material)
{
AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
folder->instances[material->getName()] = std::move(material);
} }
AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string fullPath) AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string fullPath)
+12 -9
View File
@@ -10,8 +10,8 @@ DECLARE_REF(TextureAsset)
DECLARE_REF(FontAsset) DECLARE_REF(FontAsset)
DECLARE_REF(MeshAsset) DECLARE_REF(MeshAsset)
DECLARE_REF(MaterialAsset) DECLARE_REF(MaterialAsset)
DECLARE_REF(MaterialInstanceAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
class AssetRegistry class AssetRegistry
{ {
public: public:
@@ -24,6 +24,7 @@ public:
static PTextureAsset findTexture(const std::string& filePath); static PTextureAsset findTexture(const std::string& filePath);
static PFontAsset findFont(const std::string& name); static PFontAsset findFont(const std::string& name);
static PMaterialAsset findMaterial(const std::string& filePath); static PMaterialAsset findMaterial(const std::string& filePath);
static PMaterialInstanceAsset findMaterialInstance(const std::string& filePath);
static std::ofstream createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::out); static std::ofstream createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::out);
static std::ifstream createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::in); static std::ifstream createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::in);
@@ -36,10 +37,11 @@ public:
{ {
std::string folderPath; std::string folderPath;
Map<std::string, AssetFolder*> children; Map<std::string, AssetFolder*> children;
Map<std::string, PTextureAsset> textures; Map<std::string, OTextureAsset> textures;
Map<std::string, PFontAsset> fonts; Map<std::string, OFontAsset> fonts;
Map<std::string, PMeshAsset> meshes; Map<std::string, OMeshAsset> meshes;
Map<std::string, PMaterialAsset> materials; Map<std::string, OMaterialAsset> materials;
Map<std::string, OMaterialInstanceAsset> instances;
AssetFolder(std::string_view folderPath); AssetFolder(std::string_view folderPath);
~AssetFolder(); ~AssetFolder();
}; };
@@ -59,10 +61,11 @@ private:
void saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder); void saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder);
void saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name); void saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name);
void registerMesh(PMeshAsset mesh); void registerMesh(OMeshAsset mesh);
void registerTexture(PTextureAsset texture); void registerTexture(OTextureAsset texture);
void registerFont(PFontAsset font); void registerFont(OFontAsset font);
void registerMaterial(PMaterialAsset material); void registerMaterial(OMaterialAsset material);
void registerMaterialInstance(OMaterialInstanceAsset instance);
std::ofstream internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::out); std::ofstream internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode = std::ios::out);
std::ifstream internalCreateReadStream(const std::filesystem::path& relaitvePath, std::ios_base::openmode openmode = std::ios::in); std::ifstream internalCreateReadStream(const std::filesystem::path& relaitvePath, std::ios_base::openmode openmode = std::ios::in);
+3 -1
View File
@@ -117,7 +117,9 @@ void FontAsset::load(ArchiveBuffer& buffer)
.usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT, .usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT,
}; };
glyph.texture = buffer.getGraphics()->createTexture2D(createInfo); Gfx::OTexture2D texture = buffer.getGraphics()->createTexture2D(createInfo);
glyph.texture = texture;
usedTextures.add(std::move(texture));
ktxTexture_Destroy(ktxTexture(kTexture)); ktxTexture_Destroy(ktxTexture(kTexture));
+2 -1
View File
@@ -18,13 +18,14 @@ public:
struct Glyph struct Glyph
{ {
Gfx::OTexture2D texture; Gfx::PTexture2D texture;
IVector2 size; IVector2 size;
IVector2 bearing; IVector2 bearing;
uint32 advance; uint32 advance;
}; };
const Map<uint32, Glyph> getGlyphData() const { return glyphs; } const Map<uint32, Glyph> getGlyphData() const { return glyphs; }
private: private:
Array<Gfx::OTexture2D> usedTextures;
Map<uint32, Glyph> glyphs; Map<uint32, Glyph> glyphs;
friend class FontLoader; friend class FontLoader;
}; };
+11
View File
@@ -1,6 +1,7 @@
#include "MaterialAsset.h" #include "MaterialAsset.h"
#include "Material/Material.h" #include "Material/Material.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "MaterialInstanceAsset.h"
using namespace Seele; using namespace Seele;
@@ -29,3 +30,13 @@ void MaterialAsset::load(ArchiveBuffer& buffer)
material->compile(); material->compile();
} }
OMaterialInstanceAsset Seele::MaterialAsset::instantiate(const InstantiationParameter& params)
{
OMaterialInstance instance = material->instantiate();
instance->setBaseMaterial(this);
OMaterialInstanceAsset asset = new MaterialInstanceAsset(params.folderPath, params.name);
asset->setHandle(std::move(instance));
return asset;
}
+8 -1
View File
@@ -4,6 +4,12 @@
namespace Seele namespace Seele
{ {
DECLARE_REF(Material) DECLARE_REF(Material)
DECLARE_REF(MaterialInstanceAsset)
struct InstantiationParameter
{
std::string name;
std::string folderPath;
};
class MaterialAsset : public Asset class MaterialAsset : public Asset
{ {
public: public:
@@ -14,8 +20,9 @@ public:
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
PMaterial getMaterial() const { return material; } PMaterial getMaterial() const { return material; }
OMaterialInstanceAsset instantiate(const InstantiationParameter& params);
private: private:
PMaterial material; OMaterial material;
friend class MaterialLoader; friend class MaterialLoader;
}; };
DEFINE_REF(MaterialAsset) DEFINE_REF(MaterialAsset)
@@ -2,6 +2,7 @@
#include "Material/MaterialInstance.h" #include "Material/MaterialInstance.h"
#include "Material/Material.h" #include "Material/Material.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h"
using namespace Seele; using namespace Seele;
@@ -21,8 +22,15 @@ MaterialInstanceAsset::~MaterialInstanceAsset()
void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, baseMaterial->getAssetIdentifier());
material->save(buffer);
} }
void MaterialInstanceAsset::load(ArchiveBuffer& buffer) void MaterialInstanceAsset::load(ArchiveBuffer& buffer)
{ {
std::string id;
Serialization::load(buffer, id);
material->load(buffer);
baseMaterial = AssetRegistry::findMaterial(id);
material->setBaseMaterial(baseMaterial);
} }
+4 -1
View File
@@ -13,8 +13,11 @@ public:
virtual ~MaterialInstanceAsset(); virtual ~MaterialInstanceAsset();
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
void setHandle(OMaterialInstance handle) { material = std::move(handle); }
void setBase(PMaterialAsset base) { baseMaterial = base; }
private: private:
PMaterialInstance material; OMaterialInstance material;
PMaterialAsset baseMaterial;
}; };
DEFINE_REF(MaterialInstanceAsset) DEFINE_REF(MaterialInstanceAsset)
} // namespace Seele } // namespace Seele
+1 -1
View File
@@ -16,7 +16,7 @@ public:
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
//Workaround while no editor //Workaround while no editor
Array<PMesh> meshes; Array<OMesh> meshes;
Component::Collider physicsMesh; Component::Collider physicsMesh;
}; };
DEFINE_REF(MeshAsset) DEFINE_REF(MeshAsset)
+3 -3
View File
@@ -13,16 +13,16 @@ public:
virtual ~TextureAsset(); virtual ~TextureAsset();
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
void setTexture(Gfx::PTexture _texture) void setTexture(Gfx::OTexture _texture)
{ {
texture = _texture; texture = std::move(_texture);
} }
Gfx::PTexture getTexture() Gfx::PTexture getTexture()
{ {
return texture; return texture;
} }
private: private:
Gfx::PTexture texture; Gfx::OTexture texture;
friend class TextureLoader; friend class TextureLoader;
}; };
DEFINE_REF(TextureAsset) DEFINE_REF(TextureAsset)
-2
View File
@@ -5,7 +5,6 @@
namespace Seele namespace Seele
{ {
DECLARE_NAME_REF(Gfx, Viewport)
namespace Component namespace Component
{ {
struct Camera struct Camera
@@ -24,7 +23,6 @@ struct Camera
{ {
return Vector(viewMatrix[3]); return Vector(viewMatrix[3]);
} }
void setViewport(Gfx::PViewport viewport);
void mouseMove(float deltaX, float deltaY); void mouseMove(float deltaX, float deltaY);
void mouseScroll(float x); void mouseScroll(float x);
void moveX(float amount); void moveX(float amount);
+2 -1
View File
@@ -393,7 +393,8 @@ public:
std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize++], arguments...); std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize++], arguments...);
return _data[arraySize - 1]; return _data[arraySize - 1];
} }
template<std::predicate Pred> template<class Pred>
requires std::predicate<Pred, value_type>
constexpr void remove_if(Pred pred, bool keepOrder = true) constexpr void remove_if(Pred pred, bool keepOrder = true)
{ {
remove(find(pred), keepOrder); remove(find(pred), keepOrder);
+36 -3
View File
@@ -272,6 +272,39 @@ public:
return getNode(root)->pair.value; return getNode(root)->pair.value;
} }
constexpr const mapped_type& operator[](const key_type& key) const
{
size_t it = root;
while (!equal(getNode(it)->pair.key, key))
{
if (comp(key, getNode(it)->pair.key))
{
it = getNode(it)->leftChild;
}
else
{
it = getNode(it)->rightChild;
}
}
return getNode(it)->pair.value;
}
constexpr const mapped_type& operator[](key_type&& key) const
{
size_t it = root;
while (!equal(getNode(it)->pair.key, key))
{
if (comp(key, getNode(it)->pair.key))
{
it = getNode(it)->leftChild;
}
else
{
it = getNode(it)->rightChild;
}
}
return getNode(it)->pair.value;
}
constexpr mapped_type& at(const key_type& key) constexpr mapped_type& at(const key_type& key)
{ {
root = splay(root, key); root = splay(root, key);
@@ -414,11 +447,11 @@ public:
buffer.readBytes(&len, sizeof(uint64)); buffer.readBytes(&len, sizeof(uint64));
for(uint64 i = 0; i < len; ++i) for(uint64 i = 0; i < len; ++i)
{ {
K k; K k = K();
V v; V v = V();
Serialization::load(buffer, k); Serialization::load(buffer, k);
Serialization::load(buffer, v); Serialization::load(buffer, v);
this->operator[](k) = v; this->operator[](std::move(k)) = std::move(v);
} }
} }
private: private:
-3
View File
@@ -19,8 +19,6 @@ target_sources(Engine
Resources.cpp Resources.cpp
Shader.h Shader.h
Shader.cpp Shader.cpp
ShaderCompiler.h
ShaderCompiler.cpp
StaticMeshVertexData.h StaticMeshVertexData.h
StaticMeshVertexData.cpp StaticMeshVertexData.cpp
Texture.h Texture.h
@@ -40,7 +38,6 @@ target_sources(Engine
RenderTarget.h RenderTarget.h
Resources.h Resources.h
Shader.h Shader.h
ShaderCompiler.h
StaticMeshVertexData.h StaticMeshVertexData.h
Texture.h Texture.h
VertexData.h) VertexData.h)
+2 -2
View File
@@ -132,12 +132,12 @@ public:
virtual ~PipelineLayout() {} virtual ~PipelineLayout() {}
virtual void create() = 0; virtual void create() = 0;
virtual void reset() = 0; virtual void reset() = 0;
void addDescriptorLayout(uint32 setIndex, const PDescriptorLayout layout); void addDescriptorLayout(uint32 setIndex, PDescriptorLayout layout);
void addPushConstants(const SePushConstantRange& pushConstants); void addPushConstants(const SePushConstantRange& pushConstants);
virtual uint32 getHash() const = 0; virtual uint32 getHash() const = 0;
protected: protected:
Array<const PDescriptorLayout> descriptorSetLayouts; Array<PDescriptorLayout> descriptorSetLayouts;
Array<SePushConstantRange> pushConstants; Array<SePushConstantRange> pushConstants;
}; };
DEFINE_REF(PipelineLayout) DEFINE_REF(PipelineLayout)
+1 -1
View File
@@ -1,4 +1,4 @@
#include "GraphicsEnums.h" #include "Enums.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Gfx; using namespace Seele::Gfx;
-6
View File
@@ -173,12 +173,6 @@ static constexpr uint32 numVerticesPerMeshlet = 64;
static constexpr uint32 numPrimitivesPerMeshlet = 126; static constexpr uint32 numPrimitivesPerMeshlet = 126;
double getCurrentFrameDelta(); double getCurrentFrameDelta();
enum class RenderPassType : uint8
{
DepthPrepass,
BasePass
};
enum class QueueType enum class QueueType
{ {
GRAPHICS = 1, GRAPHICS = 1,
+3 -1
View File
@@ -1,5 +1,6 @@
#include "Graphics.h" #include "Graphics.h"
#include "ShaderCompiler.h" #include "Shader.h"
#include "Graphics.h"
using namespace Seele::Gfx; using namespace Seele::Gfx;
@@ -11,3 +12,4 @@ Graphics::Graphics()
Graphics::~Graphics() Graphics::~Graphics()
{ {
} }
+1
View File
@@ -2,6 +2,7 @@
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Resources.h" #include "Resources.h"
#include "Containers/Array.h" #include "Containers/Array.h"
#include "Shader.h"
namespace Seele namespace Seele
{ {
+78 -34
View File
@@ -1,48 +1,92 @@
#include "Initializer.h" #include "Initializer.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Graphics; using namespace Seele::Gfx;
LegacyPipelineCreateInfo::LegacyPipelineCreateInfo() LegacyPipelineCreateInfo::LegacyPipelineCreateInfo()
: topology(Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) : topology(Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)
, multisampleState(MultisampleState{ , multisampleState(MultisampleState{
.samples = 1, .samples = 1,
}) })
, rasterizationState(RasterizationState{ , rasterizationState(RasterizationState{
.polygonMode = Gfx::SE_POLYGON_MODE_FILL, .polygonMode = Gfx::SE_POLYGON_MODE_FILL,
.cullMode = Gfx::SE_CULL_MODE_BACK_BIT, .cullMode = Gfx::SE_CULL_MODE_BACK_BIT,
.frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE, .frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE,
}) })
, depthStencilState(DepthStencilState{ , depthStencilState(DepthStencilState{
.depthTestEnable = true, .depthTestEnable = true,
.depthWriteEnable = true, .depthWriteEnable = true,
.stencilTestEnable = false, .stencilTestEnable = false,
.depthCompareOp = Gfx::SE_COMPARE_OP_LESS_OR_EQUAL, .depthCompareOp = Gfx::SE_COMPARE_OP_LESS_OR_EQUAL,
.minDepthBounds = 0.0f, .minDepthBounds = 0.0f,
.maxDepthBounds = 1.0f, .maxDepthBounds = 1.0f,
}) })
, colorBlend(ColorBlendState{ , colorBlend(ColorBlendState{
.logicOpEnable = false, .logicOpEnable = false,
.attachmentCount = 0, .attachmentCount = 0,
.blendAttachments = { .blendAttachments = {
ColorBlendState::BlendAttachment{ ColorBlendState::BlendAttachment{
.colorWriteMask = .colorWriteMask =
Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_R_BIT |
Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT |
Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT |
Gfx::SE_COLOR_COMPONENT_A_BIT, Gfx::SE_COLOR_COMPONENT_A_BIT,
} }
}, },
.blendConstants = { .blendConstants = {
1.0f, 1.0f,
1.0f, 1.0f,
1.0f, 1.0f,
1.0f, 1.0f,
}, },
}) })
{ {
} }
Seele::Gfx::LegacyPipelineCreateInfo::~LegacyPipelineCreateInfo() LegacyPipelineCreateInfo::~LegacyPipelineCreateInfo()
{
}
MeshPipelineCreateInfo::MeshPipelineCreateInfo()
: multisampleState(MultisampleState{
.samples = 1,
})
, rasterizationState(RasterizationState{
.polygonMode = Gfx::SE_POLYGON_MODE_FILL,
.cullMode = Gfx::SE_CULL_MODE_BACK_BIT,
.frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE,
})
, depthStencilState(DepthStencilState{
.depthTestEnable = true,
.depthWriteEnable = true,
.stencilTestEnable = false,
.depthCompareOp = Gfx::SE_COMPARE_OP_LESS_OR_EQUAL,
.minDepthBounds = 0.0f,
.maxDepthBounds = 1.0f,
})
, colorBlend(ColorBlendState{
.logicOpEnable = false,
.attachmentCount = 0,
.blendAttachments = {
ColorBlendState::BlendAttachment{
.colorWriteMask =
Gfx::SE_COLOR_COMPONENT_R_BIT |
Gfx::SE_COLOR_COMPONENT_G_BIT |
Gfx::SE_COLOR_COMPONENT_B_BIT |
Gfx::SE_COLOR_COMPONENT_A_BIT,
}
},
.blendConstants = {
1.0f,
1.0f,
1.0f,
1.0f,
},
})
{
}
MeshPipelineCreateInfo::~MeshPipelineCreateInfo()
{ {
} }
+11 -44
View File
@@ -2,7 +2,6 @@
#include "Enums.h" #include "Enums.h"
#include "Containers/Map.h" #include "Containers/Map.h"
#include "Math/Math.h" #include "Math/Math.h"
#include "Shader.h"
namespace Seele namespace Seele
{ {
@@ -26,7 +25,7 @@ struct GraphicsInitializer
, engineName("SeeleEngine") , engineName("SeeleEngine")
, windowLayoutFile(nullptr) , windowLayoutFile(nullptr)
, layers{"VK_LAYER_KHRONOS_validation"} , layers{"VK_LAYER_KHRONOS_validation"}
, instanceExtensions{} , instanceExtensions{"VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME"}
, deviceExtensions{"VK_KHR_swapchain"} , deviceExtensions{"VK_KHR_swapchain"}
, windowHandle(nullptr) , windowHandle(nullptr)
{ {
@@ -102,18 +101,17 @@ struct IndexBufferCreateInfo
struct UniformBufferCreateInfo struct UniformBufferCreateInfo
{ {
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
uint8 bDynamic = 0; uint8 dynamic = 0;
}; };
struct ShaderBufferCreateInfo struct ShaderBufferCreateInfo
{ {
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
uint32 stride; uint32 stride;
uint8 bDynamic = 0; uint8 dynamic = 0;
}; };
struct ShaderCreateInfo struct ShaderCreateInfo
{ {
std::string mainModule; std::string mainModule;
//It's possible to input multiple source files for materials or vertexFactories
Array<std::string> additionalModules; Array<std::string> additionalModules;
std::string name; // Debug info std::string name; // Debug info
std::string entryPoint; std::string entryPoint;
@@ -136,7 +134,7 @@ struct VertexElement
SeFormat vertexFormat; SeFormat vertexFormat;
uint8 attributeIndex; uint8 attributeIndex;
uint8 stride; uint8 stride;
uint8 bInstanced = 0; uint8 instanced = 0;
}; };
static_assert(std::is_aggregate_v<VertexElement>); static_assert(std::is_aggregate_v<VertexElement>);
struct RasterizationState struct RasterizationState
@@ -191,6 +189,11 @@ struct ColorBlendState
float blendConstants[4]; float blendConstants[4];
}; };
DECLARE_REF(VertexDeclaration) DECLARE_REF(VertexDeclaration)
DECLARE_REF(VertexShader)
DECLARE_REF(TaskShader)
DECLARE_REF(MeshShader)
DECLARE_REF(FragmentShader)
DECLARE_REF(ComputeShader)
DECLARE_REF(RenderPass) DECLARE_REF(RenderPass)
DECLARE_REF(PipelineLayout) DECLARE_REF(PipelineLayout)
struct LegacyPipelineCreateInfo struct LegacyPipelineCreateInfo
@@ -220,44 +223,8 @@ struct MeshPipelineCreateInfo
RasterizationState rasterizationState; RasterizationState rasterizationState;
DepthStencilState depthStencilState; DepthStencilState depthStencilState;
ColorBlendState colorBlend; ColorBlendState colorBlend;
MeshPipelineCreateInfo() MeshPipelineCreateInfo();
: multisampleState(MultisampleState{ ~MeshPipelineCreateInfo();
.samples = 1,
})
, rasterizationState(RasterizationState{
.polygonMode = Gfx::SE_POLYGON_MODE_FILL,
.cullMode = Gfx::SE_CULL_MODE_BACK_BIT,
.frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE,
})
, depthStencilState(DepthStencilState{
.depthTestEnable = true,
.depthWriteEnable = true,
.stencilTestEnable = false,
.depthCompareOp = Gfx::SE_COMPARE_OP_LESS_OR_EQUAL,
.minDepthBounds = 0.0f,
.maxDepthBounds = 1.0f,
})
, colorBlend(ColorBlendState{
.logicOpEnable = false,
.attachmentCount = 0,
.blendAttachments = {
ColorBlendState::BlendAttachment{
.colorWriteMask =
Gfx::SE_COLOR_COMPONENT_R_BIT |
Gfx::SE_COLOR_COMPONENT_G_BIT |
Gfx::SE_COLOR_COMPONENT_B_BIT |
Gfx::SE_COLOR_COMPONENT_A_BIT,
}
},
.blendConstants = {
1.0f,
1.0f,
1.0f,
1.0f,
},
})
{
}
}; };
struct ComputePipelineCreateInfo struct ComputePipelineCreateInfo
{ {
+1 -1
View File
@@ -11,7 +11,7 @@ Mesh::~Mesh()
{ {
} }
void Mesh::save(ArchiveBuffer& buffer) void Mesh::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, vertexData->getTypeName()); Serialization::save(buffer, vertexData->getTypeName());
Serialization::save(buffer, vertexCount); Serialization::save(buffer, vertexCount);
+15 -1
View File
@@ -15,9 +15,23 @@ public:
uint64 vertexCount; uint64 vertexCount;
PMaterialInstance referencedMaterial; PMaterialInstance referencedMaterial;
Array<Meshlet> meshlets; Array<Meshlet> meshlets;
void save(ArchiveBuffer& buffer); void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer); void load(ArchiveBuffer& buffer);
private: private:
}; };
DEFINE_REF(Mesh) DEFINE_REF(Mesh)
namespace Serialization
{
template<>
static void save(ArchiveBuffer& buffer, const OMesh& ptr)
{
ptr->save(buffer);
}
template<>
static void load(ArchiveBuffer& buffer, OMesh& ptr)
{
ptr = new Mesh();
ptr->load(buffer);
}
} // namespace Serialization
} // namespace Seele } // namespace Seele
+92 -81
View File
@@ -1,5 +1,6 @@
#include "BasePass.h" #include "BasePass.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/Shader.h"
#include "Window/Window.h" #include "Window/Window.h"
#include "Component/Camera.h" #include "Component/Camera.h"
#include "Component/Mesh.h" #include "Component/Mesh.h"
@@ -13,47 +14,25 @@ using namespace Seele;
BasePass::BasePass(Gfx::PGraphics graphics, PScene scene) BasePass::BasePass(Gfx::PGraphics graphics, PScene scene)
: RenderPass(graphics, scene) : RenderPass(graphics, scene)
, descriptorSets(4) , descriptorSets(6)
{ {
UniformBufferCreateInfo uniformInitializer;
basePassLayout = graphics->createPipelineLayout(); basePassLayout = graphics->createPipelineLayout();
lightLayout = graphics->createDescriptorLayout("LightLayout"); basePassLayout->addDescriptorLayout(INDEX_VIEW_PARAMS, viewParamsLayout);
basePassLayout->addDescriptorLayout(INDEX_LIGHT_ENV, scene->getLightEnvironment()->getDescriptorLayout());
// Directional Lights lightCullingLayout = graphics->createDescriptorLayout("BasePassLightCulling");
lightLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); // oLightIndexList
lightLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); lightCullingLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
// Point Lights // tLightIndexList
lightLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); lightCullingLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
lightLayout->addDescriptorBinding(3, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); // oLightGrid
// Light Index List lightCullingLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
lightLayout->addDescriptorBinding(4, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); // tLightGrid
// Light Grid lightCullingLayout->addDescriptorBinding(3, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
lightLayout->addDescriptorBinding(5, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE); lightCullingLayout->create();
lightLayout->create();
basePassLayout->addDescriptorLayout(INDEX_LIGHT_ENV, lightLayout);
descriptorSets[INDEX_LIGHT_ENV] = lightLayout->allocateDescriptorSet();
viewLayout = graphics->createDescriptorLayout("ViewLayout"); basePassLayout->addDescriptorLayout(INDEX_LIGHT_CULLING, lightCullingLayout);
viewLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
uniformInitializer.sourceData.size = sizeof(ViewParameter);
uniformInitializer.sourceData.data = (uint8*)&viewParams;
uniformInitializer.bDynamic = true;
viewParamBuffer = graphics->createUniformBuffer(uniformInitializer);
viewLayout->create();
basePassLayout->addDescriptorLayout(INDEX_VIEW_PARAMS, viewLayout);
descriptorSets[INDEX_VIEW_PARAMS] = viewLayout->allocateDescriptorSet();
sceneLayout = graphics->createDescriptorLayout("SceneLayout");
sceneLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
sceneLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
sceneLayout->create();
basePassLayout->addDescriptorLayout(INDEX_SCENE_DATA, sceneLayout);
//basePassLayout->addPushConstants(Gfx::SePushConstantRange{
// .stageFlags = (Gfx::SE_SHADER_STAGE_VERTEX_BIT | Gfx::SE_SHADER_STAGE_FRAGMENT_BIT),
// .offset = 0,
// .size = sizeof(uint32),
//});
} }
BasePass::~BasePass() BasePass::~BasePass()
@@ -62,61 +41,95 @@ BasePass::~BasePass()
void BasePass::beginFrame(const Component::Camera& cam) void BasePass::beginFrame(const Component::Camera& cam)
{ {
DataSource uniformUpdate; RenderPass::beginFrame(cam);
viewParams.viewMatrix = cam.getViewMatrix(); lightCullingLayout->reset();
viewParams.projectionMatrix = viewport->getProjectionMatrix(); descriptorSets[INDEX_VIEW_PARAMS] = viewParamsSet;
viewParams.cameraPosition = Vector4(cam.getCameraPosition(), 1); descriptorSets[INDEX_LIGHT_ENV] = scene->getLightEnvironment()->getDescriptorSet();
viewParams.screenDimensions = Vector2(static_cast<float>(viewport->getSizeX()), static_cast<float>(viewport->getSizeY())); descriptorSets[INDEX_LIGHT_CULLING] = lightCullingLayout->allocateDescriptorSet();
uniformUpdate.size = sizeof(ViewParameter);
uniformUpdate.data = (uint8*)&viewParams;
viewParamBuffer->updateContents(uniformUpdate);
viewLayout->reset();
lightLayout->reset();
descriptorSets[INDEX_SCENE_DATA] = sceneLayout->allocateDescriptorSet();
descriptorSets[INDEX_SCENE_DATA]->updateBuffer(0, passData.sceneDataBuffer);
descriptorSets[INDEX_SCENE_DATA]->writeChanges();
descriptorSets[INDEX_LIGHT_ENV] = lightLayout->allocateDescriptorSet();
descriptorSets[INDEX_VIEW_PARAMS] = viewLayout->allocateDescriptorSet();
descriptorSets[INDEX_VIEW_PARAMS]->updateBuffer(0, viewParamBuffer);
descriptorSets[INDEX_VIEW_PARAMS]->writeChanges();
//std::cout << "BasePass beginFrame()" << std::endl;
//co_return;
} }
void BasePass::render() void BasePass::render()
{ {
oLightIndexList->pipelineBarrier( oLightIndexList->pipelineBarrier(
Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
oLightGrid->pipelineBarrier( tLightIndexList->pipelineBarrier(
Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
oLightGrid->pipelineBarrier(
Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
tLightGrid->pipelineBarrier(
Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
descriptorSets[INDEX_LIGHT_ENV]->updateBuffer(0, passData.lightEnv.directionalLights); descriptorSets[INDEX_LIGHT_CULLING]->updateBuffer(0, oLightIndexList);
descriptorSets[INDEX_LIGHT_ENV]->updateBuffer(1, passData.lightEnv.numDirectional); descriptorSets[INDEX_LIGHT_CULLING]->updateBuffer(1, tLightIndexList);
descriptorSets[INDEX_LIGHT_ENV]->updateBuffer(2, passData.lightEnv.pointLights); descriptorSets[INDEX_LIGHT_CULLING]->updateTexture(2, oLightGrid);
descriptorSets[INDEX_LIGHT_ENV]->updateBuffer(3, passData.lightEnv.numPoints); descriptorSets[INDEX_LIGHT_CULLING]->updateTexture(3, tLightGrid);
descriptorSets[INDEX_LIGHT_ENV]->updateBuffer(4, oLightIndexList); descriptorSets[INDEX_LIGHT_CULLING]->writeChanges();
descriptorSets[INDEX_LIGHT_ENV]->updateTexture(5, oLightGrid);
descriptorSets[INDEX_LIGHT_ENV]->writeChanges();
graphics->beginRenderPass(renderPass); graphics->beginRenderPass(renderPass);
for (const auto& meshBatch : passData.staticDrawList) Gfx::ShaderPermutation permutation;
permutation.hasFragment = true;
permutation.useMeshShading = true;
permutation.hasTaskShader = true;
std::memcpy(permutation.taskFile, "MeshletBasePass", std::strlen("MeshletBasePass"));
std::memcpy(permutation.vertexMeshFile, "MeshletBasePass", std::strlen("MeshletBasePass"));
std::memcpy(permutation.fragmentFile, "BasePass", std::strlen("BasePass"));
for (VertexData* vertexData : VertexData::getList())
{ {
processor->processMeshBatch(meshBatch, viewport, renderPass, basePassLayout, primitiveLayout, descriptorSets); std::memcpy(permutation.vertexDataName, vertexData->getTypeName().c_str(), std::strlen(vertexData->getTypeName().c_str()));
const auto& materials = vertexData->getMaterialData();
for (const auto& [_, materialData] : materials)
{
// Create Pipeline(Material, VertexData)
// Descriptors:
// ViewData => global, static
// LightEnv => global, static
// LightCulling => global, static
// Material => per material
// VertexData => per meshtype
// SceneData => per material instance
std::memcpy(permutation.materialName, materialData.material->getName().c_str(), std::strlen(materialData.material->getName().c_str()));
Gfx::PermutationId id(permutation);
Gfx::PRenderCommand command = graphics->createRenderCommand("DepthRender");
Gfx::OPipelineLayout layout = graphics->createPipelineLayout(basePassLayout);
layout->addDescriptorLayout(INDEX_MATERIAL, materialData.material->getDescriptorLayout());
layout->addDescriptorLayout(INDEX_VERTEX_DATA, vertexData->getVertexDataLayout());
layout->addDescriptorLayout(INDEX_SCENE_DATA, vertexData->getInstanceDataLayout());
layout->create();
const Gfx::ShaderCollection* collection = graphics->getShaderCompiler()->findShaders(id);
assert(collection != nullptr);
Gfx::MeshPipelineCreateInfo pipelineInfo;
pipelineInfo.taskShader = collection->taskShader;
pipelineInfo.meshShader = collection->meshShader;
pipelineInfo.fragmentShader = collection->fragmentShader;
pipelineInfo.pipelineLayout = layout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.depthStencilState.depthCompareOp = Gfx::SE_COMPARE_OP_LESS_OR_EQUAL;
Gfx::PGraphicsPipeline pipeline = graphics->createGraphicsPipeline(pipelineInfo);
command->bindPipeline(pipeline);
descriptorSets[INDEX_VERTEX_DATA] = vertexData->getVertexDataSet();
for (const auto& [_, instance] : materialData.instances)
{
descriptorSets[INDEX_MATERIAL] = instance.materialInstance->getDescriptorSet();
descriptorSets[INDEX_SCENE_DATA] = instance.descriptorSet;
command->bindDescriptor(descriptorSets);
command->dispatch(instance.numMeshes, 1, 1);
}
}
} }
graphics->executeCommands(processor->getRenderCommands());
graphics->endRenderPass(); graphics->endRenderPass();
//std::cout << "BasePass render()" << std::endl;
//co_return;
} }
void BasePass::endFrame() void BasePass::endFrame()
{ {
//std::cout << "BasePass endFrame()" << std::endl;
//co_return;
} }
void BasePass::publishOutputs() void BasePass::publishOutputs()
@@ -131,16 +144,14 @@ void BasePass::createRenderPass()
depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD;
colorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment->storeOp = Gfx::SE_ATTACHMENT_STORE_OP_STORE; colorAttachment->storeOp = Gfx::SE_ATTACHMENT_STORE_OP_STORE;
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(colorAttachment, depthAttachment); Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout(colorAttachment, depthAttachment);
renderPass = graphics->createRenderPass(layout, viewport); renderPass = graphics->createRenderPass(std::move(layout), viewport);
oLightIndexList = resources->requestBuffer("LIGHTCULLING_OLIGHTLIST"); oLightIndexList = resources->requestBuffer("LIGHTCULLING_OLIGHTLIST");
tLightIndexList = resources->requestBuffer("LIGHTCULLING_TLIGHTLIST");
oLightGrid = resources->requestTexture("LIGHTCULLING_OLIGHTGRID"); oLightGrid = resources->requestTexture("LIGHTCULLING_OLIGHTGRID");
tLightGrid = resources->requestTexture("LIGHTCULLING_TLIGHTGRID");
} }
void BasePass::modifyRenderPassMacros(Map<const char*, const char*>& defines) void BasePass::modifyRenderPassMacros(Map<const char*, const char*>& defines)
{ {
defines["INDEX_LIGHT_ENV"] = "0";
defines["INDEX_VIEW_PARAMS"] = "1";
defines["INDEX_MATERIAL"] = "2";
defines["INDEX_SCENE_DATA"] = "3";
} }
+18 -14
View File
@@ -9,6 +9,8 @@ class BasePass : public RenderPass
{ {
public: public:
BasePass(Gfx::PGraphics graphics, PScene scene); BasePass(Gfx::PGraphics graphics, PScene scene);
BasePass(BasePass&&) = default;
BasePass& operator=(BasePass&&) = default;
virtual ~BasePass(); virtual ~BasePass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -19,24 +21,26 @@ public:
private: private:
Gfx::PRenderTargetAttachment colorAttachment; Gfx::PRenderTargetAttachment colorAttachment;
Gfx::PTexture2D depthBuffer; Gfx::PTexture2D depthBuffer;
Gfx::PShaderBuffer oLightIndexList;
Gfx::PShaderBuffer tLightIndexList;
Gfx::PTexture2D oLightGrid;
Gfx::PTexture2D tLightGrid;
Array<Gfx::PDescriptorSet> descriptorSets; Array<Gfx::PDescriptorSet> descriptorSets;
PCameraActor source; PCameraActor source;
Gfx::OPipelineLayout basePassLayout; Gfx::OPipelineLayout basePassLayout;
// Set 0: Light environment // Set 0: viewParameter, provided by renderpass
static constexpr uint32 INDEX_LIGHT_ENV = 0; // Set 1: light environment, provided by lightenv
Gfx::OShaderBuffer oLightIndexList; static constexpr uint32 INDEX_LIGHT_ENV = 1;
Gfx::OTexture oLightGrid; // Set 2: light culling data
Gfx::ODescriptorLayout lightLayout; static constexpr uint32 INDEX_LIGHT_CULLING = 2;
// Set 1: viewParameter Gfx::ODescriptorLayout lightCullingLayout;
static constexpr uint32 INDEX_VIEW_PARAMS = 1; // Set 3: material data, generated from material
Gfx::ODescriptorLayout viewLayout; static constexpr uint32 INDEX_MATERIAL = 3;
Gfx::OUniformBuffer viewParamBuffer; // Set 4: vertex buffers, provided by vertexdata
// Set 2: materials, generated static constexpr uint32 INDEX_VERTEX_DATA = 4;
static constexpr uint32 INDEX_MATERIAL = 2; // Set 5: instance data, provided by vertexdata
// Set 3: primitive scene data static constexpr uint32 INDEX_SCENE_DATA = 5;
static constexpr uint32 INDEX_SCENE_DATA = 3;
Gfx::ODescriptorLayout sceneLayout;
}; };
DEFINE_REF(BasePass) DEFINE_REF(BasePass)
} // namespace Seele } // namespace Seele
@@ -12,6 +12,7 @@ target_sources(Engine
RenderGraphResources.h RenderGraphResources.h
RenderGraphResources.cpp RenderGraphResources.cpp
RenderPass.h RenderPass.h
RenderPass.cpp
SkyboxRenderPass.h SkyboxRenderPass.h
SkyboxRenderPass.cpp SkyboxRenderPass.cpp
TextPass.h TextPass.h
+126 -125
View File
@@ -16,128 +16,129 @@ void Seele::addDebugVertices(Array<DebugVertex> verts)
gDebugVertices.addAll(verts); gDebugVertices.addAll(verts);
} }
DebugPass::DebugPass(Gfx::PGraphics graphics) //DebugPass::DebugPass(Gfx::PGraphics graphics, PScene scene)
: RenderPass(graphics) // : RenderPass(graphics, scene)
{ //{
//
} //}
DebugPass::~DebugPass() //DebugPass::~DebugPass()
{ //{
//
} //}
//
void DebugPass::beginFrame(const Component::Camera& cam) //void DebugPass::beginFrame(const Component::Camera& cam)
{ //{
DataSource uniformUpdate; // RenderPass::beginFrame(cam);
// DataSource uniformUpdate;
viewParams.viewMatrix = cam.getViewMatrix(); //
viewParams.projectionMatrix = viewport->getProjectionMatrix(); // viewParams.viewMatrix = cam.getViewMatrix();
viewParams.cameraPosition = Vector4(cam.getCameraPosition(), 1); // viewParams.projectionMatrix = viewport->getProjectionMatrix();
viewParams.screenDimensions = Vector2(static_cast<float>(viewport->getSizeX()), static_cast<float>(viewport->getSizeY())); // viewParams.cameraPosition = Vector4(cam.getCameraPosition(), 1);
uniformUpdate.size = sizeof(ViewParameter); // viewParams.screenDimensions = Vector2(static_cast<float>(viewport->getSizeX()), static_cast<float>(viewport->getSizeY()));
uniformUpdate.data = (uint8*)&viewParams; // uniformUpdate.size = sizeof(ViewParameter);
viewParamsBuffer->updateContents(uniformUpdate); // uniformUpdate.data = (uint8*)&viewParams;
descriptorLayout->reset(); // viewParamsBuffer->updateContents(uniformUpdate);
descriptorSet = descriptorLayout->allocateDescriptorSet(); // descriptorLayout->reset();
descriptorSet->updateBuffer(0, viewParamsBuffer); // descriptorSet = descriptorLayout->allocateDescriptorSet();
descriptorSet->writeChanges(); // descriptorSet->updateBuffer(0, viewParamsBuffer);
// descriptorSet->writeChanges();
VertexBufferCreateInfo vertexBufferInfo = { //
.sourceData = { // VertexBufferCreateInfo vertexBufferInfo = {
.size = sizeof(DebugVertex) * passData.vertices.size(), // .sourceData = {
.data = (uint8*)passData.vertices.data(), // .size = sizeof(DebugVertex) * passData.vertices.size(),
}, // .data = (uint8*)passData.vertices.data(),
.vertexSize = sizeof(DebugVertex), // },
.numVertices = (uint32)passData.vertices.size(), // .vertexSize = sizeof(DebugVertex),
}; // .numVertices = (uint32)passData.vertices.size(),
debugVertices = graphics->createVertexBuffer(vertexBufferInfo); // };
// debugVertices = graphics->createVertexBuffer(vertexBufferInfo);
} //
//}
void DebugPass::render() //
{ //void DebugPass::render()
graphics->beginRenderPass(renderPass); //{
Gfx::PRenderCommand renderCommand = graphics->createRenderCommand("DebugRender"); // graphics->beginRenderPass(renderPass);
renderCommand->setViewport(viewport); // Gfx::PRenderCommand renderCommand = graphics->createRenderCommand("DebugRender");
renderCommand->bindPipeline(pipeline); // renderCommand->setViewport(viewport);
renderCommand->bindDescriptor(descriptorSet); // renderCommand->bindPipeline(pipeline);
renderCommand->bindVertexBuffer({VertexInputStream(0, 0, debugVertices)}); // renderCommand->bindDescriptor(descriptorSet);
renderCommand->draw((uint32)passData.vertices.size(), 1, 0, 0); // renderCommand->bindVertexBuffer({VertexInputStream(0, 0, debugVertices)});
graphics->executeCommands(Array{renderCommand}); // renderCommand->draw((uint32)passData.vertices.size(), 1, 0, 0);
graphics->endRenderPass(); // graphics->executeCommands(Array{renderCommand});
} // graphics->endRenderPass();
//}
void DebugPass::endFrame() //
{ //void DebugPass::endFrame()
//{
} //
//}
void DebugPass::publishOutputs() //
{ //void DebugPass::publishOutputs()
UniformBufferCreateInfo viewCreateInfo = { //{
.sourceData = DataSource { // UniformBufferCreateInfo viewCreateInfo = {
.size = sizeof(ViewParameter), // .sourceData = DataSource {
.data = nullptr, // .size = sizeof(ViewParameter),
}, // .data = nullptr,
.bDynamic = true // },
}; // .dynamic = true
viewParamsBuffer = graphics->createUniformBuffer(viewCreateInfo); // };
// viewParamsBuffer = graphics->createUniformBuffer(viewCreateInfo);
descriptorLayout = graphics->createDescriptorLayout("DebugDescLayout"); //
descriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); // descriptorLayout = graphics->createDescriptorLayout("DebugDescLayout");
descriptorLayout->create(); // descriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
// descriptorLayout->create();
pipelineLayout = graphics->createPipelineLayout(); //
pipelineLayout->addDescriptorLayout(0, descriptorLayout); // pipelineLayout = graphics->createPipelineLayout();
pipelineLayout->create(); // pipelineLayout->addDescriptorLayout(0, descriptorLayout);
} // pipelineLayout->create();
//}
void DebugPass::createRenderPass() //
{ //void DebugPass::createRenderPass()
Gfx::PRenderTargetAttachment baseColorAttachment = resources->requestRenderTarget("BASEPASS_COLOR"); //{
baseColorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; // Gfx::PRenderTargetAttachment baseColorAttachment = resources->requestRenderTarget("BASEPASS_COLOR");
Gfx::PRenderTargetAttachment depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); // baseColorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD;
depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; // Gfx::PRenderTargetAttachment depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH");
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(baseColorAttachment, depthAttachment); // depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD;
renderPass = graphics->createRenderPass(layout, viewport); // Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(baseColorAttachment, depthAttachment);
// renderPass = graphics->createRenderPass(layout, viewport);
ShaderCreateInfo createInfo; //
createInfo.name = "DebugVertex"; // ShaderCreateInfo createInfo;
createInfo.mainModule = "Debug"; // createInfo.name = "DebugVertex";
createInfo.entryPoint = "vertexMain"; // createInfo.mainModule = "Debug";
createInfo.defines["INDEX_VIEW_PARAMS"] = "0"; // createInfo.entryPoint = "vertexMain";
Gfx::PVertexShader vertexShader = graphics->createVertexShader(createInfo); // createInfo.defines["INDEX_VIEW_PARAMS"] = "0";
// Gfx::PVertexShader vertexShader = graphics->createVertexShader(createInfo);
createInfo.name = "DebugFragment"; //
// createInfo.name = "DebugFragment";
createInfo.entryPoint = "fragmentMain"; //
Gfx::PFragmentShader fragmentShader = graphics->createFragmentShader(createInfo); // createInfo.entryPoint = "fragmentMain";
// Gfx::PFragmentShader fragmentShader = graphics->createFragmentShader(createInfo);
Gfx::PVertexDeclaration vertexDecl = graphics->createVertexDeclaration({ //
Gfx::VertexElement { // Gfx::PVertexDeclaration vertexDecl = graphics->createVertexDeclaration({
.streamIndex = 0, // Gfx::VertexElement {
.offset = offsetof(DebugVertex, position), // .streamIndex = 0,
.vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT, // .offset = offsetof(DebugVertex, position),
.attributeIndex = 0, // .vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT,
.stride = sizeof(DebugVertex), // .attributeIndex = 0,
}, // .stride = sizeof(DebugVertex),
Gfx::VertexElement { // },
.streamIndex = 0, // Gfx::VertexElement {
.offset = offsetof(DebugVertex, color), // .streamIndex = 0,
.vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT, // .offset = offsetof(DebugVertex, color),
.attributeIndex = 1, // .vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT,
.stride = sizeof(DebugVertex), // .attributeIndex = 1,
} // .stride = sizeof(DebugVertex),
}); // }
// });
GraphicsPipelineCreateInfo gfxInfo; //
gfxInfo.vertexDeclaration = vertexDecl; // GraphicsPipelineCreateInfo gfxInfo;
gfxInfo.vertexShader = vertexShader; // gfxInfo.vertexDeclaration = vertexDecl;
gfxInfo.fragmentShader = fragmentShader; // gfxInfo.vertexShader = vertexShader;
gfxInfo.rasterizationState.polygonMode = Gfx::SE_POLYGON_MODE_LINE; // gfxInfo.fragmentShader = fragmentShader;
gfxInfo.rasterizationState.lineWidth = 5.f; // gfxInfo.rasterizationState.polygonMode = Gfx::SE_POLYGON_MODE_LINE;
gfxInfo.topology = Gfx::SE_PRIMITIVE_TOPOLOGY_LINE_LIST; // gfxInfo.rasterizationState.lineWidth = 5.f;
gfxInfo.pipelineLayout = pipelineLayout; // gfxInfo.topology = Gfx::SE_PRIMITIVE_TOPOLOGY_LINE_LIST;
gfxInfo.renderPass = renderPass; // gfxInfo.pipelineLayout = pipelineLayout;
pipeline = graphics->createGraphicsPipeline(gfxInfo); // gfxInfo.renderPass = renderPass;
} // pipeline = graphics->createGraphicsPipeline(gfxInfo);
//}
+8 -6
View File
@@ -11,7 +11,9 @@ DECLARE_REF(Viewport)
class DebugPass : public RenderPass class DebugPass : public RenderPass
{ {
public: public:
DebugPass(Gfx::PGraphics graphics); DebugPass(Gfx::PGraphics graphics, PScene scene);
DebugPass(DebugPass&&) = default;
DebugPass& operator=(DebugPass&&) = default;
virtual ~DebugPass(); virtual ~DebugPass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -19,12 +21,12 @@ public:
virtual void publishOutputs() override; virtual void publishOutputs() override;
virtual void createRenderPass() override; virtual void createRenderPass() override;
private: private:
Gfx::PVertexBuffer debugVertices; Gfx::OVertexBuffer debugVertices;
Gfx::PUniformBuffer viewParamsBuffer; Gfx::OUniformBuffer viewParamsBuffer;
Gfx::PDescriptorLayout descriptorLayout; Gfx::ODescriptorLayout descriptorLayout;
Gfx::PDescriptorSet descriptorSet; Gfx::PDescriptorSet descriptorSet;
Gfx::PPipelineLayout pipelineLayout; Gfx::OPipelineLayout pipelineLayout;
Gfx::PGraphicsPipeline pipeline; Gfx::OGraphicsPipeline pipeline;
}; };
DEFINE_REF(DebugPass) DEFINE_REF(DebugPass)
} // namespace Seele } // namespace Seele
+16 -31
View File
@@ -1,5 +1,6 @@
#include "DepthPrepass.h" #include "DepthPrepass.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/Shader.h"
#include "Window/Window.h" #include "Window/Window.h"
#include "Component/Camera.h" #include "Component/Camera.h"
#include "Component/Mesh.h" #include "Component/Mesh.h"
@@ -16,15 +17,7 @@ DepthPrepass::DepthPrepass(Gfx::PGraphics graphics, PScene scene)
UniformBufferCreateInfo uniformInitializer; UniformBufferCreateInfo uniformInitializer;
depthPrepassLayout = graphics->createPipelineLayout(); depthPrepassLayout = graphics->createPipelineLayout();
depthPrepassLayout->addDescriptorLayout(INDEX_VIEW_PARAMS, viewParamsLayout);
viewLayout = graphics->createDescriptorLayout("ViewLayout");
viewLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
uniformInitializer.sourceData.size = sizeof(ViewParameter);
uniformInitializer.sourceData.data = (uint8*)&viewParams;
uniformInitializer.bDynamic = true;
viewParamBuffer = graphics->createUniformBuffer(uniformInitializer);
viewLayout->create();
depthPrepassLayout->addDescriptorLayout(INDEX_VIEW_PARAMS, viewLayout);
} }
DepthPrepass::~DepthPrepass() DepthPrepass::~DepthPrepass()
@@ -33,22 +26,8 @@ DepthPrepass::~DepthPrepass()
void DepthPrepass::beginFrame(const Component::Camera& cam) void DepthPrepass::beginFrame(const Component::Camera& cam)
{ {
DataSource uniformUpdate; RenderPass::beginFrame(cam);
descriptorSets[INDEX_VIEW_PARAMS] = viewParamsSet;
viewParams.viewMatrix = cam.getViewMatrix();
viewParams.projectionMatrix = viewport->getProjectionMatrix();
viewParams.cameraPosition = Vector4(cam.getCameraPosition(), 1);
viewParams.screenDimensions = Vector2(static_cast<float>(viewport->getSizeX()), static_cast<float>(viewport->getSizeY()));
uniformUpdate.size = sizeof(ViewParameter);
uniformUpdate.data = (uint8*)&viewParams;
viewParamBuffer->updateContents(uniformUpdate);
viewLayout->reset();
descriptorSets[INDEX_VIEW_PARAMS] = viewLayout->allocateDescriptorSet();
descriptorSets[INDEX_VIEW_PARAMS]->updateBuffer(0, viewParamBuffer);
descriptorSets[INDEX_VIEW_PARAMS]->writeChanges();
//std::cout << "DepthPrepass beginFrame()" << std::endl;
//co_return;
} }
void DepthPrepass::render() void DepthPrepass::render()
@@ -57,9 +36,16 @@ void DepthPrepass::render()
Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); Gfx::SE_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT);
depthAttachment->getTexture()->transferOwnership(Gfx::QueueType::GRAPHICS); depthAttachment->getTexture()->transferOwnership(Gfx::QueueType::GRAPHICS);
Gfx::ShaderPermutation permutation;
permutation.hasFragment = false;
permutation.useMeshShading = true;
permutation.hasTaskShader = true;
std::memcpy(permutation.taskFile, "MeshletBasePass", sizeof("MeshletBasePass"));
std::memcpy(permutation.vertexMeshFile, "MeshletBasePass", sizeof("MeshletBasePass"));
graphics->beginRenderPass(renderPass); graphics->beginRenderPass(renderPass);
for (VertexData* vertexData : VertexData::getList()) for (VertexData* vertexData : VertexData::getList())
{ {
std::memcpy(permutation.vertexDataName, vertexData->getTypeName().c_str(), std::strlen(vertexData->getTypeName().c_str()));
const auto& materials = vertexData->getMaterialData(); const auto& materials = vertexData->getMaterialData();
for (const auto& [_, materialData] : materials) for (const auto& [_, materialData] : materials)
{ {
@@ -69,6 +55,9 @@ void DepthPrepass::render()
// Material => per material // Material => per material
// VertexData => per meshtype // VertexData => per meshtype
// SceneData => per material instance // SceneData => per material instance
std::memcpy(permutation.materialName, materialData.material->getName().c_str(), std::strlen(materialData.material->getName().c_str()));
Gfx::PermutationId id(permutation);
Gfx::PRenderCommand command = graphics->createRenderCommand("DepthRender"); Gfx::PRenderCommand command = graphics->createRenderCommand("DepthRender");
Gfx::OPipelineLayout layout = graphics->createPipelineLayout(depthPrepassLayout); Gfx::OPipelineLayout layout = graphics->createPipelineLayout(depthPrepassLayout);
layout->addDescriptorLayout(INDEX_MATERIAL, materialData.material->getDescriptorLayout()); layout->addDescriptorLayout(INDEX_MATERIAL, materialData.material->getDescriptorLayout());
@@ -91,14 +80,10 @@ void DepthPrepass::render()
} }
} }
graphics->endRenderPass(); graphics->endRenderPass();
//std::cout << "DepthPrepass render()" << std::endl;
//co_return;
} }
void DepthPrepass::endFrame() void DepthPrepass::endFrame()
{ {
//std::cout << "DepthPrepass endFrame()" << std::endl;
//co_return;
} }
void DepthPrepass::publishOutputs() void DepthPrepass::publishOutputs()
@@ -119,8 +104,8 @@ void DepthPrepass::publishOutputs()
void DepthPrepass::createRenderPass() void DepthPrepass::createRenderPass()
{ {
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(depthAttachment); Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout(depthAttachment);
renderPass = graphics->createRenderPass(layout, viewport); renderPass = graphics->createRenderPass(std::move(layout), viewport);
} }
void DepthPrepass::modifyRenderPassMacros(Map<const char*, const char*>& defines) void DepthPrepass::modifyRenderPassMacros(Map<const char*, const char*>& defines)
@@ -8,7 +8,9 @@ class DepthPrepass : public RenderPass
{ {
public: public:
DepthPrepass(Gfx::PGraphics graphics, PScene scene); DepthPrepass(Gfx::PGraphics graphics, PScene scene);
~DepthPrepass(); DepthPrepass(DepthPrepass&&) = default;
DepthPrepass& operator=(DepthPrepass&&) = default;
virtual ~DepthPrepass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
virtual void endFrame() override; virtual void endFrame() override;
@@ -23,15 +25,12 @@ private:
Gfx::OPipelineLayout depthPrepassLayout; Gfx::OPipelineLayout depthPrepassLayout;
// Set 0: viewParameter // Set 0: viewParameter
static constexpr uint32 INDEX_VIEW_PARAMS = 0;
Gfx::ODescriptorLayout viewLayout;
Gfx::OUniformBuffer viewParamBuffer;
// Set 1: materials, generated // Set 1: materials, generated
static constexpr uint32 INDEX_MATERIAL = 1; constexpr static uint32 INDEX_MATERIAL = 1;
// Set 2: vertices, from VertexData // Set 2: vertices, from VertexData
static constexpr uint32 INDEX_VERTEX_DATA = 2; constexpr static uint32 INDEX_VERTEX_DATA = 2;
// Set 3: mesh data, either index buffer or meshlet data // Set 3: mesh data, either index buffer or meshlet data
static constexpr uint32 INDEX_SCENE_DATA = 3; constexpr static uint32 INDEX_SCENE_DATA = 3;
Gfx::ODescriptorLayout sceneDataLayout; Gfx::ODescriptorLayout sceneDataLayout;
}; };
DEFINE_REF(DepthPrepass) DEFINE_REF(DepthPrepass)
@@ -19,46 +19,30 @@ LightCullingPass::~LightCullingPass()
void LightCullingPass::beginFrame(const Component::Camera& cam) void LightCullingPass::beginFrame(const Component::Camera& cam)
{ {
RenderPass::beginFrame(cam);
uint32_t viewportWidth = viewport->getSizeX(); uint32_t viewportWidth = viewport->getSizeX();
uint32_t viewportHeight = viewport->getSizeY(); uint32_t viewportHeight = viewport->getSizeY();
DataSource uniformUpdate;
viewParams.viewMatrix = cam.getViewMatrix();
viewParams.projectionMatrix = viewport->getProjectionMatrix();
viewParams.cameraPosition = Vector4(cam.getCameraPosition(), 1);
viewParams.screenDimensions = Vector2(static_cast<float>(viewportWidth), static_cast<float>(viewportHeight));
uniformUpdate.size = sizeof(ViewParameter);
uniformUpdate.data = (uint8*)&viewParams;
viewParamsBuffer->updateContents(uniformUpdate);
DataSource counterReset;
uint32 reset = 0; uint32 reset = 0;
counterReset.data = (uint8*)&reset; DataSource counterReset = {
counterReset.size = sizeof(uint32); .size = sizeof(uint32),
.data = (uint8*)&reset,
};
oLightIndexCounter->updateContents(counterReset); oLightIndexCounter->updateContents(counterReset);
tLightIndexCounter->updateContents(counterReset); tLightIndexCounter->updateContents(counterReset);
cullingDescriptorLayout->reset(); cullingDescriptorLayout->reset();
lightEnvDescriptorLayout->reset();
cullingDescriptorSet = cullingDescriptorLayout->allocateDescriptorSet(); cullingDescriptorSet = cullingDescriptorLayout->allocateDescriptorSet();
lightEnvDescriptorSet = lightEnvDescriptorLayout->allocateDescriptorSet();
cullingDescriptorSet->updateBuffer(0, viewParamsBuffer); cullingDescriptorSet->updateBuffer(0, dispatchParamsBuffer);
cullingDescriptorSet->updateBuffer(1, dispatchParamsBuffer); cullingDescriptorSet->updateTexture(1, depthAttachment);
cullingDescriptorSet->updateBuffer(3, oLightIndexCounter); cullingDescriptorSet->updateBuffer(2, oLightIndexCounter);
cullingDescriptorSet->updateBuffer(4, tLightIndexCounter); cullingDescriptorSet->updateBuffer(3, tLightIndexCounter);
cullingDescriptorSet->updateBuffer(5, oLightIndexList); cullingDescriptorSet->updateBuffer(4, oLightIndexList);
cullingDescriptorSet->updateBuffer(6, tLightIndexList); cullingDescriptorSet->updateBuffer(5, tLightIndexList);
cullingDescriptorSet->updateTexture(7, oLightGrid); cullingDescriptorSet->updateTexture(6, Gfx::PTexture2D(oLightGrid));
cullingDescriptorSet->updateTexture(8, tLightGrid); cullingDescriptorSet->updateTexture(7, Gfx::PTexture2D(tLightGrid));
cullingDescriptorSet->updateBuffer(9, frustumBuffer); cullingDescriptorSet->updateBuffer(8, frustumBuffer);
lightEnvDescriptorSet->updateBuffer(0, passData.lightEnv.directionalLights);
lightEnvDescriptorSet->updateBuffer(1, passData.lightEnv.numDirectional);
lightEnvDescriptorSet->updateBuffer(2, passData.lightEnv.pointLights);
lightEnvDescriptorSet->updateBuffer(3, passData.lightEnv.numPoints);
lightEnvDescriptorSet->writeChanges();
//std::cout << "LightCulling beginFrame()" << std::endl; //std::cout << "LightCulling beginFrame()" << std::endl;
//co_return; //co_return;
} }
@@ -80,9 +64,8 @@ void LightCullingPass::render()
cullingDescriptorSet->writeChanges(); cullingDescriptorSet->writeChanges();
Gfx::PComputeCommand computeCommand = graphics->createComputeCommand("CullingCommand"); Gfx::PComputeCommand computeCommand = graphics->createComputeCommand("CullingCommand");
computeCommand->bindPipeline(cullingPipeline); computeCommand->bindPipeline(cullingPipeline);
Array<Gfx::PDescriptorSet> descriptorSets = {cullingDescriptorSet, lightEnvDescriptorSet}; computeCommand->bindDescriptor({ viewParamsSet, lightEnv->getDescriptorSet(), cullingDescriptorSet });
computeCommand->bindDescriptor(descriptorSets); computeCommand->dispatch(dispatchParams.numThreadGroups.x, dispatchParams.numThreadGroups.y, dispatchParams.numThreadGroups.z);
//computeCommand->dispatch(dispatchParams.numThreadGroups.x, dispatchParams.numThreadGroups.y, dispatchParams.numThreadGroups.z);
Array<Gfx::PComputeCommand> commands = {computeCommand}; Array<Gfx::PComputeCommand> commands = {computeCommand};
graphics->executeCommands(commands); graphics->executeCommands(commands);
depthAttachment->changeLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); depthAttachment->changeLayout(Gfx::SE_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
@@ -105,42 +88,41 @@ void LightCullingPass::publishOutputs()
glm::uvec3 numThreadGroups = glm::ceil(glm::vec3(viewportWidth / (float)BLOCK_SIZE, viewportHeight / (float)BLOCK_SIZE, 1)); glm::uvec3 numThreadGroups = glm::ceil(glm::vec3(viewportWidth / (float)BLOCK_SIZE, viewportHeight / (float)BLOCK_SIZE, 1));
dispatchParams.numThreadGroups = numThreadGroups; dispatchParams.numThreadGroups = numThreadGroups;
dispatchParams.numThreads = numThreadGroups * glm::uvec3(BLOCK_SIZE, BLOCK_SIZE, 1); dispatchParams.numThreads = numThreadGroups * glm::uvec3(BLOCK_SIZE, BLOCK_SIZE, 1);
dispatchParamsBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{
.sourceData = {
.size = sizeof(DispatchParams),
.data = (uint8*)&dispatchParams,
},
.dynamic = false,
});
cullingDescriptorLayout = graphics->createDescriptorLayout("CullingLayout"); cullingDescriptorLayout = graphics->createDescriptorLayout("CullingLayout");
//ViewParams // Dispatchparams
cullingDescriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); cullingDescriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
//Dispatchparams
cullingDescriptorLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
//DepthTexture //DepthTexture
cullingDescriptorLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE); cullingDescriptorLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
//o_lightIndexCounter //o_lightIndexCounter
cullingDescriptorLayout->addDescriptorBinding(3, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); cullingDescriptorLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
//t_lightIndexCounter //t_lightIndexCounter
cullingDescriptorLayout->addDescriptorBinding(4, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); cullingDescriptorLayout->addDescriptorBinding(3, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
//o_lightIndexList //o_lightIndexList
cullingDescriptorLayout->addDescriptorBinding(5, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); cullingDescriptorLayout->addDescriptorBinding(4, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
//t_lightIndexList //t_lightIndexList
cullingDescriptorLayout->addDescriptorBinding(6, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER); cullingDescriptorLayout->addDescriptorBinding(5, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
//o_lightGrid //o_lightGrid
cullingDescriptorLayout->addDescriptorBinding(7, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE); cullingDescriptorLayout->addDescriptorBinding(6, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE);
//t_lightGrid //t_lightGrid
cullingDescriptorLayout->addDescriptorBinding(8, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE); cullingDescriptorLayout->addDescriptorBinding(7, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_IMAGE);
//Frustums //Frustums
cullingDescriptorLayout->addDescriptorBinding(9, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, viewportWidth * viewportHeight); cullingDescriptorLayout->addDescriptorBinding(8, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, viewportWidth * viewportHeight);
lightEnv = scene->getLightEnvironment();
lightEnvDescriptorLayout = graphics->createDescriptorLayout("LightEnv");
// Directional Lights
lightEnvDescriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, MAX_DIRECTIONAL_LIGHTS);
lightEnvDescriptorLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
// Point Lights
lightEnvDescriptorLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER, MAX_POINT_LIGHTS);
lightEnvDescriptorLayout->addDescriptorBinding(3, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
cullingLayout = graphics->createPipelineLayout(); cullingLayout = graphics->createPipelineLayout();
cullingLayout->addDescriptorLayout(0, cullingDescriptorLayout); cullingLayout->addDescriptorLayout(0, viewParamsLayout);
cullingLayout->addDescriptorLayout(1, lightEnvDescriptorLayout); cullingLayout->addDescriptorLayout(1, lightEnv->getDescriptorLayout());
cullingLayout->addDescriptorLayout(2, cullingDescriptorLayout);
cullingLayout->create(); cullingLayout->create();
ShaderCreateInfo createInfo; ShaderCreateInfo createInfo;
@@ -148,9 +130,6 @@ void LightCullingPass::publishOutputs()
createInfo.mainModule = "LightCulling"; createInfo.mainModule = "LightCulling";
createInfo.entryPoint = "cullLights"; createInfo.entryPoint = "cullLights";
createInfo.defines["INDEX_VIEW_PARAMS"] = "0";
createInfo.defines["INDEX_LIGHT_ENV"] = "1";
createInfo.defines["NUM_MATERIAL_TEXCOORDS"] = "0";
cullingShader = graphics->createComputeShader(createInfo); cullingShader = graphics->createComputeShader(createInfo);
Gfx::ComputePipelineCreateInfo pipelineInfo; Gfx::ComputePipelineCreateInfo pipelineInfo;
@@ -167,7 +146,7 @@ void LightCullingPass::publishOutputs()
.owner = Gfx::QueueType::COMPUTE, .owner = Gfx::QueueType::COMPUTE,
}, },
.stride = sizeof(uint32), .stride = sizeof(uint32),
.bDynamic = true, .dynamic = true,
}; };
oLightIndexCounter = graphics->createShaderBuffer(structInfo); oLightIndexCounter = graphics->createShaderBuffer(structInfo);
tLightIndexCounter = graphics->createShaderBuffer(structInfo); tLightIndexCounter = graphics->createShaderBuffer(structInfo);
@@ -181,7 +160,7 @@ void LightCullingPass::publishOutputs()
.owner = Gfx::QueueType::COMPUTE .owner = Gfx::QueueType::COMPUTE
}, },
.stride = sizeof(uint32), .stride = sizeof(uint32),
.bDynamic = false, .dynamic = false,
}; };
oLightIndexList = graphics->createShaderBuffer(structInfo); oLightIndexList = graphics->createShaderBuffer(structInfo);
tLightIndexList = graphics->createShaderBuffer(structInfo); tLightIndexList = graphics->createShaderBuffer(structInfo);
@@ -197,8 +176,8 @@ void LightCullingPass::publishOutputs()
oLightGrid = graphics->createTexture2D(textureInfo); oLightGrid = graphics->createTexture2D(textureInfo);
tLightGrid = graphics->createTexture2D(textureInfo); tLightGrid = graphics->createTexture2D(textureInfo);
resources->registerTextureOutput("LIGHTCULLING_OLIGHTGRID", oLightGrid); resources->registerTextureOutput("LIGHTCULLING_OLIGHTGRID", Gfx::PTexture2D(oLightGrid));
resources->registerTextureOutput("LIGHTCULLING_TLIGHTGRID", tLightGrid); resources->registerTextureOutput("LIGHTCULLING_TLIGHTGRID", Gfx::PTexture2D(tLightGrid));
} }
@@ -219,28 +198,22 @@ void LightCullingPass::setupFrustums()
glm::uvec3 numThreads = glm::ceil(glm::vec3(viewportWidth / (float)BLOCK_SIZE, viewportHeight / (float)BLOCK_SIZE, 1)); glm::uvec3 numThreads = glm::ceil(glm::vec3(viewportWidth / (float)BLOCK_SIZE, viewportHeight / (float)BLOCK_SIZE, 1));
glm::uvec3 numThreadGroups = glm::ceil(glm::vec3(numThreads.x / (float)BLOCK_SIZE, numThreads.y / (float)BLOCK_SIZE, 1)); glm::uvec3 numThreadGroups = glm::ceil(glm::vec3(numThreads.x / (float)BLOCK_SIZE, numThreads.y / (float)BLOCK_SIZE, 1));
viewParams = { RenderPass::beginFrame(Component::Camera());
.viewMatrix = Matrix4(),
.projectionMatrix = Matrix4(),
.cameraPosition = Vector4(),
.screenDimensions = glm::vec2(viewportWidth, viewportHeight),
};
dispatchParams.numThreads = numThreads; dispatchParams.numThreads = numThreads;
dispatchParams.numThreadGroups = numThreadGroups; dispatchParams.numThreadGroups = numThreadGroups;
Gfx::PDescriptorLayout frustumDescriptorLayout = graphics->createDescriptorLayout("FrustumLayout"); Gfx::ODescriptorLayout frustumDescriptorLayout = graphics->createDescriptorLayout("FrustumLayout");
frustumDescriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); frustumDescriptorLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
frustumDescriptorLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER); frustumDescriptorLayout->addDescriptorBinding(1, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
frustumDescriptorLayout->addDescriptorBinding(2, Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER);
frustumLayout = graphics->createPipelineLayout(); frustumLayout = graphics->createPipelineLayout();
frustumLayout->addDescriptorLayout(0, frustumDescriptorLayout); frustumLayout->addDescriptorLayout(0, viewParamsLayout);
frustumLayout->addDescriptorLayout(1, frustumDescriptorLayout);
frustumLayout->create(); frustumLayout->create();
ShaderCreateInfo createInfo; ShaderCreateInfo createInfo;
createInfo.name = "Frustum"; createInfo.name = "Frustum";
createInfo.mainModule = "ComputeFrustums"; createInfo.mainModule = "ComputeFrustums";
createInfo.entryPoint = "computeFrustums"; createInfo.entryPoint = "computeFrustums";
createInfo.defines["INDEX_VIEW_PARAMS"] = "0";
frustumShader = graphics->createComputeShader(createInfo); frustumShader = graphics->createComputeShader(createInfo);
Gfx::ComputePipelineCreateInfo pipelineInfo; Gfx::ComputePipelineCreateInfo pipelineInfo;
@@ -248,40 +221,31 @@ void LightCullingPass::setupFrustums()
pipelineInfo.pipelineLayout = frustumLayout; pipelineInfo.pipelineLayout = frustumLayout;
frustumPipeline = graphics->createComputePipeline(pipelineInfo); frustumPipeline = graphics->createComputePipeline(pipelineInfo);
DataSource resourceInfo; Gfx::OUniformBuffer frustumDispatchParamsBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{
UniformBufferCreateInfo uniformInfo; .sourceData = {
resourceInfo.size = sizeof(ViewParameter); .size = sizeof(DispatchParams),
resourceInfo.data = (uint8*)&viewParams; .data = (uint8*) & dispatchParams,
resourceInfo.owner = Gfx::QueueType::COMPUTE; },
uniformInfo.sourceData = resourceInfo; .dynamic = false,
uniformInfo.bDynamic = false; });
viewParamsBuffer = graphics->createUniformBuffer(uniformInfo);
resourceInfo.size = sizeof(DispatchParams); frustumBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{
resourceInfo.data = (uint8*)&dispatchParams;
uniformInfo.sourceData = resourceInfo;
uniformInfo.bDynamic = false;
dispatchParamsBuffer = graphics->createUniformBuffer(uniformInfo);
ShaderBufferCreateInfo structuredInfo = {
.sourceData = { .sourceData = {
.size = sizeof(Frustum) * numThreads.x * numThreads.y * numThreads.z, .size = sizeof(Frustum) * numThreads.x * numThreads.y * numThreads.z,
.data = nullptr, .data = nullptr,
}, },
.stride = sizeof(Frustum), .stride = sizeof(Frustum),
.bDynamic = false, .dynamic = false,
}; });
frustumBuffer = graphics->createShaderBuffer(structuredInfo);
frustumDescriptorSet = frustumDescriptorLayout->allocateDescriptorSet(); frustumDescriptorSet = frustumDescriptorLayout->allocateDescriptorSet();
frustumDescriptorSet->updateBuffer(0, viewParamsBuffer); frustumDescriptorSet->updateBuffer(0, frustumDispatchParamsBuffer);
frustumDescriptorSet->updateBuffer(1, dispatchParamsBuffer); frustumDescriptorSet->updateBuffer(1, frustumBuffer);
frustumDescriptorSet->updateBuffer(2, frustumBuffer);
frustumDescriptorSet->writeChanges(); frustumDescriptorSet->writeChanges();
Gfx::PComputeCommand command = graphics->createComputeCommand("FrustumCommand"); Gfx::PComputeCommand command = graphics->createComputeCommand("FrustumCommand");
command->bindPipeline(frustumPipeline); command->bindPipeline(frustumPipeline);
command->bindDescriptor(frustumDescriptorSet); command->bindDescriptor({ viewParamsSet, frustumDescriptorSet });
command->dispatch(numThreadGroups.x, numThreadGroups.y, numThreadGroups.z); command->dispatch(numThreadGroups.x, numThreadGroups.y, numThreadGroups.z);
Array<Gfx::PComputeCommand> commands = {command}; Array<Gfx::PComputeCommand> commands = {command};
graphics->executeCommands(commands); graphics->executeCommands(commands);
@@ -12,6 +12,8 @@ class LightCullingPass : public RenderPass
{ {
public: public:
LightCullingPass(Gfx::PGraphics graphics, PScene scene); LightCullingPass(Gfx::PGraphics graphics, PScene scene);
LightCullingPass(LightCullingPass&&) = default;
LightCullingPass& operator=(LightCullingPass&&) = default;
virtual ~LightCullingPass(); virtual ~LightCullingPass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -40,29 +42,28 @@ private:
Plane planes[4]; Plane planes[4];
}; };
Gfx::PShaderBuffer frustumBuffer; Gfx::OShaderBuffer frustumBuffer;
Gfx::PUniformBuffer dispatchParamsBuffer; Gfx::OUniformBuffer dispatchParamsBuffer;
Gfx::PUniformBuffer viewParamsBuffer; Gfx::OUniformBuffer viewParamsBuffer;
Gfx::PDescriptorSet frustumDescriptorSet; Gfx::PDescriptorSet frustumDescriptorSet;
Gfx::PComputeShader frustumShader; Gfx::OComputeShader frustumShader;
Gfx::PPipelineLayout frustumLayout; Gfx::OPipelineLayout frustumLayout;
Gfx::PComputePipeline frustumPipeline; Gfx::OComputePipeline frustumPipeline;
PLightEnvironment lightEnv;
Gfx::PTexture2D depthAttachment; Gfx::PTexture2D depthAttachment;
Gfx::PShaderBuffer frustums; Gfx::OShaderBuffer frustums;
Gfx::PShaderBuffer oLightIndexCounter; Gfx::OShaderBuffer oLightIndexCounter;
Gfx::PShaderBuffer tLightIndexCounter; Gfx::OShaderBuffer tLightIndexCounter;
Gfx::PShaderBuffer oLightIndexList; Gfx::OShaderBuffer oLightIndexList;
Gfx::PShaderBuffer tLightIndexList; Gfx::OShaderBuffer tLightIndexList;
Gfx::PTexture2D oLightGrid; Gfx::OTexture2D oLightGrid;
Gfx::PTexture2D tLightGrid; Gfx::OTexture2D tLightGrid;
Gfx::PDescriptorSet lightEnvDescriptorSet;
Gfx::PDescriptorSet cullingDescriptorSet; Gfx::PDescriptorSet cullingDescriptorSet;
Gfx::PDescriptorLayout lightEnvDescriptorLayout; Gfx::ODescriptorLayout cullingDescriptorLayout;
Gfx::PDescriptorLayout cullingDescriptorLayout; Gfx::OComputeShader cullingShader;
Gfx::PComputeShader cullingShader; Gfx::OPipelineLayout cullingLayout;
Gfx::PPipelineLayout cullingLayout; Gfx::OComputePipeline cullingPipeline;
Gfx::PComputePipeline cullingPipeline;
}; };
DEFINE_REF(LightCullingPass) DEFINE_REF(LightCullingPass)
} // namespace Seele } // namespace Seele
+2 -2
View File
@@ -24,7 +24,7 @@ template<typename This, typename... Rest>
class RenderGraph<This, Rest...> : private RenderGraph<Rest...> class RenderGraph<This, Rest...> : private RenderGraph<Rest...>
{ {
public: public:
RenderGraph(PRenderGraphResources resources, This&& pass, Rest&&... rest) RenderGraph(PRenderGraphResources resources, This pass, Rest... rest)
: RenderGraph<Rest...>(resources, std::move(rest)...) : RenderGraph<Rest...>(resources, std::move(rest)...)
, resources(resources) , resources(resources)
, rp(std::move(pass)) , rp(std::move(pass))
@@ -83,7 +83,7 @@ class RenderGraphBuilder
{ {
public: public:
template<typename... RenderPasses> template<typename... RenderPasses>
static RenderGraph<RenderPasses...> build(RenderPasses&&... renderPasses) static RenderGraph<RenderPasses...> build(RenderPasses... renderPasses)
{ {
PRenderGraphResources resources = new RenderGraphResources(); PRenderGraphResources resources = new RenderGraphResources();
return RenderGraph<RenderPasses...>(resources, std::move(renderPasses)...); return RenderGraph<RenderPasses...>(resources, std::move(renderPasses)...);
@@ -0,0 +1,54 @@
#include "RenderPass.h"
using namespace Seele;
RenderPass::RenderPass(Gfx::PGraphics graphics, PScene scene)
: graphics(graphics)
, scene(scene)
{
viewParamsLayout = graphics->createDescriptorLayout("ViewLayout");
viewParamsLayout->addDescriptorBinding(0, Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
UniformBufferCreateInfo uniformInitializer = {
.sourceData = {
.size = sizeof(ViewParameter),
.data = (uint8*)&viewParams,
},
.dynamic = true,
};
viewParamsBuffer = graphics->createUniformBuffer(uniformInitializer);
viewParamsLayout->create();
}
RenderPass::~RenderPass()
{}
void RenderPass::beginFrame(const Component::Camera& cam)
{
viewParams = {
.viewMatrix = cam.getViewMatrix(),
.projectionMatrix = viewport->getProjectionMatrix(),
.cameraPosition = Vector4(cam.getCameraPosition(), 1),
.screenDimensions = Vector2(static_cast<float>(viewport->getSizeX()), static_cast<float>(viewport->getSizeY())),
};
DataSource uniformUpdate = {
.size = sizeof(ViewParameter),
.data = (uint8*)&viewParams,
};
viewParamsBuffer->updateContents(uniformUpdate);
viewParamsLayout->reset();
viewParamsSet = viewParamsLayout->allocateDescriptorSet();
viewParamsSet->updateBuffer(0, viewParamsBuffer);
viewParamsSet->writeChanges();
}
void RenderPass::setResources(PRenderGraphResources _resources)
{
resources = _resources;
}
void RenderPass::setViewport(Gfx::PViewport _viewport)
{
viewport = _viewport;
publishOutputs();
}
+12 -14
View File
@@ -15,23 +15,17 @@ DECLARE_NAME_REF(Gfx, RenderPass)
class RenderPass class RenderPass
{ {
public: public:
RenderPass(Gfx::PGraphics graphics, PScene scene) RenderPass(Gfx::PGraphics graphics, PScene scene);
: graphics(graphics) RenderPass(RenderPass&&) = default;
, scene(scene) RenderPass& operator=(RenderPass&&) = default;
{} virtual ~RenderPass();
virtual ~RenderPass() virtual void beginFrame(const Component::Camera& cam);
{}
virtual void beginFrame(const Component::Camera& cam) = 0;
virtual void render() = 0; virtual void render() = 0;
virtual void endFrame() = 0; virtual void endFrame() = 0;
virtual void publishOutputs() = 0; virtual void publishOutputs() = 0;
virtual void createRenderPass() = 0; virtual void createRenderPass() = 0;
void setResources(PRenderGraphResources _resources) { resources = _resources; } void setResources(PRenderGraphResources _resources);
void setViewport(Gfx::PViewport _viewport) void setViewport(Gfx::PViewport _viewport);
{
viewport = _viewport;
publishOutputs();
}
protected: protected:
struct ViewParameter struct ViewParameter
{ {
@@ -42,7 +36,11 @@ protected:
Vector2 pad0; Vector2 pad0;
} viewParams; } viewParams;
PRenderGraphResources resources; PRenderGraphResources resources;
Gfx::PRenderPass renderPass; static constexpr uint32 INDEX_VIEW_PARAMS = 0;
Gfx::ODescriptorLayout viewParamsLayout;
Gfx::OShaderBuffer viewParamsBuffer;
Gfx::PDescriptorSet viewParamsSet;
Gfx::ORenderPass renderPass;
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
Gfx::PViewport viewport; Gfx::PViewport viewport;
PScene scene; PScene scene;
@@ -86,6 +86,7 @@ SkyboxRenderPass::~SkyboxRenderPass()
void SkyboxRenderPass::beginFrame(const Component::Camera& cam) void SkyboxRenderPass::beginFrame(const Component::Camera& cam)
{ {
RenderPass::beginFrame(cam);
DataSource uniformUpdate; DataSource uniformUpdate;
viewParams.viewMatrix = cam.getViewMatrix(); viewParams.viewMatrix = cam.getViewMatrix();
@@ -131,7 +132,7 @@ void SkyboxRenderPass::publishOutputs()
.size = sizeof(ViewParameter), .size = sizeof(ViewParameter),
.data = nullptr, .data = nullptr,
}, },
.bDynamic = true .dynamic = true
}; };
viewParamsBuffer = graphics->createUniformBuffer(viewCreateInfo); viewParamsBuffer = graphics->createUniformBuffer(viewCreateInfo);
@@ -161,8 +162,8 @@ void SkyboxRenderPass::createRenderPass()
baseColorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; baseColorAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD;
Gfx::PRenderTargetAttachment depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH"); Gfx::PRenderTargetAttachment depthAttachment = resources->requestRenderTarget("DEPTHPREPASS_DEPTH");
depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD; depthAttachment->loadOp = Gfx::SE_ATTACHMENT_LOAD_OP_LOAD;
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(baseColorAttachment, depthAttachment); Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout(baseColorAttachment, depthAttachment);
renderPass = graphics->createRenderPass(layout, viewport); renderPass = graphics->createRenderPass(std::move(layout), viewport);
ShaderCreateInfo createInfo; ShaderCreateInfo createInfo;
createInfo.name = "SkyboxVertex"; createInfo.name = "SkyboxVertex";
@@ -12,6 +12,8 @@ class SkyboxRenderPass : public RenderPass
{ {
public: public:
SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene); SkyboxRenderPass(Gfx::PGraphics graphics, PScene scene);
SkyboxRenderPass(SkyboxRenderPass&&) = default;
SkyboxRenderPass& operator=(SkyboxRenderPass&&) = default;
virtual ~SkyboxRenderPass(); virtual ~SkyboxRenderPass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -19,13 +21,13 @@ public:
virtual void publishOutputs() override; virtual void publishOutputs() override;
virtual void createRenderPass() override; virtual void createRenderPass() override;
private: private:
Gfx::PVertexBuffer cubeBuffer; Gfx::OVertexBuffer cubeBuffer;
Gfx::PUniformBuffer viewParamsBuffer; Gfx::OUniformBuffer viewParamsBuffer;
Gfx::PDescriptorLayout descriptorLayout; Gfx::ODescriptorLayout descriptorLayout;
Gfx::PDescriptorSet descriptorSet; Gfx::PDescriptorSet descriptorSet;
Gfx::PPipelineLayout pipelineLayout; Gfx::OPipelineLayout pipelineLayout;
Gfx::PGraphicsPipeline pipeline; Gfx::OGraphicsPipeline pipeline;
Gfx::PSamplerState skyboxSampler; Gfx::OSamplerState skyboxSampler;
Component::Skybox skybox; Component::Skybox skybox;
}; };
DEFINE_REF(SkyboxRenderPass) DEFINE_REF(SkyboxRenderPass)
+9 -7
View File
@@ -15,8 +15,9 @@ TextPass::~TextPass()
} }
void TextPass::beginFrame(const Component::Camera&) void TextPass::beginFrame(const Component::Camera& cam)
{ {
RenderPass::beginFrame(cam);
for(TextRender& render : texts) for(TextRender& render : texts)
{ {
FontData& fd = getFontData(render.font); FontData& fd = getFontData(render.font);
@@ -126,7 +127,7 @@ void TextPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT,
.attributeIndex = 0, .attributeIndex = 0,
.stride = sizeof(GlyphInstanceData), .stride = sizeof(GlyphInstanceData),
.bInstanced = 1 .instanced = 1
}); });
elements.add({ elements.add({
.binding = 0, .binding = 0,
@@ -134,7 +135,7 @@ void TextPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT,
.attributeIndex = 1, .attributeIndex = 1,
.stride = sizeof(GlyphInstanceData), .stride = sizeof(GlyphInstanceData),
.bInstanced = 1 .instanced = 1
}); });
elements.add({ elements.add({
.binding = 0, .binding = 0,
@@ -142,7 +143,7 @@ void TextPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32_UINT, .vertexFormat = Gfx::SE_FORMAT_R32_UINT,
.attributeIndex = 2, .attributeIndex = 2,
.stride = sizeof(GlyphInstanceData), .stride = sizeof(GlyphInstanceData),
.bInstanced = 1 .instanced = 1
}); });
declaration = graphics->createVertexDeclaration(elements); declaration = graphics->createVertexDeclaration(elements);
@@ -160,7 +161,7 @@ void TextPass::createRenderPass()
.size = sizeof(Matrix4), .size = sizeof(Matrix4),
.data = nullptr, .data = nullptr,
}, },
.bDynamic = true, .dynamic = true,
}); });
glyphSampler = graphics->createSamplerState({ glyphSampler = graphics->createSamplerState({
@@ -184,8 +185,8 @@ void TextPass::createRenderPass()
.size = sizeof(TextData)}); .size = sizeof(TextData)});
pipelineLayout->create(); pipelineLayout->create();
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(renderTarget, depthAttachment); Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout(renderTarget, depthAttachment);
renderPass = graphics->createRenderPass(layout, viewport); renderPass = graphics->createRenderPass(std::move(layout), viewport);
Gfx::LegacyPipelineCreateInfo pipelineInfo; Gfx::LegacyPipelineCreateInfo pipelineInfo;
pipelineInfo.vertexDeclaration = declaration; pipelineInfo.vertexDeclaration = declaration;
@@ -229,6 +230,7 @@ TextPass::FontData& TextPass::getFontData(PFontAsset font)
} }
fd.glyphDataSet = glyphData; fd.glyphDataSet = glyphData;
textureArrayLayout->reset();
fd.textureArraySet = textureArrayLayout->allocateDescriptorSet(); fd.textureArraySet = textureArrayLayout->allocateDescriptorSet();
fd.textureArraySet->updateTextureArray(0, textures); fd.textureArraySet->updateTextureArray(0, textures);
fd.textureArraySet->writeChanges(); fd.textureArraySet->writeChanges();
+11 -9
View File
@@ -21,6 +21,8 @@ class TextPass : public RenderPass
{ {
public: public:
TextPass(Gfx::PGraphics graphics, PScene scene); TextPass(Gfx::PGraphics graphics, PScene scene);
TextPass(TextPass&&) = default;
TextPass& operator=(TextPass&&) = default;
virtual ~TextPass(); virtual ~TextPass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -65,19 +67,19 @@ private:
Gfx::PRenderTargetAttachment renderTarget; Gfx::PRenderTargetAttachment renderTarget;
Gfx::PRenderTargetAttachment depthAttachment; Gfx::PRenderTargetAttachment depthAttachment;
Gfx::PDescriptorLayout generalLayout; Gfx::ODescriptorLayout generalLayout;
Gfx::PDescriptorLayout textureArrayLayout; Gfx::ODescriptorLayout textureArrayLayout;
Gfx::PDescriptorSet generalSet; Gfx::PDescriptorSet generalSet;
Gfx::PUniformBuffer projectionBuffer; Gfx::OUniformBuffer projectionBuffer;
Gfx::PSamplerState glyphSampler; Gfx::OSamplerState glyphSampler;
Gfx::PVertexDeclaration declaration; Gfx::OVertexDeclaration declaration;
Gfx::PVertexShader vertexShader; Gfx::OVertexShader vertexShader;
Gfx::PFragmentShader fragmentShader; Gfx::OFragmentShader fragmentShader;
Gfx::PPipelineLayout pipelineLayout; Gfx::OPipelineLayout pipelineLayout;
Gfx::PGraphicsPipeline pipeline; Gfx::OGraphicsPipeline pipeline;
Array<TextRender> texts; Array<TextRender> texts;
}; };
DEFINE_REF(TextPass); DEFINE_REF(TextPass);
+11 -10
View File
@@ -15,8 +15,9 @@ UIPass::~UIPass()
} }
void UIPass::beginFrame(const Component::Camera&) void UIPass::beginFrame(const Component::Camera& cam)
{ {
RenderPass::beginFrame(cam);
VertexBufferCreateInfo info = { VertexBufferCreateInfo info = {
.sourceData = { .sourceData = {
.size = (uint32)(sizeof(UI::RenderElementStyle) * renderElements.size()), .size = (uint32)(sizeof(UI::RenderElementStyle) * renderElements.size()),
@@ -103,7 +104,7 @@ void UIPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT,
.attributeIndex = 0, .attributeIndex = 0,
.stride = sizeof(UI::RenderElementStyle), .stride = sizeof(UI::RenderElementStyle),
.bInstanced = 1 .instanced = 1
}); });
decl.add({ decl.add({
.binding = 0, .binding = 0,
@@ -111,7 +112,7 @@ void UIPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32_UINT, .vertexFormat = Gfx::SE_FORMAT_R32_UINT,
.attributeIndex = 1, .attributeIndex = 1,
.stride = sizeof(UI::RenderElementStyle), .stride = sizeof(UI::RenderElementStyle),
.bInstanced = 1 .instanced = 1
}); });
decl.add({ decl.add({
.binding = 0, .binding = 0,
@@ -119,7 +120,7 @@ void UIPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32G32B32_SFLOAT,
.attributeIndex = 2, .attributeIndex = 2,
.stride = sizeof(UI::RenderElementStyle), .stride = sizeof(UI::RenderElementStyle),
.bInstanced = 1 .instanced = 1
}); });
decl.add({ decl.add({
.binding = 0, .binding = 0,
@@ -127,7 +128,7 @@ void UIPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32_SFLOAT,
.attributeIndex = 3, .attributeIndex = 3,
.stride = sizeof(UI::RenderElementStyle), .stride = sizeof(UI::RenderElementStyle),
.bInstanced = 1 .instanced = 1
}); });
decl.add({ decl.add({
.binding = 0, .binding = 0,
@@ -135,7 +136,7 @@ void UIPass::createRenderPass()
.vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT, .vertexFormat = Gfx::SE_FORMAT_R32G32_SFLOAT,
.attributeIndex = 4, .attributeIndex = 4,
.stride = sizeof(UI::RenderElementStyle), .stride = sizeof(UI::RenderElementStyle),
.bInstanced = 1 .instanced = 1
}); });
declaration = graphics->createVertexDeclaration(decl); declaration = graphics->createVertexDeclaration(decl);
@@ -152,7 +153,7 @@ void UIPass::createRenderPass()
.size = sizeof(Matrix4), .size = sizeof(Matrix4),
.data = (uint8*)&projectionMatrix, .data = (uint8*)&projectionMatrix,
}, },
.bDynamic = false, .dynamic = false,
}; };
Gfx::PUniformBuffer uniformBuffer = graphics->createUniformBuffer(info); Gfx::PUniformBuffer uniformBuffer = graphics->createUniformBuffer(info);
Gfx::PSamplerState backgroundSampler = graphics->createSamplerState({}); Gfx::PSamplerState backgroundSampler = graphics->createSamplerState({});
@@ -162,7 +163,7 @@ void UIPass::createRenderPass()
.size = sizeof(uint32), .size = sizeof(uint32),
.data = nullptr .data = nullptr
}, },
.bDynamic = true, .dynamic = true,
}; };
numTexturesBuffer = graphics->createUniformBuffer(info); numTexturesBuffer = graphics->createUniformBuffer(info);
@@ -176,8 +177,8 @@ void UIPass::createRenderPass()
pipelineLayout->addDescriptorLayout(0, descriptorLayout); pipelineLayout->addDescriptorLayout(0, descriptorLayout);
pipelineLayout->create(); pipelineLayout->create();
Gfx::PRenderTargetLayout layout = new Gfx::RenderTargetLayout(renderTarget, depthAttachment); Gfx::ORenderTargetLayout layout = new Gfx::RenderTargetLayout(std::move(renderTarget), std::move(depthAttachment));
renderPass = graphics->createRenderPass(layout, viewport); renderPass = graphics->createRenderPass(std::move(layout), viewport);
Gfx::LegacyPipelineCreateInfo pipelineInfo; Gfx::LegacyPipelineCreateInfo pipelineInfo;
pipelineInfo.vertexDeclaration = declaration; pipelineInfo.vertexDeclaration = declaration;
+3 -1
View File
@@ -11,6 +11,8 @@ class UIPass : public RenderPass
{ {
public: public:
UIPass(Gfx::PGraphics graphics, PScene scene); UIPass(Gfx::PGraphics graphics, PScene scene);
UIPass(UIPass&&) = default;
UIPass& operator=(UIPass&&) = default;
virtual ~UIPass(); virtual ~UIPass();
virtual void beginFrame(const Component::Camera& cam) override; virtual void beginFrame(const Component::Camera& cam) override;
virtual void render() override; virtual void render() override;
@@ -24,7 +26,7 @@ private:
Gfx::OTexture2D depthBuffer; Gfx::OTexture2D depthBuffer;
Gfx::ODescriptorLayout descriptorLayout; Gfx::ODescriptorLayout descriptorLayout;
Gfx::ODescriptorSet descriptorSet; Gfx::PDescriptorSet descriptorSet;
Gfx::OUniformBuffer numTexturesBuffer; Gfx::OUniformBuffer numTexturesBuffer;
Gfx::OVertexBuffer elementBuffer; Gfx::OVertexBuffer elementBuffer;
+13 -11
View File
@@ -8,38 +8,40 @@ RenderTargetLayout::RenderTargetLayout()
: inputAttachments() : inputAttachments()
, colorAttachments() , colorAttachments()
, depthAttachment() , depthAttachment()
, width(0)
, height(0)
{ {
} }
RenderTargetLayout::RenderTargetLayout(ORenderTargetAttachment depthAttachment) RenderTargetLayout::RenderTargetLayout(PRenderTargetAttachment depthAttachment)
: inputAttachments() : inputAttachments()
, colorAttachments() , colorAttachments()
, depthAttachment(std::move(depthAttachment)) , depthAttachment(depthAttachment)
, width(depthAttachment->getTexture()->getSizeX()) , width(depthAttachment->getTexture()->getSizeX())
, height(depthAttachment->getTexture()->getSizeY()) , height(depthAttachment->getTexture()->getSizeY())
{ {
} }
RenderTargetLayout::RenderTargetLayout(ORenderTargetAttachment colorAttachment, ORenderTargetAttachment depthAttachment) RenderTargetLayout::RenderTargetLayout(PRenderTargetAttachment colorAttachment, PRenderTargetAttachment depthAttachment)
: inputAttachments() : inputAttachments()
, depthAttachment(std::move(depthAttachment)) , depthAttachment(depthAttachment)
, width(depthAttachment->getTexture()->getSizeX()) , width(depthAttachment->getTexture()->getSizeX())
, height(depthAttachment->getTexture()->getSizeY()) , height(depthAttachment->getTexture()->getSizeY())
{ {
colorAttachments.add(colorAttachment); colorAttachments.add(colorAttachment);
} }
RenderTargetLayout::RenderTargetLayout(Array<ORenderTargetAttachment> colorAttachments, ORenderTargetAttachment depthAttachment) RenderTargetLayout::RenderTargetLayout(Array<PRenderTargetAttachment> colorAttachments, PRenderTargetAttachment depthAttachment)
: inputAttachments() : inputAttachments()
, colorAttachments(std::move(colorAttachments)) , colorAttachments(colorAttachments)
, depthAttachment(std::move(depthAttachment)) , depthAttachment(depthAttachment)
, width(depthAttachment->getTexture()->getSizeX()) , width(depthAttachment->getTexture()->getSizeX())
, height(depthAttachment->getTexture()->getSizeY()) , height(depthAttachment->getTexture()->getSizeY())
{ {
} }
RenderTargetLayout::RenderTargetLayout(Array<ORenderTargetAttachment> inputAttachments, Array<ORenderTargetAttachment> colorAttachments, ORenderTargetAttachment depthAttachment) RenderTargetLayout::RenderTargetLayout(Array<PRenderTargetAttachment> inputAttachments, Array<PRenderTargetAttachment> colorAttachments, PRenderTargetAttachment depthAttachment)
: inputAttachments(std::move(inputAttachments)) : inputAttachments(inputAttachments)
, colorAttachments(std::move(colorAttachments)) , colorAttachments(colorAttachments)
, depthAttachment(std::move(depthAttachment)) , depthAttachment(depthAttachment)
, width(depthAttachment->getTexture()->getSizeX()) , width(depthAttachment->getTexture()->getSizeX())
, height(depthAttachment->getTexture()->getSizeY()) , height(depthAttachment->getTexture()->getSizeY())
{ {
+10 -8
View File
@@ -167,13 +167,13 @@ class RenderTargetLayout
{ {
public: public:
RenderTargetLayout(); RenderTargetLayout();
RenderTargetLayout(ORenderTargetAttachment depthAttachment); RenderTargetLayout(PRenderTargetAttachment depthAttachment);
RenderTargetLayout(ORenderTargetAttachment colorAttachment, ORenderTargetAttachment depthAttachment); RenderTargetLayout(PRenderTargetAttachment colorAttachment, PRenderTargetAttachment depthAttachment);
RenderTargetLayout(Array<ORenderTargetAttachment> colorAttachments, ORenderTargetAttachment depthAttachmet); RenderTargetLayout(Array<PRenderTargetAttachment> colorAttachments, PRenderTargetAttachment depthAttachmet);
RenderTargetLayout(Array<ORenderTargetAttachment> inputAttachments, Array<ORenderTargetAttachment> colorAttachments, ORenderTargetAttachment depthAttachment); RenderTargetLayout(Array<PRenderTargetAttachment> inputAttachments, Array<PRenderTargetAttachment> colorAttachments, PRenderTargetAttachment depthAttachment);
Array<ORenderTargetAttachment> inputAttachments; Array<PRenderTargetAttachment> inputAttachments;
Array<ORenderTargetAttachment> colorAttachments; Array<PRenderTargetAttachment> colorAttachments;
ORenderTargetAttachment depthAttachment; PRenderTargetAttachment depthAttachment;
uint32 width; uint32 width;
uint32 height; uint32 height;
}; };
@@ -184,7 +184,9 @@ class RenderPass
public: public:
RenderPass(ORenderTargetLayout layout) : layout(std::move(layout)) {} RenderPass(ORenderTargetLayout layout) : layout(std::move(layout)) {}
virtual ~RenderPass() {} virtual ~RenderPass() {}
inline PRenderTargetLayout getLayout() { return layout; } RenderPass(RenderPass&&) = default;
RenderPass& operator=(RenderPass&&) = default;
PRenderTargetLayout getLayout() const { return layout; }
protected: protected:
ORenderTargetLayout layout; ORenderTargetLayout layout;
+4 -1
View File
@@ -1,9 +1,12 @@
#include "GraphicsResources.h" #include "Resources.h"
#include "Graphics.h" #include "Graphics.h"
#include "RenderPass/DepthPrepass.h" #include "RenderPass/DepthPrepass.h"
#include "RenderPass/BasePass.h" #include "RenderPass/BasePass.h"
#include "Material/Material.h" #include "Material/Material.h"
using namespace Seele;
using namespace Seele::Gfx;
QueueOwnedResource::QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType) QueueOwnedResource::QueueOwnedResource(QueueFamilyMapping mapping, QueueType startQueueType)
: currentOwner(startQueueType) : currentOwner(startQueueType)
, mapping(mapping) , mapping(mapping)
+2 -2
View File
@@ -83,7 +83,7 @@ class VertexDeclaration
{ {
public: public:
VertexDeclaration(); VertexDeclaration();
~VertexDeclaration(); virtual ~VertexDeclaration();
static PVertexDeclaration createDeclaration(PGraphics graphics, const Array<VertexElement>& elementList); static PVertexDeclaration createDeclaration(PGraphics graphics, const Array<VertexElement>& elementList);
private: private:
@@ -126,7 +126,7 @@ public:
virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0; virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) = 0;
virtual void pushConstants(Gfx::PPipelineLayout layout, Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) = 0; virtual void pushConstants(Gfx::PPipelineLayout layout, Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) = 0;
virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) = 0; virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) = 0;
virtual void dispatch(uint32 groupX, uint32 groupY, uint32 groupZ); virtual void dispatch(uint32 groupX, uint32 groupY, uint32 groupZ) = 0;
std::string name; std::string name;
}; };
DEFINE_REF(RenderCommand) DEFINE_REF(RenderCommand)
+99 -63
View File
@@ -5,89 +5,125 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Gfx; using namespace Seele::Gfx;
std::string getShaderNameFromRenderPassType(Gfx::RenderPassType type) ShaderCompiler::ShaderCompiler(Gfx::PGraphics graphics)
{ : graphics(graphics)
switch (type)
{
case Gfx::RenderPassType::DepthPrepass:
return "DepthPrepass";
case Gfx::RenderPassType::BasePass:
return "ForwardPlus";
default:
return "";
}
}
void modifyRenderPassMacros(Gfx::RenderPassType type, Map<const char*, const char*>& defines)
{
switch (type)
{
case Gfx::RenderPassType::DepthPrepass:
DepthPrepass::modifyRenderPassMacros(defines);
break;
case Gfx::RenderPassType::BasePass:
BasePass::modifyRenderPassMacros(defines);
break;
}
}
ShaderMap::ShaderMap()
{ {
} }
ShaderMap::~ShaderMap() ShaderCompiler::~ShaderCompiler()
{ {
} }
const ShaderCollection* ShaderMap::findShaders(PermutationId&& id) const const ShaderCollection* ShaderCompiler::findShaders(PermutationId id) const
{ {
for (uint32 i = 0; i < shaders.size(); ++i) return &shaders[id];
}
void ShaderCompiler::registerMaterial(PMaterial material)
{
materials[material->getName()] = material;
compile();
}
void ShaderCompiler::registerVertexData(VertexData* vd)
{
vertexData[vd->getTypeName()] = vd;
compile();
}
void ShaderCompiler::registerRenderPass(std::string name, std::string mainFile, bool useMaterials, bool hasFragmentShader, std::string fragmentFile, bool useMeshShading, bool hasTaskShader, std::string taskFile)
{
passes[name] = PassConfig{
.taskFile = taskFile,
.mainFile = mainFile,
.fragmentFile = fragmentFile,
.hasFragmentShader = hasFragmentShader,
.useMeshShading = useMeshShading,
.hasTaskShader = hasTaskShader,
.useMaterial = useMaterials,
};
compile();
}
void ShaderCompiler::compile()
{
ShaderPermutation permutation;
for (const auto& [name, pass] : passes)
{ {
if (shaders[i].id == id) std::memset(&permutation, 0, sizeof(ShaderPermutation));
permutation = {
.hasFragment = pass.hasFragmentShader,
.useMeshShading = pass.useMeshShading,
.hasTaskShader = pass.hasTaskShader,
};
std::memcpy(permutation.vertexMeshFile, pass.mainFile.c_str(), sizeof(permutation.vertexMeshFile));
if (pass.hasFragmentShader)
{ {
return &(shaders[i]); std::memcpy(permutation.fragmentFile, pass.fragmentFile.c_str(), sizeof(permutation.fragmentFile));
}
if (pass.hasTaskShader)
{
std::memcpy(permutation.taskFile, pass.taskFile.c_str(), sizeof(permutation.taskFile));
}
for (const auto& [vdName, vd] : vertexData)
{
std::memcpy(permutation.vertexDataName, vd->getTypeName().c_str(), sizeof(permutation.vertexDataName));
if (pass.useMaterial)
{
for (const auto& [matName, mat] : materials)
{
std::memcpy(permutation.materialName, matName.c_str(), sizeof(permutation.materialName));
createShaders(permutation);
}
}
else
{
std::memset(permutation.materialName, 0, sizeof(permutation.materialName));
createShaders(permutation);
}
} }
} }
return nullptr;
} }
ShaderCollection& ShaderMap::createShaders(
PGraphics graphics, ShaderCollection& ShaderCompiler::createShaders(ShaderPermutation permutation)
RenderPassType renderPass,
PMaterial material,
bool /*bPositionOnly*/)
{ {
std::scoped_lock lock(shadersLock); std::scoped_lock lock(shadersLock);
ShaderCollection& collection = shaders.add(); ShaderCollection collection;
//collection.vertexDeclaration = bPositionOnly ? vertexInput->getPositionDeclaration() : vertexInput->getDeclaration();
ShaderCreateInfo createInfo; ShaderCreateInfo createInfo;
createInfo.entryPoint = "vertexMain"; createInfo.typeParameter = { permutation.materialName, permutation.vertexDataName };
createInfo.typeParameter = { material->getName().c_str() }; createInfo.name = std::format("Material {0}", permutation.materialName);
createInfo.defines["NUM_MATERIAL_TEXCOORDS"] = "1"; createInfo.additionalModules.add(permutation.materialName);
createInfo.defines["USE_INSTANCING"] = "0"; createInfo.additionalModules.add(permutation.vertexDataName);
modifyRenderPassMacros(renderPass, createInfo.defines);
createInfo.name = getShaderNameFromRenderPassType(renderPass) + " Material " + material->getName();
std::ifstream codeStream("./shaders/" + getShaderNameFromRenderPassType(renderPass)); if (permutation.useMeshShading)
createInfo.mainModule = getShaderNameFromRenderPassType(renderPass);
createInfo.additionalModules.add(vertexInput->getShaderFilename());
createInfo.additionalModules.add(material->getName());
collection.vertexShader = graphics->createVertexShader(createInfo);
if (renderPass != RenderPassType::DepthPrepass)
{ {
createInfo.entryPoint = "fragmentMain"; if (permutation.hasTaskShader)
{
createInfo.mainModule = permutation.taskFile;
createInfo.entryPoint = "taskMain";
collection.taskShader = graphics->createTaskShader(createInfo);
}
createInfo.mainModule = permutation.vertexMeshFile;
createInfo.entryPoint = "meshMain";
collection.meshShader = graphics->createMeshShader(createInfo);
}
else
{
createInfo.mainModule = permutation.vertexMeshFile;
createInfo.entryPoint = "vertexMain";
collection.vertexShader = graphics->createVertexShader(createInfo);
}
if (permutation.hasFragment)
{
createInfo.mainModule = permutation.fragmentFile;
createInfo.entryPoint = "fragmentMain";
collection.fragmentShader = graphics->createFragmentShader(createInfo); collection.fragmentShader = graphics->createFragmentShader(createInfo);
} }
ShaderPermutation permutation; PermutationId perm = PermutationId(permutation);
std::string materialName = material->getName(); shaders[perm] = std::move(collection);
std::string vertexInputName = vertexInput->getName();
permutation.passType = renderPass;
std::memcpy(permutation.materialName, materialName.c_str(), sizeof(permutation.materialName));
std::memcpy(permutation.vertexInputName, vertexInputName.c_str(), sizeof(permutation.vertexInputName));
collection.id = PermutationId(permutation);
return collection; return shaders[perm];
} }
+44 -26
View File
@@ -2,6 +2,7 @@
#include "Enums.h" #include "Enums.h"
#include "CRC.h" #include "CRC.h"
#include "Resources.h" #include "Resources.h"
#include "VertexData.h"
namespace Seele namespace Seele
{ {
@@ -52,9 +53,14 @@ DEFINE_REF(ComputeShader)
//using the type parameters used to generate it //using the type parameters used to generate it
struct ShaderPermutation struct ShaderPermutation
{ {
RenderPassType passType; char taskFile[32];
char vertexInputName[15]; char vertexMeshFile[32];
char materialName[16]; char fragmentFile[32];
char vertexDataName[32];
char materialName[32];
uint8 hasFragment : 1;
uint8 useMeshShading : 1;
uint8 hasTaskShader : 1;
//TODO: lightmapping etc //TODO: lightmapping etc
}; };
//Hashed ShaderPermutation for fast lookup //Hashed ShaderPermutation for fast lookup
@@ -67,47 +73,59 @@ struct PermutationId
PermutationId(ShaderPermutation permutation) PermutationId(ShaderPermutation permutation)
: hash(CRC::Calculate(&permutation, sizeof(ShaderPermutation), CRC::CRC_32())) : hash(CRC::Calculate(&permutation, sizeof(ShaderPermutation), CRC::CRC_32()))
{} {}
friend inline bool operator==(const PermutationId& lhs, const PermutationId& rhs) friend constexpr bool operator==(const PermutationId& lhs, const PermutationId& rhs)
{ {
return lhs.hash == rhs.hash; return lhs.hash == rhs.hash;
} }
friend inline bool operator!=(const PermutationId& lhs, const PermutationId& rhs) friend constexpr auto operator<=>(const PermutationId& lhs, const PermutationId& rhs)
{ {
return lhs.hash != rhs.hash; return lhs.hash <=> rhs.hash;
}
friend inline bool operator<(const PermutationId& lhs, const PermutationId& rhs)
{
return lhs.hash < rhs.hash;
}
friend inline bool operator>(const PermutationId& lhs, const PermutationId& rhs)
{
return lhs.hash > rhs.hash;
} }
}; };
struct ShaderCollection struct ShaderCollection
{ {
PermutationId id;
OVertexDeclaration vertexDeclaration; OVertexDeclaration vertexDeclaration;
OVertexShader vertexShader; OVertexShader vertexShader;
OTaskShader taskShader; OTaskShader taskShader;
OMeshShader meshShader; OMeshShader meshShader;
OFragmentShader fragmentShader; OFragmentShader fragmentShader;
}; };
class ShaderMap class ShaderCompiler
{ {
public: public:
ShaderMap(); ShaderCompiler(Gfx::PGraphics graphics);
~ShaderMap(); ~ShaderCompiler();
const ShaderCollection* findShaders(PermutationId&& id) const; const ShaderCollection* findShaders(PermutationId id) const;
ShaderCollection& createShaders( void registerMaterial(PMaterial material);
PGraphics graphics, void registerVertexData(VertexData* vertexData);
RenderPassType passName, void registerRenderPass(std::string name,
bool bPositionOnly); std::string mainFile,
bool useMaterials = false,
bool hasFragmentShader = false,
std::string fragmentFile = "",
bool useMeshShading = false,
bool hasTaskShader = false,
std::string taskFile = "");
private: private:
void compile();
ShaderCollection& createShaders(ShaderPermutation permutation);
std::mutex shadersLock; std::mutex shadersLock;
Array<ShaderCollection> shaders; Map<PermutationId, ShaderCollection> shaders;
Map<std::string, PMaterial> materials;
Map<std::string, VertexData*> vertexData;
struct PassConfig
{
std::string taskFile;
std::string mainFile;
std::string fragmentFile;
bool hasFragmentShader;
bool useMeshShading;
bool hasTaskShader;
bool useMaterial;
};
Map<std::string, PassConfig> passes;
Gfx::PGraphics graphics;
}; };
DEFINE_REF(ShaderMap) DEFINE_REF(ShaderCompiler)
} }
} // namespace Seele } // namespace Seele
-18
View File
@@ -1,18 +0,0 @@
#include "ShaderCompiler.h"
#include "Graphics.h"
using namespace Seele;
using namespace Seele::Gfx;
ShaderCompiler::ShaderCompiler(PGraphics graphics)
: graphics(graphics)
{
}
ShaderCompiler::~ShaderCompiler()
{
}
-19
View File
@@ -1,19 +0,0 @@
#pragma once
#include "Material/Material.h"
namespace Seele
{
DECLARE_NAME_REF(Gfx, Graphics)
namespace Gfx
{
class ShaderCompiler
{
public:
ShaderCompiler(PGraphics graphics);
~ShaderCompiler();
private:
PGraphics graphics;
};
DEFINE_REF(ShaderCompiler)
} // namespace Gfx
} // namespace Seele
+2 -1
View File
@@ -135,7 +135,7 @@ void StaticMeshVertexData::resizeBuffers()
.size = verticesAllocated * sizeof(Vector), .size = verticesAllocated * sizeof(Vector),
}, },
.stride = sizeof(Vector), .stride = sizeof(Vector),
.bDynamic = true, .dynamic = true,
}; };
positions = graphics->createShaderBuffer(createInfo); positions = graphics->createShaderBuffer(createInfo);
normals = graphics->createShaderBuffer(createInfo); normals = graphics->createShaderBuffer(createInfo);
@@ -174,6 +174,7 @@ void StaticMeshVertexData::updateBuffers()
.size = biTangentData.size() * sizeof(Vector), .size = biTangentData.size() * sizeof(Vector),
.data = (uint8*)biTangentData.data(), .data = (uint8*)biTangentData.data(),
}); });
descriptorLayout->reset();
descriptorSet = descriptorLayout->allocateDescriptorSet(); descriptorSet = descriptorLayout->allocateDescriptorSet();
descriptorSet->updateBuffer(0, positions); descriptorSet->updateBuffer(0, positions);
descriptorSet->updateBuffer(1, texCoords); descriptorSet->updateBuffer(1, texCoords);
+2 -1
View File
@@ -1,4 +1,5 @@
#pragma once #pragma once
#include "Math/Vector.h"
#include "VertexData.h" #include "VertexData.h"
namespace Seele namespace Seele
@@ -35,6 +36,6 @@ private:
Gfx::OShaderBuffer biTangents; Gfx::OShaderBuffer biTangents;
Array<Vector> biTangentData; Array<Vector> biTangentData;
Gfx::ODescriptorLayout descriptorLayout; Gfx::ODescriptorLayout descriptorLayout;
Gfx::ODescriptorSet descriptorSet; Gfx::PDescriptorSet descriptorSet;
}; };
} }
+8 -4
View File
@@ -70,7 +70,7 @@ void VertexData::loadMesh(MeshId id, Array<Meshlet> loadedMeshlets)
.data = (uint8*)meshlets.data() .data = (uint8*)meshlets.data()
}, },
.stride = sizeof(MeshletDescription), .stride = sizeof(MeshletDescription),
.bDynamic = true, .dynamic = true,
}); });
vertexIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo { vertexIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo {
.sourceData = { .sourceData = {
@@ -78,7 +78,7 @@ void VertexData::loadMesh(MeshId id, Array<Meshlet> loadedMeshlets)
.data = (uint8*)vertexIndices.data(), .data = (uint8*)vertexIndices.data(),
}, },
.stride = sizeof(uint32), .stride = sizeof(uint32),
.bDynamic = true, .dynamic = true,
}); });
primitiveIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo { primitiveIndicesBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo {
.sourceData = { .sourceData = {
@@ -86,7 +86,7 @@ void VertexData::loadMesh(MeshId id, Array<Meshlet> loadedMeshlets)
.data = (uint8*)primitiveIndices.data(), .data = (uint8*)primitiveIndices.data(),
}, },
.stride = sizeof(uint8), .stride = sizeof(uint8),
.bDynamic = true, .dynamic = true,
}); });
} }
@@ -114,6 +114,7 @@ void VertexData::createDescriptors()
}, },
.stride = sizeof(InstanceData) .stride = sizeof(InstanceData)
}); });
instanceDataLayout->reset();
matInst.descriptorSet = instanceDataLayout->allocateDescriptorSet(); matInst.descriptorSet = instanceDataLayout->allocateDescriptorSet();
matInst.descriptorSet->updateBuffer(0, instanceBuffer); matInst.descriptorSet->updateBuffer(0, instanceBuffer);
if (Gfx::useMeshShading) if (Gfx::useMeshShading)
@@ -187,15 +188,18 @@ void Seele::VertexData::init(Gfx::PGraphics graphics)
} }
instanceDataLayout->create(); instanceDataLayout->create();
resizeBuffers(); resizeBuffers();
graphics->getShaderCompiler()->registerVertexData(this);
} }
VertexData::VertexData() VertexData::VertexData()
: idCounter(0) : idCounter(0)
, dirty(false) , dirty(false)
, head(0)
, verticesAllocated(0)
{ {
} }
void Meshlet::save(ArchiveBuffer& buffer) void Meshlet::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, uniqueVertices); Serialization::save(buffer, uniqueVertices);
Serialization::save(buffer, primitiveLayout); Serialization::save(buffer, primitiveLayout);
+2 -2
View File
@@ -26,7 +26,7 @@ struct Meshlet
StaticArray<uint8, Gfx::numPrimitivesPerMeshlet * 3> primitiveLayout; // indices into the uniqueVertices array, only uint8 needed StaticArray<uint8, Gfx::numPrimitivesPerMeshlet * 3> primitiveLayout; // indices into the uniqueVertices array, only uint8 needed
uint32 numVertices; uint32 numVertices;
uint32 numPrimitives; uint32 numPrimitives;
void save(ArchiveBuffer& buffer); void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer); void load(ArchiveBuffer& buffer);
}; };
class VertexData class VertexData
@@ -101,7 +101,7 @@ protected:
Array<MeshletDescription> meshlets; Array<MeshletDescription> meshlets;
Array<uint8> primitiveIndices; Array<uint8> primitiveIndices;
Array<uint32> vertexIndices; Array<uint32> vertexIndices;
Gfx::OGraphics graphics; Gfx::PGraphics graphics;
Gfx::ODescriptorLayout instanceDataLayout; Gfx::ODescriptorLayout instanceDataLayout;
// for mesh shading // for mesh shading
Gfx::OShaderBuffer meshletBuffer; Gfx::OShaderBuffer meshletBuffer;
+187 -79
View File
@@ -4,7 +4,7 @@
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
SubAllocation::SubAllocation(Allocation *owner, VkDeviceSize allocatedOffset, VkDeviceSize size, VkDeviceSize alignedOffset, VkDeviceSize allocatedSize) SubAllocation::SubAllocation(PAllocation owner, VkDeviceSize allocatedOffset, VkDeviceSize size, VkDeviceSize alignedOffset, VkDeviceSize allocatedSize)
: owner(owner) : owner(owner)
, size(size) , size(size)
, allocatedOffset(allocatedOffset) , allocatedOffset(allocatedOffset)
@@ -18,12 +18,22 @@ SubAllocation::~SubAllocation()
owner->markFree(this); owner->markFree(this);
} }
VkDeviceMemory SubAllocation::getHandle() const constexpr VkDeviceMemory SubAllocation::getHandle() const
{ {
return owner->getHandle(); return owner->getHandle();
} }
bool SubAllocation::isReadable() const constexpr VkDeviceSize SubAllocation::getSize() const
{
return size;
}
constexpr VkDeviceSize SubAllocation::getOffset() const
{
return alignedOffset;
}
constexpr bool SubAllocation::isReadable() const
{ {
return owner->isReadable(); return owner->isReadable();
} }
@@ -61,8 +71,7 @@ Allocation::Allocation(PGraphics graphics, PAllocator allocator, VkDeviceSize si
allocInfo.pNext = dedicatedInfo; allocInfo.pNext = dedicatedInfo;
VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &allocatedMemory)); VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &allocatedMemory));
bytesAllocated = size; bytesAllocated = size;
PSubAllocation freeRange = new SubAllocation(this, 0, size, 0, size); freeRanges[0] = new SubAllocation(this, 0, size, 0, size);
freeRanges[0] = freeRange;
canMap = (properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; canMap = (properties & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
isMapped = false; isMapped = false;
@@ -72,15 +81,15 @@ Allocation::~Allocation()
{ {
} }
PSubAllocation Allocation::getSuballocation(VkDeviceSize requestedSize, VkDeviceSize alignment) OSubAllocation Allocation::getSuballocation(VkDeviceSize requestedSize, VkDeviceSize alignment)
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
if (isDedicated) if (isDedicated)
{ {
if (activeAllocations.empty() && requestedSize == bytesAllocated) if (activeAllocations.empty() && requestedSize == bytesAllocated)
{ {
PSubAllocation suballoc = freeRanges[0]; OSubAllocation suballoc = std::move(freeRanges[0]);
activeAllocations[0] = suballoc.getHandle(); activeAllocations.add(suballoc);
freeRanges.clear(); freeRanges.clear();
bytesUsed += requestedSize; bytesUsed += requestedSize;
return suballoc; return suballoc;
@@ -92,37 +101,38 @@ PSubAllocation Allocation::getSuballocation(VkDeviceSize requestedSize, VkDevice
} }
for (auto& it : freeRanges) for (auto& it : freeRanges)
{ {
VkDeviceSize allocatedOffset = it.first; VkDeviceSize allocatedOffset = it.key;
PSubAllocation freeAllocation = it.second; OSubAllocation& freeAllocation = it.value;
assert(allocatedOffset == freeAllocation->allocatedOffset); assert(allocatedOffset == freeAllocation->allocatedOffset);
VkDeviceSize alignedOffset = align(allocatedOffset, alignment); VkDeviceSize alignedOffset = allocatedOffset + alignment - 1;
VkDeviceSize alignmentAdjustment = alignedOffset - allocatedOffset; alignedOffset /= alignment;
VkDeviceSize size = alignmentAdjustment + requestedSize; alignedOffset *= alignment;
if (freeAllocation->size == size) VkDeviceSize allocatedSize = requestedSize + (alignedOffset - allocatedOffset);
if (freeAllocation->size == allocatedSize)
{ {
activeAllocations[allocatedOffset] = freeAllocation.getHandle(); activeAllocations.add(freeAllocation);
freeRanges.erase(allocatedOffset); freeRanges.erase(allocatedOffset);
bytesUsed += size; bytesUsed += allocatedSize;
return freeAllocation; return std::move(freeAllocation);
} }
else if (size < freeAllocation->allocatedSize) else if (allocatedSize < freeAllocation->allocatedSize)
{ {
freeAllocation->size -= size; freeAllocation->size -= allocatedSize;
freeAllocation->allocatedSize -= size; freeAllocation->allocatedSize -= allocatedSize;
freeAllocation->allocatedOffset += size; freeAllocation->allocatedOffset += allocatedSize;
freeAllocation->alignedOffset += size; freeAllocation->alignedOffset += allocatedSize;
PSubAllocation subAlloc = new SubAllocation(this, allocatedOffset, size, alignedOffset, size); OSubAllocation subAlloc = new SubAllocation(this, allocatedOffset, allocatedSize, alignedOffset, allocatedSize);
activeAllocations[allocatedOffset] = subAlloc.getHandle(); activeAllocations.add(subAlloc);
freeRanges[freeAllocation->allocatedOffset] = std::move(freeAllocation);
freeRanges.erase(allocatedOffset); freeRanges.erase(allocatedOffset);
freeRanges[freeAllocation->allocatedOffset] = freeAllocation; bytesUsed += allocatedSize;
bytesUsed += size;
return subAlloc; return subAlloc;
} }
} }
return nullptr; return nullptr;
} }
void Allocation::markFree(SubAllocation *allocation) void Allocation::markFree(PSubAllocation allocation)
{ {
// Dont free if it is already a free allocation, since they also mark themselves on deletion // Dont free if it is already a free allocation, since they also mark themselves on deletion
if (freeRanges.find(allocation->allocatedOffset) != freeRanges.end()) if (freeRanges.find(allocation->allocatedOffset) != freeRanges.end())
@@ -143,7 +153,7 @@ void Allocation::markFree(SubAllocation *allocation)
&& freeAlloc->allocatedOffset + freeAlloc->allocatedSize >= upperBound) && freeAlloc->allocatedOffset + freeAlloc->allocatedSize >= upperBound)
{ {
// allocation is already in a free region // allocation is already in a free region
return; assert(false);
} }
if (freeAlloc->allocatedOffset + freeAlloc->allocatedSize == lowerBound) if (freeAlloc->allocatedOffset + freeAlloc->allocatedSize == lowerBound)
{ {
@@ -157,35 +167,34 @@ void Allocation::markFree(SubAllocation *allocation)
auto foundAlloc = freeRanges.find(upperBound); auto foundAlloc = freeRanges.find(upperBound);
if (foundAlloc != freeRanges.end()) if (foundAlloc != freeRanges.end())
{ {
freeRangeToDelete = foundAlloc->second;
// There is a free allocation ending where the new free one ends // There is a free allocation ending where the new free one ends
freeRangeToDelete = foundAlloc->value;
if (allocHandle != nullptr) if (allocHandle != nullptr)
{ {
// extend allocHandle by another foundAlloc->allocatedSize bytes // extend allocHandle by another foundAlloc->allocatedSize bytes
allocHandle->allocatedSize += foundAlloc->second->allocatedSize; allocHandle->allocatedSize += foundAlloc->value->allocatedSize;
freeRanges.erase(foundAlloc->first); freeRanges.erase(foundAlloc->key);
} }
else else
{ {
// set foundAlloc back by size amount // set foundAlloc back by size amount
allocHandle = foundAlloc->second; allocHandle = foundAlloc->value;
allocHandle->allocatedOffset -= allocation->allocatedSize; allocHandle->allocatedOffset -= allocation->allocatedSize;
allocHandle->alignedOffset -= allocation->allocatedSize; allocHandle->alignedOffset -= allocation->allocatedSize;
allocHandle->size += allocation->allocatedSize; allocHandle->size += allocation->allocatedSize;
allocHandle->allocatedSize += allocation->allocatedSize; allocHandle->allocatedSize += allocation->allocatedSize;
// place back at correct offset // place back at correct offset, move original owning pointer
freeRanges[allocHandle->allocatedOffset] = allocHandle; freeRanges[allocHandle->allocatedOffset] = std::move(foundAlloc->value);
// remove from offset map since key changes // remove from offset map since key changes
freeRanges.erase(foundAlloc->first); freeRanges.erase(foundAlloc->key);
} }
} }
if (allocHandle == nullptr) if (allocHandle == nullptr)
{ {
allocHandle = new SubAllocation(this, allocation->allocatedOffset, allocation->size, allocation->alignedOffset, allocation->allocatedSize); freeRanges[allocation->allocatedOffset] = new SubAllocation(this, allocation->allocatedOffset, allocation->size, allocation->alignedOffset, allocation->allocatedSize);
freeRanges[allocation->allocatedOffset] = allocHandle;
} }
activeAllocations.erase(allocation->allocatedOffset); activeAllocations.remove_if([&](const PSubAllocation& a) {return a.getHandle() == allocation.getHandle(); });
} }
bytesUsed -= allocation->allocatedSize; bytesUsed -= allocation->allocatedSize;
if(bytesUsed == 0) if(bytesUsed == 0)
@@ -194,25 +203,73 @@ void Allocation::markFree(SubAllocation *allocation)
} }
} }
constexpr VkDeviceMemory Allocation::getHandle() const
{
return allocatedMemory;
}
constexpr void* Allocation::getMappedPointer()
{
if (!canMap)
{
return nullptr;
}
if (!isMapped)
{
vkMapMemory(device, allocatedMemory, 0, bytesAllocated, 0, &mappedPointer);
isMapped = true;
}
return mappedPointer;
}
constexpr bool Allocation::isReadable() const
{
return readable;
}
void Allocation::flushMemory()
{
VkMappedMemoryRange range = {
.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
.pNext = 0,
.memory = allocatedMemory,
.offset = 0,
.size = bytesAllocated,
};
vkFlushMappedMemoryRanges(device, 1, &range);
}
void Allocation::invalidateMemory()
{
VkMappedMemoryRange range = {
.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,
.pNext = 0,
.memory = allocatedMemory,
.size = bytesAllocated,
};
vkInvalidateMappedMemoryRanges(device, 1, &range);
}
Allocator::Allocator(PGraphics graphics) Allocator::Allocator(PGraphics graphics)
: graphics(graphics) : graphics(graphics)
{ {
vkGetPhysicalDeviceMemoryProperties(graphics->getPhysicalDevice(), &memProperties); vkGetPhysicalDeviceMemoryProperties(graphics->getPhysicalDevice(), &memProperties);
heaps.resize(memProperties.memoryHeapCount); heaps.reserve(memProperties.memoryHeapCount);
for (size_t i = 0; i < memProperties.memoryHeapCount; ++i) for (size_t i = 0; i < memProperties.memoryHeapCount; ++i)
{ {
VkMemoryHeap memoryHeap = memProperties.memoryHeaps[i]; VkMemoryHeap memoryHeap = memProperties.memoryHeaps[i];
HeapInfo &heapInfo = heaps[i]; HeapInfo heapInfo;
heapInfo.maxSize = memoryHeap.size; heapInfo.maxSize = memoryHeap.size;
heaps.add(std::move(heapInfo));
} }
} }
Allocator::~Allocator() Allocator::~Allocator()
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
for (auto heap : heaps) for (auto& heap : heaps)
{ {
for (auto alloc : heap.allocations) for (auto& alloc : heap.allocations)
{ {
assert(alloc->activeAllocations.empty()); assert(alloc->activeAllocations.empty());
assert(alloc->freeRanges.size() == 1); assert(alloc->freeRanges.size() == 1);
@@ -222,7 +279,7 @@ Allocator::~Allocator()
graphics = nullptr; graphics = nullptr;
} }
PSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2, VkMemoryPropertyFlags properties, VkMemoryDedicatedAllocateInfo *dedicatedInfo) OSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2, VkMemoryPropertyFlags properties, VkMemoryDedicatedAllocateInfo *dedicatedInfo)
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
const VkMemoryRequirements &requirements = memRequirements2.memoryRequirements; const VkMemoryRequirements &requirements = memRequirements2.memoryRequirements;
@@ -234,17 +291,17 @@ PSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2
VkMemoryDedicatedRequirements *dedicatedReq = (VkMemoryDedicatedRequirements *)memRequirements2.pNext; VkMemoryDedicatedRequirements *dedicatedReq = (VkMemoryDedicatedRequirements *)memRequirements2.pNext;
if (dedicatedReq->prefersDedicatedAllocation) if (dedicatedReq->prefersDedicatedAllocation)
{ {
PAllocation newAllocation = new Allocation(graphics, this, requirements.size, memoryTypeIndex, properties, dedicatedInfo); OAllocation newAllocation = new Allocation(graphics, this, requirements.size, memoryTypeIndex, properties, dedicatedInfo);
heaps[heapIndex].allocations.add(newAllocation);
heaps[heapIndex].inUse += newAllocation->bytesAllocated; heaps[heapIndex].inUse += newAllocation->bytesAllocated;
return newAllocation->getSuballocation(requirements.size, requirements.alignment); heaps[heapIndex].allocations.add(std::move(newAllocation));
return heaps[heapIndex].allocations.back()->getSuballocation(requirements.size, requirements.alignment);
} }
} }
for (auto alloc : heaps[heapIndex].allocations) for (auto& alloc : heaps[heapIndex].allocations)
{ {
if(alloc->memoryTypeIndex == memoryTypeIndex) if(alloc->memoryTypeIndex == memoryTypeIndex)
{ {
PSubAllocation suballoc = alloc->getSuballocation(requirements.size, requirements.alignment); OSubAllocation suballoc = alloc->getSuballocation(requirements.size, requirements.alignment);
if (suballoc != nullptr) if (suballoc != nullptr)
{ {
return suballoc; return suballoc;
@@ -253,16 +310,16 @@ PSubAllocation Allocator::allocate(const VkMemoryRequirements2 &memRequirements2
} }
// no suitable allocations found, allocate new block // no suitable allocations found, allocate new block
PAllocation newAllocation = new Allocation(graphics, this, (requirements.size > MemoryBlockSize) ? requirements.size : (VkDeviceSize)MemoryBlockSize, memoryTypeIndex, properties, nullptr); OAllocation newAllocation = new Allocation(graphics, this, (requirements.size > MemoryBlockSize) ? requirements.size : (VkDeviceSize)MemoryBlockSize, memoryTypeIndex, properties, nullptr);
heaps[heapIndex].allocations.add(newAllocation);
heaps[heapIndex].inUse += newAllocation->bytesAllocated; heaps[heapIndex].inUse += newAllocation->bytesAllocated;
return newAllocation->getSuballocation(requirements.size, requirements.alignment); heaps[heapIndex].allocations.add(std::move(newAllocation));
return heaps[heapIndex].allocations.back()->getSuballocation(requirements.size, requirements.alignment);
} }
void Allocator::free(Allocation *allocation) void Allocator::free(Allocation *allocation)
{ {
std::scoped_lock lck(lock); std::scoped_lock lck(lock);
for (auto heap : heaps) for (auto& heap : heaps)
{ {
for (uint32 i = 0; i < heap.allocations.size(); ++i) for (uint32 i = 0; i < heap.allocations.size(); ++i)
{ {
@@ -288,12 +345,58 @@ uint32 Allocator::findMemoryType(uint32 typeFilter, VkMemoryPropertyFlags proper
throw std::runtime_error("error finding memory"); throw std::runtime_error("error finding memory");
} }
StagingBuffer::StagingBuffer() StagingBuffer::StagingBuffer(OSubAllocation allocation, VkBuffer buffer, VkBufferUsageFlags usage, uint8 readable)
: allocation(std::move(allocation))
, buffer(buffer)
, usage(usage)
, readable(readable)
{ {
} }
StagingBuffer::~StagingBuffer() StagingBuffer::~StagingBuffer()
{ {
assert(allocation == nullptr);
// buffer went out of scope without being cleaned up
}
void* StagingBuffer::getMappedPointer()
{
return allocation->getMappedPointer();
}
void StagingBuffer::flushMappedMemory()
{
allocation->flushMemory();
}
void StagingBuffer::invalidateMemory()
{
allocation->invalidateMemory();
}
constexpr VkDeviceMemory StagingBuffer::getMemoryHandle() const
{
return allocation->getHandle();
}
constexpr VkDeviceSize StagingBuffer::getOffset() const
{
return allocation->getOffset();
}
constexpr uint64 StagingBuffer::getSize() const
{
return allocation->getSize();
}
constexpr bool StagingBuffer::isReadable() const
{
return readable;
}
constexpr VkBufferUsageFlags StagingBuffer::getUsage() const
{
return usage;
} }
StagingManager::StagingManager(PGraphics graphics, PAllocator allocator) StagingManager::StagingManager(PGraphics graphics, PAllocator allocator)
@@ -309,22 +412,22 @@ void StagingManager::clearPending()
{ {
} }
PStagingBuffer StagingManager::allocateStagingBuffer(uint64 size, VkBufferUsageFlags usage, bool bCPURead) OStagingBuffer StagingManager::allocateStagingBuffer(uint64 size, VkBufferUsageFlags usage, bool readable)
{ {
std::scoped_lock l(lock); std::scoped_lock l(lock);
for (auto it = freeBuffers.begin(); it != freeBuffers.end(); ++it) for (auto it = freeBuffers.begin(); it != freeBuffers.end(); ++it)
{ {
auto freeBuffer = *it; auto& freeBuffer = *it;
if (freeBuffer->getSize() == size && freeBuffer->isReadable() == bCPURead && freeBuffer->usage == usage) if (freeBuffer->getSize() == size && freeBuffer->isReadable() == readable && freeBuffer->getUsage() == usage)
{ {
//std::cout << "Reusing staging buffer" << std::endl; //std::cout << "Reusing staging buffer" << std::endl;
activeBuffers.add(freeBuffer.getHandle()); activeBuffers.add(freeBuffer);
freeBuffers.remove(it, false); freeBuffers.remove(it, false);
return freeBuffer; return std::move(freeBuffer);
} }
} }
//std::cout << "Creating new stagingbuffer" << std::endl; //std::cout << "Creating new stagingbuffer" << std::endl;
PStagingBuffer stagingBuffer = new StagingBuffer(); VkBuffer buffer;
VkBufferCreateInfo stagingBufferCreateInfo = init::BufferCreateInfo(usage, size); VkBufferCreateInfo stagingBufferCreateInfo = init::BufferCreateInfo(usage, size);
stagingBufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; stagingBufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
uint32 queueIndex = graphics->getFamilyMapping().getQueueTypeFamilyIndex(Gfx::QueueType::DEDICATED_TRANSFER); uint32 queueIndex = graphics->getFamilyMapping().getQueueTypeFamilyIndex(Gfx::QueueType::DEDICATED_TRANSFER);
@@ -332,37 +435,42 @@ PStagingBuffer StagingManager::allocateStagingBuffer(uint64 size, VkBufferUsageF
stagingBufferCreateInfo.pQueueFamilyIndices = &queueIndex; stagingBufferCreateInfo.pQueueFamilyIndices = &queueIndex;
VkDevice vulkanDevice = graphics->getDevice(); VkDevice vulkanDevice = graphics->getDevice();
VK_CHECK(vkCreateBuffer(vulkanDevice, &stagingBufferCreateInfo, nullptr, &stagingBuffer->buffer)); VK_CHECK(vkCreateBuffer(vulkanDevice, &stagingBufferCreateInfo, nullptr, &buffer));
VkMemoryDedicatedRequirements dedicatedReqs; VkMemoryDedicatedRequirements dedicatedReqs = {
dedicatedReqs.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS; .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
dedicatedReqs.pNext = nullptr; .pNext = nullptr,
VkMemoryRequirements2 memReqs; };
memReqs.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2; VkMemoryRequirements2 memReqs = {
memReqs.pNext = &dedicatedReqs; .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
VkBufferMemoryRequirementsInfo2 bufferQuery; .pNext = &dedicatedReqs,
bufferQuery.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2; };
bufferQuery.pNext = nullptr; VkBufferMemoryRequirementsInfo2 bufferQuery = {
bufferQuery.buffer = stagingBuffer->buffer; .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
.pNext = nullptr,
.buffer = buffer,
};
vkGetBufferMemoryRequirements2(vulkanDevice, &bufferQuery, &memReqs); vkGetBufferMemoryRequirements2(vulkanDevice, &bufferQuery, &memReqs);
memReqs.memoryRequirements.alignment = memReqs.memoryRequirements.alignment =
(16 > memReqs.memoryRequirements.alignment) ? 16 : memReqs.memoryRequirements.alignment; (16 > memReqs.memoryRequirements.alignment) ? 16 : memReqs.memoryRequirements.alignment;
stagingBuffer->allocation = allocator->allocate(memReqs, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | (bCPURead ? VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : VK_MEMORY_PROPERTY_HOST_CACHED_BIT), stagingBuffer->buffer); OStagingBuffer stagingBuffer = new StagingBuffer(
stagingBuffer->bReadable = bCPURead; allocator->allocate(memReqs, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | (readable ? VK_MEMORY_PROPERTY_HOST_COHERENT_BIT : VK_MEMORY_PROPERTY_HOST_CACHED_BIT), buffer),
stagingBuffer->size = size; buffer,
stagingBuffer->usage = usage; usage,
vkBindBufferMemory(graphics->getDevice(), stagingBuffer->buffer, stagingBuffer->getMemoryHandle(), stagingBuffer->getOffset()); readable
);
vkBindBufferMemory(graphics->getDevice(), buffer, stagingBuffer->getMemoryHandle(), stagingBuffer->getOffset());
activeBuffers.add(stagingBuffer.getHandle()); activeBuffers.add(stagingBuffer);
return stagingBuffer; return stagingBuffer;
} }
void StagingManager::releaseStagingBuffer(PStagingBuffer buffer) void StagingManager::releaseStagingBuffer(OStagingBuffer buffer)
{ {
std::scoped_lock l(lock); std::scoped_lock l(lock);
freeBuffers.add(buffer); activeBuffers.remove(buffer);
activeBuffers.remove(activeBuffers.find(buffer.getHandle())); freeBuffers.add(std::move(buffer));
} }
+41 -104
View File
@@ -10,29 +10,23 @@ namespace Seele
namespace Vulkan namespace Vulkan
{ {
DECLARE_REF(Graphics) DECLARE_REF(Graphics)
class Allocation; DECLARE_REF(Allocator)
class Allocator; DECLARE_REF(Allocation)
class SubAllocation class SubAllocation
{ {
public: public:
SubAllocation(Allocation *owner, VkDeviceSize allocatedOffset, VkDeviceSize size, VkDeviceSize alignedOffset, VkDeviceSize allocatedSize); SubAllocation(PAllocation owner, VkDeviceSize allocatedOffset, VkDeviceSize size, VkDeviceSize alignedOffset, VkDeviceSize allocatedSize);
~SubAllocation(); ~SubAllocation();
VkDeviceMemory getHandle() const; constexpr VkDeviceMemory getHandle() const;
inline VkDeviceSize getSize() const constexpr VkDeviceSize getSize() const;
{ constexpr VkDeviceSize getOffset() const;
return size; constexpr bool isReadable() const;
}
inline VkDeviceSize getOffset() const
{
return alignedOffset;
}
inline bool isReadable() const;
void *getMappedPointer(); void *getMappedPointer();
void flushMemory(); void flushMemory();
void invalidateMemory(); void invalidateMemory();
private: private:
Allocation *owner; PAllocation owner;
VkDeviceSize size; VkDeviceSize size;
VkDeviceSize allocatedOffset; VkDeviceSize allocatedOffset;
VkDeviceSize alignedOffset; VkDeviceSize alignedOffset;
@@ -44,54 +38,16 @@ DEFINE_REF(SubAllocation)
class Allocation class Allocation
{ {
public: public:
Allocation(PGraphics graphics, Allocator *allocator, VkDeviceSize size, uint8 memoryTypeIndex, Allocation(PGraphics graphics, PAllocator allocator, VkDeviceSize size, uint8 memoryTypeIndex,
VkMemoryPropertyFlags properties, VkMemoryDedicatedAllocateInfo *dedicatedInfo = nullptr); VkMemoryPropertyFlags properties, VkMemoryDedicatedAllocateInfo *dedicatedInfo = nullptr);
~Allocation(); ~Allocation();
PSubAllocation getSuballocation(VkDeviceSize size, VkDeviceSize alignment); OSubAllocation getSuballocation(VkDeviceSize size, VkDeviceSize alignment);
void markFree(SubAllocation *alloc); void markFree(PSubAllocation alloc);
inline VkDeviceMemory getHandle() const constexpr VkDeviceMemory getHandle() const;
{ constexpr void* getMappedPointer();
return allocatedMemory; constexpr bool isReadable() const;
} void flushMemory();
inline void *getMappedPointer() void invalidateMemory();
{
if (!canMap)
{
return nullptr;
}
if (!isMapped)
{
vkMapMemory(device, allocatedMemory, 0, bytesAllocated, 0, &mappedPointer);
isMapped = true;
}
return mappedPointer;
}
inline bool isReadable() const
{
return readable;
}
void flushMemory()
{
VkMappedMemoryRange range;
range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range.pNext = 0;
range.memory = allocatedMemory;
range.size = bytesAllocated;
range.offset = 0;
vkFlushMappedMemoryRanges(device, 1, &range);
}
void invalidateMemory()
{
VkMappedMemoryRange range;
range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range.pNext = 0;
range.memory = allocatedMemory;
range.size = bytesAllocated;
vkInvalidateMappedMemoryRanges(device, 1, &range);
}
private: private:
VkDevice device; VkDevice device;
@@ -99,8 +55,8 @@ private:
VkDeviceSize bytesAllocated; VkDeviceSize bytesAllocated;
VkDeviceSize bytesUsed; VkDeviceSize bytesUsed;
VkDeviceMemory allocatedMemory; VkDeviceMemory allocatedMemory;
std::map<VkDeviceSize, PSubAllocation> activeAllocations; Array<PSubAllocation> activeAllocations;
std::map<VkDeviceSize, PSubAllocation> freeRanges; Map<VkDeviceSize, OSubAllocation> freeRanges;
std::mutex lock; std::mutex lock;
void *mappedPointer; void *mappedPointer;
uint8 isDedicated : 1; uint8 isDedicated : 1;
@@ -142,7 +98,6 @@ public:
} }
void free(Allocation *allocation); void free(Allocation *allocation);
void notifyUsageChanged(int64 usageChange);
private: private:
enum enum
{ {
@@ -152,7 +107,12 @@ private:
{ {
VkDeviceSize maxSize = 0; VkDeviceSize maxSize = 0;
VkDeviceSize inUse = 0; VkDeviceSize inUse = 0;
Array<PAllocation> allocations; Array<OAllocation> allocations;
HeapInfo() {}
HeapInfo(const HeapInfo& other) = delete;
HeapInfo(HeapInfo&& other) = default;
HeapInfo& operator=(const HeapInfo& other) = delete;
HeapInfo& operator=(HeapInfo&& other) = default;
}; };
Array<HeapInfo> heaps; Array<HeapInfo> heaps;
uint32 findMemoryType(uint32 typeBits, VkMemoryPropertyFlags properties); uint32 findMemoryType(uint32 typeBits, VkMemoryPropertyFlags properties);
@@ -161,52 +121,29 @@ private:
VkPhysicalDeviceMemoryProperties memProperties; VkPhysicalDeviceMemoryProperties memProperties;
}; };
DEFINE_REF(Allocator) DEFINE_REF(Allocator)
DECLARE_REF(StagingManager)
class StagingBuffer class StagingBuffer
{ {
public: public:
StagingBuffer(); StagingBuffer(OSubAllocation allocation, VkBuffer buffer, VkBufferUsageFlags usage, uint8 readable);
~StagingBuffer(); ~StagingBuffer();
void *getMappedPointer() void* getMappedPointer();
{ void flushMappedMemory();
return allocation->getMappedPointer(); void invalidateMemory();
} constexpr VkBuffer getHandle() const
void flushMappedMemory()
{
allocation->flushMemory();
}
void invalidateMemory()
{
allocation->invalidateMemory();
}
VkBuffer getHandle() const
{ {
return buffer; return buffer;
} }
VkDeviceMemory getMemoryHandle() const constexpr VkDeviceMemory getMemoryHandle() const;
{ constexpr VkDeviceSize getOffset() const;
return allocation->getHandle(); constexpr uint64 getSize() const;
} constexpr bool isReadable() const;
VkDeviceSize getOffset() const constexpr VkBufferUsageFlags getUsage() const;
{
return allocation->getOffset();
}
uint64 getSize() const
{
return size;
}
bool isReadable() const
{
return bReadable;
}
private: private:
PSubAllocation allocation; OSubAllocation allocation;
VkBuffer buffer; VkBuffer buffer;
uint64 size;
VkBufferUsageFlags usage; VkBufferUsageFlags usage;
uint8 bReadable; uint8 readable;
friend class StagingManager;
}; };
DEFINE_REF(StagingBuffer) DEFINE_REF(StagingBuffer)
@@ -215,15 +152,15 @@ class StagingManager
public: public:
StagingManager(PGraphics graphics, PAllocator allocator); StagingManager(PGraphics graphics, PAllocator allocator);
~StagingManager(); ~StagingManager();
PStagingBuffer allocateStagingBuffer(uint64 size, VkBufferUsageFlags usageFlags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, bool bCPURead = false); OStagingBuffer allocateStagingBuffer(uint64 size, VkBufferUsageFlags usageFlags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, bool bCPURead = false);
void releaseStagingBuffer(PStagingBuffer buffer); void releaseStagingBuffer(OStagingBuffer buffer);
void clearPending(); void clearPending();
private: private:
PGraphics graphics; PGraphics graphics;
PAllocator allocator; PAllocator allocator;
Array<PStagingBuffer> freeBuffers; Array<OStagingBuffer> freeBuffers;
Array<StagingBuffer *> activeBuffers; Array<PStagingBuffer> activeBuffers;
std::mutex lock; std::mutex lock;
}; };
DEFINE_REF(StagingManager) DEFINE_REF(StagingManager)
+29 -26
View File
@@ -1,4 +1,6 @@
#include "Buffer.h" #include "Buffer.h"
#include "Initializer.h"
#include "CommandBuffer.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
@@ -7,20 +9,20 @@ struct PendingBuffer
{ {
uint64 offset; uint64 offset;
uint64 size; uint64 size;
PStagingBuffer stagingBuffer; OStagingBuffer stagingBuffer;
Gfx::QueueType prevQueue; Gfx::QueueType prevQueue;
bool bWriteOnly; bool writeOnly;
}; };
static std::map<Vulkan::Buffer*, PendingBuffer> pendingBuffers; static std::map<Vulkan::Buffer*, PendingBuffer> pendingBuffers;
Buffer::Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool bDynamic) Buffer::Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool dynamic)
: graphics(graphics) : graphics(graphics)
, currentBuffer(0) , currentBuffer(0)
, size(size) , size(size)
, owner(queueType) , owner(queueType)
{ {
if(bDynamic) if(dynamic)
{ {
numBuffers = Gfx::numFramesBuffered; numBuffers = Gfx::numFramesBuffered;
} }
@@ -166,12 +168,12 @@ void Buffer::executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlag
vkCmdPipelineBarrier(commandBuffer->getHandle(), srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr); vkCmdPipelineBarrier(commandBuffer->getHandle(), srcStage, dstStage, 0, 0, nullptr, numBuffers, dynamicBarriers, 0, nullptr);
} }
void * Buffer::lock(bool bWriteOnly) void * Buffer::lock(bool writeOnly)
{ {
return lockRegion(0, size, bWriteOnly); return lockRegion(0, size, writeOnly);
} }
void * Buffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool bWriteOnly) void * Buffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly)
{ {
void *data = nullptr; void *data = nullptr;
@@ -190,16 +192,16 @@ void * Buffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool bWriteOnl
//assert(bStatic || bDynamic || bUAV); //assert(bStatic || bDynamic || bUAV);
PendingBuffer pending; PendingBuffer pending;
pending.bWriteOnly = bWriteOnly; pending.writeOnly = writeOnly;
pending.prevQueue = owner; pending.prevQueue = owner;
pending.offset = regionOffset; pending.offset = regionOffset;
pending.size = regionSize; pending.size = regionSize;
if (bWriteOnly) if (writeOnly)
{ {
//requestOwnershipTransfer(Gfx::QueueType::DEDICATED_TRANSFER); //requestOwnershipTransfer(Gfx::QueueType::DEDICATED_TRANSFER);
PStagingBuffer stagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(regionSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); OStagingBuffer stagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(regionSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
data = stagingBuffer->getMappedPointer(); data = stagingBuffer->getMappedPointer();
pending.stagingBuffer = stagingBuffer; pending.stagingBuffer = std::move(stagingBuffer);
} }
else else
{ {
@@ -220,7 +222,7 @@ void * Buffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool bWriteOnl
barrier.size = size; barrier.size = size;
vkCmdPipelineBarrier(handle, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr); vkCmdPipelineBarrier(handle, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr);
PStagingBuffer stagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true); OStagingBuffer stagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true);
VkBufferCopy regions; VkBufferCopy regions;
regions.size = size; regions.size = size;
@@ -233,11 +235,12 @@ void * Buffer::lockRegion(uint64 regionOffset, uint64 regionSize, bool bWriteOnl
vkQueueWaitIdle(graphics->getQueueCommands(owner)->getQueue()->getHandle()); vkQueueWaitIdle(graphics->getQueueCommands(owner)->getQueue()->getHandle());
stagingBuffer->getMappedPointer(); // this maps the memory if not mapped already stagingBuffer->getMappedPointer(); // this maps the memory if not mapped already
stagingBuffer->flushMappedMemory(); stagingBuffer->flushMappedMemory();
pending.stagingBuffer = stagingBuffer;
data = stagingBuffer->getMappedPointer(); data = stagingBuffer->getMappedPointer();
pending.stagingBuffer = std::move(stagingBuffer);
} }
pendingBuffers[this] = pending; pendingBuffers[this] = std::move(pending);
assert(data); assert(data);
return data; return data;
@@ -248,10 +251,9 @@ void Buffer::unlock()
auto found = pendingBuffers.find(this); auto found = pendingBuffers.find(this);
if (found != pendingBuffers.end()) if (found != pendingBuffers.end())
{ {
PendingBuffer pending = found->second; PendingBuffer& pending = found->second;
pending.stagingBuffer->flushMappedMemory(); pending.stagingBuffer->flushMappedMemory();
pendingBuffers.erase(this); if (pending.writeOnly)
if (pending.bWriteOnly)
{ {
PStagingBuffer stagingBuffer = pending.stagingBuffer; PStagingBuffer stagingBuffer = pending.stagingBuffer;
PCmdBuffer cmdBuffer = graphics->getQueueCommands(owner)->getCommands(); PCmdBuffer cmdBuffer = graphics->getQueueCommands(owner)->getCommands();
@@ -265,16 +267,17 @@ void Buffer::unlock()
graphics->getQueueCommands(owner)->submitCommands(); graphics->getQueueCommands(owner)->submitCommands();
} }
//requestOwnershipTransfer(pending.prevQueue); //requestOwnershipTransfer(pending.prevQueue);
graphics->getStagingManager()->releaseStagingBuffer(pending.stagingBuffer); graphics->getStagingManager()->releaseStagingBuffer(std::move(pending.stagingBuffer));
pendingBuffers.erase(this);
} }
} }
UniformBuffer::UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &createInfo) UniformBuffer::UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &createInfo)
: Gfx::UniformBuffer(graphics->getFamilyMapping(), createInfo.sourceData) : Gfx::UniformBuffer(graphics->getFamilyMapping(), createInfo.sourceData)
, Vulkan::Buffer(graphics, createInfo.sourceData.size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, currentOwner, createInfo.bDynamic) , Vulkan::Buffer(graphics, createInfo.sourceData.size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, currentOwner, createInfo.dynamic)
, dedicatedStagingBuffer(nullptr) , dedicatedStagingBuffer(nullptr)
{ {
if(createInfo.bDynamic) if(createInfo.dynamic)
{ {
dedicatedStagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(createInfo.sourceData.size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); dedicatedStagingBuffer = graphics->getStagingManager()->allocateStagingBuffer(createInfo.sourceData.size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
} }
@@ -302,13 +305,13 @@ bool UniformBuffer::updateContents(const DataSource &sourceData)
unlock(); unlock();
return true; return true;
} }
void* UniformBuffer::lock(bool bWriteOnly) void* UniformBuffer::lock(bool writeOnly)
{ {
if(dedicatedStagingBuffer != nullptr) if(dedicatedStagingBuffer != nullptr)
{ {
return dedicatedStagingBuffer->getMappedPointer(); return dedicatedStagingBuffer->getMappedPointer();
} }
return Vulkan::Buffer::lock(bWriteOnly); return Vulkan::Buffer::lock(writeOnly);
} }
void UniformBuffer::unlock() void UniformBuffer::unlock()
@@ -359,7 +362,7 @@ VkAccessFlags UniformBuffer::getDestAccessMask()
ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &sourceData) ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &sourceData)
: Gfx::ShaderBuffer(graphics->getFamilyMapping(), sourceData.stride, sourceData.sourceData.size / sourceData.stride, sourceData.sourceData) : Gfx::ShaderBuffer(graphics->getFamilyMapping(), sourceData.stride, sourceData.sourceData.size / sourceData.stride, sourceData.sourceData)
, Vulkan::Buffer(graphics, sourceData.sourceData.size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, currentOwner, sourceData.bDynamic) , Vulkan::Buffer(graphics, sourceData.sourceData.size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, currentOwner, sourceData.dynamic)
{ {
if (sourceData.sourceData.data != nullptr) if (sourceData.sourceData.data != nullptr)
{ {
@@ -383,13 +386,13 @@ bool ShaderBuffer::updateContents(const DataSource &sourceData)
unlock(); unlock();
return true; return true;
} }
void* ShaderBuffer::lock(bool bWriteOnly) void* ShaderBuffer::lock(bool writeOnly)
{ {
if(dedicatedStagingBuffer != nullptr) if(dedicatedStagingBuffer != nullptr)
{ {
return dedicatedStagingBuffer->getMappedPointer(); return dedicatedStagingBuffer->getMappedPointer();
} }
return ShaderBuffer::lock(bWriteOnly); return ShaderBuffer::lock(writeOnly);
} }
void ShaderBuffer::unlock() void ShaderBuffer::unlock()
+7 -7
View File
@@ -11,7 +11,7 @@ namespace Vulkan
class Buffer class Buffer
{ {
public: public:
Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool bDynamic = false); Buffer(PGraphics graphics, uint64 size, VkBufferUsageFlags usage, Gfx::QueueType& queueType, bool dynamic = false);
virtual ~Buffer(); virtual ~Buffer();
VkBuffer getHandle() const VkBuffer getHandle() const
{ {
@@ -26,8 +26,8 @@ public:
{ {
currentBuffer = (currentBuffer + 1) % numBuffers; currentBuffer = (currentBuffer + 1) % numBuffers;
} }
virtual void *lock(bool bWriteOnly = true); virtual void *lock(bool writeOnly = true);
virtual void *lockRegion(uint64 regionOffset, uint64 regionSize, bool bWriteOnly = true); virtual void *lockRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly = true);
virtual void unlock(); virtual void unlock();
protected: protected:
@@ -62,7 +62,7 @@ public:
virtual ~UniformBuffer(); virtual ~UniformBuffer();
virtual bool updateContents(const DataSource &sourceData); virtual bool updateContents(const DataSource &sourceData);
virtual void* lock(bool bWriteOnly = true) override; virtual void* lock(bool writeOnly = true) override;
virtual void unlock() override; virtual void unlock() override;
protected: protected:
// Inherited via Vulkan::Buffer // Inherited via Vulkan::Buffer
@@ -75,7 +75,7 @@ protected:
VkAccessFlags dstAccess, VkPipelineStageFlags dstStage); VkAccessFlags dstAccess, VkPipelineStageFlags dstStage);
private: private:
PStagingBuffer dedicatedStagingBuffer; OStagingBuffer dedicatedStagingBuffer;
}; };
DEFINE_REF(UniformBuffer) DEFINE_REF(UniformBuffer)
@@ -86,7 +86,7 @@ public:
virtual ~ShaderBuffer(); virtual ~ShaderBuffer();
virtual bool updateContents(const DataSource &sourceData); virtual bool updateContents(const DataSource &sourceData);
virtual void* lock(bool bWriteOnly = true) override; virtual void* lock(bool writeOnly = true) override;
virtual void unlock() override; virtual void unlock() override;
protected: protected:
// Inherited via Vulkan::Buffer // Inherited via Vulkan::Buffer
@@ -98,7 +98,7 @@ protected:
virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage, virtual void executePipelineBarrier(VkAccessFlags srcAccess, VkPipelineStageFlags srcStage,
VkAccessFlags dstAccess, VkPipelineStageFlags dstStage); VkAccessFlags dstAccess, VkPipelineStageFlags dstStage);
private: private:
PStagingBuffer dedicatedStagingBuffer; OStagingBuffer dedicatedStagingBuffer;
}; };
DEFINE_REF(ShaderBuffer) DEFINE_REF(ShaderBuffer)
+1 -1
View File
@@ -313,7 +313,7 @@ void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, int32 firstVe
void RenderCommand::dispatch(uint32 groupX, uint32 groupY, uint32 groupZ) void RenderCommand::dispatch(uint32 groupX, uint32 groupY, uint32 groupZ)
{ {
assert(threadId == std::this_thread::get_id()); assert(threadId == std::this_thread::get_id());
vkCmdDrawMeshTasksEXT(handle, groupX, groupY, groupZ); graphics->vkCmdDrawMeshTasksEXT(handle, groupX, groupY, groupZ);
} }
ComputeCommand::ComputeCommand(PGraphics graphics, VkCommandPool cmdPool) ComputeCommand::ComputeCommand(PGraphics graphics, VkCommandPool cmdPool)
@@ -2,6 +2,7 @@
#include "Graphics.h" #include "Graphics.h"
#include "Initializer.h" #include "Initializer.h"
#include "CommandBuffer.h" #include "CommandBuffer.h"
#include "Texture.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
@@ -130,12 +131,12 @@ void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBu
VkWriteDescriptorSet writeDescriptor = init::WriteDescriptorSet(setHandle, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, binding, &bufferInfos.back()); VkWriteDescriptorSet writeDescriptor = init::WriteDescriptorSet(setHandle, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, binding, &bufferInfos.back());
writeDescriptors.add(writeDescriptor); writeDescriptors.add(writeDescriptor);
cachedData[binding] = new UniformBuffer(*vulkanBuffer.getHandle()); cachedData[binding] = vulkanBuffer.getHandle();
} }
void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PShaderBuffer ShaderBuffer) void DescriptorSet::updateBuffer(uint32_t binding, Gfx::PShaderBuffer shaderBuffer)
{ {
PShaderBuffer vulkanBuffer = ShaderBuffer.cast<ShaderBuffer>(); PShaderBuffer vulkanBuffer = shaderBuffer.cast<ShaderBuffer>();
ShaderBuffer* cachedBuffer = reinterpret_cast<ShaderBuffer*>(cachedData[binding]); ShaderBuffer* cachedBuffer = reinterpret_cast<ShaderBuffer*>(cachedData[binding]);
if(vulkanBuffer.getHandle() == cachedBuffer) if(vulkanBuffer.getHandle() == cachedBuffer)
{ {
@@ -349,21 +350,20 @@ Gfx::PDescriptorSet DescriptorAllocator::allocateDescriptorSet()
VK_CHECK(vkAllocateDescriptorSets(graphics->getDevice(), &allocInfo, &cachedHandles[setIndex]->setHandle)); VK_CHECK(vkAllocateDescriptorSets(graphics->getDevice(), &allocInfo, &cachedHandles[setIndex]->setHandle));
} }
cachedHandles[setIndex]->allocate(); cachedHandles[setIndex]->allocate();
descriptorSet = cachedHandles[setIndex];
PDescriptorSet vulkanSet = descriptorSet.cast<DescriptorSet>(); PDescriptorSet vulkanSet = cachedHandles[setIndex];
vulkanSet->cachedData.resize(layout.bindings.size()); vulkanSet->cachedData.resize(layout.bindings.size());
// Not really pretty, but this way the set knows which ones are valid // Not really pretty, but this way the set knows which ones are valid
std::memset(vulkanSet->cachedData.data(), 0, sizeof(void*) * vulkanSet->cachedData.size()); std::memset(vulkanSet->cachedData.data(), 0, sizeof(void*) * vulkanSet->cachedData.size());
//Found set, stop searching //Found set, stop searching
return; return vulkanSet;
} }
if(nextAlloc == nullptr) if(nextAlloc == nullptr)
{ {
nextAlloc = new DescriptorAllocator(graphics, layout); nextAlloc = new DescriptorAllocator(graphics, layout);
} }
nextAlloc->allocateDescriptorSet(descriptorSet); return nextAlloc->allocateDescriptorSet();
//throw std::logic_error("Out of descriptor sets"); //throw std::logic_error("Out of descriptor sets");
} }
+1 -1
View File
@@ -1,4 +1,4 @@
#include "VulkanGraphicsEnums.h" #include "Enums.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
+57 -43
View File
@@ -8,6 +8,7 @@
#include "RenderTarget.h" #include "RenderTarget.h"
#include "RenderPass.h" #include "RenderPass.h"
#include "Framebuffer.h" #include "Framebuffer.h"
#include "Shader.h"
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
using namespace Seele; using namespace Seele;
@@ -134,8 +135,8 @@ Gfx::OUniformBuffer Graphics::createUniformBuffer(const UniformBufferCreateInfo
Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData)
{ {
OShaderBuffer ShaderBuffer = new ShaderBuffer(this, bulkData); OShaderBuffer shaderBuffer = new ShaderBuffer(this, bulkData);
return ShaderBuffer; return shaderBuffer;
} }
Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData)
{ {
@@ -150,13 +151,13 @@ Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkD
} }
Gfx::PRenderCommand Graphics::createRenderCommand(const std::string& name) Gfx::PRenderCommand Graphics::createRenderCommand(const std::string& name)
{ {
ORenderCommand cmdBuffer = getGraphicsCommands()->createRenderCommand(activeRenderPass, activeFramebuffer, name); PRenderCommand cmdBuffer = getGraphicsCommands()->createRenderCommand(activeRenderPass, activeFramebuffer, name);
return cmdBuffer; return cmdBuffer;
} }
Gfx::PComputeCommand Graphics::createComputeCommand(const std::string& name) Gfx::PComputeCommand Graphics::createComputeCommand(const std::string& name)
{ {
OComputeCommand cmdBuffer = getComputeCommands()->createComputeCommand(name); PComputeCommand cmdBuffer = getComputeCommands()->createComputeCommand(name);
return cmdBuffer; return cmdBuffer;
} }
@@ -172,52 +173,51 @@ Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createIn
shader->create(createInfo); shader->create(createInfo);
return shader; return shader;
} }
Gfx::PControlShader Graphics::createControlShader(const ShaderCreateInfo& createInfo) Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo)
{ {
PControlShader shader = new ControlShader(this); OFragmentShader shader = new FragmentShader(this);
shader->create(createInfo); shader->create(createInfo);
return shader; return shader;
} }
Gfx::PEvaluationShader Graphics::createEvaluationShader(const ShaderCreateInfo& createInfo) Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo)
{ {
PEvaluationShader shader = new EvaluationShader(this); OComputeShader shader = new ComputeShader(this);
shader->create(createInfo); shader->create(createInfo);
return shader; return shader;
} }
Gfx::PGeometryShader Graphics::createGeometryShader(const ShaderCreateInfo& createInfo) Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo)
{ {
PGeometryShader shader = new GeometryShader(this); OTaskShader shader = new TaskShader(this);
shader->create(createInfo); shader->create(createInfo);
return shader; return shader;
} }
Gfx::PFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo) Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo)
{ {
PFragmentShader shader = new FragmentShader(this); OMeshShader shader = new MeshShader(this);
shader->create(createInfo);
return shader;
}
Gfx::PComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo)
{
PComputeShader shader = new ComputeShader(this);
shader->create(createInfo); shader->create(createInfo);
return shader; return shader;
} }
Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(const GraphicsPipelineCreateInfo& createInfo) Gfx::OGraphicsPipeline Graphics::createGraphicsPipeline(const Gfx::LegacyPipelineCreateInfo& createInfo)
{ {
PGraphicsPipeline pipeline = pipelineCache->createPipeline(createInfo); OGraphicsPipeline pipeline = pipelineCache->createPipeline(createInfo);
return pipeline;
}
Gfx::OGraphicsPipeline Graphics::createGraphicsPipeline(const Gfx::MeshPipelineCreateInfo& createInfo)
{
OGraphicsPipeline pipeline = pipelineCache->createPipeline(createInfo);
return pipeline; return pipeline;
} }
Gfx::PComputePipeline Graphics::createComputePipeline(const ComputePipelineCreateInfo& createInfo) Gfx::OComputePipeline Graphics::createComputePipeline(const Gfx::ComputePipelineCreateInfo& createInfo)
{ {
PComputePipeline pipeline = pipelineCache->createPipeline(createInfo); OComputePipeline pipeline = pipelineCache->createPipeline(createInfo);
return pipeline; return pipeline;
} }
Gfx::PSamplerState Graphics::createSamplerState(const SamplerCreateInfo& createInfo) Gfx::OSamplerState Graphics::createSamplerState(const SamplerCreateInfo& createInfo)
{ {
PSamplerState sampler = new SamplerState(); OSamplerState sampler = new SamplerState();
VkSamplerCreateInfo vkInfo = VkSamplerCreateInfo vkInfo =
init::SamplerCreateInfo(); init::SamplerCreateInfo();
vkInfo.addressModeU = cast(createInfo.addressModeU); vkInfo.addressModeU = cast(createInfo.addressModeU);
@@ -239,14 +239,14 @@ Gfx::PSamplerState Graphics::createSamplerState(const SamplerCreateInfo& createI
VK_CHECK(vkCreateSampler(handle, &vkInfo, nullptr, &sampler->sampler)); VK_CHECK(vkCreateSampler(handle, &vkInfo, nullptr, &sampler->sampler));
return sampler; return sampler;
} }
Gfx::PDescriptorLayout Graphics::createDescriptorLayout(const std::string& name) Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name)
{ {
PDescriptorLayout layout = new DescriptorLayout(this, name); ODescriptorLayout layout = new DescriptorLayout(this, name);
return layout; return layout;
} }
Gfx::PPipelineLayout Graphics::createPipelineLayout(Gfx::PPipelineLayout baseLayout) Gfx::OPipelineLayout Graphics::createPipelineLayout(Gfx::PPipelineLayout baseLayout)
{ {
PPipelineLayout layout = new PipelineLayout(this, baseLayout); OPipelineLayout layout = new PipelineLayout(this, baseLayout);
return layout; return layout;
} }
@@ -317,6 +317,10 @@ void Graphics::copyTexture(Gfx::PTexture srcTexture, Gfx::PTexture dstTexture)
} }
} }
void Graphics::vkCmdDrawMeshTasksEXT(VkCommandBuffer handle, uint32 groupX, uint32 groupY, uint32 groupZ)
{
cmdDrawMeshTasks(handle, groupX, groupY, groupZ);
}
PCommandBufferManager Graphics::getQueueCommands(Gfx::QueueType queueType) PCommandBufferManager Graphics::getQueueCommands(Gfx::QueueType queueType)
{ {
switch (queueType) switch (queueType)
@@ -361,7 +365,7 @@ PCommandBufferManager Graphics::getDedicatedTransferCommands()
{ {
if(dedicatedTransferCommands == nullptr) if(dedicatedTransferCommands == nullptr)
{ {
dedicatedTransferCommands = new CommandBufferManager(this, dedicatedTransferQueue); dedicatedTransferCommands = new CommandBufferManager(this, dedicatedTransferQueue != nullptr ? dedicatedTransferQueue : transferQueue);
} }
return dedicatedTransferCommands; return dedicatedTransferCommands;
} }
@@ -441,7 +445,7 @@ void Graphics::pickPhysicalDevice()
{ {
uint32 currentRating = 0; uint32 currentRating = 0;
vkGetPhysicalDeviceProperties(dev, &props); vkGetPhysicalDeviceProperties(dev, &props);
vkGetPhysicalDeviceFeatures(dev, &features); vkGetPhysicalDeviceFeatures2(dev, &features);
if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
{ {
std::cout << "found dedicated gpu " << props.deviceName << std::endl; std::cout << "found dedicated gpu " << props.deviceName << std::endl;
@@ -461,7 +465,7 @@ void Graphics::pickPhysicalDevice()
} }
physicalDevice = bestDevice; physicalDevice = bestDevice;
vkGetPhysicalDeviceProperties(physicalDevice, &props); vkGetPhysicalDeviceProperties(physicalDevice, &props);
vkGetPhysicalDeviceFeatures(physicalDevice, &features); vkGetPhysicalDeviceFeatures2(physicalDevice, &features);
} }
void Graphics::createDevice(GraphicsInitializer initializer) void Graphics::createDevice(GraphicsInitializer initializer)
@@ -563,13 +567,13 @@ void Graphics::createDevice(GraphicsInitializer initializer)
(uint32)queueInfos.size(), (uint32)queueInfos.size(),
&features); &features);
VkPhysicalDeviceDescriptorIndexingFeatures descriptorIndexing = {}; VkPhysicalDeviceDescriptorIndexingFeatures descriptorIndexing = {
std::memset(&descriptorIndexing, 0, sizeof(descriptorIndexing)); .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES,
descriptorIndexing.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES; .shaderSampledImageArrayNonUniformIndexing = VK_TRUE,
descriptorIndexing.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; .descriptorBindingPartiallyBound = VK_TRUE,
descriptorIndexing.runtimeDescriptorArray = VK_TRUE; .descriptorBindingVariableDescriptorCount = VK_TRUE,
descriptorIndexing.descriptorBindingVariableDescriptorCount = VK_TRUE; .runtimeDescriptorArray = VK_TRUE,
descriptorIndexing.descriptorBindingPartiallyBound = VK_TRUE; };
deviceInfo.pNext = &descriptorIndexing; deviceInfo.pNext = &descriptorIndexing;
#if ENABLE_VALIDATION #if ENABLE_VALIDATION
VkDeviceDiagnosticsConfigCreateInfoNV crashDiagInfo; VkDeviceDiagnosticsConfigCreateInfoNV crashDiagInfo;
@@ -581,6 +585,18 @@ void Graphics::createDevice(GraphicsInitializer initializer)
VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV; VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_DEBUG_INFO_BIT_NV;
descriptorIndexing.pNext = &crashDiagInfo; descriptorIndexing.pNext = &crashDiagInfo;
#endif #endif
VkPhysicalDeviceMeshShaderFeaturesEXT enabledMeshShaderFeatures = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT,
.taskShader = VK_TRUE,
.meshShader = VK_TRUE,
};
if (Gfx::useMeshShading)
{
descriptorIndexing.pNext = &enabledMeshShaderFeatures;
initializer.deviceExtensions.add("VK_EXT_mesh_shader");
initializer.deviceExtensions.add("VK_KHR_SPIRV_1_4_EXTENSION_NAME");
initializer.deviceExtensions.add("VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME");
}
deviceInfo.enabledExtensionCount = (uint32)initializer.deviceExtensions.size(); deviceInfo.enabledExtensionCount = (uint32)initializer.deviceExtensions.size();
deviceInfo.ppEnabledExtensionNames = initializer.deviceExtensions.data(); deviceInfo.ppEnabledExtensionNames = initializer.deviceExtensions.data();
deviceInfo.enabledLayerCount = (uint32_t)initializer.layers.size(); deviceInfo.enabledLayerCount = (uint32_t)initializer.layers.size();
@@ -590,6 +606,8 @@ void Graphics::createDevice(GraphicsInitializer initializer)
VK_CHECK(vkCreateDevice(physicalDevice, &deviceInfo, nullptr, &handle)); VK_CHECK(vkCreateDevice(physicalDevice, &deviceInfo, nullptr, &handle));
std::cout << "Vulkan handle: " << handle << std::endl; std::cout << "Vulkan handle: " << handle << std::endl;
cmdDrawMeshTasks = (PFN_vkCmdDrawMeshTasksEXT)vkGetDeviceProcAddr(handle, "vkCmdDrawMeshTasksEXT");
graphicsQueue = new Queue(this, Gfx::QueueType::GRAPHICS, graphicsQueueInfo.familyIndex, 0); graphicsQueue = new Queue(this, Gfx::QueueType::GRAPHICS, graphicsQueueInfo.familyIndex, 0);
if (Gfx::useAsyncCompute && asyncComputeInfo.familyIndex != -1) if (Gfx::useAsyncCompute && asyncComputeInfo.familyIndex != -1)
{ {
@@ -613,12 +631,8 @@ void Graphics::createDevice(GraphicsInitializer initializer)
{ {
dedicatedTransferQueue = new Queue(this, Gfx::QueueType::DEDICATED_TRANSFER, dedicatedTransferQueueInfo.familyIndex, 0); dedicatedTransferQueue = new Queue(this, Gfx::QueueType::DEDICATED_TRANSFER, dedicatedTransferQueueInfo.familyIndex, 0);
} }
else
{
dedicatedTransferQueue = transferQueue;
}
queueMapping.graphicsFamily = graphicsQueue->getFamilyIndex(); queueMapping.graphicsFamily = graphicsQueue->getFamilyIndex();
queueMapping.computeFamily = computeQueue->getFamilyIndex(); queueMapping.computeFamily = computeQueue->getFamilyIndex();
queueMapping.transferFamily = transferQueue->getFamilyIndex(); queueMapping.transferFamily = transferQueue->getFamilyIndex();
queueMapping.dedicatedTransferFamily = dedicatedTransferQueue->getFamilyIndex(); queueMapping.dedicatedTransferFamily = dedicatedTransferQueue != nullptr ? dedicatedTransferQueue->getFamilyIndex() : transferQueue->getFamilyIndex();
} }
+3 -1
View File
@@ -73,7 +73,9 @@ public:
virtual Gfx::OPipelineLayout createPipelineLayout(Gfx::PPipelineLayout baseLayout = nullptr) override; virtual Gfx::OPipelineLayout createPipelineLayout(Gfx::PPipelineLayout baseLayout = nullptr) override;
virtual void copyTexture(Gfx::PTexture srcTexture, Gfx::PTexture dstTexture) override; virtual void copyTexture(Gfx::PTexture srcTexture, Gfx::PTexture dstTexture) override;
void vkCmdDrawMeshTasksEXT(VkCommandBuffer handle, uint32 groupX, uint32 groupY, uint32 groupZ);
protected: protected:
PFN_vkCmdDrawMeshTasksEXT cmdDrawMeshTasks;
Array<const char *> getRequiredExtensions(); Array<const char *> getRequiredExtensions();
void initInstance(GraphicsInitializer initInfo); void initInstance(GraphicsInitializer initInfo);
void setupDebugCallback(); void setupDebugCallback();
@@ -97,7 +99,7 @@ protected:
thread_local static OCommandBufferManager transferCommands; thread_local static OCommandBufferManager transferCommands;
thread_local static OCommandBufferManager dedicatedTransferCommands; thread_local static OCommandBufferManager dedicatedTransferCommands;
VkPhysicalDeviceProperties props; VkPhysicalDeviceProperties props;
VkPhysicalDeviceFeatures features; VkPhysicalDeviceFeatures2 features;
VkDebugReportCallbackEXT callback; VkDebugReportCallbackEXT callback;
std::mutex viewportLock; std::mutex viewportLock;
Array<PViewport> viewports; Array<PViewport> viewports;
@@ -1,6 +1,7 @@
#include "Initializer.h" #include "Initializer.h"
#include <iostream> #include <iostream>
#include "Initializer.h" #include "Initializer.h"
#include "Initializer.h"
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
+5
View File
@@ -51,6 +51,11 @@ VkDeviceCreateInfo DeviceCreateInfo(
uint32_t queueCount, uint32_t queueCount,
VkPhysicalDeviceFeatures *features); VkPhysicalDeviceFeatures *features);
VkDeviceCreateInfo DeviceCreateInfo(
VkDeviceQueueCreateInfo* queueInfos,
uint32_t queueCount,
VkPhysicalDeviceFeatures2* features);
VkSwapchainCreateInfoKHR SwapchainCreateInfo( VkSwapchainCreateInfoKHR SwapchainCreateInfo(
VkSurfaceKHR surface, VkSurfaceKHR surface,
uint32_t minImageCount, uint32_t minImageCount,
+21 -19
View File
@@ -48,7 +48,7 @@ PipelineCache::~PipelineCache()
std::cout << "Written " << cacheSize << " bytes to cache" << std::endl; std::cout << "Written " << cacheSize << " bytes to cache" << std::endl;
} }
PGraphicsPipeline PipelineCache::createPipeline(const Gfx::LegacyPipelineCreateInfo& gfxInfo) OGraphicsPipeline PipelineCache::createPipeline(const Gfx::LegacyPipelineCreateInfo& gfxInfo)
{ {
uint32 stageCount = 0; uint32 stageCount = 0;
@@ -99,7 +99,7 @@ PGraphicsPipeline PipelineCache::createPipeline(const Gfx::LegacyPipelineCreateI
*res = VkVertexInputBindingDescription{ *res = VkVertexInputBindingDescription{
.binding = elem.binding, .binding = elem.binding,
.stride = elem.stride, .stride = elem.stride,
.inputRate = elem.bInstanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX, .inputRate = elem.instanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX,
}; };
} }
vertexInput.pVertexAttributeDescriptions = attributes.data(); vertexInput.pVertexAttributeDescriptions = attributes.data();
@@ -217,12 +217,12 @@ PGraphicsPipeline PipelineCache::createPipeline(const Gfx::LegacyPipelineCreateI
std::cout << "Gfx creation time: " << delta << std::endl; std::cout << "Gfx creation time: " << delta << std::endl;
PGraphicsPipeline result = new GraphicsPipeline(graphics, pipelineHandle, layout); OGraphicsPipeline result = new GraphicsPipeline(graphics, pipelineHandle, layout);
return result; return result;
} }
PGraphicsPipeline PipelineCache::createPipeline(const Gfx::MeshPipelineCreateInfo& gfxInfo) OGraphicsPipeline PipelineCache::createPipeline(const Gfx::MeshPipelineCreateInfo& gfxInfo)
{ {
uint32 stageCount = 0; uint32 stageCount = 0;
@@ -361,33 +361,35 @@ PGraphicsPipeline PipelineCache::createPipeline(const Gfx::MeshPipelineCreateInf
int64 delta = std::chrono::duration_cast<std::chrono::microseconds>(endTime - beginTime).count(); int64 delta = std::chrono::duration_cast<std::chrono::microseconds>(endTime - beginTime).count();
std::cout << "Gfx creation time: " << delta << std::endl; std::cout << "Gfx creation time: " << delta << std::endl;
OGraphicsPipeline result = new GraphicsPipeline(graphics, pipelineHandle, layout);
PGraphicsPipeline result = new GraphicsPipeline(graphics, pipelineHandle, layout);
return result; return result;
} }
PComputePipeline PipelineCache::createPipeline(const Gfx::ComputePipelineCreateInfo& computeInfo) OComputePipeline PipelineCache::createPipeline(const Gfx::ComputePipelineCreateInfo& computeInfo)
{ {
VkComputePipelineCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
createInfo.pNext = 0;
createInfo.flags = 0;
createInfo.basePipelineIndex = 0;
createInfo.basePipelineHandle = VK_NULL_HANDLE;
auto layout = computeInfo.pipelineLayout.cast<PipelineLayout>(); auto layout = computeInfo.pipelineLayout.cast<PipelineLayout>();
createInfo.layout = layout->getHandle();
auto computeStage = computeInfo.computeShader.cast<ComputeShader>(); auto computeStage = computeInfo.computeShader.cast<ComputeShader>();
createInfo.stage = init::PipelineShaderStageCreateInfo(
VK_SHADER_STAGE_COMPUTE_BIT, VkComputePipelineCreateInfo createInfo = {
computeStage->getModuleHandle(), .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
computeStage->getEntryPointName()); .pNext = 0,
.flags = 0,
.stage = init::PipelineShaderStageCreateInfo(
VK_SHADER_STAGE_COMPUTE_BIT,
computeStage->getModuleHandle(),
computeStage->getEntryPointName()),
.layout = layout->getHandle(),
.basePipelineHandle = VK_NULL_HANDLE,
.basePipelineIndex = 0,
};
VkPipeline pipelineHandle; VkPipeline pipelineHandle;
auto beginTime = std::chrono::high_resolution_clock::now(); auto beginTime = std::chrono::high_resolution_clock::now();
VK_CHECK(vkCreateComputePipelines(graphics->getDevice(), cache, 1, &createInfo, nullptr, &pipelineHandle)); VK_CHECK(vkCreateComputePipelines(graphics->getDevice(), cache, 1, &createInfo, nullptr, &pipelineHandle));
auto endTime = std::chrono::high_resolution_clock::now(); auto endTime = std::chrono::high_resolution_clock::now();
int64 delta = std::chrono::duration_cast<std::chrono::microseconds>(endTime - beginTime).count(); int64 delta = std::chrono::duration_cast<std::chrono::microseconds>(endTime - beginTime).count();
std::cout << "Compute creation time: " << delta << std::endl; std::cout << "Compute creation time: " << delta << std::endl;
PComputePipeline result = new ComputePipeline(graphics, pipelineHandle, layout); OComputePipeline result = new ComputePipeline(graphics, pipelineHandle, layout);
return result; return result;
} }
+3 -3
View File
@@ -10,9 +10,9 @@ class PipelineCache
public: public:
PipelineCache(PGraphics graphics, const std::string& cacheFilePath); PipelineCache(PGraphics graphics, const std::string& cacheFilePath);
~PipelineCache(); ~PipelineCache();
PGraphicsPipeline createPipeline(const Gfx::LegacyPipelineCreateInfo& createInfo); OGraphicsPipeline createPipeline(const Gfx::LegacyPipelineCreateInfo& createInfo);
PGraphicsPipeline createPipeline(const Gfx::MeshPipelineCreateInfo& createInfo); OGraphicsPipeline createPipeline(const Gfx::MeshPipelineCreateInfo& createInfo);
PComputePipeline createPipeline(const Gfx::ComputePipelineCreateInfo& createInfo); OComputePipeline createPipeline(const Gfx::ComputePipelineCreateInfo& createInfo);
private: private:
VkPipelineCache cache; VkPipelineCache cache;
PGraphics graphics; PGraphics graphics;
@@ -3,6 +3,7 @@
#include "Graphics.h" #include "Graphics.h"
#include "Framebuffer.h" #include "Framebuffer.h"
#include "Texture.h" #include "Texture.h"
#include "RenderPass.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Vulkan; using namespace Seele::Vulkan;
@@ -144,3 +145,4 @@ uint32 RenderPass::getFramebufferHash()
} }
return CRC::Calculate(&description, sizeof(FramebufferDescription), CRC::CRC_32()); return CRC::Calculate(&description, sizeof(FramebufferDescription), CRC::CRC_32());
} }
+3 -7
View File
@@ -1,10 +1,6 @@
#include "VulkanGraphicsResources.h" #include "Texture.h"
#include "VulkanGraphics.h" #include "Initializer.h"
#include "VulkanInitializer.h" #include "CommandBuffer.h"
#include "VulkanGraphicsEnums.h"
#include "VulkanAllocator.h"
#include "VulkanCommandBuffer.h"
#include "Graphics/GraphicsEnums.h"
#include <math.h> #include <math.h>
using namespace Seele; using namespace Seele;
+19 -19
View File
@@ -10,22 +10,22 @@ Material::Material()
} }
Material::Material(Gfx::PGraphics graphics, Material::Material(Gfx::PGraphics graphics,
Array<OShaderParameter> parameter,
Gfx::ODescriptorLayout layout, Gfx::ODescriptorLayout layout,
uint32 uniformDataSize, uint32 uniformDataSize,
uint32 uniformBinding, uint32 uniformBinding,
std::string materialName, std::string materialName,
Array<OShaderExpression> expressions, Map<std::string, OShaderExpression> expressions,
Array<std::string> parameter,
MaterialNode brdf) MaterialNode brdf)
: graphics(graphics) : graphics(graphics)
, parameters(std::move(parameter))
, uniformDataSize(uniformDataSize) , uniformDataSize(uniformDataSize)
, uniformBinding(uniformBinding) , uniformBinding(uniformBinding)
, instanceId(0)
, layout(std::move(layout)) , layout(std::move(layout))
, materialName(materialName) , materialName(materialName)
, codeExpressions(std::move(expressions)) , codeExpressions(std::move(expressions))
, brdf(brdf) , parameters(std::move(parameter))
, instanceId(0) , brdf(std::move(brdf))
{ {
} }
@@ -33,14 +33,19 @@ Material::~Material()
{ {
} }
PMaterialInstance Seele::Material::instantiate() OMaterialInstance Material::instantiate()
{ {
return new MaterialInstance(instanceId++, graphics, this, layout, parameters, uniformBinding, uniformDataSize); return new MaterialInstance(
instanceId++,
graphics,
codeExpressions,
parameters,
uniformBinding,
uniformDataSize);
} }
void Material::save(ArchiveBuffer& buffer) const void Material::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, brdfName);
Serialization::save(buffer, uniformDataSize); Serialization::save(buffer, uniformDataSize);
Serialization::save(buffer, uniformBinding); Serialization::save(buffer, uniformBinding);
Serialization::save(buffer, instanceId); Serialization::save(buffer, instanceId);
@@ -59,13 +64,11 @@ void Material::save(ArchiveBuffer& buffer) const
Serialization::save(buffer, binding.descriptorType); Serialization::save(buffer, binding.descriptorType);
Serialization::save(buffer, binding.shaderStages); Serialization::save(buffer, binding.shaderStages);
} }
Serialization::save(buffer, instances);
} }
void Material::load(ArchiveBuffer& buffer) void Material::load(ArchiveBuffer& buffer)
{ {
graphics = buffer.getGraphics(); graphics = buffer.getGraphics();
Serialization::load(buffer, brdfName);
Serialization::load(buffer, uniformDataSize); Serialization::load(buffer, uniformDataSize);
Serialization::load(buffer, uniformBinding); Serialization::load(buffer, uniformBinding);
Serialization::load(buffer, instanceId); Serialization::load(buffer, instanceId);
@@ -98,11 +101,6 @@ void Material::load(ArchiveBuffer& buffer)
layout->addDescriptorBinding(binding, descriptorType, descriptorCount, bindingFlags, shaderStages); layout->addDescriptorBinding(binding, descriptorType, descriptorCount, bindingFlags, shaderStages);
} }
layout->create(); layout->create();
Serialization::load(buffer, instances);
for (auto& instance : instances)
{
instance->setBaseMaterial(this);
}
} }
void Material::compile() void Material::compile()
@@ -114,21 +112,23 @@ void Material::compile()
codeStream << "struct " << materialName << " : IMaterial {\n"; codeStream << "struct " << materialName << " : IMaterial {\n";
for(const auto& parameter : parameters) for(const auto& parameter : parameters)
{ {
parameter->generateDeclaration(codeStream); PShaderParameter handle = PShaderExpression(codeExpressions[parameter]);
handle->generateDeclaration(codeStream);
} }
codeStream << "\ttypedef " << brdf.profile << " BRDF;\n"; codeStream << "\ttypedef " << brdf.profile << " BRDF;\n";
codeStream << "\t" << brdf.profile << " prepare(MaterialFragmentParameter input) {\n"; codeStream << "\t" << brdf.profile << " prepare(MaterialFragmentParameter input) {\n";
codeStream << "\t\t" << brdf.profile << " result;\n"; codeStream << "\t\t" << brdf.profile << " result;\n";
Map<int32, std::string> varState; Map<std::string, std::string> varState;
for(const auto& expr : codeExpressions) for(const auto& [_, expr] :codeExpressions)
{ {
codeStream << expr->evaluate(varState); codeStream << expr->evaluate(varState);
} }
for(const auto& [name, exp] : brdf.variables) for(const auto& [name, exp] : brdf.variables)
{ {
codeStream << "\t\tresult." << name << " = " << varState[exp->key] << ";"; codeStream << "\t\tresult." << name << " = " << varState[exp] << ";";
} }
codeStream << "\t\treturn result;\n"; codeStream << "\t\treturn result;\n";
codeStream << "\t}\n"; codeStream << "\t}\n";
codeStream << "};\n"; codeStream << "};\n";
graphics->getShaderCompiler()->registerMaterial(this);
} }
+5 -8
View File
@@ -10,17 +10,16 @@ class Material
public: public:
Material(); Material();
Material(Gfx::PGraphics graphics, Material(Gfx::PGraphics graphics,
Array<OShaderParameter> parameter,
Gfx::ODescriptorLayout layout, Gfx::ODescriptorLayout layout,
uint32 uniformDataSize, uint32 uniformDataSize,
uint32 uniformBinding, uint32 uniformBinding,
std::string materialName, std::string materialName,
Array<OShaderExpression> expressions, Map<std::string, OShaderExpression> expressions,
Array<std::string> parameter,
MaterialNode brdf); MaterialNode brdf);
~Material(); ~Material();
const Gfx::PDescriptorLayout getDescriptorLayout() const { return layout; } const Gfx::PDescriptorLayout getDescriptorLayout() const { return layout; }
PMaterialInstance instantiate(); OMaterialInstance instantiate();
PMaterialInstance getInstance(uint64 instance) { return instances[instance]; }
const std::string& getName() const { return materialName; } const std::string& getName() const { return materialName; }
void save(ArchiveBuffer& buffer) const; void save(ArchiveBuffer& buffer) const;
@@ -30,15 +29,13 @@ public:
private: private:
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
std::string brdfName;
uint32 uniformDataSize; uint32 uniformDataSize;
uint32 uniformBinding; uint32 uniformBinding;
uint64 instanceId; uint64 instanceId;
Gfx::ODescriptorLayout layout; Gfx::ODescriptorLayout layout;
std::string materialName; std::string materialName;
Array<OShaderExpression> codeExpressions; Map<std::string, OShaderExpression> codeExpressions;
Array<OShaderParameter> parameters; Array<std::string> parameters;
Array<OMaterialInstance> instances;
MaterialNode brdf; MaterialNode brdf;
}; };
DEFINE_REF(Material) DEFINE_REF(Material)
+35 -18
View File
@@ -8,17 +8,34 @@ MaterialInstance::MaterialInstance()
{ {
} }
MaterialInstance::MaterialInstance(uint64 id, Gfx::PGraphics graphics, PMaterial baseMaterial, Gfx::PDescriptorLayout layout, Array<OShaderParameter> params, uint32 uniformBinding, uint32 uniformSize) MaterialInstance::MaterialInstance(uint64 id,
: id(id), graphics(graphics), baseMaterial(baseMaterial), layout(layout), parameters(params), uniformBinding(uniformBinding) Gfx::PGraphics graphics,
Map<std::string, OShaderExpression>& expressions,
Array<std::string> params,
uint32 uniformBinding,
uint32 uniformSize)
: id(id)
, graphics(graphics)
, uniformBinding(uniformBinding)
{ {
uniformBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{ uniformBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{
.sourceData = { .sourceData = {
.size = uniformSize, .size = uniformSize,
}, },
.bDynamic = true, .dynamic = true,
} }
); );
uniformData.resize(uniformSize); uniformData.resize(uniformSize);
ArchiveBuffer buffer(graphics);
parameters.reserve(params.size());
for (int i = 0; i < params.size(); ++i)
{
Serialization::save(buffer, params[i]);
buffer.rewind();
OShaderParameter param;
Serialization::load(buffer, param);
parameters.add(std::move(param));
}
} }
MaterialInstance::~MaterialInstance() MaterialInstance::~MaterialInstance()
@@ -28,6 +45,8 @@ MaterialInstance::~MaterialInstance()
void MaterialInstance::updateDescriptor() void MaterialInstance::updateDescriptor()
{ {
Gfx::PDescriptorLayout layout = baseMaterial->getMaterial()->getDescriptorLayout();
layout->reset();
descriptor = layout->allocateDescriptorSet(); descriptor = layout->allocateDescriptorSet();
for (auto& param : parameters) for (auto& param : parameters)
{ {
@@ -36,16 +55,27 @@ void MaterialInstance::updateDescriptor()
descriptor->writeChanges(); descriptor->writeChanges();
} }
Gfx::PDescriptorSet Seele::MaterialInstance::getDescriptorSet() const Gfx::PDescriptorSet MaterialInstance::getDescriptorSet() const
{ {
return descriptor; return descriptor;
} }
void MaterialInstance::setBaseMaterial(PMaterialAsset asset)
{
uniformBuffer = graphics->createUniformBuffer(UniformBufferCreateInfo{
.sourceData = {
.size = uniformData.size(),
},
.dynamic = true,
}
);
baseMaterial = asset;
}
void MaterialInstance::save(ArchiveBuffer& buffer) const void MaterialInstance::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, uniformData); Serialization::save(buffer, uniformData);
Serialization::save(buffer, uniformBinding); Serialization::save(buffer, uniformBinding);
Serialization::save(buffer, uniformBuffer);
Serialization::save(buffer, parameters); Serialization::save(buffer, parameters);
Serialization::save(buffer, id); Serialization::save(buffer, id);
} }
@@ -55,19 +85,6 @@ void MaterialInstance::load(ArchiveBuffer& buffer)
graphics = buffer.getGraphics(); graphics = buffer.getGraphics();
Serialization::load(buffer, uniformData); Serialization::load(buffer, uniformData);
Serialization::load(buffer, uniformBinding); Serialization::load(buffer, uniformBinding);
Serialization::load(buffer, uniformBuffer);
Serialization::load(buffer, parameters); Serialization::load(buffer, parameters);
Serialization::load(buffer, id); Serialization::load(buffer, id);
} }
void MaterialInstance::setBaseMaterial(PMaterial material)
{
layout = material->getDescriptorLayout();
baseMaterial = material;
descriptor = layout->allocateDescriptorSet();
for (auto& param : parameters)
{
param->updateDescriptorSet(descriptor, uniformData.data());
}
descriptor->writeChanges();
}
+11 -5
View File
@@ -1,6 +1,7 @@
#pragma once #pragma once
#include "Material.h" #include "Material.h"
#include "Graphics/Buffer.h" #include "Graphics/Buffer.h"
#include "Asset/MaterialAsset.h"
namespace Seele namespace Seele
{ {
@@ -8,16 +9,22 @@ class MaterialInstance
{ {
public: public:
MaterialInstance(); MaterialInstance();
MaterialInstance(uint64 id, Gfx::PGraphics graphics, PMaterial baseMaterial, Gfx::PDescriptorLayout descriptor, Array<OShaderParameter> params, uint32 uniformBinding, uint32 uniformSize); MaterialInstance(uint64 id,
Gfx::PGraphics graphics,
Map<std::string, OShaderExpression>& expressions,
Array<std::string> params,
uint32 uniformBinding,
uint32 uniformSize);
~MaterialInstance(); ~MaterialInstance();
void updateDescriptor(); void updateDescriptor();
Gfx::PDescriptorSet getDescriptorSet() const; Gfx::PDescriptorSet getDescriptorSet() const;
PMaterial getBaseMaterial() const { return baseMaterial; } PMaterial getBaseMaterial() const { return baseMaterial->getMaterial(); }
uint64 getId() const { return id; } uint64 getId() const { return id; }
void setBaseMaterial(PMaterialAsset asset);
void save(ArchiveBuffer& buffer) const; void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer); void load(ArchiveBuffer& buffer);
void setBaseMaterial(PMaterial material);
private: private:
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
@@ -25,9 +32,8 @@ private:
uint32 uniformBinding; uint32 uniformBinding;
Gfx::OUniformBuffer uniformBuffer; Gfx::OUniformBuffer uniformBuffer;
Array<OShaderParameter> parameters; Array<OShaderParameter> parameters;
Gfx::PDescriptorLayout layout;
Gfx::PDescriptorSet descriptor; Gfx::PDescriptorSet descriptor;
PMaterial baseMaterial; PMaterialAsset baseMaterial;
uint64 id; uint64 id;
}; };
DEFINE_REF(MaterialInstance) DEFINE_REF(MaterialInstance)
+27 -17
View File
@@ -31,6 +31,15 @@ void ExpressionOutput::load(ArchiveBuffer& buffer)
Serialization::load(buffer, type); Serialization::load(buffer, type);
} }
ShaderExpression::ShaderExpression()
{
}
ShaderExpression::ShaderExpression(std::string key)
: key(key)
{
}
void ShaderExpression::save(ArchiveBuffer& buffer) const void ShaderExpression::save(ArchiveBuffer& buffer) const
{ {
Serialization::save(buffer, inputs); Serialization::save(buffer, inputs);
@@ -46,7 +55,7 @@ void ShaderExpression::load(ArchiveBuffer& buffer)
} }
ShaderParameter::ShaderParameter(std::string name, uint32 byteOffset, uint32 binding) ShaderParameter::ShaderParameter(std::string name, uint32 byteOffset, uint32 binding)
: name(name) : ShaderExpression(name)
, byteOffset(byteOffset) , byteOffset(byteOffset)
, binding(binding) , binding(binding)
{ {
@@ -56,16 +65,16 @@ ShaderParameter::~ShaderParameter()
{ {
} }
std::string ShaderParameter::evaluate(Map<int32, std::string>& varState) const std::string ShaderParameter::evaluate(Map<std::string, std::string>& varState) const
{ {
varState[key] = name; varState[key] = key;
return ""; return "";
} }
void ShaderParameter::save(ArchiveBuffer& buffer) const void ShaderParameter::save(ArchiveBuffer& buffer) const
{ {
ShaderExpression::save(buffer); ShaderExpression::save(buffer);
Serialization::save(buffer, name); Serialization::save(buffer, key);
Serialization::save(buffer, byteOffset); Serialization::save(buffer, byteOffset);
Serialization::save(buffer, binding); Serialization::save(buffer, binding);
} }
@@ -73,7 +82,7 @@ void ShaderParameter::save(ArchiveBuffer& buffer) const
void ShaderParameter::load(ArchiveBuffer& buffer) void ShaderParameter::load(ArchiveBuffer& buffer)
{ {
ShaderExpression::load(buffer); ShaderExpression::load(buffer);
Serialization::load(buffer, name); Serialization::load(buffer, key);
Serialization::load(buffer, byteOffset); Serialization::load(buffer, byteOffset);
Serialization::load(buffer, binding); Serialization::load(buffer, binding);
} }
@@ -109,7 +118,7 @@ void FloatParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst)
void FloatParameter::generateDeclaration(std::ofstream& stream) const void FloatParameter::generateDeclaration(std::ofstream& stream) const
{ {
stream << "\tlayout(offset = " << byteOffset << ") float " << name << ";\n"; stream << "\tlayout(offset = " << byteOffset << ") float " << key << ";\n";
} }
VectorParameter::VectorParameter(std::string name, uint32 byteOffset, uint32 binding) VectorParameter::VectorParameter(std::string name, uint32 byteOffset, uint32 binding)
@@ -131,7 +140,7 @@ void VectorParameter::updateDescriptorSet(Gfx::PDescriptorSet, uint8* dst)
void VectorParameter::generateDeclaration(std::ofstream& stream) const void VectorParameter::generateDeclaration(std::ofstream& stream) const
{ {
stream << "\tlayout(offset = " << byteOffset << ") float3 " << name << ";\n"; stream << "\tlayout(offset = " << byteOffset << ") float3 " << key << ";\n";
} }
void VectorParameter::save(ArchiveBuffer& buffer) const void VectorParameter::save(ArchiveBuffer& buffer) const
@@ -164,7 +173,7 @@ void TextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, ui
void TextureParameter::generateDeclaration(std::ofstream& stream) const void TextureParameter::generateDeclaration(std::ofstream& stream) const
{ {
stream << "\tTexture2D " << name << ";\n"; stream << "\tTexture2D " << key << ";\n";
} }
void TextureParameter::save(ArchiveBuffer& buffer) const void TextureParameter::save(ArchiveBuffer& buffer) const
@@ -200,7 +209,7 @@ void SamplerParameter::updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, ui
void SamplerParameter::generateDeclaration(std::ofstream& stream) const void SamplerParameter::generateDeclaration(std::ofstream& stream) const
{ {
stream << "\tSamplerState " << name << ";\n"; stream << "\tSamplerState " << key << ";\n";
} }
void SamplerParameter::save(ArchiveBuffer& buffer) const void SamplerParameter::save(ArchiveBuffer& buffer) const
@@ -233,7 +242,7 @@ void CombinedTextureParameter::updateDescriptorSet(Gfx::PDescriptorSet descripto
void CombinedTextureParameter::generateDeclaration(std::ofstream& stream) const void CombinedTextureParameter::generateDeclaration(std::ofstream& stream) const
{ {
stream << "\tTexture2D " << name << ";\n"; stream << "\tTexture2D " << key << ";\n";
} }
void CombinedTextureParameter::save(ArchiveBuffer& buffer) const void CombinedTextureParameter::save(ArchiveBuffer& buffer) const
@@ -267,9 +276,9 @@ ConstantExpression::~ConstantExpression()
} }
std::string ConstantExpression::evaluate(Map<int32, std::string>& varState) const std::string ConstantExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("const_exp_{}", std::abs(key)); std::string varName = std::format("const_exp_{}", key);
varState[key] = varName; varState[key] = varName;
return std::format("let {} = {};\n", varName, expr); return std::format("let {} = {};\n", varName, expr);
} }
@@ -296,7 +305,7 @@ AddExpression::~AddExpression()
} }
std::string AddExpression::evaluate(Map<int32, std::string>& varState) const std::string AddExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("exp_{}", key); std::string varName = std::format("exp_{}", key);
varState[key] = varName; varState[key] = varName;
@@ -313,7 +322,7 @@ void AddExpression::load(ArchiveBuffer& buffer)
ShaderExpression::load(buffer); ShaderExpression::load(buffer);
} }
std::string SubExpression::evaluate(Map<int32, std::string>& varState) const std::string SubExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("exp_{}", key); std::string varName = std::format("exp_{}", key);
varState[key] = varName; varState[key] = varName;
@@ -330,7 +339,7 @@ void SubExpression::load(ArchiveBuffer& buffer)
ShaderExpression::load(buffer); ShaderExpression::load(buffer);
} }
std::string MulExpression::evaluate(Map<int32, std::string>& varState) const std::string MulExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("exp_{}", key); std::string varName = std::format("exp_{}", key);
varState[key] = varName; varState[key] = varName;
@@ -347,7 +356,7 @@ void MulExpression::load(ArchiveBuffer& buffer)
ShaderExpression::load(buffer); ShaderExpression::load(buffer);
} }
std::string SwizzleExpression::evaluate(Map<int32, std::string>& varState) const std::string SwizzleExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("exp_{}", key); std::string varName = std::format("exp_{}", key);
std::string swizzle = ""; std::string swizzle = "";
@@ -370,6 +379,7 @@ std::string SwizzleExpression::evaluate(Map<int32, std::string>& varState) const
break; break;
case 3: case 3:
swizzle += "w"; swizzle += "w";
break;
default: default:
throw std::logic_error("invalid component"); throw std::logic_error("invalid component");
} }
@@ -390,7 +400,7 @@ void SwizzleExpression::load(ArchiveBuffer& buffer)
Serialization::load(buffer, comp); Serialization::load(buffer, comp);
} }
std::string SampleExpression::evaluate(Map<int32, std::string>& varState) const std::string SampleExpression::evaluate(Map<std::string, std::string>& varState) const
{ {
std::string varName = std::format("exp_{}", key); std::string varName = std::format("exp_{}", key);
varState[key] = varName; varState[key] = varName;
+13 -12
View File
@@ -18,7 +18,7 @@ enum class ExpressionType
}; };
struct ExpressionInput struct ExpressionInput
{ {
int source; std::string source;
ExpressionType type = ExpressionType::UNKNOWN; ExpressionType type = ExpressionType::UNKNOWN;
void save(ArchiveBuffer& buffer) const; void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer); void load(ArchiveBuffer& buffer);
@@ -35,9 +35,11 @@ struct ShaderExpression
{ {
Map<std::string, ExpressionInput> inputs; Map<std::string, ExpressionInput> inputs;
ExpressionOutput output; ExpressionOutput output;
int32 key; std::string key;
ShaderExpression();
ShaderExpression(std::string key);
virtual uint64 getIdentifier() const = 0; virtual uint64 getIdentifier() const = 0;
virtual std::string evaluate(Map<int32, std::string>& varState) const = 0; virtual std::string evaluate(Map<std::string, std::string>& varState) const = 0;
virtual void save(ArchiveBuffer& buffer) const; virtual void save(ArchiveBuffer& buffer) const;
virtual void load(ArchiveBuffer& buffer); virtual void load(ArchiveBuffer& buffer);
}; };
@@ -46,7 +48,6 @@ DEFINE_REF(ShaderExpression)
DECLARE_NAME_REF(Gfx, DescriptorSet) DECLARE_NAME_REF(Gfx, DescriptorSet)
struct ShaderParameter : public ShaderExpression struct ShaderParameter : public ShaderExpression
{ {
std::string name;
uint32 byteOffset; uint32 byteOffset;
uint32 binding; uint32 binding;
ShaderParameter() {} ShaderParameter() {}
@@ -56,7 +57,7 @@ struct ShaderParameter : public ShaderExpression
virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) = 0; virtual void updateDescriptorSet(Gfx::PDescriptorSet descriptorSet, uint8* dst) = 0;
virtual void generateDeclaration(std::ofstream& stream) const = 0; virtual void generateDeclaration(std::ofstream& stream) const = 0;
virtual uint64 getIdentifier() const = 0; virtual uint64 getIdentifier() const = 0;
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const; virtual void save(ArchiveBuffer& buffer) const;
virtual void load(ArchiveBuffer& buffer); virtual void load(ArchiveBuffer& buffer);
}; };
@@ -143,7 +144,7 @@ struct ConstantExpression : public ShaderExpression
ConstantExpression(std::string expr, ExpressionType type); ConstantExpression(std::string expr, ExpressionType type);
virtual ~ConstantExpression(); virtual ~ConstantExpression();
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -154,7 +155,7 @@ struct AddExpression : public ShaderExpression
AddExpression(); AddExpression();
virtual ~AddExpression(); virtual ~AddExpression();
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -165,7 +166,7 @@ struct SubExpression : public ShaderExpression
SubExpression() {} SubExpression() {}
virtual ~SubExpression() {} virtual ~SubExpression() {}
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -176,7 +177,7 @@ struct MulExpression : public ShaderExpression
MulExpression() {} MulExpression() {}
virtual ~MulExpression() {} virtual ~MulExpression() {}
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -188,7 +189,7 @@ struct SwizzleExpression : public ShaderExpression
SwizzleExpression() {} SwizzleExpression() {}
virtual ~SwizzleExpression() {} virtual ~SwizzleExpression() {}
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -199,7 +200,7 @@ struct SampleExpression : public ShaderExpression
SampleExpression() {} SampleExpression() {}
virtual ~SampleExpression() {} virtual ~SampleExpression() {}
virtual uint64 getIdentifier() const { return IDENTIFIER; } virtual uint64 getIdentifier() const { return IDENTIFIER; }
virtual std::string evaluate(Map<int32, std::string>& varState) const override; virtual std::string evaluate(Map<std::string, std::string>& varState) const override;
virtual void save(ArchiveBuffer& buffer) const override; virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
}; };
@@ -208,7 +209,7 @@ DEFINE_REF(SampleExpression)
struct MaterialNode struct MaterialNode
{ {
std::string profile; std::string profile;
Map<std::string, OShaderExpression> variables; Map<std::string, std::string> variables;
MaterialNode() {} MaterialNode() {}
~MaterialNode() {} ~MaterialNode() {}
void save(ArchiveBuffer& buffer) const; void save(ArchiveBuffer& buffer) const;

Some files were not shown because too many files have changed in this diff Show More