Formatted EVERYTHING

This commit is contained in:
Dynamitos
2024-06-09 12:20:53 +02:00
parent f18bf8acbe
commit d95dab850c
265 changed files with 8002 additions and 12310 deletions
+6
View File
@@ -0,0 +1,6 @@
BasedOnStyle: LLVM
IndentWidth: 4
Language: Cpp
ColumnLimit: 140
DerivePointerAlignment: false
PointerAlignment: Left
+10 -11
View File
@@ -1,23 +1,23 @@
#include "Asset/Asset.h" #include "Asset/Asset.h"
#include "Asset/MeshAsset.h" #include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h" #include "Asset/FontAsset.h"
#include "Asset/TextureAsset.h"
#include "Asset/MaterialAsset.h" #include "Asset/MaterialAsset.h"
#include "Asset/MaterialInstanceAsset.h" #include "Asset/MaterialInstanceAsset.h"
#include "Asset/AssetRegistry.h" #include "Asset/MeshAsset.h"
#include "Asset/TextureAsset.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
using namespace Seele; using namespace Seele;
AssetRegistry * _instance = new AssetRegistry(); AssetRegistry* _instance = new AssetRegistry();
int main(int, char**) int main(int, char**) {
{ // if(argc < 2)
//if(argc < 2)
//{ //{
// return -1; // return -1;
//} // }
std::filesystem::path path = std::filesystem::path("C:\\Users\\Dynamitos\\TrackClear\\Assets\\Dirt.asset"); std::filesystem::path path = std::filesystem::path("C:\\Users\\Dynamitos\\TrackClear\\Assets\\Dirt.asset");
std::ifstream stream = std::ifstream(path, std::ios::binary); std::ifstream stream = std::ifstream(path, std::ios::binary);
@@ -37,8 +37,7 @@ int main(int, char**)
Serialization::load(buffer, folderPath); Serialization::load(buffer, folderPath);
PAsset asset; PAsset asset;
switch (identifier) switch (identifier) {
{
case TextureAsset::IDENTIFIER: case TextureAsset::IDENTIFIER:
asset = new TextureAsset(folderPath, name); asset = new TextureAsset(folderPath, name);
break; break;
+13 -23
View File
@@ -1,54 +1,46 @@
#include "AssetImporter.h" #include "AssetImporter.h"
#include "FontLoader.h" #include "FontLoader.h"
#include "TextureLoader.h" #include "Graphics/Graphics.h"
#include "MaterialLoader.h" #include "MaterialLoader.h"
#include "MeshLoader.h" #include "MeshLoader.h"
#include "Graphics/Graphics.h" #include "TextureLoader.h"
using namespace Seele; using namespace Seele;
void AssetImporter::importMesh(MeshImportArgs args) void AssetImporter::importMesh(MeshImportArgs args) {
{ if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string())) {
if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string()))
{
// skip importing duplicates // skip importing duplicates
return; return;
} }
get().meshLoader->importAsset(args); get().meshLoader->importAsset(args);
} }
void AssetImporter::importTexture(TextureImportArgs args) void AssetImporter::importTexture(TextureImportArgs args) {
{ if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string())) {
if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string()))
{
// skip importing duplicates // skip importing duplicates
return; return;
} }
get().textureLoader->importAsset(args); get().textureLoader->importAsset(args);
} }
void AssetImporter::importFont(FontImportArgs args) void AssetImporter::importFont(FontImportArgs args) {
{ if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string())) {
if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string()))
{
// skip importing duplicates // skip importing duplicates
return; return;
} }
get().fontLoader->importAsset(args); get().fontLoader->importAsset(args);
} }
void AssetImporter::importMaterial(MaterialImportArgs args) void AssetImporter::importMaterial(MaterialImportArgs args) {
{ if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string())) {
if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string()))
{
// skip importing duplicates // skip importing duplicates
return; return;
} }
get().materialLoader->importAsset(args); get().materialLoader->importAsset(args);
} }
void AssetImporter::init(Gfx::PGraphics graphics) void AssetImporter::init(Gfx::PGraphics graphics) {
{
get().registry = AssetRegistry::getInstance(); get().registry = AssetRegistry::getInstance();
get().meshLoader = new MeshLoader(graphics); get().meshLoader = new MeshLoader(graphics);
get().textureLoader = new TextureLoader(graphics); get().textureLoader = new TextureLoader(graphics);
@@ -56,9 +48,7 @@ void AssetImporter::init(Gfx::PGraphics graphics)
get().fontLoader = new FontLoader(graphics); get().fontLoader = new FontLoader(graphics);
} }
AssetImporter& AssetImporter::get() AssetImporter& AssetImporter::get() {
{
static AssetImporter instance; static AssetImporter instance;
return instance; return instance;
} }
+7 -7
View File
@@ -1,22 +1,22 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "MinimalEngine.h"
namespace Seele
{ namespace Seele {
DECLARE_REF(TextureLoader) DECLARE_REF(TextureLoader)
DECLARE_REF(FontLoader) DECLARE_REF(FontLoader)
DECLARE_REF(MeshLoader) DECLARE_REF(MeshLoader)
DECLARE_REF(MaterialLoader) DECLARE_REF(MaterialLoader)
class AssetImporter class AssetImporter {
{ public:
public:
static void importMesh(struct MeshImportArgs args); static void importMesh(struct MeshImportArgs args);
static void importTexture(struct TextureImportArgs args); static void importTexture(struct TextureImportArgs args);
static void importFont(struct FontImportArgs args); static void importFont(struct FontImportArgs args);
static void importMaterial(struct MaterialImportArgs args); static void importMaterial(struct MaterialImportArgs args);
static void init(Gfx::PGraphics graphics); static void init(Gfx::PGraphics graphics);
private:
private:
static AssetImporter& get(); static AssetImporter& get();
UPTextureLoader textureLoader; UPTextureLoader textureLoader;
UPFontLoader fontLoader; UPFontLoader fontLoader;
+14 -22
View File
@@ -1,28 +1,23 @@
#include "FontLoader.h" #include "FontLoader.h"
#include "Graphics/Graphics.h"
#include "Asset/FontAsset.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Resources.h" #include "Graphics/Resources.h"
#include "Graphics/Texture.h" #include "Graphics/Texture.h"
#include <ft2build.h> #include <ft2build.h>
#include FT_FREETYPE_H #include FT_FREETYPE_H
#include <iostream>
#include <fstream> #include <fstream>
#include <iostream>
using namespace Seele; using namespace Seele;
FontLoader::FontLoader(Gfx::PGraphics graphics) FontLoader::FontLoader(Gfx::PGraphics graphics) : graphics(graphics) {}
: graphics(graphics)
{
} FontLoader::~FontLoader() {}
FontLoader::~FontLoader() void FontLoader::importAsset(FontImportArgs args) {
{
}
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");
OFontAsset asset = new FontAsset(args.importPath, assetPath.stem().string()); OFontAsset asset = new FontAsset(args.importPath, assetPath.stem().string());
@@ -36,8 +31,7 @@ void FontLoader::importAsset(FontImportArgs args)
// in case of the space character there is no bitmap // in case of the space character there is no bitmap
// so we create a single pixel empty texture // so we create a single pixel empty texture
uint8 transparentPixel = 0; uint8 transparentPixel = 0;
void FontLoader::import(FontImportArgs args, PFontAsset asset) void FontLoader::import(FontImportArgs args, PFontAsset asset) {
{
FT_Library ft; FT_Library ft;
FT_Error error = FT_Init_FreeType(&ft); FT_Error error = FT_Init_FreeType(&ft);
assert(!error); assert(!error);
@@ -46,10 +40,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
assert(!error); assert(!error);
FT_Set_Pixel_Sizes(face, 0, 48); FT_Set_Pixel_Sizes(face, 0, 48);
Array<Gfx::OTexture2D> usedTextures; Array<Gfx::OTexture2D> usedTextures;
for(uint32 c = 0; c < 256; ++c) for (uint32 c = 0; c < 256; ++c) {
{ if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
if(FT_Load_Char(face, c, FT_LOAD_RENDER))
{
std::cout << "error loading " << (char)c << std::endl; std::cout << "error loading " << (char)c << std::endl;
continue; continue;
} }
@@ -63,8 +55,7 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
imageData.height = face->glyph->bitmap.rows; imageData.height = face->glyph->bitmap.rows;
imageData.sourceData.data = face->glyph->bitmap.buffer; imageData.sourceData.data = face->glyph->bitmap.buffer;
imageData.sourceData.size = imageData.width * imageData.height; imageData.sourceData.size = imageData.width * imageData.height;
if(imageData.width == 0 || imageData.height == 0) if (imageData.width == 0 || imageData.height == 0) {
{
glyph.size.x = 1; glyph.size.x = 1;
glyph.size.y = 1; glyph.size.y = 1;
glyph.bearing.x = 0; glyph.bearing.x = 0;
@@ -81,7 +72,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
FT_Done_FreeType(ft); FT_Done_FreeType(ft);
asset->setUsedTextures(std::move(usedTextures)); asset->setUsedTextures(std::move(usedTextures));
auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->getFolderPath()) / asset->getName()).replace_extension("asset").string(), std::ios::binary); auto stream = AssetRegistry::createWriteStream(
(std::filesystem::path(asset->getFolderPath()) / asset->getName()).replace_extension("asset").string(), std::ios::binary);
ArchiveBuffer archive; ArchiveBuffer archive;
Serialization::save(archive, FontAsset::IDENTIFIER); Serialization::save(archive, FontAsset::IDENTIFIER);
+8 -9
View File
@@ -1,24 +1,23 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Containers/List.h" #include "Containers/List.h"
#include "MinimalEngine.h"
#include <filesystem> #include <filesystem>
namespace Seele
{ namespace Seele {
DECLARE_REF(FontAsset) DECLARE_REF(FontAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
struct FontImportArgs struct FontImportArgs {
{
std::filesystem::path filePath; std::filesystem::path filePath;
std::string importPath; std::string importPath;
}; };
class FontLoader class FontLoader {
{ public:
public:
FontLoader(Gfx::PGraphics graphic); FontLoader(Gfx::PGraphics graphic);
~FontLoader(); ~FontLoader();
void importAsset(FontImportArgs args); void importAsset(FontImportArgs args);
private:
private:
void import(FontImportArgs args, PFontAsset asset); void import(FontImportArgs args, PFontAsset asset);
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
}; };
+76 -112
View File
@@ -1,37 +1,35 @@
#include "MaterialLoader.h" #include "MaterialLoader.h"
#include "Asset/AssetRegistry.h"
#include "Asset/MaterialAsset.h"
#include "Asset/TextureAsset.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/Shader.h" #include "Graphics/Shader.h"
#include "Asset/MaterialAsset.h"
#include "Asset/AssetRegistry.h"
#include "Material/Material.h" #include "Material/Material.h"
#include "Window/WindowManager.h"
#include "Material/ShaderExpression.h" #include "Material/ShaderExpression.h"
#include "Asset/TextureAsset.h" #include "Window/WindowManager.h"
#include <nlohmann/json.hpp>
#include <fmt/core.h> #include <fmt/core.h>
#include <iostream>
#include <fstream> #include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using namespace Seele; using namespace Seele;
using json = nlohmann::json; using json = nlohmann::json;
MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) : graphics(graphics) {
: graphics(graphics)
{
OMaterialAsset placeholderAsset = new MaterialAsset(); OMaterialAsset placeholderAsset = new MaterialAsset();
import(MaterialImportArgs{ import(
.filePath = std::filesystem::absolute("./shaders/Placeholder.json"), MaterialImportArgs{
.importPath = "", .filePath = std::filesystem::absolute("./shaders/Placeholder.json"),
}, placeholderAsset); .importPath = "",
},
placeholderAsset);
AssetRegistry::get().assetRoot->materials[""] = std::move(placeholderAsset); AssetRegistry::get().assetRoot->materials[""] = std::move(placeholderAsset);
} }
MaterialLoader::~MaterialLoader() MaterialLoader::~MaterialLoader() {}
{
}
void MaterialLoader::importAsset(MaterialImportArgs args) 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");
OMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string()); OMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string());
@@ -41,14 +39,13 @@ void MaterialLoader::importAsset(MaterialImportArgs args)
import(args, ref); import(args, ref);
} }
void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset) {
{
auto jsonstream = std::ifstream(args.filePath.c_str()); auto jsonstream = std::ifstream(args.filePath.c_str());
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::ODescriptorLayout layout = graphics->createDescriptorLayout("pMaterial"); Gfx::ODescriptorLayout layout = graphics->createDescriptorLayout("pMaterial");
//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());
@@ -59,22 +56,21 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
uint32 key = 0; uint32 key = 0;
uint32 auxKey = 0; uint32 auxKey = 0;
Array<std::string> 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) {
{
float defaultData = 0.f; float defaultData = 0.f;
if (defaultValue != param.value().end()) if (defaultValue != param.value().end()) {
{
defaultData = std::stof(defaultValue.value().get<std::string>()); defaultData = std::stof(defaultValue.value().get<std::string>());
} }
OFloatParameter p = new FloatParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding); OFloatParameter p = new FloatParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding);
if(uniformBinding == -1) if (uniformBinding == -1) {
{ layout->addDescriptorBinding(Gfx::DescriptorBinding{
layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); .binding = bindingCounter,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
});
uniformBinding = bindingCounter++; uniformBinding = bindingCounter++;
} }
uniformBufferOffset += 4; uniformBufferOffset += 4;
@@ -82,93 +78,85 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
expressions.add(std::move(p)); expressions.add(std::move(p));
} }
// TODO: ALIGNMENT RULES // TODO: ALIGNMENT RULES
else if(type.compare("float3") == 0) else if (type.compare("float3") == 0) {
{
Vector defaultData = Vector(0, 0, 0); Vector defaultData = Vector(0, 0, 0);
if (defaultValue != param.value().end()) if (defaultValue != param.value().end()) {
{
defaultData = parseVector(defaultValue.value().get<std::string>().c_str()); defaultData = parseVector(defaultValue.value().get<std::string>().c_str());
} }
OVectorParameter p = new VectorParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding); OVectorParameter p = new VectorParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding);
if(uniformBinding == -1) if (uniformBinding == -1) {
{ layout->addDescriptorBinding(Gfx::DescriptorBinding{
layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,}); .binding = bindingCounter,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
});
uniformBinding = bindingCounter++; uniformBinding = bindingCounter++;
} }
uniformBufferOffset += 16; uniformBufferOffset += 16;
parameters.add(p->key); parameters.add(p->key);
expressions.add(std::move(p)); expressions.add(std::move(p));
} } else if (type.compare("Texture2D") == 0) {
else if(type.compare("Texture2D") == 0)
{
PTextureAsset texture; PTextureAsset texture;
if(defaultValue != param.value().end()) if (defaultValue != param.value().end()) {
{
std::string defaultString = defaultValue.value().get<std::string>(); std::string defaultString = defaultValue.value().get<std::string>();
auto slashPos = defaultString.rfind("/"); auto slashPos = defaultString.rfind("/");
std::string folder = ""; std::string folder = "";
if (slashPos != std::string::npos) if (slashPos != std::string::npos) {
{
folder = defaultString.substr(0, slashPos - 1); folder = defaultString.substr(0, slashPos - 1);
defaultString = defaultString.substr(slashPos, defaultString.length()); defaultString = defaultString.substr(slashPos, defaultString.length());
} }
texture = AssetRegistry::findTexture(folder, defaultString); texture = AssetRegistry::findTexture(folder, defaultString);
} }
if(texture == nullptr) if (texture == nullptr) {
{
texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture
} }
OTextureParameter p = new TextureParameter(param.key(), texture, bindingCounter); OTextureParameter p = new TextureParameter(param.key(), texture, bindingCounter);
layout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, }); layout->addDescriptorBinding(Gfx::DescriptorBinding{
.binding = bindingCounter++,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
});
parameters.add(p->key); parameters.add(p->key);
expressions.add(std::move(p)); expressions.add(std::move(p));
} } else if (type.compare("Sampler") == 0) {
else if(type.compare("Sampler") == 0)
{
OSamplerParameter p = new SamplerParameter(param.key(), graphics->createSampler({}), bindingCounter); OSamplerParameter p = new SamplerParameter(param.key(), graphics->createSampler({}), bindingCounter);
layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,}); layout->addDescriptorBinding(Gfx::DescriptorBinding{
.binding = bindingCounter++,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
});
parameters.add(p->key); parameters.add(p->key);
expressions.add(std::move(p)); expressions.add(std::move(p));
} } else if (type.compare("Sampler2D") == 0) {
else if (type.compare("Sampler2D") == 0)
{
PTextureAsset texture; PTextureAsset texture;
if (defaultValue != param.value().end()) if (defaultValue != param.value().end()) {
{
std::string defaultString = defaultValue.value().get<std::string>(); std::string defaultString = defaultValue.value().get<std::string>();
auto slashPos = defaultString.rfind("/"); auto slashPos = defaultString.rfind("/");
std::string folder = ""; std::string folder = "";
if (slashPos != std::string::npos) if (slashPos != std::string::npos) {
{
folder = defaultString.substr(0, slashPos - 1); folder = defaultString.substr(0, slashPos - 1);
defaultString = defaultString.substr(slashPos, defaultString.length()); defaultString = defaultString.substr(slashPos, defaultString.length());
} }
texture = AssetRegistry::findTexture(folder, defaultString); texture = AssetRegistry::findTexture(folder, defaultString);
} }
if (texture == nullptr) if (texture == nullptr) {
{
texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture
} }
OCombinedTextureParameter p = new CombinedTextureParameter(param.key(), texture, graphics->createSampler({}), bindingCounter); OCombinedTextureParameter p = new CombinedTextureParameter(param.key(), texture, graphics->createSampler({}), bindingCounter);
layout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = bindingCounter++, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, }); layout->addDescriptorBinding(Gfx::DescriptorBinding{
.binding = bindingCounter++,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
});
parameters.add(p->key); parameters.add(p->key);
expressions.add(std::move(p)); expressions.add(std::move(p));
} } else {
else
{
std::cout << "Error unsupported parameter type" << std::endl; std::cout << "Error unsupported parameter type" << std::endl;
} }
} }
uint32 uniformDataSize = uniformBufferOffset; uint32 uniformDataSize = uniformBufferOffset;
auto referenceExpression = [&parameters, &auxKey, &expressions](json obj) -> std::string auto referenceExpression = [&parameters, &auxKey, &expressions](json obj) -> std::string {
{ if (obj.is_string()) {
if(obj.is_string())
{
std::string str = obj.get<std::string>(); std::string str = obj.get<std::string>();
if (parameters.find(str) != parameters.end()) if (parameters.find(str) != parameters.end()) {
{
return str; return str;
} }
OConstantExpression c = new ConstantExpression(str, ExpressionType::UNKNOWN); OConstantExpression c = new ConstantExpression(str, ExpressionType::UNKNOWN);
@@ -176,28 +164,23 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
c->key = name; c->key = name;
expressions.add(std::move(c)); expressions.add(std::move(c));
return name; return name;
} } else {
else
{
return fmt::format("{0}", obj.get<uint32>()); return fmt::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("Const") == 0) if (exp.compare("Const") == 0) {
{
OConstantExpression p = new ConstantExpression(); OConstantExpression p = new ConstantExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
p->expr = obj["value"]; p->expr = obj["value"];
expressions.add(std::move(p)); expressions.add(std::move(p));
} }
if(exp.compare("Add") == 0) if (exp.compare("Add") == 0) {
{
OAddExpression p = new AddExpression(); OAddExpression p = new AddExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
@@ -205,8 +188,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]); p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p)); expressions.add(std::move(p));
} }
if(exp.compare("Sub") == 0) if (exp.compare("Sub") == 0) {
{
OSubExpression p = new SubExpression(); OSubExpression p = new SubExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
@@ -214,8 +196,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]); p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p)); expressions.add(std::move(p));
} }
if(exp.compare("Mul") == 0) if (exp.compare("Mul") == 0) {
{
OMulExpression p = new MulExpression(); OMulExpression p = new MulExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
@@ -223,63 +204,49 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]); p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p)); expressions.add(std::move(p));
} }
if(exp.compare("Swizzle") == 0) if (exp.compare("Swizzle") == 0) {
{
OSwizzleExpression p = new SwizzleExpression(); OSwizzleExpression p = new SwizzleExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
p->inputs["target"].source = referenceExpression(obj["target"]); 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.add(std::move(p)); expressions.add(std::move(p));
} }
if(exp.compare("Sample") == 0) if (exp.compare("Sample") == 0) {
{
OSampleExpression p = new SampleExpression(); OSampleExpression p = new SampleExpression();
std::string name = fmt::format("{0}", key++); std::string name = fmt::format("{0}", key++);
p->key = name; p->key = name;
if (obj.contains("texture")) if (obj.contains("texture")) {
{
p->inputs["texture"].source = referenceExpression(obj["texture"]); p->inputs["texture"].source = referenceExpression(obj["texture"]);
} }
p->inputs["sampler"].source = referenceExpression(obj["sampler"]); p->inputs["sampler"].source = referenceExpression(obj["sampler"]);
p->inputs["coords"].source = referenceExpression(obj["coords"]); p->inputs["coords"].source = referenceExpression(obj["coords"]);
expressions.add(std::move(p)); expressions.add(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()] = referenceExpression(val.value());
} }
} }
} }
layout->create(); layout->create();
asset->material = new Material( asset->material = new Material(graphics, std::move(layout), uniformDataSize, uniformBinding, materialName, std::move(expressions),
graphics, std::move(parameters), std::move(mat));
std::move(layout),
uniformDataSize,
uniformBinding,
materialName,
std::move(expressions),
std::move(parameters),
std::move(mat)
);
asset->material->compile(); asset->material->compile();
graphics->getShaderCompiler()->registerMaterial(asset->material); graphics->getShaderCompiler()->registerMaterial(asset->material);
asset->setStatus(Asset::Status::Ready); asset->setStatus(Asset::Status::Ready);
if (asset->getName().empty()) if (asset->getName().empty()) {
{
return; return;
} }
auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->folderPath) / asset->getName()).string().append(".asset"), std::ios::binary); auto stream = AssetRegistry::createWriteStream((std::filesystem::path(asset->folderPath) / asset->getName()).string().append(".asset"),
std::ios::binary);
ArchiveBuffer archive; ArchiveBuffer archive;
Serialization::save(archive, MaterialAsset::IDENTIFIER); Serialization::save(archive, MaterialAsset::IDENTIFIER);
@@ -290,7 +257,4 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
////co_return; ////co_return;
} }
PMaterialAsset MaterialLoader::getPlaceHolderMaterial() PMaterialAsset MaterialLoader::getPlaceHolderMaterial() { return placeholderMaterial; }
{
return placeholderMaterial;
}
+8 -9
View File
@@ -1,25 +1,24 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Containers/List.h" #include "Containers/List.h"
#include "MinimalEngine.h"
#include <filesystem> #include <filesystem>
namespace Seele
{ namespace Seele {
DECLARE_REF(MaterialAsset) DECLARE_REF(MaterialAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
struct MaterialImportArgs struct MaterialImportArgs {
{
std::filesystem::path filePath; std::filesystem::path filePath;
std::string importPath; std::string importPath;
}; };
class MaterialLoader class MaterialLoader {
{ public:
public:
MaterialLoader(Gfx::PGraphics graphic); MaterialLoader(Gfx::PGraphics graphic);
~MaterialLoader(); ~MaterialLoader();
void importAsset(MaterialImportArgs args); void importAsset(MaterialImportArgs args);
PMaterialAsset getPlaceHolderMaterial(); PMaterialAsset getPlaceHolderMaterial();
private:
private:
void import(MaterialImportArgs args, PMaterialAsset asset); void import(MaterialImportArgs args, PMaterialAsset asset);
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
PMaterialAsset placeholderMaterial; PMaterialAsset placeholderMaterial;
+235 -314
View File
@@ -1,37 +1,32 @@
#include "MeshLoader.h" #include "MeshLoader.h"
#include "Graphics/Graphics.h"
#include "Asset/MeshAsset.h"
#include "Graphics/Mesh.h"
#include "Graphics/StaticMeshVertexData.h"
#include "Asset/AssetImporter.h" #include "Asset/AssetImporter.h"
#include "Asset/MaterialAsset.h" #include "Asset/MaterialAsset.h"
#include "Asset/MeshAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
#include "Graphics/Shader.h" #include "Graphics/Shader.h"
#include <set> #include "Graphics/StaticMeshVertexData.h"
#include <Asset/MaterialLoader.h>
#include <Asset/TextureLoader.h>
#include <assimp/Importer.hpp>
#include <assimp/config.h>
#include <assimp/material.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <fmt/core.h> #include <fmt/core.h>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <set>
#include <stb_image_write.h> #include <stb_image_write.h>
#include <assimp/config.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/material.h>
#include <Asset/MaterialLoader.h>
#include <Asset/TextureLoader.h>
using namespace Seele; using namespace Seele;
MeshLoader::MeshLoader(Gfx::PGraphics graphics) MeshLoader::MeshLoader(Gfx::PGraphics graphics) : graphics(graphics) {}
: graphics(graphics)
{
}
MeshLoader::~MeshLoader() MeshLoader::~MeshLoader() {}
{
}
void MeshLoader::importAsset(MeshImportArgs args) 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");
OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string()); OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
@@ -41,43 +36,31 @@ void MeshLoader::importAsset(MeshImportArgs args)
import(args, ref); import(args, ref);
} }
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels) {
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels) for (uint32 i = 0; i < numPixels; ++i) {
{
for (uint32 i = 0; i < numPixels; ++i)
{
dst[i * 4 + 0] = src[i].r; dst[i * 4 + 0] = src[i].r;
dst[i * 4 + 1] = src[i].g; dst[i * 4 + 1] = src[i].g;
dst[i * 4 + 2] = src[i].b; dst[i * 4 + 2] = src[i].b;
dst[i * 4 + 3] = src[i].a; dst[i * 4 + 3] = src[i].a;
} }
} }
void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PTextureAsset>& textures) void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath,
{ Array<PTextureAsset>& textures) {
for (uint32 i = 0; i < scene->mNumTextures; ++i) for (uint32 i = 0; i < scene->mNumTextures; ++i) {
{
aiTexture* tex = scene->mTextures[i]; aiTexture* tex = scene->mTextures[i];
auto texPath = std::filesystem::path(tex->mFilename.C_Str()); auto texPath = std::filesystem::path(tex->mFilename.C_Str());
if (std::filesystem::exists(texPath)) if (std::filesystem::exists(texPath)) {
{ } else if (std::filesystem::exists(meshDirectory / texPath)) {
}
else if (std::filesystem::exists(meshDirectory / texPath))
{
texPath = meshDirectory / texPath; texPath = meshDirectory / texPath;
} } else {
else
{
texPath = (meshDirectory / texPath).replace_extension("png"); texPath = (meshDirectory / texPath).replace_extension("png");
if (tex->mHeight == 0) if (tex->mHeight == 0) {
{
std::cout << "Dumping texture " << texPath << std::endl; std::cout << "Dumping texture " << texPath << std::endl;
// already compressed, just dump it to the disk // already compressed, just dump it to the disk
std::ofstream file(texPath, std::ios::binary); std::ofstream file(texPath, std::ios::binary);
file.write((const char*)tex->pcData, tex->mWidth); file.write((const char*)tex->pcData, tex->mWidth);
file.flush(); file.flush();
} } else {
else
{
std::cout << "Writing extracted png " << texPath << std::endl; std::cout << "Writing extracted png " << texPath << std::endl;
// recompress data so that the TextureLoader can read it // recompress data so that the TextureLoader can read it
unsigned char* texData = new unsigned char[tex->mWidth * tex->mHeight * 4]; unsigned char* texData = new unsigned char[tex->mWidth * tex->mHeight * 4];
@@ -90,7 +73,7 @@ void MeshLoader::loadTextures(const aiScene* scene, const std::filesystem::path&
AssetImporter::importTexture(TextureImportArgs{ AssetImporter::importTexture(TextureImportArgs{
.filePath = texPath, .filePath = texPath,
.importPath = importPath, .importPath = importPath,
}); });
textures.add(AssetRegistry::findTexture(importPath, texPath.stem().string())); textures.add(AssetRegistry::findTexture(importPath, texPath.stem().string()));
} }
} }
@@ -111,18 +94,23 @@ constexpr const char* KEY_ROUGHNESS_TEXTURE = "tex_r";
constexpr const char* KEY_METALLIC_TEXTURE = "tex_m"; constexpr const char* KEY_METALLIC_TEXTURE = "tex_m";
constexpr const char* KEY_AMBIENT_OCCLUSION_TEXTURE = "tex_ao"; constexpr const char* KEY_AMBIENT_OCCLUSION_TEXTURE = "tex_ao";
void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>& textures, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialInstanceAsset>& globalMaterials) void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>& textures, const std::string& baseName,
{ const std::filesystem::path& meshDirectory, const std::string& importPath,
for (uint32 m = 0; m < scene->mNumMaterials; ++m) Array<PMaterialInstanceAsset>& globalMaterials) {
{ for (uint32 m = 0; m < scene->mNumMaterials; ++m) {
aiMaterial* material = scene->mMaterials[m]; aiMaterial* material = scene->mMaterials[m];
aiString texPath; aiString texPath;
std::string materialName = fmt::format("M{0}{1}{2}", baseName, material->GetName().C_Str(), m); std::string materialName = fmt::format("M{0}{1}{2}", baseName, material->GetName().C_Str(), m);
materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'), materialName.end()); // dots break adding the .asset extension later materialName.erase(std::remove(materialName.begin(), materialName.end(), '.'),
materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'), materialName.end()); // dots break adding the .asset extension later materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), ' '), materialName.end()); // dots break adding the .asset extension later materialName.erase(std::remove(materialName.begin(), materialName.end(), '-'),
materialName.erase(std::remove(materialName.begin(), materialName.end(), '('), materialName.end()); // dots break adding the .asset extension later materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), ')'), materialName.end()); // dots break adding the .asset extension later materialName.erase(std::remove(materialName.begin(), materialName.end(), ' '),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), '('),
materialName.end()); // dots break adding the .asset extension later
materialName.erase(std::remove(materialName.begin(), materialName.end(), ')'),
materialName.end()); // dots break adding the .asset extension later
Gfx::ODescriptorLayout materialLayout = graphics->createDescriptorLayout("pMaterial"); Gfx::ODescriptorLayout materialLayout = graphics->createDescriptorLayout("pMaterial");
Array<OShaderExpression> expressions; Array<OShaderExpression> expressions;
Array<std::string> parameters; Array<std::string> parameters;
@@ -131,200 +119,183 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
.binding = 0, .binding = 0,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT,
}); });
size_t uniformSize = 0; size_t uniformSize = 0;
uint32 bindingCounter = 1; uint32 bindingCounter = 1;
auto addScalarParameter = [&](std::string paramKey, const char* matKey, int type, int index) auto addScalarParameter = [&](std::string paramKey, const char* matKey, int type, int index) {
{ float scalar;
float scalar; material->Get(matKey, type, index, scalar);
material->Get(matKey, type, index, scalar); expressions.add(new FloatParameter(paramKey, scalar, uniformSize, 0));
expressions.add(new FloatParameter(paramKey, scalar, uniformSize, 0)); uniformSize += sizeof(float);
uniformSize += sizeof(float); parameters.add(paramKey);
parameters.add(paramKey); };
};
auto addVectorParameter = [&](std::string paramKey, const char* matKey, int type, int index) auto addVectorParameter = [&](std::string paramKey, const char* matKey, int type, int index) {
{ aiColor3D color;
aiColor3D color; material->Get(matKey, type, index, color);
material->Get(matKey, type, index, color); uniformSize = (uniformSize + sizeof(Vector4) - 1) / sizeof(Vector4) * sizeof(Vector4);
uniformSize = (uniformSize + sizeof(Vector4) - 1) / sizeof(Vector4) * sizeof(Vector4); expressions.add(new VectorParameter(paramKey, Vector(color.r, color.g, color.b), uniformSize, 0));
expressions.add(new VectorParameter(paramKey, Vector(color.r, color.g, color.b), uniformSize, 0)); uniformSize += sizeof(Vector);
uniformSize += sizeof(Vector); parameters.add(paramKey);
parameters.add(paramKey); };
};
auto addTextureParameter = [&](std::string paramKey, aiTextureType type, int index, std::string& result, StaticArray<int32, 4> extractMask = { 0, 1, 2, -1 }) auto addTextureParameter = [&](std::string paramKey, aiTextureType type, int index, std::string& result,
{ StaticArray<int32, 4> extractMask = {0, 1, 2, -1}) {
aiString texPath; aiString texPath;
aiTextureMapping mapping; aiTextureMapping mapping;
uint32 uvIndex = 0; uint32 uvIndex = 0;
aiTextureMapMode mapMode = aiTextureMapMode_Clamp; aiTextureMapMode mapMode = aiTextureMapMode_Clamp;
float blend = std::numeric_limits<float>::max(); float blend = std::numeric_limits<float>::max();
aiTextureOp op; aiTextureOp op;
if (material->GetTexture(type, index, &texPath, &mapping, &uvIndex, nullptr, nullptr, nullptr) != AI_SUCCESS) if (material->GetTexture(type, index, &texPath, &mapping, &uvIndex, nullptr, nullptr, nullptr) != AI_SUCCESS) {
{ std::cout << "fuck" << std::endl;
std::cout << "fuck" << std::endl; }
}
std::string textureKey = fmt::format("{0}Texture{1}", paramKey, index); std::string textureKey = fmt::format("{0}Texture{1}", paramKey, index);
auto texFilename = std::filesystem::path(texPath.C_Str()); auto texFilename = std::filesystem::path(texPath.C_Str());
PTextureAsset texture; PTextureAsset texture;
if (texFilename.string()[0] == '*') if (texFilename.string()[0] == '*') {
{ texture = textures[atoi(texFilename.string().substr(1).c_str())];
texture = textures[atoi(texFilename.string().substr(1).c_str())]; } else if (std::filesystem::exists(texFilename)) {
} AssetImporter::importTexture(TextureImportArgs{
else if (std::filesystem::exists(texFilename))
{
AssetImporter::importTexture(TextureImportArgs{
.filePath = texFilename, .filePath = texFilename,
.importPath = importPath, .importPath = importPath,
}); });
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} } else if (std::filesystem::exists(meshDirectory / texFilename)) {
else if (std::filesystem::exists(meshDirectory / texFilename)) AssetImporter::importTexture(TextureImportArgs{
{
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texFilename, .filePath = meshDirectory / texFilename,
.importPath = importPath, .importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D, .type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
}); });
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} } else if (std::filesystem::exists(meshDirectory.parent_path() / "textures" / texFilename)) {
else if (std::filesystem::exists(meshDirectory.parent_path() / "textures" / texFilename)) AssetImporter::importTexture(TextureImportArgs{
{
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory.parent_path() / "textures" / texFilename, .filePath = meshDirectory.parent_path() / "textures" / texFilename,
.importPath = importPath, .importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D, .type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
}); });
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string()); texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
} } else {
else std::cout << "couldnt find " << texPath.C_Str() << std::endl;
{ return;
std::cout << "couldnt find " << texPath.C_Str() << std::endl; }
return; expressions.add(new TextureParameter(textureKey, texture, bindingCounter));
} materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{
expressions.add(new TextureParameter(textureKey, texture, bindingCounter)); .binding = bindingCounter,
materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
.binding = bindingCounter, .textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE, .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT,
.textureType = Gfx::SE_IMAGE_VIEW_TYPE_2D, });
.shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, parameters.add(textureKey);
}); bindingCounter++;
parameters.add(textureKey);
bindingCounter++;
std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index); std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index);
SamplerCreateInfo samplerInfo = {}; SamplerCreateInfo samplerInfo = {};
switch (mapMode) switch (mapMode) {
{ case aiTextureMapMode_Wrap:
case aiTextureMapMode_Wrap: samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT; break;
break; case aiTextureMapMode_Clamp:
case aiTextureMapMode_Clamp: samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; break;
break; case aiTextureMapMode_Decal:
case aiTextureMapMode_Decal: samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; break;
break; case aiTextureMapMode_Mirror:
case aiTextureMapMode_Mirror: samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
samplerInfo.addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
samplerInfo.addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
samplerInfo.addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; break;
break; }
} expressions.add(new SamplerParameter(samplerKey, graphics->createSampler(samplerInfo), bindingCounter));
expressions.add(new SamplerParameter(samplerKey, graphics->createSampler(samplerInfo), bindingCounter)); materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{
materialLayout->addDescriptorBinding(Gfx::DescriptorBinding{ .binding = bindingCounter,
.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_SAMPLER, .shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT,
.shaderStages = Gfx::SE_SHADER_STAGE_FRAGMENT_BIT, });
}); parameters.add(samplerKey);
parameters.add(samplerKey); bindingCounter++;
bindingCounter++;
std::string sampleKey = fmt::format("{0}Sample{1}", paramKey, index); std::string sampleKey = fmt::format("{0}Sample{1}", paramKey, index);
expressions.add(new SampleExpression()); expressions.add(new SampleExpression());
expressions.back()->key = sampleKey; expressions.back()->key = sampleKey;
expressions.back()->inputs["texture"].source = textureKey; expressions.back()->inputs["texture"].source = textureKey;
expressions.back()->inputs["sampler"].source = samplerKey; expressions.back()->inputs["sampler"].source = samplerKey;
expressions.back()->inputs["coords"].source = fmt::format("input.texCoords[{0}]", uvIndex); expressions.back()->inputs["coords"].source = fmt::format("input.texCoords[{0}]", uvIndex);
std::string colorExtract = fmt::format("{0}Extract{1}", paramKey, index); std::string colorExtract = fmt::format("{0}Extract{1}", paramKey, index);
expressions.add(new SwizzleExpression(extractMask)); expressions.add(new SwizzleExpression(extractMask));
expressions.back()->key = colorExtract; expressions.back()->key = colorExtract;
expressions.back()->inputs["target"].source = sampleKey; expressions.back()->inputs["target"].source = sampleKey;
//TODO: extract alpha, set opacity // TODO: extract alpha, set opacity
if (blend == std::numeric_limits<float>::max()) if (blend == std::numeric_limits<float>::max()) {
{ result = colorExtract;
result = colorExtract; return;
return; }
} std::string blendFactorKey = fmt::format("{0}BlendFactor{1}", paramKey, index);
std::string blendFactorKey = fmt::format("{0}BlendFactor{1}", paramKey, index); expressions.add(new FloatParameter(blendFactorKey, blend, uniformSize, 0));
expressions.add(new FloatParameter(blendFactorKey, blend, uniformSize, 0)); uniformSize += sizeof(float);
uniformSize += sizeof(float); parameters.add(blendFactorKey);
parameters.add(blendFactorKey);
std::string strengthKey = fmt::format("{0}Strength{1}", paramKey, index); std::string strengthKey = fmt::format("{0}Strength{1}", paramKey, index);
expressions.add(new MulExpression());
expressions.back()->key = strengthKey;
expressions.back()->inputs["lhs"].source = colorExtract;
expressions.back()->inputs["rhs"].source = blendFactorKey;
std::string blendKey = fmt::format("{0}Blend{1}", paramKey, index);
switch (op) {
/** T = T1 * T2 */
case aiTextureOp_Multiply:
expressions.add(new MulExpression()); expressions.add(new MulExpression());
expressions.back()->key = strengthKey; break;
expressions.back()->inputs["lhs"].source = colorExtract;
expressions.back()->inputs["rhs"].source = blendFactorKey;
std::string blendKey = fmt::format("{0}Blend{1}", paramKey, index); /** T = T1 - T2 */
switch (op) { case aiTextureOp_Subtract:
/** T = T1 * T2 */ expressions.add(new SubExpression());
case aiTextureOp_Multiply: break;
expressions.add(new MulExpression());
break;
/** T = T1 - T2 */ /** T = T1 / T2 */
case aiTextureOp_Subtract: case aiTextureOp_Divide:
expressions.add(new SubExpression()); // expressions[blendKey] = new DivExpression();
break; throw std::logic_error("Not implemented");
/** T = T1 / T2 */ /** T = (T1 + T2) - (T1 * T2) */
case aiTextureOp_Divide: case aiTextureOp_SmoothAdd:
//expressions[blendKey] = new DivExpression(); throw std::logic_error("Not implemented");
throw std::logic_error("Not implemented");
/** T = (T1 + T2) - (T1 * T2) */ /** T = T1 + (T2-0.5) */
case aiTextureOp_SmoothAdd: case aiTextureOp_SignedAdd:
throw std::logic_error("Not implemented"); throw std::logic_error("Not implemented");
/** T = T1 + T2 */
case aiTextureOp_Add:
default:
expressions.add(new AddExpression());
break;
}
expressions.back()->key = blendKey;
expressions.back()->inputs["lhs"].source = result;
expressions.back()->inputs["rhs"].source = strengthKey;
/** T = T1 + (T2-0.5) */ result = blendKey;
case aiTextureOp_SignedAdd: };
throw std::logic_error("Not implemented");
/** T = T1 + T2 */
case aiTextureOp_Add:
default:
expressions.add(new AddExpression());
break;
}
expressions.back()->key = blendKey;
expressions.back()->inputs["lhs"].source = result;
expressions.back()->inputs["rhs"].source = strengthKey;
result = blendKey;
};
// Diffuse // Diffuse
addVectorParameter(KEY_DIFFUSE_COLOR, AI_MATKEY_COLOR_DIFFUSE); addVectorParameter(KEY_DIFFUSE_COLOR, AI_MATKEY_COLOR_DIFFUSE);
std::string outputDiffuse = KEY_DIFFUSE_COLOR; std::string outputDiffuse = KEY_DIFFUSE_COLOR;
uint32 numDiffuseTextures = material->GetTextureCount(aiTextureType_DIFFUSE); uint32 numDiffuseTextures = material->GetTextureCount(aiTextureType_DIFFUSE);
for (uint32 i = 0; i < numDiffuseTextures; ++i) for (uint32 i = 0; i < numDiffuseTextures; ++i) {
{
addTextureParameter(KEY_DIFFUSE_TEXTURE, aiTextureType_DIFFUSE, i, outputDiffuse); addTextureParameter(KEY_DIFFUSE_TEXTURE, aiTextureType_DIFFUSE, i, outputDiffuse);
} }
@@ -332,16 +303,14 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addVectorParameter(KEY_SPECULAR_COLOR, AI_MATKEY_COLOR_SPECULAR); addVectorParameter(KEY_SPECULAR_COLOR, AI_MATKEY_COLOR_SPECULAR);
std::string outputSpecular = KEY_SPECULAR_COLOR; std::string outputSpecular = KEY_SPECULAR_COLOR;
uint32 numSpecular = material->GetTextureCount(aiTextureType_SPECULAR); uint32 numSpecular = material->GetTextureCount(aiTextureType_SPECULAR);
for (uint32 i = 0; i < numSpecular; ++i) for (uint32 i = 0; i < numSpecular; ++i) {
{
addTextureParameter(KEY_SPECULAR_TEXTURE, aiTextureType_SPECULAR, i, outputSpecular); addTextureParameter(KEY_SPECULAR_TEXTURE, aiTextureType_SPECULAR, i, outputSpecular);
} }
// Normal // Normal
std::string outputNormal = ""; std::string outputNormal = "";
uint32 numNormal = material->GetTextureCount(aiTextureType_NORMALS); uint32 numNormal = material->GetTextureCount(aiTextureType_NORMALS);
for (uint32 i = 0; i < numNormal; ++i) for (uint32 i = 0; i < numNormal; ++i) {
{
addTextureParameter(KEY_NORMAL_TEXTURE, aiTextureType_NORMALS, i, outputNormal); addTextureParameter(KEY_NORMAL_TEXTURE, aiTextureType_NORMALS, i, outputNormal);
} }
@@ -349,8 +318,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addVectorParameter(KEY_AMBIENT_COLOR, AI_MATKEY_COLOR_AMBIENT); addVectorParameter(KEY_AMBIENT_COLOR, AI_MATKEY_COLOR_AMBIENT);
std::string outputAmbient = KEY_AMBIENT_COLOR; std::string outputAmbient = KEY_AMBIENT_COLOR;
uint32 numAmbient = material->GetTextureCount(aiTextureType_AMBIENT); uint32 numAmbient = material->GetTextureCount(aiTextureType_AMBIENT);
for (uint32 i = 0; i < numAmbient; ++i) for (uint32 i = 0; i < numAmbient; ++i) {
{
addTextureParameter(KEY_AMBIENT_TEXTURE, aiTextureType_AMBIENT, i, outputAmbient); addTextureParameter(KEY_AMBIENT_TEXTURE, aiTextureType_AMBIENT, i, outputAmbient);
} }
@@ -358,42 +326,36 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addScalarParameter(KEY_SHININESS, AI_MATKEY_SHININESS); addScalarParameter(KEY_SHININESS, AI_MATKEY_SHININESS);
std::string outputShininess = KEY_SHININESS; std::string outputShininess = KEY_SHININESS;
uint32 numShiny = material->GetTextureCount(aiTextureType_SHININESS); uint32 numShiny = material->GetTextureCount(aiTextureType_SHININESS);
for (uint32 i = 0; i < numShiny; ++i) for (uint32 i = 0; i < numShiny; ++i) {
{ addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, {0, -1, -1, -1});
addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, { 0, -1, -1, -1 });
} }
// Roughness // Roughness
addScalarParameter(KEY_ROUGHNESS, AI_MATKEY_ROUGHNESS_FACTOR); addScalarParameter(KEY_ROUGHNESS, AI_MATKEY_ROUGHNESS_FACTOR);
std::string outputRoughness = KEY_ROUGHNESS; std::string outputRoughness = KEY_ROUGHNESS;
uint32 numRoughness = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS); uint32 numRoughness = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS);
for (uint32 i = 0; i < numRoughness; ++i) for (uint32 i = 0; i < numRoughness; ++i) {
{ addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, {0, -1, -1, -1});
addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, { 0, -1, -1, -1 });
} }
// Metallic // Metallic
addScalarParameter(KEY_METALLIC, AI_MATKEY_METALLIC_FACTOR); addScalarParameter(KEY_METALLIC, AI_MATKEY_METALLIC_FACTOR);
std::string outputMetallic = KEY_METALLIC; std::string outputMetallic = KEY_METALLIC;
uint32 numMetallic = material->GetTextureCount(aiTextureType_METALNESS); uint32 numMetallic = material->GetTextureCount(aiTextureType_METALNESS);
for (uint32 i = 0; i < numMetallic; ++i) for (uint32 i = 0; i < numMetallic; ++i) {
{ addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, {0, -1, -1, -1});
addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, { 0, -1, -1, -1 });
} }
// Ambient Occlusion // Ambient Occlusion
std::string outputAO = ""; std::string outputAO = "";
uint32 numAO = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION); uint32 numAO = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION);
for (uint32 i = 0; i < numAO; ++i) for (uint32 i = 0; i < numAO; ++i) {
{ addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, {0, -1, -1, -1});
addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, { 0, -1, -1, -1 });
} }
MaterialNode brdf; MaterialNode brdf;
brdf.variables["baseColor"] = outputDiffuse; brdf.variables["baseColor"] = outputDiffuse;
if (!outputNormal.empty()) if (!outputNormal.empty()) {
{
expressions.add(new MulExpression()); expressions.add(new MulExpression());
expressions.back()->key = "NormalMul"; expressions.back()->key = "NormalMul";
expressions.back()->inputs["lhs"].source = "2"; expressions.back()->inputs["lhs"].source = "2";
@@ -429,8 +391,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
brdf.profile = "CookTorrance"; brdf.profile = "CookTorrance";
brdf.variables["roughness"] = outputRoughness; brdf.variables["roughness"] = outputRoughness;
brdf.variables["metallic"] = outputMetallic; brdf.variables["metallic"] = outputMetallic;
if (!outputAO.empty()) if (!outputAO.empty()) {
{
brdf.variables["ambientOcclusion"] = outputAmbient; brdf.variables["ambientOcclusion"] = outputAmbient;
} }
break; break;
@@ -439,41 +400,32 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
materialLayout->create(); materialLayout->create();
OMaterialAsset baseMat = new MaterialAsset(importPath, materialName); OMaterialAsset baseMat = new MaterialAsset(importPath, materialName);
baseMat->material = new Material(graphics, baseMat->material = new Material(graphics, std::move(materialLayout), uniformSize, 0, materialName, std::move(expressions),
std::move(materialLayout), std::move(parameters), std::move(brdf));
uniformSize, 0, materialName,
std::move(expressions),
std::move(parameters),
std::move(brdf)
);
baseMat->material->compile(); baseMat->material->compile();
graphics->getShaderCompiler()->registerMaterial(baseMat->material); graphics->getShaderCompiler()->registerMaterial(baseMat->material);
globalMaterials[m] = baseMat->instantiate(InstantiationParameter{ globalMaterials[m] = baseMat->instantiate(InstantiationParameter{
.name = fmt::format("{0}_Inst_0", baseMat->getName()), .name = fmt::format("{0}_Inst_0", baseMat->getName()),
.folderPath = baseMat->getFolderPath(), .folderPath = baseMat->getFolderPath(),
}); });
AssetRegistry::get().saveAsset(PMaterialAsset(baseMat), MaterialAsset::IDENTIFIER, baseMat->getFolderPath(), baseMat->getName()); AssetRegistry::get().saveAsset(PMaterialAsset(baseMat), MaterialAsset::IDENTIFIER, baseMat->getFolderPath(), baseMat->getName());
AssetRegistry::get().registerMaterial(std::move(baseMat)); AssetRegistry::get().registerMaterial(std::move(baseMat));
} }
} }
void findMeshRoots(aiNode* node, List<aiNode*>& meshNodes) void findMeshRoots(aiNode* node, List<aiNode*>& meshNodes) {
{ if (node->mNumMeshes > 0) {
if (node->mNumMeshes > 0)
{
meshNodes.add(node); meshNodes.add(node);
return; return;
} }
for (uint32 i = 0; i < node->mNumChildren; ++i) for (uint32 i = 0; i < node->mNumChildren; ++i) {
{
findMeshRoots(node->mChildren[i], meshNodes); findMeshRoots(node->mChildren[i], meshNodes);
} }
} }
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider) void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes,
{ Component::Collider& collider) {
for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) {
{
aiMesh* mesh = scene->mMeshes[meshIndex]; aiMesh* mesh = scene->mMeshes[meshIndex];
if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE)) if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE))
continue; continue;
@@ -483,8 +435,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
// assume static mesh for now // assume static mesh for now
Array<Vector> positions(mesh->mNumVertices); Array<Vector> positions(mesh->mNumVertices);
StaticArray<Array<Vector2>, MAX_TEXCOORDS> texCoords; StaticArray<Array<Vector2>, MAX_TEXCOORDS> texCoords;
for (size_t i = 0; i < MAX_TEXCOORDS; ++i) for (size_t i = 0; i < MAX_TEXCOORDS; ++i) {
{
texCoords[i].resize(mesh->mNumVertices); texCoords[i].resize(mesh->mNumVertices);
} }
Array<Vector> normals(mesh->mNumVertices); Array<Vector> normals(mesh->mNumVertices);
@@ -493,45 +444,33 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
Array<Vector> colors(mesh->mNumVertices); Array<Vector> colors(mesh->mNumVertices);
StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance(); StaticMeshVertexData* vertexData = StaticMeshVertexData::getInstance();
for (int32 i = 0; i < mesh->mNumVertices; ++i) for (int32 i = 0; i < mesh->mNumVertices; ++i) {
{
positions[i] = Vector(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); positions[i] = Vector(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
for (size_t j = 0; j < MAX_TEXCOORDS; ++j) for (size_t j = 0; j < MAX_TEXCOORDS; ++j) {
{ if (mesh->HasTextureCoords(j)) {
if (mesh->HasTextureCoords(j))
{
texCoords[j][i] = Vector2(mesh->mTextureCoords[j][i].x, mesh->mTextureCoords[j][i].y); texCoords[j][i] = Vector2(mesh->mTextureCoords[j][i].x, mesh->mTextureCoords[j][i].y);
} } else {
else
{
texCoords[j][i] = Vector2(0, 0); texCoords[j][i] = Vector2(0, 0);
} }
} }
normals[i] = Vector(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); normals[i] = Vector(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
if (mesh->HasTangentsAndBitangents()) if (mesh->HasTangentsAndBitangents()) {
{
tangents[i] = Vector(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z); tangents[i] = Vector(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z);
biTangents[i] = Vector(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z); biTangents[i] = Vector(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z);
} } else {
else
{
tangents[i] = Vector(0, 0, 1); tangents[i] = Vector(0, 0, 1);
biTangents[i] = Vector(1, 0, 0); biTangents[i] = Vector(1, 0, 0);
} }
if (mesh->HasVertexColors(0)) if (mesh->HasVertexColors(0)) {
{
colors[i] = Vector(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b); colors[i] = Vector(mesh->mColors[0][i].r, mesh->mColors[0][i].g, mesh->mColors[0][i].b);
} } else {
else
{
colors[i] = Vector(1, 1, 1); colors[i] = Vector(1, 1, 1);
} }
} }
MeshId id = vertexData->allocateVertexData(mesh->mNumVertices); MeshId id = vertexData->allocateVertexData(mesh->mNumVertices);
vertexData->loadPositions(id, positions); vertexData->loadPositions(id, positions);
for (size_t i = 0; i < MAX_TEXCOORDS; ++i) for (size_t i = 0; i < MAX_TEXCOORDS; ++i) {
{
vertexData->loadTexCoords(id, i, texCoords[i]); vertexData->loadTexCoords(id, i, texCoords[i]);
} }
vertexData->loadNormals(id, normals); vertexData->loadNormals(id, normals);
@@ -540,8 +479,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
vertexData->loadColors(id, colors); vertexData->loadColors(id, colors);
Array<uint32> indices(mesh->mNumFaces * 3); Array<uint32> indices(mesh->mNumFaces * 3);
for (int32 faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex) for (int32 faceIndex = 0; faceIndex < mesh->mNumFaces; ++faceIndex) {
{
indices[faceIndex * 3 + 0] = mesh->mFaces[faceIndex].mIndices[0]; indices[faceIndex * 3 + 0] = mesh->mFaces[faceIndex].mIndices[0];
indices[faceIndex * 3 + 1] = mesh->mFaces[faceIndex].mIndices[1]; indices[faceIndex * 3 + 1] = mesh->mFaces[faceIndex].mIndices[1];
indices[faceIndex * 3 + 2] = mesh->mFaces[faceIndex].mIndices[2]; indices[faceIndex * 3 + 2] = mesh->mFaces[faceIndex].mIndices[2];
@@ -552,7 +490,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
Meshlet::build(positions, indices, meshlets); Meshlet::build(positions, indices, meshlets);
vertexData->loadMesh(id, indices, meshlets); vertexData->loadMesh(id, indices, meshlets);
//collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f)); // collider.physicsMesh.addCollider(positions, indices, Matrix4(1.0f));
globalMeshes[meshIndex] = new Mesh(); globalMeshes[meshIndex] = new Mesh();
globalMeshes[meshIndex]->vertexData = vertexData; globalMeshes[meshIndex]->vertexData = vertexData;
@@ -564,42 +502,27 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
} }
} }
Matrix4 convertMatrix(aiMatrix4x4 matrix) {
Matrix4 convertMatrix(aiMatrix4x4 matrix) return Matrix4(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2, matrix.a3, matrix.b3, matrix.c3,
{ matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4);
return Matrix4(
matrix.a1, matrix.b1, matrix.c1, matrix.d1,
matrix.a2, matrix.b2, matrix.c2, matrix.d2,
matrix.a3, matrix.b3, matrix.c3, matrix.d3,
matrix.a4, matrix.b4, matrix.c4, matrix.d4
);
} }
aiMatrix4x4 loadNodeTransform(aiNode* node) aiMatrix4x4 loadNodeTransform(aiNode* node) {
{
aiMatrix4x4 parent = aiMatrix4x4(); aiMatrix4x4 parent = aiMatrix4x4();
if (node->mParent != nullptr) if (node->mParent != nullptr) {
{
parent = loadNodeTransform(node->mParent); parent = loadNodeTransform(node->mParent);
} }
return node->mTransformation * parent; return node->mTransformation * parent;
} }
void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset) {
{
std::cout << "Starting to import " << args.filePath << std::endl; std::cout << "Starting to import " << args.filePath << std::endl;
meshAsset->setStatus(Asset::Status::Loading); meshAsset->setStatus(Asset::Status::Loading);
Assimp::Importer importer; Assimp::Importer importer;
importer.ReadFile(args.filePath.string().c_str(), (uint32)( importer.ReadFile(args.filePath.string().c_str(),
aiProcess_JoinIdenticalVertices | (uint32)(aiProcess_JoinIdenticalVertices | aiProcess_FlipUVs | aiProcess_Triangulate | aiProcess_SortByPType |
aiProcess_FlipUVs | aiProcess_GenBoundingBoxes | aiProcess_GenSmoothNormals | aiProcess_ImproveCacheLocality |
aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_FindDegenerates));
aiProcess_SortByPType |
aiProcess_GenBoundingBoxes |
aiProcess_GenSmoothNormals |
aiProcess_ImproveCacheLocality |
aiProcess_GenUVCoords |
aiProcess_FindDegenerates));
const aiScene* scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace); const aiScene* scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
std::cout << importer.GetErrorString() << std::endl; std::cout << importer.GetErrorString() << std::endl;
@@ -616,12 +539,9 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset)
findMeshRoots(scene->mRootNode, meshNodes); findMeshRoots(scene->mRootNode, meshNodes);
Array<OMesh> meshes; 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) if (globalMeshes[meshNode->mMeshes[i]] == nullptr) {
{
if (globalMeshes[meshNode->mMeshes[i]] == nullptr)
{
continue; continue;
} }
meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]])); meshes.add(std::move(globalMeshes[meshNode->mMeshes[i]]));
@@ -631,7 +551,8 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset)
meshAsset->meshes = std::move(meshes); meshAsset->meshes = std::move(meshes);
meshAsset->physicsMesh = std::move(collider); meshAsset->physicsMesh = std::move(collider);
auto stream = AssetRegistry::createWriteStream((std::filesystem::path(meshAsset->getFolderPath()) / meshAsset->getName()).replace_extension("asset").string(), std::ios::binary); auto stream = AssetRegistry::createWriteStream(
(std::filesystem::path(meshAsset->getFolderPath()) / meshAsset->getName()).replace_extension("asset").string(), std::ios::binary);
ArchiveBuffer archive; ArchiveBuffer archive;
Serialization::save(archive, MeshAsset::IDENTIFIER); Serialization::save(archive, MeshAsset::IDENTIFIER);
+16 -13
View File
@@ -1,35 +1,38 @@
#pragma once #pragma once
#include "MinimalEngine.h" #include "Component/Collider.h"
#include "Containers/List.h" #include "Containers/List.h"
#include "Containers/Map.h" #include "Containers/Map.h"
#include "Component/Collider.h" #include "MinimalEngine.h"
#include <filesystem> #include <filesystem>
struct aiScene; struct aiScene;
struct aiTexel; struct aiTexel;
struct aiNode; struct aiNode;
namespace Seele namespace Seele {
{
DECLARE_REF(Mesh) DECLARE_REF(Mesh)
DECLARE_REF(MeshAsset) DECLARE_REF(MeshAsset)
DECLARE_REF(MaterialInstanceAsset) DECLARE_REF(MaterialInstanceAsset)
DECLARE_REF(TextureAsset) DECLARE_REF(TextureAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
struct MeshImportArgs struct MeshImportArgs {
{
std::filesystem::path filePath; std::filesystem::path filePath;
std::string importPath; std::string importPath;
}; };
class MeshLoader class MeshLoader {
{ public:
public:
MeshLoader(Gfx::PGraphics graphic); MeshLoader(Gfx::PGraphics graphic);
~MeshLoader(); ~MeshLoader();
void importAsset(MeshImportArgs args); void importAsset(MeshImportArgs args);
private:
void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PTextureAsset>& textures); private:
void loadMaterials(const aiScene* scene, const Array<PTextureAsset>& textures, const std::string& baseName, const std::filesystem::path& meshDirectory, const std::string& importPath, Array<PMaterialInstanceAsset>& globalMaterials); void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath,
void loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider); Array<PTextureAsset>& textures);
void loadMaterials(const aiScene* scene, const Array<PTextureAsset>& textures, const std::string& baseName,
const std::filesystem::path& meshDirectory, const std::string& importPath,
Array<PMaterialInstanceAsset>& globalMaterials);
void loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& 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);
+68 -71
View File
@@ -1,8 +1,9 @@
#include "TextureLoader.h" #include "TextureLoader.h"
#include "Asset/AssetRegistry.h"
#include "Asset/TextureAsset.h" #include "Asset/TextureAsset.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h"
#include "Graphics/Vulkan/Enums.h" #include "Graphics/Vulkan/Enums.h"
#pragma GCC diagnostic push #pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable" #pragma GCC diagnostic ignored "-Wunused-but-set-variable"
@@ -17,24 +18,21 @@
using namespace Seele; using namespace Seele;
TextureLoader::TextureLoader(Gfx::PGraphics graphics) TextureLoader::TextureLoader(Gfx::PGraphics graphics) : graphics(graphics) {
: graphics(graphics)
{
OTextureAsset placeholder = new TextureAsset(); OTextureAsset placeholder = new TextureAsset();
placeholderAsset = placeholder; placeholderAsset = placeholder;
import(TextureImportArgs{ import(
.filePath = std::filesystem::absolute("textures/placeholder.png"), TextureImportArgs{
.importPath = "", .filePath = std::filesystem::absolute("textures/placeholder.png"),
}, placeholderAsset); .importPath = "",
},
placeholderAsset);
AssetRegistry::get().assetRoot->textures[""] = std::move(placeholder); AssetRegistry::get().assetRoot->textures[""] = std::move(placeholder);
} }
TextureLoader::~TextureLoader() TextureLoader::~TextureLoader() {}
{
}
void TextureLoader::importAsset(TextureImportArgs args) void TextureLoader::importAsset(TextureImportArgs args) {
{
std::string str = args.filePath.filename().string(); std::string str = args.filePath.filename().string();
auto pos = str.rfind("."); auto pos = str.rfind(".");
str.replace(str.begin() + pos, str.end(), ""); str.replace(str.begin() + pos, str.end(), "");
@@ -46,25 +44,26 @@ void TextureLoader::importAsset(TextureImportArgs args)
import(args, ref); import(args, ref);
} }
PTextureAsset TextureLoader::getPlaceholderTexture() PTextureAsset TextureLoader::getPlaceholderTexture() { return placeholderAsset; }
{
return placeholderAsset;
}
#define KTX_ASSERT(x) { auto error = x; if(error != KTX_SUCCESS) { std::cout << ktxErrorString(error) << std::endl; abort(); } } #define KTX_ASSERT(x) \
{ \
auto error = x; \
if (error != KTX_SUCCESS) { \
std::cout << ktxErrorString(error) << std::endl; \
abort(); \
} \
}
void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset) {
{
// manually transcode ktx textures using toktx // manually transcode ktx textures using toktx
if (args.filePath.extension().compare("ktx") != 0) if (args.filePath.extension().compare("ktx") != 0) {
{
auto ktxFile = args.filePath; auto ktxFile = args.filePath;
ktxFile.replace_extension("ktx"); ktxFile.replace_extension("ktx");
std::stringstream ss; std::stringstream ss;
ss << "toktx --encode etc1s "; ss << "toktx --encode etc1s ";
if (args.type == TextureImportType::TEXTURE_NORMAL) if (args.type == TextureImportType::TEXTURE_NORMAL) {
{ // ss << "--normal_mode ";
//ss << "--normal_mode ";
} }
ss << ktxFile << " " << args.filePath; ss << ktxFile << " " << args.filePath;
system(ss.str().c_str()); system(ss.str().c_str());
@@ -72,31 +71,30 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
} }
ktxTexture2* ktxHandle; ktxTexture2* ktxHandle;
KTX_ASSERT(ktxTexture_CreateFromNamedFile(args.filePath.string().c_str(), 0, (ktxTexture**) & ktxHandle)); KTX_ASSERT(ktxTexture_CreateFromNamedFile(args.filePath.string().c_str(), 0, (ktxTexture**)&ktxHandle));
// int totalWidth = 0, totalHeight = 0, n = 0;
//int totalWidth = 0, totalHeight = 0, n = 0; // unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4);
//unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4); // ktxTexture2* kTexture = nullptr;
//ktxTexture2* kTexture = nullptr; // VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
//VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; // ktxTextureCreateInfo createInfo = {
//ktxTextureCreateInfo createInfo = { // .vkFormat = (uint32)format,
// .vkFormat = (uint32)format, // .baseDepth = 1,
// .baseDepth = 1, // .numLevels = 1,
// .numLevels = 1, // .numLayers = 1,
// .numLayers = 1, // .isArray = false,
// .isArray = false, // .generateMipmaps = false,
// .generateMipmaps = false, // };
//};
// //
//if (args.type == TextureImportType::TEXTURE_CUBEMAP) // if (args.type == TextureImportType::TEXTURE_CUBEMAP)
//{ //{
// uint32 faceWidth = totalWidth / 4; // uint32 faceWidth = totalWidth / 4;
// // uint32 faceHeight = totalHeight / 3; // // uint32 faceHeight = totalHeight / 3;
// // Cube map // // Cube map
// createInfo.baseWidth = totalWidth / 4; // createInfo.baseWidth = totalWidth / 4;
// createInfo.baseHeight = totalHeight / 3; // createInfo.baseHeight = totalHeight / 3;
// createInfo.numFaces = 6; // createInfo.numFaces = 6;
// createInfo.numDimensions = 2; // createInfo.numDimensions = 2;
// KTX_ASSERT(ktxTexture2_Create(&createInfo, // KTX_ASSERT(ktxTexture2_Create(&createInfo,
// KTX_TEXTURE_CREATE_ALLOC_STORAGE, // KTX_TEXTURE_CREATE_ALLOC_STORAGE,
@@ -124,7 +122,7 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// loadCubeFace(1, 1, 4); // +Z // loadCubeFace(1, 1, 4); // +Z
// loadCubeFace(3, 1, 5); // -Z // loadCubeFace(3, 1, 5); // -Z
//} //}
//else // else
//{ //{
// createInfo.baseWidth = totalWidth; // createInfo.baseWidth = totalWidth;
// createInfo.baseHeight = totalHeight; // createInfo.baseHeight = totalHeight;
@@ -138,34 +136,33 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// ktxTexture_SetImageFromMemory(ktxTexture(kTexture), // ktxTexture_SetImageFromMemory(ktxTexture(kTexture),
// 0, 0, 0, data, totalWidth * totalHeight * n * sizeof(unsigned char)); // 0, 0, 0, data, totalWidth * totalHeight * n * sizeof(unsigned char));
//} //}
//ktxTexture_WriteToNamedFile(ktxTexture(kTexture), args.filePath.replace_extension(".ktx").string().c_str()); // ktxTexture_WriteToNamedFile(ktxTexture(kTexture), args.filePath.replace_extension(".ktx").string().c_str());
//ktxBasisParams basisParams = { // ktxBasisParams basisParams = {
// .structSize = sizeof(ktxBasisParams), // .structSize = sizeof(ktxBasisParams),
// .uastc = true, // .uastc = true,
// .threadCount = std::thread::hardware_concurrency(), // .threadCount = std::thread::hardware_concurrency(),
// .normalMap = normalMap, // .normalMap = normalMap,
// .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW,
// .uastcRDO = true, // .uastcRDO = true,
// .uastcRDOQualityScalar = 1, // .uastcRDOQualityScalar = 1,
//}; // };
//KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams)); // KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams));
//KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3)); // KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3));
//char writer[100]; // char writer[100];
//snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1"); // snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1");
//ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, // ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY,
// (ktx_uint32_t)strlen(writer) + 1, // (ktx_uint32_t)strlen(writer) + 1,
// writer); // writer);
//uint8* texData; // uint8* texData;
//size_t texSize; // size_t texSize;
//KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize)); // KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize));
// //
//stbi_image_free(data); // stbi_image_free(data);
if (textureAsset->getName().empty()) if (textureAsset->getName().empty()) {
{
return; return;
} }
+9 -11
View File
@@ -1,36 +1,34 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Containers/List.h" #include "Containers/List.h"
#include "Graphics/Enums.h" #include "Graphics/Enums.h"
#include "MinimalEngine.h"
#include <filesystem> #include <filesystem>
namespace Seele
{ namespace Seele {
DECLARE_REF(TextureAsset) DECLARE_REF(TextureAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
DECLARE_NAME_REF(Gfx, Texture2D) DECLARE_NAME_REF(Gfx, Texture2D)
enum class TextureImportType enum class TextureImportType {
{
TEXTURE_2D, TEXTURE_2D,
TEXTURE_NORMAL, TEXTURE_NORMAL,
TEXTURE_CUBEMAP, TEXTURE_CUBEMAP,
}; };
struct TextureImportArgs struct TextureImportArgs {
{
std::filesystem::path filePath; std::filesystem::path filePath;
std::string importPath; std::string importPath;
TextureImportType type = TextureImportType::TEXTURE_2D; TextureImportType type = TextureImportType::TEXTURE_2D;
Gfx::SeImageUsageFlagBits usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT; Gfx::SeImageUsageFlagBits usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
uint32 numChannels = 4; uint32 numChannels = 4;
}; };
class TextureLoader class TextureLoader {
{ public:
public:
TextureLoader(Gfx::PGraphics graphic); TextureLoader(Gfx::PGraphics graphic);
~TextureLoader(); ~TextureLoader();
void importAsset(TextureImportArgs args); void importAsset(TextureImportArgs args);
PTextureAsset getPlaceholderTexture(); PTextureAsset getPlaceholderTexture();
private:
private:
void import(TextureImportArgs args, PTextureAsset asset); void import(TextureImportArgs args, PTextureAsset asset);
Gfx::PGraphics graphics; Gfx::PGraphics graphics;
PTextureAsset placeholderAsset; PTextureAsset placeholderAsset;
+24 -49
View File
@@ -1,74 +1,49 @@
#include "InspectorView.h" #include "InspectorView.h"
#include "Graphics/Graphics.h"
#include "Actor/Actor.h" #include "Actor/Actor.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Asset/FontLoader.h" #include "Asset/FontLoader.h"
#include "Graphics/Graphics.h"
#include "UI/System.h" #include "UI/System.h"
#include "Window/Window.h" #include "Window/Window.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Editor; 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);
} }
InspectorView::~InspectorView() InspectorView::~InspectorView() {}
{
void InspectorView::beginUpdate() {
// co_return;
} }
void InspectorView::beginUpdate() void InspectorView::update() {
{ // co_return;
//co_return;
} }
void InspectorView::update() void InspectorView::commitUpdate() {}
{
//co_return;
}
void InspectorView::commitUpdate() void InspectorView::prepareRender() {}
{
}
void InspectorView::prepareRender() void InspectorView::render() {}
{
} void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) {}
void InspectorView::render() void InspectorView::mouseMoveCallback(double, double) {}
{
}
void InspectorView::keyCallback(KeyCode, InputAction, KeyModifier) void InspectorView::mouseButtonCallback(MouseButton, InputAction, KeyModifier) {}
{
} void InspectorView::scrollCallback(double, double) {}
void InspectorView::mouseMoveCallback(double, double) void InspectorView::fileCallback(int, const char**) {}
{
}
void InspectorView::mouseButtonCallback(MouseButton, InputAction, KeyModifier)
{
}
void InspectorView::scrollCallback(double, double)
{
}
void InspectorView::fileCallback(int, const char**)
{
}
+16 -18
View File
@@ -1,38 +1,36 @@
#pragma once #pragma once
#include "Window/View.h"
#include "Graphics/RenderPass/RenderGraph.h" #include "Graphics/RenderPass/RenderGraph.h"
#include "Graphics/RenderPass/UIPass.h"
#include "Graphics/RenderPass/TextPass.h" #include "Graphics/RenderPass/TextPass.h"
#include "Graphics/RenderPass/UIPass.h"
#include "UI/Elements/Panel.h" #include "UI/Elements/Panel.h"
#include "Window/View.h"
namespace Seele
{ namespace Seele {
DECLARE_REF(Actor) DECLARE_REF(Actor)
namespace Editor namespace Editor {
{ class InspectorView : public View {
class InspectorView : public View public:
{ InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo);
public:
InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo);
virtual ~InspectorView(); virtual ~InspectorView();
virtual void beginUpdate() override; virtual void beginUpdate() override;
virtual void update() override; virtual void update() override;
virtual void commitUpdate() override; virtual void commitUpdate() override;
virtual void prepareRender() override; virtual void prepareRender() override;
virtual void render() override; virtual void render() override;
void selectActor(); void selectActor();
protected:
protected:
UI::PSystem uiSystem; UI::PSystem uiSystem;
PActor selectedActor; PActor selectedActor;
virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override;
virtual void mouseMoveCallback(double xPos, double yPos) override; virtual void mouseMoveCallback(double xPos, double yPos) override;
virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override;
virtual void scrollCallback(double xOffset, double yOffset) override; virtual void scrollCallback(double xOffset, double yOffset) override;
virtual void fileCallback(int count, const char** paths) override; virtual void fileCallback(int count, const char** paths) override;
}; };
DEFINE_REF(InspectorView) DEFINE_REF(InspectorView)
} // namespace Editor } // namespace Editor
+7 -26
View File
@@ -5,35 +5,16 @@ using namespace Seele;
using namespace Seele::Editor; using namespace Seele::Editor;
PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath) PlayView::PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath)
: GameView(graphics, window, createInfo, dllPath) : GameView(graphics, window, createInfo, dllPath) {}
{
}
PlayView::~PlayView() PlayView::~PlayView() {}
{
}
void PlayView::beginUpdate() void PlayView::beginUpdate() { GameView::beginUpdate(); }
{
GameView::beginUpdate();
}
void PlayView::update() void PlayView::update() { GameView::update(); }
{
GameView::update();
}
void PlayView::commitUpdate() void PlayView::commitUpdate() { GameView::commitUpdate(); }
{
GameView::commitUpdate();
}
void PlayView::prepareRender() void PlayView::prepareRender() { GameView::prepareRender(); }
{
GameView::prepareRender();
}
void PlayView::render() void PlayView::render() { GameView::render(); }
{
GameView::render();
}
+11 -13
View File
@@ -1,22 +1,20 @@
#pragma once #pragma once
#include "Window/GameView.h" #include "Window/GameView.h"
namespace Seele namespace Seele {
{ namespace Editor {
namespace Editor class PlayView : public GameView {
{ public:
class PlayView : public GameView
{
public:
PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath); PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath);
virtual ~PlayView(); virtual ~PlayView();
virtual void beginUpdate() override; virtual void beginUpdate() override;
virtual void update() override; virtual void update() override;
virtual void commitUpdate() override; virtual void commitUpdate() override;
virtual void prepareRender() override; virtual void prepareRender() override;
virtual void render() override; virtual void render() override;
private:
private:
}; };
DECLARE_REF(PlayView) DECLARE_REF(PlayView)
} // namespace Editor } // namespace Editor
+23 -48
View File
@@ -1,22 +1,20 @@
#include "SceneView.h" #include "SceneView.h"
#include "Scene/Scene.h"
#include "Window/Window.h"
#include "Graphics/Mesh.h"
#include "Graphics/Graphics.h"
#include "Asset/MeshAsset.h"
#include "Asset/AssetRegistry.h"
#include "Actor/CameraActor.h" #include "Actor/CameraActor.h"
#include "Asset/AssetRegistry.h"
#include "Asset/MeshAsset.h"
#include "Component/Camera.h" #include "Component/Camera.h"
#include "Component/Mesh.h" #include "Component/Mesh.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
#include "Scene/Scene.h"
#include "Window/Window.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Editor; using namespace Seele::Editor;
SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo) SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo)
: View(graphics, owner, createInfo, "SceneView") : View(graphics, owner, createInfo, "SceneView"), scene(new Scene(graphics)), cameraSystem(createInfo.dimensions, Vector(0, 0, 10)) {
, scene(new Scene(graphics))
, cameraSystem(createInfo.dimensions, Vector(0, 0, 10))
{
cameraSystem.update(viewportCamera, static_cast<float>(Gfx::getCurrentFrameDelta())); cameraSystem.update(viewportCamera, static_cast<float>(Gfx::getCurrentFrameDelta()));
renderGraph.addPass(new DepthPrepass(graphics, scene)); renderGraph.addPass(new DepthPrepass(graphics, scene));
renderGraph.addPass(new LightCullingPass(graphics, scene)); renderGraph.addPass(new LightCullingPass(graphics, scene));
@@ -25,54 +23,31 @@ SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreat
renderGraph.createRenderPass(); renderGraph.createRenderPass();
} }
SceneView::~SceneView() SceneView::~SceneView() {}
{
void SceneView::beginUpdate() {
// co_return;
} }
void SceneView::beginUpdate() void SceneView::update() {
{
//co_return;
}
void SceneView::update()
{
cameraSystem.update(viewportCamera, static_cast<float>(Gfx::getCurrentFrameDelta())); cameraSystem.update(viewportCamera, static_cast<float>(Gfx::getCurrentFrameDelta()));
//co_return; // co_return;
} }
void SceneView::commitUpdate() void SceneView::commitUpdate() {}
{
}
void SceneView::prepareRender() void SceneView::prepareRender() {}
{
}
void SceneView::render() void SceneView::render() { renderGraph.render(viewportCamera); }
{
renderGraph.render(viewportCamera);
}
void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) { cameraSystem.keyCallback(code, action); }
{
cameraSystem.keyCallback(code, action);
}
void SceneView::mouseMoveCallback(double xPos, double yPos) void SceneView::mouseMoveCallback(double xPos, double yPos) { cameraSystem.mouseMoveCallback(xPos, yPos); }
{
cameraSystem.mouseMoveCallback(xPos, yPos);
}
void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) void SceneView::mouseButtonCallback(MouseButton button, InputAction action, KeyModifier) {
{
cameraSystem.mouseButtonCallback(button, action); cameraSystem.mouseButtonCallback(button, action);
} }
void SceneView::scrollCallback(double, double) void SceneView::scrollCallback(double, double) {}
{
}
void SceneView::fileCallback(int, const char**) void SceneView::fileCallback(int, const char**) {}
{
}
+27 -28
View File
@@ -1,43 +1,42 @@
#pragma once #pragma once
#include "ThreadPool.h" #include "Graphics/RenderPass/BasePass.h"
#include "Window/View.h"
#include "Graphics/RenderPass/DepthPrepass.h" #include "Graphics/RenderPass/DepthPrepass.h"
#include "Graphics/RenderPass/LightCullingPass.h" #include "Graphics/RenderPass/LightCullingPass.h"
#include "Graphics/RenderPass/BasePass.h" #include "ThreadPool.h"
#include "ViewportControl.h" #include "ViewportControl.h"
#include "Window/View.h"
namespace Seele
{ namespace Seele {
DECLARE_REF(Scene) DECLARE_REF(Scene)
namespace Editor namespace Editor {
{ class SceneView : public View {
class SceneView : public View public:
{ SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo);
public: ~SceneView();
SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo);
~SceneView();
virtual void beginUpdate() override; virtual void beginUpdate() override;
virtual void update() override; virtual void update() override;
virtual void commitUpdate() override; virtual void commitUpdate() override;
virtual void prepareRender() override; virtual void prepareRender() override;
virtual void render() override; virtual void render() override;
PScene getScene() const { return scene; } PScene getScene() const { return scene; }
private:
OScene scene;
Component::Camera viewportCamera;
RenderGraph renderGraph; private:
OScene scene;
Component::Camera viewportCamera;
ViewportControl cameraSystem; RenderGraph renderGraph;
virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override; ViewportControl cameraSystem;
virtual void mouseMoveCallback(double xPos, double yPos) override;
virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override; virtual void keyCallback(KeyCode code, InputAction action, KeyModifier modifier) override;
virtual void scrollCallback(double xOffset, double yOffset) override; virtual void mouseMoveCallback(double xPos, double yPos) override;
virtual void fileCallback(int count, const char** paths) override; virtual void mouseButtonCallback(MouseButton button, InputAction action, KeyModifier modifier) override;
virtual void scrollCallback(double xOffset, double yOffset) override;
virtual void fileCallback(int count, const char** paths) override;
}; };
DEFINE_REF(SceneView) DEFINE_REF(SceneView)
} // namespace Editor } // namespace Editor
+17 -42
View File
@@ -6,81 +6,56 @@ using namespace Seele;
using namespace Seele::Editor; using namespace Seele::Editor;
ViewportControl::ViewportControl(const URect& viewportDimensions, Vector initialPos) ViewportControl::ViewportControl(const URect& viewportDimensions, Vector initialPos)
: position(initialPos) : position(initialPos), fieldOfView(glm::radians(70.f)),
, fieldOfView(glm::radians(70.f)) aspectRatio(static_cast<float>(viewportDimensions.size.x) / viewportDimensions.size.y), pitch(0), yaw(glm::pi<float>() / -2.0f) {
, aspectRatio(static_cast<float>(viewportDimensions.size.x) / viewportDimensions.size.y)
, pitch(0)
, yaw(glm::pi<float>()/-2.0f)
{
std::cout << yaw << " " << pitch << std::endl; std::cout << yaw << " " << pitch << std::endl;
} }
ViewportControl::~ViewportControl() ViewportControl::~ViewportControl() {}
{
} void ViewportControl::update(Component::Camera& camera, float deltaTime) {
void ViewportControl::update(Component::Camera& camera, float deltaTime)
{
float cameraMove = deltaTime * 20; float cameraMove = deltaTime * 20;
if(keys[KeyCode::KEY_LEFT_SHIFT]) if (keys[KeyCode::KEY_LEFT_SHIFT]) {
{
cameraMove *= 4; cameraMove *= 4;
} }
Vector moveVector = Vector(); Vector moveVector = Vector();
Vector forward = glm::normalize(springArm); Vector forward = glm::normalize(springArm);
Vector side = glm::cross(Vector(0, 1, 0), forward); Vector side = glm::cross(Vector(0, 1, 0), forward);
if(keys[KeyCode::KEY_W]) if (keys[KeyCode::KEY_W]) {
{
moveVector += forward * cameraMove; moveVector += forward * cameraMove;
} }
if(keys[KeyCode::KEY_S]) if (keys[KeyCode::KEY_S]) {
{
moveVector += forward * -cameraMove; moveVector += forward * -cameraMove;
} }
if(keys[KeyCode::KEY_A]) if (keys[KeyCode::KEY_A]) {
{
moveVector += side * cameraMove; moveVector += side * cameraMove;
} }
if(keys[KeyCode::KEY_D]) if (keys[KeyCode::KEY_D]) {
{
moveVector += side * -cameraMove; moveVector += side * -cameraMove;
} }
if(keys[KeyCode::KEY_E]) if (keys[KeyCode::KEY_E]) {
{
moveVector += glm::vec3(0, cameraMove, 0); moveVector += glm::vec3(0, cameraMove, 0);
} }
if(keys[KeyCode::KEY_Q]) if (keys[KeyCode::KEY_Q]) {
{
moveVector += glm::vec3(0, -cameraMove, 0); moveVector += glm::vec3(0, -cameraMove, 0);
} }
throw std::logic_error("Not implemented"); throw std::logic_error("Not implemented");
} }
void ViewportControl::keyCallback(KeyCode key, InputAction action) void ViewportControl::keyCallback(KeyCode key, InputAction action) { keys[static_cast<size_t>(key)] = action != InputAction::RELEASE; }
{
keys[static_cast<size_t>(key)] = action != InputAction::RELEASE;
}
void ViewportControl::mouseMoveCallback(double xPos, double yPos) void ViewportControl::mouseMoveCallback(double xPos, double yPos) {
{
mouseX = static_cast<float>(xPos); mouseX = static_cast<float>(xPos);
mouseY = static_cast<float>(yPos); mouseY = static_cast<float>(yPos);
} }
void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action) void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action) {
{ if (button == MouseButton::MOUSE_BUTTON_1) {
if(button == MouseButton::MOUSE_BUTTON_1)
{
mouse1 = action != InputAction::RELEASE; mouse1 = action != InputAction::RELEASE;
} }
if(button == MouseButton::MOUSE_BUTTON_2) if (button == MouseButton::MOUSE_BUTTON_2) {
{
mouse2 = action != InputAction::RELEASE; mouse2 = action != InputAction::RELEASE;
} }
} }
void ViewportControl::viewportResize(URect dimensions) void ViewportControl::viewportResize(URect dimensions) { aspectRatio = static_cast<float>(dimensions.size.x) / dimensions.size.y; }
{
aspectRatio = static_cast<float>(dimensions.size.x) / dimensions.size.y;
}
+30 -31
View File
@@ -1,37 +1,36 @@
#pragma once #pragma once
#include "MinimalEngine.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" #include "Containers/Array.h"
#include "Graphics/Enums.h"
#include "Math/Math.h"
#include "Math/Vector.h"
#include "MinimalEngine.h"
namespace Seele
{ namespace Seele {
namespace Editor namespace Editor {
{ class ViewportControl {
class ViewportControl public:
{ ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/);
public: ~ViewportControl();
ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/); void update(Component::Camera& camera, float deltaTime);
~ViewportControl(); void keyCallback(KeyCode key, InputAction action);
void update(Component::Camera& camera, float deltaTime); void mouseMoveCallback(double xPos, double yPos);
void keyCallback(KeyCode key, InputAction action); void mouseButtonCallback(MouseButton button, InputAction action);
void mouseMoveCallback(double xPos, double yPos); void viewportResize(URect dimensions);
void mouseButtonCallback(MouseButton button, InputAction action);
void viewportResize(URect dimensions); private:
private: Vector position;
Vector position; Vector springArm;
Vector springArm; float fieldOfView;
float fieldOfView; float aspectRatio;
float aspectRatio; StaticArray<bool, static_cast<size_t>(KeyCode::KEY_LAST)> keys;
StaticArray<bool, static_cast<size_t>(KeyCode::KEY_LAST)> keys; bool mouse1 = false;
bool mouse1 = false; bool mouse2 = false;
bool mouse2 = false; float mouseX;
float mouseX; float mouseY;
float mouseY; float pitch;
float pitch; float yaw;
float yaw; };
};
} // namespace Editor } // namespace Editor
} // namespace Seele } // namespace Seele
+71 -73
View File
@@ -25,88 +25,86 @@ static Gfx::OGraphics graphics;
int main() { int main() {
std::string gameName = "MeshShadingDemo"; std::string gameName = "MeshShadingDemo";
#ifdef WIN32 #ifdef WIN32
std::filesystem::path outputPath = "C:/Users/Dynamitos/MeshShadingDemoGame"; std::filesystem::path outputPath = "C:/Users/Dynamitos/MeshShadingDemoGame";
std::filesystem::path sourcePath = "C:/Users/Dynamitos/MeshShadingDemo"; std::filesystem::path sourcePath = "C:/Users/Dynamitos/MeshShadingDemo";
std::filesystem::path binaryPath = sourcePath / "bin" / "MeshShadingDemo.dll"; std::filesystem::path binaryPath = sourcePath / "bin" / "MeshShadingDemo.dll";
#elif __APPLE__ #elif __APPLE__
std::filesystem::path outputPath = "/Users/dynamitos/MeshShadingDemoGame"; std::filesystem::path outputPath = "/Users/dynamitos/MeshShadingDemoGame";
std::filesystem::path sourcePath = "/Users/dynamitos/MeshShadingDemo"; std::filesystem::path sourcePath = "/Users/dynamitos/MeshShadingDemo";
std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.dylib"; std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.dylib";
#else #else
std::filesystem::path outputPath = "/home/dynamitos/MeshShadingDemoGame"; std::filesystem::path outputPath = "/home/dynamitos/MeshShadingDemoGame";
std::filesystem::path sourcePath = "/home/dynamitos/MeshShadingDemo"; std::filesystem::path sourcePath = "/home/dynamitos/MeshShadingDemo";
std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.so"; std::filesystem::path binaryPath = sourcePath / "cmake" / "libMeshShadingDemo.so";
#endif #endif
std::filesystem::path cmakePath = outputPath / "cmake"; std::filesystem::path cmakePath = outputPath / "cmake";
#ifdef __APPLE__ #ifdef __APPLE__
graphics = new Metal::Graphics(); graphics = new Metal::Graphics();
#else #else
graphics = new Vulkan::Graphics(); graphics = new Vulkan::Graphics();
#endif #endif
GraphicsInitializer initializer; GraphicsInitializer initializer;
graphics->init(initializer); graphics->init(initializer);
StaticMeshVertexData* vd = StaticMeshVertexData::getInstance(); StaticMeshVertexData* vd = StaticMeshVertexData::getInstance();
vd->init(graphics); vd->init(graphics);
OWindowManager windowManager = new WindowManager(); OWindowManager windowManager = new WindowManager();
AssetRegistry::init(sourcePath / "Assets", graphics); AssetRegistry::init(sourcePath / "Assets", graphics);
AssetImporter::init(graphics); AssetImporter::init(graphics);
AssetImporter::importFont(FontImportArgs{ AssetImporter::importFont(FontImportArgs{
.filePath = "./fonts/Calibri.ttf", .filePath = "./fonts/Calibri.ttf",
}); });
AssetImporter::importMesh(MeshImportArgs{ AssetImporter::importMesh(MeshImportArgs{
.filePath = sourcePath / "import/models/cube.fbx", .filePath = sourcePath / "import/models/cube.fbx",
}); });
//AssetImporter::importMesh(MeshImportArgs{ // AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import/models/greek-temple/source/greek-temple.fbx", // .filePath = sourcePath / "import/models/greek-temple/source/greek-temple.fbx",
// .importPath = "temple" // .importPath = "temple"
// }); // });
AssetImporter::importMesh(MeshImportArgs{ AssetImporter::importMesh(MeshImportArgs{.filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx",
.filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx", .importPath = "Whitechapel"});
.importPath = "Whitechapel" // AssetImporter::importMesh(MeshImportArgs{
}); // .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj",
//AssetImporter::importMesh(MeshImportArgs{ // .importPath = "Nitriansky"
// .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj", // });
// .importPath = "Nitriansky" WindowCreateInfo mainWindowInfo;
// }); mainWindowInfo.title = "SeeleEngine";
WindowCreateInfo mainWindowInfo; mainWindowInfo.width = 1920;
mainWindowInfo.title = "SeeleEngine"; mainWindowInfo.height = 1080;
mainWindowInfo.width = 1920; mainWindowInfo.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB;
mainWindowInfo.height = 1080; auto window = windowManager->addWindow(graphics, mainWindowInfo);
mainWindowInfo.preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_SRGB; ViewportCreateInfo sceneViewInfo;
auto window = windowManager->addWindow(graphics, mainWindowInfo); sceneViewInfo.dimensions.size.x = 1920;
ViewportCreateInfo sceneViewInfo; sceneViewInfo.dimensions.size.y = 1080;
sceneViewInfo.dimensions.size.x = 1920; sceneViewInfo.dimensions.offset.x = 0;
sceneViewInfo.dimensions.size.y = 1080; sceneViewInfo.dimensions.offset.y = 0;
sceneViewInfo.dimensions.offset.x = 0; sceneViewInfo.numSamples = Gfx::SE_SAMPLE_COUNT_1_BIT;
sceneViewInfo.dimensions.offset.y = 0; OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath.generic_string());
sceneViewInfo.numSamples = Gfx::SE_SAMPLE_COUNT_1_BIT; sceneView->setFocused();
OGameView sceneView = new Editor::PlayView(graphics, window, sceneViewInfo, binaryPath.generic_string());
sceneView->setFocused();
while (windowManager->isActive()) { while (windowManager->isActive()) {
windowManager->render(); windowManager->render();
} }
vd->destroy(); vd->destroy();
// export game // export game
if (false) { if (false) {
std::filesystem::create_directories(outputPath); std::filesystem::create_directories(outputPath);
std::system(fmt::format("cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DGAME_TITLE=\"{}\" -DGAME_DESTINATION=\"{}\" " std::system(fmt::format("cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DGAME_TITLE=\"{}\" -DGAME_DESTINATION=\"{}\" "
"-DGAME_BINARY=\"{}\" -P ./cmake/ExportProject.cmake", "-DGAME_BINARY=\"{}\" -P ./cmake/ExportProject.cmake",
gameName, outputPath.generic_string(), binaryPath.generic_string()) gameName, outputPath.generic_string(), binaryPath.generic_string())
.c_str()); .c_str());
std::system(fmt::format("cmake -S {} -B {}", cmakePath.generic_string(), cmakePath.generic_string()).c_str()); std::system(fmt::format("cmake -S {} -B {}", cmakePath.generic_string(), cmakePath.generic_string()).c_str());
std::system(fmt::format("cmake --build {}", cmakePath.generic_string()).c_str()); std::system(fmt::format("cmake --build {}", cmakePath.generic_string()).c_str());
std::filesystem::copy(sourcePath / "Assets", outputPath / "Assets", std::filesystem::copy_options::recursive); std::filesystem::copy(sourcePath / "Assets", outputPath / "Assets", std::filesystem::copy_options::recursive);
std::filesystem::copy("shaders", outputPath / "shaders", std::filesystem::copy_options::recursive); std::filesystem::copy("shaders", outputPath / "shaders", std::filesystem::copy_options::recursive);
std::filesystem::copy("textures", outputPath / "textures", std::filesystem::copy_options::recursive); std::filesystem::copy("textures", outputPath / "textures", std::filesystem::copy_options::recursive);
#ifdef WIN32 #ifdef WIN32
std::filesystem::copy_file("assimp-vc143-mt.dll", outputPath / "assimp-vc143-mt.dll"); std::filesystem::copy_file("assimp-vc143-mt.dll", outputPath / "assimp-vc143-mt.dll");
std::filesystem::copy_file("slang.dll", outputPath / "slang.dll"); std::filesystem::copy_file("slang.dll", outputPath / "slang.dll");
std::filesystem::copy_file("slang-glslang.dll", outputPath / "slang-glslang.dll"); std::filesystem::copy_file("slang-glslang.dll", outputPath / "slang-glslang.dll");
std::filesystem::copy_file("slang-llvm.dll", outputPath / "slang-llvm.dll"); std::filesystem::copy_file("slang-llvm.dll", outputPath / "slang-llvm.dll");
#endif #endif
} }
return 0; return 0;
} }
+7 -22
View File
@@ -3,38 +3,23 @@
using namespace Seele; using namespace Seele;
Actor::Actor(PScene scene) Actor::Actor(PScene scene) : Entity(scene) { attachComponent<Component::Transform>(); }
: Entity(scene)
{
attachComponent<Component::Transform>();
}
Actor::~Actor() Actor::~Actor() {}
{
} void Actor::setParent(PActor newParent) {
if (parent != nullptr) {
void Actor::setParent(PActor newParent)
{
if(parent != nullptr)
{
parent->removeChild(this); parent->removeChild(this);
} }
parent = newParent; parent = newParent;
} }
void Actor::addChild(PActor child) void Actor::addChild(PActor child) {
{
children.add(child); children.add(child);
child->setParent(this); child->setParent(this);
} }
void Actor::removeChild(PActor child) void Actor::removeChild(PActor child) {
{
children.remove(children.find(child), false); children.remove(children.find(child), false);
child->setParent(nullptr); child->setParent(nullptr);
} }
Component::Transform& Actor::getTransform() Component::Transform& Actor::getTransform() { return accessComponent<Component::Transform>(); }
{
return accessComponent<Component::Transform>();
}
+7 -8
View File
@@ -1,15 +1,14 @@
#pragma once #pragma once
#include "Entity.h"
#include "Component/Transform.h" #include "Component/Transform.h"
#include "Entity.h"
namespace Seele
{ namespace Seele {
DECLARE_REF(Actor) DECLARE_REF(Actor)
// Actors are entities that are part of the scene hierarchy // Actors are entities that are part of the scene hierarchy
// In order for that hierarchy to make sense it requires at least a transform component // In order for that hierarchy to make sense it requires at least a transform component
class Actor : public Entity class Actor : public Entity {
{ public:
public:
Actor(PScene scene); Actor(PScene scene);
virtual ~Actor(); virtual ~Actor();
@@ -20,8 +19,8 @@ public:
Component::Transform& getTransform(); Component::Transform& getTransform();
protected: protected:
//Component::Transform& getTransform(); // Component::Transform& getTransform();
void setParent(PActor parent); void setParent(PActor parent);
PActor parent; PActor parent;
Array<PActor> children; Array<PActor> children;
+4 -14
View File
@@ -3,23 +3,13 @@
using namespace Seele; using namespace Seele;
CameraActor::CameraActor(PScene scene) CameraActor::CameraActor(PScene scene) : Actor(scene) {
: Actor(scene)
{
attachComponent<Component::Camera>(); attachComponent<Component::Camera>();
accessComponent<Component::Transform>().setPosition(Vector(10, 5, 14)); accessComponent<Component::Transform>().setPosition(Vector(10, 5, 14));
} }
CameraActor::~CameraActor() CameraActor::~CameraActor() {}
{
}
Component::Camera& CameraActor::getCameraComponent() Component::Camera& CameraActor::getCameraComponent() { return accessComponent<Component::Camera>(); }
{
return accessComponent<Component::Camera>();
}
const Component::Camera& CameraActor::getCameraComponent() const const Component::Camera& CameraActor::getCameraComponent() const { return accessComponent<Component::Camera>(); }
{
return accessComponent<Component::Camera>();
}
+5 -6
View File
@@ -2,16 +2,15 @@
#include "Actor.h" #include "Actor.h"
#include "Component/Camera.h" #include "Component/Camera.h"
namespace Seele namespace Seele {
{ class CameraActor : public Actor {
class CameraActor : public Actor public:
{
public:
CameraActor(PScene scene); CameraActor(PScene scene);
virtual ~CameraActor(); virtual ~CameraActor();
Component::Camera& getCameraComponent(); Component::Camera& getCameraComponent();
const Component::Camera& getCameraComponent() const; const Component::Camera& getCameraComponent() const;
private:
private:
}; };
DEFINE_REF(CameraActor) DEFINE_REF(CameraActor)
} // namespace Seele } // namespace Seele
+5 -16
View File
@@ -2,29 +2,18 @@
using namespace Seele; using namespace Seele;
DirectionalLightActor::DirectionalLightActor(PScene scene) DirectionalLightActor::DirectionalLightActor(PScene scene) : Actor(scene) { attachComponent<Component::DirectionalLight>(); }
: Actor(scene)
{
attachComponent<Component::DirectionalLight>();
}
DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction) DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction) : Actor(scene) {
: Actor(scene)
{
attachComponent<Component::DirectionalLight>(Vector4(color, 0), Vector4(direction, 0)); attachComponent<Component::DirectionalLight>(Vector4(color, 0), Vector4(direction, 0));
} }
DirectionalLightActor::~DirectionalLightActor() DirectionalLightActor::~DirectionalLightActor() {}
{
} Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() {
Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent()
{
return accessComponent<Component::DirectionalLight>(); return accessComponent<Component::DirectionalLight>();
} }
const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const {
{
return accessComponent<Component::DirectionalLight>(); return accessComponent<Component::DirectionalLight>();
} }
+5 -6
View File
@@ -2,17 +2,16 @@
#include "Actor.h" #include "Actor.h"
#include "Component/DirectionalLight.h" #include "Component/DirectionalLight.h"
namespace Seele namespace Seele {
{ class DirectionalLightActor : public Actor {
class DirectionalLightActor : public Actor public:
{
public:
DirectionalLightActor(PScene scene); DirectionalLightActor(PScene scene);
DirectionalLightActor(PScene scene, Vector color, Vector direction); DirectionalLightActor(PScene scene, Vector color, Vector direction);
virtual ~DirectionalLightActor(); virtual ~DirectionalLightActor();
Component::DirectionalLight& getDirectionalLightComponent(); Component::DirectionalLight& getDirectionalLightComponent();
const Component::DirectionalLight& getDirectionalLightComponent() const; const Component::DirectionalLight& getDirectionalLightComponent() const;
private:
private:
}; };
DEFINE_REF(DirectionalLightActor) DEFINE_REF(DirectionalLightActor)
} // namespace Seele } // namespace Seele
+2 -10
View File
@@ -2,14 +2,6 @@
using namespace Seele; using namespace Seele;
Entity::Entity(PScene scene) Entity::Entity(PScene scene) : scene(scene), identifier(scene->createEntity()) {}
: scene(scene)
, identifier(scene->createEntity())
{
}
Entity::~Entity() { scene->destroyEntity(identifier); }
Entity::~Entity()
{
scene->destroyEntity(identifier);
}
+10 -20
View File
@@ -1,33 +1,23 @@
#pragma once #pragma once
#include <entt/entt.hpp>
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Scene/Scene.h" #include "Scene/Scene.h"
namespace Seele #include <entt/entt.hpp>
{
namespace Seele {
// An entity describes a part of a scene // An entity describes a part of a scene
// It is just a wrapper the ID of a registry // It is just a wrapper the ID of a registry
class Entity class Entity {
{ public:
public:
Entity(PScene scene); Entity(PScene scene);
virtual ~Entity(); virtual ~Entity();
template<typename Component, typename... Args> template <typename Component, typename... Args> Component& attachComponent(Args&&... args) {
Component& attachComponent(Args&&... args)
{
return scene->attachComponent<Component>(identifier, std::forward<Args>(args)...); return scene->attachComponent<Component>(identifier, std::forward<Args>(args)...);
} }
template<typename Component> template <typename Component> Component& accessComponent() { return scene->accessComponent<Component>(identifier); }
Component& accessComponent() template <typename Component> const Component& accessComponent() const { return scene->accessComponent<Component>(identifier); }
{
return scene->accessComponent<Component>(identifier); protected:
}
template<typename Component>
const Component& accessComponent() const
{
return scene->accessComponent<Component>(identifier);
}
protected:
PScene scene; PScene scene;
entt::entity identifier; entt::entity identifier;
}; };
+5 -20
View File
@@ -2,29 +2,14 @@
using namespace Seele; using namespace Seele;
PointLightActor::PointLightActor(PScene scene) PointLightActor::PointLightActor(PScene scene) : Actor(scene) { attachComponent<Component::PointLight>(); }
: Actor(scene)
{
attachComponent<Component::PointLight>();
}
PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation) PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation) : Actor(scene) {
: Actor(scene)
{
attachComponent<Component::PointLight>(Vector4(position, 1), Vector4(color, attenuation)); attachComponent<Component::PointLight>(Vector4(position, 1), Vector4(color, attenuation));
} }
PointLightActor::~PointLightActor() PointLightActor::~PointLightActor() {}
{
} Component::PointLight& PointLightActor::getPointLightComponent() { return accessComponent<Component::PointLight>(); }
Component::PointLight& PointLightActor::getPointLightComponent() const Component::PointLight& PointLightActor::getPointLightComponent() const { return accessComponent<Component::PointLight>(); }
{
return accessComponent<Component::PointLight>();
}
const Component::PointLight& PointLightActor::getPointLightComponent() const
{
return accessComponent<Component::PointLight>();
}
+5 -6
View File
@@ -2,17 +2,16 @@
#include "Actor.h" #include "Actor.h"
#include "Component/PointLight.h" #include "Component/PointLight.h"
namespace Seele namespace Seele {
{ class PointLightActor : public Actor {
class PointLightActor : public Actor public:
{
public:
PointLightActor(PScene scene); PointLightActor(PScene scene);
PointLightActor(PScene scene, Vector position, Vector color, float attenuation); PointLightActor(PScene scene, Vector position, Vector color, float attenuation);
virtual ~PointLightActor(); virtual ~PointLightActor();
Component::PointLight& getPointLightComponent(); Component::PointLight& getPointLightComponent();
const Component::PointLight& getPointLightComponent() const; const Component::PointLight& getPointLightComponent() const;
private:
private:
}; };
DEFINE_REF(PointLightActor) DEFINE_REF(PointLightActor)
} // namespace Seele } // namespace Seele
+4 -16
View File
@@ -2,22 +2,10 @@
using namespace Seele; using namespace Seele;
StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh) StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh) : Actor(scene) { attachComponent<Component::Mesh>(mesh); }
: Actor(scene)
{
attachComponent<Component::Mesh>(mesh);
}
Seele::StaticMeshActor::~StaticMeshActor() Seele::StaticMeshActor::~StaticMeshActor() {}
{
}
Component::Mesh &Seele::StaticMeshActor::getMesh() Component::Mesh& Seele::StaticMeshActor::getMesh() { return accessComponent<Component::Mesh>(); }
{
return accessComponent<Component::Mesh>();
}
const Component::Mesh &Seele::StaticMeshActor::getMesh() const const Component::Mesh& Seele::StaticMeshActor::getMesh() const { return accessComponent<Component::Mesh>(); }
{
return accessComponent<Component::Mesh>();
}
+5 -6
View File
@@ -2,16 +2,15 @@
#include "Actor.h" #include "Actor.h"
#include "Component/Mesh.h" #include "Component/Mesh.h"
namespace Seele namespace Seele {
{ class StaticMeshActor : public Actor {
class StaticMeshActor : public Actor public:
{
public:
StaticMeshActor(PScene scene, PMeshAsset mesh); StaticMeshActor(PScene scene, PMeshAsset mesh);
virtual ~StaticMeshActor(); virtual ~StaticMeshActor();
Component::Mesh& getMesh(); Component::Mesh& getMesh();
const Component::Mesh& getMesh() const; const Component::Mesh& getMesh() const;
private:
private:
}; };
DEFINE_REF(StaticMeshActor) DEFINE_REF(StaticMeshActor)
} // namespace Seele } // namespace Seele
+8 -33
View File
@@ -4,44 +4,19 @@
using namespace Seele; using namespace Seele;
Asset::Asset() Asset::Asset() : folderPath(""), name(""), status(Status::Uninitialized), byteSize(0) {}
: folderPath("") Asset::Asset(std::string_view _folderPath, std::string_view _name) : folderPath(_folderPath), name(_name), status(Status::Uninitialized) {
, name("") if (folderPath.empty()) {
, status(Status::Uninitialized)
, byteSize(0)
{
}
Asset::Asset(std::string_view _folderPath, std::string_view _name)
: folderPath(_folderPath)
, name(_name)
, status(Status::Uninitialized)
{
if (folderPath.empty())
{
assetId = name; assetId = name;
} } else {
else
{
assetId = folderPath + "/" + name; assetId = folderPath + "/" + name;
} }
} }
Asset::~Asset() {}
Asset::~Asset() std::string Asset::getFolderPath() const { return folderPath; }
{
}
std::string Asset::getFolderPath() const std::string Asset::getName() const { return name; }
{
return folderPath;
}
std::string Asset::getName() const std::string Asset::getAssetIdentifier() const { return assetId; }
{
return name;
}
std::string Asset::getAssetIdentifier() const
{
return assetId;
}
+8 -20
View File
@@ -2,18 +2,11 @@
#include "MinimalEngine.h" #include "MinimalEngine.h"
#include "Serialization/ArchiveBuffer.h" #include "Serialization/ArchiveBuffer.h"
namespace Seele namespace Seele {
{
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
class Asset class Asset {
{ public:
public: enum class Status { Uninitialized, Loading, Ready };
enum class Status
{
Uninitialized,
Loading,
Ready
};
Asset(); Asset();
Asset(std::string_view folderPath, std::string_view name); Asset(std::string_view folderPath, std::string_view name);
virtual ~Asset(); virtual ~Asset();
@@ -31,15 +24,10 @@ public:
// returns the identifier with which it can be found from the asset registry // returns the identifier with which it can be found from the asset registry
std::string getAssetIdentifier() const; std::string getAssetIdentifier() const;
constexpr Status getStatus() constexpr Status getStatus() { return status; }
{ constexpr void setStatus(Status _status) { status = _status; }
return status;
} protected:
constexpr void setStatus(Status _status)
{
status = _status;
}
protected:
std::string folderPath; std::string folderPath;
std::string name; std::string name;
std::string assetId; std::string assetId;
+67 -149
View File
@@ -1,134 +1,96 @@
#include "AssetRegistry.h" #include "AssetRegistry.h"
#include "MeshAsset.h"
#include "FontAsset.h" #include "FontAsset.h"
#include "TextureAsset.h" #include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
#include "MaterialAsset.h" #include "MaterialAsset.h"
#include "MaterialInstanceAsset.h" #include "MaterialInstanceAsset.h"
#include "Graphics/Mesh.h"
#include "Graphics/Graphics.h"
#include "Window/WindowManager.h"
#include "MeshAsset.h" #include "MeshAsset.h"
#include <nlohmann/json.hpp> #include "TextureAsset.h"
#include <iostream> #include "Window/WindowManager.h"
#include <fstream> #include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using namespace Seele; using namespace Seele;
AssetRegistry* _instance = new AssetRegistry(); AssetRegistry* _instance = new AssetRegistry();
AssetRegistry::~AssetRegistry() AssetRegistry::~AssetRegistry() { delete assetRoot; }
{
delete assetRoot;
}
void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics graphics) void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics graphics) { get().initialize(rootFolder, graphics); }
{
get().initialize(rootFolder, graphics);
}
PMeshAsset AssetRegistry::findMesh(std::string_view folderPath, std::string_view filePath) PMeshAsset AssetRegistry::findMesh(std::string_view folderPath, std::string_view filePath) {
{
AssetFolder* folder = get().assetRoot; AssetFolder* folder = get().assetRoot;
if (!folderPath.empty()) if (!folderPath.empty()) {
{
folder = get().getOrCreateFolder(folderPath); folder = get().getOrCreateFolder(folderPath);
} }
return folder->meshes.at(std::string(filePath)); return folder->meshes.at(std::string(filePath));
} }
PTextureAsset AssetRegistry::findTexture(std::string_view folderPath, std::string_view filePath) PTextureAsset AssetRegistry::findTexture(std::string_view folderPath, std::string_view filePath) {
{
AssetFolder* folder = get().assetRoot; AssetFolder* folder = get().assetRoot;
if (!folderPath.empty()) if (!folderPath.empty()) {
{
folder = get().getOrCreateFolder(folderPath); folder = get().getOrCreateFolder(folderPath);
} }
return folder->textures.at(std::string(filePath)); return folder->textures.at(std::string(filePath));
} }
PFontAsset AssetRegistry::findFont(std::string_view folderPath, std::string_view filePath) PFontAsset AssetRegistry::findFont(std::string_view folderPath, std::string_view filePath) {
{
AssetFolder* folder = get().assetRoot; AssetFolder* folder = get().assetRoot;
if (!folderPath.empty()) if (!folderPath.empty()) {
{
folder = get().getOrCreateFolder(folderPath); folder = get().getOrCreateFolder(folderPath);
} }
return folder->fonts.at(std::string(filePath)); return folder->fonts.at(std::string(filePath));
} }
PMaterialAsset AssetRegistry::findMaterial(std::string_view folderPath, std::string_view filePath) PMaterialAsset AssetRegistry::findMaterial(std::string_view folderPath, std::string_view filePath) {
{
AssetFolder* folder = get().assetRoot; AssetFolder* folder = get().assetRoot;
if (!folderPath.empty()) if (!folderPath.empty()) {
{
folder = get().getOrCreateFolder(folderPath); folder = get().getOrCreateFolder(folderPath);
} }
return folder->materials.at(std::string(filePath)); return folder->materials.at(std::string(filePath));
} }
PMaterialInstanceAsset AssetRegistry::findMaterialInstance(std::string_view folderPath, std::string_view filePath) PMaterialInstanceAsset AssetRegistry::findMaterialInstance(std::string_view folderPath, std::string_view filePath) {
{
AssetFolder* folder = get().assetRoot; AssetFolder* folder = get().assetRoot;
if (!folderPath.empty()) if (!folderPath.empty()) {
{
folder = get().getOrCreateFolder(folderPath); folder = get().getOrCreateFolder(folderPath);
} }
return folder->instances.at(std::string(filePath)); return folder->instances.at(std::string(filePath));
} }
std::ofstream AssetRegistry::createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) std::ofstream AssetRegistry::createWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) {
{
return get().internalCreateWriteStream(relativePath, openmode); return get().internalCreateWriteStream(relativePath, openmode);
} }
std::ifstream AssetRegistry::createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) std::ifstream AssetRegistry::createReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) {
{
return get().internalCreateReadStream(relativePath, openmode); return get().internalCreateReadStream(relativePath, openmode);
} }
AssetRegistry &AssetRegistry::get() AssetRegistry& AssetRegistry::get() { return *_instance; }
{
return *_instance;
}
AssetRegistry::AssetRegistry() AssetRegistry::AssetRegistry() : assetRoot(nullptr) {}
: assetRoot(nullptr)
{
}
AssetRegistry* AssetRegistry::getInstance() AssetRegistry* AssetRegistry::getInstance() { return _instance; }
{
return _instance;
}
void AssetRegistry::loadRegistry() void AssetRegistry::loadRegistry() { get().loadRegistryInternal(); }
{
get().loadRegistryInternal();
}
void AssetRegistry::saveRegistry() void AssetRegistry::saveRegistry() { get().saveRegistryInternal(); }
{
get().saveRegistryInternal();
}
AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath) AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath) {
{
AssetFolder* result = assetRoot; AssetFolder* result = assetRoot;
std::string temp = std::string(fullPath); std::string temp = std::string(fullPath);
while (!temp.empty()) while (!temp.empty()) {
{
size_t slashLoc = temp.find("/"); size_t slashLoc = temp.find("/");
if (slashLoc == std::string::npos) if (slashLoc == std::string::npos) {
{ if (!result->children.contains(temp)) {
if (!result->children.contains(temp))
{
result->children[temp] = new AssetFolder(temp); result->children[temp] = new AssetFolder(temp);
} }
return result->children[temp]; return result->children[temp];
} }
std::string folderName = temp.substr(0, slashLoc); std::string folderName = temp.substr(0, slashLoc);
if (!result->children.contains(folderName)) if (!result->children.contains(folderName)) {
{
result->children[folderName] = new AssetFolder(fullPath); result->children[folderName] = new AssetFolder(fullPath);
} }
result = result->children[folderName]; result = result->children[folderName];
@@ -137,40 +99,31 @@ AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fu
return result; return result;
} }
void AssetRegistry::initialize(const std::filesystem::path &_rootFolder, Gfx::PGraphics _graphics) void AssetRegistry::initialize(const std::filesystem::path& _rootFolder, Gfx::PGraphics _graphics) {
{
this->graphics = _graphics; this->graphics = _graphics;
this->rootFolder = _rootFolder; this->rootFolder = _rootFolder;
this->assetRoot = new AssetFolder(""); this->assetRoot = new AssetFolder("");
loadRegistryInternal(); loadRegistryInternal();
} }
void AssetRegistry::loadRegistryInternal() void AssetRegistry::loadRegistryInternal() {
{
peekFolder(assetRoot); peekFolder(assetRoot);
loadFolder(assetRoot); loadFolder(assetRoot);
} }
void AssetRegistry::peekFolder(AssetFolder* folder) void AssetRegistry::peekFolder(AssetFolder* folder) {
{ for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) {
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath))
{
const auto& stem = entry.path().stem().string(); const auto& stem = entry.path().stem().string();
if (entry.is_directory()) if (entry.is_directory()) {
{ if (folder->folderPath.empty()) {
if (folder->folderPath.empty())
{
folder->children[stem] = new AssetFolder(stem); folder->children[stem] = new AssetFolder(stem);
} } else {
else
{
folder->children[stem] = new AssetFolder(folder->folderPath + "/" + stem); folder->children[stem] = new AssetFolder(folder->folderPath + "/" + stem);
} }
peekFolder(folder->children[stem]); peekFolder(folder->children[stem]);
continue; continue;
} }
if(entry.path().filename().compare(".DS_Store") == 0) if (entry.path().filename().compare(".DS_Store") == 0) {
{
continue; continue;
} }
auto stream = std::ifstream(entry.path(), std::ios::binary); auto stream = std::ifstream(entry.path(), std::ios::binary);
@@ -181,20 +134,16 @@ void AssetRegistry::peekFolder(AssetFolder* folder)
} }
} }
void AssetRegistry::loadFolder(AssetFolder* folder) void AssetRegistry::loadFolder(AssetFolder* folder) {
{ for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) {
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath))
{
const auto& path = entry.path(); const auto& path = entry.path();
if (entry.is_directory()) if (entry.is_directory()) {
{
auto relative = path.stem().string(); auto relative = path.stem().string();
loadFolder(folder->children[relative]); loadFolder(folder->children[relative]);
continue; continue;
} }
if(entry.path().filename().compare(".DS_Store") == 0) if (entry.path().filename().compare(".DS_Store") == 0) {
{
continue; continue;
} }
auto stream = std::ifstream(path, std::ios::binary); auto stream = std::ifstream(path, std::ios::binary);
@@ -205,8 +154,7 @@ void AssetRegistry::loadFolder(AssetFolder* folder)
} }
} }
void AssetRegistry::peekAsset(ArchiveBuffer& buffer) void AssetRegistry::peekAsset(ArchiveBuffer& buffer) {
{
// Read asset type // Read asset type
uint64 identifier; uint64 identifier;
Serialization::load(buffer, identifier); Serialization::load(buffer, identifier);
@@ -222,8 +170,7 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer)
AssetFolder* folder = getOrCreateFolder(folderPath); AssetFolder* folder = getOrCreateFolder(folderPath);
OAsset 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[name] = std::move(asset); folder->textures[name] = std::move(asset);
@@ -249,8 +196,7 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer)
} }
} }
void AssetRegistry::loadAsset(ArchiveBuffer& buffer) void AssetRegistry::loadAsset(ArchiveBuffer& buffer) {
{
// Read asset type // Read asset type
uint64 identifier; uint64 identifier;
Serialization::load(buffer, identifier); Serialization::load(buffer, identifier);
@@ -266,8 +212,7 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer)
AssetFolder* folder = getOrCreateFolder(folderPath); AssetFolder* folder = getOrCreateFolder(folderPath);
PAsset asset; PAsset asset;
switch (identifier) switch (identifier) {
{
case TextureAsset::IDENTIFIER: case TextureAsset::IDENTIFIER:
asset = PTextureAsset(folder->textures.at(name)); asset = PTextureAsset(folder->textures.at(name));
break; break;
@@ -289,42 +234,31 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer)
asset->load(buffer); asset->load(buffer);
} }
void AssetRegistry::saveRegistryInternal() void AssetRegistry::saveRegistryInternal() { saveFolder("", assetRoot); }
{
saveFolder("", assetRoot);
}
void AssetRegistry::saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder) void AssetRegistry::saveFolder(const std::filesystem::path& folderPath, AssetFolder* folder) {
{
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(PTextureAsset(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(PMeshAsset(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(PMaterialAsset(material), MaterialAsset::IDENTIFIER, folderPath, name); saveAsset(PMaterialAsset(material), MaterialAsset::IDENTIFIER, folderPath, name);
} }
for (const auto& [name, material] : folder->instances) for (const auto& [name, material] : folder->instances) {
{
saveAsset(PMaterialInstanceAsset(material), MaterialInstanceAsset::IDENTIFIER, folderPath, name); saveAsset(PMaterialInstanceAsset(material), MaterialInstanceAsset::IDENTIFIER, folderPath, name);
} }
for (const auto& [name, font] : folder->fonts) for (const auto& [name, font] : folder->fonts) {
{
saveAsset(PFontAsset(font), FontAsset::IDENTIFIER, folderPath, name); saveAsset(PFontAsset(font), FontAsset::IDENTIFIER, folderPath, name);
} }
for (auto& [name, child] : folder->children) for (auto& [name, child] : folder->children) {
{
saveFolder(folderPath / name, child); saveFolder(folderPath / name, child);
} }
} }
void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name) void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesystem::path& folderPath, std::string name) {
{
if (name.empty()) if (name.empty())
return; return;
@@ -342,65 +276,49 @@ void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesy
buffer.writeToStream(assetStream); buffer.writeToStream(assetStream);
} }
std::filesystem::path AssetRegistry::getRootFolder() std::filesystem::path AssetRegistry::getRootFolder() { return get().rootFolder; }
{
return get().rootFolder;
}
void AssetRegistry::registerMesh(OMeshAsset mesh) void AssetRegistry::registerMesh(OMeshAsset mesh) {
{
AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath()); AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath());
folder->meshes[mesh->getName()] = std::move(mesh); folder->meshes[mesh->getName()] = std::move(mesh);
} }
void AssetRegistry::registerTexture(OTextureAsset texture) void AssetRegistry::registerTexture(OTextureAsset texture) {
{
AssetFolder* folder = getOrCreateFolder(texture->getFolderPath()); AssetFolder* folder = getOrCreateFolder(texture->getFolderPath());
folder->textures[texture->getName()] = std::move(texture); folder->textures[texture->getName()] = std::move(texture);
} }
void AssetRegistry::registerFont(OFontAsset font) void AssetRegistry::registerFont(OFontAsset font) {
{
AssetFolder* folder = getOrCreateFolder(font->getFolderPath()); AssetFolder* folder = getOrCreateFolder(font->getFolderPath());
folder->fonts[font->getName()] = std::move(font); folder->fonts[font->getName()] = std::move(font);
} }
void AssetRegistry::registerMaterial(OMaterialAsset material) void AssetRegistry::registerMaterial(OMaterialAsset material) {
{
AssetFolder* folder = getOrCreateFolder(material->getFolderPath()); AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
folder->materials[material->getName()] = std::move(material); folder->materials[material->getName()] = std::move(material);
} }
void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material) void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material) {
{
AssetFolder* folder = getOrCreateFolder(material->getFolderPath()); AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
folder->instances[material->getName()] = std::move(material); folder->instances[material->getName()] = std::move(material);
} }
std::ofstream AssetRegistry::internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) {
std::ofstream AssetRegistry::internalCreateWriteStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode)
{
auto fullPath = rootFolder / relativePath; auto fullPath = rootFolder / relativePath;
std::filesystem::create_directories(fullPath.parent_path()); std::filesystem::create_directories(fullPath.parent_path());
return std::ofstream(fullPath.string(), openmode); return std::ofstream(fullPath.string(), openmode);
} }
std::ifstream AssetRegistry::internalCreateReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) std::ifstream AssetRegistry::internalCreateReadStream(const std::filesystem::path& relativePath, std::ios_base::openmode openmode) {
{
auto fullPath = rootFolder / relativePath; auto fullPath = rootFolder / relativePath;
std::filesystem::create_directories(fullPath.parent_path()); std::filesystem::create_directories(fullPath.parent_path());
return std::ifstream(fullPath.string(), openmode); return std::ifstream(fullPath.string(), openmode);
} }
AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath) AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath) : folderPath(folderPath) {}
: folderPath(folderPath)
{}
AssetRegistry::AssetFolder::~AssetFolder() AssetRegistry::AssetFolder::~AssetFolder() {
{ for (auto [_, child] : children) {
for (auto [_, child] : children)
{
delete child; delete child;
} }
} }
+10 -11
View File
@@ -1,21 +1,20 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Asset.h" #include "Asset.h"
#include "Containers/Map.h" #include "Containers/Map.h"
#include <string> #include "MinimalEngine.h"
#include <filesystem> #include <filesystem>
#include <string>
namespace Seele
{ namespace Seele {
DECLARE_REF(TextureAsset) 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_REF(MaterialInstanceAsset)
DECLARE_NAME_REF(Gfx, Graphics) DECLARE_NAME_REF(Gfx, Graphics)
class AssetRegistry class AssetRegistry {
{ public:
public:
~AssetRegistry(); ~AssetRegistry();
static void init(std::filesystem::path path, Gfx::PGraphics graphics); static void init(std::filesystem::path path, Gfx::PGraphics graphics);
@@ -34,8 +33,7 @@ public:
static void loadRegistry(); static void loadRegistry();
static void saveRegistry(); static void saveRegistry();
struct AssetFolder struct AssetFolder {
{
std::string folderPath; std::string folderPath;
Map<std::string, AssetFolder*> children; Map<std::string, AssetFolder*> children;
Map<std::string, OTextureAsset> textures; Map<std::string, OTextureAsset> textures;
@@ -49,7 +47,8 @@ public:
AssetFolder* getOrCreateFolder(std::string_view foldername); AssetFolder* getOrCreateFolder(std::string_view foldername);
AssetRegistry(); AssetRegistry();
static AssetRegistry* getInstance(); static AssetRegistry* getInstance();
private:
private:
static AssetRegistry& get(); static AssetRegistry& get();
void initialize(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics); void initialize(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics);
@@ -81,4 +80,4 @@ private:
friend class MaterialLoader; friend class MaterialLoader;
friend class MeshLoader; friend class MeshLoader;
}; };
} } // namespace Seele
+23 -45
View File
@@ -5,26 +5,16 @@
using namespace Seele; using namespace Seele;
FontAsset::FontAsset() FontAsset::FontAsset() {}
{
}
FontAsset::FontAsset(std::string_view folderPath, std::string_view name) FontAsset::FontAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
: Asset(folderPath, name)
{
}
FontAsset::~FontAsset() FontAsset::~FontAsset() {}
{
} void FontAsset::save(ArchiveBuffer& buffer) const {
void FontAsset::save(ArchiveBuffer& buffer) const
{
Serialization::save(buffer, glyphs); Serialization::save(buffer, glyphs);
Serialization::save(buffer, usedTextures.size()); Serialization::save(buffer, usedTextures.size());
for (uint32 x = 0; x < usedTextures.size(); ++x) for (uint32 x = 0; x < usedTextures.size(); ++x) {
{
Array<uint8> textureData; Array<uint8> textureData;
ktxTexture2* kTexture; ktxTexture2* kTexture;
ktxTextureCreateInfo createInfo = { ktxTextureCreateInfo createInfo = {
@@ -34,7 +24,9 @@ void FontAsset::save(ArchiveBuffer& buffer) const
.baseWidth = usedTextures[x]->getWidth(), .baseWidth = usedTextures[x]->getWidth(),
.baseHeight = usedTextures[x]->getHeight(), .baseHeight = usedTextures[x]->getHeight(),
.baseDepth = usedTextures[x]->getDepth(), .baseDepth = usedTextures[x]->getDepth(),
.numDimensions = usedTextures[x]->getDepth() > 1 ? 3u : usedTextures[x]->getHeight() > 1 ? 2u : 1u, .numDimensions = usedTextures[x]->getDepth() > 1 ? 3u
: usedTextures[x]->getHeight() > 1 ? 2u
: 1u,
.numLevels = usedTextures[x]->getMipLevels(), .numLevels = usedTextures[x]->getMipLevels(),
.numLayers = usedTextures[x]->getDepth(), .numLayers = usedTextures[x]->getDepth(),
.numFaces = usedTextures[x]->getNumFaces(), .numFaces = usedTextures[x]->getNumFaces(),
@@ -43,10 +35,8 @@ void FontAsset::save(ArchiveBuffer& buffer) const
}; };
ktxTexture2_Create(&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &kTexture); ktxTexture2_Create(&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &kTexture);
for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth) for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth) {
{ for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face) {
for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face)
{
// technically, downloading cant be const, because we have to allocate temporary buffers and change layouts // technically, downloading cant be const, because we have to allocate temporary buffers and change layouts
// but practically the texture stays the same // but practically the texture stays the same
const_cast<Gfx::Texture2D*>(*(usedTextures[x]))->download(0, depth, face, textureData); const_cast<Gfx::Texture2D*>(*(usedTextures[x]))->download(0, depth, face, textureData);
@@ -55,9 +45,7 @@ void FontAsset::save(ArchiveBuffer& buffer) const
} }
char writer[100]; char writer[100];
snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1"); snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1");
ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, (ktx_uint32_t)strlen(writer) + 1, writer);
(ktx_uint32_t)strlen(writer) + 1,
writer);
ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_ASTC_4x4_RGBA, 0); ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_ASTC_4x4_RGBA, 0);
@@ -74,31 +62,26 @@ void FontAsset::save(ArchiveBuffer& buffer) const
} }
} }
void FontAsset::load(ArchiveBuffer& buffer) {
void FontAsset::load(ArchiveBuffer& buffer)
{
Serialization::load(buffer, glyphs); Serialization::load(buffer, glyphs);
size_t numTextures; size_t numTextures;
Serialization::load(buffer, numTextures); Serialization::load(buffer, numTextures);
for (uint64 x = 0; x < numTextures; ++x) for (uint64 x = 0; x < numTextures; ++x) {
{
Array<uint8> rawTex; Array<uint8> rawTex;
Serialization::load(buffer, rawTex); Serialization::load(buffer, rawTex);
ktxTexture2* kTexture; ktxTexture2* kTexture;
ktxTexture2_CreateFromMemory(rawTex.data(), ktxTexture2_CreateFromMemory(rawTex.data(), rawTex.size(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &kTexture);
rawTex.size(),
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT,
&kTexture);
ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0); ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0);
TextureCreateInfo createInfo = { TextureCreateInfo createInfo = {
.sourceData = { .sourceData =
.size = ktxTexture_GetDataSize(ktxTexture(kTexture)), {
.data = ktxTexture_GetData(ktxTexture(kTexture)), .size = ktxTexture_GetDataSize(ktxTexture(kTexture)),
.owner = Gfx::QueueType::GRAPHICS, .data = ktxTexture_GetData(ktxTexture(kTexture)),
}, .owner = Gfx::QueueType::GRAPHICS,
},
.format = (Gfx::SeFormat)kTexture->vkFormat, .format = (Gfx::SeFormat)kTexture->vkFormat,
.width = kTexture->baseWidth, .width = kTexture->baseWidth,
.height = kTexture->baseHeight, .height = kTexture->baseHeight,
@@ -116,21 +99,16 @@ void FontAsset::load(ArchiveBuffer& buffer)
} }
} }
void Seele::FontAsset::setUsedTextures(Array<Gfx::OTexture2D> _usedTextures) void Seele::FontAsset::setUsedTextures(Array<Gfx::OTexture2D> _usedTextures) { usedTextures = std::move(_usedTextures); }
{
usedTextures = std::move(_usedTextures);
}
void FontAsset::Glyph::save(ArchiveBuffer& buffer) const void FontAsset::Glyph::save(ArchiveBuffer& buffer) const {
{
Serialization::save(buffer, textureIndex); Serialization::save(buffer, textureIndex);
Serialization::save(buffer, size); Serialization::save(buffer, size);
Serialization::save(buffer, bearing); Serialization::save(buffer, bearing);
Serialization::save(buffer, advance); Serialization::save(buffer, advance);
} }
void FontAsset::Glyph::load(ArchiveBuffer& buffer) void FontAsset::Glyph::load(ArchiveBuffer& buffer) {
{
Serialization::load(buffer, textureIndex); Serialization::load(buffer, textureIndex);
Serialization::load(buffer, size); Serialization::load(buffer, size);
Serialization::load(buffer, bearing); Serialization::load(buffer, bearing);
+6 -8
View File
@@ -3,12 +3,10 @@
#include "Containers/Map.h" #include "Containers/Map.h"
#include "Math/Math.h" #include "Math/Math.h"
namespace Seele namespace Seele {
{
DECLARE_NAME_REF(Gfx, Texture2D) DECLARE_NAME_REF(Gfx, Texture2D)
class FontAsset : public Asset class FontAsset : public Asset {
{ public:
public:
static constexpr uint64 IDENTIFIER = 0x10; static constexpr uint64 IDENTIFIER = 0x10;
FontAsset(); FontAsset();
FontAsset(std::string_view folderPath, std::string_view name); FontAsset(std::string_view folderPath, std::string_view name);
@@ -16,8 +14,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;
struct Glyph struct Glyph {
{
uint32 textureIndex; uint32 textureIndex;
IVector2 size; IVector2 size;
IVector2 bearing; IVector2 bearing;
@@ -28,7 +25,8 @@ public:
const Map<uint32, Glyph> getGlyphData() const { return glyphs; } const Map<uint32, Glyph> getGlyphData() const { return glyphs; }
Gfx::PTexture2D getTexture(uint32 index) { return usedTextures[index]; } Gfx::PTexture2D getTexture(uint32 index) { return usedTextures[index]; }
void setUsedTextures(Array<Gfx::OTexture2D> _usedTextures); void setUsedTextures(Array<Gfx::OTexture2D> _usedTextures);
private:
private:
Array<Gfx::OTexture2D> usedTextures; Array<Gfx::OTexture2D> usedTextures;
Map<uint32, Glyph> glyphs; Map<uint32, Glyph> glyphs;
friend class FontLoader; friend class FontLoader;
+5 -21
View File
@@ -2,28 +2,12 @@
using namespace Seele; using namespace Seele;
LevelAsset::LevelAsset() LevelAsset::LevelAsset() {}
{
} LevelAsset::LevelAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
LevelAsset::LevelAsset(std::string_view folderPath, std::string_view name) LevelAsset::~LevelAsset() {}
: Asset(folderPath, name)
{
} void LevelAsset::save(ArchiveBuffer&) const {}
LevelAsset::~LevelAsset() void LevelAsset::load(ArchiveBuffer&) {}
{
}
void LevelAsset::save(ArchiveBuffer&) const
{
}
void LevelAsset::load(ArchiveBuffer&)
{
}
+4 -6
View File
@@ -1,18 +1,16 @@
#pragma once #pragma once
#include "Asset.h" #include "Asset.h"
namespace Seele namespace Seele {
{ class LevelAsset : public Asset {
class LevelAsset : public Asset public:
{
public:
static constexpr uint64 IDENTIFIER = 0x20; static constexpr uint64 IDENTIFIER = 0x20;
LevelAsset(); LevelAsset();
LevelAsset(std::string_view folderPath, std::string_view name); LevelAsset(std::string_view folderPath, std::string_view name);
virtual ~LevelAsset(); virtual ~LevelAsset();
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;
private:
private:
}; };
} // namespace Seele } // namespace Seele
+10 -21
View File
@@ -1,38 +1,27 @@
#include "MaterialAsset.h" #include "MaterialAsset.h"
#include "Material/Material.h"
#include "Graphics/Graphics.h"
#include "MaterialInstanceAsset.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
#include "Material/Material.h"
#include "MaterialInstanceAsset.h"
using namespace Seele; using namespace Seele;
MaterialAsset::MaterialAsset() MaterialAsset::MaterialAsset() {}
{
}
MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name) MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
: Asset(folderPath, name)
{
}
MaterialAsset::~MaterialAsset() MaterialAsset::~MaterialAsset() {}
{
}
void MaterialAsset::save(ArchiveBuffer& buffer) const void MaterialAsset::save(ArchiveBuffer& buffer) const { material->save(buffer); }
{
material->save(buffer);
}
void MaterialAsset::load(ArchiveBuffer& buffer) void MaterialAsset::load(ArchiveBuffer& buffer) {
{
material = new Material(); material = new Material();
material->load(buffer); material->load(buffer);
material->compile(); material->compile();
} }
PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params) PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params) {
{
OMaterialInstance instance = material->instantiate(); OMaterialInstance instance = material->instantiate();
instance->setBaseMaterial(this); instance->setBaseMaterial(this);
OMaterialInstanceAsset asset = new MaterialInstanceAsset(params.folderPath, params.name); OMaterialInstanceAsset asset = new MaterialInstanceAsset(params.folderPath, params.name);
+6 -8
View File
@@ -1,18 +1,15 @@
#pragma once #pragma once
#include "Asset.h" #include "Asset.h"
namespace Seele namespace Seele {
{
DECLARE_REF(Material) DECLARE_REF(Material)
DECLARE_REF(MaterialInstanceAsset) DECLARE_REF(MaterialInstanceAsset)
struct InstantiationParameter struct InstantiationParameter {
{
std::string name; std::string name;
std::string folderPath; std::string folderPath;
}; };
class MaterialAsset : public Asset class MaterialAsset : public Asset {
{ public:
public:
static constexpr uint64 IDENTIFIER = 0x4; static constexpr uint64 IDENTIFIER = 0x4;
MaterialAsset(); MaterialAsset();
MaterialAsset(std::string_view folderPath, std::string_view name); MaterialAsset(std::string_view folderPath, std::string_view name);
@@ -21,7 +18,8 @@ public:
virtual void load(ArchiveBuffer& buffer) override; virtual void load(ArchiveBuffer& buffer) override;
PMaterial getMaterial() const { return material; } PMaterial getMaterial() const { return material; }
PMaterialInstanceAsset instantiate(const InstantiationParameter& params); PMaterialInstanceAsset instantiate(const InstantiationParameter& params);
private:
private:
OMaterial material; OMaterial material;
friend class MaterialLoader; friend class MaterialLoader;
friend class MeshLoader; friend class MeshLoader;
+9 -18
View File
@@ -1,34 +1,25 @@
#include "MaterialInstanceAsset.h" #include "MaterialInstanceAsset.h"
#include "Material/MaterialInstance.h"
#include "Material/Material.h"
#include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
#include "Material/Material.h"
#include "Material/MaterialInstance.h"
using namespace Seele; using namespace Seele;
MaterialInstanceAsset::MaterialInstanceAsset() MaterialInstanceAsset::MaterialInstanceAsset() {}
{
}
MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view name) MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
: Asset(folderPath, name)
{
}
MaterialInstanceAsset::~MaterialInstanceAsset() MaterialInstanceAsset::~MaterialInstanceAsset() {}
{
}
void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const {
void MaterialInstanceAsset::save(ArchiveBuffer& buffer) const
{
Serialization::save(buffer, baseMaterial->getFolderPath()); Serialization::save(buffer, baseMaterial->getFolderPath());
Serialization::save(buffer, baseMaterial->getName()); Serialization::save(buffer, baseMaterial->getName());
material->save(buffer); material->save(buffer);
} }
void MaterialInstanceAsset::load(ArchiveBuffer& buffer) void MaterialInstanceAsset::load(ArchiveBuffer& buffer) {
{
std::string folder; std::string folder;
Serialization::load(buffer, folder); Serialization::load(buffer, folder);
std::string id; std::string id;
+5 -6
View File
@@ -2,11 +2,9 @@
#include "Asset.h" #include "Asset.h"
#include "Material/MaterialInstance.h" #include "Material/MaterialInstance.h"
namespace Seele namespace Seele {
{ class MaterialInstanceAsset : public Asset {
class MaterialInstanceAsset : public Asset public:
{
public:
static constexpr uint64 IDENTIFIER = 0x8; static constexpr uint64 IDENTIFIER = 0x8;
MaterialInstanceAsset(); MaterialInstanceAsset();
MaterialInstanceAsset(std::string_view folderPath, std::string_view name); MaterialInstanceAsset(std::string_view folderPath, std::string_view name);
@@ -16,7 +14,8 @@ public:
void setHandle(OMaterialInstance handle) { material = std::move(handle); } void setHandle(OMaterialInstance handle) { material = std::move(handle); }
void setBase(PMaterialAsset base) { baseMaterial = base; } void setBase(PMaterialAsset base) { baseMaterial = base; }
PMaterialInstance getHandle() const { return material; } PMaterialInstance getHandle() const { return material; }
private:
private:
OMaterialInstance material; OMaterialInstance material;
PMaterialAsset baseMaterial; PMaterialAsset baseMaterial;
}; };
+7 -19
View File
@@ -1,29 +1,17 @@
#include "MeshAsset.h" #include "MeshAsset.h"
#include "AssetRegistry.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Graphics/Mesh.h" #include "Graphics/Mesh.h"
#include "AssetRegistry.h"
using namespace Seele; using namespace Seele;
MeshAsset::MeshAsset() MeshAsset::MeshAsset() {}
{
}
MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name) MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
: Asset(folderPath, name)
{
}
MeshAsset::~MeshAsset() MeshAsset::~MeshAsset() {}
{
}
void MeshAsset::save(ArchiveBuffer& buffer) const void MeshAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, meshes); }
{
Serialization::save(buffer, meshes);
}
void MeshAsset::load(ArchiveBuffer& buffer) void MeshAsset::load(ArchiveBuffer& buffer) { Serialization::load(buffer, meshes); }
{
Serialization::load(buffer, meshes);
}
+4 -6
View File
@@ -2,20 +2,18 @@
#include "Asset.h" #include "Asset.h"
#include "Component/Collider.h" #include "Component/Collider.h"
namespace Seele namespace Seele {
{
DECLARE_REF(Mesh) DECLARE_REF(Mesh)
DECLARE_REF(MaterialInterface) DECLARE_REF(MaterialInterface)
class MeshAsset : public Asset class MeshAsset : public Asset {
{ public:
public:
static constexpr uint64 IDENTIFIER = 0x2; static constexpr uint64 IDENTIFIER = 0x2;
MeshAsset(); MeshAsset();
MeshAsset(std::string_view folderPath, std::string_view name); MeshAsset(std::string_view folderPath, std::string_view name);
virtual ~MeshAsset(); virtual ~MeshAsset();
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<OMesh> meshes; Array<OMesh> meshes;
Component::Collider physicsMesh; Component::Collider physicsMesh;
}; };
+47 -63
View File
@@ -1,69 +1,67 @@
#include "TextureAsset.h" #include "TextureAsset.h"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Window/WindowManager.h"
#include "Graphics/Vulkan/Enums.h"
#include "Graphics/Texture.h" #include "Graphics/Texture.h"
#include "Graphics/Vulkan/Enums.h"
#include "Window/WindowManager.h"
#include "ktx.h" #include "ktx.h"
using namespace Seele; using namespace Seele;
#define KTX_ASSERT(x) { auto error = x; if(error != KTX_SUCCESS) { std::cout << ktxErrorString(error) << std::endl; abort(); } } #define KTX_ASSERT(x) \
{ \
auto error = x; \
if (error != KTX_SUCCESS) { \
std::cout << ktxErrorString(error) << std::endl; \
abort(); \
} \
}
TextureAsset::TextureAsset() TextureAsset::TextureAsset() {}
{
}
TextureAsset::TextureAsset(std::string_view folderPath, std::string_view name) TextureAsset::TextureAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
: Asset(folderPath, name)
{
}
TextureAsset::~TextureAsset() TextureAsset::~TextureAsset() {}
{
}
void TextureAsset::save(ArchiveBuffer& buffer) const void TextureAsset::save(ArchiveBuffer& buffer) const {
{ // ktxBasisParams basisParams = {
//ktxBasisParams basisParams = { // .structSize = sizeof(ktxBasisParams),
// .structSize = sizeof(ktxBasisParams), // .uastc = true,
// .uastc = true, // .threadCount = std::thread::hardware_concurrency(),
// .threadCount = std::thread::hardware_concurrency(), // .normalMap = normalMap,
// .normalMap = normalMap, // .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW,
// .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW, // .uastcRDO = true,
// .uastcRDO = true, // .uastcRDOQualityScalar = 1,
// .uastcRDOQualityScalar = 1, // };
//}; // KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams));
//KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams)); // KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20));
//KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20)); // ktx_uint8_t* texData;
//ktx_uint8_t* texData; // ktx_size_t texSize;
//ktx_size_t texSize; // KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize));
//KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize));
// //
//Array<uint8> rawData(texSize); // Array<uint8> rawData(texSize);
//std::memcpy(rawData.data(), texData, texSize); // std::memcpy(rawData.data(), texData, texSize);
//Serialization::save(buffer, rawData); // Serialization::save(buffer, rawData);
//free(texData); // free(texData);
} }
void TextureAsset::load(ArchiveBuffer& buffer) void TextureAsset::load(ArchiveBuffer& buffer) {
{
std::string ktxPath; std::string ktxPath;
Serialization::load(buffer, ktxPath); Serialization::load(buffer, ktxPath);
ktxTexture2* ktxHandle; ktxTexture2* ktxHandle;
KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(), KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(), KTX_TEXTURE_CREATE_NO_FLAGS, (ktxTexture**)&ktxHandle));
KTX_TEXTURE_CREATE_NO_FLAGS,
(ktxTexture**)&ktxHandle));
KTX_ASSERT(ktxTexture2_TranscodeBasis(ktxHandle, KTX_TTF_BC7_RGBA, 0)); KTX_ASSERT(ktxTexture2_TranscodeBasis(ktxHandle, KTX_TTF_BC7_RGBA, 0));
Gfx::PGraphics graphics = buffer.getGraphics(); Gfx::PGraphics graphics = buffer.getGraphics();
TextureCreateInfo createInfo = { TextureCreateInfo createInfo = {
.sourceData = { .sourceData =
.size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)), {
.data = ktxTexture_GetData(ktxTexture(ktxHandle)), .size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)),
.owner = Gfx::QueueType::TRANSFER, .data = ktxTexture_GetData(ktxTexture(ktxHandle)),
}, .owner = Gfx::QueueType::TRANSFER,
},
.format = (Gfx::SeFormat)ktxHandle->vkFormat, .format = (Gfx::SeFormat)ktxHandle->vkFormat,
.width = ktxHandle->baseWidth, .width = ktxHandle->baseWidth,
.height = ktxHandle->baseHeight, .height = ktxHandle->baseHeight,
@@ -73,16 +71,11 @@ void TextureAsset::load(ArchiveBuffer& buffer)
.elements = ktxHandle->numLayers, .elements = ktxHandle->numLayers,
.usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT, .usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT,
}; };
if (ktxHandle->isCubemap) if (ktxHandle->isCubemap) {
{
texture = graphics->createTextureCube(createInfo); texture = graphics->createTextureCube(createInfo);
} } else if (ktxHandle->isArray) {
else if (ktxHandle->isArray)
{
texture = graphics->createTexture3D(createInfo); texture = graphics->createTexture3D(createInfo);
} } else {
else
{
texture = graphics->createTexture2D(createInfo); texture = graphics->createTexture2D(createInfo);
} }
@@ -90,17 +83,8 @@ void TextureAsset::load(ArchiveBuffer& buffer)
ktxTexture_Destroy(ktxTexture(ktxHandle)); ktxTexture_Destroy(ktxTexture(ktxHandle));
} }
void TextureAsset::setTexture(Gfx::OTexture _texture) void TextureAsset::setTexture(Gfx::OTexture _texture) { texture = std::move(_texture); }
{
texture = std::move(_texture);
}
uint32 TextureAsset::getWidth() uint32 TextureAsset::getWidth() { return texture->getWidth(); }
{
return texture->getWidth();
}
uint32 TextureAsset::getHeight() uint32 TextureAsset::getHeight() { return texture->getHeight(); }
{
return texture->getHeight();
}
+6 -10
View File
@@ -2,12 +2,10 @@
#include "Asset.h" #include "Asset.h"
struct ktxTexture2; struct ktxTexture2;
namespace Seele namespace Seele {
{
DECLARE_NAME_REF(Gfx, Texture) DECLARE_NAME_REF(Gfx, Texture)
class TextureAsset : public Asset class TextureAsset : public Asset {
{ public:
public:
static constexpr uint64 IDENTIFIER = 0x1; static constexpr uint64 IDENTIFIER = 0x1;
TextureAsset(); TextureAsset();
TextureAsset(std::string_view folderPath, std::string_view name); TextureAsset(std::string_view folderPath, std::string_view name);
@@ -15,13 +13,11 @@ 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;
void setTexture(Gfx::OTexture _texture); void setTexture(Gfx::OTexture _texture);
Gfx::PTexture getTexture() Gfx::PTexture getTexture() { return texture; }
{
return texture;
}
uint32 getWidth(); uint32 getWidth();
uint32 getHeight(); uint32 getHeight();
private:
private:
Gfx::OTexture texture; Gfx::OTexture texture;
bool normalMap; bool normalMap;
friend class TextureLoader; friend class TextureLoader;
+11 -22
View File
@@ -7,21 +7,14 @@ using namespace Seele;
using namespace Seele::Component; using namespace Seele::Component;
using namespace Seele::Math; using namespace Seele::Math;
Camera::Camera() Camera::Camera() : viewMatrix(Matrix4()), cameraPos(Vector()), bNeedsViewBuild(false) {
: viewMatrix(Matrix4()) yaw = -3.1415f / 2;
, cameraPos(Vector())
, bNeedsViewBuild(false)
{
yaw = -3.1415f/2;
pitch = 0; pitch = 0;
} }
Camera::~Camera() Camera::~Camera() {}
{
}
void Camera::mouseMove(float deltaYaw, float deltaPitch) void Camera::mouseMove(float deltaYaw, float deltaPitch) {
{
yaw += deltaYaw / 500.f; yaw += deltaYaw / 500.f;
pitch += deltaPitch / 500.f; pitch += deltaPitch / 500.f;
Vector cameraDirection = glm::normalize(Vector(cos(yaw) * cos(pitch), sin(pitch), sin(yaw) * cos(pitch))); Vector cameraDirection = glm::normalize(Vector(cos(yaw) * cos(pitch), sin(pitch), sin(yaw) * cos(pitch)));
@@ -30,26 +23,22 @@ void Camera::mouseMove(float deltaYaw, float deltaPitch)
bNeedsViewBuild = true; bNeedsViewBuild = true;
} }
void Camera::mouseScroll(float x) void Camera::mouseScroll(float x) {
{ getTransform().translate(getTransform().getForward() * x);
getTransform().translate(getTransform().getForward()*x);
bNeedsViewBuild = true; bNeedsViewBuild = true;
} }
void Camera::moveX(float amount) void Camera::moveX(float amount) {
{ getTransform().translate(getTransform().getForward() * amount);
getTransform().translate(getTransform().getForward()*amount);
bNeedsViewBuild = true; bNeedsViewBuild = true;
} }
void Camera::moveY(float amount) void Camera::moveY(float amount) {
{ getTransform().translate(getTransform().getRight() * amount);
getTransform().translate(getTransform().getRight()*amount);
bNeedsViewBuild = true; bNeedsViewBuild = true;
} }
void Camera::buildViewMatrix() void Camera::buildViewMatrix() {
{
Vector eyePos = getTransform().getPosition(); Vector eyePos = getTransform().getPosition();
Vector lookAt = eyePos + getTransform().getForward(); Vector lookAt = eyePos + getTransform().getForward();
viewMatrix = glm::lookAt(eyePos, lookAt, Vector(0, 1, 0)); viewMatrix = glm::lookAt(eyePos, lookAt, Vector(0, 1, 0));
+8 -14
View File
@@ -3,26 +3,19 @@
#include "Math/Matrix.h" #include "Math/Matrix.h"
#include "Transform.h" #include "Transform.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct Camera {
{
struct Camera
{
REQUIRE_COMPONENT(Transform) REQUIRE_COMPONENT(Transform)
Camera(); Camera();
~Camera(); ~Camera();
Matrix4 getViewMatrix() const Matrix4 getViewMatrix() const {
{ assert(!bNeedsViewBuild);
assert (!bNeedsViewBuild);
return viewMatrix; return viewMatrix;
} }
Vector getCameraPosition() const Vector getCameraPosition() const { return cameraPos; }
{
return cameraPos;
}
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);
@@ -30,7 +23,8 @@ struct Camera
void buildViewMatrix(); void buildViewMatrix();
bool mainCamera = false; bool mainCamera = false;
private:
private:
float yaw; float yaw;
float pitch; float pitch;
Matrix4 viewMatrix; Matrix4 viewMatrix;
+1 -2
View File
@@ -3,8 +3,7 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Component; using namespace Seele::Component;
Collider Collider::transform(const Transform& transform) const Collider Collider::transform(const Transform& transform) const {
{
return Collider{ return Collider{
.type = this->type, .type = this->type,
.boundingbox = this->boundingbox.getTransformedBox(transform.toMatrix()), .boundingbox = this->boundingbox.getTransformedBox(transform.toMatrix()),
+4 -8
View File
@@ -2,17 +2,13 @@
#include "Math/AABB.h" #include "Math/AABB.h"
#include "ShapeBase.h" #include "ShapeBase.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component enum class ColliderType {
{
enum class ColliderType
{
STATIC, STATIC,
DYNAMIC, DYNAMIC,
}; };
struct Collider struct Collider {
{
ColliderType type = ColliderType::STATIC; ColliderType type = ColliderType::STATIC;
AABB boundingbox; AABB boundingbox;
ShapeBase physicsMesh; ShapeBase physicsMesh;
+22 -39
View File
@@ -2,58 +2,41 @@
#include <concepts> #include <concepts>
#include <tuple> #include <tuple>
namespace Seele namespace Seele {
{ template <typename... Types> struct Dependencies;
template<typename... Types> template <> struct Dependencies<> {
struct Dependencies;
template<>
struct Dependencies<>
{
int x; int x;
template<typename... Right> template <typename... Right> Dependencies<Right...> operator|(const Dependencies<Right...>&) { return Dependencies<Right...>(); }
Dependencies<Right...> operator|(const Dependencies<Right...>&)
{
return Dependencies<Right...>();
}
}; };
template<typename This, typename... Rest> template <typename This, typename... Rest> struct Dependencies<This, Rest...> : public Dependencies<Rest...> {
struct Dependencies<This, Rest...> : public Dependencies<Rest...> template <typename... Right> Dependencies<This, Rest..., Right...> operator|(const Dependencies<Right...>&) {
{
template<typename... Right>
Dependencies<This, Rest..., Right...> operator|(const Dependencies<Right...>&)
{
return Dependencies<This, Rest..., Right...>(); return Dependencies<This, Rest..., Right...>();
} }
int x; int x;
}; };
namespace Component namespace Component {
{ template <typename Comp> Comp& getComponent();
template<typename Comp>
Comp& getComponent();
} }
template<typename Comp> template <typename Comp>
concept has_dependencies = requires(Comp) { Comp::dependencies; }; concept has_dependencies = requires(Comp) { Comp::dependencies; };
#define REQUIRE_COMPONENT(x) \ #define REQUIRE_COMPONENT(x) \
private: \ private: \
x& get##x() { return getComponent<x>(); } \ x& get##x() { return getComponent<x>(); } \
const x& get##x() const { return getComponent<x>(); } \ const x& get##x() const { return getComponent<x>(); } \
public: \ \
public: \
constexpr static Dependencies<x> dependencies = {}; constexpr static Dependencies<x> dependencies = {};
#define DECLARE_COMPONENT(x) \ #define DECLARE_COMPONENT(x) \
void accessComponent(x& val); \ void accessComponent(x& val); \
template<> \ template <> x& getComponent<x>();
x& getComponent<x>();
#define DEFINE_COMPONENT(x) \
thread_local x* tl_##x = nullptr; \
void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \
template<> \
x& Seele::Component::getComponent<x>() { return *tl_##x; }
#define DEFINE_COMPONENT(x) \
thread_local x* tl_##x = nullptr; \
void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \
template <> x& Seele::Component::getComponent<x>() { return *tl_##x; }
} // namespace Seele } // namespace Seele
+3 -6
View File
@@ -1,11 +1,8 @@
#pragma once #pragma once
#include "Math/Vector.h" #include "Math/Vector.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct DirectionalLight {
{
struct DirectionalLight
{
Vector4 color; Vector4 color;
Vector4 direction; Vector4 direction;
}; };
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "Graphics/Resources.h" #include "Graphics/Resources.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct KeyboardInput {
{
struct KeyboardInput
{
Seele::StaticArray<bool, static_cast<size_t>(Seele::KeyCode::KEY_LAST)> keys; Seele::StaticArray<bool, static_cast<size_t>(Seele::KeyCode::KEY_LAST)> keys;
bool mouse1; bool mouse1;
bool mouse2; bool mouse2;
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "Asset/MeshAsset.h" #include "Asset/MeshAsset.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct Mesh {
{
struct Mesh
{
PMeshAsset asset; PMeshAsset asset;
bool isStatic = true; bool isStatic = true;
}; };
+4 -7
View File
@@ -1,14 +1,11 @@
#pragma once #pragma once
#include "Math/Vector.h" #include "Math/Vector.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct PointLight {
{
struct PointLight
{
Vector4 positionWS; Vector4 positionWS;
//Vector4 positionVS; // Vector4 positionVS;
Vector4 colorRange; Vector4 colorRange;
}; };
} // namespace Component } // namespace Component
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "Math/AABB.h" #include "Math/AABB.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct RigidBody {
{
struct RigidBody
{
float mass = 1.0f; float mass = 1.0f;
Vector force; Vector force;
Vector torque; Vector torque;
+52 -78
View File
@@ -4,14 +4,12 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Component; using namespace Seele::Component;
// https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html
//https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html struct ComputationState {
struct ComputationState
{
// compute physics properties // compute physics properties
int A; /* alpha */ int A; /* alpha */
int B; /* beta */ int B; /* beta */
int C; /* gamma */ int C; /* gamma */
/* projection integrals */ /* projection integrals */
float P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb; float P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb;
@@ -24,28 +22,25 @@ struct ComputationState
Vector T1, T2, TP; Vector T1, T2, TP;
}; };
struct Face struct Face {
{
StaticArray<Vector, 3> vertices; StaticArray<Vector, 3> vertices;
Vector normal; Vector normal;
float w; float w;
}; };
void computeProjectionIntegrals(Face& f, ComputationState& state) void computeProjectionIntegrals(Face& f, ComputationState& state) {
{
state.P1 = state.Pa = state.Pb = state.Paa = state.Pab = state.Pbb = state.Paaa = state.Paab = state.Pabb = state.Pbbb = 0.0; state.P1 = state.Pa = state.Pb = state.Paa = state.Pab = state.Pbb = state.Paaa = state.Paab = state.Pabb = state.Pbbb = 0.0;
for(uint32_t i = 0; i < 3; ++i) for (uint32_t i = 0; i < 3; ++i) {
{
float a0 = f.vertices[i][state.A]; float a0 = f.vertices[i][state.A];
float b0 = f.vertices[i][state.B]; float b0 = f.vertices[i][state.B];
float a1 = f.vertices[(i+1)%3][state.A]; float a1 = f.vertices[(i + 1) % 3][state.A];
float b1 = f.vertices[(i+1)%3][state.B]; float b1 = f.vertices[(i + 1) % 3][state.B];
float da = a1 - a0; float da = a1 - a0;
float db = b1 - b0; float db = b1 - b0;
float a0_2 = a0 * a0, a0_3 = a0_2 * a0, a0_4 = a0_3 * a0; float a0_2 = a0 * a0, a0_3 = a0_2 * a0, a0_4 = a0_3 * a0;
float b0_2 = b0 * b0, b0_3 = b0_2 * b0, b0_4 = b0_3 * b0; float b0_2 = b0 * b0, b0_3 = b0_2 * b0, b0_4 = b0_3 * b0;
float a1_2 = a1 * a1, a1_3 = a1_2 * a1; float a1_2 = a1 * a1, a1_3 = a1_2 * a1;
float b1_2 = b1 * b1, b1_3 = b1_2 * b1; float b1_2 = b1 * b1, b1_3 = b1_2 * b1;
@@ -87,10 +82,9 @@ void computeProjectionIntegrals(Face& f, ComputationState& state)
state.Pabb /= -60.0; state.Pabb /= -60.0;
} }
void computeFaceIntegrals(Face& f, ComputationState& state) void computeFaceIntegrals(Face& f, ComputationState& state) {
{
computeProjectionIntegrals(f, state); computeProjectionIntegrals(f, state);
float k1 = 1.0f/f.normal[state.C]; float k1 = 1.0f / f.normal[state.C];
float k2 = k1 * k1; float k2 = k1 * k1;
float k3 = k2 * k1; float k3 = k2 * k1;
float k4 = k3 * k1; float k4 = k3 * k1;
@@ -104,53 +98,46 @@ void computeFaceIntegrals(Face& f, ComputationState& state)
state.Faa = k1 * state.Paa; state.Faa = k1 * state.Paa;
state.Fbb = k1 * state.Pbb; state.Fbb = k1 * state.Pbb;
state.Fcc = k3 * (n[state.A] * n[state.A] * state.Paa state.Fcc = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Pab + n[state.B] * n[state.B] * state.Pbb +
+ 2 * n[state.A] * n[state.B] * state.Pab w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1));
+ n[state.B] * n[state.B] * state.Pbb
+ w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1));
state.Faaa = k1 * state.Paaa; state.Faaa = k1 * state.Paaa;
state.Fbbb = k1 * state.Pbbb; state.Fbbb = k1 * state.Pbbb;
state.Fccc = -k4 * (n[state.A] * n[state.A] * n[state.A] * state.Paaa state.Fccc =
+ 3 * n[state.A] * n[state.A] * n[state.B] * state.Paab -k4 *
+ 3 * n[state.A] * n[state.B] * n[state.B] * state.Pabb (n[state.A] * n[state.A] * n[state.A] * state.Paaa + 3 * n[state.A] * n[state.A] * n[state.B] * state.Paab +
+ 3 * n[state.B] * n[state.B] * n[state.B] * state.Pbbb 3 * n[state.A] * n[state.B] * n[state.B] * state.Pabb + 3 * n[state.B] * n[state.B] * n[state.B] * state.Pbbb +
+ 3 * w * (n[state.A] * n[state.A] * state.Paa 3 * w * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Pa + n[state.B] * n[state.B] * state.Pbb) +
+ 2 * n[state.A] * n[state.B] * state.Pa w * w * (3 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1));
+ n[state.B] * n[state.B] * state.Pbb)
+ w * w *(3 * (n[state.A]*state.Pa + n[state.B]*state.Pb) + w * state.P1)
);
state.Faab = k1 * state.Paab; state.Faab = k1 * state.Paab;
state.Fbbc = -k2 * (n[state.A] * state.Paab + n[state.B] * state.Pbbb + w * state.Pbb); state.Fbbc = -k2 * (n[state.A] * state.Paab + n[state.B] * state.Pbbb + w * state.Pbb);
state.Fcca = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Paab + n[state.B] * n[state.B] * state.Pabb state.Fcca = k3 * (n[state.A] * n[state.A] * state.Paa + 2 * n[state.A] * n[state.B] * state.Paab +
+ w * (2 * (n[state.A] * state.Paa + n[state.B] * state.Pab) + w * state.Pa)); n[state.B] * n[state.B] * state.Pabb + w * (2 * (n[state.A] * state.Paa + n[state.B] * state.Pab) + w * state.Pa));
} }
void computeVolumeIntegrals(const Array<Vector> vertices, const Array<uint32>& indices, ComputationState& state) void computeVolumeIntegrals(const Array<Vector> vertices, const Array<uint32>& indices, ComputationState& state) {
{
std::memset(&state, 0, sizeof(ComputationState)); std::memset(&state, 0, sizeof(ComputationState));
for (size_t i = 0; i < indices.size(); i+=3) for (size_t i = 0; i < indices.size(); i += 3) {
{
Face f; Face f;
f.vertices = { f.vertices = {
vertices[indices[i]], vertices[indices[i]],
vertices[indices[i+1]], vertices[indices[i + 1]],
vertices[indices[i+2]], vertices[indices[i + 2]],
}; };
Vector e1 = f.vertices[2] - f.vertices[0]; Vector e1 = f.vertices[2] - f.vertices[0];
Vector e2 = f.vertices[1] - f.vertices[0]; Vector e2 = f.vertices[1] - f.vertices[0];
f.normal = glm::normalize(glm::cross(e1, e2)); f.normal = glm::normalize(glm::cross(e1, e2));
f.w = - f.normal.x * f.vertices[0].x f.w = -f.normal.x * f.vertices[0].x - f.normal.y * f.vertices[0].y - f.normal.z * f.vertices[0].z;
- f.normal.y * f.vertices[0].y
- f.normal.z * f.vertices[0].z;
float nx = std::abs(f.normal.x); float nx = std::abs(f.normal.x);
float ny = std::abs(f.normal.y); float ny = std::abs(f.normal.y);
float nz = std::abs(f.normal.z); float nz = std::abs(f.normal.z);
if (nx > ny && nx > nz) state.C = 0; if (nx > ny && nx > nz)
else state.C = (ny > nz) ? 1 : 2; state.C = 0;
else
state.C = (ny > nz) ? 1 : 2;
state.A = (state.C + 1) % 3; state.A = (state.C + 1) % 3;
state.B = (state.A + 1) % 3; state.B = (state.A + 1) % 3;
@@ -172,8 +159,8 @@ void computeVolumeIntegrals(const Array<Vector> vertices, const Array<uint32>& i
state.TP /= 2.0f; state.TP /= 2.0f;
} }
void computePhysicsParamsForMesh(Array<Vector>& vertices, const Array<uint32>& indices, Matrix3& bodyInertia, Vector& centerOfMass, float& mass) void computePhysicsParamsForMesh(Array<Vector>& vertices, const Array<uint32>& indices, Matrix3& bodyInertia, Vector& centerOfMass,
{ float& mass) {
ComputationState state; ComputationState state;
computeVolumeIntegrals(vertices, indices, state); computeVolumeIntegrals(vertices, indices, state);
float density = 1; float density = 1;
@@ -183,9 +170,9 @@ void computePhysicsParamsForMesh(Array<Vector>& vertices, const Array<uint32>& i
bodyInertia[0][0] = density * (state.T2.y + state.T2.z); bodyInertia[0][0] = density * (state.T2.y + state.T2.z);
bodyInertia[1][1] = density * (state.T2.z + state.T2.x); bodyInertia[1][1] = density * (state.T2.z + state.T2.x);
bodyInertia[2][2] = density * (state.T2.x + state.T2.y); bodyInertia[2][2] = density * (state.T2.x + state.T2.y);
bodyInertia[0][1] = bodyInertia[1][0] = - density * state.TP.x; bodyInertia[0][1] = bodyInertia[1][0] = -density * state.TP.x;
bodyInertia[1][2] = bodyInertia[2][1] = - density * state.TP.y; bodyInertia[1][2] = bodyInertia[2][1] = -density * state.TP.y;
bodyInertia[2][1] = bodyInertia[1][2] = - density * state.TP.z; bodyInertia[2][1] = bodyInertia[1][2] = -density * state.TP.z;
bodyInertia[0][0] -= mass * (r.y * r.y + r.z * r.z); bodyInertia[0][0] -= mass * (r.y * r.y + r.z * r.z);
bodyInertia[1][1] -= mass * (r.z * r.z + r.x * r.x); bodyInertia[1][1] -= mass * (r.z * r.z + r.x * r.x);
@@ -195,74 +182,61 @@ void computePhysicsParamsForMesh(Array<Vector>& vertices, const Array<uint32>& i
bodyInertia[2][1] = bodyInertia[1][2] += mass * r.z * r.x; bodyInertia[2][1] = bodyInertia[1][2] += mass * r.z * r.x;
} }
ShapeBase::ShapeBase() ShapeBase::ShapeBase() {}
{
} ShapeBase::ShapeBase(Array<Vector> vertices, Array<uint32> indices) : vertices(vertices), indices(indices) {
ShapeBase::ShapeBase(Array<Vector> vertices, Array<uint32> indices)
: vertices(vertices)
, indices(indices)
{
computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass); computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass);
} }
ShapeBase ShapeBase::transform(const Component::Transform& transform) const ShapeBase ShapeBase::transform(const Component::Transform& transform) const {
{
ShapeBase result = *this; ShapeBase result = *this;
for(auto& vert : result.vertices) for (auto& vert : result.vertices) {
{
vert = transform.toMatrix() * Vector4(vert, 1.0f); vert = transform.toMatrix() * Vector4(vert, 1.0f);
} }
return result; return result;
} }
void ShapeBase::addCollider(Array<Vector> verts, Array<uint32> inds, Matrix4 matrix) void ShapeBase::addCollider(Array<Vector> verts, Array<uint32> inds, Matrix4 matrix) {
{
size_t indOffset = vertices.size(); size_t indOffset = vertices.size();
for(auto vert : verts) for (auto vert : verts) {
{
vertices.add(Vector(matrix * Vector4(vert, 1.0f))); vertices.add(Vector(matrix * Vector4(vert, 1.0f)));
} }
for(auto ind : inds) for (auto ind : inds) {
{
indices.add(ind + static_cast<uint32>(indOffset)); indices.add(ind + static_cast<uint32>(indOffset));
} }
computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass); computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass);
} }
void ShapeBase::visualize() const void ShapeBase::visualize() const {
{
Array<DebugVertex> verts; Array<DebugVertex> verts;
for(uint32 i = 0; i < indices.size(); i+=3) for (uint32 i = 0; i < indices.size(); i += 3) {
{
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+0]]), .position = Vector(vertices[indices[i + 0]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+1]]), .position = Vector(vertices[indices[i + 1]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+1]]), .position = Vector(vertices[indices[i + 1]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+2]]), .position = Vector(vertices[indices[i + 2]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+2]]), .position = Vector(vertices[indices[i + 2]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
verts.add(DebugVertex{ verts.add(DebugVertex{
.position = Vector(vertices[indices[i+0]]), .position = Vector(vertices[indices[i + 0]]),
.color = Vector(1, 0, 0), .color = Vector(1, 0, 0),
}); });
} }
+5 -7
View File
@@ -1,14 +1,12 @@
#pragma once #pragma once
#include "Containers/Array.h" #include "Containers/Array.h"
#include "Transform.h"
#include "Graphics/DebugVertex.h" #include "Graphics/DebugVertex.h"
#include "Transform.h"
namespace Seele
{ namespace Seele {
namespace Component namespace Component {
{ struct ShapeBase {
struct ShapeBase
{
ShapeBase(); ShapeBase();
ShapeBase(Array<Vector> vertices, Array<uint32> indices); ShapeBase(Array<Vector> vertices, Array<uint32> indices);
ShapeBase transform(const Component::Transform& transform) const; ShapeBase transform(const Component::Transform& transform) const;
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "Graphics/Texture.h" #include "Graphics/Texture.h"
namespace Seele namespace Seele {
{ namespace Component {
namespace Component struct Skybox {
{
struct Skybox
{
Gfx::PTextureCube day; Gfx::PTextureCube day;
Gfx::PTextureCube night; Gfx::PTextureCube night;
Vector fogColor; Vector fogColor;
+6 -24
View File
@@ -4,29 +4,11 @@ using namespace Seele::Component;
DEFINE_COMPONENT(Transform); DEFINE_COMPONENT(Transform);
void Transform::setPosition(Vector pos) void Transform::setPosition(Vector pos) { transform.setPosition(pos); }
{
transform.setPosition(pos);
}
void Transform::setRotation(Quaternion quat) void Transform::setRotation(Quaternion quat) { transform.setRotation(quat); }
{
transform.setRotation(quat);
}
void Transform::setScale(Vector scale) void Transform::setScale(Vector scale) { transform.setScale(scale); }
{ void Transform::translate(Vector direction) { transform.setPosition(transform.getPosition() + direction); }
transform.setScale(scale); void Transform::rotate(Quaternion quat) { transform.setRotation(transform.getRotation() * quat); }
} void Transform::scale(Vector scale) { transform.setScale(transform.getScale() + scale); }
void Transform::translate(Vector direction)
{
transform.setPosition(transform.getPosition() + direction);
}
void Transform::rotate(Quaternion quat)
{
transform.setRotation(transform.getRotation() * quat);
}
void Transform::scale(Vector scale)
{
transform.setScale(transform.getScale() + scale);
}
+7 -8
View File
@@ -1,13 +1,11 @@
#pragma once #pragma once
#include "Math/Transform.h"
#include "Component.h" #include "Component.h"
#include "Math/Transform.h"
namespace Seele
{ namespace Seele {
namespace Component namespace Component {
{ struct Transform {
struct Transform
{
Vector getPosition() const { return transform.getPosition(); } Vector getPosition() const { return transform.getPosition(); }
Quaternion getRotation() const { return transform.getRotation(); } Quaternion getRotation() const { return transform.getRotation(); }
Vector getScale() const { return transform.getScale(); } Vector getScale() const { return transform.getScale(); }
@@ -24,7 +22,8 @@ struct Transform
void translate(Vector direction); void translate(Vector direction);
void rotate(Quaternion quat); void rotate(Quaternion quat);
void scale(Vector scale); void scale(Vector scale);
private:
private:
Math::Transform transform; Math::Transform transform;
}; };
DECLARE_COMPONENT(Transform) DECLARE_COMPONENT(Transform)
+6 -13
View File
@@ -1,19 +1,12 @@
#pragma once #pragma once
#include <concepts> #include <concepts>
namespace Seele namespace Seele {
{ template <class F, class... Args>
template<class F, class... Args>
concept invocable = std::invocable<F, Args...>; concept invocable = std::invocable<F, Args...>;
template<class Archive, class T> template <class Archive, class T>
concept serializable = requires(const T& t, Archive& a) concept serializable = requires(const T& t, Archive& a) { t.save(a); } && requires(T& t, Archive& a) { t.load(a); };
{ template <typename T>
t.save(a);
} && requires(T& t, Archive& a)
{
t.load(a);
};
template<typename T>
concept enumeration = std::is_enum_v<T>; concept enumeration = std::is_enum_v<T>;
} } // namespace Seele
File diff suppressed because it is too large Load Diff
+104 -271
View File
@@ -1,118 +1,71 @@
#pragma once #pragma once
#include <memory_resource>
#include <assert.h> #include <assert.h>
#include <memory_resource>
namespace Seele
{ namespace Seele {
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> class List {
class List private:
{ struct Node {
private: Node(Node* prev, Node* next, const T& data) : prev(prev), next(next), data(data) {}
struct Node Node(Node* prev, Node* next, T&& data) : prev(prev), next(next), data(std::move(data)) {}
{ Node* prev;
Node(Node* prev, Node* next, const T& data) Node* next;
: prev(prev)
, next(next)
, data(data)
{}
Node(Node* prev, Node* next, T&& data)
: prev(prev)
, next(next)
, data(std::move(data))
{}
Node *prev;
Node *next;
T data; T data;
}; };
using NodeAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Node>; using NodeAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Node>;
public: public:
template <typename X> template <typename X> class IteratorBase {
class IteratorBase public:
{
public:
using iterator_category = std::forward_iterator_tag; using iterator_category = std::forward_iterator_tag;
using value_type = X; using value_type = X;
using difference_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t;
using reference = X&; using reference = X&;
using pointer = X*; using pointer = X*;
IteratorBase(Node *x = nullptr) IteratorBase(Node* x = nullptr) : node(x) {}
: node(x) IteratorBase(const IteratorBase& i) : node(i.node) {}
{ IteratorBase(IteratorBase&& i) noexcept : node(std::move(i.node)) {}
} ~IteratorBase() {}
IteratorBase(const IteratorBase &i) IteratorBase& operator=(const IteratorBase& other) {
: node(i.node) if (this != &other) {
{
}
IteratorBase(IteratorBase&& i) noexcept
: node(std::move(i.node))
{
}
~IteratorBase()
{
}
IteratorBase& operator=(const IteratorBase& other)
{
if(this != &other)
{
node = other.node; node = other.node;
} }
return *this; return *this;
} }
IteratorBase& operator=(IteratorBase&& other) noexcept IteratorBase& operator=(IteratorBase&& other) noexcept {
{ if (this != &other) {
if(this != &other)
{
node = std::move(other.node); node = std::move(other.node);
} }
return *this; return *this;
} }
constexpr reference operator*() const constexpr reference operator*() const { return node->data; }
{ constexpr pointer operator->() const { return &node->data; }
return node->data; constexpr bool operator!=(const IteratorBase& other) { return node != other.node; }
} constexpr bool operator==(const IteratorBase& other) { return node == other.node; }
constexpr pointer operator->() const constexpr std::strong_ordering operator<=>(const IteratorBase& other) { return node <=> other.node; }
{ constexpr IteratorBase& operator--() {
return &node->data;
}
constexpr bool operator!=(const IteratorBase &other)
{
return node != other.node;
}
constexpr bool operator==(const IteratorBase &other)
{
return node == other.node;
}
constexpr std::strong_ordering operator<=>(const IteratorBase& other)
{
return node <=> other.node;
}
constexpr IteratorBase &operator--()
{
node = node->prev; node = node->prev;
return *this; return *this;
} }
constexpr IteratorBase operator--(int) constexpr IteratorBase operator--(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
--*this; --*this;
return tmp; return tmp;
} }
constexpr IteratorBase &operator++() constexpr IteratorBase& operator++() {
{
node = node->next; node = node->next;
return *this; return *this;
} }
constexpr IteratorBase operator++(int) constexpr IteratorBase operator++(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
++*this; ++*this;
return tmp; return tmp;
} }
private: private:
Node *node; Node* node;
friend class List<T>; friend class List<T>;
}; };
@@ -133,117 +86,71 @@ public:
using reverse_iterator = std::reverse_iterator<iterator>; using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr List() constexpr List() : allocator(Allocator()), root(allocateNode()), tail(root), beginIt(Iterator(root)), endIt(Iterator(tail)), _size(0) {}
: allocator(Allocator())
, root(allocateNode())
, tail(root)
, beginIt(Iterator(root))
, endIt(Iterator(tail))
, _size(0)
{
}
constexpr explicit List(const Allocator& alloc) constexpr explicit List(const Allocator& alloc)
: allocator(alloc) : allocator(alloc), root(allocateNode()), tail(root), beginIt(Iterator(root)), endIt(Iterator(tail)), _size(0) {}
, root(allocateNode()) constexpr List(size_type count, const T& value = T(), const Allocator& alloc = Allocator()) : List(alloc) {
, tail(root) for (size_type i = 0; i < count; ++i) {
, beginIt(Iterator(root))
, endIt(Iterator(tail))
, _size(0)
{
}
constexpr List(size_type count, const T& value = T(), const Allocator& alloc = Allocator())
: List(alloc)
{
for(size_type i = 0; i < count; ++i)
{
add(value); add(value);
} }
} }
constexpr List(size_type count, const Allocator& alloc = Allocator()) constexpr List(size_type count, const Allocator& alloc = Allocator()) : List(alloc) {
: List(alloc) for (size_type i = 0; i < count; ++i) {
{
for(size_type i = 0; i < count; ++i)
{
add(T()); add(T());
} }
} }
constexpr List(const List& other) constexpr List(const List& other)
: List(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator)) : List(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator)) {
{ // TODO: improve
//TODO: improve for (const auto& it : other) {
for(const auto& it : other)
{
add(it); add(it);
} }
} }
constexpr List(const List& other, const Allocator& alloc) constexpr List(const List& other, const Allocator& alloc) : List(alloc) {
: List(alloc) // TODO: improve
{ for (const auto& it : other) {
//TODO: improve
for(const auto& it : other)
{
add(it); add(it);
} }
} }
constexpr List(List&& other) constexpr List(List&& other)
: allocator(std::move(other.allocator)) : allocator(std::move(other.allocator)), root(std::move(other.root)), tail(std::move(other.tail)),
, root(std::move(other.root)) beginIt(std::move(other.beginIt)), endIt(std::move(other.endIt)), _size(std::move(other._size)) {
, tail(std::move(other.tail))
, beginIt(std::move(other.beginIt))
, endIt(std::move(other.endIt))
, _size(std::move(other._size))
{
other.root = nullptr; other.root = nullptr;
other.tail = nullptr; other.tail = nullptr;
other._size = 0; other._size = 0;
} }
constexpr List(List&& other, const Allocator& alloc) constexpr List(List&& other, const Allocator& alloc)
: allocator(alloc) : allocator(alloc), root(std::move(other.root)), tail(std::move(other.tail)), beginIt(std::move(other.beginIt)),
, root(std::move(other.root)) endIt(std::move(other.endIt)), _size(std::move(other._size)) {
, tail(std::move(other.tail))
, beginIt(std::move(other.beginIt))
, endIt(std::move(other.endIt))
, _size(std::move(other._size))
{
other.root = nullptr; other.root = nullptr;
other.tail = nullptr; other.tail = nullptr;
other._size = 0; other._size = 0;
} }
constexpr ~List() constexpr ~List() {
{
clear(); clear();
deallocateNode(tail); deallocateNode(tail);
} }
constexpr List& operator=(const List& other) constexpr List& operator=(const List& other) {
{ if (this != &other) {
if(this != &other)
{
clear(); clear();
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value ) if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
{ if (!std::allocator_traits<allocator_type>::is_always_equal::value && allocator != other.allocator) {
if (!std::allocator_traits<allocator_type>::is_always_equal::value
&& allocator != other.allocator)
{
clear(); clear();
} }
allocator = other.allocator; allocator = other.allocator;
} }
for(const auto& it : other) for (const auto& it : other) {
{
add(it); add(it);
} }
markIteratorDirty(); markIteratorDirty();
} }
return *this; return *this;
} }
constexpr List& operator=(List&& other) constexpr List& operator=(List&& other) {
{ if (this != &other) {
if(this != &other)
{
clear(); clear();
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {
{
allocator = std::move(other.allocator); allocator = std::move(other.allocator);
} }
root = other.root; root = other.root;
@@ -259,22 +166,13 @@ public:
return *this; return *this;
} }
constexpr reference front() constexpr reference front() { return root->data; }
{ constexpr reference back() { return tail->prev->data; }
return root->data; constexpr void clear() {
} if (empty()) {
constexpr reference back()
{
return tail->prev->data;
}
constexpr void clear()
{
if (empty())
{
return; return;
} }
for (Node *tmp = root; tmp != tail;) for (Node* tmp = root; tmp != tail;) {
{
tmp = tmp->next; tmp = tmp->next;
destroyNode(tmp->prev); destroyNode(tmp->prev);
deallocateNode(tmp->prev); deallocateNode(tmp->prev);
@@ -283,24 +181,12 @@ public:
markIteratorDirty(); markIteratorDirty();
_size = 0; _size = 0;
} }
//Insert at the end // Insert at the end
constexpr iterator add(const T &value) constexpr iterator add(const T& value) { return addInternal(value); }
{ constexpr iterator add(T&& value) { return addInternal(std::move(value)); }
return addInternal(value); template <typename... args> constexpr reference emplace(args... arguments) {
} std::allocator_traits<NodeAllocator>::construct(allocator, tail, tail->prev, tail->next, arguments...);
constexpr iterator add(T&& value) Node* newTail = allocateNode();
{
return addInternal(std::move(value));
}
template<typename... args>
constexpr reference emplace(args... arguments)
{
std::allocator_traits<NodeAllocator>::construct(allocator,
tail,
tail->prev,
tail->next,
arguments...);
Node *newTail = allocateNode();
newTail->prev = tail; newTail->prev = tail;
newTail->next = nullptr; newTail->next = nullptr;
tail->next = newTail; tail->next = newTail;
@@ -311,31 +197,23 @@ public:
return insertedElement; return insertedElement;
} }
// front + popFront // front + popFront
constexpr value_type retrieve() constexpr value_type retrieve() {
{
value_type temp = std::move(root->data); value_type temp = std::move(root->data);
popFront(); popFront();
return temp; return temp;
} }
constexpr iterator remove(iterator pos) constexpr iterator remove(iterator pos) {
{
_size--; _size--;
Node *prev = pos.node->prev; Node* prev = pos.node->prev;
Node *next = pos.node->next; Node* next = pos.node->next;
if (prev == nullptr) if (prev == nullptr) {
{
root = next; root = next;
} } else {
else
{
prev->next = next; prev->next = next;
} }
if(next == nullptr) if (next == nullptr) {
{
tail = prev; tail = prev;
} } else {
else
{
next->prev = prev; next->prev = prev;
} }
destroyNode(pos.node); destroyNode(pos.node);
@@ -343,111 +221,67 @@ public:
markIteratorDirty(); markIteratorDirty();
return Iterator(next); return Iterator(next);
} }
constexpr void popBack() constexpr void popBack() {
{
assert(_size > 0); assert(_size > 0);
remove(Iterator(tail->prev)); remove(Iterator(tail->prev));
} }
constexpr void pop_back() constexpr void pop_back() {
{
assert(_size > 0); assert(_size > 0);
remove(Iterator(tail->prev)); remove(Iterator(tail->prev));
} }
constexpr void popFront() constexpr void popFront() {
{
assert(_size > 0); assert(_size > 0);
remove(Iterator(root)); remove(Iterator(root));
} }
constexpr void pop_front() constexpr void pop_front() {
{
assert(_size > 0); assert(_size > 0);
remove(Iterator(root)); remove(Iterator(root));
} }
constexpr iterator insert(iterator pos, const T &value) constexpr iterator insert(iterator pos, const T& value) {
{
_size++; _size++;
Node *newNode = allocateNode(); Node* newNode = allocateNode();
initializeNode(newNode, value); initializeNode(newNode, value);
newNode->next = pos.node; newNode->next = pos.node;
pos.node->prev = newNode; pos.node->prev = newNode;
Node *tmp = pos.node->prev; Node* tmp = pos.node->prev;
if (tmp != nullptr) if (tmp != nullptr) {
{
tmp->next = newNode; tmp->next = newNode;
newNode->prev = tmp; newNode->prev = tmp;
} } else {
else
{
root = newNode; root = newNode;
} }
markIteratorDirty(); markIteratorDirty();
return Iterator(newNode); return Iterator(newNode);
} }
constexpr iterator find(const T &value) constexpr iterator find(const T& value) {
{ for (Node* i = root; i != tail; i = i->next) {
for (Node *i = root; i != tail; i = i->next) if (!(i->data < value) && !(value < i->data)) {
{
if (!(i->data < value) && !(value < i->data))
{
return iterator(i); return iterator(i);
} }
} }
return endIt; return endIt;
} }
constexpr bool empty() const constexpr bool empty() const { return _size == 0; }
{ constexpr size_type size() const { return _size; }
return _size == 0; constexpr iterator begin() { return beginIt; }
} constexpr const_iterator begin() const { return cbeginIt; }
constexpr size_type size() const constexpr iterator end() { return endIt; }
{ constexpr const_iterator end() const { return cendIt; }
return _size;
}
constexpr iterator begin()
{
return beginIt;
}
constexpr const_iterator begin() const
{
return cbeginIt;
}
constexpr iterator end()
{
return endIt;
}
constexpr const_iterator end() const
{
return cendIt;
}
private: private:
constexpr Node* allocateNode() constexpr Node* allocateNode() {
{
Node* node = allocator.allocate(1); Node* node = allocator.allocate(1);
assert(node != nullptr); assert(node != nullptr);
node->prev = nullptr; node->prev = nullptr;
node->next = nullptr; node->next = nullptr;
return node; return node;
} }
template<typename Type> template <typename Type> constexpr void initializeNode(Node* node, Type&& data) {
constexpr void initializeNode(Node* node, Type&& data) std::allocator_traits<NodeAllocator>::construct(allocator, node, node->prev, node->next, std::forward<Type>(data));
{
std::allocator_traits<NodeAllocator>::construct(allocator,
node,
node->prev,
node->next,
std::forward<Type>(data));
} }
constexpr void destroyNode(Node* node) constexpr void destroyNode(Node* node) { std::allocator_traits<NodeAllocator>::destroy(allocator, node); }
{ constexpr void deallocateNode(Node* node) { allocator.deallocate(node, 1); }
std::allocator_traits<NodeAllocator>::destroy(allocator, node); template <typename ValueType> constexpr iterator addInternal(ValueType&& value) {
}
constexpr void deallocateNode(Node* node)
{
allocator.deallocate(node, 1);
}
template<typename ValueType>
constexpr iterator addInternal(ValueType&& value)
{
initializeNode(tail, std::forward<ValueType>(value)); initializeNode(tail, std::forward<ValueType>(value));
Node* newTail = allocateNode(); Node* newTail = allocateNode();
newTail->prev = tail; newTail->prev = tail;
@@ -459,16 +293,15 @@ private:
_size++; _size++;
return insertedElement; return insertedElement;
} }
constexpr void markIteratorDirty() constexpr void markIteratorDirty() {
{
beginIt = Iterator(root); beginIt = Iterator(root);
endIt = Iterator(tail); endIt = Iterator(tail);
cbeginIt = ConstIterator(root); cbeginIt = ConstIterator(root);
cendIt = ConstIterator(tail); cendIt = ConstIterator(tail);
} }
NodeAllocator allocator; NodeAllocator allocator;
Node *root; Node* root;
Node *tail; Node* tail;
iterator beginIt; iterator beginIt;
iterator endIt; iterator endIt;
const_iterator cbeginIt; const_iterator cbeginIt;
+27 -78
View File
@@ -1,26 +1,17 @@
#pragma once #pragma once
#include <utility>
#include "Array.h" #include "Array.h"
#include "Pair.h" #include "Pair.h"
#include "Tree.h"
#include "Serialization/Serialization.h" #include "Serialization/Serialization.h"
#include "Tree.h"
#include <utility>
namespace Seele
{ namespace Seele {
template<typename KeyType, typename PairType> template <typename KeyType, typename PairType> struct _KeyFun {
struct _KeyFun const KeyType& operator()(const PairType& pair) const { return pair.key; }
{
const KeyType& operator()(const PairType& pair) const
{
return pair.key;
}
}; };
template <typename K, template <typename K, typename V, typename Compare = std::less<K>, typename Allocator = std::pmr::polymorphic_allocator<Pair<const K, V>>>
typename V, struct Map : public Tree<K, Pair<K, V>, _KeyFun<K, Pair<K, V>>, Compare, Allocator> {
typename Compare = std::less<K>,
typename Allocator = std::pmr::polymorphic_allocator<Pair<const K, V>>>
struct Map : public Tree<K, Pair<K, V>, _KeyFun<K, Pair<K, V>>, Compare, Allocator>
{
using Super = Tree<K, Pair<K, V>, _KeyFun<K, Pair<K, V>>, Compare, Allocator>; using Super = Tree<K, Pair<K, V>, _KeyFun<K, Pair<K, V>>, Compare, Allocator>;
using key_type = Super::key_type; using key_type = Super::key_type;
using mapped_type = V; using mapped_type = V;
@@ -39,84 +30,42 @@ struct Map : public Tree<K, Pair<K, V>, _KeyFun<K, Pair<K, V>>, Compare, Allocat
using reverse_iterator = Super::reverse_iterator; using reverse_iterator = Super::reverse_iterator;
using const_reverse_iterator = Super::const_reverse_iterator; using const_reverse_iterator = Super::const_reverse_iterator;
constexpr Map() noexcept constexpr Map() noexcept : Super() {}
: Super()
{
}
constexpr explicit Map(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator())) constexpr explicit Map(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator()))
: Super(comp, alloc) : Super(comp, alloc) {}
{ constexpr explicit Map(const Allocator& alloc) noexcept(noexcept(Compare())) : Super(alloc) {}
} constexpr mapped_type& operator[](const key_type& key) {
constexpr explicit Map(const Allocator& alloc) noexcept(noexcept(Compare()))
: Super(alloc)
{
}
constexpr mapped_type& operator[](const key_type& key)
{
auto [it, inserted] = Super::insert(Pair<K, V>(key, V())); auto [it, inserted] = Super::insert(Pair<K, V>(key, V()));
return it->value; return it->value;
} }
constexpr const mapped_type& operator[](const key_type& key) const constexpr const mapped_type& operator[](const key_type& key) const { return Super::find(key)->value; }
{ constexpr mapped_type& at(const key_type& key) {
return Super::find(key)->value;
}
constexpr mapped_type& at(const key_type& key)
{
iterator elem = Super::find(key); iterator elem = Super::find(key);
if (elem == Super::end()) if (elem == Super::end()) {
{
throw std::logic_error("Key not found"); throw std::logic_error("Key not found");
} }
return elem->value; return elem->value;
} }
constexpr const mapped_type& at(const key_type& key) const constexpr const mapped_type& at(const key_type& key) const { return Super::find(key)->value; }
{ constexpr iterator find(const key_type& key) { return Super::find(key); }
return Super::find(key)->value; constexpr iterator erase(const key_type& key) { return Super::remove(key); }
} constexpr bool exists(const key_type& key) const { return Super::find(key) != Super::end(); }
constexpr iterator find(const key_type& key) constexpr bool exists(const key_type& key) { return Super::find(key) != Super::end(); }
{ constexpr bool contains(const key_type& key) const { return exists(key); }
return Super::find(key); constexpr bool contains(const key_type& key) { return exists(key); }
} constexpr Pair<iterator, bool> insert(const value_type& val) { return Super::insert(val); }
constexpr iterator erase(const key_type& key) void save(ArchiveBuffer& buffer) const {
{
return Super::remove(key);
}
constexpr bool exists(const key_type& key) const
{
return Super::find(key) != Super::end();
}
constexpr bool exists(const key_type& key)
{
return Super::find(key) != Super::end();
}
constexpr bool contains(const key_type& key) const
{
return exists(key);
}
constexpr bool contains(const key_type& key)
{
return exists(key);
}
constexpr Pair<iterator, bool> insert(const value_type& val)
{
return Super::insert(val);
}
void save(ArchiveBuffer& buffer) const
{
size_t s = Super::size(); size_t s = Super::size();
buffer.writeBytes(&s, sizeof(uint64)); buffer.writeBytes(&s, sizeof(uint64));
for(const auto& [k, v] : *this) for (const auto& [k, v] : *this) {
{
Serialization::save(buffer, k); Serialization::save(buffer, k);
Serialization::save(buffer, v); Serialization::save(buffer, v);
} }
} }
void load(ArchiveBuffer& buffer) void load(ArchiveBuffer& buffer) {
{
uint64 len = 0; uint64 len = 0;
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 = K();
V v = V(); V v = V();
Serialization::load(buffer, k); Serialization::load(buffer, k);
+8 -21
View File
@@ -1,30 +1,17 @@
#pragma once #pragma once
namespace Seele namespace Seele {
{ template <typename K, typename V> struct Pair {
template <typename K, typename V> public:
struct Pair constexpr Pair() : key(K()), value(V()) {}
{ constexpr Pair(const K& key, const V& value) : key(key), value(value) {}
public: template <class U1 = K, class U2 = V> constexpr Pair(U1&& x, U2&& y) : key(std::forward<U1>(x)), value(std::forward<U2>(y)) {}
constexpr Pair()
: key(K()), value(V())
{}
constexpr Pair(const K & key, const V & value)
: key(key), value(value)
{}
template<class U1 = K, class U2 = V>
constexpr Pair(U1&& x, U2&& y)
: key(std::forward<U1>(x))
, value(std::forward<U2>(y))
{
}
Pair(const Pair& other) = default; Pair(const Pair& other) = default;
Pair(Pair&& other) = default; Pair(Pair&& other) = default;
~Pair(){} ~Pair() {}
Pair& operator=(const Pair& other) = default; Pair& operator=(const Pair& other) = default;
Pair& operator=(Pair&& other) = default; Pair& operator=(Pair&& other) = default;
constexpr friend bool operator<(const Pair& left, const Pair& right) constexpr friend bool operator<(const Pair& left, const Pair& right) {
{
return left.key < right.key || (!(right.key < left.key) && left.value < right.value); return left.key < right.key || (!(right.key < left.key) && left.value < right.value);
} }
K key; K key;
+10 -23
View File
@@ -1,14 +1,13 @@
#pragma once #pragma once
#include <utility>
#include "Array.h" #include "Array.h"
#include "Tree.h" #include "Tree.h"
#include <utility>
namespace Seele
{ namespace Seele {
template<class Key, class Compare = std::less<Key>, class Allocator = std::pmr::polymorphic_allocator<Key>> template <class Key, class Compare = std::less<Key>, class Allocator = std::pmr::polymorphic_allocator<Key>>
class Set : public Tree<Key, Key, std::identity, Compare, Allocator> class Set : public Tree<Key, Key, std::identity, Compare, Allocator> {
{ public:
public:
using Super = Tree<Key, Key, std::identity, Compare, Allocator>; using Super = Tree<Key, Key, std::identity, Compare, Allocator>;
using key_type = Key; using key_type = Key;
using value_type = Key; using value_type = Key;
@@ -26,21 +25,9 @@ public:
using reverse_iterator = Super::reverse_iterator; using reverse_iterator = Super::reverse_iterator;
using const_reverse_iterator = Super::const_reverse_iterator; using const_reverse_iterator = Super::const_reverse_iterator;
Set() Set() : Set(Compare()) {}
: Set(Compare()) explicit Set(const Compare& comp, const Allocator alloc = Allocator()) : Super(comp, alloc) {}
{ explicit Set(const Allocator alloc) : Super(alloc) {}
} constexpr Pair<iterator, bool> insert(const value_type& value) { return Super::insert(value); }
explicit Set(const Compare& comp, const Allocator alloc = Allocator())
: Super(comp, alloc)
{
}
explicit Set(const Allocator alloc)
: Super(alloc)
{
}
constexpr Pair<iterator, bool> insert(const value_type& value)
{
return Super::insert(value);
}
}; };
} // namespace Seele } // namespace Seele
+105 -276
View File
@@ -1,147 +1,88 @@
#pragma once #pragma once
#include <memory_resource>
#include "Pair.h" #include "Pair.h"
#include <memory_resource>
namespace Seele
{ namespace Seele {
template < template <typename KeyType, typename NodeData, typename KeyFun, typename Compare, typename Allocator> struct Tree {
typename KeyType, protected:
typename NodeData, struct Node {
typename KeyFun, Node(Node* left, Node* right, const NodeData& nodeData) : leftChild(left), rightChild(right), data(nodeData) {}
typename Compare, Node(Node* left, Node* right, NodeData&& nodeData) : leftChild(left), rightChild(right), data(std::move(nodeData)) {}
typename Allocator>
struct Tree
{
protected:
struct Node
{
Node(Node* left, Node* right, const NodeData& nodeData)
: leftChild(left)
, rightChild(right)
, data(nodeData)
{}
Node(Node* left, Node* right, NodeData&& nodeData)
: leftChild(left)
, rightChild(right)
, data(std::move(nodeData))
{}
Node* leftChild; Node* leftChild;
Node* rightChild; Node* rightChild;
NodeData data; NodeData data;
}; };
using NodeAlloc = std::allocator_traits<Allocator>::template rebind_alloc<Node>; using NodeAlloc = std::allocator_traits<Allocator>::template rebind_alloc<Node>;
public:
template<typename IterType> public:
class IteratorBase template <typename IterType> class IteratorBase {
{ public:
public:
using iterator_category = std::bidirectional_iterator_tag; using iterator_category = std::bidirectional_iterator_tag;
using value_type = IterType; using value_type = IterType;
using difference_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t;
using reference = IterType&; using reference = IterType&;
using pointer = IterType*; using pointer = IterType*;
constexpr IteratorBase(Node* x = nullptr, Array<Node*>&& beginIt = Array<Node*>()) constexpr IteratorBase(Node* x = nullptr, Array<Node*>&& beginIt = Array<Node*>()) : node(x), traversal(std::move(beginIt)) {}
: node(x), traversal(std::move(beginIt)) constexpr IteratorBase(const IteratorBase& i) : node(i.node), traversal(i.traversal) {}
{ constexpr IteratorBase(IteratorBase&& i) noexcept : node(std::move(i.node)), traversal(std::move(i.traversal)) {}
} constexpr IteratorBase& operator=(const IteratorBase& other) {
constexpr IteratorBase(const IteratorBase& i) if (this != &other) {
: node(i.node), traversal(i.traversal)
{
}
constexpr IteratorBase(IteratorBase&& i) noexcept
: node(std::move(i.node)), traversal(std::move(i.traversal))
{
}
constexpr IteratorBase& operator=(const IteratorBase& other)
{
if (this != &other)
{
node = other.node; node = other.node;
traversal = other.traversal; traversal = other.traversal;
} }
return *this; return *this;
} }
constexpr IteratorBase& operator=(IteratorBase&& other) noexcept constexpr IteratorBase& operator=(IteratorBase&& other) noexcept {
{ if (this != &other) {
if (this != &other)
{
node = std::move(other.node); node = std::move(other.node);
traversal = std::move(other.traversal); traversal = std::move(other.traversal);
} }
return *this; return *this;
} }
constexpr reference operator*() const constexpr reference operator*() const { return node->data; }
{ constexpr pointer operator->() const { return &(node->data); }
return node->data; constexpr bool operator!=(const IteratorBase& other) { return node != other.node; }
} constexpr bool operator==(const IteratorBase& other) { return node == other.node; }
constexpr pointer operator->() const constexpr std::strong_ordering operator<=>(const IteratorBase& other) { return node <=> other.node; }
{ constexpr IteratorBase& operator++() {
return &(node->data);
}
constexpr bool operator!=(const IteratorBase& other)
{
return node != other.node;
}
constexpr bool operator==(const IteratorBase& other)
{
return node == other.node;
}
constexpr std::strong_ordering operator<=>(const IteratorBase& other)
{
return node <=> other.node;
}
constexpr IteratorBase& operator++()
{
node = node->rightChild; node = node->rightChild;
while (node != nullptr while (node != nullptr && node->leftChild != nullptr) {
&& node->leftChild != nullptr)
{
traversal.add(node); traversal.add(node);
node = node->leftChild; node = node->leftChild;
} }
if (node == nullptr if (node == nullptr && traversal.size() > 0) {
&& traversal.size() > 0)
{
node = traversal.back(); node = traversal.back();
traversal.pop(); traversal.pop();
} }
return *this; return *this;
} }
constexpr IteratorBase& operator--() constexpr IteratorBase& operator--() {
{
node = node->leftChild; node = node->leftChild;
while (node != nullptr while (node != nullptr && node->rightChild != nullptr) {
&& node->rightChild != nullptr)
{
traversal.add(node); traversal.add(node);
node = node->rightchild; node = node->rightchild;
} }
if (node == nullptr if (node == nullptr && traversal.size() > 0) {
&& traversal.size() > 0)
{
node = traversal.back(); node = traversal.back();
traversal.pop(); traversal.pop();
} }
return *this; return *this;
} }
constexpr IteratorBase operator--(int) constexpr IteratorBase operator--(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
--*this; --*this;
return tmp; return tmp;
} }
constexpr IteratorBase operator++(int) constexpr IteratorBase operator++(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
++*this; ++*this;
return tmp; return tmp;
} }
Node* getNode() Node* getNode() { return node; }
{
return node; private:
}
private:
Node* node; Node* node;
Array<Node*> traversal; Array<Node*> traversal;
}; };
@@ -164,84 +105,39 @@ public:
using const_reverse_iterator = std::reverse_iterator<const_iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr Tree() noexcept constexpr Tree() noexcept
: alloc(NodeAlloc()) : alloc(NodeAlloc()), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(Compare()) {}
, root(nullptr)
, beginIt(nullptr)
, endIt(nullptr)
, iteratorsDirty(true)
, _size(0)
, comp(Compare())
{
}
constexpr explicit Tree(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator())) constexpr explicit Tree(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator()))
: alloc(alloc) : alloc(alloc), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(comp) {}
, root(nullptr)
, beginIt(nullptr)
, endIt(nullptr)
, iteratorsDirty(true)
, _size(0)
, comp(comp)
{
}
constexpr explicit Tree(const Allocator& alloc) noexcept(noexcept(Compare())) constexpr explicit Tree(const Allocator& alloc) noexcept(noexcept(Compare()))
: alloc(alloc) : alloc(alloc), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(Compare()) {}
, root(nullptr) constexpr Tree(const Tree& other) : alloc(other.alloc), root(nullptr), iteratorsDirty(true), _size(), comp(other.comp) {
, beginIt(nullptr) for (const auto& elem : other) {
, endIt(nullptr)
, iteratorsDirty(true)
, _size(0)
, comp(Compare())
{
}
constexpr Tree(const Tree& other)
: alloc(other.alloc)
, root(nullptr)
, iteratorsDirty(true)
, _size()
, comp(other.comp)
{
for (const auto& elem : other)
{
insert(elem); insert(elem);
} }
} }
constexpr Tree(Tree&& other) noexcept constexpr Tree(Tree&& other) noexcept
: alloc(std::move(other.alloc)) : alloc(std::move(other.alloc)), root(std::move(other.root)), iteratorsDirty(true), _size(std::move(other._size)),
, root(std::move(other.root)) comp(std::move(other.comp)) {
, iteratorsDirty(true)
, _size(std::move(other._size))
, comp(std::move(other.comp))
{
other._size = 0; other._size = 0;
} }
constexpr ~Tree() noexcept constexpr ~Tree() noexcept { clear(); }
{ constexpr Tree& operator=(const Tree& other) {
clear(); if (this != &other) {
}
constexpr Tree& operator=(const Tree& other)
{
if (this != &other)
{
clear(); clear();
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
{
alloc = other.alloc; alloc = other.alloc;
} }
for (const auto& elem : other) for (const auto& elem : other) {
{
insert(elem); insert(elem);
} }
markIteratorsDirty(); markIteratorsDirty();
} }
return *this; return *this;
} }
constexpr Tree& operator=(Tree&& other) noexcept constexpr Tree& operator=(Tree&& other) noexcept {
{ if (this != &other) {
if (this != &other)
{
clear(); clear();
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {
{
alloc = std::move(other.alloc); alloc = std::move(other.alloc);
} }
root = std::move(other.root); root = std::move(other.root);
@@ -252,144 +148,108 @@ public:
} }
return *this; return *this;
} }
constexpr void clear() constexpr void clear() {
{ while (_size > 0) {
while (_size > 0)
{
root = _remove(root, keyFun(root->data)); root = _remove(root, keyFun(root->data));
} }
root = nullptr; root = nullptr;
markIteratorsDirty(); markIteratorsDirty();
} }
constexpr iterator begin() constexpr iterator begin() {
{ if (iteratorsDirty) {
if (iteratorsDirty)
{
refreshIterators(); refreshIterators();
} }
return beginIt; return beginIt;
} }
constexpr iterator end() constexpr iterator end() {
{ if (iteratorsDirty) {
if (iteratorsDirty)
{
refreshIterators(); refreshIterators();
} }
return endIt; return endIt;
} }
constexpr iterator begin() const constexpr iterator begin() const {
{ if (iteratorsDirty) {
if (iteratorsDirty)
{
return calcBeginIterator(); return calcBeginIterator();
} }
return beginIt; return beginIt;
} }
constexpr iterator end() const constexpr iterator end() const {
{ if (iteratorsDirty) {
if (iteratorsDirty)
{
return calcEndIterator(); return calcEndIterator();
} }
return endIt; return endIt;
} }
constexpr bool empty() const constexpr bool empty() const { return _size == 0; }
{ constexpr size_type size() const { return _size; }
return _size == 0;
} protected:
constexpr size_type size() const constexpr iterator find(const key_type& key) {
{
return _size;
}
protected:
constexpr iterator find(const key_type& key)
{
root = _splay(root, key); root = _splay(root, key);
if (root == nullptr || !equal(root->data, key)) if (root == nullptr || !equal(root->data, key)) {
{
return end(); return end();
} }
return iterator(root); return iterator(root);
} }
constexpr iterator find(const key_type& key) const constexpr iterator find(const key_type& key) const {
{
Node* it = root; Node* it = root;
while (it != nullptr && !equal(it->data, key)) while (it != nullptr && !equal(it->data, key)) {
{ if (comp(key, keyFun(it->data))) {
if (comp(key, keyFun(it->data)))
{
it = it->leftChild; it = it->leftChild;
} } else {
else
{
it = it->rightChild; it = it->rightChild;
} }
} }
if (it == nullptr) if (it == nullptr) {
{
return end(); return end();
} }
return iterator(it); return iterator(it);
} }
constexpr Pair<iterator, bool> insert(const NodeData& data) constexpr Pair<iterator, bool> insert(const NodeData& data) {
{
auto [r, inserted] = _insert(root, data); auto [r, inserted] = _insert(root, data);
root = r; root = r;
return Pair<iterator, bool>(iterator(root), inserted); return Pair<iterator, bool>(iterator(root), inserted);
} }
constexpr Pair<iterator, bool> insert(NodeData&& data) constexpr Pair<iterator, bool> insert(NodeData&& data) {
{
auto [r, inserted] = _insert(root, std::move(data)); auto [r, inserted] = _insert(root, std::move(data));
root = r; root = r;
return Pair<iterator, bool>(iterator(root), inserted); return Pair<iterator, bool>(iterator(root), inserted);
} }
constexpr iterator remove(const key_type& key) constexpr iterator remove(const key_type& key) {
{
root = _remove(root, key); root = _remove(root, key);
return iterator(root); return iterator(root);
} }
private:
void verifyTree() private:
{ void verifyTree() {
size_t numElems = 0; size_t numElems = 0;
for (const auto& it : *this) for (const auto& it : *this) {
{
numElems++; numElems++;
} }
assert(numElems == _size); assert(numElems == _size);
} }
void markIteratorsDirty() void markIteratorsDirty() { iteratorsDirty = true; }
{ void refreshIterators() {
iteratorsDirty = true;
}
void refreshIterators()
{
beginIt = calcBeginIterator(); beginIt = calcBeginIterator();
endIt = calcEndIterator(); endIt = calcEndIterator();
iteratorsDirty = false; iteratorsDirty = false;
} }
constexpr Iterator calcBeginIterator() const constexpr Iterator calcBeginIterator() const {
{
Node* begin = root; Node* begin = root;
Array<Node*> beginTraversal; Array<Node*> beginTraversal;
while (begin != nullptr) while (begin != nullptr) {
{
beginTraversal.add(begin); beginTraversal.add(begin);
begin = begin->leftChild; begin = begin->leftChild;
} }
if (!beginTraversal.empty()) if (!beginTraversal.empty()) {
{
begin = beginTraversal.back(); begin = beginTraversal.back();
beginTraversal.pop(); beginTraversal.pop();
} }
return Iterator(begin, std::move(beginTraversal)); return Iterator(begin, std::move(beginTraversal));
} }
constexpr Iterator calcEndIterator() const constexpr Iterator calcEndIterator() const {
{
Node* endIndex = root; Node* endIndex = root;
Array<Node*> endTraversal; Array<Node*> endTraversal;
while (endIndex != nullptr) while (endIndex != nullptr) {
{
endTraversal.add(endIndex); endTraversal.add(endIndex);
endIndex = endIndex->rightChild; endIndex = endIndex->rightChild;
} }
@@ -403,26 +263,21 @@ private:
size_type _size; size_type _size;
Compare comp; Compare comp;
KeyFun keyFun = KeyFun(); KeyFun keyFun = KeyFun();
Node* rotateLeft(Node* x) Node* rotateLeft(Node* x) {
{
Node* y = x->rightChild; Node* y = x->rightChild;
x->rightChild = y->leftChild; x->rightChild = y->leftChild;
y->leftChild = x; y->leftChild = x;
return y; return y;
} }
Node* rotateRight(Node* x) Node* rotateRight(Node* x) {
{
Node* y = x->leftChild; Node* y = x->leftChild;
x->leftChild = y->rightChild; x->leftChild = y->rightChild;
y->rightChild = x; y->rightChild = x;
return y; return y;
} }
template<class NodeDataType> template <class NodeDataType> Pair<Node*, bool> _insert(Node* r, NodeDataType&& data) {
Pair<Node*, bool> _insert(Node* r, NodeDataType&& data)
{
markIteratorsDirty(); markIteratorsDirty();
if (r == nullptr) if (r == nullptr) {
{
root = alloc.allocate(1); root = alloc.allocate(1);
std::allocator_traits<NodeAlloc>::construct(alloc, root, nullptr, nullptr, std::forward<NodeDataType>(data)); std::allocator_traits<NodeAlloc>::construct(alloc, root, nullptr, nullptr, std::forward<NodeDataType>(data));
_size++; _size++;
@@ -436,14 +291,11 @@ private:
Node* newNode = alloc.allocate(1); Node* newNode = alloc.allocate(1);
std::allocator_traits<NodeAlloc>::construct(alloc, newNode, nullptr, nullptr, std::forward<NodeDataType>(data)); std::allocator_traits<NodeAlloc>::construct(alloc, newNode, nullptr, nullptr, std::forward<NodeDataType>(data));
if (comp(keyFun(newNode->data), keyFun(r->data))) if (comp(keyFun(newNode->data), keyFun(r->data))) {
{
newNode->rightChild = r; newNode->rightChild = r;
newNode->leftChild = r->leftChild; newNode->leftChild = r->leftChild;
r->leftChild = nullptr; r->leftChild = nullptr;
} } else {
else
{
newNode->leftChild = r; newNode->leftChild = r;
newNode->rightChild = r->rightChild; newNode->rightChild = r->rightChild;
r->rightChild = nullptr; r->rightChild = nullptr;
@@ -451,9 +303,7 @@ private:
_size++; _size++;
return Pair<Node*, bool>(newNode, true); return Pair<Node*, bool>(newNode, true);
} }
template<class K> template <class K> Node* _remove(Node* r, K&& key) {
Node* _remove(Node* r, K&& key)
{
markIteratorsDirty(); markIteratorsDirty();
Node* temp; Node* temp;
if (r == nullptr) if (r == nullptr)
@@ -464,13 +314,10 @@ private:
if (!equal(r->data, key)) if (!equal(r->data, key))
return r; return r;
if (r->leftChild == nullptr) if (r->leftChild == nullptr) {
{
temp = r; temp = r;
r = r->rightChild; r = r->rightChild;
} } else {
else
{
temp = r; temp = r;
r = _splay(r->leftChild, key); r = _splay(r->leftChild, key);
@@ -481,52 +328,38 @@ private:
_size--; _size--;
return r; return r;
} }
template<class K> template <class K> Node* _splay(Node* r, K&& key) {
Node* _splay(Node* r, K&& key)
{
markIteratorsDirty(); markIteratorsDirty();
if (r == nullptr || equal(r->data, key)) if (r == nullptr || equal(r->data, key)) {
{
return r; return r;
} }
if (comp(key, keyFun(r->data))) if (comp(key, keyFun(r->data))) {
{
if (r->leftChild == nullptr) if (r->leftChild == nullptr)
return r; return r;
if (comp(key, keyFun(r->leftChild->data))) if (comp(key, keyFun(r->leftChild->data))) {
{
r->leftChild->leftChild = _splay(r->leftChild->leftChild, key); r->leftChild->leftChild = _splay(r->leftChild->leftChild, key);
r = rotateRight(r); r = rotateRight(r);
} } else if (comp(keyFun(r->leftChild->data), key)) {
else if (comp(keyFun(r->leftChild->data), key))
{
r->leftChild->rightChild = _splay(r->leftChild->rightChild, key); r->leftChild->rightChild = _splay(r->leftChild->rightChild, key);
if (r->leftChild->rightChild != nullptr) if (r->leftChild->rightChild != nullptr) {
{
r->leftChild = rotateLeft(r->leftChild); r->leftChild = rotateLeft(r->leftChild);
} }
} }
return (r->leftChild == nullptr) ? r : rotateRight(r); return (r->leftChild == nullptr) ? r : rotateRight(r);
} } else {
else
{
if (r->rightChild == nullptr) if (r->rightChild == nullptr)
return r; return r;
if (comp(key, keyFun(r->rightChild->data))) if (comp(key, keyFun(r->rightChild->data))) {
{
r->rightChild->leftChild = _splay(r->rightChild->leftChild, key); r->rightChild->leftChild = _splay(r->rightChild->leftChild, key);
if (r->rightChild->leftChild != nullptr) if (r->rightChild->leftChild != nullptr) {
{
r->rightChild = rotateRight(r->rightChild); r->rightChild = rotateRight(r->rightChild);
} }
} } else if (comp(keyFun(r->rightChild->data), key)) {
else if (comp(keyFun(r->rightChild->data), key))
{
r->rightChild->rightChild = _splay(r->rightChild->rightChild, key); r->rightChild->rightChild = _splay(r->rightChild->rightChild, key);
r = rotateLeft(r); r = rotateLeft(r);
@@ -534,10 +367,6 @@ private:
return (r->rightChild == nullptr) ? r : rotateLeft(r); return (r->rightChild == nullptr) ? r : rotateLeft(r);
} }
} }
template<typename K> template <typename K> bool equal(const NodeData& a, K&& b) const { return !comp(keyFun(a), b) && !comp(b, keyFun(a)); }
bool equal(const NodeData& a, K&& b) const
{
return !comp(keyFun(a), b) && !comp(b, keyFun(a));
}
}; };
} // namespace Seele } // namespace Seele
+3 -5
View File
@@ -2,11 +2,9 @@
#include "Scene/Scene.h" #include "Scene/Scene.h"
#include "System/SystemGraph.h" #include "System/SystemGraph.h"
namespace Seele namespace Seele {
{ class Game {
class Game public:
{
public:
Game() {} Game() {}
virtual ~Game() {} virtual ~Game() {}
virtual void setupScene(PScene scene, PSystemGraph graph) = 0; virtual void setupScene(PScene scene, PSystemGraph graph) = 0;
+20 -46
View File
@@ -3,60 +3,34 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Gfx; using namespace Seele::Gfx;
Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue) Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue) : QueueOwnedResource(mapping, startQueue) {}
: QueueOwnedResource(mapping, startQueue)
{
}
Buffer::~Buffer() Buffer::~Buffer() {}
{
}
VertexBuffer::VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType) VertexBuffer::VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType)
: Buffer(mapping, startQueueType) : Buffer(mapping, startQueueType), numVertices(numVertices), vertexSize(vertexSize) {}
, numVertices(numVertices) VertexBuffer::~VertexBuffer() {}
, vertexSize(vertexSize)
{
}
VertexBuffer::~VertexBuffer()
{
}
IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType indexType, QueueType startQueueType) IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType indexType, QueueType startQueueType)
: Buffer(mapping, startQueueType) : Buffer(mapping, startQueueType), indexType(indexType) {
, indexType(indexType) switch (indexType) {
{ case SE_INDEX_TYPE_UINT16:
switch (indexType) numIndices = size / sizeof(uint16);
{ break;
case SE_INDEX_TYPE_UINT16: case SE_INDEX_TYPE_UINT32:
numIndices = size / sizeof(uint16); numIndices = size / sizeof(uint32);
break; break;
case SE_INDEX_TYPE_UINT32: default:
numIndices = size / sizeof(uint32); break;
break; }
default:
break;
}
}
IndexBuffer::~IndexBuffer()
{
} }
IndexBuffer::~IndexBuffer() {}
UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData) UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData) : Buffer(mapping, sourceData.owner) {}
: Buffer(mapping, sourceData.owner)
{}
UniformBuffer::~UniformBuffer() UniformBuffer::~UniformBuffer() {}
{
}
ShaderBuffer::ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& sourceData) ShaderBuffer::ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& sourceData)
: Buffer(mapping, sourceData.owner) : Buffer(mapping, sourceData.owner), numElements(numElements) {}
, numElements(numElements)
{
}
ShaderBuffer::~ShaderBuffer()
{
}
ShaderBuffer::~ShaderBuffer() {}
+61 -72
View File
@@ -1,106 +1,95 @@
#pragma once #pragma once
#include "Resources.h"
#include "Initializer.h" #include "Initializer.h"
#include "Resources.h"
namespace Seele { namespace Seele {
namespace Gfx { namespace Gfx {
class Buffer : public QueueOwnedResource { class Buffer : public QueueOwnedResource {
public: public:
Buffer(QueueFamilyMapping mapping, QueueType startQueueType); Buffer(QueueFamilyMapping mapping, QueueType startQueueType);
virtual ~Buffer(); virtual ~Buffer();
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0; virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
}; };
class VertexBuffer : public Buffer { class VertexBuffer : public Buffer {
public: public:
VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType);
uint32 vertexSize, QueueType startQueueType); virtual ~VertexBuffer();
virtual ~VertexBuffer(); constexpr uint32 getNumVertices() const { return numVertices; }
constexpr uint32 getNumVertices() const { return numVertices; } // Size of one vertex in bytes
// Size of one vertex in bytes constexpr uint32 getVertexSize() const { return vertexSize; }
constexpr uint32 getVertexSize() const { return vertexSize; }
virtual void updateRegion(DataSource update) = 0; virtual void updateRegion(DataSource update) = 0;
virtual void download(Array<uint8> &buffer) = 0; virtual void download(Array<uint8>& buffer) = 0;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0; virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess, virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags srcStage, SePipelineStageFlags dstStage) = 0;
SeAccessFlags dstAccess, uint32 numVertices;
SePipelineStageFlags dstStage) = 0; uint32 vertexSize;
uint32 numVertices;
uint32 vertexSize;
}; };
DEFINE_REF(VertexBuffer) DEFINE_REF(VertexBuffer)
class IndexBuffer : public Buffer { class IndexBuffer : public Buffer {
public: public:
IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index, IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index, QueueType startQueueType);
QueueType startQueueType); virtual ~IndexBuffer();
virtual ~IndexBuffer(); constexpr uint64 getNumIndices() const { return numIndices; }
constexpr uint64 getNumIndices() const { return numIndices; } constexpr Gfx::SeIndexType getIndexType() const { return indexType; }
constexpr Gfx::SeIndexType getIndexType() const { return indexType; }
virtual void download(Array<uint8> &buffer) = 0; virtual void download(Array<uint8>& buffer) = 0;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0; virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess, virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags srcStage, SePipelineStageFlags dstStage) = 0;
SeAccessFlags dstAccess, Gfx::SeIndexType indexType;
SePipelineStageFlags dstStage) = 0; uint64 numIndices;
Gfx::SeIndexType indexType;
uint64 numIndices;
}; };
DEFINE_REF(IndexBuffer) DEFINE_REF(IndexBuffer)
DECLARE_REF(UniformBuffer) DECLARE_REF(UniformBuffer)
class UniformBuffer : public Buffer { class UniformBuffer : public Buffer {
public: public:
UniformBuffer(QueueFamilyMapping mapping, const DataSource &sourceData); UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData);
virtual ~UniformBuffer(); virtual ~UniformBuffer();
virtual void rotateBuffer(uint64 size) = 0; virtual void rotateBuffer(uint64 size) = 0;
virtual void updateContents(const DataSource &sourceData) = 0; virtual void updateContents(const DataSource& sourceData) = 0;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0; virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess, virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags srcStage, SePipelineStageFlags dstStage) = 0;
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
}; };
DEFINE_REF(UniformBuffer) DEFINE_REF(UniformBuffer)
class ShaderBuffer : public Buffer { class ShaderBuffer : public Buffer {
public: public:
ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& bulkResourceData);
const DataSource &bulkResourceData); virtual ~ShaderBuffer();
virtual ~ShaderBuffer(); virtual void rotateBuffer(uint64 size, bool preserveContents = false) = 0;
virtual void rotateBuffer(uint64 size, bool preserveContents = false) = 0; virtual void updateContents(const ShaderBufferCreateInfo& sourceData) = 0;
virtual void updateContents(const ShaderBufferCreateInfo &sourceData) = 0; constexpr uint32 getNumElements() const { return numElements; }
constexpr uint32 getNumElements() const { return numElements; } virtual void* mapRegion(uint64 offset = 0, uint64 size = -1, bool writeOnly = true) = 0;
virtual void *mapRegion(uint64 offset = 0, uint64 size = -1, virtual void unmap() = 0;
bool writeOnly = true) = 0;
virtual void unmap() = 0;
virtual void clear() = 0; virtual void clear() = 0;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0; virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess, virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags srcStage, SePipelineStageFlags dstStage) = 0;
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
uint32 numElements; uint32 numElements;
}; };
DEFINE_REF(ShaderBuffer) DEFINE_REF(ShaderBuffer)
} // namespace Gfx } // namespace Gfx
+4 -13
View File
@@ -3,19 +3,10 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Gfx; using namespace Seele::Gfx;
RenderCommand::RenderCommand() {}
RenderCommand::RenderCommand() RenderCommand::~RenderCommand() {}
{
}
RenderCommand::~RenderCommand() ComputeCommand::ComputeCommand() {}
{
}
ComputeCommand::ComputeCommand() ComputeCommand::~ComputeCommand() {}
{
}
ComputeCommand::~ComputeCommand()
{
}
+10 -13
View File
@@ -1,15 +1,13 @@
#pragma once #pragma once
#include "Enums.h"
#include "Descriptor.h" #include "Descriptor.h"
#include "Enums.h"
namespace Seele
{ namespace Seele {
namespace Gfx namespace Gfx {
{
DECLARE_REF(Viewport) DECLARE_REF(Viewport)
class RenderCommand class RenderCommand {
{ public:
public:
RenderCommand(); RenderCommand();
virtual ~RenderCommand(); virtual ~RenderCommand();
virtual void setViewport(Gfx::PViewport viewport) = 0; virtual void setViewport(Gfx::PViewport viewport) = 0;
@@ -26,9 +24,8 @@ public:
std::string name; std::string name;
}; };
DEFINE_REF(RenderCommand) DEFINE_REF(RenderCommand)
class ComputeCommand class ComputeCommand {
{ public:
public:
ComputeCommand(); ComputeCommand();
virtual ~ComputeCommand(); virtual ~ComputeCommand();
virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0; virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0;
@@ -40,5 +37,5 @@ public:
}; };
DEFINE_REF(ComputeCommand) DEFINE_REF(ComputeCommand)
} } // namespace Gfx
} } // namespace Seele
+4 -5
View File
@@ -1,11 +1,10 @@
#pragma once #pragma once
#include "Math/Vector.h"
#include "Containers/Array.h" #include "Containers/Array.h"
#include "Math/Vector.h"
namespace Seele
{ namespace Seele {
struct DebugVertex struct DebugVertex {
{
Vector position; Vector position;
Vector color; Vector color;
}; };
+22 -27
View File
@@ -6,28 +6,28 @@ using namespace Seele::Gfx;
DescriptorLayout::DescriptorLayout(const std::string& name) : name(name) {} DescriptorLayout::DescriptorLayout(const std::string& name) : name(name) {}
DescriptorLayout::DescriptorLayout(const DescriptorLayout& other) { DescriptorLayout::DescriptorLayout(const DescriptorLayout& other) {
descriptorBindings.resize(other.descriptorBindings.size()); descriptorBindings.resize(other.descriptorBindings.size());
for (uint32 i = 0; i < descriptorBindings.size(); ++i) { for (uint32 i = 0; i < descriptorBindings.size(); ++i) {
descriptorBindings[i] = other.descriptorBindings[i]; descriptorBindings[i] = other.descriptorBindings[i];
} }
} }
DescriptorLayout& DescriptorLayout::operator=(const DescriptorLayout& other) { DescriptorLayout& DescriptorLayout::operator=(const DescriptorLayout& other) {
if (this != &other) { if (this != &other) {
descriptorBindings.resize(other.descriptorBindings.size()); descriptorBindings.resize(other.descriptorBindings.size());
for (uint32 i = 0; i < descriptorBindings.size(); ++i) { for (uint32 i = 0; i < descriptorBindings.size(); ++i) {
descriptorBindings[i] = other.descriptorBindings[i]; descriptorBindings[i] = other.descriptorBindings[i];
}
} }
} return *this;
return *this;
} }
DescriptorLayout::~DescriptorLayout() {} DescriptorLayout::~DescriptorLayout() {}
void DescriptorLayout::addDescriptorBinding(DescriptorBinding binding) { void DescriptorLayout::addDescriptorBinding(DescriptorBinding binding) {
if (descriptorBindings.size() <= binding.binding) { if (descriptorBindings.size() <= binding.binding) {
descriptorBindings.resize(binding.binding + 1); descriptorBindings.resize(binding.binding + 1);
} }
descriptorBindings[binding.binding] = binding; descriptorBindings[binding.binding] = binding;
} }
@@ -45,27 +45,22 @@ DescriptorSet::~DescriptorSet() {}
PipelineLayout::PipelineLayout(const std::string& name) : name(name) {} PipelineLayout::PipelineLayout(const std::string& name) : name(name) {}
PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayout) : name(name){ PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayout) : name(name) {
if (baseLayout != nullptr) { if (baseLayout != nullptr) {
descriptorSetLayouts = baseLayout->descriptorSetLayouts; descriptorSetLayouts = baseLayout->descriptorSetLayouts;
pushConstants = baseLayout->pushConstants; pushConstants = baseLayout->pushConstants;
} }
} }
PipelineLayout::~PipelineLayout() {} PipelineLayout::~PipelineLayout() {}
void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) { void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) { descriptorSetLayouts[layout->getName()] = layout; }
descriptorSetLayouts[layout->getName()] = layout;
}
void PipelineLayout::addPushConstants(const SePushConstantRange& pushConstant) { pushConstants.add(pushConstant); } void PipelineLayout::addPushConstants(const SePushConstantRange& pushConstant) { pushConstants.add(pushConstant); }
void PipelineLayout::addMapping(Map<std::string, uint32> mapping) void PipelineLayout::addMapping(Map<std::string, uint32> mapping) {
{ for (const auto& [name, index] : mapping) {
for(const auto& [name, index] : mapping) if (parameterMapping.contains(name)) {
{
if(parameterMapping.contains(name))
{
assert(parameterMapping[name] == index); assert(parameterMapping[name] == index);
} }
parameterMapping[name] = index; parameterMapping[name] = index;
+66 -74
View File
@@ -1,55 +1,54 @@
#pragma once #pragma once
#include "Enums.h" #include "Enums.h"
#include "Resources.h"
#include "Initializer.h" #include "Initializer.h"
#include "Resources.h"
namespace Seele { namespace Seele {
namespace Gfx { namespace Gfx {
struct DescriptorBinding { struct DescriptorBinding {
uint32 binding = 0; uint32 binding = 0;
SeDescriptorType descriptorType = SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER; SeDescriptorType descriptorType = SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
SeImageViewType textureType = SE_IMAGE_VIEW_TYPE_2D; SeImageViewType textureType = SE_IMAGE_VIEW_TYPE_2D;
uint32 descriptorCount = 1; uint32 descriptorCount = 1;
SeDescriptorBindingFlags bindingFlags = 0; SeDescriptorBindingFlags bindingFlags = 0;
SeShaderStageFlags shaderStages = SE_SHADER_STAGE_ALL; SeShaderStageFlags shaderStages = SE_SHADER_STAGE_ALL;
Gfx::SeDescriptorAccessTypeFlags access = SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT; Gfx::SeDescriptorAccessTypeFlags access = SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT;
}; };
DECLARE_REF(DescriptorPool) DECLARE_REF(DescriptorPool)
DECLARE_REF(DescriptorSet) DECLARE_REF(DescriptorSet)
class DescriptorLayout { class DescriptorLayout {
public: public:
DescriptorLayout(const std::string &name); DescriptorLayout(const std::string& name);
DescriptorLayout(const DescriptorLayout &other); DescriptorLayout(const DescriptorLayout& other);
DescriptorLayout &operator=(const DescriptorLayout &other); DescriptorLayout& operator=(const DescriptorLayout& other);
virtual ~DescriptorLayout(); virtual ~DescriptorLayout();
void addDescriptorBinding(DescriptorBinding binding); void addDescriptorBinding(DescriptorBinding binding);
void reset(); void reset();
PDescriptorSet allocateDescriptorSet(); PDescriptorSet allocateDescriptorSet();
virtual void create() = 0; virtual void create() = 0;
constexpr const Array<DescriptorBinding> &getBindings() const { constexpr const Array<DescriptorBinding>& getBindings() const { return descriptorBindings; }
return descriptorBindings; constexpr uint32 getHash() const { return hash; }
} constexpr const std::string& getName() const { return name; }
constexpr uint32 getHash() const { return hash; }
constexpr const std::string &getName() const { return name; }
protected: protected:
Array<DescriptorBinding> descriptorBindings; Array<DescriptorBinding> descriptorBindings;
ODescriptorPool pool; ODescriptorPool pool;
std::string name; std::string name;
uint32 hash = 0; uint32 hash = 0;
friend class PipelineLayout; friend class PipelineLayout;
friend class DescriptorPool; friend class DescriptorPool;
}; };
DEFINE_REF(DescriptorLayout) DEFINE_REF(DescriptorLayout)
DECLARE_REF(DescriptorSet) DECLARE_REF(DescriptorSet)
class DescriptorPool { class DescriptorPool {
public: public:
DescriptorPool(); DescriptorPool();
virtual ~DescriptorPool(); virtual ~DescriptorPool();
virtual PDescriptorSet allocateDescriptorSet() = 0; virtual PDescriptorSet allocateDescriptorSet() = 0;
virtual void reset() = 0; virtual void reset() = 0;
}; };
DEFINE_REF(DescriptorPool) DEFINE_REF(DescriptorPool)
DECLARE_REF(UniformBuffer) DECLARE_REF(UniformBuffer)
@@ -57,54 +56,47 @@ DECLARE_REF(ShaderBuffer)
DECLARE_REF(Texture) DECLARE_REF(Texture)
DECLARE_REF(Sampler) DECLARE_REF(Sampler)
class DescriptorSet { class DescriptorSet {
public: public:
DescriptorSet(PDescriptorLayout layout); DescriptorSet(PDescriptorLayout layout);
virtual ~DescriptorSet(); virtual ~DescriptorSet();
virtual void writeChanges() = 0; virtual void writeChanges() = 0;
virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0; virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0;
virtual void updateBuffer(uint32 binding, PShaderBuffer ShaderBuffer) = 0; virtual void updateBuffer(uint32 binding, PShaderBuffer ShaderBuffer) = 0;
virtual void updateBuffer(uint32_t binding, uint32 index, virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) = 0;
Gfx::PShaderBuffer uniformBuffer) = 0; virtual void updateSampler(uint32 binding, PSampler sampler) = 0;
virtual void updateSampler(uint32 binding, PSampler sampler) = 0; virtual void updateTexture(uint32 binding, PTexture texture, PSampler samplerState = nullptr) = 0;
virtual void updateTexture(uint32 binding, PTexture texture, virtual void updateTextureArray(uint32_t binding, Array<PTexture> texture) = 0;
PSampler samplerState = nullptr) = 0; bool operator<(PDescriptorSet other);
virtual void updateTextureArray(uint32_t binding,
Array<PTexture> texture) = 0;
bool operator<(PDescriptorSet other);
constexpr PDescriptorLayout getLayout() const { return layout; } constexpr PDescriptorLayout getLayout() const { return layout; }
constexpr const std::string &getName() const { return layout->getName(); } constexpr const std::string& getName() const { return layout->getName(); }
protected: protected:
PDescriptorLayout layout; PDescriptorLayout layout;
}; };
DEFINE_REF(DescriptorSet) DEFINE_REF(DescriptorSet)
DECLARE_REF(PipelineLayout) DECLARE_REF(PipelineLayout)
class PipelineLayout { class PipelineLayout {
public: public:
PipelineLayout(const std::string &name); PipelineLayout(const std::string& name);
PipelineLayout(const std::string &name, PPipelineLayout baseLayout); PipelineLayout(const std::string& name, PPipelineLayout baseLayout);
virtual ~PipelineLayout(); virtual ~PipelineLayout();
virtual void create() = 0; virtual void create() = 0;
void addDescriptorLayout(PDescriptorLayout layout); void addDescriptorLayout(PDescriptorLayout layout);
void addPushConstants(const SePushConstantRange &pushConstants); void addPushConstants(const SePushConstantRange& pushConstants);
constexpr uint32 getHash() const { return layoutHash; } constexpr uint32 getHash() const { return layoutHash; }
constexpr const Map<std::string, PDescriptorLayout> &getLayouts() const { constexpr const Map<std::string, PDescriptorLayout>& getLayouts() const { return descriptorSetLayouts; }
return descriptorSetLayouts; constexpr uint32 findParameter(const std::string& param) const { return parameterMapping[param]; }
} void addMapping(Map<std::string, uint32> mapping);
constexpr uint32 findParameter(const std::string &param) const { constexpr std::string getName() const { return name; };
return parameterMapping[param];
}
void addMapping(Map<std::string, uint32> mapping);
constexpr std::string getName() const { return name; };
protected: protected:
uint32 layoutHash = 0; uint32 layoutHash = 0;
Map<std::string, PDescriptorLayout> descriptorSetLayouts; Map<std::string, PDescriptorLayout> descriptorSetLayouts;
Map<std::string, uint32> parameterMapping; Map<std::string, uint32> parameterMapping;
Array<SePushConstantRange> pushConstants; Array<SePushConstantRange> pushConstants;
std::string name; std::string name;
}; };
DEFINE_REF(PipelineLayout) DEFINE_REF(PipelineLayout)
} // namespace Gfx } // namespace Gfx
+107 -108
View File
@@ -4,113 +4,112 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Gfx; using namespace Seele::Gfx;
FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format) FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format) {
{ switch (format) {
switch(format) { case SE_FORMAT_R4G4_UNORM_PACK8:
case SE_FORMAT_R4G4_UNORM_PACK8: case SE_FORMAT_R8_UNORM:
case SE_FORMAT_R8_UNORM: case SE_FORMAT_R8_SNORM:
case SE_FORMAT_R8_SNORM: case SE_FORMAT_R8_USCALED:
case SE_FORMAT_R8_USCALED: case SE_FORMAT_R8_SSCALED:
case SE_FORMAT_R8_SSCALED: case SE_FORMAT_R8_UINT:
case SE_FORMAT_R8_UINT: case SE_FORMAT_R8_SINT:
case SE_FORMAT_R8_SINT: case SE_FORMAT_R8_SRGB:
case SE_FORMAT_R8_SRGB: return FormatCompatibilityInfo{
return FormatCompatibilityInfo { .blockSize = 1,
.blockSize = 1, .blockExtent = UVector(1, 1, 1),
.blockExtent = UVector(1, 1, 1), .texelsPerBlock = 1,
.texelsPerBlock = 1, };
}; case SE_FORMAT_R10X6_UNORM_PACK16:
case SE_FORMAT_R10X6_UNORM_PACK16: case SE_FORMAT_R12X4_UNORM_PACK16:
case SE_FORMAT_R12X4_UNORM_PACK16: // case SE_FORMAT_A4R4G4B4_UNORM_PACK16:
//case SE_FORMAT_A4R4G4B4_UNORM_PACK16: // case SE_FORMAT_A4B4G4R4_UNORM_PACK16:
//case SE_FORMAT_A4B4G4R4_UNORM_PACK16: case SE_FORMAT_R4G4B4A4_UNORM_PACK16:
case SE_FORMAT_R4G4B4A4_UNORM_PACK16: case SE_FORMAT_B4G4R4A4_UNORM_PACK16:
case SE_FORMAT_B4G4R4A4_UNORM_PACK16: case SE_FORMAT_R5G6B5_UNORM_PACK16:
case SE_FORMAT_R5G6B5_UNORM_PACK16: case SE_FORMAT_B5G6R5_UNORM_PACK16:
case SE_FORMAT_B5G6R5_UNORM_PACK16: case SE_FORMAT_R5G5B5A1_UNORM_PACK16:
case SE_FORMAT_R5G5B5A1_UNORM_PACK16: case SE_FORMAT_B5G5R5A1_UNORM_PACK16:
case SE_FORMAT_B5G5R5A1_UNORM_PACK16: case SE_FORMAT_A1R5G5B5_UNORM_PACK16:
case SE_FORMAT_A1R5G5B5_UNORM_PACK16: case SE_FORMAT_R8G8_UNORM:
case SE_FORMAT_R8G8_UNORM: case SE_FORMAT_R8G8_SNORM:
case SE_FORMAT_R8G8_SNORM: case SE_FORMAT_R8G8_USCALED:
case SE_FORMAT_R8G8_USCALED: case SE_FORMAT_R8G8_SSCALED:
case SE_FORMAT_R8G8_SSCALED: case SE_FORMAT_R8G8_UINT:
case SE_FORMAT_R8G8_UINT: case SE_FORMAT_R8G8_SINT:
case SE_FORMAT_R8G8_SINT: case SE_FORMAT_R8G8_SRGB:
case SE_FORMAT_R8G8_SRGB: case SE_FORMAT_R16_UNORM:
case SE_FORMAT_R16_UNORM: case SE_FORMAT_R16_SNORM:
case SE_FORMAT_R16_SNORM: case SE_FORMAT_R16_USCALED:
case SE_FORMAT_R16_USCALED: case SE_FORMAT_R16_SSCALED:
case SE_FORMAT_R16_SSCALED: case SE_FORMAT_R16_UINT:
case SE_FORMAT_R16_UINT: case SE_FORMAT_R16_SINT:
case SE_FORMAT_R16_SINT: case SE_FORMAT_R16_SFLOAT:
case SE_FORMAT_R16_SFLOAT: return FormatCompatibilityInfo{
return FormatCompatibilityInfo { .blockSize = 2,
.blockSize = 2, .blockExtent = UVector(1, 1, 1),
.blockExtent = UVector(1, 1, 1), .texelsPerBlock = 1,
.texelsPerBlock = 1, };
}; case SE_FORMAT_BC7_UNORM_BLOCK:
case SE_FORMAT_BC7_UNORM_BLOCK: case SE_FORMAT_BC7_SRGB_BLOCK:
case SE_FORMAT_BC7_SRGB_BLOCK: return FormatCompatibilityInfo{
return FormatCompatibilityInfo { .blockSize = 16,
.blockSize = 16, .blockExtent = UVector(4, 4, 1),
.blockExtent = UVector(4, 4, 1), .texelsPerBlock = 16,
.texelsPerBlock = 16, };
}; case SE_FORMAT_R10X6G10X6_UNORM_2PACK16:
case SE_FORMAT_R10X6G10X6_UNORM_2PACK16: case SE_FORMAT_R12X4G12X4_UNORM_2PACK16:
case SE_FORMAT_R12X4G12X4_UNORM_2PACK16: // case SE_FORMAT_R16G16_S10_5_NV:
//case SE_FORMAT_R16G16_S10_5_NV: case SE_FORMAT_R8G8B8A8_UNORM:
case SE_FORMAT_R8G8B8A8_UNORM: case SE_FORMAT_R8G8B8A8_SNORM:
case SE_FORMAT_R8G8B8A8_SNORM: case SE_FORMAT_R8G8B8A8_USCALED:
case SE_FORMAT_R8G8B8A8_USCALED: case SE_FORMAT_R8G8B8A8_SSCALED:
case SE_FORMAT_R8G8B8A8_SSCALED: case SE_FORMAT_R8G8B8A8_UINT:
case SE_FORMAT_R8G8B8A8_UINT: case SE_FORMAT_R8G8B8A8_SINT:
case SE_FORMAT_R8G8B8A8_SINT: case SE_FORMAT_R8G8B8A8_SRGB:
case SE_FORMAT_R8G8B8A8_SRGB: case SE_FORMAT_B8G8R8A8_UNORM:
case SE_FORMAT_B8G8R8A8_UNORM: case SE_FORMAT_B8G8R8A8_SNORM:
case SE_FORMAT_B8G8R8A8_SNORM: case SE_FORMAT_B8G8R8A8_USCALED:
case SE_FORMAT_B8G8R8A8_USCALED: case SE_FORMAT_B8G8R8A8_SSCALED:
case SE_FORMAT_B8G8R8A8_SSCALED: case SE_FORMAT_B8G8R8A8_UINT:
case SE_FORMAT_B8G8R8A8_UINT: case SE_FORMAT_B8G8R8A8_SINT:
case SE_FORMAT_B8G8R8A8_SINT: case SE_FORMAT_B8G8R8A8_SRGB:
case SE_FORMAT_B8G8R8A8_SRGB: case SE_FORMAT_A8B8G8R8_UNORM_PACK32:
case SE_FORMAT_A8B8G8R8_UNORM_PACK32: case SE_FORMAT_A8B8G8R8_SNORM_PACK32:
case SE_FORMAT_A8B8G8R8_SNORM_PACK32: case SE_FORMAT_A8B8G8R8_USCALED_PACK32:
case SE_FORMAT_A8B8G8R8_USCALED_PACK32: case SE_FORMAT_A8B8G8R8_SSCALED_PACK32:
case SE_FORMAT_A8B8G8R8_SSCALED_PACK32: case SE_FORMAT_A8B8G8R8_UINT_PACK32:
case SE_FORMAT_A8B8G8R8_UINT_PACK32: case SE_FORMAT_A8B8G8R8_SINT_PACK32:
case SE_FORMAT_A8B8G8R8_SINT_PACK32: case SE_FORMAT_A8B8G8R8_SRGB_PACK32:
case SE_FORMAT_A8B8G8R8_SRGB_PACK32: case SE_FORMAT_A2R10G10B10_UNORM_PACK32:
case SE_FORMAT_A2R10G10B10_UNORM_PACK32: case SE_FORMAT_A2R10G10B10_SNORM_PACK32:
case SE_FORMAT_A2R10G10B10_SNORM_PACK32: case SE_FORMAT_A2R10G10B10_USCALED_PACK32:
case SE_FORMAT_A2R10G10B10_USCALED_PACK32: case SE_FORMAT_A2R10G10B10_SSCALED_PACK32:
case SE_FORMAT_A2R10G10B10_SSCALED_PACK32: case SE_FORMAT_A2R10G10B10_UINT_PACK32:
case SE_FORMAT_A2R10G10B10_UINT_PACK32: case SE_FORMAT_A2R10G10B10_SINT_PACK32:
case SE_FORMAT_A2R10G10B10_SINT_PACK32: case SE_FORMAT_A2B10G10R10_UNORM_PACK32:
case SE_FORMAT_A2B10G10R10_UNORM_PACK32: case SE_FORMAT_A2B10G10R10_SNORM_PACK32:
case SE_FORMAT_A2B10G10R10_SNORM_PACK32: case SE_FORMAT_A2B10G10R10_USCALED_PACK32:
case SE_FORMAT_A2B10G10R10_USCALED_PACK32: case SE_FORMAT_A2B10G10R10_SSCALED_PACK32:
case SE_FORMAT_A2B10G10R10_SSCALED_PACK32: case SE_FORMAT_A2B10G10R10_UINT_PACK32:
case SE_FORMAT_A2B10G10R10_UINT_PACK32: case SE_FORMAT_A2B10G10R10_SINT_PACK32:
case SE_FORMAT_A2B10G10R10_SINT_PACK32: case SE_FORMAT_R16G16_UNORM:
case SE_FORMAT_R16G16_UNORM: case SE_FORMAT_R16G16_SNORM:
case SE_FORMAT_R16G16_SNORM: case SE_FORMAT_R16G16_USCALED:
case SE_FORMAT_R16G16_USCALED: case SE_FORMAT_R16G16_SSCALED:
case SE_FORMAT_R16G16_SSCALED: case SE_FORMAT_R16G16_UINT:
case SE_FORMAT_R16G16_UINT: case SE_FORMAT_R16G16_SINT:
case SE_FORMAT_R16G16_SINT: case SE_FORMAT_R16G16_SFLOAT:
case SE_FORMAT_R16G16_SFLOAT: case SE_FORMAT_R32_UINT:
case SE_FORMAT_R32_UINT: case SE_FORMAT_R32_SINT:
case SE_FORMAT_R32_SINT: case SE_FORMAT_R32_SFLOAT:
case SE_FORMAT_R32_SFLOAT: case SE_FORMAT_B10G11R11_UFLOAT_PACK32:
case SE_FORMAT_B10G11R11_UFLOAT_PACK32: case SE_FORMAT_E5B9G9R9_UFLOAT_PACK32:
case SE_FORMAT_E5B9G9R9_UFLOAT_PACK32: return FormatCompatibilityInfo{
return FormatCompatibilityInfo{ .blockSize = 4,
.blockSize = 4, .blockExtent = Vector(1, 1, 1),
.blockExtent = Vector(1, 1, 1), .texelsPerBlock = 1,
.texelsPerBlock = 1, };
}; default:
default: throw new std::logic_error("not yet implemented");
throw new std::logic_error("not yet implemented");
} }
} }
File diff suppressed because it is too large Load Diff
+3 -8
View File
@@ -1,14 +1,9 @@
#include "Graphics.h" #include "Graphics.h"
#include "Shader.h" #include "Shader.h"
#include "Graphics.h"
using namespace Seele::Gfx; using namespace Seele::Gfx;
Graphics::Graphics() Graphics::Graphics() { shaderCompiler = new ShaderCompiler(this); }
{
shaderCompiler = new ShaderCompiler(this);
}
Graphics::~Graphics() Graphics::~Graphics() {}
{
}
+24 -31
View File
@@ -1,14 +1,13 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Initializer.h"
#include "Resources.h"
#include "RenderTarget.h"
#include "Containers/Array.h" #include "Containers/Array.h"
#include "Initializer.h"
#include "MinimalEngine.h"
#include "RenderTarget.h"
#include "Resources.h"
namespace Seele
{ namespace Seele {
namespace Gfx namespace Gfx {
{
DECLARE_REF(Window) DECLARE_REF(Window)
DECLARE_REF(Viewport) DECLARE_REF(Viewport)
DECLARE_REF(ShaderCompiler) DECLARE_REF(ShaderCompiler)
@@ -33,25 +32,18 @@ DECLARE_REF(RenderCommand)
DECLARE_REF(ComputeCommand) DECLARE_REF(ComputeCommand)
DECLARE_REF(BottomLevelAS) DECLARE_REF(BottomLevelAS)
DECLARE_REF(TopLevelAS) DECLARE_REF(TopLevelAS)
class Graphics class Graphics {
{ public:
public:
Graphics(); Graphics();
virtual ~Graphics(); virtual ~Graphics();
virtual void init(GraphicsInitializer initializer) = 0; virtual void init(GraphicsInitializer initializer) = 0;
const QueueFamilyMapping getFamilyMapping() const const QueueFamilyMapping getFamilyMapping() const { return queueMapping; }
{
return queueMapping;
}
PShaderCompiler getShaderCompiler() PShaderCompiler getShaderCompiler() { return shaderCompiler; }
{
return shaderCompiler;
}
virtual OWindow createWindow(const WindowCreateInfo &createInfo) = 0; virtual OWindow createWindow(const WindowCreateInfo& createInfo) = 0;
virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo &createInfo) = 0; virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo& createInfo) = 0;
virtual ORenderPass createRenderPass(RenderTargetLayout layout, Array<SubPassDependency> dependencies, PViewport renderArea) = 0; virtual ORenderPass createRenderPass(RenderTargetLayout layout, Array<SubPassDependency> dependencies, PViewport renderArea) = 0;
virtual void beginRenderPass(PRenderPass renderPass) = 0; virtual void beginRenderPass(PRenderPass renderPass) = 0;
@@ -61,13 +53,13 @@ public:
virtual void executeCommands(Array<ORenderCommand> commands) = 0; virtual void executeCommands(Array<ORenderCommand> commands) = 0;
virtual void executeCommands(Array<OComputeCommand> commands) = 0; virtual void executeCommands(Array<OComputeCommand> commands) = 0;
virtual OTexture2D createTexture2D(const TextureCreateInfo &createInfo) = 0; virtual OTexture2D createTexture2D(const TextureCreateInfo& createInfo) = 0;
virtual OTexture3D createTexture3D(const TextureCreateInfo &createInfo) = 0; virtual OTexture3D createTexture3D(const TextureCreateInfo& createInfo) = 0;
virtual OTextureCube createTextureCube(const TextureCreateInfo &createInfo) = 0; virtual OTextureCube createTextureCube(const TextureCreateInfo& createInfo) = 0;
virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) = 0; virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) = 0;
virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) = 0; virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) = 0;
virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) = 0; virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) = 0;
virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) = 0; virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) = 0;
virtual ORenderCommand createRenderCommand(const std::string& name = "") = 0; virtual ORenderCommand createRenderCommand(const std::string& name = "") = 0;
virtual OComputeCommand createComputeCommand(const std::string& name = "") = 0; virtual OComputeCommand createComputeCommand(const std::string& name = "") = 0;
@@ -82,8 +74,8 @@ public:
virtual PComputePipeline createComputePipeline(ComputePipelineCreateInfo createInfo) = 0; virtual PComputePipeline createComputePipeline(ComputePipelineCreateInfo createInfo) = 0;
virtual OSampler createSampler(const SamplerCreateInfo& createInfo) = 0; virtual OSampler createSampler(const SamplerCreateInfo& createInfo) = 0;
virtual ODescriptorLayout createDescriptorLayout(const std::string& name = "") = 0; virtual ODescriptorLayout createDescriptorLayout(const std::string& name = "") = 0;
virtual OPipelineLayout createPipelineLayout(const std::string& name = "", PPipelineLayout baseLayout = nullptr) = 0; virtual OPipelineLayout createPipelineLayout(const std::string& name = "", PPipelineLayout baseLayout = nullptr) = 0;
virtual OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) = 0; virtual OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) = 0;
@@ -94,7 +86,8 @@ public:
// Ray Tracing // Ray Tracing
virtual OBottomLevelAS createBottomLevelAccelerationStructure(const BottomLevelASCreateInfo& createInfo) = 0; virtual OBottomLevelAS createBottomLevelAccelerationStructure(const BottomLevelASCreateInfo& createInfo) = 0;
virtual OTopLevelAS createTopLevelAccelerationStructure(const TopLevelASCreateInfo& createInfo) = 0; virtual OTopLevelAS createTopLevelAccelerationStructure(const TopLevelASCreateInfo& createInfo) = 0;
protected:
protected:
QueueFamilyMapping queueMapping; QueueFamilyMapping queueMapping;
OShaderCompiler shaderCompiler; OShaderCompiler shaderCompiler;
bool meshShadingEnabled = false; bool meshShadingEnabled = false;
+223 -256
View File
@@ -1,266 +1,233 @@
#pragma once #pragma once
#include "Enums.h"
#include "Containers/Map.h" #include "Containers/Map.h"
#include "Enums.h"
#include "Math/Math.h" #include "Math/Math.h"
#include "MinimalEngine.h"
#include "MeshData.h" #include "MeshData.h"
#include "MinimalEngine.h"
namespace Seele
{
struct GraphicsInitializer
{
const char* applicationName;
const char* engineName;
const char* windowLayoutFile;
/**
* layers defines the enabled Vulkan layers used in the instance,
* if ENABLE_VALIDATION is defined, standard validation is already enabled
* not yet implemented
*/
Array<const char*> layers;
Array<const char*> instanceExtensions;
Array<const char*> deviceExtensions;
void* windowHandle; namespace Seele {
GraphicsInitializer() struct GraphicsInitializer {
: applicationName("SeeleEngine") const char* applicationName;
, engineName("SeeleEngine") const char* engineName;
, windowLayoutFile(nullptr) const char* windowLayoutFile;
, layers{ "VK_LAYER_LUNARG_monitor" } /**
, instanceExtensions{} * layers defines the enabled Vulkan layers used in the instance,
, deviceExtensions{ "VK_KHR_swapchain" } * if ENABLE_VALIDATION is defined, standard validation is already enabled
, windowHandle(nullptr) * not yet implemented
{ */
} Array<const char*> layers;
}; Array<const char*> instanceExtensions;
struct WindowCreateInfo Array<const char*> deviceExtensions;
{
int32 width;
int32 height;
const char* title;
Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM;
void* windowHandle;
};
struct ViewportCreateInfo
{
URect dimensions;
float fieldOfView = 1.222f; // 70 deg
Gfx::SeSampleCountFlags numSamples;
};
// doesnt own the data, only proxy it
struct DataSource
{
uint64 size = 0;
uint64 offset = 0;
uint8* data = nullptr;
Gfx::QueueType owner = Gfx::QueueType::GRAPHICS;
};
struct TextureCreateInfo
{
DataSource sourceData = DataSource();
Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT;
uint32 width = 1;
uint32 height = 1;
uint32 depth = 1;
uint32 mipLevels = 1;
uint32 layers = 1;
uint32 elements = 1;
uint32 samples = 1;
Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
std::string name;
};
struct SamplerCreateInfo
{
Gfx::SeSamplerCreateFlags flags;
Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR;
Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR;
Gfx::SeSamplerMipmapMode mipmapMode = Gfx::SE_SAMPLER_MIPMAP_MODE_LINEAR;
Gfx::SeSamplerAddressMode addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
Gfx::SeSamplerAddressMode addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
Gfx::SeSamplerAddressMode addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
float mipLodBias = 0.0f;
uint32 anisotropyEnable = 0;
float maxAnisotropy = 0.0f;
uint32 compareEnable = 0;
Gfx::SeCompareOp compareOp = Gfx::SE_COMPARE_OP_NEVER;
float minLod = 0.0f;
float maxLod = 0.0f;
Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
uint32 unnormalizedCoordinates = 0;
std::string name;
};
struct VertexBufferCreateInfo
{
DataSource sourceData = DataSource();
// bytes per vertex
uint32 vertexSize = 0;
uint32 numVertices = 0;
std::string name = "Unnamed";
};
struct IndexBufferCreateInfo
{
DataSource sourceData = DataSource();
Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16;
std::string name = "Unnamed";
};
struct UniformBufferCreateInfo
{
DataSource sourceData = DataSource();
uint8 dynamic = 0;
std::string name = "Unnamed";
};
struct ShaderBufferCreateInfo
{
DataSource sourceData = DataSource();
uint64 numElements = 1;
uint8 dynamic = 0;
uint8 vertexBuffer = 0;
std::string name = "Unnamed";
};
DECLARE_NAME_REF(Gfx, PipelineLayout)
struct ShaderCreateInfo
{
std::string name; // Debug info
std::string mainModule;
Array<std::string> additionalModules;
std::string entryPoint;
Array<Pair<const char*, const char*>> typeParameter;
Map<const char*, const char*> defines;
Gfx::PPipelineLayout rootSignature;
};
struct VertexInputBinding
{
uint32 binding;
uint32 stride;
Gfx::SeVertexInputRate inputRate;
};
struct VertexInputAttribute
{
uint32 location;
uint32 binding;
Gfx::SeFormat format;
uint32 offset;
};
struct VertexInputStateCreateInfo
{
Array<VertexInputBinding> bindings;
Array<VertexInputAttribute> attributes;
};
DECLARE_REF(MaterialInstance)
namespace Gfx
{
struct SePushConstantRange
{
SeShaderStageFlags stageFlags;
uint32 offset;
uint32 size;
};
struct RasterizationState
{
uint32 depthClampEnable = 0;
uint32 rasterizerDiscardEnable = 0;
SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL;
SeCullModeFlags cullMode = Gfx::SE_CULL_MODE_BACK_BIT;
SeFrontFace frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE;
uint32 depthBiasEnable = 0;
float depthBiasConstantFactor = 0;
float depthBiasClamp = 0;
float depthBiasSlopeFactor = 0;
float lineWidth = 1.0;
};
struct MultisampleState
{
SeSampleCountFlags samples = 1;
uint32 sampleShadingEnable = 0;
float minSampleShading = 1;
uint8 alphaCoverageEnable = 0;
uint8 alphaToOneEnable = 0;
};
struct DepthStencilState
{
uint32 depthTestEnable = 1;
uint32 depthWriteEnable = 1;
SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER;
uint32 depthBoundsTestEnable = 0;
uint32 stencilTestEnable = 0;
SeStencilOp front = Gfx::SE_STENCIL_OP_ZERO;
SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO;
float minDepthBounds = 0.0f;
float maxDepthBounds = 1.0f;
};
struct ColorBlendState
{
struct BlendAttachment
{
uint32 blendEnable = 0;
SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp colorBlendOp = Gfx::SE_BLEND_OP_ADD;
SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD;
SeColorComponentFlags 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;
};
uint32 logicOpEnable = 0;
SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR;
uint32 attachmentCount = 0;
StaticArray<BlendAttachment, 16> blendAttachments;
StaticArray<float, 4> blendConstants = { 1.0f, 1.0f, 1.0f, 1.0f, };
};
DECLARE_REF(VertexInput) void* windowHandle;
DECLARE_REF(VertexShader) GraphicsInitializer()
DECLARE_REF(TaskShader) : applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), layers{"VK_LAYER_LUNARG_monitor"},
DECLARE_REF(MeshShader) instanceExtensions{}, deviceExtensions{"VK_KHR_swapchain"}, windowHandle(nullptr) {}
DECLARE_REF(FragmentShader) };
DECLARE_REF(ComputeShader) struct WindowCreateInfo {
DECLARE_REF(RenderPass) int32 width;
DECLARE_REF(PipelineLayout) int32 height;
struct LegacyPipelineCreateInfo const char* title;
{ Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM;
SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; void* windowHandle;
PVertexInput vertexInput = nullptr; };
PVertexShader vertexShader = nullptr; struct ViewportCreateInfo {
PFragmentShader fragmentShader = nullptr; URect dimensions;
PRenderPass renderPass = nullptr; float fieldOfView = 1.222f; // 70 deg
PPipelineLayout pipelineLayout = nullptr; Gfx::SeSampleCountFlags numSamples;
MultisampleState multisampleState; };
RasterizationState rasterizationState; // doesnt own the data, only proxy it
DepthStencilState depthStencilState; struct DataSource {
ColorBlendState colorBlend; uint64 size = 0;
}; uint64 offset = 0;
uint8* data = nullptr;
Gfx::QueueType owner = Gfx::QueueType::GRAPHICS;
};
struct TextureCreateInfo {
DataSource sourceData = DataSource();
Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT;
uint32 width = 1;
uint32 height = 1;
uint32 depth = 1;
uint32 mipLevels = 1;
uint32 layers = 1;
uint32 elements = 1;
uint32 samples = 1;
Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
std::string name;
};
struct SamplerCreateInfo {
Gfx::SeSamplerCreateFlags flags;
Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR;
Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR;
Gfx::SeSamplerMipmapMode mipmapMode = Gfx::SE_SAMPLER_MIPMAP_MODE_LINEAR;
Gfx::SeSamplerAddressMode addressModeU = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
Gfx::SeSamplerAddressMode addressModeV = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
Gfx::SeSamplerAddressMode addressModeW = Gfx::SE_SAMPLER_ADDRESS_MODE_REPEAT;
float mipLodBias = 0.0f;
uint32 anisotropyEnable = 0;
float maxAnisotropy = 0.0f;
uint32 compareEnable = 0;
Gfx::SeCompareOp compareOp = Gfx::SE_COMPARE_OP_NEVER;
float minLod = 0.0f;
float maxLod = 0.0f;
Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
uint32 unnormalizedCoordinates = 0;
std::string name;
};
struct VertexBufferCreateInfo {
DataSource sourceData = DataSource();
// bytes per vertex
uint32 vertexSize = 0;
uint32 numVertices = 0;
std::string name = "Unnamed";
};
struct IndexBufferCreateInfo {
DataSource sourceData = DataSource();
Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16;
std::string name = "Unnamed";
};
struct UniformBufferCreateInfo {
DataSource sourceData = DataSource();
uint8 dynamic = 0;
std::string name = "Unnamed";
};
struct ShaderBufferCreateInfo {
DataSource sourceData = DataSource();
uint64 numElements = 1;
uint8 dynamic = 0;
uint8 vertexBuffer = 0;
std::string name = "Unnamed";
};
DECLARE_NAME_REF(Gfx, PipelineLayout)
struct ShaderCreateInfo {
std::string name; // Debug info
std::string mainModule;
Array<std::string> additionalModules;
std::string entryPoint;
Array<Pair<const char*, const char*>> typeParameter;
Map<const char*, const char*> defines;
Gfx::PPipelineLayout rootSignature;
};
struct VertexInputBinding {
uint32 binding;
uint32 stride;
Gfx::SeVertexInputRate inputRate;
};
struct VertexInputAttribute {
uint32 location;
uint32 binding;
Gfx::SeFormat format;
uint32 offset;
};
struct VertexInputStateCreateInfo {
Array<VertexInputBinding> bindings;
Array<VertexInputAttribute> attributes;
};
DECLARE_REF(MaterialInstance)
DECLARE_REF(Mesh)
namespace Gfx {
struct SePushConstantRange {
SeShaderStageFlags stageFlags;
uint32 offset;
uint32 size;
};
struct RasterizationState {
uint32 depthClampEnable = 0;
uint32 rasterizerDiscardEnable = 0;
SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL;
SeCullModeFlags cullMode = Gfx::SE_CULL_MODE_BACK_BIT;
SeFrontFace frontFace = Gfx::SE_FRONT_FACE_COUNTER_CLOCKWISE;
uint32 depthBiasEnable = 0;
float depthBiasConstantFactor = 0;
float depthBiasClamp = 0;
float depthBiasSlopeFactor = 0;
float lineWidth = 1.0;
};
struct MultisampleState {
SeSampleCountFlags samples = 1;
uint32 sampleShadingEnable = 0;
float minSampleShading = 1;
uint8 alphaCoverageEnable = 0;
uint8 alphaToOneEnable = 0;
};
struct DepthStencilState {
uint32 depthTestEnable = 1;
uint32 depthWriteEnable = 1;
SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER;
uint32 depthBoundsTestEnable = 0;
uint32 stencilTestEnable = 0;
SeStencilOp front = Gfx::SE_STENCIL_OP_ZERO;
SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO;
float minDepthBounds = 0.0f;
float maxDepthBounds = 1.0f;
};
struct ColorBlendState {
struct BlendAttachment {
uint32 blendEnable = 0;
SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp colorBlendOp = Gfx::SE_BLEND_OP_ADD;
SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD;
SeColorComponentFlags 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;
};
uint32 logicOpEnable = 0;
SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR;
uint32 attachmentCount = 0;
StaticArray<BlendAttachment, 16> blendAttachments;
StaticArray<float, 4> blendConstants = {
1.0f,
1.0f,
1.0f,
1.0f,
};
};
struct MeshPipelineCreateInfo DECLARE_REF(VertexInput)
{ DECLARE_REF(VertexShader)
PTaskShader taskShader = nullptr; DECLARE_REF(TaskShader)
PMeshShader meshShader = nullptr; DECLARE_REF(MeshShader)
PFragmentShader fragmentShader = nullptr; DECLARE_REF(FragmentShader)
PRenderPass renderPass = nullptr; DECLARE_REF(ComputeShader)
PPipelineLayout pipelineLayout = nullptr; DECLARE_REF(RenderPass)
MultisampleState multisampleState; DECLARE_REF(PipelineLayout)
RasterizationState rasterizationState; struct LegacyPipelineCreateInfo {
DepthStencilState depthStencilState; SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
ColorBlendState colorBlend; PVertexInput vertexInput = nullptr;
}; PVertexShader vertexShader = nullptr;
struct ComputePipelineCreateInfo PFragmentShader fragmentShader = nullptr;
{ PRenderPass renderPass = nullptr;
Gfx::PComputeShader computeShader = nullptr; PPipelineLayout pipelineLayout = nullptr;
Gfx::PPipelineLayout pipelineLayout = nullptr; MultisampleState multisampleState;
}; RasterizationState rasterizationState;
DECLARE_REF(ShaderBuffer) DepthStencilState depthStencilState;
struct BottomLevelASCreateInfo ColorBlendState colorBlend;
{ };
PShaderBuffer positionBuffer;
PShaderBuffer indexBuffer;
MeshData meshData;
PMaterialInstance material;
uint64 verticesOffset;
uint64 indicesOffset;
};
struct TopLevelASCreateInfo
{
}; struct MeshPipelineCreateInfo {
} // namespace Gfx PTaskShader taskShader = nullptr;
PMeshShader meshShader = nullptr;
PFragmentShader fragmentShader = nullptr;
PRenderPass renderPass = nullptr;
PPipelineLayout pipelineLayout = nullptr;
MultisampleState multisampleState;
RasterizationState rasterizationState;
DepthStencilState depthStencilState;
ColorBlendState colorBlend;
};
struct ComputePipelineCreateInfo {
Gfx::PComputeShader computeShader = nullptr;
Gfx::PPipelineLayout pipelineLayout = nullptr;
};
DECLARE_REF(ShaderBuffer)
struct BottomLevelASCreateInfo {
PMesh mesh;
};
struct TopLevelASCreateInfo {};
} // namespace Gfx
} // namespace Seele } // namespace Seele
+6 -11
View File
@@ -1,19 +1,15 @@
#include "Mesh.h" #include "Mesh.h"
#include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h" #include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
using namespace Seele; using namespace Seele;
Mesh::Mesh() Mesh::Mesh() {}
{
}
Mesh::~Mesh() Mesh::~Mesh() {}
{
}
void Mesh::save(ArchiveBuffer& buffer) const void Mesh::save(ArchiveBuffer& buffer) const {
{
Serialization::save(buffer, transform); Serialization::save(buffer, transform);
Serialization::save(buffer, vertexData->getTypeName()); Serialization::save(buffer, vertexData->getTypeName());
Serialization::save(buffer, vertexCount); Serialization::save(buffer, vertexCount);
@@ -24,8 +20,7 @@ void Mesh::save(ArchiveBuffer& buffer) const
vertexData->serializeMesh(id, vertexCount, buffer); vertexData->serializeMesh(id, vertexCount, buffer);
} }
void Mesh::load(ArchiveBuffer& buffer) void Mesh::load(ArchiveBuffer& buffer) {
{
std::string typeName; std::string typeName;
Serialization::load(buffer, transform); Serialization::load(buffer, transform);
Serialization::load(buffer, typeName); Serialization::load(buffer, typeName);
+13 -20
View File
@@ -1,13 +1,12 @@
#pragma once #pragma once
#include "Asset/MaterialInstanceAsset.h" #include "Asset/MaterialInstanceAsset.h"
#include "VertexData.h"
#include "Graphics/Buffer.h" #include "Graphics/Buffer.h"
#include "VertexData.h"
namespace Seele
{ namespace Seele {
class Mesh class Mesh {
{ public:
public:
Mesh(); Mesh();
~Mesh(); ~Mesh();
@@ -21,21 +20,15 @@ public:
Array<Meshlet> meshlets; Array<Meshlet> meshlets;
void save(ArchiveBuffer& buffer) const; void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer); void load(ArchiveBuffer& buffer);
private:
private:
}; };
DEFINE_REF(Mesh) DEFINE_REF(Mesh)
namespace Serialization namespace Serialization {
{ template <> void save(ArchiveBuffer& buffer, const OMesh& ptr) { ptr->save(buffer); }
template<> template <> void load(ArchiveBuffer& buffer, OMesh& ptr) {
void save(ArchiveBuffer& buffer, const OMesh& ptr) ptr = new Mesh();
{ ptr->load(buffer);
ptr->save(buffer); }
}
template<>
void load(ArchiveBuffer& buffer, OMesh& ptr)
{
ptr = new Mesh();
ptr->load(buffer);
}
} // namespace Serialization } // namespace Serialization
} // namespace Seele } // namespace Seele
+4 -7
View File
@@ -1,18 +1,15 @@
#pragma once #pragma once
#include "Math/AABB.h" #include "Math/AABB.h"
namespace Seele namespace Seele {
{ struct MeshData {
struct MeshData
{
AABB bounding; AABB bounding;
uint32 numMeshlets = 0; uint32 numMeshlets = 0;
uint32 meshletOffset = 0; uint32 meshletOffset = 0;
uint32 firstIndex = 0; uint32 firstIndex = 0;
uint32 numIndices = 0; uint32 numIndices = 0;
}; };
struct InstanceData struct InstanceData {
{
Matrix4 transformMatrix; Matrix4 transformMatrix;
Matrix4 inverseTransformMatrix; Matrix4 inverseTransformMatrix;
}; };
} } // namespace Seele
+43 -72
View File
@@ -1,29 +1,26 @@
#include "Meshlet.h" #include "Meshlet.h"
#include "Containers/Map.h"
#include "Containers/List.h" #include "Containers/List.h"
#include "Containers/Map.h"
#include "Containers/Set.h" #include "Containers/Set.h"
#include <iostream> #include <iostream>
using namespace Seele; using namespace Seele;
struct AdjacencyInfo struct AdjacencyInfo {
{
Array<uint32> trianglesPerVertex; Array<uint32> trianglesPerVertex;
Array<uint32> indexBufferOffset; Array<uint32> indexBufferOffset;
Array<uint32> triangleData; Array<uint32> triangleData;
}; };
void buildAdjacency(const uint32 numVerts, const Array<uint32>& indices, AdjacencyInfo& info) void buildAdjacency(const uint32 numVerts, const Array<uint32>& indices, AdjacencyInfo& info) {
{
info.trianglesPerVertex.resize(numVerts, 0); info.trianglesPerVertex.resize(numVerts, 0);
for (size_t i = 0; i < indices.size(); ++i) for (size_t i = 0; i < indices.size(); ++i) {
{
info.trianglesPerVertex[indices[i]]++; info.trianglesPerVertex[indices[i]]++;
} }
uint32 triangleOffset = 0; uint32 triangleOffset = 0;
info.indexBufferOffset.resize(numVerts, 0); info.indexBufferOffset.resize(numVerts, 0);
for (size_t j = 0; j < numVerts; ++j) for (size_t j = 0; j < numVerts; ++j) {
{
info.indexBufferOffset[j] = triangleOffset; info.indexBufferOffset[j] = triangleOffset;
triangleOffset += info.trianglesPerVertex[j]; triangleOffset += info.trianglesPerVertex[j];
} }
@@ -31,8 +28,7 @@ void buildAdjacency(const uint32 numVerts, const Array<uint32>& indices, Adjacen
uint32 numTriangles = indices.size() / 3; uint32 numTriangles = indices.size() / 3;
info.triangleData.resize(triangleOffset); info.triangleData.resize(triangleOffset);
Array<uint32> offsets = info.indexBufferOffset; Array<uint32> offsets = info.indexBufferOffset;
for (uint32 k = 0; k < numTriangles; ++k) for (uint32 k = 0; k < numTriangles; ++k) {
{
int a = indices[k * 3]; int a = indices[k * 3];
int b = indices[k * 3 + 1]; int b = indices[k * 3 + 1];
int c = indices[k * 3 + 2]; int c = indices[k * 3 + 2];
@@ -43,21 +39,16 @@ void buildAdjacency(const uint32 numVerts, const Array<uint32>& indices, Adjacen
} }
} }
int32 skipDeadEnd(const Array<uint32>& liveTriCount, List<uint32>& deadEndStack, uint32& cursor) int32 skipDeadEnd(const Array<uint32>& liveTriCount, List<uint32>& deadEndStack, uint32& cursor) {
{ while (!deadEndStack.empty()) {
while (!deadEndStack.empty())
{
uint32 vertIdx = deadEndStack.front(); uint32 vertIdx = deadEndStack.front();
deadEndStack.popFront(); deadEndStack.popFront();
if (liveTriCount[vertIdx] > 0) if (liveTriCount[vertIdx] > 0) {
{
return vertIdx; return vertIdx;
} }
} }
while (cursor < liveTriCount.size()) while (cursor < liveTriCount.size()) {
{ if (liveTriCount[cursor] > 0) {
if (liveTriCount[cursor] > 0)
{
return cursor; return cursor;
} }
++cursor; ++cursor;
@@ -65,35 +56,29 @@ int32 skipDeadEnd(const Array<uint32>& liveTriCount, List<uint32>& deadEndStack,
return -1; return -1;
} }
int32 getNextVertex(const uint32 cacheSize, const Array<uint32>& oneRing, const Array<uint32>& cacheTimeStamps, const uint32 timeStamp, const Array<uint32>& liveTriCount, List<uint32>& deadEndStack, uint32& cursor) int32 getNextVertex(const uint32 cacheSize, const Array<uint32>& oneRing, const Array<uint32>& cacheTimeStamps, const uint32 timeStamp,
{ const Array<uint32>& liveTriCount, List<uint32>& deadEndStack, uint32& cursor) {
uint32 bestCandidate = std::numeric_limits<uint32>::max(); uint32 bestCandidate = std::numeric_limits<uint32>::max();
int highestPriority = -1; int highestPriority = -1;
for (const uint32& vertIdx : oneRing) for (const uint32& vertIdx : oneRing) {
{ if (liveTriCount[vertIdx] > 0) {
if (liveTriCount[vertIdx] > 0)
{
int priority = 0; int priority = 0;
if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize) if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize) {
{
priority = timeStamp - cacheTimeStamps[vertIdx]; priority = timeStamp - cacheTimeStamps[vertIdx];
} }
if (priority > highestPriority) if (priority > highestPriority) {
{
highestPriority = priority; highestPriority = priority;
bestCandidate = vertIdx; bestCandidate = vertIdx;
} }
} }
} }
if(bestCandidate == std::numeric_limits<uint32>::max()) if (bestCandidate == std::numeric_limits<uint32>::max()) {
{
bestCandidate = skipDeadEnd(liveTriCount, deadEndStack, cursor); bestCandidate = skipDeadEnd(liveTriCount, deadEndStack, cursor);
} }
return bestCandidate; return bestCandidate;
} }
void tipsifyIndexBuffer(const Array<uint32>& indices, const uint32 numVerts, const uint32 cacheSize, Array<uint32>& outIndices) void tipsifyIndexBuffer(const Array<uint32>& indices, const uint32 numVerts, const uint32 cacheSize, Array<uint32>& outIndices) {
{
AdjacencyInfo adjacencyStruct; AdjacencyInfo adjacencyStruct;
buildAdjacency(numVerts, indices, adjacencyStruct); buildAdjacency(numVerts, indices, adjacencyStruct);
@@ -108,14 +93,12 @@ void tipsifyIndexBuffer(const Array<uint32>& indices, const uint32 numVerts, con
int32 curVert = 0; int32 curVert = 0;
uint32 timeStamp = cacheSize + 1; uint32 timeStamp = cacheSize + 1;
uint32 cursor = 1; uint32 cursor = 1;
while (curVert != -1) while (curVert != -1) {
{
Array<uint32> oneRing; Array<uint32> oneRing;
const uint32* startTriPointer = &adjacencyStruct.triangleData[0] + adjacencyStruct.indexBufferOffset[curVert]; const uint32* startTriPointer = &adjacencyStruct.triangleData[0] + adjacencyStruct.indexBufferOffset[curVert];
const uint32* endTriPointer = startTriPointer + adjacencyStruct.trianglesPerVertex[curVert]; const uint32* endTriPointer = startTriPointer + adjacencyStruct.trianglesPerVertex[curVert];
for (const uint32* it = startTriPointer; it != endTriPointer; ++it) for (const uint32* it = startTriPointer; it != endTriPointer; ++it) {
{
uint32 triangle = *it; uint32 triangle = *it;
if (emittedTriangles[triangle]) if (emittedTriangles[triangle])
@@ -156,22 +139,17 @@ void tipsifyIndexBuffer(const Array<uint32>& indices, const uint32 numVerts, con
} }
} }
struct Triangle struct Triangle {
{
StaticArray<uint32, 3> indices; StaticArray<uint32, 3> indices;
}; };
int findIndex(Meshlet &current, uint32 index) int findIndex(Meshlet& current, uint32 index) {
{ for (uint32 i = 0; i < current.numVertices; ++i) {
for (uint32 i = 0; i < current.numVertices; ++i) if (current.uniqueVertices[i] == index) {
{
if (current.uniqueVertices[i] == index)
{
return i; return i;
} }
} }
if (current.numVertices == Gfx::numVerticesPerMeshlet) if (current.numVertices == Gfx::numVerticesPerMeshlet) {
{
return -1; return -1;
} }
current.uniqueVertices[current.numVertices] = index; current.uniqueVertices[current.numVertices] = index;
@@ -179,8 +157,7 @@ int findIndex(Meshlet &current, uint32 index)
return current.numVertices++; return current.numVertices++;
} }
void completeMeshlet(Array<Meshlet> &meshlets, Meshlet &current) void completeMeshlet(Array<Meshlet>& meshlets, Meshlet& current) {
{
meshlets.add(current); meshlets.add(current);
current = { current = {
.boundingBox = AABB(), .boundingBox = AABB(),
@@ -189,14 +166,12 @@ void completeMeshlet(Array<Meshlet> &meshlets, Meshlet &current)
}; };
} }
bool addTriangle(const Array<Vector>& positions, Meshlet &current, Triangle& tri) bool addTriangle(const Array<Vector>& positions, Meshlet& current, Triangle& tri) {
{
int f1 = findIndex(current, tri.indices[0]); int f1 = findIndex(current, tri.indices[0]);
int f2 = findIndex(current, tri.indices[1]); int f2 = findIndex(current, tri.indices[1]);
int f3 = findIndex(current, tri.indices[2]); int f3 = findIndex(current, tri.indices[2]);
if (f1 == -1 || f2 == -1 || f3 == -1 || current.numPrimitives == Gfx::numPrimitivesPerMeshlet) if (f1 == -1 || f2 == -1 || f3 == -1 || current.numPrimitives == Gfx::numPrimitivesPerMeshlet) {
{
return false; return false;
} }
current.boundingBox.adjust(positions[tri.indices[0]]); current.boundingBox.adjust(positions[tri.indices[0]]);
@@ -209,36 +184,32 @@ bool addTriangle(const Array<Vector>& positions, Meshlet &current, Triangle& tri
return true; return true;
} }
void Meshlet::build(const Array<Vector> &positions, const Array<uint32> &indices, Array<Meshlet> &meshlets) void Meshlet::build(const Array<Vector>& positions, const Array<uint32>& indices, Array<Meshlet>& meshlets) {
{
Meshlet current = { Meshlet current = {
.numVertices = 0, .numVertices = 0,
.numPrimitives = 0, .numPrimitives = 0,
}; };
//Array<uint32> optimizedIndices = indices; // Array<uint32> optimizedIndices = indices;
//tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices); // tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices);
Array<Triangle> triangles(indices.size() / 3); Array<Triangle> triangles(indices.size() / 3);
for (size_t i = 0; i < triangles.size(); ++i) for (size_t i = 0; i < triangles.size(); ++i) {
{
triangles[i] = Triangle{ triangles[i] = Triangle{
.indices = { .indices =
indices[i * 3 + 0], {
indices[i * 3 + 1], indices[i * 3 + 0],
indices[i * 3 + 2], indices[i * 3 + 1],
}, indices[i * 3 + 2],
},
}; };
} }
while(!triangles.empty()) while (!triangles.empty()) {
{ if (!addTriangle(positions, current, triangles.back())) {
if (!addTriangle(positions, current, triangles.back()))
{
completeMeshlet(meshlets, current); completeMeshlet(meshlets, current);
addTriangle(positions, current, triangles.back()); addTriangle(positions, current, triangles.back());
} }
triangles.pop(); triangles.pop();
} }
if (current.numVertices > 0) if (current.numVertices > 0) {
{
completeMeshlet(meshlets, current); completeMeshlet(meshlets, current);
} }
} }
+5 -6
View File
@@ -1,13 +1,12 @@
#pragma once #pragma once
#include "Math/AABB.h"
#include "Graphics/Enums.h" #include "Graphics/Enums.h"
#include "Math/AABB.h"
namespace Seele
{ namespace Seele {
struct Meshlet struct Meshlet {
{
AABB boundingBox; AABB boundingBox;
uint32 uniqueVertices[Gfx::numVerticesPerMeshlet]; // unique vertiex indices in the vertex data uint32 uniqueVertices[Gfx::numVerticesPerMeshlet]; // unique vertiex indices in the vertex data
uint8 primitiveLayout[Gfx::numPrimitivesPerMeshlet * 3]; // indices into the uniqueVertices array, only uint8 needed uint8 primitiveLayout[Gfx::numPrimitivesPerMeshlet * 3]; // indices into the uniqueVertices array, only uint8 needed
uint32 numVertices; uint32 numVertices;
uint32 numPrimitives; uint32 numPrimitives;
+64 -64
View File
@@ -9,93 +9,93 @@
namespace Seele { namespace Seele {
namespace Metal { namespace Metal {
DECLARE_REF(Graphics) DECLARE_REF(Graphics)
class BufferAllocation : public CommandBoundResource class BufferAllocation : public CommandBoundResource {
{ public:
public: BufferAllocation(PGraphics graphics);
BufferAllocation(PGraphics graphics); virtual ~BufferAllocation();
virtual ~BufferAllocation(); MTL::Buffer* buffer = nullptr;
MTL::Buffer* buffer = nullptr; uint64 size = 0;
uint64 size = 0;
}; };
DECLARE_REF(BufferAllocation) DECLARE_REF(BufferAllocation)
class Buffer { class Buffer {
public: public:
Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic, const std::string& name); Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name);
virtual ~Buffer(); virtual ~Buffer();
MTL::Buffer *getHandle() const { return buffers[currentBuffer]->buffer; } MTL::Buffer* getHandle() const { return buffers[currentBuffer]->buffer; }
PBufferAllocation getAlloc() const { return buffers[currentBuffer]; } PBufferAllocation getAlloc() const { return buffers[currentBuffer]; }
uint64 getSize() const { return buffers[currentBuffer]->size; } uint64 getSize() const { return buffers[currentBuffer]->size; }
void *map(bool writeOnly = true); void* map(bool writeOnly = true);
void *mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly); void* mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly);
void unmap(); void unmap();
protected: protected:
PGraphics graphics; PGraphics graphics;
uint32 currentBuffer = 0; uint32 currentBuffer = 0;
Array<OBufferAllocation> buffers; Array<OBufferAllocation> buffers;
bool dynamic; bool dynamic;
std::string name; std::string name;
void rotateBuffer(uint64 size); void rotateBuffer(uint64 size);
void createBuffer(uint64 size, void* data); void createBuffer(uint64 size, void* data);
}; };
DEFINE_REF(Buffer) DEFINE_REF(Buffer)
class VertexBuffer : public Gfx::VertexBuffer, public Buffer { class VertexBuffer : public Gfx::VertexBuffer, public Buffer {
public: public:
VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo &createInfo); VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& createInfo);
virtual ~VertexBuffer(); virtual ~VertexBuffer();
virtual void updateRegion(DataSource update) override; virtual void updateRegion(DataSource update) override;
virtual void download(Array<uint8> &buffer) override; virtual void download(Array<uint8>& buffer) override;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; Gfx::SePipelineStageFlags dstStage) override;
}; };
DEFINE_REF(VertexBuffer) DEFINE_REF(VertexBuffer)
class IndexBuffer : public Gfx::IndexBuffer, public Buffer { class IndexBuffer : public Gfx::IndexBuffer, public Buffer {
public: public:
IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo &createInfo); IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& createInfo);
virtual ~IndexBuffer(); virtual ~IndexBuffer();
virtual void download(Array<uint8> &buffer) override; virtual void download(Array<uint8>& buffer) override;
protected:
// Inherited via QueueOwnedResource protected:
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; // Inherited via QueueOwnedResource
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) override;
}; };
DEFINE_REF(IndexBuffer) DEFINE_REF(IndexBuffer)
DEFINE_REF(IndexBuffer) DEFINE_REF(IndexBuffer)
class UniformBuffer : public Gfx::UniformBuffer, public Buffer { class UniformBuffer : public Gfx::UniformBuffer, public Buffer {
public: public:
UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &createInfo); UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& createInfo);
virtual ~UniformBuffer(); virtual ~UniformBuffer();
virtual bool updateContents(const DataSource &sourceData) override; virtual bool updateContents(const DataSource& sourceData) override;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; Gfx::SePipelineStageFlags dstStage) override;
}; };
DEFINE_REF(UniformBuffer) DEFINE_REF(UniformBuffer)
class ShaderBuffer : public Gfx::ShaderBuffer, public Buffer { class ShaderBuffer : public Gfx::ShaderBuffer, public Buffer {
public: public:
ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &createInfo); ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo);
virtual ~ShaderBuffer(); virtual ~ShaderBuffer();
virtual void rotateBuffer(uint64 size) override; virtual void rotateBuffer(uint64 size) override;
virtual void updateContents(const ShaderBufferCreateInfo &sourceData) override; virtual void updateContents(const ShaderBufferCreateInfo& sourceData) override;
virtual void *mapRegion(uint64 offset, uint64 size, bool writeOnly) override; virtual void* mapRegion(uint64 offset, uint64 size, bool writeOnly) override;
virtual void unmap() override; virtual void unmap() override;
protected: protected:
// Inherited via QueueOwnedResource // Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override; virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override; Gfx::SePipelineStageFlags dstStage) override;
}; };
DEFINE_REF(ShaderBuffer) DEFINE_REF(ShaderBuffer)
} // namespace Metal } // namespace Metal
+96 -75
View File
@@ -11,49 +11,44 @@ using namespace Seele;
using namespace Seele::Metal; using namespace Seele::Metal;
BufferAllocation::BufferAllocation(PGraphics graphics) BufferAllocation::BufferAllocation(PGraphics graphics)
: CommandBoundResource(graphics) : CommandBoundResource(graphics) {}
{}
BufferAllocation::~BufferAllocation() BufferAllocation::~BufferAllocation() {
{ if (buffer != nullptr) {
if(buffer != nullptr)
{
buffer->release(); buffer->release();
} }
} }
Buffer::Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name) Buffer::Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic,
: graphics(graphics) const std::string &name)
, dynamic(dynamic) : graphics(graphics), dynamic(dynamic), name(name) {
, name(name) {
createBuffer(size, data); createBuffer(size, data);
} }
Buffer::~Buffer() { Buffer::~Buffer() {
for (size_t i = 0; i < buffers.size(); ++i) { for (size_t i = 0; i < buffers.size(); ++i) {
//TODO // TODO
} }
} }
void* Buffer::map(bool) { return getHandle()->contents(); } void *Buffer::map(bool) { return getHandle()->contents(); }
void* Buffer::mapRegion(uint64 regionOffset, uint64, bool) { return (char*)getHandle()->contents() + regionOffset; } void *Buffer::mapRegion(uint64 regionOffset, uint64, bool) {
return (char *)getHandle()->contents() + regionOffset;
}
void Buffer::unmap() {} void Buffer::unmap() {}
void Buffer::rotateBuffer(uint64 size) void Buffer::rotateBuffer(uint64 size) {
{
size = std::max(getSize(), size); size = std::max(getSize(), size);
for(size_t i = 0; i < buffers.size(); ++i) for (size_t i = 0; i < buffers.size(); ++i) {
{ if (buffers[i]->isCurrentlyBound()) {
if(buffers[i]->isCurrentlyBound())
{
continue; continue;
} }
if(buffers[i]->size < size) if (buffers[i]->size < size) {
{
buffers[i]->buffer->release(); buffers[i]->buffer->release();
buffers[i]->buffer = graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); buffers[i]->buffer =
graphics->getDevice()->newBuffer(size, MTL::StorageModeShared);
buffers[i]->size = size; buffers[i]->size = size;
} }
currentBuffer = i; currentBuffer = i;
@@ -63,79 +58,106 @@ void Buffer::rotateBuffer(uint64 size)
currentBuffer = buffers.size() - 1; currentBuffer = buffers.size() - 1;
} }
void Buffer::createBuffer(uint64 size, void* data) void Buffer::createBuffer(uint64 size, void *data) {
{
buffers.add(new BufferAllocation(graphics)); buffers.add(new BufferAllocation(graphics));
if (data != nullptr) { if (data != nullptr) {
buffers.back()->buffer = graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared); buffers.back()->buffer =
graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared);
} else { } else {
buffers.back()->buffer = graphics->getDevice()->newBuffer(size, MTL::StorageModeShared); buffers.back()->buffer =
graphics->getDevice()->newBuffer(size, MTL::StorageModeShared);
} }
buffers.back()->buffer->setLabel(NS::String::string(name.c_str(), NS::ASCIIStringEncoding)); buffers.back()->buffer->setLabel(
NS::String::string(name.c_str(), NS::ASCIIStringEncoding));
} }
VertexBuffer::VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& createInfo) VertexBuffer::VertexBuffer(PGraphics graphics,
: Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices, createInfo.vertexSize, const VertexBufferCreateInfo &createInfo)
createInfo.sourceData.owner), : Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices,
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, false, createInfo.name) {} createInfo.vertexSize, createInfo.sourceData.owner),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, false, createInfo.name) {
}
VertexBuffer::~VertexBuffer() {} VertexBuffer::~VertexBuffer() {}
void VertexBuffer::updateRegion(DataSource update) { void VertexBuffer::updateRegion(DataSource update) {
void* data = getHandle()->contents(); void *data = getHandle()->contents();
std::memcpy((char*)data + update.offset, update.data, update.size); std::memcpy((char *)data + update.offset, update.data, update.size);
} }
void VertexBuffer::download(Array<uint8>& buffer) { void VertexBuffer::download(Array<uint8> &buffer) {
void* data = getHandle()->contents(); void *data = getHandle()->contents();
buffer.resize(getSize()); buffer.resize(getSize());
std::memcpy(buffer.data(), data, getSize()); std::memcpy(buffer.data(), data, getSize());
} }
void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) {
currentOwner = newOwner;
void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {
} }
IndexBuffer::IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& createInfo) void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
: Gfx::IndexBuffer(graphics->getFamilyMapping(), createInfo.sourceData.size, createInfo.indexType, Gfx::SePipelineStageFlags srcStage,
createInfo.sourceData.owner), Gfx::SeAccessFlags dstAccess,
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, false, createInfo.name) {} Gfx::SePipelineStageFlags dstStage) {}
IndexBuffer::IndexBuffer(PGraphics graphics,
const IndexBufferCreateInfo &createInfo)
: Gfx::IndexBuffer(graphics->getFamilyMapping(), createInfo.sourceData.size,
createInfo.indexType, createInfo.sourceData.owner),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, false, createInfo.name) {
}
IndexBuffer::~IndexBuffer() {} IndexBuffer::~IndexBuffer() {}
void IndexBuffer::download(Array<uint8>& buffer) { void IndexBuffer::download(Array<uint8> &buffer) {
void* data = getHandle()->contents(); void *data = getHandle()->contents();
buffer.resize(getSize()); buffer.resize(getSize());
std::memcpy(buffer.data(), data, getSize()); std::memcpy(buffer.data(), data, getSize());
} }
void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } void IndexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) {
currentOwner = newOwner;
}
void IndexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, void IndexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {} Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) {}
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),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, createInfo.dynamic, createInfo.name) {} Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, createInfo.dynamic,
createInfo.name) {}
UniformBuffer::~UniformBuffer() {} UniformBuffer::~UniformBuffer() {}
bool UniformBuffer::updateContents(const DataSource& sourceData) { bool UniformBuffer::updateContents(const DataSource &sourceData) {
void* data = getHandle()->contents(); void *data = getHandle()->contents();
std::memcpy((char*)data + sourceData.offset, sourceData.data, sourceData.size); std::memcpy((char *)data + sourceData.offset, sourceData.data,
sourceData.size);
return true; return true;
} }
void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } void UniformBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) {
currentOwner = newOwner;
}
void UniformBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, void UniformBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {} Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) {
}
ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo) ShaderBuffer::ShaderBuffer(PGraphics graphics,
: Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements, createInfo.sourceData), const ShaderBufferCreateInfo &createInfo)
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, createInfo.dynamic, createInfo.name) {} : Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements,
createInfo.sourceData),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, createInfo.dynamic,
createInfo.name) {}
ShaderBuffer::~ShaderBuffer() {} ShaderBuffer::~ShaderBuffer() {}
@@ -143,29 +165,28 @@ void ShaderBuffer::rotateBuffer(uint64 size) {
Metal::Buffer::rotateBuffer(size); Metal::Buffer::rotateBuffer(size);
} }
void ShaderBuffer::updateContents(const ShaderBufferCreateInfo& createInfo) { void ShaderBuffer::updateContents(const ShaderBufferCreateInfo &createInfo) {
Gfx::ShaderBuffer::updateContents(createInfo); Gfx::ShaderBuffer::updateContents(createInfo);
if(createInfo.sourceData.data == nullptr) if (createInfo.sourceData.data == nullptr) {
{
return; return;
} }
void* data = map(); void *data = map();
std::memcpy((char*)data + createInfo.sourceData.offset, createInfo.sourceData.data, createInfo.sourceData.size); std::memcpy((char *)data + createInfo.sourceData.offset,
createInfo.sourceData.data, createInfo.sourceData.size);
unmap(); unmap();
} }
void* ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) void *ShaderBuffer::mapRegion(uint64 offset, uint64 size, bool writeOnly) {
{
return Metal::Buffer::mapRegion(offset, size, writeOnly); return Metal::Buffer::mapRegion(offset, size, writeOnly);
} }
void ShaderBuffer::unmap() void ShaderBuffer::unmap() { Metal::Buffer::unmap(); }
{
Metal::Buffer::unmap(); void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) {
currentOwner = newOwner;
} }
void ShaderBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; } void ShaderBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
void ShaderBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SePipelineStageFlags dstStage) {}
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {}
+82 -86
View File
@@ -19,113 +19,109 @@ DECLARE_REF(IndexBuffer)
DECLARE_REF(GraphicsPipeline) DECLARE_REF(GraphicsPipeline)
DECLARE_REF(ComputePipeline) DECLARE_REF(ComputePipeline)
class Command { class Command {
public: public:
Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer); Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer);
~Command(); ~Command();
void beginRenderPass(PRenderPass renderPass); void beginRenderPass(PRenderPass renderPass);
void endRenderPass(); void endRenderPass();
void present(MTL::Drawable* drawable); void present(MTL::Drawable* drawable);
void end(PEvent signal); void end(PEvent signal);
void waitDeviceIdle(); void waitDeviceIdle();
void signalEvent(PEvent event); void signalEvent(PEvent event);
void waitForEvent(PEvent event); void waitForEvent(PEvent event);
MTL::RenderCommandEncoder* createRenderEncoder() { return parallelEncoder->renderCommandEncoder(); } MTL::RenderCommandEncoder* createRenderEncoder() { return parallelEncoder->renderCommandEncoder(); }
MTL::BlitCommandEncoder* getBlitEncoder() { MTL::BlitCommandEncoder* getBlitEncoder() {
assert(!parallelEncoder); assert(!parallelEncoder);
if(blitEncoder == nullptr) if (blitEncoder == nullptr) {
{ blitEncoder = cmdBuffer->blitCommandEncoder();
blitEncoder = cmdBuffer->blitCommandEncoder(); }
return blitEncoder;
} }
return blitEncoder; PEvent getCompletedEvent() const { return completed; }
} constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; }
PEvent getCompletedEvent() const { return completed; }
constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; }
private: private:
PGraphics graphics; PGraphics graphics;
OEvent completed; OEvent completed;
MTL::CommandBuffer* cmdBuffer; MTL::CommandBuffer* cmdBuffer;
MTL::ParallelRenderCommandEncoder* parallelEncoder = nullptr; MTL::ParallelRenderCommandEncoder* parallelEncoder = nullptr;
MTL::BlitCommandEncoder* blitEncoder = nullptr; MTL::BlitCommandEncoder* blitEncoder = nullptr;
}; };
DEFINE_REF(Command) DEFINE_REF(Command)
class RenderCommand : public Gfx::RenderCommand { class RenderCommand : public Gfx::RenderCommand {
public: public:
RenderCommand(MTL::RenderCommandEncoder* encode, const std::string& name); RenderCommand(MTL::RenderCommandEncoder* encode, const std::string& name);
virtual ~RenderCommand(); virtual ~RenderCommand();
void end(); void end();
virtual void setViewport(Gfx::PViewport viewport) override; virtual void setViewport(Gfx::PViewport viewport) override;
virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override; virtual void bindPipeline(Gfx::PGraphicsPipeline pipeline) override;
virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array<uint32> dynamicOffsets) override; virtual void bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array<uint32> dynamicOffsets) override;
virtual void bindDescriptor(const Array<Gfx::PDescriptorSet>& descriptorSets, Array<uint32> dynamicOffsets) override; virtual void bindDescriptor(const Array<Gfx::PDescriptorSet>& descriptorSets, Array<uint32> dynamicOffsets) override;
virtual void bindVertexBuffer(const Array<Gfx::PVertexBuffer>& buffers) override; virtual void bindVertexBuffer(const Array<Gfx::PVertexBuffer>& buffers) override;
virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override; virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override;
virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override;
const void* data) override; virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override;
virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override; virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) override;
virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override;
uint32 firstInstance) override; virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override;
virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override;
virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override;
private: private:
PGraphicsPipeline boundPipeline; PGraphicsPipeline boundPipeline;
PIndexBuffer boundIndexBuffer; PIndexBuffer boundIndexBuffer;
MTL::Buffer* argumentBuffer; MTL::Buffer* argumentBuffer;
MTL::RenderCommandEncoder* encoder; MTL::RenderCommandEncoder* encoder;
std::string name; std::string name;
}; };
DEFINE_REF(RenderCommand) DEFINE_REF(RenderCommand)
class ComputeCommand : public Gfx::ComputeCommand { class ComputeCommand : public Gfx::ComputeCommand {
public: public:
ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name); ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name);
virtual ~ComputeCommand(); virtual ~ComputeCommand();
void end(); void end();
virtual void bindPipeline(Gfx::PComputePipeline pipeline) override; virtual void bindPipeline(Gfx::PComputePipeline pipeline) override;
virtual void bindDescriptor(Gfx::PDescriptorSet set, Array<uint32> dynamicOffsets) override; virtual void bindDescriptor(Gfx::PDescriptorSet set, Array<uint32> dynamicOffsets) override;
virtual void bindDescriptor(const Array<Gfx::PDescriptorSet>& sets, Array<uint32> dynamicOffsets) override; virtual void bindDescriptor(const Array<Gfx::PDescriptorSet>& sets, Array<uint32> dynamicOffsets) override;
virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override;
const void* data) override; virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override;
virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override;
private: private:
PComputePipeline boundPipeline; PComputePipeline boundPipeline;
MTL::CommandBuffer* commandBuffer; MTL::CommandBuffer* commandBuffer;
MTL::ComputeCommandEncoder* encoder; MTL::ComputeCommandEncoder* encoder;
MTL::Buffer* argumentBuffer; MTL::Buffer* argumentBuffer;
std::string name; std::string name;
}; };
DEFINE_REF(ComputeCommand) DEFINE_REF(ComputeCommand)
class CommandQueue { class CommandQueue {
public: public:
CommandQueue(PGraphics graphics); CommandQueue(PGraphics graphics);
~CommandQueue(); ~CommandQueue();
constexpr MTL::CommandQueue* getHandle() { return queue; } constexpr MTL::CommandQueue* getHandle() { return queue; }
PCommand getCommands() { return activeCommand; } PCommand getCommands() { return activeCommand; }
ORenderCommand getRenderCommand(const std::string& name); ORenderCommand getRenderCommand(const std::string& name);
OComputeCommand getComputeCommand(const std::string& name); OComputeCommand getComputeCommand(const std::string& name);
void executeCommands(Array<Gfx::ORenderCommand> commands); void executeCommands(Array<Gfx::ORenderCommand> commands);
void executeCommands(Array<Gfx::OComputeCommand> commands); void executeCommands(Array<Gfx::OComputeCommand> commands);
void submitCommands(PEvent signal = nullptr); void submitCommands(PEvent signal = nullptr);
private: private:
PGraphics graphics; PGraphics graphics;
MTL::CommandQueue* queue; MTL::CommandQueue* queue;
OCommand activeCommand; OCommand activeCommand;
Array<OCommand> pendingCommands; Array<OCommand> pendingCommands;
}; };
class IOCommandQueue { class IOCommandQueue {
public: public:
IOCommandQueue(PGraphics graphics); IOCommandQueue(PGraphics graphics);
~IOCommandQueue(); ~IOCommandQueue();
constexpr MTL::IOCommandQueue* getHandle() { return queue; } constexpr MTL::IOCommandQueue* getHandle() { return queue; }
PCommand getCommands() { return activeCommand; } // TODO PCommand getCommands() { return activeCommand; } // TODO
void submitCommands(PEvent signal = nullptr); void submitCommands(PEvent signal = nullptr);
private: private:
PGraphics graphics; PGraphics graphics;
MTL::IOCommandQueue* queue; MTL::IOCommandQueue* queue;
OCommand activeCommand; OCommand activeCommand;
}; };
DEFINE_REF(IOCommandQueue) DEFINE_REF(IOCommandQueue)
} // namespace Metal } // namespace Metal
+93 -56
View File
@@ -16,8 +16,9 @@
using namespace Seele; using namespace Seele;
using namespace Seele::Metal; using namespace Seele::Metal;
Command::Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer) Command::Command(PGraphics graphics, MTL::CommandBuffer *cmdBuffer)
: graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) {} : graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) {
}
Command::~Command() {} Command::~Command() {}
@@ -27,7 +28,8 @@ void Command::beginRenderPass(PRenderPass renderPass) {
blitEncoder = nullptr; blitEncoder = nullptr;
} }
renderPass->updateRenderPass(); renderPass->updateRenderPass();
parallelEncoder = cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor()); parallelEncoder =
cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor());
} }
void Command::endRenderPass() { void Command::endRenderPass() {
@@ -35,7 +37,9 @@ void Command::endRenderPass() {
parallelEncoder = nullptr; parallelEncoder = nullptr;
} }
void Command::present(MTL::Drawable* drawable) { cmdBuffer->presentDrawable(drawable); } void Command::present(MTL::Drawable *drawable) {
cmdBuffer->presentDrawable(drawable);
}
void Command::end(PEvent signal) { void Command::end(PEvent signal) {
assert(!parallelEncoder); assert(!parallelEncoder);
@@ -49,11 +53,16 @@ void Command::end(PEvent signal) {
void Command::waitDeviceIdle() { cmdBuffer->waitUntilCompleted(); } void Command::waitDeviceIdle() { cmdBuffer->waitUntilCompleted(); }
void Command::signalEvent(PEvent event) { cmdBuffer->encodeSignalEvent(event->getHandle(), 1); } void Command::signalEvent(PEvent event) {
cmdBuffer->encodeSignalEvent(event->getHandle(), 1);
}
void Command::waitForEvent(PEvent event) { cmdBuffer->encodeWait(event->getHandle(), 1); } void Command::waitForEvent(PEvent event) {
cmdBuffer->encodeWait(event->getHandle(), 1);
}
RenderCommand::RenderCommand(MTL::RenderCommandEncoder* encoder, const std::string& name) RenderCommand::RenderCommand(MTL::RenderCommandEncoder *encoder,
const std::string &name)
: encoder(encoder), name(name) {} : encoder(encoder), name(name) {}
RenderCommand::~RenderCommand() {} RenderCommand::~RenderCommand() {}
@@ -79,15 +88,19 @@ void RenderCommand::bindPipeline(Gfx::PGraphicsPipeline pipeline) {
for (auto [_, layout] : boundPipeline->getPipelineLayout()->getLayouts()) { for (auto [_, layout] : boundPipeline->getPipelineLayout()->getLayouts()) {
argBufferSize += 3 * sizeof(uint64) * layout->getBindings().size(); argBufferSize += 3 * sizeof(uint64) * layout->getBindings().size();
} }
argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer(argBufferSize, MTL::ResourceStorageModeShared); argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer(
argBufferSize, MTL::ResourceStorageModeShared);
argumentBuffer->setLabel( argumentBuffer->setLabel(
NS::String::string(boundPipeline->getPipelineLayout()->getName().c_str(), NS::ASCIIStringEncoding)); NS::String::string(boundPipeline->getPipelineLayout()->getName().c_str(),
NS::ASCIIStringEncoding));
} }
void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array<uint32> offsets) { void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet,
Array<uint32> offsets) {
auto metalSet = descriptorSet.cast<DescriptorSet>(); auto metalSet = descriptorSet.cast<DescriptorSet>();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(descriptorSet->getLayout()->getName()); uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(
uint64* topLevelTable = (uint64*)argumentBuffer->contents(); descriptorSet->getLayout()->getName());
uint64 *topLevelTable = (uint64 *)argumentBuffer->contents();
topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress(); topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress();
auto bindings = metalSet->getLayout()->getBindings(); auto bindings = metalSet->getLayout()->getBindings();
encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead); encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead);
@@ -117,15 +130,17 @@ void RenderCommand::bindDescriptor(Gfx::PDescriptorSet descriptorSet, Array<uint
} }
} }
void RenderCommand::bindDescriptor(const Array<Gfx::PDescriptorSet>& descriptorSets, Array<uint32> offsets) { void RenderCommand::bindDescriptor(
const Array<Gfx::PDescriptorSet> &descriptorSets, Array<uint32> offsets) {
for (auto set : descriptorSets) { for (auto set : descriptorSets) {
bindDescriptor(set, offsets); bindDescriptor(set, offsets);
} }
} }
void RenderCommand::bindVertexBuffer(const Array<Gfx::PVertexBuffer>& buffers) { void RenderCommand::bindVertexBuffer(const Array<Gfx::PVertexBuffer> &buffers) {
uint32 i = 0; uint32 i = 0;
for (auto buffer : buffers) { for (auto buffer : buffers) {
encoder->setVertexBuffer(buffer.cast<VertexBuffer>()->getHandle(), 0, METAL_VERTEXBUFFER_OFFSET + i++); encoder->setVertexBuffer(buffer.cast<VertexBuffer>()->getHandle(), 0,
METAL_VERTEXBUFFER_OFFSET + i++);
} }
} }
@@ -133,24 +148,29 @@ void RenderCommand::bindIndexBuffer(Gfx::PIndexBuffer gfxIndexBuffer) {
boundIndexBuffer = gfxIndexBuffer.cast<IndexBuffer>(); boundIndexBuffer = gfxIndexBuffer.cast<IndexBuffer>();
} }
void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset,
const void* data) { uint32 size, const void *data) {
if (stage & Gfx::SE_SHADER_STAGE_VERTEX_BIT) { if (stage & Gfx::SE_SHADER_STAGE_VERTEX_BIT) {
encoder->setVertexBytes((char*)data + offset, size, 0); encoder->setVertexBytes((char *)data + offset, size, 0);
} }
if (stage & Gfx::SE_SHADER_STAGE_FRAGMENT_BIT) { if (stage & Gfx::SE_SHADER_STAGE_FRAGMENT_BIT) {
encoder->setFragmentBytes((char*)data + offset, size, 0); encoder->setFragmentBytes((char *)data + offset, size, 0);
} }
} }
void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) { void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount,
encoder->drawPrimitives(boundPipeline->getPrimitive(), firstVertex, vertexCount, instanceCount, firstInstance); int32 firstVertex, uint32 firstInstance) {
encoder->drawPrimitives(boundPipeline->getPrimitive(), firstVertex,
vertexCount, instanceCount, firstInstance);
} }
void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, void RenderCommand::drawIndexed(uint32 indexCount, uint32 instanceCount,
int32 firstIndex, uint32 vertexOffset,
uint32 firstInstance) { uint32 firstInstance) {
encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount, cast(boundIndexBuffer->getIndexType()), encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount,
boundIndexBuffer->getHandle(), firstIndex, instanceCount, vertexOffset, firstInstance); cast(boundIndexBuffer->getIndexType()),
boundIndexBuffer->getHandle(), firstIndex,
instanceCount, vertexOffset, firstInstance);
} }
void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) { void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) {
@@ -159,15 +179,19 @@ void RenderCommand::drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) {
encoder->setFragmentBuffer(argumentBuffer, 0, 2); encoder->setFragmentBuffer(argumentBuffer, 0, 2);
encoder->setMeshBuffer(argumentBuffer, 0, 2); encoder->setMeshBuffer(argumentBuffer, 0, 2);
encoder->setObjectBuffer(argumentBuffer, 0, 2); encoder->setObjectBuffer(argumentBuffer, 0, 2);
encoder->drawMeshThreadgroups(MTL::Size(groupX, groupY, groupZ), MTL::Size(128, 1, 1), MTL::Size(32, 1, 1)); encoder->drawMeshThreadgroups(MTL::Size(groupX, groupY, groupZ),
MTL::Size(128, 1, 1), MTL::Size(32, 1, 1));
} }
void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) { void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset,
//encoder->drawMeshThreadgroups() uint32 drawCount, uint32 stride) {
// encoder->drawMeshThreadgroups()
} }
ComputeCommand::ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name) ComputeCommand::ComputeCommand(MTL::CommandBuffer *cmdBuffer,
: commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()), name(name) {} const std::string &name)
: commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()),
name(name) {}
ComputeCommand::~ComputeCommand() {} ComputeCommand::~ComputeCommand() {}
@@ -180,16 +204,21 @@ void ComputeCommand::bindPipeline(Gfx::PComputePipeline pipeline) {
boundPipeline = pipeline.cast<ComputePipeline>(); boundPipeline = pipeline.cast<ComputePipeline>();
encoder->setComputePipelineState(boundPipeline->getHandle()); encoder->setComputePipelineState(boundPipeline->getHandle());
argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer( argumentBuffer = boundPipeline->graphics->getDevice()->newBuffer(
sizeof(uint64) * (boundPipeline->getPipelineLayout()->getLayouts().size() + 1), MTL::ResourceStorageModeShared); sizeof(uint64) *
(boundPipeline->getPipelineLayout()->getLayouts().size() + 1),
MTL::ResourceStorageModeShared);
argumentBuffer->setLabel( argumentBuffer->setLabel(
NS::String::string(pipeline->getPipelineLayout()->getName().c_str(), NS::ASCIIStringEncoding)); NS::String::string(pipeline->getPipelineLayout()->getName().c_str(),
NS::ASCIIStringEncoding));
} }
void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set, Array<uint32> offsets) { void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set,
Array<uint32> offsets) {
auto metalSet = set.cast<DescriptorSet>(); auto metalSet = set.cast<DescriptorSet>();
metalSet->bind(); metalSet->bind();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(set->getLayout()->getName()); uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(
uint64* topLevelTable = (uint64*)argumentBuffer->contents(); set->getLayout()->getName());
uint64 *topLevelTable = (uint64 *)argumentBuffer->contents();
topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress(); topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress();
auto bindings = metalSet->getLayout()->getBindings(); auto bindings = metalSet->getLayout()->getBindings();
encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead); encoder->useResource(metalSet->getBuffer(), MTL::ResourceUsageRead);
@@ -219,42 +248,45 @@ void ComputeCommand::bindDescriptor(Gfx::PDescriptorSet set, Array<uint32> offse
} }
} }
void ComputeCommand::bindDescriptor(const Array<Gfx::PDescriptorSet>& sets, Array<uint32> offsets) { void ComputeCommand::bindDescriptor(const Array<Gfx::PDescriptorSet> &sets,
for (auto& set : sets) { Array<uint32> offsets) {
for (auto &set : sets) {
bindDescriptor(set, offsets); bindDescriptor(set, offsets);
} }
} }
void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset, uint32 size, void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset,
const void* data) { uint32 size, const void *data) {
encoder->setBytes((char*)data + offset, size, 0); encoder->setBytes((char *)data + offset, size, 0);
} }
void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) { void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) {
// TODO // TODO
encoder->setBuffer(argumentBuffer, 0, 2); encoder->setBuffer(argumentBuffer, 0, 2);
encoder->dispatchThreadgroups(MTL::Size(threadX, threadY, threadZ), MTL::Size(32, 32, 1)); encoder->dispatchThreadgroups(MTL::Size(threadX, threadY, threadZ),
MTL::Size(32, 32, 1));
} }
CommandQueue::CommandQueue(PGraphics graphics) : graphics(graphics) { CommandQueue::CommandQueue(PGraphics graphics) : graphics(graphics) {
queue = graphics->getDevice()->newCommandQueue(); queue = graphics->getDevice()->newCommandQueue();
MTL::CommandBufferDescriptor* descriptor = MTL::CommandBufferDescriptor::alloc()->init(); MTL::CommandBufferDescriptor *descriptor =
MTL::CommandBufferDescriptor::alloc()->init();
activeCommand = new Command(graphics, queue->commandBuffer(descriptor)); activeCommand = new Command(graphics, queue->commandBuffer(descriptor));
descriptor->release(); descriptor->release();
} }
CommandQueue::~CommandQueue() { queue->release(); } CommandQueue::~CommandQueue() { queue->release(); }
ORenderCommand CommandQueue::getRenderCommand(const std::string& name) { ORenderCommand CommandQueue::getRenderCommand(const std::string &name) {
return new RenderCommand(activeCommand->createRenderEncoder(), name); return new RenderCommand(activeCommand->createRenderEncoder(), name);
} }
OComputeCommand CommandQueue::getComputeCommand(const std::string& name) { OComputeCommand CommandQueue::getComputeCommand(const std::string &name) {
return new ComputeCommand(queue->commandBuffer(), name); return new ComputeCommand(queue->commandBuffer(), name);
} }
void CommandQueue::executeCommands(Array<Gfx::ORenderCommand> commands) { void CommandQueue::executeCommands(Array<Gfx::ORenderCommand> commands) {
for (auto& command : commands) { for (auto &command : commands) {
auto metalCmd = Gfx::PRenderCommand(command).cast<RenderCommand>(); auto metalCmd = Gfx::PRenderCommand(command).cast<RenderCommand>();
metalCmd->end(); metalCmd->end();
} }
@@ -262,33 +294,38 @@ void CommandQueue::executeCommands(Array<Gfx::ORenderCommand> commands) {
void CommandQueue::executeCommands(Array<Gfx::OComputeCommand> commands) { void CommandQueue::executeCommands(Array<Gfx::OComputeCommand> commands) {
submitCommands(); submitCommands();
for (auto& command : commands) { for (auto &command : commands) {
auto metalCmd = Gfx::PComputeCommand(command).cast<ComputeCommand>(); auto metalCmd = Gfx::PComputeCommand(command).cast<ComputeCommand>();
metalCmd->end(); metalCmd->end();
} }
} }
void CommandQueue::submitCommands(PEvent signalSemaphore) { void CommandQueue::submitCommands(PEvent signalSemaphore) {
activeCommand->getHandle()->addCompletedHandler(MTL::CommandBufferHandler([&](MTL::CommandBuffer* cmdBuffer) { activeCommand->getHandle()->addCompletedHandler(
for (auto it = pendingCommands.begin(); it != pendingCommands.end(); it++) { MTL::CommandBufferHandler([&](MTL::CommandBuffer *cmdBuffer) {
if ((*it)->getHandle() == cmdBuffer) { for (auto it = pendingCommands.begin(); it != pendingCommands.end();
pendingCommands.remove(it); it++) {
return; if ((*it)->getHandle() == cmdBuffer) {
} pendingCommands.remove(it);
} return;
})); }
}
}));
activeCommand->end(signalSemaphore); activeCommand->end(signalSemaphore);
activeCommand->waitDeviceIdle(); activeCommand->waitDeviceIdle();
PEvent prevCmdEvent = activeCommand->getCompletedEvent(); PEvent prevCmdEvent = activeCommand->getCompletedEvent();
pendingCommands.add(std::move(activeCommand)); pendingCommands.add(std::move(activeCommand));
MTL::CommandBufferDescriptor* descriptor = MTL::CommandBufferDescriptor::alloc()->init(); MTL::CommandBufferDescriptor *descriptor =
descriptor->setErrorOptions(MTL::CommandBufferErrorOptionEncoderExecutionStatus); MTL::CommandBufferDescriptor::alloc()->init();
descriptor->setErrorOptions(
MTL::CommandBufferErrorOptionEncoderExecutionStatus);
activeCommand = new Command(graphics, queue->commandBuffer(descriptor)); activeCommand = new Command(graphics, queue->commandBuffer(descriptor));
activeCommand->waitForEvent(prevCmdEvent); activeCommand->waitForEvent(prevCmdEvent);
} }
IOCommandQueue::IOCommandQueue(PGraphics graphics) : graphics(graphics) { IOCommandQueue::IOCommandQueue(PGraphics graphics) : graphics(graphics) {
MTL::IOCommandQueueDescriptor* desc = MTL::IOCommandQueueDescriptor::alloc()->init(); MTL::IOCommandQueueDescriptor *desc =
MTL::IOCommandQueueDescriptor::alloc()->init();
desc->setType(MTL::IOCommandQueueTypeConcurrent); desc->setType(MTL::IOCommandQueueTypeConcurrent);
desc->setPriority(MTL::IOPriorityNormal); desc->setPriority(MTL::IOPriorityNormal);
queue = graphics->getDevice()->newIOCommandQueue(desc, nullptr); queue = graphics->getDevice()->newIOCommandQueue(desc, nullptr);
+44 -50
View File
@@ -9,75 +9,69 @@ namespace Seele {
namespace Metal { namespace Metal {
DECLARE_REF(Graphics) DECLARE_REF(Graphics)
class DescriptorLayout : public Gfx::DescriptorLayout { class DescriptorLayout : public Gfx::DescriptorLayout {
public: public:
DescriptorLayout(PGraphics graphics, const std::string &name); DescriptorLayout(PGraphics graphics, const std::string& name);
virtual ~DescriptorLayout(); virtual ~DescriptorLayout();
virtual void create() override; virtual void create() override;
private: private:
PGraphics graphics; PGraphics graphics;
}; };
DEFINE_REF(DescriptorLayout) DEFINE_REF(DescriptorLayout)
DECLARE_REF(DescriptorSet) DECLARE_REF(DescriptorSet)
class DescriptorPool : public Gfx::DescriptorPool { class DescriptorPool : public Gfx::DescriptorPool {
public: public:
DescriptorPool(PGraphics graphics, PDescriptorLayout layout); DescriptorPool(PGraphics graphics, PDescriptorLayout layout);
virtual ~DescriptorPool(); virtual ~DescriptorPool();
virtual Gfx::PDescriptorSet allocateDescriptorSet() override; virtual Gfx::PDescriptorSet allocateDescriptorSet() override;
virtual void reset() override; virtual void reset() override;
constexpr PDescriptorLayout getLayout() const { return layout; } constexpr PDescriptorLayout getLayout() const { return layout; }
private: private:
PGraphics graphics; PGraphics graphics;
PDescriptorLayout layout; PDescriptorLayout layout;
Array<ODescriptorSet> allocatedSets; Array<ODescriptorSet> allocatedSets;
}; };
DEFINE_REF(DescriptorPool) DEFINE_REF(DescriptorPool)
class DescriptorSet : public Gfx::DescriptorSet, public CommandBoundResource { class DescriptorSet : public Gfx::DescriptorSet, public CommandBoundResource {
public: public:
DescriptorSet(PGraphics graphics, PDescriptorPool owner); DescriptorSet(PGraphics graphics, PDescriptorPool owner);
virtual ~DescriptorSet(); virtual ~DescriptorSet();
virtual void writeChanges() override; virtual void writeChanges() override;
virtual void updateBuffer(uint32_t binding, virtual void updateBuffer(uint32_t binding, Gfx::PUniformBuffer uniformBuffer) override;
Gfx::PUniformBuffer uniformBuffer) override; virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override;
virtual void updateBuffer(uint32_t binding, Gfx::PShaderBuffer uniformBuffer) override; virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override;
virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) override; virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override;
virtual void updateSampler(uint32_t binding, Gfx::PSampler samplerState) override; virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override;
virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, virtual void updateTextureArray(uint32_t binding, Array<Gfx::PTexture> texture) override;
Gfx::PSampler sampler = nullptr) override;
virtual void updateTextureArray(uint32_t binding,
Array<Gfx::PTexture> texture) override;
constexpr bool isCurrentlyInUse() const { return currentlyInUse; } constexpr bool isCurrentlyInUse() const { return currentlyInUse; }
constexpr void allocate() { currentlyInUse = true; } constexpr void allocate() { currentlyInUse = true; }
constexpr void free() { currentlyInUse = false; } constexpr void free() { currentlyInUse = false; }
constexpr MTL::Buffer *getBuffer() const { return buffer; } constexpr MTL::Buffer* getBuffer() const { return buffer; }
constexpr const Array<MTL::Resource *> &getBoundResources() const { constexpr const Array<MTL::Resource*>& getBoundResources() const { return boundResources; }
return boundResources;
}
private: private:
PGraphics graphics; PGraphics graphics;
PDescriptorPool owner; PDescriptorPool owner;
MTL::Buffer *buffer = nullptr; MTL::Buffer* buffer = nullptr;
uint64 *argumentBuffer = nullptr; uint64* argumentBuffer = nullptr;
Array<MTL::Resource *> boundResources; Array<MTL::Resource*> boundResources;
bool currentlyInUse; bool currentlyInUse;
}; };
DEFINE_REF(DescriptorSet) DEFINE_REF(DescriptorSet)
class PipelineLayout : public Gfx::PipelineLayout { class PipelineLayout : public Gfx::PipelineLayout {
public: public:
PipelineLayout(PGraphics graphics, const std::string &name, PipelineLayout(PGraphics graphics, const std::string& name, Gfx::PPipelineLayout baseLayout);
Gfx::PPipelineLayout baseLayout); virtual ~PipelineLayout();
virtual ~PipelineLayout(); virtual void create() override;
virtual void create() override;
private: private:
PGraphics graphics; PGraphics graphics;
}; };
DEFINE_REF(PipelineLayout) DEFINE_REF(PipelineLayout)
} // namespace Metal } // namespace Metal
+2 -5
View File
@@ -94,11 +94,8 @@ void DescriptorSet::updateBuffer(uint32_t binding,
boundResources[binding] = metalBuffer->getHandle(); boundResources[binding] = metalBuffer->getHandle();
} }
void DescriptorSet::updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) void DescriptorSet::updateBuffer(uint32_t binding, uint32 index,
{ Gfx::PShaderBuffer uniformBuffer) {}
}
void DescriptorSet::updateSampler(uint32_t binding, void DescriptorSet::updateSampler(uint32_t binding,
Gfx::PSampler samplerState) { Gfx::PSampler samplerState) {
+5 -7
View File
@@ -3,11 +3,9 @@
#include "Metal/MTLStageInputOutputDescriptor.hpp" #include "Metal/MTLStageInputOutputDescriptor.hpp"
#include "Resources.h" #include "Resources.h"
namespace Seele namespace Seele {
{ namespace Metal {
namespace Metal constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6; // something about metal vertex fetch
{
constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6;// something about metal vertex fetch
constexpr uint64 METAL_VERTEXATTRIBUTE_OFFSET = 11; constexpr uint64 METAL_VERTEXATTRIBUTE_OFFSET = 11;
MTL::PixelFormat cast(Gfx::SeFormat format); MTL::PixelFormat cast(Gfx::SeFormat format);
@@ -32,5 +30,5 @@ MTL::PrimitiveTopologyClass cast(Gfx::SePrimitiveTopology topology);
Gfx::SePrimitiveTopology cast(MTL::PrimitiveTopologyClass topology); Gfx::SePrimitiveTopology cast(MTL::PrimitiveTopologyClass topology);
MTL::IndexType cast(Gfx::SeIndexType indexType); MTL::IndexType cast(Gfx::SeIndexType indexType);
Gfx::SeIndexType cast(MTL::IndexType indexType); Gfx::SeIndexType cast(MTL::IndexType indexType);
} } // namespace Metal
} } // namespace Seele
+2 -1
View File
@@ -767,7 +767,8 @@ Gfx::SeSamplerAddressMode Seele::Metal::cast(MTL::SamplerAddressMode mode) {
} }
} }
MTL::PrimitiveTopologyClass Seele::Metal::cast(Gfx::SePrimitiveTopology topology) { MTL::PrimitiveTopologyClass
Seele::Metal::cast(Gfx::SePrimitiveTopology topology) {
switch (topology) { switch (topology) {
case Gfx::SE_PRIMITIVE_TOPOLOGY_POINT_LIST: case Gfx::SE_PRIMITIVE_TOPOLOGY_POINT_LIST:
return MTL::PrimitiveTopologyClassPoint; return MTL::PrimitiveTopologyClassPoint;
+21 -21
View File
@@ -1,25 +1,24 @@
#pragma once #pragma once
#include "Metal/Metal.hpp"
#include "Graphics/Graphics.h" #include "Graphics/Graphics.h"
#include "Metal/Metal.hpp"
namespace Seele
{ namespace Seele {
namespace Metal namespace Metal {
{
DECLARE_REF(CommandQueue) DECLARE_REF(CommandQueue)
DECLARE_REF(IOCommandQueue) DECLARE_REF(IOCommandQueue)
DECLARE_REF(PipelineCache) DECLARE_REF(PipelineCache)
class Graphics : public Gfx::Graphics class Graphics : public Gfx::Graphics {
{ public:
public:
Graphics(); Graphics();
virtual ~Graphics(); virtual ~Graphics();
virtual void init(GraphicsInitializer initializer) override; virtual void init(GraphicsInitializer initializer) override;
virtual Gfx::OWindow createWindow(const WindowCreateInfo &createInfo) override; virtual Gfx::OWindow createWindow(const WindowCreateInfo& createInfo) override;
virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) override; virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo& createInfo) override;
virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, Gfx::PViewport renderArea) override; virtual Gfx::ORenderPass createRenderPass(Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies,
Gfx::PViewport renderArea) override;
virtual void beginRenderPass(Gfx::PRenderPass renderPass) override; virtual void beginRenderPass(Gfx::PRenderPass renderPass) override;
virtual void endRenderPass() override; virtual void endRenderPass() override;
virtual void waitDeviceIdle() override; virtual void waitDeviceIdle() override;
@@ -27,13 +26,13 @@ public:
virtual void executeCommands(Array<Gfx::ORenderCommand> commands) override; virtual void executeCommands(Array<Gfx::ORenderCommand> commands) override;
virtual void executeCommands(Array<Gfx::OComputeCommand> commands) override; virtual void executeCommands(Array<Gfx::OComputeCommand> commands) override;
virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo &createInfo) override; virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo& createInfo) override;
virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo &createInfo) override; virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo& createInfo) override;
virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo &createInfo) override; virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo& createInfo) override;
virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) override; virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) override;
virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) override; virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) override;
virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) override; virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) override;
virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) override; virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) override;
virtual Gfx::ORenderCommand createRenderCommand(const std::string& name = "") override; virtual Gfx::ORenderCommand createRenderCommand(const std::string& name = "") override;
virtual Gfx::OComputeCommand createComputeCommand(const std::string& name = "") override; virtual Gfx::OComputeCommand createComputeCommand(const std::string& name = "") override;
@@ -48,8 +47,8 @@ public:
virtual Gfx::PComputePipeline createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) override; virtual Gfx::PComputePipeline createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) override;
virtual Gfx::OSampler createSampler(const SamplerCreateInfo& createInfo) override; virtual Gfx::OSampler createSampler(const SamplerCreateInfo& createInfo) override;
virtual Gfx::ODescriptorLayout createDescriptorLayout(const std::string& name = "") override; virtual Gfx::ODescriptorLayout createDescriptorLayout(const std::string& name = "") override;
virtual Gfx::OPipelineLayout createPipelineLayout(const std::string& name = "", Gfx::PPipelineLayout baseLayout = nullptr) override; virtual Gfx::OPipelineLayout createPipelineLayout(const std::string& name = "", Gfx::PPipelineLayout baseLayout = nullptr) override;
virtual Gfx::OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) override; virtual Gfx::OVertexInput createVertexInput(VertexInputStateCreateInfo createInfo) override;
@@ -58,7 +57,8 @@ public:
MTL::Device* getDevice() const { return device; } MTL::Device* getDevice() const { return device; }
PCommandQueue getQueue() const { return queue; } PCommandQueue getQueue() const { return queue; }
PIOCommandQueue getIOQueue() const { return ioQueue; } PIOCommandQueue getIOQueue() const { return ioQueue; }
protected:
protected:
MTL::Device* device; MTL::Device* device;
OCommandQueue queue; OCommandQueue queue;
OIOCommandQueue ioQueue; OIOCommandQueue ioQueue;
+58 -79
View File
@@ -1,31 +1,25 @@
#include "Graphics.h" #include "Graphics.h"
#include "Buffer.h"
#include "Command.h"
#include "Graphics/Initializer.h" #include "Graphics/Initializer.h"
#include "Graphics/Metal/Descriptor.h" #include "Graphics/Metal/Descriptor.h"
#include "Graphics/Metal/Pipeline.h" #include "Graphics/Metal/Pipeline.h"
#include "Graphics/Metal/PipelineCache.h" #include "Graphics/Metal/PipelineCache.h"
#include "Graphics/Metal/Resources.h" #include "Graphics/Metal/Resources.h"
#include "Shader.h"
#include "RenderPass.h" #include "RenderPass.h"
#include "Resources.h" #include "Resources.h"
#include "Command.h" #include "Shader.h"
#include "Window.h" #include "Window.h"
#include "Buffer.h"
using namespace Seele; using namespace Seele;
using namespace Seele::Metal; using namespace Seele::Metal;
Graphics::Graphics() Graphics::Graphics() {}
{
} Graphics::~Graphics() {}
Graphics::~Graphics() void Graphics::init(GraphicsInitializer) {
{
}
void Graphics::init(GraphicsInitializer)
{
glfwInit(); glfwInit();
device = MTL::CreateSystemDefaultDevice(); device = MTL::CreateSystemDefaultDevice();
queue = new CommandQueue(this); queue = new CommandQueue(this);
@@ -34,164 +28,149 @@ void Graphics::init(GraphicsInitializer)
meshShadingEnabled = false; meshShadingEnabled = false;
} }
Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo) Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo) {
{
return new Window(this, createInfo); return new Window(this, createInfo);
} }
Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) Gfx::OViewport Graphics::createViewport(Gfx::PWindow owner,
{ const ViewportCreateInfo &createInfo) {
return new Viewport(owner, createInfo); return new Viewport(owner, createInfo);
} }
Gfx::ORenderPass Graphics::createRenderPass(Gfx::RenderTargetLayout layout, Array<Gfx::SubPassDependency> dependencies, Gfx::PViewport renderArea) Gfx::ORenderPass
{ Graphics::createRenderPass(Gfx::RenderTargetLayout layout,
Array<Gfx::SubPassDependency> dependencies,
Gfx::PViewport renderArea) {
return new RenderPass(this, layout, dependencies, renderArea); return new RenderPass(this, layout, dependencies, renderArea);
} }
void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) {
{
queue->getCommands()->beginRenderPass(renderPass.cast<RenderPass>()); queue->getCommands()->beginRenderPass(renderPass.cast<RenderPass>());
} }
void Graphics::endRenderPass() void Graphics::endRenderPass() { queue->getCommands()->endRenderPass(); }
{
queue->getCommands()->endRenderPass();
}
void Graphics::waitDeviceIdle() void Graphics::waitDeviceIdle() { queue->getCommands()->waitDeviceIdle(); }
{
queue->getCommands()->waitDeviceIdle();
}
void Graphics::executeCommands(Array<Gfx::ORenderCommand> commands) void Graphics::executeCommands(Array<Gfx::ORenderCommand> commands) {
{
queue->executeCommands(std::move(commands)); queue->executeCommands(std::move(commands));
} }
void Graphics::executeCommands(Array<Gfx::OComputeCommand> commands) void Graphics::executeCommands(Array<Gfx::OComputeCommand> commands) {
{
queue->executeCommands(std::move(commands)); queue->executeCommands(std::move(commands));
} }
Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo) {
{
return new Texture2D(this, createInfo); return new Texture2D(this, createInfo);
} }
Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo &createInfo) Gfx::OTexture3D Graphics::createTexture3D(const TextureCreateInfo &createInfo) {
{
return new Texture3D(this, createInfo); return new Texture3D(this, createInfo);
} }
Gfx::OTextureCube Graphics::createTextureCube(const TextureCreateInfo &createInfo) Gfx::OTextureCube
{ Graphics::createTextureCube(const TextureCreateInfo &createInfo) {
return new TextureCube(this, createInfo); return new TextureCube(this, createInfo);
} }
Gfx::OUniformBuffer Graphics::createUniformBuffer(const UniformBufferCreateInfo &bulkData) Gfx::OUniformBuffer
{ Graphics::createUniformBuffer(const UniformBufferCreateInfo &bulkData) {
return new UniformBuffer(this, bulkData); return new UniformBuffer(this, bulkData);
} }
Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) Gfx::OShaderBuffer
{ Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData) {
return new ShaderBuffer(this, bulkData); return new ShaderBuffer(this, bulkData);
} }
Gfx::OVertexBuffer Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) Gfx::OVertexBuffer
{ Graphics::createVertexBuffer(const VertexBufferCreateInfo &bulkData) {
return new VertexBuffer(this, bulkData); return new VertexBuffer(this, bulkData);
} }
Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData) Gfx::OIndexBuffer
{ Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData) {
return new IndexBuffer(this, bulkData); return new IndexBuffer(this, bulkData);
} }
Gfx::ORenderCommand Graphics::createRenderCommand(const std::string& name) Gfx::ORenderCommand Graphics::createRenderCommand(const std::string &name) {
{
return queue->getRenderCommand(name); return queue->getRenderCommand(name);
} }
Gfx::OComputeCommand Graphics::createComputeCommand(const std::string& name) Gfx::OComputeCommand Graphics::createComputeCommand(const std::string &name) {
{
return queue->getComputeCommand(name); return queue->getComputeCommand(name);
} }
Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createInfo) Gfx::OVertexShader
{ Graphics::createVertexShader(const ShaderCreateInfo &createInfo) {
OVertexShader result = new VertexShader(this); OVertexShader result = new VertexShader(this);
result->create(createInfo); result->create(createInfo);
return result; return result;
} }
Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo) Gfx::OFragmentShader
{ Graphics::createFragmentShader(const ShaderCreateInfo &createInfo) {
OFragmentShader result = new FragmentShader(this); OFragmentShader result = new FragmentShader(this);
result->create(createInfo); result->create(createInfo);
return result; return result;
} }
Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo) Gfx::OComputeShader
{ Graphics::createComputeShader(const ShaderCreateInfo &createInfo) {
OComputeShader result = new ComputeShader(this); OComputeShader result = new ComputeShader(this);
result->create(createInfo); result->create(createInfo);
return result; return result;
} }
Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo) Gfx::OMeshShader
{ Graphics::createMeshShader(const ShaderCreateInfo &createInfo) {
OMeshShader result = new MeshShader(this); OMeshShader result = new MeshShader(this);
result->create(createInfo); result->create(createInfo);
return result; return result;
} }
Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo) Gfx::OTaskShader
{ Graphics::createTaskShader(const ShaderCreateInfo &createInfo) {
OTaskShader result = new TaskShader(this); OTaskShader result = new TaskShader(this);
result->create(createInfo); result->create(createInfo);
return result; return result;
} }
Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) Gfx::PGraphicsPipeline
{ Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo) {
return cache->createPipeline(std::move(createInfo)); return cache->createPipeline(std::move(createInfo));
} }
Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) Gfx::PGraphicsPipeline
{ Graphics::createGraphicsPipeline(Gfx::MeshPipelineCreateInfo createInfo) {
return cache->createPipeline(std::move(createInfo)); return cache->createPipeline(std::move(createInfo));
} }
Gfx::PComputePipeline Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) Gfx::PComputePipeline
{ Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo) {
return cache->createPipeline(std::move(createInfo)); return cache->createPipeline(std::move(createInfo));
} }
Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo& createInfo) Gfx::OSampler Graphics::createSampler(const SamplerCreateInfo &createInfo) {
{
return new Sampler(this, createInfo); return new Sampler(this, createInfo);
} }
Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name) Gfx::ODescriptorLayout
{ Graphics::createDescriptorLayout(const std::string &name) {
return new DescriptorLayout(this, name); return new DescriptorLayout(this, name);
} }
Gfx::OPipelineLayout Graphics::createPipelineLayout(const std::string& name, Gfx::PPipelineLayout baseLayout) Gfx::OPipelineLayout
{ Graphics::createPipelineLayout(const std::string &name,
Gfx::PPipelineLayout baseLayout) {
return new PipelineLayout(this, name, baseLayout); return new PipelineLayout(this, name, baseLayout);
} }
Gfx::OVertexInput Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) Gfx::OVertexInput
{ Graphics::createVertexInput(VertexInputStateCreateInfo createInfo) {
return new VertexInput(createInfo); return new VertexInput(createInfo);
} }
void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) void Graphics::resolveTexture(Gfx::PTexture source, Gfx::PTexture destination) {
{
} }
+21 -19
View File
@@ -7,33 +7,35 @@
namespace Seele { namespace Seele {
namespace Metal { namespace Metal {
class VertexInput : public Gfx::VertexInput { class VertexInput : public Gfx::VertexInput {
public: public:
VertexInput(VertexInputStateCreateInfo createInfo); VertexInput(VertexInputStateCreateInfo createInfo);
virtual ~VertexInput(); virtual ~VertexInput();
}; };
DECLARE_REF(PipelineLayout) DECLARE_REF(PipelineLayout)
DECLARE_REF(Graphics) DECLARE_REF(Graphics)
class GraphicsPipeline : public Gfx::GraphicsPipeline { class GraphicsPipeline : public Gfx::GraphicsPipeline {
public: public:
GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, Gfx::PPipelineLayout createInfo); GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, Gfx::PPipelineLayout createInfo);
virtual ~GraphicsPipeline(); virtual ~GraphicsPipeline();
constexpr MTL::RenderPipelineState* getHandle() const { return state; } constexpr MTL::RenderPipelineState* getHandle() const { return state; }
constexpr MTL::PrimitiveType getPrimitive() const { return primitiveType; } constexpr MTL::PrimitiveType getPrimitive() const { return primitiveType; }
PGraphics graphics; PGraphics graphics;
MTL::RenderPipelineState* state; MTL::RenderPipelineState* state;
MTL::PrimitiveType primitiveType; MTL::PrimitiveType primitiveType;
private:
private:
}; };
DEFINE_REF(GraphicsPipeline) DEFINE_REF(GraphicsPipeline)
class ComputePipeline : public Gfx::ComputePipeline { class ComputePipeline : public Gfx::ComputePipeline {
public: public:
ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, Gfx::PPipelineLayout); ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, Gfx::PPipelineLayout);
virtual ~ComputePipeline(); virtual ~ComputePipeline();
constexpr MTL::ComputePipelineState* getHandle() const { return state; } constexpr MTL::ComputePipelineState* getHandle() const { return state; }
PGraphics graphics; PGraphics graphics;
private:
MTL::ComputePipelineState* state; private:
MTL::ComputePipelineState* state;
}; };
DEFINE_REF(ComputePipeline) DEFINE_REF(ComputePipeline)
} // namespace Metal } // namespace Metal

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