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
+9 -10
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;
}; };
+74 -110
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(
MaterialImportArgs{
.filePath = std::filesystem::absolute("./shaders/Placeholder.json"), .filePath = std::filesystem::absolute("./shaders/Placeholder.json"),
.importPath = "", .importPath = "",
}, placeholderAsset); },
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;
+103 -182
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];
@@ -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;
@@ -135,8 +123,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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));
@@ -144,8 +131,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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);
@@ -154,16 +140,15 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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;
} }
@@ -171,38 +156,29 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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)) {
else if (std::filesystem::exists(texFilename))
{
AssetImporter::importTexture(TextureImportArgs{ 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; std::cout << "couldnt find " << texPath.C_Str() << std::endl;
return; return;
} }
@@ -218,8 +194,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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;
@@ -261,10 +236,9 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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;
} }
@@ -293,14 +267,13 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
/** T = T1 / T2 */ /** T = T1 / T2 */
case aiTextureOp_Divide: case aiTextureOp_Divide:
//expressions[blendKey] = new DivExpression(); // expressions[blendKey] = new DivExpression();
throw std::logic_error("Not implemented"); throw std::logic_error("Not implemented");
/** T = (T1 + T2) - (T1 * T2) */ /** T = (T1 + T2) - (T1 * T2) */
case aiTextureOp_SmoothAdd: case aiTextureOp_SmoothAdd:
throw std::logic_error("Not implemented"); throw std::logic_error("Not implemented");
/** T = T1 + (T2-0.5) */ /** T = T1 + (T2-0.5) */
case aiTextureOp_SignedAdd: case aiTextureOp_SignedAdd:
throw std::logic_error("Not implemented"); throw std::logic_error("Not implemented");
@@ -316,15 +289,13 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
expressions.back()->inputs["rhs"].source = strengthKey; expressions.back()->inputs["rhs"].source = strengthKey;
result = blendKey; 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,13 +400,8 @@ 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{
@@ -457,23 +413,19 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
} }
} }
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);
+44 -47
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(
TextureImportArgs{
.filePath = std::filesystem::absolute("textures/placeholder.png"), .filePath = std::filesystem::absolute("textures/placeholder.png"),
.importPath = "", .importPath = "",
}, placeholderAsset); },
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,23 +71,22 @@ 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;
@@ -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,9 +136,9 @@ 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(),
@@ -148,24 +146,23 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// .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;
+20 -45
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**)
{
}
+9 -11
View File
@@ -1,19 +1,17 @@
#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;
@@ -23,8 +21,8 @@ public:
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;
+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();
}
+6 -8
View File
@@ -1,13 +1,10 @@
#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;
@@ -16,7 +13,8 @@ public:
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**) {}
{
}
+11 -12
View File
@@ -1,20 +1,18 @@
#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(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo);
~SceneView(); ~SceneView();
virtual void beginUpdate() override; virtual void beginUpdate() override;
@@ -25,7 +23,8 @@ public:
virtual void render() override; virtual void render() override;
PScene getScene() const { return scene; } PScene getScene() const { return scene; }
private:
private:
OScene scene; OScene scene;
Component::Camera viewportCamera; Component::Camera viewportCamera;
+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;
}
+10 -11
View File
@@ -1,17 +1,15 @@
#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: public:
ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/); ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/);
~ViewportControl(); ~ViewportControl();
@@ -20,6 +18,7 @@ namespace Editor
void mouseMoveCallback(double xPos, double yPos); void mouseMoveCallback(double xPos, double yPos);
void mouseButtonCallback(MouseButton button, InputAction action); void mouseButtonCallback(MouseButton button, InputAction action);
void viewportResize(URect dimensions); void viewportResize(URect dimensions);
private: private:
Vector position; Vector position;
Vector springArm; Vector springArm;
@@ -32,6 +31,6 @@ namespace Editor
float mouseY; float mouseY;
float pitch; float pitch;
float yaw; float yaw;
}; };
} // namespace Editor } // namespace Editor
} // namespace Seele } // namespace Seele
+4 -6
View File
@@ -58,15 +58,13 @@ int main() {
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{
});
//AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj", // .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj",
// .importPath = "Nitriansky" // .importPath = "Nitriansky"
// }); // });
+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
+19 -41
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,27 +62,22 @@ 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)), .size = ktxTexture_GetDataSize(ktxTexture(kTexture)),
.data = ktxTexture_GetData(ktxTexture(kTexture)), .data = ktxTexture_GetData(ktxTexture(kTexture)),
.owner = Gfx::QueueType::GRAPHICS, .owner = Gfx::QueueType::GRAPHICS,
@@ -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;
}; };
+36 -52
View File
@@ -1,30 +1,30 @@
#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(),
@@ -32,34 +32,32 @@ void TextureAsset::save(ArchiveBuffer& buffer) const
// .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)), .size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)),
.data = ktxTexture_GetData(ktxTexture(ktxHandle)), .data = ktxTexture_GetData(ktxTexture(ktxHandle)),
.owner = Gfx::QueueType::TRANSFER, .owner = Gfx::QueueType::TRANSFER,
@@ -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;
+12 -29
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) \ #define DEFINE_COMPONENT(x) \
thread_local x* tl_##x = nullptr; \ thread_local x* tl_##x = nullptr; \
void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \ void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \
template<> \ template <> x& Seele::Component::getComponent<x>() { return *tl_##x; }
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;
+48 -74
View File
@@ -4,10 +4,8 @@
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 */
@@ -24,22 +22,19 @@ 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;
@@ -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
+189 -482
View File
@@ -1,24 +1,20 @@
#pragma once #pragma once
#include "EngineTypes.h" #include "EngineTypes.h"
#include <algorithm>
#include <assert.h>
#include <initializer_list> #include <initializer_list>
#include <iterator> #include <iterator>
#include <assert.h>
#include <memory_resource> #include <memory_resource>
#include <algorithm>
#ifndef DEFAULT_ALLOC_SIZE #ifndef DEFAULT_ALLOC_SIZE
#define DEFAULT_ALLOC_SIZE 16 #define DEFAULT_ALLOC_SIZE 16
#endif #endif
namespace Seele namespace Seele {
{ template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> struct Array {
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> public:
struct Array template <typename X> class IteratorBase {
{
public:
template <typename X>
class IteratorBase
{
public: public:
using iterator_category = std::random_access_iterator_tag; using iterator_category = std::random_access_iterator_tag;
using value_type = X; using value_type = X;
@@ -26,78 +22,48 @@ public:
using reference = X&; using reference = X&;
using pointer = X*; using pointer = X*;
constexpr IteratorBase(X *x = nullptr) constexpr IteratorBase(X* x = nullptr) : p(x) {}
: p(x) constexpr reference operator*() const { return *p; }
{ constexpr pointer operator->() const { return p; }
} constexpr bool operator==(const IteratorBase& other) const { return p == other.p; }
constexpr reference operator*() const constexpr bool operator!=(const IteratorBase& other) const { return p != other.p; }
{ constexpr std::strong_ordering operator<=>(const IteratorBase& other) const { return p <=> other.p; }
return *p; constexpr IteratorBase operator+(size_t other) const {
}
constexpr pointer operator->() const
{
return p;
}
constexpr bool operator==(const IteratorBase &other) const
{
return p == other.p;
}
constexpr bool operator!=(const IteratorBase &other) const
{
return p != other.p;
}
constexpr std::strong_ordering operator<=>(const IteratorBase &other) const
{
return p <=> other.p;
}
constexpr IteratorBase operator+(size_t other) const
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
tmp.p += other; tmp.p += other;
return tmp; return tmp;
} }
constexpr int operator-(const IteratorBase &other) const constexpr int operator-(const IteratorBase& other) const { return (int)(p - other.p); }
{ constexpr IteratorBase& operator-=(difference_type other) {
return (int)(p - other.p); p -= other;
}
constexpr IteratorBase& operator-=(difference_type other)
{
p-=other;
return *this; return *this;
} }
constexpr IteratorBase& operator+=(difference_type other) constexpr IteratorBase& operator+=(difference_type other) {
{ p += other;
p+=other;
return *this; return *this;
} }
constexpr IteratorBase operator-(difference_type diff) const constexpr IteratorBase operator-(difference_type diff) const { return IteratorBase(p - diff); }
{ constexpr IteratorBase& operator++() {
return IteratorBase(p - diff);
}
constexpr IteratorBase &operator++()
{
p++; p++;
return *this; return *this;
} }
constexpr IteratorBase &operator--() constexpr IteratorBase& operator--() {
{
p--; p--;
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;
} }
private: private:
X *p; X* p;
}; };
using value_type = T; using value_type = T;
@@ -116,97 +82,63 @@ 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 Array() noexcept(noexcept(Allocator())) constexpr Array() noexcept(noexcept(Allocator())) : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(Allocator()) {
: arraySize(0)
, allocated(DEFAULT_ALLOC_SIZE)
, allocator(Allocator())
{
_data = allocateArray(DEFAULT_ALLOC_SIZE); _data = allocateArray(DEFAULT_ALLOC_SIZE);
assert(_data != nullptr); assert(_data != nullptr);
} }
constexpr explicit Array(const allocator_type& alloc) noexcept constexpr explicit Array(const allocator_type& alloc) noexcept : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(alloc) {
: arraySize(0)
, allocated(DEFAULT_ALLOC_SIZE)
, allocator(alloc)
{
_data = allocateArray(DEFAULT_ALLOC_SIZE); _data = allocateArray(DEFAULT_ALLOC_SIZE);
assert(_data != nullptr); assert(_data != nullptr);
} }
constexpr Array(size_type size, const value_type& value, const allocator_type& alloc = allocator_type()) constexpr Array(size_type size, const value_type& value, const allocator_type& alloc = allocator_type())
: arraySize(size) : arraySize(size), allocated(size), allocator(alloc) {
, allocated(size)
, allocator(alloc)
{
_data = allocateArray(size); _data = allocateArray(size);
assert(_data != nullptr); assert(_data != nullptr);
for (size_type i = 0; i < size; ++i) for (size_type i = 0; i < size; ++i) {
{
std::allocator_traits<allocator_type>::construct(allocator, &_data[i], value); std::allocator_traits<allocator_type>::construct(allocator, &_data[i], value);
} }
} }
constexpr explicit Array(size_type size, const allocator_type& alloc = allocator_type()) constexpr explicit Array(size_type size, const allocator_type& alloc = allocator_type())
: arraySize(size) : arraySize(size), allocated(size), allocator(alloc) {
, allocated(size)
, allocator(alloc)
{
_data = allocateArray(size); _data = allocateArray(size);
assert(_data != nullptr); assert(_data != nullptr);
if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>) if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>) {
{
std::memset(_data, 0, size * sizeof(T)); std::memset(_data, 0, size * sizeof(T));
} } else {
else for (size_type i = 0; i < size; ++i) {
{
for (size_type i = 0; i < size; ++i)
{
std::allocator_traits<allocator_type>::construct(allocator, &_data[i]); std::allocator_traits<allocator_type>::construct(allocator, &_data[i]);
} }
} }
} }
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type()) constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
: arraySize(init.size()) : arraySize(init.size()), allocated(init.size()), allocator(alloc) {
, allocated(init.size())
, allocator(alloc)
{
_data = allocateArray(init.size()); _data = allocateArray(init.size());
assert(_data != nullptr); assert(_data != nullptr);
std::uninitialized_move(init.begin(), init.end(), begin()); std::uninitialized_move(init.begin(), init.end(), begin());
} }
constexpr Array(const Array &other) constexpr Array(const Array& other)
: arraySize(other.arraySize) : arraySize(other.arraySize), allocated(other.allocated),
, allocated(other.allocated) allocator(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator)) {
, allocator(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator))
{
_data = allocateArray(other.allocated); _data = allocateArray(other.allocated);
assert(_data != nullptr); assert(_data != nullptr);
std::uninitialized_copy(other.begin(), other.end(), begin()); std::uninitialized_copy(other.begin(), other.end(), begin());
} }
constexpr Array(const Array& other, const Allocator& alloc) constexpr Array(const Array& other, const Allocator& alloc) : arraySize(other.arraySize), allocated(other.allocated), allocator(alloc) {
: arraySize(other.arraySize)
, allocated(other.allocated)
, allocator(alloc)
{
_data = allocateArray(other.allocated); _data = allocateArray(other.allocated);
assert(_data != nullptr); assert(_data != nullptr);
std::uninitialized_copy(other.begin(), other.end(), begin()); std::uninitialized_copy(other.begin(), other.end(), begin());
} }
constexpr Array(Array &&other) noexcept constexpr Array(Array&& other) noexcept
: arraySize(std::move(other.arraySize)) : arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(std::move(other.allocator)) {
, allocated(std::move(other.allocated))
, allocator(std::move(other.allocator))
{
_data = other._data; _data = other._data;
other._data = nullptr; other._data = nullptr;
other.allocated = 0; other.allocated = 0;
other.arraySize = 0; other.arraySize = 0;
} }
constexpr Array(Array &&other, const Allocator& alloc) noexcept constexpr Array(Array&& other, const Allocator& alloc) noexcept
: arraySize(std::move(other.arraySize)) : arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(alloc) {
, allocated(std::move(other.allocated))
, allocator(alloc)
{
_data = allocateArray(other.allocated); _data = allocateArray(other.allocated);
std::uninitialized_move(other.begin(), other.end(), begin()); std::uninitialized_move(other.begin(), other.end(), begin());
other.deallocateArray(other._data, other.allocated); other.deallocateArray(other._data, other.allocated);
@@ -214,25 +146,18 @@ public:
other.allocated = 0; other.allocated = 0;
other.arraySize = 0; other.arraySize = 0;
} }
Array &operator=(const Array &other) Array& operator=(const Array& other) {
{ if (this != &other) {
if (this != &other) if (other.arraySize > allocated) {
{
if (other.arraySize > allocated)
{
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;
} }
if(_data == nullptr) if (_data == nullptr) {
{
_data = allocateArray(other.allocated); _data = allocateArray(other.allocated);
allocated = other.allocated; allocated = other.allocated;
} }
@@ -241,17 +166,13 @@ public:
} }
return *this; return *this;
} }
Array &operator=(Array &&other) noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value Array& operator=(Array&& other) noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
|| std::allocator_traits<Allocator>::is_always_equal::value) std::allocator_traits<Allocator>::is_always_equal::value) {
{ if (this != &other) {
if (this != &other) if (_data != nullptr) {
{
if (_data != nullptr)
{
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);
} }
allocated = std::move(other.allocated); allocated = std::move(other.allocated);
@@ -261,153 +182,96 @@ public:
} }
return *this; return *this;
} }
constexpr ~Array() constexpr ~Array() { clear(); }
{
clear();
}
[[nodiscard]] [[nodiscard]]
constexpr iterator find(const value_type &item) noexcept constexpr iterator find(const value_type& item) noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (_data[i] == item) {
{
if (_data[i] == item)
{
return iterator(&_data[i]); return iterator(&_data[i]);
} }
} }
return end(); return end();
} }
[[nodiscard]] [[nodiscard]]
constexpr iterator find(value_type&& item) noexcept constexpr iterator find(value_type&& item) noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (_data[i] == item) {
{
if (_data[i] == item)
{
return iterator(&_data[i]); return iterator(&_data[i]);
} }
} }
return end(); return end();
} }
[[nodiscard]] [[nodiscard]]
constexpr const_iterator find(const value_type &item) const noexcept constexpr const_iterator find(const value_type& item) const noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (_data[i] == item) {
{
if (_data[i] == item)
{
return const_iterator(&_data[i]); return const_iterator(&_data[i]);
} }
} }
return end(); return end();
} }
[[nodiscard]] [[nodiscard]]
constexpr const_iterator find(value_type&& item) const noexcept constexpr const_iterator find(value_type&& item) const noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (_data[i] == item) {
{
if (_data[i] == item)
{
return const_iterator(&_data[i]); return const_iterator(&_data[i]);
} }
} }
return end(); return end();
} }
template<class Pred> template <class Pred>
requires std::predicate<Pred, value_type> requires std::predicate<Pred, value_type>
constexpr const_iterator find(Pred pred) const noexcept constexpr const_iterator find(Pred pred) const noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (pred(_data[i])) {
{
if(pred(_data[i]))
{
return const_iterator(&_data[i]); return const_iterator(&_data[i]);
} }
} }
return end(); return end();
} }
template<class Pred> template <class Pred>
requires std::predicate<Pred, value_type> requires std::predicate<Pred, value_type>
constexpr iterator find(Pred pred) noexcept constexpr iterator find(Pred pred) noexcept {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i) if (pred(_data[i])) {
{
if (pred(_data[i]))
{
return iterator(&_data[i]); return iterator(&_data[i]);
} }
} }
return end(); return end();
} }
constexpr allocator_type get_allocator() const noexcept constexpr allocator_type get_allocator() const noexcept { return allocator; }
{ constexpr iterator begin() noexcept { return iterator(_data); }
return allocator; constexpr iterator end() noexcept { return iterator(_data + arraySize); }
} constexpr const_iterator begin() const noexcept { return const_iterator(_data); }
constexpr iterator begin() noexcept constexpr const_iterator end() const noexcept { return const_iterator(_data + arraySize); }
{ constexpr const_iterator cbegin() const noexcept { return const_iterator(_data); }
return iterator(_data); constexpr const_iterator cend() const noexcept { return const_iterator(_data + arraySize); }
} constexpr reference add(const value_type& item = value_type()) { return addInternal(item); }
constexpr iterator end() noexcept constexpr reference add(value_type&& item) { return addInternal(std::forward<T>(item)); }
{ constexpr void addAll(const Array& other) {
return iterator(_data + arraySize); for (const auto& value : other) {
}
constexpr const_iterator begin() const noexcept
{
return const_iterator(_data);
}
constexpr const_iterator end() const noexcept
{
return const_iterator(_data + arraySize);
}
constexpr const_iterator cbegin() const noexcept
{
return const_iterator(_data);
}
constexpr const_iterator cend() const noexcept
{
return const_iterator(_data + arraySize);
}
constexpr reference add(const value_type &item = value_type())
{
return addInternal(item);
}
constexpr reference add(value_type&& item)
{
return addInternal(std::forward<T>(item));
}
constexpr void addAll(const Array& other)
{
for(const auto& value : other)
{
addInternal(value); addInternal(value);
} }
} }
constexpr void addAll(Array&& other) constexpr void addAll(Array&& other) {
{ for (auto&& value : other) {
for(auto&& value : other)
{
addInternal(value); addInternal(value);
} }
} }
constexpr reference addUnique(const value_type &item = value_type()) constexpr reference addUnique(const value_type& item = value_type()) {
{
iterator it; iterator it;
if((it = std::move(find(item))) != end()) if ((it = std::move(find(item))) != end()) {
{
return *it; return *it;
} }
return addInternal(item); return addInternal(item);
} }
template<typename... args> template <typename... args> constexpr reference emplace(args... arguments) {
constexpr reference emplace(args... arguments) if (arraySize == allocated) {
{
if (arraySize == allocated)
{
size_type newSize = arraySize + 1; size_type newSize = arraySize + 1;
allocated = calculateGrowth(newSize); allocated = calculateGrowth(newSize);
T *tempArray = allocateArray(allocated); T* tempArray = allocateArray(allocated);
assert(tempArray != nullptr); assert(tempArray != nullptr);
std::uninitialized_move(begin(), end(), Iterator(tempArray)); std::uninitialized_move(begin(), end(), Iterator(tempArray));
@@ -417,61 +281,33 @@ public:
std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize++], arguments...); std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize++], arguments...);
return _data[arraySize - 1]; return _data[arraySize - 1];
} }
template<class Pred> template <class Pred>
requires std::predicate<Pred, value_type> requires std::predicate<Pred, value_type>
constexpr void remove_if(Pred pred, bool keepOrder = true) constexpr void remove_if(Pred pred, bool keepOrder = true) {
{
remove(find(pred), keepOrder); remove(find(pred), keepOrder);
} }
constexpr void remove(const value_type& element, bool keepOrder = true) constexpr void remove(const value_type& element, bool keepOrder = true) { remove(find(element), keepOrder); }
{ constexpr void remove(value_type&& element, bool keepOrder = true) { remove(find(element), keepOrder); }
remove(find(element), keepOrder); constexpr void remove(iterator it, bool keepOrder = true) { removeAt(it - begin(), keepOrder); }
constexpr void remove(const_iterator it, bool keepOrder = true) { removeAt(it - cbegin(), keepOrder); }
constexpr void removeAt(size_type index, bool keepOrder = true) {
if (keepOrder) {
for (size_type i = index; i < arraySize - 1; ++i) {
_data[i] = std::move(_data[i + 1]);
} }
constexpr void remove(value_type&& element, bool keepOrder = true) } else {
{
remove(find(element), keepOrder);
}
constexpr void remove(iterator it, bool keepOrder = true)
{
removeAt(it - begin(), keepOrder);
}
constexpr void remove(const_iterator it, bool keepOrder = true)
{
removeAt(it - cbegin(), keepOrder);
}
constexpr void removeAt(size_type index, bool keepOrder = true)
{
if (keepOrder)
{
for(size_type i = index; i < arraySize-1; ++i)
{
_data[i] = std::move(_data[i+1]);
}
}
else
{
_data[index] = std::move(_data[arraySize - 1]); _data[index] = std::move(_data[arraySize - 1]);
} }
std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]); std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]);
} }
constexpr void resize(size_type newSize) constexpr void resize(size_type newSize) { resizeInternal(newSize, T()); }
{ constexpr void resize(size_type newSize, const value_type& value) { resizeInternal(newSize, value); }
resizeInternal(newSize, T()); constexpr void clear() noexcept {
} if (_data == nullptr) {
constexpr void resize(size_type newSize, const value_type& value)
{
resizeInternal(newSize, value);
}
constexpr void clear() noexcept
{
if(_data == nullptr)
{
return; return;
} }
if constexpr (!std::is_trivially_destructible_v<T>) if constexpr (!std::is_trivially_destructible_v<T>) {
{ for (size_type i = 0; i < arraySize; ++i) {
for (size_type i = 0; i < arraySize; ++i)
{
std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]); std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]);
} }
} }
@@ -480,42 +316,21 @@ public:
arraySize = 0; arraySize = 0;
allocated = 0; allocated = 0;
} }
constexpr size_type indexOf(iterator iterator) constexpr size_type indexOf(iterator iterator) { return iterator - begin(); }
{ constexpr size_type indexOf(const_iterator iterator) const { return iterator.p - begin().p; }
return iterator - begin(); constexpr size_type indexOf(T& t) { return indexOf(find(t)); }
} constexpr size_type indexOf(const T& t) const { return indexOf(find(t)); }
constexpr size_type indexOf(const_iterator iterator) const constexpr size_type size() const noexcept { return arraySize; }
{
return iterator.p - begin().p;
}
constexpr size_type indexOf(T& t)
{
return indexOf(find(t));
}
constexpr size_type indexOf(const T& t) const
{
return indexOf(find(t));
}
constexpr size_type size() const noexcept
{
return arraySize;
}
[[nodiscard]] [[nodiscard]]
constexpr bool empty() const noexcept constexpr bool empty() const noexcept {
{
return arraySize == 0; return arraySize == 0;
} }
constexpr void reserve(size_type new_cap) constexpr void reserve(size_type new_cap) {
{ if (new_cap > allocated) {
if(new_cap > allocated)
{
T* temp = allocateArray(new_cap); T* temp = allocateArray(new_cap);
if constexpr (std::is_trivially_copyable_v<T>) if constexpr (std::is_trivially_copyable_v<T>) {
{
std::memcpy(temp, _data, sizeof(T) * arraySize); std::memcpy(temp, _data, sizeof(T) * arraySize);
} } else {
else
{
std::uninitialized_move_n(begin(), arraySize, temp); std::uninitialized_move_n(begin(), arraySize, temp);
} }
deallocateArray(_data, allocated); deallocateArray(_data, allocated);
@@ -523,78 +338,55 @@ public:
} }
allocated = new_cap; allocated = new_cap;
} }
constexpr size_type capacity() const noexcept constexpr size_type capacity() const noexcept { return allocated; }
{ constexpr pointer data() const noexcept { return _data; }
return allocated; constexpr reference front() const {
}
constexpr pointer data() const noexcept
{
return _data;
}
constexpr reference front() const
{
assert(arraySize > 0); assert(arraySize > 0);
return _data[0]; return _data[0];
} }
constexpr reference back() const constexpr reference back() const {
{
assert(arraySize > 0); assert(arraySize > 0);
return _data[arraySize - 1]; return _data[arraySize - 1];
} }
constexpr void pop() constexpr void pop() { std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]); }
{ constexpr reference operator[](size_type index) {
std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]);
}
constexpr reference operator[](size_type index)
{
assert(index < arraySize); assert(index < arraySize);
return _data[index]; return _data[index];
} }
constexpr const_reference operator[](size_type index) const constexpr const_reference operator[](size_type index) const {
{
assert(index < arraySize); assert(index < arraySize);
return _data[index]; return _data[index];
} }
private:
size_type calculateGrowth(size_type newSize) const private:
{ size_type calculateGrowth(size_type newSize) const {
const size_type oldCapacity = capacity(); const size_type oldCapacity = capacity();
if (oldCapacity > SIZE_MAX - oldCapacity) if (oldCapacity > SIZE_MAX - oldCapacity) {
{
return newSize; // geometric growth would overflow return newSize; // geometric growth would overflow
} }
const size_type geometric = oldCapacity + oldCapacity; const size_type geometric = oldCapacity + oldCapacity;
if (geometric < newSize) if (geometric < newSize) {
{
return newSize; // geometric growth would be insufficient return newSize; // geometric growth would be insufficient
} }
return geometric; // geometric growth is sufficient return geometric; // geometric growth is sufficient
} }
[[nodiscard]] [[nodiscard]]
T* allocateArray(size_type size) T* allocateArray(size_type size) {
{
T* result = allocator.allocate(size); T* result = allocator.allocate(size);
assert(result != nullptr); assert(result != nullptr);
return result; return result;
} }
void deallocateArray(T* ptr, size_type size) void deallocateArray(T* ptr, size_type size) { allocator.deallocate(ptr, size); }
{ template <typename Type> T& addInternal(Type&& t) noexcept {
allocator.deallocate(ptr, size); if (arraySize == allocated) {
}
template<typename Type>
T& addInternal(Type&& t) noexcept
{
if (arraySize == allocated)
{
size_type newSize = arraySize + 1; size_type newSize = arraySize + 1;
allocated = calculateGrowth(newSize); allocated = calculateGrowth(newSize);
T *tempArray = allocateArray(allocated); T* tempArray = allocateArray(allocated);
for (size_type i = 0; i < arraySize; ++i) for (size_type i = 0; i < arraySize; ++i) {
{
std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::forward<Type>(_data[i])); std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::forward<Type>(_data[i]));
} }
deallocateArray(_data, arraySize); deallocateArray(_data, arraySize);
@@ -603,52 +395,37 @@ private:
std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize], std::forward<Type>(t)); std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize], std::forward<Type>(t));
return _data[arraySize++]; return _data[arraySize++];
} }
template<typename Type> template <typename Type> void resizeInternal(size_type newSize, const Type& value) noexcept {
void resizeInternal(size_type newSize, const Type& value) noexcept if (newSize <= allocated) {
{
if (newSize <= allocated)
{
// The array is already big enough // The array is already big enough
if(newSize < arraySize) if (newSize < arraySize) {
{
// But since we are sizing down we destruct some of them // But since we are sizing down we destruct some of them
if constexpr (!std::is_trivially_destructible_v<T>) if constexpr (!std::is_trivially_destructible_v<T>) {
{ for (size_type i = newSize; i < arraySize; ++i) {
for (size_type i = newSize; i < arraySize; ++i)
{
std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]); std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]);
} }
} }
} } else {
else
{
// Or construct the new elements by default // Or construct the new elements by default
for(size_type i = arraySize; i < newSize; ++i) for (size_type i = arraySize; i < newSize; ++i) {
{
std::allocator_traits<allocator_type>::construct(allocator, &_data[i], value); std::allocator_traits<allocator_type>::construct(allocator, &_data[i], value);
} }
} }
arraySize = newSize; arraySize = newSize;
} } else {
else
{
allocated = calculateGrowth(newSize); allocated = calculateGrowth(newSize);
// The array is not big enough, so we make a new one // The array is not big enough, so we make a new one
T *newData = allocateArray(allocated); T* newData = allocateArray(allocated);
if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>) if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>) {
{
std::memcpy(newData, _data, sizeof(T) * arraySize); std::memcpy(newData, _data, sizeof(T) * arraySize);
std::memset(&newData[arraySize], 0, sizeof(T) * (allocated - arraySize)); std::memset(&newData[arraySize], 0, sizeof(T) * (allocated - arraySize));
} } else {
else
{
// And move the current elements into that one // And move the current elements into that one
std::uninitialized_move(begin(), end(), Iterator(newData)); std::uninitialized_move(begin(), end(), Iterator(newData));
// As well as default initialize the others // As well as default initialize the others
for (size_type i = arraySize; i < allocated; ++i) for (size_type i = arraySize; i < allocated; ++i) {
{
std::allocator_traits<allocator_type>::construct(allocator, &newData[i], value); std::allocator_traits<allocator_type>::construct(allocator, &newData[i], value);
} }
} }
@@ -659,41 +436,29 @@ private:
} }
size_type arraySize = 0; size_type arraySize = 0;
size_type allocated = 0; size_type allocated = 0;
T *_data = nullptr; T* _data = nullptr;
allocator_type allocator; allocator_type allocator;
}; };
template <class Type, class Alloc> constexpr bool operator==(const Array<Type, Alloc>& lhs, const Array<Type, Alloc>& rhs) {
template<class Type, class Alloc> if (lhs.size() != rhs.size()) {
constexpr bool operator==(const Array<Type, Alloc> &lhs, const Array<Type, Alloc>& rhs)
{
if(lhs.size() != rhs.size())
{
return false; return false;
} }
for(auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2) for (auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2) {
{ if (*it1 != *it2) {
if(*it1 != *it2)
{
return false; return false;
} }
} }
return true; return true;
} }
template<class Type, class Alloc> template <class Type, class Alloc> constexpr auto operator<=>(const Array<Type, Alloc>& lhs, const Array<Type, Alloc>& rhs) {
constexpr auto operator<=>(const Array<Type, Alloc>& lhs, const Array<Type, Alloc>& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
} }
template <typename T, size_t N> template <typename T, size_t N> struct StaticArray {
struct StaticArray public:
{ template <typename X> class IteratorBase {
public:
template <typename X>
class IteratorBase
{
public: public:
using iterator_category = std::random_access_iterator_tag; using iterator_category = std::random_access_iterator_tag;
using value_type = X; using value_type = X;
@@ -701,52 +466,32 @@ public:
using reference = X&; using reference = X&;
using pointer = X*; using pointer = X*;
IteratorBase(X *x = nullptr) IteratorBase(X* x = nullptr) : p(x) {}
: p(x) reference operator*() const { return *p; }
{ pointer operator->() const { return p; }
} inline bool operator!=(const IteratorBase& other) { return p != other.p; }
reference operator*() const inline bool operator==(const IteratorBase& other) { return p == other.p; }
{ IteratorBase& operator++() {
return *p;
}
pointer operator->() const
{
return p;
}
inline bool operator!=(const IteratorBase &other)
{
return p != other.p;
}
inline bool operator==(const IteratorBase &other)
{
return p == other.p;
}
IteratorBase &operator++()
{
p++; p++;
return *this; return *this;
} }
IteratorBase operator++(int) IteratorBase operator++(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
++*this; ++*this;
return tmp; return tmp;
} }
IteratorBase &operator--() IteratorBase& operator--() {
{
p--; p--;
return *this; return *this;
} }
IteratorBase operator--(int) IteratorBase operator--(int) {
{
IteratorBase tmp(*this); IteratorBase tmp(*this);
--*this; --*this;
return tmp; return tmp;
} }
private: private:
X *p; X* p;
}; };
using value_type = T; using value_type = T;
using size_type = size_t; using size_type = size_t;
@@ -762,85 +507,47 @@ 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>;
StaticArray() StaticArray() {
{
beginIt = iterator(_data); beginIt = iterator(_data);
endIt = iterator(_data + N); endIt = iterator(_data + N);
} }
StaticArray(T value) StaticArray(T value) {
{ for (size_t i = 0; i < N; ++i) {
for (size_t i = 0; i < N; ++i)
{
_data[i] = value; _data[i] = value;
} }
beginIt = iterator(_data); beginIt = iterator(_data);
endIt = iterator(_data + N); endIt = iterator(_data + N);
} }
StaticArray(std::initializer_list<T> init) StaticArray(std::initializer_list<T> init) {
{
auto beg = init.begin(); auto beg = init.begin();
for (size_t i = 0; i < N; ++i) for (size_t i = 0; i < N; ++i) {
{
_data[i] = *beg; _data[i] = *beg;
if (init.size() == N) if (init.size() == N) {
{
beg++; beg++;
} }
} }
} }
~StaticArray() ~StaticArray() {}
{
}
inline size_type size() const inline size_type size() const { return N; }
{ inline pointer data() { return _data; }
return N; inline const_pointer data() const { return _data; }
} template <typename I> constexpr reference operator[](I index) noexcept { return operator[](static_cast<size_t>(index)); }
inline pointer data() template <typename I> constexpr const_reference operator[](I index) const noexcept { return operator[](static_cast<size_t>(index)); }
{ constexpr reference operator[](size_type index) noexcept {
return _data;
}
inline const_pointer data() const
{
return _data;
}
template<typename I>
constexpr reference operator[](I index) noexcept
{
return operator[](static_cast<size_t>(index));
}
template<typename I>
constexpr const_reference operator[](I index) const noexcept
{
return operator[](static_cast<size_t>(index));
}
constexpr reference operator[](size_type index) noexcept
{
assert(index < N); assert(index < N);
return _data[index]; return _data[index];
} }
constexpr const_reference operator[](size_type index) const noexcept constexpr const_reference operator[](size_type index) const noexcept {
{
assert(index < N); assert(index < N);
return _data[index]; return _data[index];
} }
iterator begin() iterator begin() { return beginIt; }
{ iterator end() { return endIt; }
return beginIt; const_iterator begin() const { return beginIt; }
} const_iterator end() const { return beginIt; }
iterator end()
{ private:
return endIt;
}
const_iterator begin() const
{
return beginIt;
}
const_iterator end() const
{
return beginIt;
}
private:
T _data[N]; T _data[N];
iterator beginIt; iterator beginIt;
iterator endIt; iterator endIt;
+102 -269
View File
@@ -1,35 +1,22 @@
#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;
@@ -37,82 +24,48 @@ public:
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
+103 -274
View File
@@ -1,39 +1,22 @@
#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;
@@ -41,106 +24,64 @@ public:
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) {
if (this != &other) {
clear(); clear();
} if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
constexpr Tree& operator=(const Tree& other)
{
if (this != &other)
{
clear();
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;
+11 -37
View File
@@ -3,31 +3,17 @@
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) {
{
switch (indexType)
{
case SE_INDEX_TYPE_UINT16: case SE_INDEX_TYPE_UINT16:
numIndices = size / sizeof(uint16); numIndices = size / sizeof(uint16);
break; break;
@@ -38,25 +24,13 @@ IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexTy
break; 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() {}
+25 -36
View File
@@ -1,37 +1,35 @@
#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,
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0; SePipelineStageFlags dstStage) = 0;
uint32 numVertices; uint32 numVertices;
uint32 vertexSize; uint32 vertexSize;
@@ -39,21 +37,18 @@ protected:
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,
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0; SePipelineStageFlags dstStage) = 0;
Gfx::SeIndexType indexType; Gfx::SeIndexType indexType;
uint64 numIndices; uint64 numIndices;
@@ -62,42 +57,36 @@ 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,
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0; 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, virtual void* mapRegion(uint64 offset = 0, uint64 size = -1, bool writeOnly = true) = 0;
bool writeOnly = true) = 0;
virtual void unmap() = 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,
SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0; SePipelineStageFlags dstStage) = 0;
uint32 numElements; uint32 numElements;
+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;
}; };
+5 -10
View File
@@ -45,7 +45,7 @@ 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;
@@ -54,18 +54,13 @@ PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayo
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;
+23 -31
View File
@@ -1,7 +1,8 @@
#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 {
@@ -18,22 +19,20 @@ struct DescriptorBinding {
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 uint32 getHash() const { return hash; }
constexpr const std::string &getName() const { return name; } 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;
@@ -45,7 +44,7 @@ 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;
@@ -57,49 +56,42 @@ 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, virtual void updateTexture(uint32 binding, PTexture texture, PSampler samplerState = nullptr) = 0;
PSampler samplerState = nullptr) = 0; virtual void updateTextureArray(uint32_t binding, Array<PTexture> texture) = 0;
virtual void updateTextureArray(uint32_t binding,
Array<PTexture> texture) = 0;
bool operator<(PDescriptorSet other); 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]; }
}
constexpr uint32 findParameter(const std::string &param) const {
return parameterMapping[param];
}
void addMapping(Map<std::string, uint32> mapping); void addMapping(Map<std::string, uint32> mapping);
constexpr std::string getName() const { return name; }; 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;
+8 -9
View File
@@ -4,9 +4,8 @@
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:
@@ -15,15 +14,15 @@ FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format)
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:
@@ -45,21 +44,21 @@ FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format)
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:
+93 -182
View File
@@ -1,12 +1,11 @@
#pragma once #pragma once
#include "MinimalEngine.h"
#include "Math/Vector.h" #include "Math/Vector.h"
#include "MinimalEngine.h"
namespace Seele
{ namespace Seele {
// Input codes matching GLFW for convenience, since its the primary windowing system // Input codes matching GLFW for convenience, since its the primary windowing system
enum class KeyCode : size_t enum class KeyCode : size_t {
{
/* Printable keys */ /* Printable keys */
KEY_SPACE = 32, KEY_SPACE = 32,
KEY_APOSTROPHE = 39 /* ' */, KEY_APOSTROPHE = 39 /* ' */,
@@ -132,8 +131,7 @@ enum class KeyCode : size_t
KEY_LAST = KEY_MENU KEY_LAST = KEY_MENU
}; };
enum class MouseButton enum class MouseButton {
{
MOUSE_BUTTON_1 = 0, MOUSE_BUTTON_1 = 0,
MOUSE_BUTTON_2 = 1, MOUSE_BUTTON_2 = 1,
MOUSE_BUTTON_3 = 2, MOUSE_BUTTON_3 = 2,
@@ -144,15 +142,9 @@ enum class MouseButton
MOUSE_BUTTON_8 = 7, MOUSE_BUTTON_8 = 7,
}; };
enum class InputAction enum class InputAction { RELEASE = 0, PRESS = 1, REPEAT = 2 };
{
RELEASE = 0,
PRESS = 1,
REPEAT = 2
};
enum class KeyModifier : uint32 enum class KeyModifier : uint32 {
{
MOD_SHIFT = 0x0001, MOD_SHIFT = 0x0001,
MOD_CONTROL = 0x0002, MOD_CONTROL = 0x0002,
MOD_ALT = 0x0004, MOD_ALT = 0x0004,
@@ -162,8 +154,7 @@ enum class KeyModifier : uint32
}; };
typedef uint32 KeyModifierFlags; typedef uint32 KeyModifierFlags;
namespace Gfx namespace Gfx {
{
static constexpr bool useAsyncCompute = false; static constexpr bool useAsyncCompute = false;
static constexpr bool useMeshShading = true; static constexpr bool useMeshShading = true;
static constexpr uint32 numFramesBuffered = 3; static constexpr uint32 numFramesBuffered = 3;
@@ -174,8 +165,7 @@ static constexpr uint32 numPrimitivesPerMeshlet = 256;
double getCurrentFrameDelta(); double getCurrentFrameDelta();
uint32 getCurrentFrameIndex(); uint32 getCurrentFrameIndex();
enum class QueueType enum class QueueType {
{
GRAPHICS = 1, GRAPHICS = 1,
COMPUTE = 2, COMPUTE = 2,
TRANSFER = 3, TRANSFER = 3,
@@ -185,8 +175,7 @@ typedef uint32_t SeFlags;
typedef uint32_t SeBool32; typedef uint32_t SeBool32;
typedef uint64_t SeDeviceSize; typedef uint64_t SeDeviceSize;
typedef uint32_t SeSampleMask; typedef uint32_t SeSampleMask;
typedef enum SeResult typedef enum SeResult {
{
SE_SUCCESS = 0, SE_SUCCESS = 0,
SE_NOT_READY = 1, SE_NOT_READY = 1,
SE_TIMEOUT = 2, SE_TIMEOUT = 2,
@@ -221,8 +210,7 @@ typedef enum SeResult
SE_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT = -1000255000, SE_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT = -1000255000,
} SeResult; } SeResult;
typedef enum SeStructureType typedef enum SeStructureType {
{
SE_STRUCTURE_TYPE_APPLICATION_INFO = 0, SE_STRUCTURE_TYPE_APPLICATION_INFO = 0,
SE_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1, SE_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1,
SE_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2, SE_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2,
@@ -598,8 +586,7 @@ typedef enum SeStructureType
SE_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT = 1000281001, SE_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT = 1000281001,
} SeStructureType; } SeStructureType;
typedef enum SeSystemAllocationScope typedef enum SeSystemAllocationScope {
{
SE_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0, SE_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0,
SE_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1, SE_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1,
SE_SYSTEM_ALLOCATION_SCOPE_CACHE = 2, SE_SYSTEM_ALLOCATION_SCOPE_CACHE = 2,
@@ -607,13 +594,11 @@ typedef enum SeSystemAllocationScope
SE_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4, SE_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4,
} SeSystemAllocationScope; } SeSystemAllocationScope;
typedef enum SeInternalAllocationType typedef enum SeInternalAllocationType {
{
SE_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0, SE_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0,
} SeInternalAllocationType; } SeInternalAllocationType;
typedef enum SeFormat typedef enum SeFormat {
{
SE_FORMAT_UNDEFINED = 0, SE_FORMAT_UNDEFINED = 0,
SE_FORMAT_R4G4_UNORM_PACK8 = 1, SE_FORMAT_R4G4_UNORM_PACK8 = 1,
SE_FORMAT_R4G4B4A4_UNORM_PACK16 = 2, SE_FORMAT_R4G4B4A4_UNORM_PACK16 = 2,
@@ -857,8 +842,7 @@ typedef enum SeFormat
SE_FORMAT_ASTC_12x12_SFLOAT_BLOCK = 1000066013, SE_FORMAT_ASTC_12x12_SFLOAT_BLOCK = 1000066013,
} SeFormat; } SeFormat;
struct FormatCompatibilityInfo struct FormatCompatibilityInfo {
{
// std::string class // std::string class
uint32 blockSize; uint32 blockSize;
UVector blockExtent; UVector blockExtent;
@@ -867,21 +851,18 @@ struct FormatCompatibilityInfo
FormatCompatibilityInfo getFormatInfo(SeFormat format); FormatCompatibilityInfo getFormatInfo(SeFormat format);
typedef enum SeImageType typedef enum SeImageType {
{
SE_IMAGE_TYPE_1D = 0, SE_IMAGE_TYPE_1D = 0,
SE_IMAGE_TYPE_2D = 1, SE_IMAGE_TYPE_2D = 1,
SE_IMAGE_TYPE_3D = 2, SE_IMAGE_TYPE_3D = 2,
} SeImageType; } SeImageType;
typedef enum SeImageTiling typedef enum SeImageTiling {
{
SE_IMAGE_TILING_OPTIMAL = 0, SE_IMAGE_TILING_OPTIMAL = 0,
SE_IMAGE_TILING_LINEAR = 1, SE_IMAGE_TILING_LINEAR = 1,
} SeImageTiling; } SeImageTiling;
typedef enum SePhysicalDeviceType typedef enum SePhysicalDeviceType {
{
SE_PHYSICAL_DEVICE_TYPE_OTHER = 0, SE_PHYSICAL_DEVICE_TYPE_OTHER = 0,
SE_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1, SE_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1,
SE_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2, SE_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2,
@@ -889,8 +870,7 @@ typedef enum SePhysicalDeviceType
SE_PHYSICAL_DEVICE_TYPE_CPU = 4, SE_PHYSICAL_DEVICE_TYPE_CPU = 4,
} SePhysicalDeviceType; } SePhysicalDeviceType;
typedef enum SeQueryType typedef enum SeQueryType {
{
SE_QUERY_TYPE_OCCLUSION = 0, SE_QUERY_TYPE_OCCLUSION = 0,
SE_QUERY_TYPE_PIPELINE_STATISTICS = 1, SE_QUERY_TYPE_PIPELINE_STATISTICS = 1,
SE_QUERY_TYPE_TIMESTAMP = 2, SE_QUERY_TYPE_TIMESTAMP = 2,
@@ -899,14 +879,12 @@ typedef enum SeQueryType
SE_QUERY_TYPE_PERFORMANCE_QUERY_INTEL = 1000210000, SE_QUERY_TYPE_PERFORMANCE_QUERY_INTEL = 1000210000,
} SeQueryType; } SeQueryType;
typedef enum SeSharingMode typedef enum SeSharingMode {
{
SE_SHARING_MODE_EXCLUSIVE = 0, SE_SHARING_MODE_EXCLUSIVE = 0,
SE_SHARING_MODE_CONCURRENT = 1, SE_SHARING_MODE_CONCURRENT = 1,
} SeSharingMode; } SeSharingMode;
typedef enum SeImageLayout typedef enum SeImageLayout {
{
SE_IMAGE_LAYOUT_UNDEFINED = 0, SE_IMAGE_LAYOUT_UNDEFINED = 0,
SE_IMAGE_LAYOUT_GENERAL = 1, SE_IMAGE_LAYOUT_GENERAL = 1,
SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2, SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2,
@@ -924,8 +902,7 @@ typedef enum SeImageLayout
SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000, SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000,
} SeImageLayout; } SeImageLayout;
typedef enum SeImageViewType typedef enum SeImageViewType {
{
SE_IMAGE_VIEW_TYPE_1D = 0, SE_IMAGE_VIEW_TYPE_1D = 0,
SE_IMAGE_VIEW_TYPE_2D = 1, SE_IMAGE_VIEW_TYPE_2D = 1,
SE_IMAGE_VIEW_TYPE_3D = 2, SE_IMAGE_VIEW_TYPE_3D = 2,
@@ -935,8 +912,7 @@ typedef enum SeImageViewType
SE_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6, SE_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6,
} SeImageViewType; } SeImageViewType;
typedef enum SeComponentSwizzle typedef enum SeComponentSwizzle {
{
SE_COMPONENT_SWIZZLE_IDENTITY = 0, SE_COMPONENT_SWIZZLE_IDENTITY = 0,
SE_COMPONENT_SWIZZLE_ZERO = 1, SE_COMPONENT_SWIZZLE_ZERO = 1,
SE_COMPONENT_SWIZZLE_ONE = 2, SE_COMPONENT_SWIZZLE_ONE = 2,
@@ -946,14 +922,12 @@ typedef enum SeComponentSwizzle
SE_COMPONENT_SWIZZLE_A = 6, SE_COMPONENT_SWIZZLE_A = 6,
} SeComponentSwizzle; } SeComponentSwizzle;
typedef enum SeVertexInputRate typedef enum SeVertexInputRate {
{
SE_VERTEX_INPUT_RATE_VERTEX = 0, SE_VERTEX_INPUT_RATE_VERTEX = 0,
SE_VERTEX_INPUT_RATE_INSTANCE = 1, SE_VERTEX_INPUT_RATE_INSTANCE = 1,
} SeVertexInputRate; } SeVertexInputRate;
typedef enum SePrimitiveTopology typedef enum SePrimitiveTopology {
{
SE_PRIMITIVE_TOPOLOGY_POINT_LIST = 0, SE_PRIMITIVE_TOPOLOGY_POINT_LIST = 0,
SE_PRIMITIVE_TOPOLOGY_LINE_LIST = 1, SE_PRIMITIVE_TOPOLOGY_LINE_LIST = 1,
SE_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2, SE_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2,
@@ -967,22 +941,19 @@ typedef enum SePrimitiveTopology
SE_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10, SE_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10,
} SePrimitiveTopology; } SePrimitiveTopology;
typedef enum SePolygonMode typedef enum SePolygonMode {
{
SE_POLYGON_MODE_FILL = 0, SE_POLYGON_MODE_FILL = 0,
SE_POLYGON_MODE_LINE = 1, SE_POLYGON_MODE_LINE = 1,
SE_POLYGON_MODE_POINT = 2, SE_POLYGON_MODE_POINT = 2,
SE_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000, SE_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000,
} SePolygonMode; } SePolygonMode;
typedef enum SeFrontFace typedef enum SeFrontFace {
{
SE_FRONT_FACE_COUNTER_CLOCKWISE = 0, SE_FRONT_FACE_COUNTER_CLOCKWISE = 0,
SE_FRONT_FACE_CLOCKWISE = 1, SE_FRONT_FACE_CLOCKWISE = 1,
} SeFrontFace; } SeFrontFace;
typedef enum SeCompareOp typedef enum SeCompareOp {
{
SE_COMPARE_OP_NEVER = 0, SE_COMPARE_OP_NEVER = 0,
SE_COMPARE_OP_LESS = 1, SE_COMPARE_OP_LESS = 1,
SE_COMPARE_OP_EQUAL = 2, SE_COMPARE_OP_EQUAL = 2,
@@ -993,8 +964,7 @@ typedef enum SeCompareOp
SE_COMPARE_OP_ALWAYS = 7, SE_COMPARE_OP_ALWAYS = 7,
} SeCompareOp; } SeCompareOp;
typedef enum SeStencilOp typedef enum SeStencilOp {
{
SE_STENCIL_OP_KEEP = 0, SE_STENCIL_OP_KEEP = 0,
SE_STENCIL_OP_ZERO = 1, SE_STENCIL_OP_ZERO = 1,
SE_STENCIL_OP_REPLACE = 2, SE_STENCIL_OP_REPLACE = 2,
@@ -1005,8 +975,7 @@ typedef enum SeStencilOp
SE_STENCIL_OP_DECREMENT_AND_WRAP = 7, SE_STENCIL_OP_DECREMENT_AND_WRAP = 7,
} SeStencilOp; } SeStencilOp;
typedef enum SeLogicOp typedef enum SeLogicOp {
{
SE_LOGIC_OP_CLEAR = 0, SE_LOGIC_OP_CLEAR = 0,
SE_LOGIC_OP_AND = 1, SE_LOGIC_OP_AND = 1,
SE_LOGIC_OP_AND_REVERSE = 2, SE_LOGIC_OP_AND_REVERSE = 2,
@@ -1025,8 +994,7 @@ typedef enum SeLogicOp
SE_LOGIC_OP_SET = 15, SE_LOGIC_OP_SET = 15,
} SeLogicOp; } SeLogicOp;
typedef enum SeBlendFactor typedef enum SeBlendFactor {
{
SE_BLEND_FACTOR_ZERO = 0, SE_BLEND_FACTOR_ZERO = 0,
SE_BLEND_FACTOR_ONE = 1, SE_BLEND_FACTOR_ONE = 1,
SE_BLEND_FACTOR_SRC_COLOR = 2, SE_BLEND_FACTOR_SRC_COLOR = 2,
@@ -1048,8 +1016,7 @@ typedef enum SeBlendFactor
SE_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18, SE_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18,
} SeBlendFactor; } SeBlendFactor;
typedef enum SeBlendOp typedef enum SeBlendOp {
{
SE_BLEND_OP_ADD = 0, SE_BLEND_OP_ADD = 0,
SE_BLEND_OP_SUBTRACT = 1, SE_BLEND_OP_SUBTRACT = 1,
SE_BLEND_OP_REVERSE_SUBTRACT = 2, SE_BLEND_OP_REVERSE_SUBTRACT = 2,
@@ -1103,8 +1070,7 @@ typedef enum SeBlendOp
SE_BLEND_OP_BLUE_EXT = 1000148045, SE_BLEND_OP_BLUE_EXT = 1000148045,
} SeBlendOp; } SeBlendOp;
typedef enum SeDynamicState typedef enum SeDynamicState {
{
SE_DYNAMIC_STATE_VIEWPORT = 0, SE_DYNAMIC_STATE_VIEWPORT = 0,
SE_DYNAMIC_STATE_SCISSOR = 1, SE_DYNAMIC_STATE_SCISSOR = 1,
SE_DYNAMIC_STATE_LINE_WIDTH = 2, SE_DYNAMIC_STATE_LINE_WIDTH = 2,
@@ -1123,21 +1089,18 @@ typedef enum SeDynamicState
SE_DYNAMIC_STATE_LINE_STIPPLE_EXT = 1000259000, SE_DYNAMIC_STATE_LINE_STIPPLE_EXT = 1000259000,
} SeDynamicState; } SeDynamicState;
typedef enum SeFilter typedef enum SeFilter {
{
SE_FILTER_NEAREST = 0, SE_FILTER_NEAREST = 0,
SE_FILTER_LINEAR = 1, SE_FILTER_LINEAR = 1,
SE_FILTER_CUBIC_IMG = 1000015000, SE_FILTER_CUBIC_IMG = 1000015000,
} SeFilter; } SeFilter;
typedef enum SeSamplerMipmapMode typedef enum SeSamplerMipmapMode {
{
SE_SAMPLER_MIPMAP_MODE_NEAREST = 0, SE_SAMPLER_MIPMAP_MODE_NEAREST = 0,
SE_SAMPLER_MIPMAP_MODE_LINEAR = 1, SE_SAMPLER_MIPMAP_MODE_LINEAR = 1,
} SeSamplerMipmapMode; } SeSamplerMipmapMode;
typedef enum SeSamplerAddressMode typedef enum SeSamplerAddressMode {
{
SE_SAMPLER_ADDRESS_MODE_REPEAT = 0, SE_SAMPLER_ADDRESS_MODE_REPEAT = 0,
SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1, SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1,
SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2, SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2,
@@ -1145,8 +1108,7 @@ typedef enum SeSamplerAddressMode
SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4, SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4,
} SeSamplerAddressMode; } SeSamplerAddressMode;
typedef enum SeBorderColor typedef enum SeBorderColor {
{
SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0, SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0,
SE_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1, SE_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1,
SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2, SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2,
@@ -1155,8 +1117,7 @@ typedef enum SeBorderColor
SE_BORDER_COLOR_INT_OPAQUE_WHITE = 5, SE_BORDER_COLOR_INT_OPAQUE_WHITE = 5,
} SeBorderColor; } SeBorderColor;
typedef enum SeDescriptorType typedef enum SeDescriptorType {
{
SE_DESCRIPTOR_TYPE_SAMPLER = 0, SE_DESCRIPTOR_TYPE_SAMPLER = 0,
SE_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1, SE_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1,
SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2, SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2,
@@ -1180,47 +1141,40 @@ typedef enum SeDescriptorBindingFlagBits {
} SeDescriptorBindingFlagBits; } SeDescriptorBindingFlagBits;
typedef SeFlags SeDescriptorBindingFlags; typedef SeFlags SeDescriptorBindingFlags;
typedef enum SeAttachmentLoadOp typedef enum SeAttachmentLoadOp {
{
SE_ATTACHMENT_LOAD_OP_LOAD = 0, SE_ATTACHMENT_LOAD_OP_LOAD = 0,
SE_ATTACHMENT_LOAD_OP_CLEAR = 1, SE_ATTACHMENT_LOAD_OP_CLEAR = 1,
SE_ATTACHMENT_LOAD_OP_DONT_CARE = 2, SE_ATTACHMENT_LOAD_OP_DONT_CARE = 2,
} SeAttachmentLoadOp; } SeAttachmentLoadOp;
typedef enum SeAttachmentStoreOp typedef enum SeAttachmentStoreOp {
{
SE_ATTACHMENT_STORE_OP_STORE = 0, SE_ATTACHMENT_STORE_OP_STORE = 0,
SE_ATTACHMENT_STORE_OP_DONT_CARE = 1, SE_ATTACHMENT_STORE_OP_DONT_CARE = 1,
} SeAttachmentStoreOp; } SeAttachmentStoreOp;
typedef enum SePipelineBindPoint typedef enum SePipelineBindPoint {
{
SE_PIPELINE_BIND_POINT_GRAPHICS = 0, SE_PIPELINE_BIND_POINT_GRAPHICS = 0,
SE_PIPELINE_BIND_POINT_COMPUTE = 1, SE_PIPELINE_BIND_POINT_COMPUTE = 1,
SE_PIPELINE_BIND_POINT_RAY_TRACING_NV = 1000165000, SE_PIPELINE_BIND_POINT_RAY_TRACING_NV = 1000165000,
} SePipelineBindPoint; } SePipelineBindPoint;
typedef enum SeCommandBufferLevel typedef enum SeCommandBufferLevel {
{
SE_COMMAND_BUFFER_LEVEL_PRIMARY = 0, SE_COMMAND_BUFFER_LEVEL_PRIMARY = 0,
SE_COMMAND_BUFFER_LEVEL_SECONDARY = 1, SE_COMMAND_BUFFER_LEVEL_SECONDARY = 1,
} SeCommandBufferLevel; } SeCommandBufferLevel;
typedef enum SeIndexType typedef enum SeIndexType {
{
SE_INDEX_TYPE_UINT16 = 0, SE_INDEX_TYPE_UINT16 = 0,
SE_INDEX_TYPE_UINT32 = 1, SE_INDEX_TYPE_UINT32 = 1,
SE_INDEX_TYPE_NONE_NV = 1000165000, SE_INDEX_TYPE_NONE_NV = 1000165000,
SE_INDEX_TYPE_UINT8_EXT = 1000265000, SE_INDEX_TYPE_UINT8_EXT = 1000265000,
} SeIndexType; } SeIndexType;
typedef enum SeSubpassContents typedef enum SeSubpassContents {
{
SE_SUBPASS_CONTENTS_INLINE = 0, SE_SUBPASS_CONTENTS_INLINE = 0,
} SeSubpassContents; } SeSubpassContents;
typedef enum SeObjectType typedef enum SeObjectType {
{
SE_OBJECT_TYPE_UNKNOWN = 0, SE_OBJECT_TYPE_UNKNOWN = 0,
SE_OBJECT_TYPE_INSTANCE = 1, SE_OBJECT_TYPE_INSTANCE = 1,
SE_OBJECT_TYPE_PHYSICAL_DEVICE = 2, SE_OBJECT_TYPE_PHYSICAL_DEVICE = 2,
@@ -1262,16 +1216,14 @@ typedef enum SeObjectType
SE_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000, SE_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000,
} SeObjectType; } SeObjectType;
typedef enum SeVendorId typedef enum SeVendorId {
{
SE_VENDOR_ID_VIV = 0x10001, SE_VENDOR_ID_VIV = 0x10001,
SE_VENDOR_ID_VSI = 0x10002, SE_VENDOR_ID_VSI = 0x10002,
SE_VENDOR_ID_KAZAN = 0x10003, SE_VENDOR_ID_KAZAN = 0x10003,
} SeVendorId; } SeVendorId;
typedef SeFlags SeInstanceCreateFlags; typedef SeFlags SeInstanceCreateFlags;
typedef enum SeFormatFeatureFlagBits typedef enum SeFormatFeatureFlagBits {
{
SE_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001, SE_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001,
SE_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002, SE_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002,
SE_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004, SE_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004,
@@ -1300,10 +1252,14 @@ typedef enum SeFormatFeatureFlagBits
SE_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_SRC_BIT, SE_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_SRC_BIT,
SE_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_DST_BIT, SE_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = SE_FORMAT_FEATURE_TRANSFER_DST_BIT,
SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT, SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT,
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT, SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR =
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT, SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT,
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT, SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR =
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR = SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT, SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT,
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR =
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT,
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR =
SE_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT,
SE_FORMAT_FEATURE_DISJOINT_BIT_KHR = SE_FORMAT_FEATURE_DISJOINT_BIT, SE_FORMAT_FEATURE_DISJOINT_BIT_KHR = SE_FORMAT_FEATURE_DISJOINT_BIT,
SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT, SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT_KHR = SE_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT,
SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT = SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG, SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT = SE_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG,
@@ -1311,8 +1267,7 @@ typedef enum SeFormatFeatureFlagBits
} SeFormatFeatureFlagBits; } SeFormatFeatureFlagBits;
typedef SeFlags SeFormatFeatureFlags; typedef SeFlags SeFormatFeatureFlags;
typedef enum SeImageUsageFlagBits typedef enum SeImageUsageFlagBits {
{
SE_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001, SE_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001,
SE_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002, SE_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002,
SE_IMAGE_USAGE_SAMPLED_BIT = 0x00000004, SE_IMAGE_USAGE_SAMPLED_BIT = 0x00000004,
@@ -1327,8 +1282,7 @@ typedef enum SeImageUsageFlagBits
} SeImageUsageFlagBits; } SeImageUsageFlagBits;
typedef SeFlags SeImageUsageFlags; typedef SeFlags SeImageUsageFlags;
typedef enum SeImageCreateFlagBits typedef enum SeImageCreateFlagBits {
{
SE_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001, SE_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001,
SE_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, SE_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
SE_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004, SE_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
@@ -1354,8 +1308,7 @@ typedef enum SeImageCreateFlagBits
} SeImageCreateFlagBits; } SeImageCreateFlagBits;
typedef SeFlags SeImageCreateFlags; typedef SeFlags SeImageCreateFlags;
typedef enum SeSampleCountFlagBits typedef enum SeSampleCountFlagBits {
{
SE_SAMPLE_COUNT_1_BIT = 0x00000001, SE_SAMPLE_COUNT_1_BIT = 0x00000001,
SE_SAMPLE_COUNT_2_BIT = 0x00000002, SE_SAMPLE_COUNT_2_BIT = 0x00000002,
SE_SAMPLE_COUNT_4_BIT = 0x00000004, SE_SAMPLE_COUNT_4_BIT = 0x00000004,
@@ -1367,8 +1320,7 @@ typedef enum SeSampleCountFlagBits
} SeSampleCountFlagBits; } SeSampleCountFlagBits;
typedef SeFlags SeSampleCountFlags; typedef SeFlags SeSampleCountFlags;
typedef enum SeQueueFlagBits typedef enum SeQueueFlagBits {
{
SE_QUEUE_GRAPHICS_BIT = 0x00000001, SE_QUEUE_GRAPHICS_BIT = 0x00000001,
SE_QUEUE_COMPUTE_BIT = 0x00000002, SE_QUEUE_COMPUTE_BIT = 0x00000002,
SE_QUEUE_TRANSFER_BIT = 0x00000004, SE_QUEUE_TRANSFER_BIT = 0x00000004,
@@ -1378,8 +1330,7 @@ typedef enum SeQueueFlagBits
} SeQueueFlagBits; } SeQueueFlagBits;
typedef SeFlags SeQueueFlags; typedef SeFlags SeQueueFlags;
typedef enum SeMemoryPropertyFlagBits typedef enum SeMemoryPropertyFlagBits {
{
SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001, SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001,
SE_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002, SE_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002,
SE_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004, SE_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004,
@@ -1392,8 +1343,7 @@ typedef enum SeMemoryPropertyFlagBits
} SeMemoryPropertyFlagBits; } SeMemoryPropertyFlagBits;
typedef SeFlags SeMemoryPropertyFlags; typedef SeFlags SeMemoryPropertyFlags;
typedef enum SeMemoryHeapFlagBits typedef enum SeMemoryHeapFlagBits {
{
SE_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001, SE_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001,
SE_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002, SE_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002,
SE_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR = SE_MEMORY_HEAP_MULTI_INSTANCE_BIT, SE_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR = SE_MEMORY_HEAP_MULTI_INSTANCE_BIT,
@@ -1402,15 +1352,13 @@ typedef enum SeMemoryHeapFlagBits
typedef SeFlags SeMemoryHeapFlags; typedef SeFlags SeMemoryHeapFlags;
typedef SeFlags SeDeviceCreateFlags; typedef SeFlags SeDeviceCreateFlags;
typedef enum SeDeviceQueueCreateFlagBits typedef enum SeDeviceQueueCreateFlagBits {
{
SE_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x00000001, SE_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x00000001,
SE_DEVICE_QUEUE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_DEVICE_QUEUE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeDeviceQueueCreateFlagBits; } SeDeviceQueueCreateFlagBits;
typedef SeFlags SeDeviceQueueCreateFlags; typedef SeFlags SeDeviceQueueCreateFlags;
typedef enum SePipelineStageFlagBits typedef enum SePipelineStageFlagBits {
{
SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001, SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001,
SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002, SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002,
SE_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004, SE_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004,
@@ -1443,8 +1391,7 @@ typedef enum SePipelineStageFlagBits
typedef SeFlags SePipelineStageFlags; typedef SeFlags SePipelineStageFlags;
typedef SeFlags SeMemoryMapFlags; typedef SeFlags SeMemoryMapFlags;
typedef enum SeImageAspectFlagBits typedef enum SeImageAspectFlagBits {
{
SE_IMAGE_ASPECT_COLOR_BIT = 0x00000001, SE_IMAGE_ASPECT_COLOR_BIT = 0x00000001,
SE_IMAGE_ASPECT_DEPTH_BIT = 0x00000002, SE_IMAGE_ASPECT_DEPTH_BIT = 0x00000002,
SE_IMAGE_ASPECT_STENCIL_BIT = 0x00000004, SE_IMAGE_ASPECT_STENCIL_BIT = 0x00000004,
@@ -1463,8 +1410,7 @@ typedef enum SeImageAspectFlagBits
} SeImageAspectFlagBits; } SeImageAspectFlagBits;
typedef SeFlags SeImageAspectFlags; typedef SeFlags SeImageAspectFlags;
typedef enum SeSparseImageFormatFlagBits typedef enum SeSparseImageFormatFlagBits {
{
SE_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001, SE_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001,
SE_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002, SE_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002,
SE_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004, SE_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004,
@@ -1472,15 +1418,13 @@ typedef enum SeSparseImageFormatFlagBits
} SeSparseImageFormatFlagBits; } SeSparseImageFormatFlagBits;
typedef SeFlags SeSparseImageFormatFlags; typedef SeFlags SeSparseImageFormatFlags;
typedef enum SeSparseMemoryBindFlagBits typedef enum SeSparseMemoryBindFlagBits {
{
SE_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001, SE_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001,
SE_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSparseMemoryBindFlagBits; } SeSparseMemoryBindFlagBits;
typedef SeFlags SeSparseMemoryBindFlags; typedef SeFlags SeSparseMemoryBindFlags;
typedef enum SeFenceCreateFlagBits typedef enum SeFenceCreateFlagBits {
{
SE_FENCE_CREATE_SIGNALED_BIT = 0x00000001, SE_FENCE_CREATE_SIGNALED_BIT = 0x00000001,
SE_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeFenceCreateFlagBits; } SeFenceCreateFlagBits;
@@ -1489,8 +1433,7 @@ typedef SeFlags SeSemaphoreCreateFlags;
typedef SeFlags SeEventCreateFlags; typedef SeFlags SeEventCreateFlags;
typedef SeFlags SeQueryPoolCreateFlags; typedef SeFlags SeQueryPoolCreateFlags;
typedef enum SeQueryPipelineStatisticFlagBits typedef enum SeQueryPipelineStatisticFlagBits {
{
SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001, SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001,
SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002, SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002,
SE_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004, SE_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004,
@@ -1506,8 +1449,7 @@ typedef enum SeQueryPipelineStatisticFlagBits
} SeQueryPipelineStatisticFlagBits; } SeQueryPipelineStatisticFlagBits;
typedef SeFlags SeQueryPipelineStatisticFlags; typedef SeFlags SeQueryPipelineStatisticFlags;
typedef enum SeQueryResultFlagBits typedef enum SeQueryResultFlagBits {
{
SE_QUERY_RESULT_64_BIT = 0x00000001, SE_QUERY_RESULT_64_BIT = 0x00000001,
SE_QUERY_RESULT_WAIT_BIT = 0x00000002, SE_QUERY_RESULT_WAIT_BIT = 0x00000002,
SE_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004, SE_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004,
@@ -1516,8 +1458,7 @@ typedef enum SeQueryResultFlagBits
} SeQueryResultFlagBits; } SeQueryResultFlagBits;
typedef SeFlags SeQueryResultFlags; typedef SeFlags SeQueryResultFlags;
typedef enum SeBufferCreateFlagBits typedef enum SeBufferCreateFlagBits {
{
SE_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001, SE_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001,
SE_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, SE_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
SE_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004, SE_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
@@ -1527,8 +1468,7 @@ typedef enum SeBufferCreateFlagBits
} SeBufferCreateFlagBits; } SeBufferCreateFlagBits;
typedef SeFlags SeBufferCreateFlags; typedef SeFlags SeBufferCreateFlags;
typedef enum SeBufferUsageFlagBits typedef enum SeBufferUsageFlagBits {
{
SE_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001, SE_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001,
SE_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002, SE_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002,
SE_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004, SE_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004,
@@ -1548,22 +1488,17 @@ typedef enum SeBufferUsageFlagBits
typedef SeFlags SeBufferUsageFlags; typedef SeFlags SeBufferUsageFlags;
typedef SeFlags SeBufferViewCreateFlags; typedef SeFlags SeBufferViewCreateFlags;
typedef enum SeImageViewCreateFlagBits typedef enum SeImageViewCreateFlagBits {
{
SE_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001, SE_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001,
SE_IMAGE_VIEW_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_IMAGE_VIEW_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeImageViewCreateFlagBits; } SeImageViewCreateFlagBits;
typedef SeFlags SeImageViewCreateFlags; typedef SeFlags SeImageViewCreateFlags;
typedef enum SeShaderModuleCreateFlagBits typedef enum SeShaderModuleCreateFlagBits { SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeShaderModuleCreateFlagBits;
{
SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeShaderModuleCreateFlagBits;
typedef SeFlags SeShaderModuleCreateFlags; typedef SeFlags SeShaderModuleCreateFlags;
typedef SeFlags SePipelineCacheCreateFlags; typedef SeFlags SePipelineCacheCreateFlags;
typedef enum SePipelineCreateFlagBits typedef enum SePipelineCreateFlagBits {
{
SE_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001, SE_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001,
SE_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002, SE_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002,
SE_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004, SE_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004,
@@ -1578,16 +1513,14 @@ typedef enum SePipelineCreateFlagBits
} SePipelineCreateFlagBits; } SePipelineCreateFlagBits;
typedef SeFlags SePipelineCreateFlags; typedef SeFlags SePipelineCreateFlags;
typedef enum SePipelineShaderStageCreateFlagBits typedef enum SePipelineShaderStageCreateFlagBits {
{
SE_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT = 0x00000001, SE_PIPELINE_SHADER_STAGE_CREATE_ALLOW_VARYING_SUBGROUP_SIZE_BIT_EXT = 0x00000001,
SE_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT = 0x00000002, SE_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT = 0x00000002,
SE_PIPELINE_SHADER_STAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_PIPELINE_SHADER_STAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SePipelineShaderStageCreateFlagBits; } SePipelineShaderStageCreateFlagBits;
typedef SeFlags SePipelineShaderStageCreateFlags; typedef SeFlags SePipelineShaderStageCreateFlags;
typedef enum SeShaderStageFlagBits typedef enum SeShaderStageFlagBits {
{
SE_SHADER_STAGE_VERTEX_BIT = 0x00000001, SE_SHADER_STAGE_VERTEX_BIT = 0x00000001,
SE_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002, SE_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002,
SE_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004, SE_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004,
@@ -1613,8 +1546,7 @@ typedef SeFlags SePipelineTessellationStateCreateFlags;
typedef SeFlags SePipelineViewportStateCreateFlags; typedef SeFlags SePipelineViewportStateCreateFlags;
typedef SeFlags SePipelineRasterizationStateCreateFlags; typedef SeFlags SePipelineRasterizationStateCreateFlags;
typedef enum SeCullModeFlagBits typedef enum SeCullModeFlagBits {
{
SE_CULL_MODE_NONE = 0, SE_CULL_MODE_NONE = 0,
SE_CULL_MODE_FRONT_BIT = 0x00000001, SE_CULL_MODE_FRONT_BIT = 0x00000001,
SE_CULL_MODE_BACK_BIT = 0x00000002, SE_CULL_MODE_BACK_BIT = 0x00000002,
@@ -1626,8 +1558,7 @@ typedef SeFlags SePipelineMultisampleStateCreateFlags;
typedef SeFlags SePipelineDepthStencilStateCreateFlags; typedef SeFlags SePipelineDepthStencilStateCreateFlags;
typedef SeFlags SePipelineColorBlendStateCreateFlags; typedef SeFlags SePipelineColorBlendStateCreateFlags;
typedef enum SeColorComponentFlagBits typedef enum SeColorComponentFlagBits {
{
SE_COLOR_COMPONENT_R_BIT = 0x00000001, SE_COLOR_COMPONENT_R_BIT = 0x00000001,
SE_COLOR_COMPONENT_G_BIT = 0x00000002, SE_COLOR_COMPONENT_G_BIT = 0x00000002,
SE_COLOR_COMPONENT_B_BIT = 0x00000004, SE_COLOR_COMPONENT_B_BIT = 0x00000004,
@@ -1639,24 +1570,21 @@ typedef SeFlags SePipelineDynamicStateCreateFlags;
typedef SeFlags SePipelineLayoutCreateFlags; typedef SeFlags SePipelineLayoutCreateFlags;
typedef SeFlags SeShaderStageFlags; typedef SeFlags SeShaderStageFlags;
typedef enum SeSamplerCreateFlagBits typedef enum SeSamplerCreateFlagBits {
{
SE_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001, SE_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001,
SE_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002, SE_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002,
SE_SAMPLER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_SAMPLER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSamplerCreateFlagBits; } SeSamplerCreateFlagBits;
typedef SeFlags SeSamplerCreateFlags; typedef SeFlags SeSamplerCreateFlags;
typedef enum SeDescriptorSetLayoutCreateFlagBits typedef enum SeDescriptorSetLayoutCreateFlagBits {
{
SE_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR = 0x00000001, SE_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR = 0x00000001,
SE_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT = 0x00000002, SE_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT = 0x00000002,
SE_DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeDescriptorSetLayoutCreateFlagBits; } SeDescriptorSetLayoutCreateFlagBits;
typedef SeFlags SeDescriptorSetLayoutCreateFlags; typedef SeFlags SeDescriptorSetLayoutCreateFlags;
typedef enum SeDescriptorPoolCreateFlagBits typedef enum SeDescriptorPoolCreateFlagBits {
{
SE_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001, SE_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001,
SE_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT = 0x00000002, SE_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT = 0x00000002,
SE_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
@@ -1664,36 +1592,29 @@ typedef enum SeDescriptorPoolCreateFlagBits
typedef SeFlags SeDescriptorPoolCreateFlags; typedef SeFlags SeDescriptorPoolCreateFlags;
typedef SeFlags SeDescriptorPoolResetFlags; typedef SeFlags SeDescriptorPoolResetFlags;
typedef enum SeFramebufferCreateFlagBits typedef enum SeFramebufferCreateFlagBits {
{
SE_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR = 0x00000001, SE_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR = 0x00000001,
SE_FRAMEBUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_FRAMEBUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeFramebufferCreateFlagBits; } SeFramebufferCreateFlagBits;
typedef SeFlags SeFramebufferCreateFlags; typedef SeFlags SeFramebufferCreateFlags;
typedef enum SeRenderPassCreateFlagBits typedef enum SeRenderPassCreateFlagBits { SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeRenderPassCreateFlagBits;
{
SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeRenderPassCreateFlagBits;
typedef SeFlags SeRenderPassCreateFlags; typedef SeFlags SeRenderPassCreateFlags;
typedef enum SeAttachmentDescriptionFlagBits typedef enum SeAttachmentDescriptionFlagBits {
{
SE_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001, SE_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001,
SE_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeAttachmentDescriptionFlagBits; } SeAttachmentDescriptionFlagBits;
typedef SeFlags SeAttachmentDescriptionFlags; typedef SeFlags SeAttachmentDescriptionFlags;
typedef enum SeSubpassDescriptionFlagBits typedef enum SeSubpassDescriptionFlagBits {
{
SE_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001, SE_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001,
SE_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002, SE_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002,
SE_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSubpassDescriptionFlagBits; } SeSubpassDescriptionFlagBits;
typedef SeFlags SeSubpassDescriptionFlags; typedef SeFlags SeSubpassDescriptionFlags;
typedef enum SeAccessFlagBits typedef enum SeAccessFlagBits {
{
SE_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001, SE_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001,
SE_ACCESS_INDEX_READ_BIT = 0x00000002, SE_ACCESS_INDEX_READ_BIT = 0x00000002,
SE_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004, SE_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004,
@@ -1727,8 +1648,7 @@ typedef enum SeAccessFlagBits
} SeAccessFlagBits; } SeAccessFlagBits;
typedef SeFlags SeAccessFlags; typedef SeFlags SeAccessFlags;
typedef enum SeDependencyFlagBits typedef enum SeDependencyFlagBits {
{
SE_DEPENDENCY_BY_REGION_BIT = 0x00000001, SE_DEPENDENCY_BY_REGION_BIT = 0x00000001,
SE_DEPENDENCY_DEVICE_GROUP_BIT = 0x00000004, SE_DEPENDENCY_DEVICE_GROUP_BIT = 0x00000004,
SE_DEPENDENCY_VIEW_LOCAL_BIT = 0x00000002, SE_DEPENDENCY_VIEW_LOCAL_BIT = 0x00000002,
@@ -1738,8 +1658,7 @@ typedef enum SeDependencyFlagBits
} SeDependencyFlagBits; } SeDependencyFlagBits;
typedef SeFlags SeDependencyFlags; typedef SeFlags SeDependencyFlags;
typedef enum SeCommandPoolCreateFlagBits typedef enum SeCommandPoolCreateFlagBits {
{
SE_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001, SE_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001,
SE_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002, SE_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002,
SE_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x00000004, SE_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x00000004,
@@ -1747,15 +1666,13 @@ typedef enum SeCommandPoolCreateFlagBits
} SeCommandPoolCreateFlagBits; } SeCommandPoolCreateFlagBits;
typedef SeFlags SeCommandPoolCreateFlags; typedef SeFlags SeCommandPoolCreateFlags;
typedef enum SeCommandPoolResetFlagBits typedef enum SeCommandPoolResetFlagBits {
{
SE_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001, SE_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
SE_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeCommandPoolResetFlagBits; } SeCommandPoolResetFlagBits;
typedef SeFlags SeCommandPoolResetFlags; typedef SeFlags SeCommandPoolResetFlags;
typedef enum SeCommandBufferUsageFlagBits typedef enum SeCommandBufferUsageFlagBits {
{
SE_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001, SE_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001,
SE_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002, SE_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002,
SE_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004, SE_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004,
@@ -1763,22 +1680,19 @@ typedef enum SeCommandBufferUsageFlagBits
} SeCommandBufferUsageFlagBits; } SeCommandBufferUsageFlagBits;
typedef SeFlags SeCommandBufferUsageFlags; typedef SeFlags SeCommandBufferUsageFlags;
typedef enum SeQueryControlFlagBits typedef enum SeQueryControlFlagBits {
{
SE_QUERY_CONTROL_PRECISE_BIT = 0x00000001, SE_QUERY_CONTROL_PRECISE_BIT = 0x00000001,
SE_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeQueryControlFlagBits; } SeQueryControlFlagBits;
typedef SeFlags SeQueryControlFlags; typedef SeFlags SeQueryControlFlags;
typedef enum SeCommandBufferResetFlagBits typedef enum SeCommandBufferResetFlagBits {
{
SE_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001, SE_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
SE_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF SE_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeCommandBufferResetFlagBits; } SeCommandBufferResetFlagBits;
typedef SeFlags SeCommandBufferResetFlags; typedef SeFlags SeCommandBufferResetFlags;
typedef enum SeStencilFaceFlagBits typedef enum SeStencilFaceFlagBits {
{
SE_STENCIL_FACE_FRONT_BIT = 0x00000001, SE_STENCIL_FACE_FRONT_BIT = 0x00000001,
SE_STENCIL_FACE_BACK_BIT = 0x00000002, SE_STENCIL_FACE_BACK_BIT = 0x00000002,
SE_STENCIL_FACE_FRONT_AND_BACK = 0x00000003, SE_STENCIL_FACE_FRONT_AND_BACK = 0x00000003,
@@ -1803,7 +1717,6 @@ typedef union SeClearValue {
SeClearDepthStencilValue depthStencil; SeClearDepthStencilValue depthStencil;
} SeClearValue; } SeClearValue;
typedef enum SeDescriptorAccessTypeFlagBits { typedef enum SeDescriptorAccessTypeFlagBits {
SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT = 0x00000001, SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT = 0x00000001,
SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT = 0x00000002, SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT = 0x00000002,
@@ -1811,7 +1724,5 @@ typedef enum SeDescriptorAccessTypeFlagBits {
} SeDescriptorAccessTypeFlagBits; } SeDescriptorAccessTypeFlagBits;
typedef SeFlags SeDescriptorAccessTypeFlags; typedef SeFlags SeDescriptorAccessTypeFlags;
} // namespace Gfx } // namespace Gfx
} // namespace Seele } // namespace Seele
+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() {}
{
}
+22 -29
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;
@@ -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;
+77 -110
View File
@@ -1,14 +1,13 @@
#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
{ namespace Seele {
struct GraphicsInitializer struct GraphicsInitializer {
{
const char* applicationName; const char* applicationName;
const char* engineName; const char* engineName;
const char* windowLayoutFile; const char* windowLayoutFile;
@@ -23,40 +22,29 @@ namespace Seele
void* windowHandle; void* windowHandle;
GraphicsInitializer() GraphicsInitializer()
: applicationName("SeeleEngine") : applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), layers{"VK_LAYER_LUNARG_monitor"},
, engineName("SeeleEngine") instanceExtensions{}, deviceExtensions{"VK_KHR_swapchain"}, windowHandle(nullptr) {}
, windowLayoutFile(nullptr) };
, layers{ "VK_LAYER_LUNARG_monitor" } struct WindowCreateInfo {
, instanceExtensions{}
, deviceExtensions{ "VK_KHR_swapchain" }
, windowHandle(nullptr)
{
}
};
struct WindowCreateInfo
{
int32 width; int32 width;
int32 height; int32 height;
const char* title; const char* title;
Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM; Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM;
void* windowHandle; void* windowHandle;
}; };
struct ViewportCreateInfo struct ViewportCreateInfo {
{
URect dimensions; URect dimensions;
float fieldOfView = 1.222f; // 70 deg float fieldOfView = 1.222f; // 70 deg
Gfx::SeSampleCountFlags numSamples; Gfx::SeSampleCountFlags numSamples;
}; };
// doesnt own the data, only proxy it // doesnt own the data, only proxy it
struct DataSource struct DataSource {
{
uint64 size = 0; uint64 size = 0;
uint64 offset = 0; uint64 offset = 0;
uint8* data = nullptr; uint8* data = nullptr;
Gfx::QueueType owner = Gfx::QueueType::GRAPHICS; Gfx::QueueType owner = Gfx::QueueType::GRAPHICS;
}; };
struct TextureCreateInfo struct TextureCreateInfo {
{
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT; Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT;
uint32 width = 1; uint32 width = 1;
@@ -69,9 +57,8 @@ namespace Seele
Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT; Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
std::string name; std::string name;
}; };
struct SamplerCreateInfo struct SamplerCreateInfo {
{
Gfx::SeSamplerCreateFlags flags; Gfx::SeSamplerCreateFlags flags;
Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR; Gfx::SeFilter magFilter = Gfx::SE_FILTER_LINEAR;
Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR; Gfx::SeFilter minFilter = Gfx::SE_FILTER_LINEAR;
@@ -89,38 +76,33 @@ namespace Seele
Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK; Gfx::SeBorderColor borderColor = Gfx::SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
uint32 unnormalizedCoordinates = 0; uint32 unnormalizedCoordinates = 0;
std::string name; std::string name;
}; };
struct VertexBufferCreateInfo struct VertexBufferCreateInfo {
{
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
// bytes per vertex // bytes per vertex
uint32 vertexSize = 0; uint32 vertexSize = 0;
uint32 numVertices = 0; uint32 numVertices = 0;
std::string name = "Unnamed"; std::string name = "Unnamed";
}; };
struct IndexBufferCreateInfo struct IndexBufferCreateInfo {
{
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16; Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16;
std::string name = "Unnamed"; std::string name = "Unnamed";
}; };
struct UniformBufferCreateInfo struct UniformBufferCreateInfo {
{
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
uint8 dynamic = 0; uint8 dynamic = 0;
std::string name = "Unnamed"; std::string name = "Unnamed";
}; };
struct ShaderBufferCreateInfo struct ShaderBufferCreateInfo {
{
DataSource sourceData = DataSource(); DataSource sourceData = DataSource();
uint64 numElements = 1; uint64 numElements = 1;
uint8 dynamic = 0; uint8 dynamic = 0;
uint8 vertexBuffer = 0; uint8 vertexBuffer = 0;
std::string name = "Unnamed"; std::string name = "Unnamed";
}; };
DECLARE_NAME_REF(Gfx, PipelineLayout) DECLARE_NAME_REF(Gfx, PipelineLayout)
struct ShaderCreateInfo struct ShaderCreateInfo {
{
std::string name; // Debug info std::string name; // Debug info
std::string mainModule; std::string mainModule;
Array<std::string> additionalModules; Array<std::string> additionalModules;
@@ -128,36 +110,31 @@ namespace Seele
Array<Pair<const char*, const char*>> typeParameter; Array<Pair<const char*, const char*>> typeParameter;
Map<const char*, const char*> defines; Map<const char*, const char*> defines;
Gfx::PPipelineLayout rootSignature; Gfx::PPipelineLayout rootSignature;
}; };
struct VertexInputBinding struct VertexInputBinding {
{
uint32 binding; uint32 binding;
uint32 stride; uint32 stride;
Gfx::SeVertexInputRate inputRate; Gfx::SeVertexInputRate inputRate;
}; };
struct VertexInputAttribute struct VertexInputAttribute {
{
uint32 location; uint32 location;
uint32 binding; uint32 binding;
Gfx::SeFormat format; Gfx::SeFormat format;
uint32 offset; uint32 offset;
}; };
struct VertexInputStateCreateInfo struct VertexInputStateCreateInfo {
{
Array<VertexInputBinding> bindings; Array<VertexInputBinding> bindings;
Array<VertexInputAttribute> attributes; Array<VertexInputAttribute> attributes;
}; };
DECLARE_REF(MaterialInstance) DECLARE_REF(MaterialInstance)
namespace Gfx DECLARE_REF(Mesh)
{ namespace Gfx {
struct SePushConstantRange struct SePushConstantRange {
{
SeShaderStageFlags stageFlags; SeShaderStageFlags stageFlags;
uint32 offset; uint32 offset;
uint32 size; uint32 size;
}; };
struct RasterizationState struct RasterizationState {
{
uint32 depthClampEnable = 0; uint32 depthClampEnable = 0;
uint32 rasterizerDiscardEnable = 0; uint32 rasterizerDiscardEnable = 0;
SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL; SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL;
@@ -168,17 +145,15 @@ namespace Seele
float depthBiasClamp = 0; float depthBiasClamp = 0;
float depthBiasSlopeFactor = 0; float depthBiasSlopeFactor = 0;
float lineWidth = 1.0; float lineWidth = 1.0;
}; };
struct MultisampleState struct MultisampleState {
{
SeSampleCountFlags samples = 1; SeSampleCountFlags samples = 1;
uint32 sampleShadingEnable = 0; uint32 sampleShadingEnable = 0;
float minSampleShading = 1; float minSampleShading = 1;
uint8 alphaCoverageEnable = 0; uint8 alphaCoverageEnable = 0;
uint8 alphaToOneEnable = 0; uint8 alphaToOneEnable = 0;
}; };
struct DepthStencilState struct DepthStencilState {
{
uint32 depthTestEnable = 1; uint32 depthTestEnable = 1;
uint32 depthWriteEnable = 1; uint32 depthWriteEnable = 1;
SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER; SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER;
@@ -188,11 +163,9 @@ namespace Seele
SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO; SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO;
float minDepthBounds = 0.0f; float minDepthBounds = 0.0f;
float maxDepthBounds = 1.0f; float maxDepthBounds = 1.0f;
}; };
struct ColorBlendState struct ColorBlendState {
{ struct BlendAttachment {
struct BlendAttachment
{
uint32 blendEnable = 0; uint32 blendEnable = 0;
SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; SeBlendFactor srcColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; SeBlendFactor dstColorBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
@@ -200,25 +173,30 @@ namespace Seele
SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; SeBlendFactor srcAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA; SeBlendFactor dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD; 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; 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; uint32 logicOpEnable = 0;
SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR; SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR;
uint32 attachmentCount = 0; uint32 attachmentCount = 0;
StaticArray<BlendAttachment, 16> blendAttachments; StaticArray<BlendAttachment, 16> blendAttachments;
StaticArray<float, 4> blendConstants = { 1.0f, 1.0f, 1.0f, 1.0f, }; StaticArray<float, 4> blendConstants = {
1.0f,
1.0f,
1.0f,
1.0f,
}; };
};
DECLARE_REF(VertexInput) DECLARE_REF(VertexInput)
DECLARE_REF(VertexShader) DECLARE_REF(VertexShader)
DECLARE_REF(TaskShader) DECLARE_REF(TaskShader)
DECLARE_REF(MeshShader) DECLARE_REF(MeshShader)
DECLARE_REF(FragmentShader) DECLARE_REF(FragmentShader)
DECLARE_REF(ComputeShader) DECLARE_REF(ComputeShader)
DECLARE_REF(RenderPass) DECLARE_REF(RenderPass)
DECLARE_REF(PipelineLayout) DECLARE_REF(PipelineLayout)
struct LegacyPipelineCreateInfo struct LegacyPipelineCreateInfo {
{
SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
PVertexInput vertexInput = nullptr; PVertexInput vertexInput = nullptr;
PVertexShader vertexShader = nullptr; PVertexShader vertexShader = nullptr;
@@ -229,10 +207,9 @@ namespace Seele
RasterizationState rasterizationState; RasterizationState rasterizationState;
DepthStencilState depthStencilState; DepthStencilState depthStencilState;
ColorBlendState colorBlend; ColorBlendState colorBlend;
}; };
struct MeshPipelineCreateInfo struct MeshPipelineCreateInfo {
{
PTaskShader taskShader = nullptr; PTaskShader taskShader = nullptr;
PMeshShader meshShader = nullptr; PMeshShader meshShader = nullptr;
PFragmentShader fragmentShader = nullptr; PFragmentShader fragmentShader = nullptr;
@@ -242,25 +219,15 @@ namespace Seele
RasterizationState rasterizationState; RasterizationState rasterizationState;
DepthStencilState depthStencilState; DepthStencilState depthStencilState;
ColorBlendState colorBlend; ColorBlendState colorBlend;
}; };
struct ComputePipelineCreateInfo struct ComputePipelineCreateInfo {
{
Gfx::PComputeShader computeShader = nullptr; Gfx::PComputeShader computeShader = nullptr;
Gfx::PPipelineLayout pipelineLayout = nullptr; Gfx::PPipelineLayout pipelineLayout = nullptr;
}; };
DECLARE_REF(ShaderBuffer) DECLARE_REF(ShaderBuffer)
struct BottomLevelASCreateInfo struct BottomLevelASCreateInfo {
{ PMesh mesh;
PShaderBuffer positionBuffer; };
PShaderBuffer indexBuffer; struct TopLevelASCreateInfo {};
MeshData meshData; } // namespace Gfx
PMaterialInstance material;
uint64 verticesOffset;
uint64 indicesOffset;
};
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);
+11 -18
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->save(buffer);
}
template<>
void load(ArchiveBuffer& buffer, OMesh& ptr)
{
ptr = new Mesh(); ptr = new Mesh();
ptr->load(buffer); 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
+39 -68
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 + 0],
indices[i * 3 + 1], indices[i * 3 + 1],
indices[i * 3 + 2], 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);
} }
} }
+4 -5
View File
@@ -1,11 +1,10 @@
#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
+34 -34
View File
@@ -9,9 +9,8 @@
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;
@@ -19,17 +18,17 @@ public:
}; };
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;
@@ -41,61 +40,62 @@ protected:
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:
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(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) {}
+14 -18
View File
@@ -19,7 +19,7 @@ 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);
@@ -32,8 +32,7 @@ public:
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;
@@ -41,7 +40,7 @@ public:
PEvent getCompletedEvent() const { return completed; } PEvent getCompletedEvent() const { return completed; }
constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; } constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; }
private: private:
PGraphics graphics; PGraphics graphics;
OEvent completed; OEvent completed;
MTL::CommandBuffer* cmdBuffer; MTL::CommandBuffer* cmdBuffer;
@@ -50,7 +49,7 @@ private:
}; };
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();
@@ -60,15 +59,13 @@ public:
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, virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) override;
uint32 firstInstance) override;
virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override; virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override;
virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) 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;
@@ -77,18 +74,17 @@ private:
}; };
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;
@@ -97,7 +93,7 @@ private:
}; };
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; }
@@ -108,21 +104,21 @@ public:
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;
+87 -50
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,15 +294,17 @@ 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) {
for (auto it = pendingCommands.begin(); it != pendingCommands.end();
it++) {
if ((*it)->getHandle() == cmdBuffer) { if ((*it)->getHandle() == cmdBuffer) {
pendingCommands.remove(it); pendingCommands.remove(it);
return; return;
@@ -281,14 +315,17 @@ void CommandQueue::submitCommands(PEvent 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);
+18 -24
View File
@@ -9,26 +9,26 @@ 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;
@@ -36,47 +36,41 @@ private:
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, virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override;
Gfx::PSampler sampler = nullptr) override; virtual void updateTextureArray(uint32_t binding, Array<Gfx::PTexture> texture) 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)
+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;
+19 -19
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;
@@ -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) {
{
} }
+7 -5
View File
@@ -7,14 +7,14 @@
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; }
@@ -22,17 +22,19 @@ public:
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:
private:
MTL::ComputePipelineState* state; MTL::ComputePipelineState* state;
}; };
DEFINE_REF(ComputePipeline) DEFINE_REF(ComputePipeline)

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