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/MeshAsset.h"
#include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h"
#include "Asset/TextureAsset.h"
#include "Asset/MaterialAsset.h"
#include "Asset/MaterialInstanceAsset.h"
#include "Asset/AssetRegistry.h"
#include "Asset/MeshAsset.h"
#include "Asset/TextureAsset.h"
#include <fstream>
#include <iostream>
using namespace Seele;
AssetRegistry * _instance = new AssetRegistry();
AssetRegistry* _instance = new AssetRegistry();
int main(int, char**)
{
//if(argc < 2)
int main(int, char**) {
// if(argc < 2)
//{
// return -1;
//}
// }
std::filesystem::path path = std::filesystem::path("C:\\Users\\Dynamitos\\TrackClear\\Assets\\Dirt.asset");
std::ifstream stream = std::ifstream(path, std::ios::binary);
@@ -37,8 +37,7 @@ int main(int, char**)
Serialization::load(buffer, folderPath);
PAsset asset;
switch (identifier)
{
switch (identifier) {
case TextureAsset::IDENTIFIER:
asset = new TextureAsset(folderPath, name);
break;
+13 -23
View File
@@ -1,54 +1,46 @@
#include "AssetImporter.h"
#include "FontLoader.h"
#include "TextureLoader.h"
#include "Graphics/Graphics.h"
#include "MaterialLoader.h"
#include "MeshLoader.h"
#include "Graphics/Graphics.h"
#include "TextureLoader.h"
using namespace Seele;
void AssetImporter::importMesh(MeshImportArgs args)
{
if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string()))
{
void AssetImporter::importMesh(MeshImportArgs args) {
if (get().registry->getOrCreateFolder(args.importPath)->meshes.contains(args.filePath.stem().string())) {
// skip importing duplicates
return;
}
get().meshLoader->importAsset(args);
}
void AssetImporter::importTexture(TextureImportArgs args)
{
if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string()))
{
void AssetImporter::importTexture(TextureImportArgs args) {
if (get().registry->getOrCreateFolder(args.importPath)->textures.contains(args.filePath.stem().string())) {
// skip importing duplicates
return;
}
get().textureLoader->importAsset(args);
}
void AssetImporter::importFont(FontImportArgs args)
{
if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string()))
{
void AssetImporter::importFont(FontImportArgs args) {
if (get().registry->getOrCreateFolder(args.importPath)->fonts.contains(args.filePath.stem().string())) {
// skip importing duplicates
return;
}
get().fontLoader->importAsset(args);
}
void AssetImporter::importMaterial(MaterialImportArgs args)
{
if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string()))
{
void AssetImporter::importMaterial(MaterialImportArgs args) {
if (get().registry->getOrCreateFolder(args.importPath)->materials.contains(args.filePath.stem().string())) {
// skip importing duplicates
return;
}
get().materialLoader->importAsset(args);
}
void AssetImporter::init(Gfx::PGraphics graphics)
{
void AssetImporter::init(Gfx::PGraphics graphics) {
get().registry = AssetRegistry::getInstance();
get().meshLoader = new MeshLoader(graphics);
get().textureLoader = new TextureLoader(graphics);
@@ -56,9 +48,7 @@ void AssetImporter::init(Gfx::PGraphics graphics)
get().fontLoader = new FontLoader(graphics);
}
AssetImporter& AssetImporter::get()
{
AssetImporter& AssetImporter::get() {
static AssetImporter instance;
return instance;
}
+7 -7
View File
@@ -1,22 +1,22 @@
#pragma once
#include "MinimalEngine.h"
#include "Asset/AssetRegistry.h"
#include "MinimalEngine.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(TextureLoader)
DECLARE_REF(FontLoader)
DECLARE_REF(MeshLoader)
DECLARE_REF(MaterialLoader)
class AssetImporter
{
public:
class AssetImporter {
public:
static void importMesh(struct MeshImportArgs args);
static void importTexture(struct TextureImportArgs args);
static void importFont(struct FontImportArgs args);
static void importMaterial(struct MaterialImportArgs args);
static void init(Gfx::PGraphics graphics);
private:
private:
static AssetImporter& get();
UPTextureLoader textureLoader;
UPFontLoader fontLoader;
+14 -22
View File
@@ -1,28 +1,23 @@
#include "FontLoader.h"
#include "Graphics/Graphics.h"
#include "Asset/FontAsset.h"
#include "Asset/AssetRegistry.h"
#include "Asset/FontAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Resources.h"
#include "Graphics/Texture.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include <iostream>
#include <fstream>
#include <iostream>
using namespace Seele;
FontLoader::FontLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
FontLoader::FontLoader(Gfx::PGraphics graphics) : graphics(graphics) {}
}
FontLoader::~FontLoader() {}
FontLoader::~FontLoader()
{
}
void FontLoader::importAsset(FontImportArgs args)
{
void FontLoader::importAsset(FontImportArgs args) {
std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset");
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
// so we create a single pixel empty texture
uint8 transparentPixel = 0;
void FontLoader::import(FontImportArgs args, PFontAsset asset)
{
void FontLoader::import(FontImportArgs args, PFontAsset asset) {
FT_Library ft;
FT_Error error = FT_Init_FreeType(&ft);
assert(!error);
@@ -46,10 +40,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
assert(!error);
FT_Set_Pixel_Sizes(face, 0, 48);
Array<Gfx::OTexture2D> usedTextures;
for(uint32 c = 0; c < 256; ++c)
{
if(FT_Load_Char(face, c, FT_LOAD_RENDER))
{
for (uint32 c = 0; c < 256; ++c) {
if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
std::cout << "error loading " << (char)c << std::endl;
continue;
}
@@ -63,8 +55,7 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
imageData.height = face->glyph->bitmap.rows;
imageData.sourceData.data = face->glyph->bitmap.buffer;
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.y = 1;
glyph.bearing.x = 0;
@@ -81,7 +72,8 @@ void FontLoader::import(FontImportArgs args, PFontAsset asset)
FT_Done_FreeType(ft);
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;
Serialization::save(archive, FontAsset::IDENTIFIER);
+8 -9
View File
@@ -1,24 +1,23 @@
#pragma once
#include "MinimalEngine.h"
#include "Containers/List.h"
#include "MinimalEngine.h"
#include <filesystem>
namespace Seele
{
namespace Seele {
DECLARE_REF(FontAsset)
DECLARE_NAME_REF(Gfx, Graphics)
struct FontImportArgs
{
struct FontImportArgs {
std::filesystem::path filePath;
std::string importPath;
};
class FontLoader
{
public:
class FontLoader {
public:
FontLoader(Gfx::PGraphics graphic);
~FontLoader();
void importAsset(FontImportArgs args);
private:
private:
void import(FontImportArgs args, PFontAsset asset);
Gfx::PGraphics graphics;
};
+74 -110
View File
@@ -1,37 +1,35 @@
#include "MaterialLoader.h"
#include "Asset/AssetRegistry.h"
#include "Asset/MaterialAsset.h"
#include "Asset/TextureAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Shader.h"
#include "Asset/MaterialAsset.h"
#include "Asset/AssetRegistry.h"
#include "Material/Material.h"
#include "Window/WindowManager.h"
#include "Material/ShaderExpression.h"
#include "Asset/TextureAsset.h"
#include <nlohmann/json.hpp>
#include "Window/WindowManager.h"
#include <fmt/core.h>
#include <iostream>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using namespace Seele;
using json = nlohmann::json;
MaterialLoader::MaterialLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
MaterialLoader::MaterialLoader(Gfx::PGraphics graphics) : graphics(graphics) {
OMaterialAsset placeholderAsset = new MaterialAsset();
import(MaterialImportArgs{
import(
MaterialImportArgs{
.filePath = std::filesystem::absolute("./shaders/Placeholder.json"),
.importPath = "",
}, placeholderAsset);
},
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();
assetPath.replace_extension("asset");
OMaterialAsset asset = new MaterialAsset(args.importPath, assetPath.stem().string());
@@ -41,14 +39,13 @@ void MaterialLoader::importAsset(MaterialImportArgs args)
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());
json j;
jsonstream >> j;
std::string materialName = j["name"].get<std::string>() + "Material";
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());
@@ -59,22 +56,21 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
uint32 key = 0;
uint32 auxKey = 0;
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>();
auto defaultValue = param.value().find("default");
// TODO: ALIGNMENT RULES
if(type.compare("float") == 0)
{
if (type.compare("float") == 0) {
float defaultData = 0.f;
if (defaultValue != param.value().end())
{
if (defaultValue != param.value().end()) {
defaultData = std::stof(defaultValue.value().get<std::string>());
}
OFloatParameter p = new FloatParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding);
if(uniformBinding == -1)
{
layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,});
if (uniformBinding == -1) {
layout->addDescriptorBinding(Gfx::DescriptorBinding{
.binding = bindingCounter,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
});
uniformBinding = bindingCounter++;
}
uniformBufferOffset += 4;
@@ -82,93 +78,85 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
expressions.add(std::move(p));
}
// TODO: ALIGNMENT RULES
else if(type.compare("float3") == 0)
{
else if (type.compare("float3") == 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());
}
OVectorParameter p = new VectorParameter(param.key(), defaultData, uniformBufferOffset, uniformBinding);
if(uniformBinding == -1)
{
layout->addDescriptorBinding(Gfx::DescriptorBinding{.binding = bindingCounter, .descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,});
if (uniformBinding == -1) {
layout->addDescriptorBinding(Gfx::DescriptorBinding{
.binding = bindingCounter,
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
});
uniformBinding = bindingCounter++;
}
uniformBufferOffset += 16;
parameters.add(p->key);
expressions.add(std::move(p));
}
else if(type.compare("Texture2D") == 0)
{
} else if (type.compare("Texture2D") == 0) {
PTextureAsset texture;
if(defaultValue != param.value().end())
{
if (defaultValue != param.value().end()) {
std::string defaultString = defaultValue.value().get<std::string>();
auto slashPos = defaultString.rfind("/");
std::string folder = "";
if (slashPos != std::string::npos)
{
if (slashPos != std::string::npos) {
folder = defaultString.substr(0, slashPos - 1);
defaultString = defaultString.substr(slashPos, defaultString.length());
}
texture = AssetRegistry::findTexture(folder, defaultString);
}
if(texture == nullptr)
{
if (texture == nullptr) {
texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture
}
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);
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);
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);
expressions.add(std::move(p));
}
else if (type.compare("Sampler2D") == 0)
{
} else if (type.compare("Sampler2D") == 0) {
PTextureAsset texture;
if (defaultValue != param.value().end())
{
if (defaultValue != param.value().end()) {
std::string defaultString = defaultValue.value().get<std::string>();
auto slashPos = defaultString.rfind("/");
std::string folder = "";
if (slashPos != std::string::npos)
{
if (slashPos != std::string::npos) {
folder = defaultString.substr(0, slashPos - 1);
defaultString = defaultString.substr(slashPos, defaultString.length());
}
texture = AssetRegistry::findTexture(folder, defaultString);
}
if (texture == nullptr)
{
if (texture == nullptr) {
texture = AssetRegistry::findTexture("", ""); // this will return placeholder texture
}
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);
expressions.add(std::move(p));
}
else
{
} else {
std::cout << "Error unsupported parameter type" << std::endl;
}
}
uint32 uniformDataSize = uniformBufferOffset;
auto referenceExpression = [&parameters, &auxKey, &expressions](json obj) -> std::string
{
if(obj.is_string())
{
auto referenceExpression = [&parameters, &auxKey, &expressions](json obj) -> std::string {
if (obj.is_string()) {
std::string str = obj.get<std::string>();
if (parameters.find(str) != parameters.end())
{
if (parameters.find(str) != parameters.end()) {
return str;
}
OConstantExpression c = new ConstantExpression(str, ExpressionType::UNKNOWN);
@@ -176,28 +164,23 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
c->key = name;
expressions.add(std::move(c));
return name;
}
else
{
} else {
return fmt::format("{0}", obj.get<uint32>());
}
};
MaterialNode mat;
for(auto& param : j["code"].items())
{
for (auto& param : j["code"].items()) {
auto& obj = param.value();
std::string exp = obj["exp"].get<std::string>();
if (exp.compare("Const") == 0)
{
if (exp.compare("Const") == 0) {
OConstantExpression p = new ConstantExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
p->expr = obj["value"];
expressions.add(std::move(p));
}
if(exp.compare("Add") == 0)
{
if (exp.compare("Add") == 0) {
OAddExpression p = new AddExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
@@ -205,8 +188,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p));
}
if(exp.compare("Sub") == 0)
{
if (exp.compare("Sub") == 0) {
OSubExpression p = new SubExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
@@ -214,8 +196,7 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p));
}
if(exp.compare("Mul") == 0)
{
if (exp.compare("Mul") == 0) {
OMulExpression p = new MulExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
@@ -223,63 +204,49 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
p->inputs["rhs"].source = referenceExpression(obj["rhs"]);
expressions.add(std::move(p));
}
if(exp.compare("Swizzle") == 0)
{
if (exp.compare("Swizzle") == 0) {
OSwizzleExpression p = new SwizzleExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
p->inputs["target"].source = referenceExpression(obj["target"]);
int32 i = 0;
for(auto& c : obj["comp"].items())
{
for (auto& c : obj["comp"].items()) {
p->comp[i++] = c.value().get<uint32>();
}
expressions.add(std::move(p));
}
if(exp.compare("Sample") == 0)
{
if (exp.compare("Sample") == 0) {
OSampleExpression p = new SampleExpression();
std::string name = fmt::format("{0}", key++);
p->key = name;
if (obj.contains("texture"))
{
if (obj.contains("texture")) {
p->inputs["texture"].source = referenceExpression(obj["texture"]);
}
p->inputs["sampler"].source = referenceExpression(obj["sampler"]);
p->inputs["coords"].source = referenceExpression(obj["coords"]);
expressions.add(std::move(p));
}
if(exp.compare("BRDF") == 0)
{
if (exp.compare("BRDF") == 0) {
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());
}
}
}
layout->create();
asset->material = new Material(
graphics,
std::move(layout),
uniformDataSize,
uniformBinding,
materialName,
std::move(expressions),
std::move(parameters),
std::move(mat)
);
asset->material = new Material(graphics, std::move(layout), uniformDataSize, uniformBinding, materialName, std::move(expressions),
std::move(parameters), std::move(mat));
asset->material->compile();
graphics->getShaderCompiler()->registerMaterial(asset->material);
asset->setStatus(Asset::Status::Ready);
if (asset->getName().empty())
{
if (asset->getName().empty()) {
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;
Serialization::save(archive, MaterialAsset::IDENTIFIER);
@@ -290,7 +257,4 @@ void MaterialLoader::import(MaterialImportArgs args, PMaterialAsset asset)
////co_return;
}
PMaterialAsset MaterialLoader::getPlaceHolderMaterial()
{
return placeholderMaterial;
}
PMaterialAsset MaterialLoader::getPlaceHolderMaterial() { return placeholderMaterial; }
+8 -9
View File
@@ -1,25 +1,24 @@
#pragma once
#include "MinimalEngine.h"
#include "Containers/List.h"
#include "MinimalEngine.h"
#include <filesystem>
namespace Seele
{
namespace Seele {
DECLARE_REF(MaterialAsset)
DECLARE_NAME_REF(Gfx, Graphics)
struct MaterialImportArgs
{
struct MaterialImportArgs {
std::filesystem::path filePath;
std::string importPath;
};
class MaterialLoader
{
public:
class MaterialLoader {
public:
MaterialLoader(Gfx::PGraphics graphic);
~MaterialLoader();
void importAsset(MaterialImportArgs args);
PMaterialAsset getPlaceHolderMaterial();
private:
private:
void import(MaterialImportArgs args, PMaterialAsset asset);
Gfx::PGraphics graphics;
PMaterialAsset placeholderMaterial;
+103 -182
View File
@@ -1,37 +1,32 @@
#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/MaterialAsset.h"
#include "Asset/MeshAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.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 <fstream>
#include <iostream>
#include <set>
#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;
MeshLoader::MeshLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
}
MeshLoader::MeshLoader(Gfx::PGraphics graphics) : graphics(graphics) {}
MeshLoader::~MeshLoader()
{
}
MeshLoader::~MeshLoader() {}
void MeshLoader::importAsset(MeshImportArgs args)
{
void MeshLoader::importAsset(MeshImportArgs args) {
std::filesystem::path assetPath = args.filePath.filename();
assetPath.replace_extension("asset");
OMeshAsset asset = new MeshAsset(args.importPath, assetPath.stem().string());
@@ -41,43 +36,31 @@ void MeshLoader::importAsset(MeshImportArgs args)
import(args, ref);
}
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels)
{
for (uint32 i = 0; i < numPixels; ++i)
{
void MeshLoader::convertAssimpARGB(unsigned char* dst, aiTexel* src, uint32 numPixels) {
for (uint32 i = 0; i < numPixels; ++i) {
dst[i * 4 + 0] = src[i].r;
dst[i * 4 + 1] = src[i].g;
dst[i * 4 + 2] = src[i].b;
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)
{
for (uint32 i = 0; i < scene->mNumTextures; ++i)
{
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) {
aiTexture* tex = scene->mTextures[i];
auto texPath = std::filesystem::path(tex->mFilename.C_Str());
if (std::filesystem::exists(texPath))
{
}
else if (std::filesystem::exists(meshDirectory / texPath))
{
if (std::filesystem::exists(texPath)) {
} else if (std::filesystem::exists(meshDirectory / texPath)) {
texPath = meshDirectory / texPath;
}
else
{
} else {
texPath = (meshDirectory / texPath).replace_extension("png");
if (tex->mHeight == 0)
{
if (tex->mHeight == 0) {
std::cout << "Dumping texture " << texPath << std::endl;
// already compressed, just dump it to the disk
std::ofstream file(texPath, std::ios::binary);
file.write((const char*)tex->pcData, tex->mWidth);
file.flush();
}
else
{
} else {
std::cout << "Writing extracted png " << texPath << std::endl;
// recompress data so that the TextureLoader can read it
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_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)
{
for (uint32 m = 0; m < scene->mNumMaterials; ++m)
{
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) {
for (uint32 m = 0; m < scene->mNumMaterials; ++m) {
aiMaterial* material = scene->mMaterials[m];
aiString texPath;
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.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
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");
Array<OShaderExpression> expressions;
Array<std::string> parameters;
@@ -135,8 +123,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
size_t uniformSize = 0;
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;
material->Get(matKey, type, index, scalar);
expressions.add(new FloatParameter(paramKey, scalar, uniformSize, 0));
@@ -144,8 +131,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
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;
material->Get(matKey, type, index, color);
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);
};
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;
aiTextureMapping mapping;
uint32 uvIndex = 0;
aiTextureMapMode mapMode = aiTextureMapMode_Clamp;
float blend = std::numeric_limits<float>::max();
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;
}
@@ -171,38 +156,29 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
auto texFilename = std::filesystem::path(texPath.C_Str());
PTextureAsset texture;
if (texFilename.string()[0] == '*')
{
if (texFilename.string()[0] == '*') {
texture = textures[atoi(texFilename.string().substr(1).c_str())];
}
else if (std::filesystem::exists(texFilename))
{
} else if (std::filesystem::exists(texFilename)) {
AssetImporter::importTexture(TextureImportArgs{
.filePath = texFilename,
.importPath = importPath,
});
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
}
else if (std::filesystem::exists(meshDirectory / texFilename))
{
} else if (std::filesystem::exists(meshDirectory / texFilename)) {
AssetImporter::importTexture(TextureImportArgs{
.filePath = meshDirectory / texFilename,
.importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
});
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{
.filePath = meshDirectory.parent_path() / "textures" / texFilename,
.importPath = importPath,
.type = type == aiTextureType_NORMALS ? TextureImportType::TEXTURE_NORMAL : TextureImportType::TEXTURE_2D,
});
texture = AssetRegistry::findTexture(importPath, texFilename.stem().string());
}
else
{
} else {
std::cout << "couldnt find " << texPath.C_Str() << std::endl;
return;
}
@@ -218,8 +194,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
std::string samplerKey = fmt::format("{0}Sampler{1}", paramKey, index);
SamplerCreateInfo samplerInfo = {};
switch (mapMode)
{
switch (mapMode) {
case aiTextureMapMode_Wrap:
samplerInfo.addressModeU = 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.back()->key = colorExtract;
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;
return;
}
@@ -293,14 +267,13 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
/** T = T1 / T2 */
case aiTextureOp_Divide:
//expressions[blendKey] = new DivExpression();
// expressions[blendKey] = new DivExpression();
throw std::logic_error("Not implemented");
/** T = (T1 + T2) - (T1 * T2) */
case aiTextureOp_SmoothAdd:
throw std::logic_error("Not implemented");
/** T = T1 + (T2-0.5) */
case aiTextureOp_SignedAdd:
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;
result = blendKey;
};
// Diffuse
addVectorParameter(KEY_DIFFUSE_COLOR, AI_MATKEY_COLOR_DIFFUSE);
std::string outputDiffuse = KEY_DIFFUSE_COLOR;
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);
}
@@ -332,16 +303,14 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addVectorParameter(KEY_SPECULAR_COLOR, AI_MATKEY_COLOR_SPECULAR);
std::string outputSpecular = KEY_SPECULAR_COLOR;
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);
}
// Normal
std::string outputNormal = "";
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);
}
@@ -349,8 +318,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addVectorParameter(KEY_AMBIENT_COLOR, AI_MATKEY_COLOR_AMBIENT);
std::string outputAmbient = KEY_AMBIENT_COLOR;
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);
}
@@ -358,42 +326,36 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
addScalarParameter(KEY_SHININESS, AI_MATKEY_SHININESS);
std::string outputShininess = KEY_SHININESS;
uint32 numShiny = material->GetTextureCount(aiTextureType_SHININESS);
for (uint32 i = 0; i < numShiny; ++i)
{
addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, { 0, -1, -1, -1 });
for (uint32 i = 0; i < numShiny; ++i) {
addTextureParameter(KEY_SHININESS_TEXTURE, aiTextureType_SHININESS, i, outputShininess, {0, -1, -1, -1});
}
// Roughness
addScalarParameter(KEY_ROUGHNESS, AI_MATKEY_ROUGHNESS_FACTOR);
std::string outputRoughness = KEY_ROUGHNESS;
uint32 numRoughness = material->GetTextureCount(aiTextureType_DIFFUSE_ROUGHNESS);
for (uint32 i = 0; i < numRoughness; ++i)
{
addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, { 0, -1, -1, -1 });
for (uint32 i = 0; i < numRoughness; ++i) {
addTextureParameter(KEY_ROUGHNESS_TEXTURE, aiTextureType_DIFFUSE_ROUGHNESS, i, outputRoughness, {0, -1, -1, -1});
}
// Metallic
addScalarParameter(KEY_METALLIC, AI_MATKEY_METALLIC_FACTOR);
std::string outputMetallic = KEY_METALLIC;
uint32 numMetallic = material->GetTextureCount(aiTextureType_METALNESS);
for (uint32 i = 0; i < numMetallic; ++i)
{
addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, { 0, -1, -1, -1 });
for (uint32 i = 0; i < numMetallic; ++i) {
addTextureParameter(KEY_METALLIC_TEXTURE, aiTextureType_METALNESS, i, outputMetallic, {0, -1, -1, -1});
}
// Ambient Occlusion
std::string outputAO = "";
uint32 numAO = material->GetTextureCount(aiTextureType_AMBIENT_OCCLUSION);
for (uint32 i = 0; i < numAO; ++i)
{
addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, { 0, -1, -1, -1 });
for (uint32 i = 0; i < numAO; ++i) {
addTextureParameter(KEY_AMBIENT_OCCLUSION_TEXTURE, aiTextureType_AMBIENT_OCCLUSION, i, outputAO, {0, -1, -1, -1});
}
MaterialNode brdf;
brdf.variables["baseColor"] = outputDiffuse;
if (!outputNormal.empty())
{
if (!outputNormal.empty()) {
expressions.add(new MulExpression());
expressions.back()->key = "NormalMul";
expressions.back()->inputs["lhs"].source = "2";
@@ -429,8 +391,7 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
brdf.profile = "CookTorrance";
brdf.variables["roughness"] = outputRoughness;
brdf.variables["metallic"] = outputMetallic;
if (!outputAO.empty())
{
if (!outputAO.empty()) {
brdf.variables["ambientOcclusion"] = outputAmbient;
}
break;
@@ -439,13 +400,8 @@ void MeshLoader::loadMaterials(const aiScene* scene, const Array<PTextureAsset>&
materialLayout->create();
OMaterialAsset baseMat = new MaterialAsset(importPath, materialName);
baseMat->material = new Material(graphics,
std::move(materialLayout),
uniformSize, 0, materialName,
std::move(expressions),
std::move(parameters),
std::move(brdf)
);
baseMat->material = new Material(graphics, std::move(materialLayout), uniformSize, 0, materialName, std::move(expressions),
std::move(parameters), std::move(brdf));
baseMat->material->compile();
graphics->getShaderCompiler()->registerMaterial(baseMat->material);
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)
{
if (node->mNumMeshes > 0)
{
void findMeshRoots(aiNode* node, List<aiNode*>& meshNodes) {
if (node->mNumMeshes > 0) {
meshNodes.add(node);
return;
}
for (uint32 i = 0; i < node->mNumChildren; ++i)
{
for (uint32 i = 0; i < node->mNumChildren; ++i) {
findMeshRoots(node->mChildren[i], meshNodes);
}
}
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes, Component::Collider& collider)
{
for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex)
{
void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialInstanceAsset>& materials, Array<OMesh>& globalMeshes,
Component::Collider& collider) {
for (int32 meshIndex = 0; meshIndex < scene->mNumMeshes; ++meshIndex) {
aiMesh* mesh = scene->mMeshes[meshIndex];
if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE))
continue;
@@ -483,8 +435,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
// assume static mesh for now
Array<Vector> positions(mesh->mNumVertices);
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);
}
Array<Vector> normals(mesh->mNumVertices);
@@ -493,45 +444,33 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
Array<Vector> colors(mesh->mNumVertices);
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);
for (size_t j = 0; j < MAX_TEXCOORDS; ++j)
{
if (mesh->HasTextureCoords(j))
{
for (size_t j = 0; j < MAX_TEXCOORDS; ++j) {
if (mesh->HasTextureCoords(j)) {
texCoords[j][i] = Vector2(mesh->mTextureCoords[j][i].x, mesh->mTextureCoords[j][i].y);
}
else
{
} else {
texCoords[j][i] = Vector2(0, 0);
}
}
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);
biTangents[i] = Vector(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z);
}
else
{
} else {
tangents[i] = Vector(0, 0, 1);
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);
}
else
{
} else {
colors[i] = Vector(1, 1, 1);
}
}
MeshId id = vertexData->allocateVertexData(mesh->mNumVertices);
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->loadNormals(id, normals);
@@ -540,8 +479,7 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
vertexData->loadColors(id, colors);
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 + 1] = mesh->mFaces[faceIndex].mIndices[1];
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);
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]->vertexData = vertexData;
@@ -564,42 +502,27 @@ void MeshLoader::loadGlobalMeshes(const aiScene* scene, const Array<PMaterialIns
}
}
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
);
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);
}
aiMatrix4x4 loadNodeTransform(aiNode* node)
{
aiMatrix4x4 loadNodeTransform(aiNode* node) {
aiMatrix4x4 parent = aiMatrix4x4();
if (node->mParent != nullptr)
{
if (node->mParent != nullptr) {
parent = loadNodeTransform(node->mParent);
}
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;
meshAsset->setStatus(Asset::Status::Loading);
Assimp::Importer importer;
importer.ReadFile(args.filePath.string().c_str(), (uint32)(
aiProcess_JoinIdenticalVertices |
aiProcess_FlipUVs |
aiProcess_Triangulate |
aiProcess_SortByPType |
aiProcess_GenBoundingBoxes |
aiProcess_GenSmoothNormals |
aiProcess_ImproveCacheLocality |
aiProcess_GenUVCoords |
aiProcess_FindDegenerates));
importer.ReadFile(args.filePath.string().c_str(),
(uint32)(aiProcess_JoinIdenticalVertices | aiProcess_FlipUVs | aiProcess_Triangulate | aiProcess_SortByPType |
aiProcess_GenBoundingBoxes | aiProcess_GenSmoothNormals | aiProcess_ImproveCacheLocality |
aiProcess_GenUVCoords | aiProcess_FindDegenerates));
const aiScene* scene = importer.ApplyPostProcessing(aiProcess_CalcTangentSpace);
std::cout << importer.GetErrorString() << std::endl;
@@ -616,12 +539,9 @@ void MeshLoader::import(MeshImportArgs args, PMeshAsset meshAsset)
findMeshRoots(scene->mRootNode, meshNodes);
Array<OMesh> meshes;
for (auto meshNode : meshNodes)
{
for (uint32 i = 0; i < meshNode->mNumMeshes; ++i)
{
if (globalMeshes[meshNode->mMeshes[i]] == nullptr)
{
for (auto meshNode : meshNodes) {
for (uint32 i = 0; i < meshNode->mNumMeshes; ++i) {
if (globalMeshes[meshNode->mMeshes[i]] == nullptr) {
continue;
}
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->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;
Serialization::save(archive, MeshAsset::IDENTIFIER);
+16 -13
View File
@@ -1,35 +1,38 @@
#pragma once
#include "MinimalEngine.h"
#include "Component/Collider.h"
#include "Containers/List.h"
#include "Containers/Map.h"
#include "Component/Collider.h"
#include "MinimalEngine.h"
#include <filesystem>
struct aiScene;
struct aiTexel;
struct aiNode;
namespace Seele
{
namespace Seele {
DECLARE_REF(Mesh)
DECLARE_REF(MeshAsset)
DECLARE_REF(MaterialInstanceAsset)
DECLARE_REF(TextureAsset)
DECLARE_NAME_REF(Gfx, Graphics)
struct MeshImportArgs
{
struct MeshImportArgs {
std::filesystem::path filePath;
std::string importPath;
};
class MeshLoader
{
public:
class MeshLoader {
public:
MeshLoader(Gfx::PGraphics graphic);
~MeshLoader();
void importAsset(MeshImportArgs args);
private:
void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath, 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);
private:
void loadTextures(const aiScene* scene, const std::filesystem::path& meshDirectory, const std::string& importPath,
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 import(MeshImportArgs args, PMeshAsset meshAsset);
+44 -47
View File
@@ -1,8 +1,9 @@
#include "TextureLoader.h"
#include "Asset/AssetRegistry.h"
#include "Asset/TextureAsset.h"
#include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h"
#include "Graphics/Vulkan/Enums.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
@@ -17,24 +18,21 @@
using namespace Seele;
TextureLoader::TextureLoader(Gfx::PGraphics graphics)
: graphics(graphics)
{
TextureLoader::TextureLoader(Gfx::PGraphics graphics) : graphics(graphics) {
OTextureAsset placeholder = new TextureAsset();
placeholderAsset = placeholder;
import(TextureImportArgs{
import(
TextureImportArgs{
.filePath = std::filesystem::absolute("textures/placeholder.png"),
.importPath = "",
}, placeholderAsset);
},
placeholderAsset);
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();
auto pos = str.rfind(".");
str.replace(str.begin() + pos, str.end(), "");
@@ -46,25 +44,26 @@ void TextureLoader::importAsset(TextureImportArgs args)
import(args, ref);
}
PTextureAsset TextureLoader::getPlaceholderTexture()
{
return placeholderAsset;
}
PTextureAsset TextureLoader::getPlaceholderTexture() { 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
if (args.filePath.extension().compare("ktx") != 0)
{
if (args.filePath.extension().compare("ktx") != 0) {
auto ktxFile = args.filePath;
ktxFile.replace_extension("ktx");
std::stringstream ss;
ss << "toktx --encode etc1s ";
if (args.type == TextureImportType::TEXTURE_NORMAL)
{
//ss << "--normal_mode ";
if (args.type == TextureImportType::TEXTURE_NORMAL) {
// ss << "--normal_mode ";
}
ss << ktxFile << " " << args.filePath;
system(ss.str().c_str());
@@ -72,23 +71,22 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
}
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;
//unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4);
//ktxTexture2* kTexture = nullptr;
//VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
//ktxTextureCreateInfo createInfo = {
// int totalWidth = 0, totalHeight = 0, n = 0;
// unsigned char* data = stbi_load(args.filePath.string().c_str(), &totalWidth, &totalHeight, &n, 4);
// ktxTexture2* kTexture = nullptr;
// VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
// ktxTextureCreateInfo createInfo = {
// .vkFormat = (uint32)format,
// .baseDepth = 1,
// .numLevels = 1,
// .numLayers = 1,
// .isArray = false,
// .generateMipmaps = false,
//};
// };
//
//if (args.type == TextureImportType::TEXTURE_CUBEMAP)
// if (args.type == TextureImportType::TEXTURE_CUBEMAP)
//{
// uint32 faceWidth = totalWidth / 4;
// // uint32 faceHeight = totalHeight / 3;
@@ -124,7 +122,7 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// loadCubeFace(1, 1, 4); // +Z
// loadCubeFace(3, 1, 5); // -Z
//}
//else
// else
//{
// createInfo.baseWidth = totalWidth;
// createInfo.baseHeight = totalHeight;
@@ -138,9 +136,9 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// ktxTexture_SetImageFromMemory(ktxTexture(kTexture),
// 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),
// .uastc = true,
// .threadCount = std::thread::hardware_concurrency(),
@@ -148,24 +146,23 @@ void TextureLoader::import(TextureImportArgs args, PTextureAsset textureAsset)
// .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW,
// .uastcRDO = true,
// .uastcRDOQualityScalar = 1,
//};
//KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams));
//KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3));
// };
// KTX_ASSERT(ktxTexture2_CompressBasisEx(kTexture, &basisParams));
// KTX_ASSERT(ktxTexture2_DeflateZstd(kTexture, 3));
//char writer[100];
//snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1");
//ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY,
// char writer[100];
// snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1");
// ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY,
// (ktx_uint32_t)strlen(writer) + 1,
// writer);
//uint8* texData;
//size_t texSize;
//KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(kTexture), &texData, &texSize));
// uint8* texData;
// size_t 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;
}
+9 -11
View File
@@ -1,36 +1,34 @@
#pragma once
#include "MinimalEngine.h"
#include "Containers/List.h"
#include "Graphics/Enums.h"
#include "MinimalEngine.h"
#include <filesystem>
namespace Seele
{
namespace Seele {
DECLARE_REF(TextureAsset)
DECLARE_NAME_REF(Gfx, Graphics)
DECLARE_NAME_REF(Gfx, Texture2D)
enum class TextureImportType
{
enum class TextureImportType {
TEXTURE_2D,
TEXTURE_NORMAL,
TEXTURE_CUBEMAP,
};
struct TextureImportArgs
{
struct TextureImportArgs {
std::filesystem::path filePath;
std::string importPath;
TextureImportType type = TextureImportType::TEXTURE_2D;
Gfx::SeImageUsageFlagBits usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
uint32 numChannels = 4;
};
class TextureLoader
{
public:
class TextureLoader {
public:
TextureLoader(Gfx::PGraphics graphic);
~TextureLoader();
void importAsset(TextureImportArgs args);
PTextureAsset getPlaceholderTexture();
private:
private:
void import(TextureImportArgs args, PTextureAsset asset);
Gfx::PGraphics graphics;
PTextureAsset placeholderAsset;
+20 -45
View File
@@ -1,74 +1,49 @@
#include "InspectorView.h"
#include "Graphics/Graphics.h"
#include "Actor/Actor.h"
#include "Asset/AssetRegistry.h"
#include "Asset/FontLoader.h"
#include "Graphics/Graphics.h"
#include "UI/System.h"
#include "Window/Window.h"
using namespace Seele;
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")
//, renderGraph(RenderGraphBuilder::build(
// UIPass(graphics),
// TextPass(graphics)
//))
, uiSystem(new UI::System())
{
//renderGraph.updateViewport(viewport);
,
uiSystem(new UI::System()) {
// renderGraph.updateViewport(viewport);
uiSystem->updateViewport(viewport);
}
InspectorView::~InspectorView()
{
InspectorView::~InspectorView() {}
void InspectorView::beginUpdate() {
// co_return;
}
void InspectorView::beginUpdate()
{
//co_return;
void InspectorView::update() {
// co_return;
}
void InspectorView::update()
{
//co_return;
}
void InspectorView::commitUpdate() {}
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::mouseButtonCallback(MouseButton, InputAction, KeyModifier)
{
}
void InspectorView::scrollCallback(double, double)
{
}
void InspectorView::fileCallback(int, const char**)
{
}
void InspectorView::fileCallback(int, const char**) {}
+9 -11
View File
@@ -1,19 +1,17 @@
#pragma once
#include "Window/View.h"
#include "Graphics/RenderPass/RenderGraph.h"
#include "Graphics/RenderPass/UIPass.h"
#include "Graphics/RenderPass/TextPass.h"
#include "Graphics/RenderPass/UIPass.h"
#include "UI/Elements/Panel.h"
#include "Window/View.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(Actor)
namespace Editor
{
class InspectorView : public View
{
public:
InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo &createInfo);
namespace Editor {
class InspectorView : public View {
public:
InspectorView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo);
virtual ~InspectorView();
virtual void beginUpdate() override;
@@ -23,8 +21,8 @@ public:
virtual void prepareRender() override;
virtual void render() override;
void selectActor();
protected:
protected:
UI::PSystem uiSystem;
PActor selectedActor;
+7 -26
View File
@@ -5,35 +5,16 @@ using namespace Seele;
using namespace Seele::Editor;
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()
{
GameView::beginUpdate();
}
void PlayView::beginUpdate() { GameView::beginUpdate(); }
void PlayView::update()
{
GameView::update();
}
void PlayView::update() { GameView::update(); }
void PlayView::commitUpdate()
{
GameView::commitUpdate();
}
void PlayView::commitUpdate() { GameView::commitUpdate(); }
void PlayView::prepareRender()
{
GameView::prepareRender();
}
void PlayView::prepareRender() { GameView::prepareRender(); }
void PlayView::render()
{
GameView::render();
}
void PlayView::render() { GameView::render(); }
+6 -8
View File
@@ -1,13 +1,10 @@
#pragma once
#include "Window/GameView.h"
namespace Seele
{
namespace Editor
{
class PlayView : public GameView
{
public:
namespace Seele {
namespace Editor {
class PlayView : public GameView {
public:
PlayView(Gfx::PGraphics graphics, PWindow window, const ViewportCreateInfo& createInfo, std::string dllPath);
virtual ~PlayView();
virtual void beginUpdate() override;
@@ -16,7 +13,8 @@ public:
virtual void prepareRender() override;
virtual void render() override;
private:
private:
};
DECLARE_REF(PlayView)
} // namespace Editor
+23 -48
View File
@@ -1,22 +1,20 @@
#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 "Asset/AssetRegistry.h"
#include "Asset/MeshAsset.h"
#include "Component/Camera.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::Editor;
SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo)
: View(graphics, owner, createInfo, "SceneView")
, scene(new Scene(graphics))
, cameraSystem(createInfo.dimensions, Vector(0, 0, 10))
{
SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo)
: View(graphics, owner, createInfo, "SceneView"), scene(new Scene(graphics)), cameraSystem(createInfo.dimensions, Vector(0, 0, 10)) {
cameraSystem.update(viewportCamera, static_cast<float>(Gfx::getCurrentFrameDelta()));
renderGraph.addPass(new DepthPrepass(graphics, scene));
renderGraph.addPass(new LightCullingPass(graphics, scene));
@@ -25,54 +23,31 @@ SceneView::SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreat
renderGraph.createRenderPass();
}
SceneView::~SceneView()
{
SceneView::~SceneView() {}
void SceneView::beginUpdate() {
// co_return;
}
void SceneView::beginUpdate()
{
//co_return;
}
void SceneView::update()
{
void SceneView::update() {
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()
{
renderGraph.render(viewportCamera);
}
void SceneView::render() { renderGraph.render(viewportCamera); }
void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier)
{
cameraSystem.keyCallback(code, action);
}
void SceneView::keyCallback(KeyCode code, InputAction action, KeyModifier) { cameraSystem.keyCallback(code, action); }
void SceneView::mouseMoveCallback(double xPos, double yPos)
{
cameraSystem.mouseMoveCallback(xPos, yPos);
}
void SceneView::mouseMoveCallback(double xPos, double 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);
}
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
#include "ThreadPool.h"
#include "Window/View.h"
#include "Graphics/RenderPass/BasePass.h"
#include "Graphics/RenderPass/DepthPrepass.h"
#include "Graphics/RenderPass/LightCullingPass.h"
#include "Graphics/RenderPass/BasePass.h"
#include "ThreadPool.h"
#include "ViewportControl.h"
#include "Window/View.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(Scene)
namespace Editor
{
class SceneView : public View
{
public:
SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo &createInfo);
namespace Editor {
class SceneView : public View {
public:
SceneView(Gfx::PGraphics graphics, PWindow owner, const ViewportCreateInfo& createInfo);
~SceneView();
virtual void beginUpdate() override;
@@ -25,7 +23,8 @@ public:
virtual void render() override;
PScene getScene() const { return scene; }
private:
private:
OScene scene;
Component::Camera viewportCamera;
+17 -42
View File
@@ -6,81 +6,56 @@ using namespace Seele;
using namespace Seele::Editor;
ViewportControl::ViewportControl(const URect& viewportDimensions, Vector initialPos)
: position(initialPos)
, fieldOfView(glm::radians(70.f))
, aspectRatio(static_cast<float>(viewportDimensions.size.x) / viewportDimensions.size.y)
, pitch(0)
, yaw(glm::pi<float>()/-2.0f)
{
: position(initialPos), fieldOfView(glm::radians(70.f)),
aspectRatio(static_cast<float>(viewportDimensions.size.x) / viewportDimensions.size.y), pitch(0), yaw(glm::pi<float>() / -2.0f) {
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;
if(keys[KeyCode::KEY_LEFT_SHIFT])
{
if (keys[KeyCode::KEY_LEFT_SHIFT]) {
cameraMove *= 4;
}
Vector moveVector = Vector();
Vector forward = glm::normalize(springArm);
Vector side = glm::cross(Vector(0, 1, 0), forward);
if(keys[KeyCode::KEY_W])
{
if (keys[KeyCode::KEY_W]) {
moveVector += forward * cameraMove;
}
if(keys[KeyCode::KEY_S])
{
if (keys[KeyCode::KEY_S]) {
moveVector += forward * -cameraMove;
}
if(keys[KeyCode::KEY_A])
{
if (keys[KeyCode::KEY_A]) {
moveVector += side * cameraMove;
}
if(keys[KeyCode::KEY_D])
{
if (keys[KeyCode::KEY_D]) {
moveVector += side * -cameraMove;
}
if(keys[KeyCode::KEY_E])
{
if (keys[KeyCode::KEY_E]) {
moveVector += glm::vec3(0, cameraMove, 0);
}
if(keys[KeyCode::KEY_Q])
{
if (keys[KeyCode::KEY_Q]) {
moveVector += glm::vec3(0, -cameraMove, 0);
}
throw std::logic_error("Not implemented");
}
void ViewportControl::keyCallback(KeyCode key, InputAction action)
{
keys[static_cast<size_t>(key)] = action != InputAction::RELEASE;
}
void ViewportControl::keyCallback(KeyCode key, InputAction action) { 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);
mouseY = static_cast<float>(yPos);
}
void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action)
{
if(button == MouseButton::MOUSE_BUTTON_1)
{
void ViewportControl::mouseButtonCallback(MouseButton button, InputAction action) {
if (button == MouseButton::MOUSE_BUTTON_1) {
mouse1 = action != InputAction::RELEASE;
}
if(button == MouseButton::MOUSE_BUTTON_2)
{
if (button == MouseButton::MOUSE_BUTTON_2) {
mouse2 = action != InputAction::RELEASE;
}
}
void ViewportControl::viewportResize(URect dimensions)
{
aspectRatio = static_cast<float>(dimensions.size.x) / dimensions.size.y;
}
void ViewportControl::viewportResize(URect dimensions) { aspectRatio = static_cast<float>(dimensions.size.x) / dimensions.size.y; }
+10 -11
View File
@@ -1,17 +1,15 @@
#pragma once
#include "MinimalEngine.h"
#include "Math/Vector.h"
#include "Component/Camera.h"
#include "Math/Math.h"
#include "Graphics/Enums.h"
#include "Containers/Array.h"
#include "Graphics/Enums.h"
#include "Math/Math.h"
#include "Math/Vector.h"
#include "MinimalEngine.h"
namespace Seele
{
namespace Editor
{
class ViewportControl
{
namespace Seele {
namespace Editor {
class ViewportControl {
public:
ViewportControl(const URect& viewportDimensions, Vector initialPos /*TODO: configurable initial rotations*/);
~ViewportControl();
@@ -20,6 +18,7 @@ namespace Editor
void mouseMoveCallback(double xPos, double yPos);
void mouseButtonCallback(MouseButton button, InputAction action);
void viewportResize(URect dimensions);
private:
Vector position;
Vector springArm;
@@ -32,6 +31,6 @@ namespace Editor
float mouseY;
float pitch;
float yaw;
};
};
} // namespace Editor
} // namespace Seele
+4 -6
View File
@@ -58,15 +58,13 @@ int main() {
AssetImporter::importMesh(MeshImportArgs{
.filePath = sourcePath / "import/models/cube.fbx",
});
//AssetImporter::importMesh(MeshImportArgs{
// AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import/models/greek-temple/source/greek-temple.fbx",
// .importPath = "temple"
// });
AssetImporter::importMesh(MeshImportArgs{
.filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx",
.importPath = "Whitechapel"
});
//AssetImporter::importMesh(MeshImportArgs{
AssetImporter::importMesh(MeshImportArgs{.filePath = sourcePath / "import/models/after-the-rain-vr-sound/source/Whitechapel.fbx",
.importPath = "Whitechapel"});
// AssetImporter::importMesh(MeshImportArgs{
// .filePath = sourcePath / "import/models/nitra-castle-rawscan/source/Nitriansky.obj",
// .importPath = "Nitriansky"
// });
+7 -22
View File
@@ -3,38 +3,23 @@
using namespace Seele;
Actor::Actor(PScene scene)
: Entity(scene)
{
attachComponent<Component::Transform>();
}
Actor::Actor(PScene scene) : 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 = newParent;
}
void Actor::addChild(PActor child)
{
void Actor::addChild(PActor child) {
children.add(child);
child->setParent(this);
}
void Actor::removeChild(PActor child)
{
void Actor::removeChild(PActor child) {
children.remove(children.find(child), false);
child->setParent(nullptr);
}
Component::Transform& Actor::getTransform()
{
return accessComponent<Component::Transform>();
}
Component::Transform& Actor::getTransform() { return accessComponent<Component::Transform>(); }
+7 -8
View File
@@ -1,15 +1,14 @@
#pragma once
#include "Entity.h"
#include "Component/Transform.h"
#include "Entity.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(Actor)
// 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
class Actor : public Entity
{
public:
class Actor : public Entity {
public:
Actor(PScene scene);
virtual ~Actor();
@@ -20,8 +19,8 @@ public:
Component::Transform& getTransform();
protected:
//Component::Transform& getTransform();
protected:
// Component::Transform& getTransform();
void setParent(PActor parent);
PActor parent;
Array<PActor> children;
+4 -14
View File
@@ -3,23 +3,13 @@
using namespace Seele;
CameraActor::CameraActor(PScene scene)
: Actor(scene)
{
CameraActor::CameraActor(PScene scene) : Actor(scene) {
attachComponent<Component::Camera>();
accessComponent<Component::Transform>().setPosition(Vector(10, 5, 14));
}
CameraActor::~CameraActor()
{
}
CameraActor::~CameraActor() {}
Component::Camera& CameraActor::getCameraComponent()
{
return accessComponent<Component::Camera>();
}
Component::Camera& CameraActor::getCameraComponent() { return accessComponent<Component::Camera>(); }
const Component::Camera& CameraActor::getCameraComponent() const
{
return accessComponent<Component::Camera>();
}
const Component::Camera& CameraActor::getCameraComponent() const { return accessComponent<Component::Camera>(); }
+5 -6
View File
@@ -2,16 +2,15 @@
#include "Actor.h"
#include "Component/Camera.h"
namespace Seele
{
class CameraActor : public Actor
{
public:
namespace Seele {
class CameraActor : public Actor {
public:
CameraActor(PScene scene);
virtual ~CameraActor();
Component::Camera& getCameraComponent();
const Component::Camera& getCameraComponent() const;
private:
private:
};
DEFINE_REF(CameraActor)
} // namespace Seele
+5 -16
View File
@@ -2,29 +2,18 @@
using namespace Seele;
DirectionalLightActor::DirectionalLightActor(PScene scene)
: Actor(scene)
{
attachComponent<Component::DirectionalLight>();
}
DirectionalLightActor::DirectionalLightActor(PScene scene) : Actor(scene) { attachComponent<Component::DirectionalLight>(); }
DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction)
: Actor(scene)
{
DirectionalLightActor::DirectionalLightActor(PScene scene, Vector color, Vector direction) : Actor(scene) {
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>();
}
const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const
{
const Component::DirectionalLight& DirectionalLightActor::getDirectionalLightComponent() const {
return accessComponent<Component::DirectionalLight>();
}
+5 -6
View File
@@ -2,17 +2,16 @@
#include "Actor.h"
#include "Component/DirectionalLight.h"
namespace Seele
{
class DirectionalLightActor : public Actor
{
public:
namespace Seele {
class DirectionalLightActor : public Actor {
public:
DirectionalLightActor(PScene scene);
DirectionalLightActor(PScene scene, Vector color, Vector direction);
virtual ~DirectionalLightActor();
Component::DirectionalLight& getDirectionalLightComponent();
const Component::DirectionalLight& getDirectionalLightComponent() const;
private:
private:
};
DEFINE_REF(DirectionalLightActor)
} // namespace Seele
+2 -10
View File
@@ -2,14 +2,6 @@
using namespace Seele;
Entity::Entity(PScene scene)
: scene(scene)
, identifier(scene->createEntity())
{
}
Entity::Entity(PScene scene) : 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
#include <entt/entt.hpp>
#include "MinimalEngine.h"
#include "Scene/Scene.h"
namespace Seele
{
#include <entt/entt.hpp>
namespace Seele {
// An entity describes a part of a scene
// It is just a wrapper the ID of a registry
class Entity
{
public:
class Entity {
public:
Entity(PScene scene);
virtual ~Entity();
template<typename Component, typename... Args>
Component& attachComponent(Args&&... args)
{
template <typename Component, typename... Args> Component& attachComponent(Args&&... args) {
return scene->attachComponent<Component>(identifier, std::forward<Args>(args)...);
}
template<typename Component>
Component& accessComponent()
{
return scene->accessComponent<Component>(identifier);
}
template<typename Component>
const Component& accessComponent() const
{
return scene->accessComponent<Component>(identifier);
}
protected:
template <typename Component> Component& accessComponent() { return scene->accessComponent<Component>(identifier); }
template <typename Component> const Component& accessComponent() const { return scene->accessComponent<Component>(identifier); }
protected:
PScene scene;
entt::entity identifier;
};
+5 -20
View File
@@ -2,29 +2,14 @@
using namespace Seele;
PointLightActor::PointLightActor(PScene scene)
: Actor(scene)
{
attachComponent<Component::PointLight>();
}
PointLightActor::PointLightActor(PScene scene) : Actor(scene) { attachComponent<Component::PointLight>(); }
PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation)
: Actor(scene)
{
PointLightActor::PointLightActor(PScene scene, Vector position, Vector color, float attenuation) : Actor(scene) {
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()
{
return accessComponent<Component::PointLight>();
}
const Component::PointLight& PointLightActor::getPointLightComponent() const
{
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 "Component/PointLight.h"
namespace Seele
{
class PointLightActor : public Actor
{
public:
namespace Seele {
class PointLightActor : public Actor {
public:
PointLightActor(PScene scene);
PointLightActor(PScene scene, Vector position, Vector color, float attenuation);
virtual ~PointLightActor();
Component::PointLight& getPointLightComponent();
const Component::PointLight& getPointLightComponent() const;
private:
private:
};
DEFINE_REF(PointLightActor)
} // namespace Seele
+4 -16
View File
@@ -2,22 +2,10 @@
using namespace Seele;
StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh)
: Actor(scene)
{
attachComponent<Component::Mesh>(mesh);
}
StaticMeshActor::StaticMeshActor(PScene scene, PMeshAsset mesh) : Actor(scene) { attachComponent<Component::Mesh>(mesh); }
Seele::StaticMeshActor::~StaticMeshActor()
{
}
Seele::StaticMeshActor::~StaticMeshActor() {}
Component::Mesh &Seele::StaticMeshActor::getMesh()
{
return accessComponent<Component::Mesh>();
}
Component::Mesh& Seele::StaticMeshActor::getMesh() { return accessComponent<Component::Mesh>(); }
const Component::Mesh &Seele::StaticMeshActor::getMesh() const
{
return accessComponent<Component::Mesh>();
}
const Component::Mesh& Seele::StaticMeshActor::getMesh() const { return accessComponent<Component::Mesh>(); }
+5 -6
View File
@@ -2,16 +2,15 @@
#include "Actor.h"
#include "Component/Mesh.h"
namespace Seele
{
class StaticMeshActor : public Actor
{
public:
namespace Seele {
class StaticMeshActor : public Actor {
public:
StaticMeshActor(PScene scene, PMeshAsset mesh);
virtual ~StaticMeshActor();
Component::Mesh& getMesh();
const Component::Mesh& getMesh() const;
private:
private:
};
DEFINE_REF(StaticMeshActor)
} // namespace Seele
+8 -33
View File
@@ -4,44 +4,19 @@
using namespace Seele;
Asset::Asset()
: folderPath("")
, name("")
, 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())
{
Asset::Asset() : folderPath(""), name(""), 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;
}
else
{
} else {
assetId = folderPath + "/" + name;
}
}
Asset::~Asset() {}
Asset::~Asset()
{
}
std::string Asset::getFolderPath() const { return folderPath; }
std::string Asset::getFolderPath() const
{
return folderPath;
}
std::string Asset::getName() const { return name; }
std::string Asset::getName() const
{
return name;
}
std::string Asset::getAssetIdentifier() const
{
return assetId;
}
std::string Asset::getAssetIdentifier() const { return assetId; }
+8 -20
View File
@@ -2,18 +2,11 @@
#include "MinimalEngine.h"
#include "Serialization/ArchiveBuffer.h"
namespace Seele
{
namespace Seele {
DECLARE_NAME_REF(Gfx, Graphics)
class Asset
{
public:
enum class Status
{
Uninitialized,
Loading,
Ready
};
class Asset {
public:
enum class Status { Uninitialized, Loading, Ready };
Asset();
Asset(std::string_view folderPath, std::string_view name);
virtual ~Asset();
@@ -31,15 +24,10 @@ public:
// returns the identifier with which it can be found from the asset registry
std::string getAssetIdentifier() const;
constexpr Status getStatus()
{
return status;
}
constexpr void setStatus(Status _status)
{
status = _status;
}
protected:
constexpr Status getStatus() { return status; }
constexpr void setStatus(Status _status) { status = _status; }
protected:
std::string folderPath;
std::string name;
std::string assetId;
+67 -149
View File
@@ -1,134 +1,96 @@
#include "AssetRegistry.h"
#include "MeshAsset.h"
#include "FontAsset.h"
#include "TextureAsset.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
#include "MaterialAsset.h"
#include "MaterialInstanceAsset.h"
#include "Graphics/Mesh.h"
#include "Graphics/Graphics.h"
#include "Window/WindowManager.h"
#include "MeshAsset.h"
#include <nlohmann/json.hpp>
#include <iostream>
#include "TextureAsset.h"
#include "Window/WindowManager.h"
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
using namespace Seele;
AssetRegistry* _instance = new AssetRegistry();
AssetRegistry::~AssetRegistry()
{
delete assetRoot;
}
AssetRegistry::~AssetRegistry() { delete assetRoot; }
void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics graphics)
{
get().initialize(rootFolder, graphics);
}
void AssetRegistry::init(std::filesystem::path rootFolder, Gfx::PGraphics 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;
if (!folderPath.empty())
{
if (!folderPath.empty()) {
folder = get().getOrCreateFolder(folderPath);
}
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;
if (!folderPath.empty())
{
if (!folderPath.empty()) {
folder = get().getOrCreateFolder(folderPath);
}
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;
if (!folderPath.empty())
{
if (!folderPath.empty()) {
folder = get().getOrCreateFolder(folderPath);
}
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;
if (!folderPath.empty())
{
if (!folderPath.empty()) {
folder = get().getOrCreateFolder(folderPath);
}
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;
if (!folderPath.empty())
{
if (!folderPath.empty()) {
folder = get().getOrCreateFolder(folderPath);
}
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);
}
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);
}
AssetRegistry &AssetRegistry::get()
{
return *_instance;
}
AssetRegistry& AssetRegistry::get() { return *_instance; }
AssetRegistry::AssetRegistry()
: assetRoot(nullptr)
{
}
AssetRegistry::AssetRegistry() : assetRoot(nullptr) {}
AssetRegistry* AssetRegistry::getInstance()
{
return _instance;
}
AssetRegistry* AssetRegistry::getInstance() { return _instance; }
void AssetRegistry::loadRegistry()
{
get().loadRegistryInternal();
}
void AssetRegistry::loadRegistry() { get().loadRegistryInternal(); }
void AssetRegistry::saveRegistry()
{
get().saveRegistryInternal();
}
void AssetRegistry::saveRegistry() { get().saveRegistryInternal(); }
AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath)
{
AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fullPath) {
AssetFolder* result = assetRoot;
std::string temp = std::string(fullPath);
while (!temp.empty())
{
while (!temp.empty()) {
size_t slashLoc = temp.find("/");
if (slashLoc == std::string::npos)
{
if (!result->children.contains(temp))
{
if (slashLoc == std::string::npos) {
if (!result->children.contains(temp)) {
result->children[temp] = new AssetFolder(temp);
}
return result->children[temp];
}
std::string folderName = temp.substr(0, slashLoc);
if (!result->children.contains(folderName))
{
if (!result->children.contains(folderName)) {
result->children[folderName] = new AssetFolder(fullPath);
}
result = result->children[folderName];
@@ -137,40 +99,31 @@ AssetRegistry::AssetFolder* AssetRegistry::getOrCreateFolder(std::string_view fu
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->rootFolder = _rootFolder;
this->assetRoot = new AssetFolder("");
loadRegistryInternal();
}
void AssetRegistry::loadRegistryInternal()
{
void AssetRegistry::loadRegistryInternal() {
peekFolder(assetRoot);
loadFolder(assetRoot);
}
void AssetRegistry::peekFolder(AssetFolder* folder)
{
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath))
{
void AssetRegistry::peekFolder(AssetFolder* folder) {
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) {
const auto& stem = entry.path().stem().string();
if (entry.is_directory())
{
if (folder->folderPath.empty())
{
if (entry.is_directory()) {
if (folder->folderPath.empty()) {
folder->children[stem] = new AssetFolder(stem);
}
else
{
} else {
folder->children[stem] = new AssetFolder(folder->folderPath + "/" + stem);
}
peekFolder(folder->children[stem]);
continue;
}
if(entry.path().filename().compare(".DS_Store") == 0)
{
if (entry.path().filename().compare(".DS_Store") == 0) {
continue;
}
auto stream = std::ifstream(entry.path(), std::ios::binary);
@@ -181,20 +134,16 @@ void AssetRegistry::peekFolder(AssetFolder* folder)
}
}
void AssetRegistry::loadFolder(AssetFolder* folder)
{
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath))
{
void AssetRegistry::loadFolder(AssetFolder* folder) {
for (const auto& entry : std::filesystem::directory_iterator(rootFolder / folder->folderPath)) {
const auto& path = entry.path();
if (entry.is_directory())
{
if (entry.is_directory()) {
auto relative = path.stem().string();
loadFolder(folder->children[relative]);
continue;
}
if(entry.path().filename().compare(".DS_Store") == 0)
{
if (entry.path().filename().compare(".DS_Store") == 0) {
continue;
}
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
uint64 identifier;
Serialization::load(buffer, identifier);
@@ -222,8 +170,7 @@ void AssetRegistry::peekAsset(ArchiveBuffer& buffer)
AssetFolder* folder = getOrCreateFolder(folderPath);
OAsset asset;
switch (identifier)
{
switch (identifier) {
case TextureAsset::IDENTIFIER:
asset = new TextureAsset(folderPath, name);
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
uint64 identifier;
Serialization::load(buffer, identifier);
@@ -266,8 +212,7 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer)
AssetFolder* folder = getOrCreateFolder(folderPath);
PAsset asset;
switch (identifier)
{
switch (identifier) {
case TextureAsset::IDENTIFIER:
asset = PTextureAsset(folder->textures.at(name));
break;
@@ -289,42 +234,31 @@ void AssetRegistry::loadAsset(ArchiveBuffer& buffer)
asset->load(buffer);
}
void AssetRegistry::saveRegistryInternal()
{
saveFolder("", assetRoot);
}
void AssetRegistry::saveRegistryInternal() { 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);
for (const auto& [name, texture] : folder->textures)
{
for (const auto& [name, texture] : folder->textures) {
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);
}
for (const auto& [name, material] : folder->materials)
{
for (const auto& [name, material] : folder->materials) {
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);
}
for (const auto& [name, font] : folder->fonts)
{
for (const auto& [name, font] : folder->fonts) {
saveAsset(PFontAsset(font), FontAsset::IDENTIFIER, folderPath, name);
}
for (auto& [name, child] : folder->children)
{
for (auto& [name, child] : folder->children) {
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())
return;
@@ -342,65 +276,49 @@ void AssetRegistry::saveAsset(PAsset asset, uint64 identifier, const std::filesy
buffer.writeToStream(assetStream);
}
std::filesystem::path AssetRegistry::getRootFolder()
{
return get().rootFolder;
}
std::filesystem::path AssetRegistry::getRootFolder() { return get().rootFolder; }
void AssetRegistry::registerMesh(OMeshAsset mesh)
{
void AssetRegistry::registerMesh(OMeshAsset mesh) {
AssetFolder* folder = getOrCreateFolder(mesh->getFolderPath());
folder->meshes[mesh->getName()] = std::move(mesh);
}
void AssetRegistry::registerTexture(OTextureAsset texture)
{
void AssetRegistry::registerTexture(OTextureAsset texture) {
AssetFolder* folder = getOrCreateFolder(texture->getFolderPath());
folder->textures[texture->getName()] = std::move(texture);
}
void AssetRegistry::registerFont(OFontAsset font)
{
void AssetRegistry::registerFont(OFontAsset font) {
AssetFolder* folder = getOrCreateFolder(font->getFolderPath());
folder->fonts[font->getName()] = std::move(font);
}
void AssetRegistry::registerMaterial(OMaterialAsset material)
{
void AssetRegistry::registerMaterial(OMaterialAsset material) {
AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
folder->materials[material->getName()] = std::move(material);
}
void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material)
{
void AssetRegistry::registerMaterialInstance(OMaterialInstanceAsset material) {
AssetFolder* folder = getOrCreateFolder(material->getFolderPath());
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;
std::filesystem::create_directories(fullPath.parent_path());
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;
std::filesystem::create_directories(fullPath.parent_path());
return std::ifstream(fullPath.string(), openmode);
}
AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath)
: folderPath(folderPath)
{}
AssetRegistry::AssetFolder::AssetFolder(std::string_view folderPath) : folderPath(folderPath) {}
AssetRegistry::AssetFolder::~AssetFolder()
{
for (auto [_, child] : children)
{
AssetRegistry::AssetFolder::~AssetFolder() {
for (auto [_, child] : children) {
delete child;
}
}
+10 -11
View File
@@ -1,21 +1,20 @@
#pragma once
#include "MinimalEngine.h"
#include "Asset.h"
#include "Containers/Map.h"
#include <string>
#include "MinimalEngine.h"
#include <filesystem>
#include <string>
namespace Seele
{
namespace Seele {
DECLARE_REF(TextureAsset)
DECLARE_REF(FontAsset)
DECLARE_REF(MeshAsset)
DECLARE_REF(MaterialAsset)
DECLARE_REF(MaterialInstanceAsset)
DECLARE_NAME_REF(Gfx, Graphics)
class AssetRegistry
{
public:
class AssetRegistry {
public:
~AssetRegistry();
static void init(std::filesystem::path path, Gfx::PGraphics graphics);
@@ -34,8 +33,7 @@ public:
static void loadRegistry();
static void saveRegistry();
struct AssetFolder
{
struct AssetFolder {
std::string folderPath;
Map<std::string, AssetFolder*> children;
Map<std::string, OTextureAsset> textures;
@@ -49,7 +47,8 @@ public:
AssetFolder* getOrCreateFolder(std::string_view foldername);
AssetRegistry();
static AssetRegistry* getInstance();
private:
private:
static AssetRegistry& get();
void initialize(const std::filesystem::path& rootFolder, Gfx::PGraphics graphics);
@@ -81,4 +80,4 @@ private:
friend class MaterialLoader;
friend class MeshLoader;
};
}
} // namespace Seele
+19 -41
View File
@@ -5,26 +5,16 @@
using namespace Seele;
FontAsset::FontAsset()
{
}
FontAsset::FontAsset() {}
FontAsset::FontAsset(std::string_view folderPath, std::string_view name)
: Asset(folderPath, name)
{
}
FontAsset::FontAsset(std::string_view folderPath, std::string_view 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, usedTextures.size());
for (uint32 x = 0; x < usedTextures.size(); ++x)
{
for (uint32 x = 0; x < usedTextures.size(); ++x) {
Array<uint8> textureData;
ktxTexture2* kTexture;
ktxTextureCreateInfo createInfo = {
@@ -34,7 +24,9 @@ void FontAsset::save(ArchiveBuffer& buffer) const
.baseWidth = usedTextures[x]->getWidth(),
.baseHeight = usedTextures[x]->getHeight(),
.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(),
.numLayers = usedTextures[x]->getDepth(),
.numFaces = usedTextures[x]->getNumFaces(),
@@ -43,10 +35,8 @@ void FontAsset::save(ArchiveBuffer& buffer) const
};
ktxTexture2_Create(&createInfo, KTX_TEXTURE_CREATE_ALLOC_STORAGE, &kTexture);
for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth)
{
for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face)
{
for (uint32 depth = 0; depth < usedTextures[x]->getDepth(); ++depth) {
for (uint32 face = 0; face < usedTextures[x]->getNumFaces(); ++face) {
// technically, downloading cant be const, because we have to allocate temporary buffers and change layouts
// but practically the texture stays the same
const_cast<Gfx::Texture2D*>(*(usedTextures[x]))->download(0, depth, face, textureData);
@@ -55,9 +45,7 @@ void FontAsset::save(ArchiveBuffer& buffer) const
}
char writer[100];
snprintf(writer, sizeof(writer), "%s version %s", "SeeleEngine", "0.0.1");
ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY,
(ktx_uint32_t)strlen(writer) + 1,
writer);
ktxHashList_AddKVPair(&kTexture->kvDataHead, KTX_WRITER_KEY, (ktx_uint32_t)strlen(writer) + 1, writer);
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);
size_t numTextures;
Serialization::load(buffer, numTextures);
for (uint64 x = 0; x < numTextures; ++x)
{
for (uint64 x = 0; x < numTextures; ++x) {
Array<uint8> rawTex;
Serialization::load(buffer, rawTex);
ktxTexture2* kTexture;
ktxTexture2_CreateFromMemory(rawTex.data(),
rawTex.size(),
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT,
&kTexture);
ktxTexture2_CreateFromMemory(rawTex.data(), rawTex.size(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &kTexture);
ktxTexture2_TranscodeBasis(kTexture, KTX_TTF_BC7_RGBA, 0);
TextureCreateInfo createInfo = {
.sourceData = {
.sourceData =
{
.size = ktxTexture_GetDataSize(ktxTexture(kTexture)),
.data = ktxTexture_GetData(ktxTexture(kTexture)),
.owner = Gfx::QueueType::GRAPHICS,
@@ -116,21 +99,16 @@ void FontAsset::load(ArchiveBuffer& buffer)
}
}
void Seele::FontAsset::setUsedTextures(Array<Gfx::OTexture2D> _usedTextures)
{
usedTextures = std::move(_usedTextures);
}
void Seele::FontAsset::setUsedTextures(Array<Gfx::OTexture2D> _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, size);
Serialization::save(buffer, bearing);
Serialization::save(buffer, advance);
}
void FontAsset::Glyph::load(ArchiveBuffer& buffer)
{
void FontAsset::Glyph::load(ArchiveBuffer& buffer) {
Serialization::load(buffer, textureIndex);
Serialization::load(buffer, size);
Serialization::load(buffer, bearing);
+6 -8
View File
@@ -3,12 +3,10 @@
#include "Containers/Map.h"
#include "Math/Math.h"
namespace Seele
{
namespace Seele {
DECLARE_NAME_REF(Gfx, Texture2D)
class FontAsset : public Asset
{
public:
class FontAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x10;
FontAsset();
FontAsset(std::string_view folderPath, std::string_view name);
@@ -16,8 +14,7 @@ public:
virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override;
struct Glyph
{
struct Glyph {
uint32 textureIndex;
IVector2 size;
IVector2 bearing;
@@ -28,7 +25,8 @@ public:
const Map<uint32, Glyph> getGlyphData() const { return glyphs; }
Gfx::PTexture2D getTexture(uint32 index) { return usedTextures[index]; }
void setUsedTextures(Array<Gfx::OTexture2D> _usedTextures);
private:
private:
Array<Gfx::OTexture2D> usedTextures;
Map<uint32, Glyph> glyphs;
friend class FontLoader;
+5 -21
View File
@@ -2,28 +2,12 @@
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)
: Asset(folderPath, name)
{
LevelAsset::~LevelAsset() {}
}
void LevelAsset::save(ArchiveBuffer&) const {}
LevelAsset::~LevelAsset()
{
}
void LevelAsset::save(ArchiveBuffer&) const
{
}
void LevelAsset::load(ArchiveBuffer&)
{
}
void LevelAsset::load(ArchiveBuffer&) {}
+4 -6
View File
@@ -1,18 +1,16 @@
#pragma once
#include "Asset.h"
namespace Seele
{
class LevelAsset : public Asset
{
public:
namespace Seele {
class LevelAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x20;
LevelAsset();
LevelAsset(std::string_view folderPath, std::string_view name);
virtual ~LevelAsset();
virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override;
private:
private:
};
} // namespace Seele
+10 -21
View File
@@ -1,38 +1,27 @@
#include "MaterialAsset.h"
#include "Material/Material.h"
#include "Graphics/Graphics.h"
#include "MaterialInstanceAsset.h"
#include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
#include "Material/Material.h"
#include "MaterialInstanceAsset.h"
using namespace Seele;
MaterialAsset::MaterialAsset()
{
}
MaterialAsset::MaterialAsset() {}
MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name)
: Asset(folderPath, name)
{
}
MaterialAsset::MaterialAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
MaterialAsset::~MaterialAsset()
{
}
MaterialAsset::~MaterialAsset() {}
void MaterialAsset::save(ArchiveBuffer& buffer) const
{
material->save(buffer);
}
void MaterialAsset::save(ArchiveBuffer& buffer) const { material->save(buffer); }
void MaterialAsset::load(ArchiveBuffer& buffer)
{
void MaterialAsset::load(ArchiveBuffer& buffer) {
material = new Material();
material->load(buffer);
material->compile();
}
PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params)
{
PMaterialInstanceAsset MaterialAsset::instantiate(const InstantiationParameter& params) {
OMaterialInstance instance = material->instantiate();
instance->setBaseMaterial(this);
OMaterialInstanceAsset asset = new MaterialInstanceAsset(params.folderPath, params.name);
+6 -8
View File
@@ -1,18 +1,15 @@
#pragma once
#include "Asset.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(Material)
DECLARE_REF(MaterialInstanceAsset)
struct InstantiationParameter
{
struct InstantiationParameter {
std::string name;
std::string folderPath;
};
class MaterialAsset : public Asset
{
public:
class MaterialAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x4;
MaterialAsset();
MaterialAsset(std::string_view folderPath, std::string_view name);
@@ -21,7 +18,8 @@ public:
virtual void load(ArchiveBuffer& buffer) override;
PMaterial getMaterial() const { return material; }
PMaterialInstanceAsset instantiate(const InstantiationParameter& params);
private:
private:
OMaterial material;
friend class MaterialLoader;
friend class MeshLoader;
+9 -18
View File
@@ -1,34 +1,25 @@
#include "MaterialInstanceAsset.h"
#include "Material/MaterialInstance.h"
#include "Material/Material.h"
#include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
#include "Material/Material.h"
#include "Material/MaterialInstance.h"
using namespace Seele;
MaterialInstanceAsset::MaterialInstanceAsset()
{
}
MaterialInstanceAsset::MaterialInstanceAsset() {}
MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view name)
: Asset(folderPath, name)
{
}
MaterialInstanceAsset::MaterialInstanceAsset(std::string_view folderPath, std::string_view 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->getName());
material->save(buffer);
}
void MaterialInstanceAsset::load(ArchiveBuffer& buffer)
{
void MaterialInstanceAsset::load(ArchiveBuffer& buffer) {
std::string folder;
Serialization::load(buffer, folder);
std::string id;
+5 -6
View File
@@ -2,11 +2,9 @@
#include "Asset.h"
#include "Material/MaterialInstance.h"
namespace Seele
{
class MaterialInstanceAsset : public Asset
{
public:
namespace Seele {
class MaterialInstanceAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x8;
MaterialInstanceAsset();
MaterialInstanceAsset(std::string_view folderPath, std::string_view name);
@@ -16,7 +14,8 @@ public:
void setHandle(OMaterialInstance handle) { material = std::move(handle); }
void setBase(PMaterialAsset base) { baseMaterial = base; }
PMaterialInstance getHandle() const { return material; }
private:
private:
OMaterialInstance material;
PMaterialAsset baseMaterial;
};
+7 -19
View File
@@ -1,29 +1,17 @@
#include "MeshAsset.h"
#include "AssetRegistry.h"
#include "Graphics/Graphics.h"
#include "Graphics/Mesh.h"
#include "AssetRegistry.h"
using namespace Seele;
MeshAsset::MeshAsset()
{
}
MeshAsset::MeshAsset() {}
MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name)
: Asset(folderPath, name)
{
}
MeshAsset::MeshAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
MeshAsset::~MeshAsset()
{
}
MeshAsset::~MeshAsset() {}
void MeshAsset::save(ArchiveBuffer& buffer) const
{
Serialization::save(buffer, meshes);
}
void MeshAsset::save(ArchiveBuffer& buffer) const { Serialization::save(buffer, meshes); }
void MeshAsset::load(ArchiveBuffer& buffer)
{
Serialization::load(buffer, meshes);
}
void MeshAsset::load(ArchiveBuffer& buffer) { Serialization::load(buffer, meshes); }
+4 -6
View File
@@ -2,20 +2,18 @@
#include "Asset.h"
#include "Component/Collider.h"
namespace Seele
{
namespace Seele {
DECLARE_REF(Mesh)
DECLARE_REF(MaterialInterface)
class MeshAsset : public Asset
{
public:
class MeshAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x2;
MeshAsset();
MeshAsset(std::string_view folderPath, std::string_view name);
virtual ~MeshAsset();
virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override;
//Workaround while no editor
// Workaround while no editor
Array<OMesh> meshes;
Component::Collider physicsMesh;
};
+36 -52
View File
@@ -1,30 +1,30 @@
#include "TextureAsset.h"
#include "Graphics/Graphics.h"
#include "Window/WindowManager.h"
#include "Graphics/Vulkan/Enums.h"
#include "Graphics/Texture.h"
#include "Graphics/Vulkan/Enums.h"
#include "Window/WindowManager.h"
#include "ktx.h"
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)
: Asset(folderPath, name)
{
}
TextureAsset::TextureAsset(std::string_view folderPath, std::string_view name) : Asset(folderPath, name) {}
TextureAsset::~TextureAsset()
{
}
TextureAsset::~TextureAsset() {}
void TextureAsset::save(ArchiveBuffer& buffer) const
{
//ktxBasisParams basisParams = {
void TextureAsset::save(ArchiveBuffer& buffer) const {
// ktxBasisParams basisParams = {
// .structSize = sizeof(ktxBasisParams),
// .uastc = true,
// .threadCount = std::thread::hardware_concurrency(),
@@ -32,34 +32,32 @@ void TextureAsset::save(ArchiveBuffer& buffer) const
// .uastcFlags = KTX_PACK_UASTC_LEVEL_VERYSLOW,
// .uastcRDO = true,
// .uastcRDOQualityScalar = 1,
//};
//KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams));
//KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20));
//ktx_uint8_t* texData;
//ktx_size_t texSize;
//KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize));
// };
// KTX_ASSERT(ktxTexture2_CompressBasisEx(ktxHandle, &basisParams));
// KTX_ASSERT(ktxTexture2_DeflateZstd(ktxHandle, 20));
// ktx_uint8_t* texData;
// ktx_size_t texSize;
// KTX_ASSERT(ktxTexture_WriteToMemory(ktxTexture(ktxHandle), &texData, &texSize));
//
//Array<uint8> rawData(texSize);
//std::memcpy(rawData.data(), texData, texSize);
//Serialization::save(buffer, rawData);
//free(texData);
// Array<uint8> rawData(texSize);
// std::memcpy(rawData.data(), texData, texSize);
// Serialization::save(buffer, rawData);
// free(texData);
}
void TextureAsset::load(ArchiveBuffer& buffer)
{
void TextureAsset::load(ArchiveBuffer& buffer) {
std::string ktxPath;
Serialization::load(buffer, ktxPath);
ktxTexture2* ktxHandle;
KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(),
KTX_TEXTURE_CREATE_NO_FLAGS,
(ktxTexture**)&ktxHandle));
KTX_ASSERT(ktxTexture_CreateFromNamedFile(ktxPath.c_str(), KTX_TEXTURE_CREATE_NO_FLAGS, (ktxTexture**)&ktxHandle));
KTX_ASSERT(ktxTexture2_TranscodeBasis(ktxHandle, KTX_TTF_BC7_RGBA, 0));
Gfx::PGraphics graphics = buffer.getGraphics();
TextureCreateInfo createInfo = {
.sourceData = {
.sourceData =
{
.size = ktxTexture_GetDataSize(ktxTexture(ktxHandle)),
.data = ktxTexture_GetData(ktxTexture(ktxHandle)),
.owner = Gfx::QueueType::TRANSFER,
@@ -73,16 +71,11 @@ void TextureAsset::load(ArchiveBuffer& buffer)
.elements = ktxHandle->numLayers,
.usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT,
};
if (ktxHandle->isCubemap)
{
if (ktxHandle->isCubemap) {
texture = graphics->createTextureCube(createInfo);
}
else if (ktxHandle->isArray)
{
} else if (ktxHandle->isArray) {
texture = graphics->createTexture3D(createInfo);
}
else
{
} else {
texture = graphics->createTexture2D(createInfo);
}
@@ -90,17 +83,8 @@ void TextureAsset::load(ArchiveBuffer& buffer)
ktxTexture_Destroy(ktxTexture(ktxHandle));
}
void TextureAsset::setTexture(Gfx::OTexture _texture)
{
texture = std::move(_texture);
}
void TextureAsset::setTexture(Gfx::OTexture _texture) { texture = std::move(_texture); }
uint32 TextureAsset::getWidth()
{
return texture->getWidth();
}
uint32 TextureAsset::getWidth() { return texture->getWidth(); }
uint32 TextureAsset::getHeight()
{
return texture->getHeight();
}
uint32 TextureAsset::getHeight() { return texture->getHeight(); }
+6 -10
View File
@@ -2,12 +2,10 @@
#include "Asset.h"
struct ktxTexture2;
namespace Seele
{
namespace Seele {
DECLARE_NAME_REF(Gfx, Texture)
class TextureAsset : public Asset
{
public:
class TextureAsset : public Asset {
public:
static constexpr uint64 IDENTIFIER = 0x1;
TextureAsset();
TextureAsset(std::string_view folderPath, std::string_view name);
@@ -15,13 +13,11 @@ public:
virtual void save(ArchiveBuffer& buffer) const override;
virtual void load(ArchiveBuffer& buffer) override;
void setTexture(Gfx::OTexture _texture);
Gfx::PTexture getTexture()
{
return texture;
}
Gfx::PTexture getTexture() { return texture; }
uint32 getWidth();
uint32 getHeight();
private:
private:
Gfx::OTexture texture;
bool normalMap;
friend class TextureLoader;
+11 -22
View File
@@ -7,21 +7,14 @@ using namespace Seele;
using namespace Seele::Component;
using namespace Seele::Math;
Camera::Camera()
: viewMatrix(Matrix4())
, cameraPos(Vector())
, bNeedsViewBuild(false)
{
yaw = -3.1415f/2;
Camera::Camera() : viewMatrix(Matrix4()), cameraPos(Vector()), bNeedsViewBuild(false) {
yaw = -3.1415f / 2;
pitch = 0;
}
Camera::~Camera()
{
}
Camera::~Camera() {}
void Camera::mouseMove(float deltaYaw, float deltaPitch)
{
void Camera::mouseMove(float deltaYaw, float deltaPitch) {
yaw += deltaYaw / 500.f;
pitch += deltaPitch / 500.f;
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;
}
void Camera::mouseScroll(float x)
{
getTransform().translate(getTransform().getForward()*x);
void Camera::mouseScroll(float x) {
getTransform().translate(getTransform().getForward() * x);
bNeedsViewBuild = true;
}
void Camera::moveX(float amount)
{
getTransform().translate(getTransform().getForward()*amount);
void Camera::moveX(float amount) {
getTransform().translate(getTransform().getForward() * amount);
bNeedsViewBuild = true;
}
void Camera::moveY(float amount)
{
getTransform().translate(getTransform().getRight()*amount);
void Camera::moveY(float amount) {
getTransform().translate(getTransform().getRight() * amount);
bNeedsViewBuild = true;
}
void Camera::buildViewMatrix()
{
void Camera::buildViewMatrix() {
Vector eyePos = getTransform().getPosition();
Vector lookAt = eyePos + getTransform().getForward();
viewMatrix = glm::lookAt(eyePos, lookAt, Vector(0, 1, 0));
+8 -14
View File
@@ -3,26 +3,19 @@
#include "Math/Matrix.h"
#include "Transform.h"
namespace Seele
{
namespace Component
{
struct Camera
{
namespace Seele {
namespace Component {
struct Camera {
REQUIRE_COMPONENT(Transform)
Camera();
~Camera();
Matrix4 getViewMatrix() const
{
assert (!bNeedsViewBuild);
Matrix4 getViewMatrix() const {
assert(!bNeedsViewBuild);
return viewMatrix;
}
Vector getCameraPosition() const
{
return cameraPos;
}
Vector getCameraPosition() const { return cameraPos; }
void mouseMove(float deltaX, float deltaY);
void mouseScroll(float x);
void moveX(float amount);
@@ -30,7 +23,8 @@ struct Camera
void buildViewMatrix();
bool mainCamera = false;
private:
private:
float yaw;
float pitch;
Matrix4 viewMatrix;
+1 -2
View File
@@ -3,8 +3,7 @@
using namespace Seele;
using namespace Seele::Component;
Collider Collider::transform(const Transform& transform) const
{
Collider Collider::transform(const Transform& transform) const {
return Collider{
.type = this->type,
.boundingbox = this->boundingbox.getTransformedBox(transform.toMatrix()),
+4 -8
View File
@@ -2,17 +2,13 @@
#include "Math/AABB.h"
#include "ShapeBase.h"
namespace Seele
{
namespace Component
{
enum class ColliderType
{
namespace Seele {
namespace Component {
enum class ColliderType {
STATIC,
DYNAMIC,
};
struct Collider
{
struct Collider {
ColliderType type = ColliderType::STATIC;
AABB boundingbox;
ShapeBase physicsMesh;
+12 -29
View File
@@ -2,58 +2,41 @@
#include <concepts>
#include <tuple>
namespace Seele
{
template<typename... Types>
struct Dependencies;
template<>
struct Dependencies<>
{
namespace Seele {
template <typename... Types> struct Dependencies;
template <> struct Dependencies<> {
int x;
template<typename... Right>
Dependencies<Right...> operator|(const Dependencies<Right...>&)
{
return Dependencies<Right...>();
}
template <typename... Right> Dependencies<Right...> operator|(const Dependencies<Right...>&) { return Dependencies<Right...>(); }
};
template<typename This, typename... Rest>
struct Dependencies<This, Rest...> : public Dependencies<Rest...>
{
template<typename... Right>
Dependencies<This, Rest..., Right...> operator|(const Dependencies<Right...>&)
{
template <typename This, typename... Rest> struct Dependencies<This, Rest...> : public Dependencies<Rest...> {
template <typename... Right> Dependencies<This, Rest..., Right...> operator|(const Dependencies<Right...>&) {
return Dependencies<This, Rest..., Right...>();
}
int x;
};
namespace Component
{
template<typename Comp>
Comp& getComponent();
namespace Component {
template <typename Comp> Comp& getComponent();
}
template<typename Comp>
template <typename Comp>
concept has_dependencies = requires(Comp) { Comp::dependencies; };
#define REQUIRE_COMPONENT(x) \
private: \
x& get##x() { return getComponent<x>(); } \
const x& get##x() const { return getComponent<x>(); } \
\
public: \
constexpr static Dependencies<x> dependencies = {};
#define DECLARE_COMPONENT(x) \
void accessComponent(x& val); \
template<> \
x& getComponent<x>();
template <> x& getComponent<x>();
#define DEFINE_COMPONENT(x) \
thread_local x* tl_##x = nullptr; \
void Seele::Component::accessComponent(x& ref) { tl_##x = &ref; } \
template<> \
x& Seele::Component::getComponent<x>() { return *tl_##x; }
template <> x& Seele::Component::getComponent<x>() { return *tl_##x; }
} // namespace Seele
+3 -6
View File
@@ -1,11 +1,8 @@
#pragma once
#include "Math/Vector.h"
namespace Seele
{
namespace Component
{
struct DirectionalLight
{
namespace Seele {
namespace Component {
struct DirectionalLight {
Vector4 color;
Vector4 direction;
};
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once
#include "Graphics/Resources.h"
namespace Seele
{
namespace Component
{
struct KeyboardInput
{
namespace Seele {
namespace Component {
struct KeyboardInput {
Seele::StaticArray<bool, static_cast<size_t>(Seele::KeyCode::KEY_LAST)> keys;
bool mouse1;
bool mouse2;
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once
#include "Asset/MeshAsset.h"
namespace Seele
{
namespace Component
{
struct Mesh
{
namespace Seele {
namespace Component {
struct Mesh {
PMeshAsset asset;
bool isStatic = true;
};
+4 -7
View File
@@ -1,14 +1,11 @@
#pragma once
#include "Math/Vector.h"
namespace Seele
{
namespace Component
{
struct PointLight
{
namespace Seele {
namespace Component {
struct PointLight {
Vector4 positionWS;
//Vector4 positionVS;
// Vector4 positionVS;
Vector4 colorRange;
};
} // namespace Component
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once
#include "Math/AABB.h"
namespace Seele
{
namespace Component
{
struct RigidBody
{
namespace Seele {
namespace Component {
struct RigidBody {
float mass = 1.0f;
Vector force;
Vector torque;
+48 -74
View File
@@ -4,10 +4,8 @@
using namespace Seele;
using namespace Seele::Component;
//https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html
struct ComputationState
{
// https://people.eecs.berkeley.edu/~jfc/mirtich/massProps.html
struct ComputationState {
// compute physics properties
int A; /* alpha */
int B; /* beta */
@@ -24,22 +22,19 @@ struct ComputationState
Vector T1, T2, TP;
};
struct Face
{
struct Face {
StaticArray<Vector, 3> vertices;
Vector normal;
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;
for(uint32_t i = 0; i < 3; ++i)
{
for (uint32_t i = 0; i < 3; ++i) {
float a0 = f.vertices[i][state.A];
float b0 = f.vertices[i][state.B];
float a1 = f.vertices[(i+1)%3][state.A];
float b1 = f.vertices[(i+1)%3][state.B];
float a1 = f.vertices[(i + 1) % 3][state.A];
float b1 = f.vertices[(i + 1) % 3][state.B];
float da = a1 - a0;
float db = b1 - b0;
@@ -87,10 +82,9 @@ void computeProjectionIntegrals(Face& f, ComputationState& state)
state.Pabb /= -60.0;
}
void computeFaceIntegrals(Face& f, ComputationState& state)
{
void computeFaceIntegrals(Face& f, ComputationState& 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 k3 = k2 * k1;
float k4 = k3 * k1;
@@ -104,53 +98,46 @@ void computeFaceIntegrals(Face& f, ComputationState& state)
state.Faa = k1 * state.Paa;
state.Fbb = k1 * state.Pbb;
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
+ w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1));
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 +
w * (2 * (n[state.A] * state.Pa + n[state.B] * state.Pb) + w * state.P1));
state.Faaa = k1 * state.Paaa;
state.Fbbb = k1 * state.Pbbb;
state.Fccc = -k4 * (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.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
+ 2 * n[state.A] * n[state.B] * state.Pa
+ 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.Fccc =
-k4 *
(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.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 + 2 * n[state.A] * n[state.B] * state.Pa + 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.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
+ w * (2 * (n[state.A] * state.Paa + n[state.B] * state.Pab) + w * state.Pa));
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 + 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));
for (size_t i = 0; i < indices.size(); i+=3)
{
for (size_t i = 0; i < indices.size(); i += 3) {
Face f;
f.vertices = {
vertices[indices[i]],
vertices[indices[i+1]],
vertices[indices[i+2]],
vertices[indices[i + 1]],
vertices[indices[i + 2]],
};
Vector e1 = f.vertices[2] - f.vertices[0];
Vector e2 = f.vertices[1] - f.vertices[0];
f.normal = glm::normalize(glm::cross(e1, e2));
f.w = - f.normal.x * f.vertices[0].x
- f.normal.y * f.vertices[0].y
- f.normal.z * f.vertices[0].z;
f.w = -f.normal.x * f.vertices[0].x - f.normal.y * f.vertices[0].y - f.normal.z * f.vertices[0].z;
float nx = std::abs(f.normal.x);
float ny = std::abs(f.normal.y);
float nz = std::abs(f.normal.z);
if (nx > ny && nx > nz) state.C = 0;
else state.C = (ny > nz) ? 1 : 2;
if (nx > ny && nx > nz)
state.C = 0;
else
state.C = (ny > nz) ? 1 : 2;
state.A = (state.C + 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;
}
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;
computeVolumeIntegrals(vertices, indices, state);
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[1][1] = density * (state.T2.z + state.T2.x);
bodyInertia[2][2] = density * (state.T2.x + state.T2.y);
bodyInertia[0][1] = bodyInertia[1][0] = - density * state.TP.x;
bodyInertia[1][2] = bodyInertia[2][1] = - density * state.TP.y;
bodyInertia[2][1] = bodyInertia[1][2] = - density * state.TP.z;
bodyInertia[0][1] = bodyInertia[1][0] = -density * state.TP.x;
bodyInertia[1][2] = bodyInertia[2][1] = -density * state.TP.y;
bodyInertia[2][1] = bodyInertia[1][2] = -density * state.TP.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);
@@ -195,74 +182,61 @@ void computePhysicsParamsForMesh(Array<Vector>& vertices, const Array<uint32>& i
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);
}
ShapeBase ShapeBase::transform(const Component::Transform& transform) const
{
ShapeBase ShapeBase::transform(const Component::Transform& transform) const {
ShapeBase result = *this;
for(auto& vert : result.vertices)
{
for (auto& vert : result.vertices) {
vert = transform.toMatrix() * Vector4(vert, 1.0f);
}
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();
for(auto vert : verts)
{
for (auto vert : verts) {
vertices.add(Vector(matrix * Vector4(vert, 1.0f)));
}
for(auto ind : inds)
{
for (auto ind : inds) {
indices.add(ind + static_cast<uint32>(indOffset));
}
computePhysicsParamsForMesh(vertices, indices, bodyInertia, centerOfMass, mass);
}
void ShapeBase::visualize() const
{
void ShapeBase::visualize() const {
Array<DebugVertex> verts;
for(uint32 i = 0; i < indices.size(); i+=3)
{
for (uint32 i = 0; i < indices.size(); i += 3) {
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+0]]),
.position = Vector(vertices[indices[i + 0]]),
.color = Vector(1, 0, 0),
});
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+1]]),
.position = Vector(vertices[indices[i + 1]]),
.color = Vector(1, 0, 0),
});
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+1]]),
.position = Vector(vertices[indices[i + 1]]),
.color = Vector(1, 0, 0),
});
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+2]]),
.position = Vector(vertices[indices[i + 2]]),
.color = Vector(1, 0, 0),
});
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+2]]),
.position = Vector(vertices[indices[i + 2]]),
.color = Vector(1, 0, 0),
});
verts.add(DebugVertex{
.position = Vector(vertices[indices[i+0]]),
.position = Vector(vertices[indices[i + 0]]),
.color = Vector(1, 0, 0),
});
}
+5 -7
View File
@@ -1,14 +1,12 @@
#pragma once
#include "Containers/Array.h"
#include "Transform.h"
#include "Graphics/DebugVertex.h"
#include "Transform.h"
namespace Seele
{
namespace Component
{
struct ShapeBase
{
namespace Seele {
namespace Component {
struct ShapeBase {
ShapeBase();
ShapeBase(Array<Vector> vertices, Array<uint32> indices);
ShapeBase transform(const Component::Transform& transform) const;
+3 -6
View File
@@ -1,12 +1,9 @@
#pragma once
#include "Graphics/Texture.h"
namespace Seele
{
namespace Component
{
struct Skybox
{
namespace Seele {
namespace Component {
struct Skybox {
Gfx::PTextureCube day;
Gfx::PTextureCube night;
Vector fogColor;
+6 -24
View File
@@ -4,29 +4,11 @@ using namespace Seele::Component;
DEFINE_COMPONENT(Transform);
void Transform::setPosition(Vector pos)
{
transform.setPosition(pos);
}
void Transform::setPosition(Vector pos) { transform.setPosition(pos); }
void Transform::setRotation(Quaternion quat)
{
transform.setRotation(quat);
}
void Transform::setRotation(Quaternion quat) { transform.setRotation(quat); }
void Transform::setScale(Vector scale)
{
transform.setScale(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);
}
void Transform::setScale(Vector scale) { transform.setScale(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
#include "Math/Transform.h"
#include "Component.h"
#include "Math/Transform.h"
namespace Seele
{
namespace Component
{
struct Transform
{
namespace Seele {
namespace Component {
struct Transform {
Vector getPosition() const { return transform.getPosition(); }
Quaternion getRotation() const { return transform.getRotation(); }
Vector getScale() const { return transform.getScale(); }
@@ -24,7 +22,8 @@ struct Transform
void translate(Vector direction);
void rotate(Quaternion quat);
void scale(Vector scale);
private:
private:
Math::Transform transform;
};
DECLARE_COMPONENT(Transform)
+6 -13
View File
@@ -1,19 +1,12 @@
#pragma once
#include <concepts>
namespace Seele
{
template<class F, class... Args>
namespace Seele {
template <class F, class... Args>
concept invocable = std::invocable<F, Args...>;
template<class Archive, class T>
concept serializable = requires(const T& t, Archive& a)
{
t.save(a);
} && requires(T& t, Archive& a)
{
t.load(a);
};
template<typename T>
template <class Archive, class T>
concept serializable = requires(const T& t, Archive& a) { t.save(a); } && requires(T& t, Archive& a) { t.load(a); };
template <typename T>
concept enumeration = std::is_enum_v<T>;
}
} // namespace Seele
+189 -482
View File
@@ -1,24 +1,20 @@
#pragma once
#include "EngineTypes.h"
#include <algorithm>
#include <assert.h>
#include <initializer_list>
#include <iterator>
#include <assert.h>
#include <memory_resource>
#include <algorithm>
#ifndef DEFAULT_ALLOC_SIZE
#define DEFAULT_ALLOC_SIZE 16
#endif
namespace Seele
{
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>>
struct Array
{
public:
template <typename X>
class IteratorBase
{
namespace Seele {
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> struct Array {
public:
template <typename X> class IteratorBase {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = X;
@@ -26,78 +22,48 @@ public:
using reference = X&;
using pointer = X*;
constexpr IteratorBase(X *x = nullptr)
: 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 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
{
constexpr IteratorBase(X* x = nullptr) : 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 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);
tmp.p += other;
return tmp;
}
constexpr int operator-(const IteratorBase &other) const
{
return (int)(p - other.p);
}
constexpr IteratorBase& operator-=(difference_type other)
{
p-=other;
constexpr int operator-(const IteratorBase& other) const { return (int)(p - other.p); }
constexpr IteratorBase& operator-=(difference_type other) {
p -= other;
return *this;
}
constexpr IteratorBase& operator+=(difference_type other)
{
p+=other;
constexpr IteratorBase& operator+=(difference_type other) {
p += other;
return *this;
}
constexpr IteratorBase operator-(difference_type diff) const
{
return IteratorBase(p - diff);
}
constexpr IteratorBase &operator++()
{
constexpr IteratorBase operator-(difference_type diff) const { return IteratorBase(p - diff); }
constexpr IteratorBase& operator++() {
p++;
return *this;
}
constexpr IteratorBase &operator--()
{
constexpr IteratorBase& operator--() {
p--;
return *this;
}
constexpr IteratorBase operator++(int)
{
constexpr IteratorBase operator++(int) {
IteratorBase tmp(*this);
++*this;
return tmp;
}
constexpr IteratorBase operator--(int)
{
constexpr IteratorBase operator--(int) {
IteratorBase tmp(*this);
--*this;
return tmp;
}
private:
X *p;
X* p;
};
using value_type = T;
@@ -116,97 +82,63 @@ public:
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr Array() noexcept(noexcept(Allocator()))
: arraySize(0)
, allocated(DEFAULT_ALLOC_SIZE)
, allocator(Allocator())
{
constexpr Array() noexcept(noexcept(Allocator())) : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(Allocator()) {
_data = allocateArray(DEFAULT_ALLOC_SIZE);
assert(_data != nullptr);
}
constexpr explicit Array(const allocator_type& alloc) noexcept
: arraySize(0)
, allocated(DEFAULT_ALLOC_SIZE)
, allocator(alloc)
{
constexpr explicit Array(const allocator_type& alloc) noexcept : arraySize(0), allocated(DEFAULT_ALLOC_SIZE), allocator(alloc) {
_data = allocateArray(DEFAULT_ALLOC_SIZE);
assert(_data != nullptr);
}
constexpr Array(size_type size, const value_type& value, const allocator_type& alloc = allocator_type())
: arraySize(size)
, allocated(size)
, allocator(alloc)
{
: arraySize(size), allocated(size), allocator(alloc) {
_data = allocateArray(size);
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);
}
}
constexpr explicit Array(size_type size, const allocator_type& alloc = allocator_type())
: arraySize(size)
, allocated(size)
, allocator(alloc)
{
: arraySize(size), allocated(size), allocator(alloc) {
_data = allocateArray(size);
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));
}
else
{
for (size_type i = 0; i < size; ++i)
{
} else {
for (size_type i = 0; i < size; ++i) {
std::allocator_traits<allocator_type>::construct(allocator, &_data[i]);
}
}
}
constexpr Array(std::initializer_list<T> init, const allocator_type& alloc = allocator_type())
: arraySize(init.size())
, allocated(init.size())
, allocator(alloc)
{
: arraySize(init.size()), allocated(init.size()), allocator(alloc) {
_data = allocateArray(init.size());
assert(_data != nullptr);
std::uninitialized_move(init.begin(), init.end(), begin());
}
constexpr Array(const Array &other)
: arraySize(other.arraySize)
, allocated(other.allocated)
, allocator(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator))
{
constexpr Array(const Array& other)
: arraySize(other.arraySize), allocated(other.allocated),
allocator(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator)) {
_data = allocateArray(other.allocated);
assert(_data != nullptr);
std::uninitialized_copy(other.begin(), other.end(), begin());
}
constexpr Array(const Array& other, const Allocator& alloc)
: arraySize(other.arraySize)
, allocated(other.allocated)
, allocator(alloc)
{
constexpr Array(const Array& other, const Allocator& alloc) : arraySize(other.arraySize), allocated(other.allocated), allocator(alloc) {
_data = allocateArray(other.allocated);
assert(_data != nullptr);
std::uninitialized_copy(other.begin(), other.end(), begin());
}
constexpr Array(Array &&other) noexcept
: arraySize(std::move(other.arraySize))
, allocated(std::move(other.allocated))
, allocator(std::move(other.allocator))
{
constexpr Array(Array&& other) noexcept
: arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(std::move(other.allocator)) {
_data = other._data;
other._data = nullptr;
other.allocated = 0;
other.arraySize = 0;
}
constexpr Array(Array &&other, const Allocator& alloc) noexcept
: arraySize(std::move(other.arraySize))
, allocated(std::move(other.allocated))
, allocator(alloc)
{
constexpr Array(Array&& other, const Allocator& alloc) noexcept
: arraySize(std::move(other.arraySize)), allocated(std::move(other.allocated)), allocator(alloc) {
_data = allocateArray(other.allocated);
std::uninitialized_move(other.begin(), other.end(), begin());
other.deallocateArray(other._data, other.allocated);
@@ -214,25 +146,18 @@ public:
other.allocated = 0;
other.arraySize = 0;
}
Array &operator=(const Array &other)
{
if (this != &other)
{
if (other.arraySize > allocated)
{
Array& operator=(const Array& other) {
if (this != &other) {
if (other.arraySize > allocated) {
clear();
}
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 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) {
clear();
}
allocator = other.allocator;
}
if(_data == nullptr)
{
if (_data == nullptr) {
_data = allocateArray(other.allocated);
allocated = other.allocated;
}
@@ -241,17 +166,13 @@ public:
}
return *this;
}
Array &operator=(Array &&other) noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value
|| std::allocator_traits<Allocator>::is_always_equal::value)
{
if (this != &other)
{
if (_data != nullptr)
{
Array& operator=(Array&& other) noexcept(std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value ||
std::allocator_traits<Allocator>::is_always_equal::value) {
if (this != &other) {
if (_data != nullptr) {
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);
}
allocated = std::move(other.allocated);
@@ -261,153 +182,96 @@ public:
}
return *this;
}
constexpr ~Array()
{
clear();
}
constexpr ~Array() { clear(); }
[[nodiscard]]
constexpr iterator find(const value_type &item) noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if (_data[i] == item)
{
constexpr iterator find(const value_type& item) noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (_data[i] == item) {
return iterator(&_data[i]);
}
}
return end();
}
[[nodiscard]]
constexpr iterator find(value_type&& item) noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if (_data[i] == item)
{
constexpr iterator find(value_type&& item) noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (_data[i] == item) {
return iterator(&_data[i]);
}
}
return end();
}
[[nodiscard]]
constexpr const_iterator find(const value_type &item) const noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if (_data[i] == item)
{
constexpr const_iterator find(const value_type& item) const noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (_data[i] == item) {
return const_iterator(&_data[i]);
}
}
return end();
}
[[nodiscard]]
constexpr const_iterator find(value_type&& item) const noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if (_data[i] == item)
{
constexpr const_iterator find(value_type&& item) const noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (_data[i] == item) {
return const_iterator(&_data[i]);
}
}
return end();
}
template<class Pred>
template <class Pred>
requires std::predicate<Pred, value_type>
constexpr const_iterator find(Pred pred) const noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if(pred(_data[i]))
{
constexpr const_iterator find(Pred pred) const noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (pred(_data[i])) {
return const_iterator(&_data[i]);
}
}
return end();
}
template<class Pred>
template <class Pred>
requires std::predicate<Pred, value_type>
constexpr iterator find(Pred pred) noexcept
{
for (size_type i = 0; i < arraySize; ++i)
{
if (pred(_data[i]))
{
constexpr iterator find(Pred pred) noexcept {
for (size_type i = 0; i < arraySize; ++i) {
if (pred(_data[i])) {
return iterator(&_data[i]);
}
}
return end();
}
constexpr allocator_type get_allocator() const noexcept
{
return allocator;
}
constexpr iterator begin() noexcept
{
return iterator(_data);
}
constexpr iterator end() noexcept
{
return iterator(_data + arraySize);
}
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)
{
constexpr allocator_type get_allocator() const noexcept { return allocator; }
constexpr iterator begin() noexcept { return iterator(_data); }
constexpr iterator end() noexcept { return iterator(_data + arraySize); }
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);
}
}
constexpr void addAll(Array&& other)
{
for(auto&& value : other)
{
constexpr void addAll(Array&& other) {
for (auto&& value : other) {
addInternal(value);
}
}
constexpr reference addUnique(const value_type &item = value_type())
{
constexpr reference addUnique(const value_type& item = value_type()) {
iterator it;
if((it = std::move(find(item))) != end())
{
if ((it = std::move(find(item))) != end()) {
return *it;
}
return addInternal(item);
}
template<typename... args>
constexpr reference emplace(args... arguments)
{
if (arraySize == allocated)
{
template <typename... args> constexpr reference emplace(args... arguments) {
if (arraySize == allocated) {
size_type newSize = arraySize + 1;
allocated = calculateGrowth(newSize);
T *tempArray = allocateArray(allocated);
T* tempArray = allocateArray(allocated);
assert(tempArray != nullptr);
std::uninitialized_move(begin(), end(), Iterator(tempArray));
@@ -417,61 +281,33 @@ public:
std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize++], arguments...);
return _data[arraySize - 1];
}
template<class Pred>
template <class Pred>
requires std::predicate<Pred, value_type>
constexpr void remove_if(Pred pred, bool keepOrder = true)
{
constexpr void remove_if(Pred pred, bool keepOrder = true) {
remove(find(pred), keepOrder);
}
constexpr void remove(const value_type& element, bool keepOrder = true)
{
remove(find(element), keepOrder);
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); }
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)
{
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
{
} else {
_data[index] = std::move(_data[arraySize - 1]);
}
std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]);
}
constexpr void resize(size_type newSize)
{
resizeInternal(newSize, T());
}
constexpr void resize(size_type newSize, const value_type& value)
{
resizeInternal(newSize, value);
}
constexpr void clear() noexcept
{
if(_data == nullptr)
{
constexpr void resize(size_type newSize) { resizeInternal(newSize, T()); }
constexpr void resize(size_type newSize, const value_type& value) { resizeInternal(newSize, value); }
constexpr void clear() noexcept {
if (_data == nullptr) {
return;
}
if constexpr (!std::is_trivially_destructible_v<T>)
{
for (size_type i = 0; i < arraySize; ++i)
{
if constexpr (!std::is_trivially_destructible_v<T>) {
for (size_type i = 0; i < arraySize; ++i) {
std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]);
}
}
@@ -480,42 +316,21 @@ public:
arraySize = 0;
allocated = 0;
}
constexpr size_type indexOf(iterator iterator)
{
return iterator - begin();
}
constexpr size_type indexOf(const_iterator iterator) const
{
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;
}
constexpr size_type indexOf(iterator iterator) { return iterator - begin(); }
constexpr size_type indexOf(const_iterator iterator) const { 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]]
constexpr bool empty() const noexcept
{
constexpr bool empty() const noexcept {
return arraySize == 0;
}
constexpr void reserve(size_type new_cap)
{
if(new_cap > allocated)
{
constexpr void reserve(size_type new_cap) {
if (new_cap > allocated) {
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);
}
else
{
} else {
std::uninitialized_move_n(begin(), arraySize, temp);
}
deallocateArray(_data, allocated);
@@ -523,78 +338,55 @@ public:
}
allocated = new_cap;
}
constexpr size_type capacity() const noexcept
{
return allocated;
}
constexpr pointer data() const noexcept
{
return _data;
}
constexpr reference front() const
{
constexpr size_type capacity() const noexcept { return allocated; }
constexpr pointer data() const noexcept { return _data; }
constexpr reference front() const {
assert(arraySize > 0);
return _data[0];
}
constexpr reference back() const
{
constexpr reference back() const {
assert(arraySize > 0);
return _data[arraySize - 1];
}
constexpr void pop()
{
std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]);
}
constexpr reference operator[](size_type index)
{
constexpr void pop() { std::allocator_traits<allocator_type>::destroy(allocator, &_data[--arraySize]); }
constexpr reference operator[](size_type index) {
assert(index < arraySize);
return _data[index];
}
constexpr const_reference operator[](size_type index) const
{
constexpr const_reference operator[](size_type index) const {
assert(index < arraySize);
return _data[index];
}
private:
size_type calculateGrowth(size_type newSize) const
{
private:
size_type calculateGrowth(size_type newSize) const {
const size_type oldCapacity = capacity();
if (oldCapacity > SIZE_MAX - oldCapacity)
{
if (oldCapacity > SIZE_MAX - oldCapacity) {
return newSize; // geometric growth would overflow
}
const size_type geometric = oldCapacity + oldCapacity;
if (geometric < newSize)
{
if (geometric < newSize) {
return newSize; // geometric growth would be insufficient
}
return geometric; // geometric growth is sufficient
}
[[nodiscard]]
T* allocateArray(size_type size)
{
T* allocateArray(size_type size) {
T* result = allocator.allocate(size);
assert(result != nullptr);
return result;
}
void deallocateArray(T* ptr, size_type size)
{
allocator.deallocate(ptr, size);
}
template<typename Type>
T& addInternal(Type&& t) noexcept
{
if (arraySize == allocated)
{
void deallocateArray(T* ptr, size_type size) { allocator.deallocate(ptr, size); }
template <typename Type> T& addInternal(Type&& t) noexcept {
if (arraySize == allocated) {
size_type newSize = arraySize + 1;
allocated = calculateGrowth(newSize);
T *tempArray = allocateArray(allocated);
for (size_type i = 0; i < arraySize; ++i)
{
T* tempArray = allocateArray(allocated);
for (size_type i = 0; i < arraySize; ++i) {
std::allocator_traits<allocator_type>::construct(allocator, &tempArray[i], std::forward<Type>(_data[i]));
}
deallocateArray(_data, arraySize);
@@ -603,52 +395,37 @@ private:
std::allocator_traits<allocator_type>::construct(allocator, &_data[arraySize], std::forward<Type>(t));
return _data[arraySize++];
}
template<typename Type>
void resizeInternal(size_type newSize, const Type& value) noexcept
{
if (newSize <= allocated)
{
template <typename Type> void resizeInternal(size_type newSize, const Type& value) noexcept {
if (newSize <= allocated) {
// The array is already big enough
if(newSize < arraySize)
{
if (newSize < arraySize) {
// But since we are sizing down we destruct some of them
if constexpr (!std::is_trivially_destructible_v<T>)
{
for (size_type i = newSize; i < arraySize; ++i)
{
if constexpr (!std::is_trivially_destructible_v<T>) {
for (size_type i = newSize; i < arraySize; ++i) {
std::allocator_traits<allocator_type>::destroy(allocator, &_data[i]);
}
}
}
else
{
} else {
// 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);
}
}
arraySize = newSize;
}
else
{
} else {
allocated = calculateGrowth(newSize);
// 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::memset(&newData[arraySize], 0, sizeof(T) * (allocated - arraySize));
}
else
{
} else {
// And move the current elements into that one
std::uninitialized_move(begin(), end(), Iterator(newData));
// 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);
}
}
@@ -659,41 +436,29 @@ private:
}
size_type arraySize = 0;
size_type allocated = 0;
T *_data = nullptr;
T* _data = nullptr;
allocator_type allocator;
};
template<class Type, class Alloc>
constexpr bool operator==(const Array<Type, Alloc> &lhs, const Array<Type, Alloc>& rhs)
{
if(lhs.size() != rhs.size())
{
template <class Type, class Alloc> constexpr bool operator==(const Array<Type, Alloc>& lhs, const Array<Type, Alloc>& rhs) {
if (lhs.size() != rhs.size()) {
return false;
}
for(auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2)
{
if(*it1 != *it2)
{
for (auto it1 = lhs.begin(), it2 = rhs.begin(); it1 != lhs.end() && it2 != rhs.end(); ++it1, ++it2) {
if (*it1 != *it2) {
return false;
}
}
return true;
}
template<class Type, class Alloc>
constexpr auto operator<=>(const Array<Type, Alloc>& lhs, const Array<Type, Alloc>& rhs)
{
template <class Type, class Alloc> 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());
}
template <typename T, size_t N>
struct StaticArray
{
public:
template <typename X>
class IteratorBase
{
template <typename T, size_t N> struct StaticArray {
public:
template <typename X> class IteratorBase {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = X;
@@ -701,52 +466,32 @@ public:
using reference = X&;
using pointer = X*;
IteratorBase(X *x = nullptr)
: p(x)
{
}
reference operator*() const
{
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++()
{
IteratorBase(X* x = nullptr) : p(x) {}
reference operator*() const { 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++;
return *this;
}
IteratorBase operator++(int)
{
IteratorBase operator++(int) {
IteratorBase tmp(*this);
++*this;
return tmp;
}
IteratorBase &operator--()
{
IteratorBase& operator--() {
p--;
return *this;
}
IteratorBase operator--(int)
{
IteratorBase operator--(int) {
IteratorBase tmp(*this);
--*this;
return tmp;
}
private:
X *p;
X* p;
};
using value_type = T;
using size_type = size_t;
@@ -762,85 +507,47 @@ public:
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
StaticArray()
{
StaticArray() {
beginIt = iterator(_data);
endIt = iterator(_data + N);
}
StaticArray(T value)
{
for (size_t i = 0; i < N; ++i)
{
StaticArray(T value) {
for (size_t i = 0; i < N; ++i) {
_data[i] = value;
}
beginIt = iterator(_data);
endIt = iterator(_data + N);
}
StaticArray(std::initializer_list<T> init)
{
StaticArray(std::initializer_list<T> init) {
auto beg = init.begin();
for (size_t i = 0; i < N; ++i)
{
for (size_t i = 0; i < N; ++i) {
_data[i] = *beg;
if (init.size() == N)
{
if (init.size() == N) {
beg++;
}
}
}
~StaticArray()
{
}
~StaticArray() {}
inline size_type size() const
{
return N;
}
inline pointer data()
{
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
{
inline size_type size() const { return N; }
inline pointer data() { 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);
return _data[index];
}
constexpr const_reference operator[](size_type index) const noexcept
{
constexpr const_reference operator[](size_type index) const noexcept {
assert(index < N);
return _data[index];
}
iterator begin()
{
return beginIt;
}
iterator end()
{
return endIt;
}
const_iterator begin() const
{
return beginIt;
}
const_iterator end() const
{
return beginIt;
}
private:
iterator begin() { return beginIt; }
iterator end() { return endIt; }
const_iterator begin() const { return beginIt; }
const_iterator end() const { return beginIt; }
private:
T _data[N];
iterator beginIt;
iterator endIt;
+102 -269
View File
@@ -1,35 +1,22 @@
#pragma once
#include <memory_resource>
#include <assert.h>
#include <memory_resource>
namespace Seele
{
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>>
class List
{
private:
struct Node
{
Node(Node* prev, Node* next, const T& data)
: 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;
namespace Seele {
template <typename T, typename Allocator = std::pmr::polymorphic_allocator<T>> class List {
private:
struct Node {
Node(Node* prev, Node* next, const T& data) : 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;
};
using NodeAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Node>;
public:
template <typename X>
class IteratorBase
{
public:
template <typename X> class IteratorBase {
public:
using iterator_category = std::forward_iterator_tag;
using value_type = X;
@@ -37,82 +24,48 @@ public:
using reference = X&;
using pointer = X*;
IteratorBase(Node *x = nullptr)
: node(x)
{
}
IteratorBase(const IteratorBase &i)
: node(i.node)
{
}
IteratorBase(IteratorBase&& i) noexcept
: node(std::move(i.node))
{
}
~IteratorBase()
{
}
IteratorBase& operator=(const IteratorBase& other)
{
if(this != &other)
{
IteratorBase(Node* x = nullptr) : node(x) {}
IteratorBase(const IteratorBase& i) : node(i.node) {}
IteratorBase(IteratorBase&& i) noexcept : node(std::move(i.node)) {}
~IteratorBase() {}
IteratorBase& operator=(const IteratorBase& other) {
if (this != &other) {
node = other.node;
}
return *this;
}
IteratorBase& operator=(IteratorBase&& other) noexcept
{
if(this != &other)
{
IteratorBase& operator=(IteratorBase&& other) noexcept {
if (this != &other) {
node = std::move(other.node);
}
return *this;
}
constexpr reference operator*() const
{
return node->data;
}
constexpr pointer operator->() const
{
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--()
{
constexpr reference operator*() const { return node->data; }
constexpr pointer operator->() const { 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;
return *this;
}
constexpr IteratorBase operator--(int)
{
constexpr IteratorBase operator--(int) {
IteratorBase tmp(*this);
--*this;
return tmp;
}
constexpr IteratorBase &operator++()
{
constexpr IteratorBase& operator++() {
node = node->next;
return *this;
}
constexpr IteratorBase operator++(int)
{
constexpr IteratorBase operator++(int) {
IteratorBase tmp(*this);
++*this;
return tmp;
}
private:
Node *node;
Node* node;
friend class List<T>;
};
@@ -133,117 +86,71 @@ public:
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr List()
: allocator(Allocator())
, root(allocateNode())
, tail(root)
, beginIt(Iterator(root))
, endIt(Iterator(tail))
, _size(0)
{
}
constexpr List() : allocator(Allocator()), root(allocateNode()), tail(root), beginIt(Iterator(root)), endIt(Iterator(tail)), _size(0) {}
constexpr explicit List(const Allocator& alloc)
: allocator(alloc)
, root(allocateNode())
, tail(root)
, 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)
{
: allocator(alloc), root(allocateNode()), tail(root), 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);
}
}
constexpr List(size_type count, const Allocator& alloc = Allocator())
: List(alloc)
{
for(size_type i = 0; i < count; ++i)
{
constexpr List(size_type count, const Allocator& alloc = Allocator()) : List(alloc) {
for (size_type i = 0; i < count; ++i) {
add(T());
}
}
constexpr List(const List& other)
: List(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator))
{
//TODO: improve
for(const auto& it : other)
{
: List(std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.allocator)) {
// TODO: improve
for (const auto& it : other) {
add(it);
}
}
constexpr List(const List& other, const Allocator& alloc)
: List(alloc)
{
//TODO: improve
for(const auto& it : other)
{
constexpr List(const List& other, const Allocator& alloc) : List(alloc) {
// TODO: improve
for (const auto& it : other) {
add(it);
}
}
constexpr List(List&& other)
: allocator(std::move(other.allocator))
, root(std::move(other.root))
, tail(std::move(other.tail))
, beginIt(std::move(other.beginIt))
, endIt(std::move(other.endIt))
, _size(std::move(other._size))
{
: allocator(std::move(other.allocator)), root(std::move(other.root)), tail(std::move(other.tail)),
beginIt(std::move(other.beginIt)), endIt(std::move(other.endIt)), _size(std::move(other._size)) {
other.root = nullptr;
other.tail = nullptr;
other._size = 0;
}
constexpr List(List&& other, const Allocator& alloc)
: allocator(alloc)
, root(std::move(other.root))
, tail(std::move(other.tail))
, beginIt(std::move(other.beginIt))
, endIt(std::move(other.endIt))
, _size(std::move(other._size))
{
: allocator(alloc), root(std::move(other.root)), tail(std::move(other.tail)), beginIt(std::move(other.beginIt)),
endIt(std::move(other.endIt)), _size(std::move(other._size)) {
other.root = nullptr;
other.tail = nullptr;
other._size = 0;
}
constexpr ~List()
{
constexpr ~List() {
clear();
deallocateNode(tail);
}
constexpr List& operator=(const List& other)
{
if(this != &other)
{
constexpr List& operator=(const List& other) {
if (this != &other) {
clear();
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 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) {
clear();
}
allocator = other.allocator;
}
for(const auto& it : other)
{
for (const auto& it : other) {
add(it);
}
markIteratorDirty();
}
return *this;
}
constexpr List& operator=(List&& other)
{
if(this != &other)
{
constexpr List& operator=(List&& other) {
if (this != &other) {
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);
}
root = other.root;
@@ -259,22 +166,13 @@ public:
return *this;
}
constexpr reference front()
{
return root->data;
}
constexpr reference back()
{
return tail->prev->data;
}
constexpr void clear()
{
if (empty())
{
constexpr reference front() { return root->data; }
constexpr reference back() { return tail->prev->data; }
constexpr void clear() {
if (empty()) {
return;
}
for (Node *tmp = root; tmp != tail;)
{
for (Node* tmp = root; tmp != tail;) {
tmp = tmp->next;
destroyNode(tmp->prev);
deallocateNode(tmp->prev);
@@ -283,24 +181,12 @@ public:
markIteratorDirty();
_size = 0;
}
//Insert at the end
constexpr iterator add(const T &value)
{
return addInternal(value);
}
constexpr iterator add(T&& value)
{
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();
// Insert at the end
constexpr iterator add(const T& value) { return addInternal(value); }
constexpr iterator add(T&& value) { 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->next = nullptr;
tail->next = newTail;
@@ -311,31 +197,23 @@ public:
return insertedElement;
}
// front + popFront
constexpr value_type retrieve()
{
constexpr value_type retrieve() {
value_type temp = std::move(root->data);
popFront();
return temp;
}
constexpr iterator remove(iterator pos)
{
constexpr iterator remove(iterator pos) {
_size--;
Node *prev = pos.node->prev;
Node *next = pos.node->next;
if (prev == nullptr)
{
Node* prev = pos.node->prev;
Node* next = pos.node->next;
if (prev == nullptr) {
root = next;
}
else
{
} else {
prev->next = next;
}
if(next == nullptr)
{
if (next == nullptr) {
tail = prev;
}
else
{
} else {
next->prev = prev;
}
destroyNode(pos.node);
@@ -343,111 +221,67 @@ public:
markIteratorDirty();
return Iterator(next);
}
constexpr void popBack()
{
constexpr void popBack() {
assert(_size > 0);
remove(Iterator(tail->prev));
}
constexpr void pop_back()
{
constexpr void pop_back() {
assert(_size > 0);
remove(Iterator(tail->prev));
}
constexpr void popFront()
{
constexpr void popFront() {
assert(_size > 0);
remove(Iterator(root));
}
constexpr void pop_front()
{
constexpr void pop_front() {
assert(_size > 0);
remove(Iterator(root));
}
constexpr iterator insert(iterator pos, const T &value)
{
constexpr iterator insert(iterator pos, const T& value) {
_size++;
Node *newNode = allocateNode();
Node* newNode = allocateNode();
initializeNode(newNode, value);
newNode->next = pos.node;
pos.node->prev = newNode;
Node *tmp = pos.node->prev;
if (tmp != nullptr)
{
Node* tmp = pos.node->prev;
if (tmp != nullptr) {
tmp->next = newNode;
newNode->prev = tmp;
}
else
{
} else {
root = newNode;
}
markIteratorDirty();
return Iterator(newNode);
}
constexpr iterator find(const T &value)
{
for (Node *i = root; i != tail; i = i->next)
{
if (!(i->data < value) && !(value < i->data))
{
constexpr iterator find(const T& value) {
for (Node* i = root; i != tail; i = i->next) {
if (!(i->data < value) && !(value < i->data)) {
return iterator(i);
}
}
return endIt;
}
constexpr bool empty() const
{
return _size == 0;
}
constexpr size_type size() const
{
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;
}
constexpr bool empty() const { return _size == 0; }
constexpr size_type size() const { 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:
constexpr Node* allocateNode()
{
private:
constexpr Node* allocateNode() {
Node* node = allocator.allocate(1);
assert(node != nullptr);
node->prev = nullptr;
node->next = nullptr;
return node;
}
template<typename Type>
constexpr void initializeNode(Node* node, Type&& data)
{
std::allocator_traits<NodeAllocator>::construct(allocator,
node,
node->prev,
node->next,
std::forward<Type>(data));
template <typename Type> constexpr void initializeNode(Node* node, Type&& data) {
std::allocator_traits<NodeAllocator>::construct(allocator, node, node->prev, node->next, std::forward<Type>(data));
}
constexpr void destroyNode(Node* node)
{
std::allocator_traits<NodeAllocator>::destroy(allocator, node);
}
constexpr void deallocateNode(Node* node)
{
allocator.deallocate(node, 1);
}
template<typename ValueType>
constexpr iterator addInternal(ValueType&& value)
{
constexpr void destroyNode(Node* node) { std::allocator_traits<NodeAllocator>::destroy(allocator, node); }
constexpr void deallocateNode(Node* node) { allocator.deallocate(node, 1); }
template <typename ValueType> constexpr iterator addInternal(ValueType&& value) {
initializeNode(tail, std::forward<ValueType>(value));
Node* newTail = allocateNode();
newTail->prev = tail;
@@ -459,16 +293,15 @@ private:
_size++;
return insertedElement;
}
constexpr void markIteratorDirty()
{
constexpr void markIteratorDirty() {
beginIt = Iterator(root);
endIt = Iterator(tail);
cbeginIt = ConstIterator(root);
cendIt = ConstIterator(tail);
}
NodeAllocator allocator;
Node *root;
Node *tail;
Node* root;
Node* tail;
iterator beginIt;
iterator endIt;
const_iterator cbeginIt;
+27 -78
View File
@@ -1,26 +1,17 @@
#pragma once
#include <utility>
#include "Array.h"
#include "Pair.h"
#include "Tree.h"
#include "Serialization/Serialization.h"
#include "Tree.h"
#include <utility>
namespace Seele
{
template<typename KeyType, typename PairType>
struct _KeyFun
{
const KeyType& operator()(const PairType& pair) const
{
return pair.key;
}
namespace Seele {
template <typename KeyType, typename PairType> struct _KeyFun {
const KeyType& operator()(const PairType& pair) const { return pair.key; }
};
template <typename K,
typename V,
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>
{
template <typename K, typename V, 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 key_type = Super::key_type;
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 const_reverse_iterator = Super::const_reverse_iterator;
constexpr Map() noexcept
: Super()
{
}
constexpr Map() noexcept : Super() {}
constexpr explicit Map(const Compare& comp, const Allocator& alloc = Allocator()) noexcept(noexcept(Allocator()))
: Super(comp, alloc)
{
}
constexpr explicit Map(const Allocator& alloc) noexcept(noexcept(Compare()))
: Super(alloc)
{
}
constexpr mapped_type& operator[](const key_type& key)
{
: Super(comp, alloc) {}
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()));
return it->value;
}
constexpr const mapped_type& operator[](const key_type& key) const
{
return Super::find(key)->value;
}
constexpr mapped_type& at(const key_type& key)
{
constexpr const mapped_type& operator[](const key_type& key) const { return Super::find(key)->value; }
constexpr mapped_type& at(const key_type& key) {
iterator elem = Super::find(key);
if (elem == Super::end())
{
if (elem == Super::end()) {
throw std::logic_error("Key not found");
}
return elem->value;
}
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);
}
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 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
{
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); }
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 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();
buffer.writeBytes(&s, sizeof(uint64));
for(const auto& [k, v] : *this)
{
for (const auto& [k, v] : *this) {
Serialization::save(buffer, k);
Serialization::save(buffer, v);
}
}
void load(ArchiveBuffer& buffer)
{
void load(ArchiveBuffer& buffer) {
uint64 len = 0;
buffer.readBytes(&len, sizeof(uint64));
for(uint64 i = 0; i < len; ++i)
{
for (uint64 i = 0; i < len; ++i) {
K k = K();
V v = V();
Serialization::load(buffer, k);
+8 -21
View File
@@ -1,30 +1,17 @@
#pragma once
namespace Seele
{
template <typename K, typename V>
struct Pair
{
public:
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))
{
}
namespace Seele {
template <typename K, typename V> struct Pair {
public:
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(Pair&& other) = default;
~Pair(){}
~Pair() {}
Pair& operator=(const 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);
}
K key;
+10 -23
View File
@@ -1,14 +1,13 @@
#pragma once
#include <utility>
#include "Array.h"
#include "Tree.h"
#include <utility>
namespace Seele
{
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>
{
public:
namespace Seele {
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> {
public:
using Super = Tree<Key, Key, std::identity, Compare, Allocator>;
using key_type = Key;
using value_type = Key;
@@ -26,21 +25,9 @@ public:
using reverse_iterator = Super::reverse_iterator;
using const_reverse_iterator = Super::const_reverse_iterator;
Set()
: 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);
}
Set() : 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); }
};
} // namespace Seele
+103 -274
View File
@@ -1,39 +1,22 @@
#pragma once
#include <memory_resource>
#include "Pair.h"
#include <memory_resource>
namespace Seele
{
template <
typename KeyType,
typename NodeData,
typename KeyFun,
typename Compare,
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))
{}
namespace Seele {
template <typename KeyType, typename NodeData, typename KeyFun, typename Compare, 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* rightChild;
NodeData data;
};
using NodeAlloc = std::allocator_traits<Allocator>::template rebind_alloc<Node>;
public:
template<typename IterType>
class IteratorBase
{
public:
template <typename IterType> class IteratorBase {
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = IterType;
@@ -41,106 +24,64 @@ public:
using reference = IterType&;
using pointer = IterType*;
constexpr IteratorBase(Node* x = nullptr, Array<Node*>&& beginIt = Array<Node*>())
: 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)
{
if (this != &other)
{
constexpr IteratorBase(Node* x = nullptr, Array<Node*>&& beginIt = Array<Node*>()) : 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) {
if (this != &other) {
node = other.node;
traversal = other.traversal;
}
return *this;
}
constexpr IteratorBase& operator=(IteratorBase&& other) noexcept
{
if (this != &other)
{
constexpr IteratorBase& operator=(IteratorBase&& other) noexcept {
if (this != &other) {
node = std::move(other.node);
traversal = std::move(other.traversal);
}
return *this;
}
constexpr reference operator*() const
{
return node->data;
}
constexpr pointer operator->() const
{
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++()
{
constexpr reference operator*() const { return node->data; }
constexpr pointer operator->() const { 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;
while (node != nullptr
&& node->leftChild != nullptr)
{
while (node != nullptr && node->leftChild != nullptr) {
traversal.add(node);
node = node->leftChild;
}
if (node == nullptr
&& traversal.size() > 0)
{
if (node == nullptr && traversal.size() > 0) {
node = traversal.back();
traversal.pop();
}
return *this;
}
constexpr IteratorBase& operator--()
{
constexpr IteratorBase& operator--() {
node = node->leftChild;
while (node != nullptr
&& node->rightChild != nullptr)
{
while (node != nullptr && node->rightChild != nullptr) {
traversal.add(node);
node = node->rightchild;
}
if (node == nullptr
&& traversal.size() > 0)
{
if (node == nullptr && traversal.size() > 0) {
node = traversal.back();
traversal.pop();
}
return *this;
}
constexpr IteratorBase operator--(int)
{
constexpr IteratorBase operator--(int) {
IteratorBase tmp(*this);
--*this;
return tmp;
}
constexpr IteratorBase operator++(int)
{
constexpr IteratorBase operator++(int) {
IteratorBase tmp(*this);
++*this;
return tmp;
}
Node* getNode()
{
return node;
}
Node* getNode() { return node; }
private:
Node* node;
Array<Node*> traversal;
@@ -164,84 +105,39 @@ public:
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr Tree() noexcept
: alloc(NodeAlloc())
, root(nullptr)
, beginIt(nullptr)
, endIt(nullptr)
, iteratorsDirty(true)
, _size(0)
, comp(Compare())
{
}
: alloc(NodeAlloc()), 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()))
: alloc(alloc)
, root(nullptr)
, beginIt(nullptr)
, endIt(nullptr)
, iteratorsDirty(true)
, _size(0)
, comp(comp)
{
}
: alloc(alloc), root(nullptr), beginIt(nullptr), endIt(nullptr), iteratorsDirty(true), _size(0), comp(comp) {}
constexpr explicit Tree(const Allocator& alloc) noexcept(noexcept(Compare()))
: alloc(alloc)
, root(nullptr)
, beginIt(nullptr)
, 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)
{
: alloc(alloc), root(nullptr), beginIt(nullptr), 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);
}
}
constexpr Tree(Tree&& other) noexcept
: alloc(std::move(other.alloc))
, root(std::move(other.root))
, iteratorsDirty(true)
, _size(std::move(other._size))
, comp(std::move(other.comp))
{
: alloc(std::move(other.alloc)), root(std::move(other.root)), iteratorsDirty(true), _size(std::move(other._size)),
comp(std::move(other.comp)) {
other._size = 0;
}
constexpr ~Tree() noexcept
{
constexpr ~Tree() noexcept { clear(); }
constexpr Tree& operator=(const Tree& other) {
if (this != &other) {
clear();
}
constexpr Tree& operator=(const Tree& other)
{
if (this != &other)
{
clear();
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value)
{
if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
alloc = other.alloc;
}
for (const auto& elem : other)
{
for (const auto& elem : other) {
insert(elem);
}
markIteratorsDirty();
}
return *this;
}
constexpr Tree& operator=(Tree&& other) noexcept
{
if (this != &other)
{
constexpr Tree& operator=(Tree&& other) noexcept {
if (this != &other) {
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);
}
root = std::move(other.root);
@@ -252,144 +148,108 @@ public:
}
return *this;
}
constexpr void clear()
{
while (_size > 0)
{
constexpr void clear() {
while (_size > 0) {
root = _remove(root, keyFun(root->data));
}
root = nullptr;
markIteratorsDirty();
}
constexpr iterator begin()
{
if (iteratorsDirty)
{
constexpr iterator begin() {
if (iteratorsDirty) {
refreshIterators();
}
return beginIt;
}
constexpr iterator end()
{
if (iteratorsDirty)
{
constexpr iterator end() {
if (iteratorsDirty) {
refreshIterators();
}
return endIt;
}
constexpr iterator begin() const
{
if (iteratorsDirty)
{
constexpr iterator begin() const {
if (iteratorsDirty) {
return calcBeginIterator();
}
return beginIt;
}
constexpr iterator end() const
{
if (iteratorsDirty)
{
constexpr iterator end() const {
if (iteratorsDirty) {
return calcEndIterator();
}
return endIt;
}
constexpr bool empty() const
{
return _size == 0;
}
constexpr size_type size() const
{
return _size;
}
protected:
constexpr iterator find(const key_type& key)
{
constexpr bool empty() const { return _size == 0; }
constexpr size_type size() const { return _size; }
protected:
constexpr iterator find(const key_type& key) {
root = _splay(root, key);
if (root == nullptr || !equal(root->data, key))
{
if (root == nullptr || !equal(root->data, key)) {
return end();
}
return iterator(root);
}
constexpr iterator find(const key_type& key) const
{
constexpr iterator find(const key_type& key) const {
Node* it = root;
while (it != nullptr && !equal(it->data, key))
{
if (comp(key, keyFun(it->data)))
{
while (it != nullptr && !equal(it->data, key)) {
if (comp(key, keyFun(it->data))) {
it = it->leftChild;
}
else
{
} else {
it = it->rightChild;
}
}
if (it == nullptr)
{
if (it == nullptr) {
return end();
}
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);
root = r;
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));
root = r;
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);
return iterator(root);
}
private:
void verifyTree()
{
private:
void verifyTree() {
size_t numElems = 0;
for (const auto& it : *this)
{
for (const auto& it : *this) {
numElems++;
}
assert(numElems == _size);
}
void markIteratorsDirty()
{
iteratorsDirty = true;
}
void refreshIterators()
{
void markIteratorsDirty() { iteratorsDirty = true; }
void refreshIterators() {
beginIt = calcBeginIterator();
endIt = calcEndIterator();
iteratorsDirty = false;
}
constexpr Iterator calcBeginIterator() const
{
constexpr Iterator calcBeginIterator() const {
Node* begin = root;
Array<Node*> beginTraversal;
while (begin != nullptr)
{
while (begin != nullptr) {
beginTraversal.add(begin);
begin = begin->leftChild;
}
if (!beginTraversal.empty())
{
if (!beginTraversal.empty()) {
begin = beginTraversal.back();
beginTraversal.pop();
}
return Iterator(begin, std::move(beginTraversal));
}
constexpr Iterator calcEndIterator() const
{
constexpr Iterator calcEndIterator() const {
Node* endIndex = root;
Array<Node*> endTraversal;
while (endIndex != nullptr)
{
while (endIndex != nullptr) {
endTraversal.add(endIndex);
endIndex = endIndex->rightChild;
}
@@ -403,26 +263,21 @@ private:
size_type _size;
Compare comp;
KeyFun keyFun = KeyFun();
Node* rotateLeft(Node* x)
{
Node* rotateLeft(Node* x) {
Node* y = x->rightChild;
x->rightChild = y->leftChild;
y->leftChild = x;
return y;
}
Node* rotateRight(Node* x)
{
Node* rotateRight(Node* x) {
Node* y = x->leftChild;
x->leftChild = y->rightChild;
y->rightChild = x;
return y;
}
template<class NodeDataType>
Pair<Node*, bool> _insert(Node* r, NodeDataType&& data)
{
template <class NodeDataType> Pair<Node*, bool> _insert(Node* r, NodeDataType&& data) {
markIteratorsDirty();
if (r == nullptr)
{
if (r == nullptr) {
root = alloc.allocate(1);
std::allocator_traits<NodeAlloc>::construct(alloc, root, nullptr, nullptr, std::forward<NodeDataType>(data));
_size++;
@@ -436,14 +291,11 @@ private:
Node* newNode = alloc.allocate(1);
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->leftChild = r->leftChild;
r->leftChild = nullptr;
}
else
{
} else {
newNode->leftChild = r;
newNode->rightChild = r->rightChild;
r->rightChild = nullptr;
@@ -451,9 +303,7 @@ private:
_size++;
return Pair<Node*, bool>(newNode, true);
}
template<class K>
Node* _remove(Node* r, K&& key)
{
template <class K> Node* _remove(Node* r, K&& key) {
markIteratorsDirty();
Node* temp;
if (r == nullptr)
@@ -464,13 +314,10 @@ private:
if (!equal(r->data, key))
return r;
if (r->leftChild == nullptr)
{
if (r->leftChild == nullptr) {
temp = r;
r = r->rightChild;
}
else
{
} else {
temp = r;
r = _splay(r->leftChild, key);
@@ -481,52 +328,38 @@ private:
_size--;
return r;
}
template<class K>
Node* _splay(Node* r, K&& key)
{
template <class K> Node* _splay(Node* r, K&& key) {
markIteratorsDirty();
if (r == nullptr || equal(r->data, key))
{
if (r == nullptr || equal(r->data, key)) {
return r;
}
if (comp(key, keyFun(r->data)))
{
if (comp(key, keyFun(r->data))) {
if (r->leftChild == nullptr)
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 = 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);
if (r->leftChild->rightChild != nullptr)
{
if (r->leftChild->rightChild != nullptr) {
r->leftChild = rotateLeft(r->leftChild);
}
}
return (r->leftChild == nullptr) ? r : rotateRight(r);
}
else
{
} else {
if (r->rightChild == nullptr)
return r;
if (comp(key, keyFun(r->rightChild->data)))
{
if (comp(key, keyFun(r->rightChild->data))) {
r->rightChild->leftChild = _splay(r->rightChild->leftChild, key);
if (r->rightChild->leftChild != nullptr)
{
if (r->rightChild->leftChild != nullptr) {
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 = rotateLeft(r);
@@ -534,10 +367,6 @@ private:
return (r->rightChild == nullptr) ? r : rotateLeft(r);
}
}
template<typename K>
bool equal(const NodeData& a, K&& b) const
{
return !comp(keyFun(a), b) && !comp(b, keyFun(a));
}
template <typename K> bool equal(const NodeData& a, K&& b) const { return !comp(keyFun(a), b) && !comp(b, keyFun(a)); }
};
} // namespace Seele
+3 -5
View File
@@ -2,11 +2,9 @@
#include "Scene/Scene.h"
#include "System/SystemGraph.h"
namespace Seele
{
class Game
{
public:
namespace Seele {
class Game {
public:
Game() {}
virtual ~Game() {}
virtual void setupScene(PScene scene, PSystemGraph graph) = 0;
+11 -37
View File
@@ -3,31 +3,17 @@
using namespace Seele;
using namespace Seele::Gfx;
Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue)
: QueueOwnedResource(mapping, startQueue)
{
}
Buffer::Buffer(QueueFamilyMapping mapping, QueueType startQueue) : QueueOwnedResource(mapping, startQueue) {}
Buffer::~Buffer()
{
}
Buffer::~Buffer() {}
VertexBuffer::VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType)
: Buffer(mapping, startQueueType)
, numVertices(numVertices)
, vertexSize(vertexSize)
{
}
VertexBuffer::~VertexBuffer()
{
}
: Buffer(mapping, startQueueType), numVertices(numVertices), vertexSize(vertexSize) {}
VertexBuffer::~VertexBuffer() {}
IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType indexType, QueueType startQueueType)
: Buffer(mapping, startQueueType)
, indexType(indexType)
{
switch (indexType)
{
: Buffer(mapping, startQueueType), indexType(indexType) {
switch (indexType) {
case SE_INDEX_TYPE_UINT16:
numIndices = size / sizeof(uint16);
break;
@@ -38,25 +24,13 @@ IndexBuffer::IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexTy
break;
}
}
IndexBuffer::~IndexBuffer()
{
}
IndexBuffer::~IndexBuffer() {}
UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData)
: Buffer(mapping, sourceData.owner)
{}
UniformBuffer::UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData) : Buffer(mapping, sourceData.owner) {}
UniformBuffer::~UniformBuffer()
{
}
UniformBuffer::~UniformBuffer() {}
ShaderBuffer::ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& sourceData)
: Buffer(mapping, sourceData.owner)
, numElements(numElements)
{
}
ShaderBuffer::~ShaderBuffer()
{
}
: Buffer(mapping, sourceData.owner), numElements(numElements) {}
ShaderBuffer::~ShaderBuffer() {}
+25 -36
View File
@@ -1,37 +1,35 @@
#pragma once
#include "Resources.h"
#include "Initializer.h"
#include "Resources.h"
namespace Seele {
namespace Gfx {
class Buffer : public QueueOwnedResource {
public:
public:
Buffer(QueueFamilyMapping mapping, QueueType startQueueType);
virtual ~Buffer();
protected:
protected:
// Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
};
class VertexBuffer : public Buffer {
public:
VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices,
uint32 vertexSize, QueueType startQueueType);
public:
VertexBuffer(QueueFamilyMapping mapping, uint32 numVertices, uint32 vertexSize, QueueType startQueueType);
virtual ~VertexBuffer();
constexpr uint32 getNumVertices() const { return numVertices; }
// Size of one vertex in bytes
constexpr uint32 getVertexSize() const { return vertexSize; }
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
virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess,
SePipelineStageFlags srcStage,
SeAccessFlags dstAccess,
virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
uint32 numVertices;
uint32 vertexSize;
@@ -39,21 +37,18 @@ protected:
DEFINE_REF(VertexBuffer)
class IndexBuffer : public Buffer {
public:
IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index,
QueueType startQueueType);
public:
IndexBuffer(QueueFamilyMapping mapping, uint64 size, Gfx::SeIndexType index, QueueType startQueueType);
virtual ~IndexBuffer();
constexpr uint64 getNumIndices() const { return numIndices; }
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
virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess,
SePipelineStageFlags srcStage,
SeAccessFlags dstAccess,
virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
Gfx::SeIndexType indexType;
uint64 numIndices;
@@ -62,42 +57,36 @@ DEFINE_REF(IndexBuffer)
DECLARE_REF(UniformBuffer)
class UniformBuffer : public Buffer {
public:
UniformBuffer(QueueFamilyMapping mapping, const DataSource &sourceData);
public:
UniformBuffer(QueueFamilyMapping mapping, const DataSource& sourceData);
virtual ~UniformBuffer();
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
virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess,
SePipelineStageFlags srcStage,
SeAccessFlags dstAccess,
virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
};
DEFINE_REF(UniformBuffer)
class ShaderBuffer : public Buffer {
public:
ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements,
const DataSource &bulkResourceData);
public:
ShaderBuffer(QueueFamilyMapping mapping, uint32 numElements, const DataSource& bulkResourceData);
virtual ~ShaderBuffer();
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; }
virtual void *mapRegion(uint64 offset = 0, uint64 size = -1,
bool writeOnly = true) = 0;
virtual void* mapRegion(uint64 offset = 0, uint64 size = -1, bool writeOnly = true) = 0;
virtual void unmap() = 0;
virtual void clear() = 0;
protected:
protected:
// Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(QueueType newOwner) = 0;
virtual void executePipelineBarrier(SeAccessFlags srcAccess,
SePipelineStageFlags srcStage,
SeAccessFlags dstAccess,
virtual void executePipelineBarrier(SeAccessFlags srcAccess, SePipelineStageFlags srcStage, SeAccessFlags dstAccess,
SePipelineStageFlags dstStage) = 0;
uint32 numElements;
+4 -13
View File
@@ -3,19 +3,10 @@
using namespace Seele;
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
#include "Enums.h"
#include "Descriptor.h"
#include "Enums.h"
namespace Seele
{
namespace Gfx
{
namespace Seele {
namespace Gfx {
DECLARE_REF(Viewport)
class RenderCommand
{
public:
class RenderCommand {
public:
RenderCommand();
virtual ~RenderCommand();
virtual void setViewport(Gfx::PViewport viewport) = 0;
@@ -26,9 +24,8 @@ public:
std::string name;
};
DEFINE_REF(RenderCommand)
class ComputeCommand
{
public:
class ComputeCommand {
public:
ComputeCommand();
virtual ~ComputeCommand();
virtual void bindPipeline(Gfx::PComputePipeline pipeline) = 0;
@@ -40,5 +37,5 @@ public:
};
DEFINE_REF(ComputeCommand)
}
}
} // namespace Gfx
} // namespace Seele
+4 -5
View File
@@ -1,11 +1,10 @@
#pragma once
#include "Math/Vector.h"
#include "Containers/Array.h"
#include "Math/Vector.h"
namespace Seele
{
struct DebugVertex
{
namespace Seele {
struct DebugVertex {
Vector position;
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, PPipelineLayout baseLayout) : name(name){
PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayout) : name(name) {
if (baseLayout != nullptr) {
descriptorSetLayouts = baseLayout->descriptorSetLayouts;
pushConstants = baseLayout->pushConstants;
@@ -54,18 +54,13 @@ PipelineLayout::PipelineLayout(const std::string& name, PPipelineLayout baseLayo
PipelineLayout::~PipelineLayout() {}
void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) {
descriptorSetLayouts[layout->getName()] = layout;
}
void PipelineLayout::addDescriptorLayout(PDescriptorLayout layout) { descriptorSetLayouts[layout->getName()] = layout; }
void PipelineLayout::addPushConstants(const SePushConstantRange& pushConstant) { pushConstants.add(pushConstant); }
void PipelineLayout::addMapping(Map<std::string, uint32> mapping)
{
for(const auto& [name, index] : mapping)
{
if(parameterMapping.contains(name))
{
void PipelineLayout::addMapping(Map<std::string, uint32> mapping) {
for (const auto& [name, index] : mapping) {
if (parameterMapping.contains(name)) {
assert(parameterMapping[name] == index);
}
parameterMapping[name] = index;
+23 -31
View File
@@ -1,7 +1,8 @@
#pragma once
#include "Enums.h"
#include "Resources.h"
#include "Initializer.h"
#include "Resources.h"
namespace Seele {
namespace Gfx {
@@ -18,22 +19,20 @@ struct DescriptorBinding {
DECLARE_REF(DescriptorPool)
DECLARE_REF(DescriptorSet)
class DescriptorLayout {
public:
DescriptorLayout(const std::string &name);
DescriptorLayout(const DescriptorLayout &other);
DescriptorLayout &operator=(const DescriptorLayout &other);
public:
DescriptorLayout(const std::string& name);
DescriptorLayout(const DescriptorLayout& other);
DescriptorLayout& operator=(const DescriptorLayout& other);
virtual ~DescriptorLayout();
void addDescriptorBinding(DescriptorBinding binding);
void reset();
PDescriptorSet allocateDescriptorSet();
virtual void create() = 0;
constexpr const Array<DescriptorBinding> &getBindings() const {
return descriptorBindings;
}
constexpr const Array<DescriptorBinding>& getBindings() const { return descriptorBindings; }
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;
ODescriptorPool pool;
std::string name;
@@ -45,7 +44,7 @@ DEFINE_REF(DescriptorLayout)
DECLARE_REF(DescriptorSet)
class DescriptorPool {
public:
public:
DescriptorPool();
virtual ~DescriptorPool();
virtual PDescriptorSet allocateDescriptorSet() = 0;
@@ -57,49 +56,42 @@ DECLARE_REF(ShaderBuffer)
DECLARE_REF(Texture)
DECLARE_REF(Sampler)
class DescriptorSet {
public:
public:
DescriptorSet(PDescriptorLayout layout);
virtual ~DescriptorSet();
virtual void writeChanges() = 0;
virtual void updateBuffer(uint32 binding, PUniformBuffer uniformBuffer) = 0;
virtual void updateBuffer(uint32 binding, PShaderBuffer ShaderBuffer) = 0;
virtual void updateBuffer(uint32_t binding, uint32 index,
Gfx::PShaderBuffer uniformBuffer) = 0;
virtual void updateBuffer(uint32_t binding, uint32 index, Gfx::PShaderBuffer uniformBuffer) = 0;
virtual void updateSampler(uint32 binding, PSampler sampler) = 0;
virtual void updateTexture(uint32 binding, PTexture texture,
PSampler samplerState = nullptr) = 0;
virtual void updateTextureArray(uint32_t binding,
Array<PTexture> texture) = 0;
virtual void updateTexture(uint32 binding, PTexture texture, PSampler samplerState = nullptr) = 0;
virtual void updateTextureArray(uint32_t binding, Array<PTexture> texture) = 0;
bool operator<(PDescriptorSet other);
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;
};
DEFINE_REF(DescriptorSet)
DECLARE_REF(PipelineLayout)
class PipelineLayout {
public:
PipelineLayout(const std::string &name);
PipelineLayout(const std::string &name, PPipelineLayout baseLayout);
public:
PipelineLayout(const std::string& name);
PipelineLayout(const std::string& name, PPipelineLayout baseLayout);
virtual ~PipelineLayout();
virtual void create() = 0;
void addDescriptorLayout(PDescriptorLayout layout);
void addPushConstants(const SePushConstantRange &pushConstants);
void addPushConstants(const SePushConstantRange& pushConstants);
constexpr uint32 getHash() const { return layoutHash; }
constexpr const Map<std::string, PDescriptorLayout> &getLayouts() const {
return descriptorSetLayouts;
}
constexpr uint32 findParameter(const std::string &param) const {
return parameterMapping[param];
}
constexpr const Map<std::string, PDescriptorLayout>& getLayouts() const { return descriptorSetLayouts; }
constexpr uint32 findParameter(const std::string& param) const { return parameterMapping[param]; }
void addMapping(Map<std::string, uint32> mapping);
constexpr std::string getName() const { return name; };
protected:
protected:
uint32 layoutHash = 0;
Map<std::string, PDescriptorLayout> descriptorSetLayouts;
Map<std::string, uint32> parameterMapping;
+8 -9
View File
@@ -4,9 +4,8 @@
using namespace Seele;
using namespace Seele::Gfx;
FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format)
{
switch(format) {
FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format) {
switch (format) {
case SE_FORMAT_R4G4_UNORM_PACK8:
case SE_FORMAT_R8_UNORM:
case SE_FORMAT_R8_SNORM:
@@ -15,15 +14,15 @@ FormatCompatibilityInfo Gfx::getFormatInfo(SeFormat format)
case SE_FORMAT_R8_UINT:
case SE_FORMAT_R8_SINT:
case SE_FORMAT_R8_SRGB:
return FormatCompatibilityInfo {
return FormatCompatibilityInfo{
.blockSize = 1,
.blockExtent = UVector(1, 1, 1),
.texelsPerBlock = 1,
};
case SE_FORMAT_R10X6_UNORM_PACK16:
case SE_FORMAT_R12X4_UNORM_PACK16:
//case SE_FORMAT_A4R4G4B4_UNORM_PACK16:
//case SE_FORMAT_A4B4G4R4_UNORM_PACK16:
// case SE_FORMAT_A4R4G4B4_UNORM_PACK16:
// case SE_FORMAT_A4B4G4R4_UNORM_PACK16:
case SE_FORMAT_R4G4B4A4_UNORM_PACK16:
case SE_FORMAT_B4G4R4A4_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_SINT:
case SE_FORMAT_R16_SFLOAT:
return FormatCompatibilityInfo {
return FormatCompatibilityInfo{
.blockSize = 2,
.blockExtent = UVector(1, 1, 1),
.texelsPerBlock = 1,
};
case SE_FORMAT_BC7_UNORM_BLOCK:
case SE_FORMAT_BC7_SRGB_BLOCK:
return FormatCompatibilityInfo {
return FormatCompatibilityInfo{
.blockSize = 16,
.blockExtent = UVector(4, 4, 1),
.texelsPerBlock = 16,
};
case SE_FORMAT_R10X6G10X6_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_SNORM:
case SE_FORMAT_R8G8B8A8_USCALED:
+93 -182
View File
@@ -1,12 +1,11 @@
#pragma once
#include "MinimalEngine.h"
#include "Math/Vector.h"
#include "MinimalEngine.h"
namespace Seele
{
namespace Seele {
// Input codes matching GLFW for convenience, since its the primary windowing system
enum class KeyCode : size_t
{
enum class KeyCode : size_t {
/* Printable keys */
KEY_SPACE = 32,
KEY_APOSTROPHE = 39 /* ' */,
@@ -132,8 +131,7 @@ enum class KeyCode : size_t
KEY_LAST = KEY_MENU
};
enum class MouseButton
{
enum class MouseButton {
MOUSE_BUTTON_1 = 0,
MOUSE_BUTTON_2 = 1,
MOUSE_BUTTON_3 = 2,
@@ -144,15 +142,9 @@ enum class MouseButton
MOUSE_BUTTON_8 = 7,
};
enum class InputAction
{
RELEASE = 0,
PRESS = 1,
REPEAT = 2
};
enum class InputAction { RELEASE = 0, PRESS = 1, REPEAT = 2 };
enum class KeyModifier : uint32
{
enum class KeyModifier : uint32 {
MOD_SHIFT = 0x0001,
MOD_CONTROL = 0x0002,
MOD_ALT = 0x0004,
@@ -162,8 +154,7 @@ enum class KeyModifier : uint32
};
typedef uint32 KeyModifierFlags;
namespace Gfx
{
namespace Gfx {
static constexpr bool useAsyncCompute = false;
static constexpr bool useMeshShading = true;
static constexpr uint32 numFramesBuffered = 3;
@@ -174,8 +165,7 @@ static constexpr uint32 numPrimitivesPerMeshlet = 256;
double getCurrentFrameDelta();
uint32 getCurrentFrameIndex();
enum class QueueType
{
enum class QueueType {
GRAPHICS = 1,
COMPUTE = 2,
TRANSFER = 3,
@@ -185,8 +175,7 @@ typedef uint32_t SeFlags;
typedef uint32_t SeBool32;
typedef uint64_t SeDeviceSize;
typedef uint32_t SeSampleMask;
typedef enum SeResult
{
typedef enum SeResult {
SE_SUCCESS = 0,
SE_NOT_READY = 1,
SE_TIMEOUT = 2,
@@ -221,8 +210,7 @@ typedef enum SeResult
SE_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT = -1000255000,
} SeResult;
typedef enum SeStructureType
{
typedef enum SeStructureType {
SE_STRUCTURE_TYPE_APPLICATION_INFO = 0,
SE_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1,
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,
} SeStructureType;
typedef enum SeSystemAllocationScope
{
typedef enum SeSystemAllocationScope {
SE_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0,
SE_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1,
SE_SYSTEM_ALLOCATION_SCOPE_CACHE = 2,
@@ -607,13 +594,11 @@ typedef enum SeSystemAllocationScope
SE_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4,
} SeSystemAllocationScope;
typedef enum SeInternalAllocationType
{
typedef enum SeInternalAllocationType {
SE_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0,
} SeInternalAllocationType;
typedef enum SeFormat
{
typedef enum SeFormat {
SE_FORMAT_UNDEFINED = 0,
SE_FORMAT_R4G4_UNORM_PACK8 = 1,
SE_FORMAT_R4G4B4A4_UNORM_PACK16 = 2,
@@ -857,8 +842,7 @@ typedef enum SeFormat
SE_FORMAT_ASTC_12x12_SFLOAT_BLOCK = 1000066013,
} SeFormat;
struct FormatCompatibilityInfo
{
struct FormatCompatibilityInfo {
// std::string class
uint32 blockSize;
UVector blockExtent;
@@ -867,21 +851,18 @@ struct FormatCompatibilityInfo
FormatCompatibilityInfo getFormatInfo(SeFormat format);
typedef enum SeImageType
{
typedef enum SeImageType {
SE_IMAGE_TYPE_1D = 0,
SE_IMAGE_TYPE_2D = 1,
SE_IMAGE_TYPE_3D = 2,
} SeImageType;
typedef enum SeImageTiling
{
typedef enum SeImageTiling {
SE_IMAGE_TILING_OPTIMAL = 0,
SE_IMAGE_TILING_LINEAR = 1,
} SeImageTiling;
typedef enum SePhysicalDeviceType
{
typedef enum SePhysicalDeviceType {
SE_PHYSICAL_DEVICE_TYPE_OTHER = 0,
SE_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1,
SE_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2,
@@ -889,8 +870,7 @@ typedef enum SePhysicalDeviceType
SE_PHYSICAL_DEVICE_TYPE_CPU = 4,
} SePhysicalDeviceType;
typedef enum SeQueryType
{
typedef enum SeQueryType {
SE_QUERY_TYPE_OCCLUSION = 0,
SE_QUERY_TYPE_PIPELINE_STATISTICS = 1,
SE_QUERY_TYPE_TIMESTAMP = 2,
@@ -899,14 +879,12 @@ typedef enum SeQueryType
SE_QUERY_TYPE_PERFORMANCE_QUERY_INTEL = 1000210000,
} SeQueryType;
typedef enum SeSharingMode
{
typedef enum SeSharingMode {
SE_SHARING_MODE_EXCLUSIVE = 0,
SE_SHARING_MODE_CONCURRENT = 1,
} SeSharingMode;
typedef enum SeImageLayout
{
typedef enum SeImageLayout {
SE_IMAGE_LAYOUT_UNDEFINED = 0,
SE_IMAGE_LAYOUT_GENERAL = 1,
SE_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2,
@@ -924,8 +902,7 @@ typedef enum SeImageLayout
SE_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000,
} SeImageLayout;
typedef enum SeImageViewType
{
typedef enum SeImageViewType {
SE_IMAGE_VIEW_TYPE_1D = 0,
SE_IMAGE_VIEW_TYPE_2D = 1,
SE_IMAGE_VIEW_TYPE_3D = 2,
@@ -935,8 +912,7 @@ typedef enum SeImageViewType
SE_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6,
} SeImageViewType;
typedef enum SeComponentSwizzle
{
typedef enum SeComponentSwizzle {
SE_COMPONENT_SWIZZLE_IDENTITY = 0,
SE_COMPONENT_SWIZZLE_ZERO = 1,
SE_COMPONENT_SWIZZLE_ONE = 2,
@@ -946,14 +922,12 @@ typedef enum SeComponentSwizzle
SE_COMPONENT_SWIZZLE_A = 6,
} SeComponentSwizzle;
typedef enum SeVertexInputRate
{
typedef enum SeVertexInputRate {
SE_VERTEX_INPUT_RATE_VERTEX = 0,
SE_VERTEX_INPUT_RATE_INSTANCE = 1,
} SeVertexInputRate;
typedef enum SePrimitiveTopology
{
typedef enum SePrimitiveTopology {
SE_PRIMITIVE_TOPOLOGY_POINT_LIST = 0,
SE_PRIMITIVE_TOPOLOGY_LINE_LIST = 1,
SE_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2,
@@ -967,22 +941,19 @@ typedef enum SePrimitiveTopology
SE_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10,
} SePrimitiveTopology;
typedef enum SePolygonMode
{
typedef enum SePolygonMode {
SE_POLYGON_MODE_FILL = 0,
SE_POLYGON_MODE_LINE = 1,
SE_POLYGON_MODE_POINT = 2,
SE_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000,
} SePolygonMode;
typedef enum SeFrontFace
{
typedef enum SeFrontFace {
SE_FRONT_FACE_COUNTER_CLOCKWISE = 0,
SE_FRONT_FACE_CLOCKWISE = 1,
} SeFrontFace;
typedef enum SeCompareOp
{
typedef enum SeCompareOp {
SE_COMPARE_OP_NEVER = 0,
SE_COMPARE_OP_LESS = 1,
SE_COMPARE_OP_EQUAL = 2,
@@ -993,8 +964,7 @@ typedef enum SeCompareOp
SE_COMPARE_OP_ALWAYS = 7,
} SeCompareOp;
typedef enum SeStencilOp
{
typedef enum SeStencilOp {
SE_STENCIL_OP_KEEP = 0,
SE_STENCIL_OP_ZERO = 1,
SE_STENCIL_OP_REPLACE = 2,
@@ -1005,8 +975,7 @@ typedef enum SeStencilOp
SE_STENCIL_OP_DECREMENT_AND_WRAP = 7,
} SeStencilOp;
typedef enum SeLogicOp
{
typedef enum SeLogicOp {
SE_LOGIC_OP_CLEAR = 0,
SE_LOGIC_OP_AND = 1,
SE_LOGIC_OP_AND_REVERSE = 2,
@@ -1025,8 +994,7 @@ typedef enum SeLogicOp
SE_LOGIC_OP_SET = 15,
} SeLogicOp;
typedef enum SeBlendFactor
{
typedef enum SeBlendFactor {
SE_BLEND_FACTOR_ZERO = 0,
SE_BLEND_FACTOR_ONE = 1,
SE_BLEND_FACTOR_SRC_COLOR = 2,
@@ -1048,8 +1016,7 @@ typedef enum SeBlendFactor
SE_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18,
} SeBlendFactor;
typedef enum SeBlendOp
{
typedef enum SeBlendOp {
SE_BLEND_OP_ADD = 0,
SE_BLEND_OP_SUBTRACT = 1,
SE_BLEND_OP_REVERSE_SUBTRACT = 2,
@@ -1103,8 +1070,7 @@ typedef enum SeBlendOp
SE_BLEND_OP_BLUE_EXT = 1000148045,
} SeBlendOp;
typedef enum SeDynamicState
{
typedef enum SeDynamicState {
SE_DYNAMIC_STATE_VIEWPORT = 0,
SE_DYNAMIC_STATE_SCISSOR = 1,
SE_DYNAMIC_STATE_LINE_WIDTH = 2,
@@ -1123,21 +1089,18 @@ typedef enum SeDynamicState
SE_DYNAMIC_STATE_LINE_STIPPLE_EXT = 1000259000,
} SeDynamicState;
typedef enum SeFilter
{
typedef enum SeFilter {
SE_FILTER_NEAREST = 0,
SE_FILTER_LINEAR = 1,
SE_FILTER_CUBIC_IMG = 1000015000,
} SeFilter;
typedef enum SeSamplerMipmapMode
{
typedef enum SeSamplerMipmapMode {
SE_SAMPLER_MIPMAP_MODE_NEAREST = 0,
SE_SAMPLER_MIPMAP_MODE_LINEAR = 1,
} SeSamplerMipmapMode;
typedef enum SeSamplerAddressMode
{
typedef enum SeSamplerAddressMode {
SE_SAMPLER_ADDRESS_MODE_REPEAT = 0,
SE_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1,
SE_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2,
@@ -1145,8 +1108,7 @@ typedef enum SeSamplerAddressMode
SE_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4,
} SeSamplerAddressMode;
typedef enum SeBorderColor
{
typedef enum SeBorderColor {
SE_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0,
SE_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1,
SE_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2,
@@ -1155,8 +1117,7 @@ typedef enum SeBorderColor
SE_BORDER_COLOR_INT_OPAQUE_WHITE = 5,
} SeBorderColor;
typedef enum SeDescriptorType
{
typedef enum SeDescriptorType {
SE_DESCRIPTOR_TYPE_SAMPLER = 0,
SE_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1,
SE_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2,
@@ -1180,47 +1141,40 @@ typedef enum SeDescriptorBindingFlagBits {
} SeDescriptorBindingFlagBits;
typedef SeFlags SeDescriptorBindingFlags;
typedef enum SeAttachmentLoadOp
{
typedef enum SeAttachmentLoadOp {
SE_ATTACHMENT_LOAD_OP_LOAD = 0,
SE_ATTACHMENT_LOAD_OP_CLEAR = 1,
SE_ATTACHMENT_LOAD_OP_DONT_CARE = 2,
} SeAttachmentLoadOp;
typedef enum SeAttachmentStoreOp
{
typedef enum SeAttachmentStoreOp {
SE_ATTACHMENT_STORE_OP_STORE = 0,
SE_ATTACHMENT_STORE_OP_DONT_CARE = 1,
} SeAttachmentStoreOp;
typedef enum SePipelineBindPoint
{
typedef enum SePipelineBindPoint {
SE_PIPELINE_BIND_POINT_GRAPHICS = 0,
SE_PIPELINE_BIND_POINT_COMPUTE = 1,
SE_PIPELINE_BIND_POINT_RAY_TRACING_NV = 1000165000,
} SePipelineBindPoint;
typedef enum SeCommandBufferLevel
{
typedef enum SeCommandBufferLevel {
SE_COMMAND_BUFFER_LEVEL_PRIMARY = 0,
SE_COMMAND_BUFFER_LEVEL_SECONDARY = 1,
} SeCommandBufferLevel;
typedef enum SeIndexType
{
typedef enum SeIndexType {
SE_INDEX_TYPE_UINT16 = 0,
SE_INDEX_TYPE_UINT32 = 1,
SE_INDEX_TYPE_NONE_NV = 1000165000,
SE_INDEX_TYPE_UINT8_EXT = 1000265000,
} SeIndexType;
typedef enum SeSubpassContents
{
typedef enum SeSubpassContents {
SE_SUBPASS_CONTENTS_INLINE = 0,
} SeSubpassContents;
typedef enum SeObjectType
{
typedef enum SeObjectType {
SE_OBJECT_TYPE_UNKNOWN = 0,
SE_OBJECT_TYPE_INSTANCE = 1,
SE_OBJECT_TYPE_PHYSICAL_DEVICE = 2,
@@ -1262,16 +1216,14 @@ typedef enum SeObjectType
SE_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL = 1000210000,
} SeObjectType;
typedef enum SeVendorId
{
typedef enum SeVendorId {
SE_VENDOR_ID_VIV = 0x10001,
SE_VENDOR_ID_VSI = 0x10002,
SE_VENDOR_ID_KAZAN = 0x10003,
} SeVendorId;
typedef SeFlags SeInstanceCreateFlags;
typedef enum SeFormatFeatureFlagBits
{
typedef enum SeFormatFeatureFlagBits {
SE_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001,
SE_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002,
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_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_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_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR = 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_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_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR =
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_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,
@@ -1311,8 +1267,7 @@ typedef enum SeFormatFeatureFlagBits
} SeFormatFeatureFlagBits;
typedef SeFlags SeFormatFeatureFlags;
typedef enum SeImageUsageFlagBits
{
typedef enum SeImageUsageFlagBits {
SE_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001,
SE_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002,
SE_IMAGE_USAGE_SAMPLED_BIT = 0x00000004,
@@ -1327,8 +1282,7 @@ typedef enum SeImageUsageFlagBits
} SeImageUsageFlagBits;
typedef SeFlags SeImageUsageFlags;
typedef enum SeImageCreateFlagBits
{
typedef enum SeImageCreateFlagBits {
SE_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001,
SE_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
SE_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
@@ -1354,8 +1308,7 @@ typedef enum SeImageCreateFlagBits
} SeImageCreateFlagBits;
typedef SeFlags SeImageCreateFlags;
typedef enum SeSampleCountFlagBits
{
typedef enum SeSampleCountFlagBits {
SE_SAMPLE_COUNT_1_BIT = 0x00000001,
SE_SAMPLE_COUNT_2_BIT = 0x00000002,
SE_SAMPLE_COUNT_4_BIT = 0x00000004,
@@ -1367,8 +1320,7 @@ typedef enum SeSampleCountFlagBits
} SeSampleCountFlagBits;
typedef SeFlags SeSampleCountFlags;
typedef enum SeQueueFlagBits
{
typedef enum SeQueueFlagBits {
SE_QUEUE_GRAPHICS_BIT = 0x00000001,
SE_QUEUE_COMPUTE_BIT = 0x00000002,
SE_QUEUE_TRANSFER_BIT = 0x00000004,
@@ -1378,8 +1330,7 @@ typedef enum SeQueueFlagBits
} SeQueueFlagBits;
typedef SeFlags SeQueueFlags;
typedef enum SeMemoryPropertyFlagBits
{
typedef enum SeMemoryPropertyFlagBits {
SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001,
SE_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002,
SE_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004,
@@ -1392,8 +1343,7 @@ typedef enum SeMemoryPropertyFlagBits
} SeMemoryPropertyFlagBits;
typedef SeFlags SeMemoryPropertyFlags;
typedef enum SeMemoryHeapFlagBits
{
typedef enum SeMemoryHeapFlagBits {
SE_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001,
SE_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002,
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 SeDeviceCreateFlags;
typedef enum SeDeviceQueueCreateFlagBits
{
typedef enum SeDeviceQueueCreateFlagBits {
SE_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x00000001,
SE_DEVICE_QUEUE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeDeviceQueueCreateFlagBits;
typedef SeFlags SeDeviceQueueCreateFlags;
typedef enum SePipelineStageFlagBits
{
typedef enum SePipelineStageFlagBits {
SE_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001,
SE_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002,
SE_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004,
@@ -1443,8 +1391,7 @@ typedef enum SePipelineStageFlagBits
typedef SeFlags SePipelineStageFlags;
typedef SeFlags SeMemoryMapFlags;
typedef enum SeImageAspectFlagBits
{
typedef enum SeImageAspectFlagBits {
SE_IMAGE_ASPECT_COLOR_BIT = 0x00000001,
SE_IMAGE_ASPECT_DEPTH_BIT = 0x00000002,
SE_IMAGE_ASPECT_STENCIL_BIT = 0x00000004,
@@ -1463,8 +1410,7 @@ typedef enum SeImageAspectFlagBits
} SeImageAspectFlagBits;
typedef SeFlags SeImageAspectFlags;
typedef enum SeSparseImageFormatFlagBits
{
typedef enum SeSparseImageFormatFlagBits {
SE_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001,
SE_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002,
SE_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004,
@@ -1472,15 +1418,13 @@ typedef enum SeSparseImageFormatFlagBits
} SeSparseImageFormatFlagBits;
typedef SeFlags SeSparseImageFormatFlags;
typedef enum SeSparseMemoryBindFlagBits
{
typedef enum SeSparseMemoryBindFlagBits {
SE_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001,
SE_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSparseMemoryBindFlagBits;
typedef SeFlags SeSparseMemoryBindFlags;
typedef enum SeFenceCreateFlagBits
{
typedef enum SeFenceCreateFlagBits {
SE_FENCE_CREATE_SIGNALED_BIT = 0x00000001,
SE_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeFenceCreateFlagBits;
@@ -1489,8 +1433,7 @@ typedef SeFlags SeSemaphoreCreateFlags;
typedef SeFlags SeEventCreateFlags;
typedef SeFlags SeQueryPoolCreateFlags;
typedef enum SeQueryPipelineStatisticFlagBits
{
typedef enum SeQueryPipelineStatisticFlagBits {
SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001,
SE_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002,
SE_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004,
@@ -1506,8 +1449,7 @@ typedef enum SeQueryPipelineStatisticFlagBits
} SeQueryPipelineStatisticFlagBits;
typedef SeFlags SeQueryPipelineStatisticFlags;
typedef enum SeQueryResultFlagBits
{
typedef enum SeQueryResultFlagBits {
SE_QUERY_RESULT_64_BIT = 0x00000001,
SE_QUERY_RESULT_WAIT_BIT = 0x00000002,
SE_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004,
@@ -1516,8 +1458,7 @@ typedef enum SeQueryResultFlagBits
} SeQueryResultFlagBits;
typedef SeFlags SeQueryResultFlags;
typedef enum SeBufferCreateFlagBits
{
typedef enum SeBufferCreateFlagBits {
SE_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001,
SE_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002,
SE_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004,
@@ -1527,8 +1468,7 @@ typedef enum SeBufferCreateFlagBits
} SeBufferCreateFlagBits;
typedef SeFlags SeBufferCreateFlags;
typedef enum SeBufferUsageFlagBits
{
typedef enum SeBufferUsageFlagBits {
SE_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001,
SE_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002,
SE_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004,
@@ -1548,22 +1488,17 @@ typedef enum SeBufferUsageFlagBits
typedef SeFlags SeBufferUsageFlags;
typedef SeFlags SeBufferViewCreateFlags;
typedef enum SeImageViewCreateFlagBits
{
typedef enum SeImageViewCreateFlagBits {
SE_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001,
SE_IMAGE_VIEW_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeImageViewCreateFlagBits;
typedef SeFlags SeImageViewCreateFlags;
typedef enum SeShaderModuleCreateFlagBits
{
SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeShaderModuleCreateFlagBits;
typedef enum SeShaderModuleCreateFlagBits { SE_SHADER_MODULE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeShaderModuleCreateFlagBits;
typedef SeFlags SeShaderModuleCreateFlags;
typedef SeFlags SePipelineCacheCreateFlags;
typedef enum SePipelineCreateFlagBits
{
typedef enum SePipelineCreateFlagBits {
SE_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001,
SE_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002,
SE_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004,
@@ -1578,16 +1513,14 @@ typedef enum SePipelineCreateFlagBits
} SePipelineCreateFlagBits;
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_REQUIRE_FULL_SUBGROUPS_BIT_EXT = 0x00000002,
SE_PIPELINE_SHADER_STAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SePipelineShaderStageCreateFlagBits;
typedef SeFlags SePipelineShaderStageCreateFlags;
typedef enum SeShaderStageFlagBits
{
typedef enum SeShaderStageFlagBits {
SE_SHADER_STAGE_VERTEX_BIT = 0x00000001,
SE_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002,
SE_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004,
@@ -1613,8 +1546,7 @@ typedef SeFlags SePipelineTessellationStateCreateFlags;
typedef SeFlags SePipelineViewportStateCreateFlags;
typedef SeFlags SePipelineRasterizationStateCreateFlags;
typedef enum SeCullModeFlagBits
{
typedef enum SeCullModeFlagBits {
SE_CULL_MODE_NONE = 0,
SE_CULL_MODE_FRONT_BIT = 0x00000001,
SE_CULL_MODE_BACK_BIT = 0x00000002,
@@ -1626,8 +1558,7 @@ typedef SeFlags SePipelineMultisampleStateCreateFlags;
typedef SeFlags SePipelineDepthStencilStateCreateFlags;
typedef SeFlags SePipelineColorBlendStateCreateFlags;
typedef enum SeColorComponentFlagBits
{
typedef enum SeColorComponentFlagBits {
SE_COLOR_COMPONENT_R_BIT = 0x00000001,
SE_COLOR_COMPONENT_G_BIT = 0x00000002,
SE_COLOR_COMPONENT_B_BIT = 0x00000004,
@@ -1639,24 +1570,21 @@ typedef SeFlags SePipelineDynamicStateCreateFlags;
typedef SeFlags SePipelineLayoutCreateFlags;
typedef SeFlags SeShaderStageFlags;
typedef enum SeSamplerCreateFlagBits
{
typedef enum SeSamplerCreateFlagBits {
SE_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001,
SE_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002,
SE_SAMPLER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSamplerCreateFlagBits;
typedef SeFlags SeSamplerCreateFlags;
typedef enum SeDescriptorSetLayoutCreateFlagBits
{
typedef enum SeDescriptorSetLayoutCreateFlagBits {
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_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeDescriptorSetLayoutCreateFlagBits;
typedef SeFlags SeDescriptorSetLayoutCreateFlags;
typedef enum SeDescriptorPoolCreateFlagBits
{
typedef enum SeDescriptorPoolCreateFlagBits {
SE_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001,
SE_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT = 0x00000002,
SE_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
@@ -1664,36 +1592,29 @@ typedef enum SeDescriptorPoolCreateFlagBits
typedef SeFlags SeDescriptorPoolCreateFlags;
typedef SeFlags SeDescriptorPoolResetFlags;
typedef enum SeFramebufferCreateFlagBits
{
typedef enum SeFramebufferCreateFlagBits {
SE_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR = 0x00000001,
SE_FRAMEBUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeFramebufferCreateFlagBits;
typedef SeFlags SeFramebufferCreateFlags;
typedef enum SeRenderPassCreateFlagBits
{
SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeRenderPassCreateFlagBits;
typedef enum SeRenderPassCreateFlagBits { SE_RENDER_PASS_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF } SeRenderPassCreateFlagBits;
typedef SeFlags SeRenderPassCreateFlags;
typedef enum SeAttachmentDescriptionFlagBits
{
typedef enum SeAttachmentDescriptionFlagBits {
SE_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001,
SE_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeAttachmentDescriptionFlagBits;
typedef SeFlags SeAttachmentDescriptionFlags;
typedef enum SeSubpassDescriptionFlagBits
{
typedef enum SeSubpassDescriptionFlagBits {
SE_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001,
SE_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002,
SE_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeSubpassDescriptionFlagBits;
typedef SeFlags SeSubpassDescriptionFlags;
typedef enum SeAccessFlagBits
{
typedef enum SeAccessFlagBits {
SE_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001,
SE_ACCESS_INDEX_READ_BIT = 0x00000002,
SE_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004,
@@ -1727,8 +1648,7 @@ typedef enum SeAccessFlagBits
} SeAccessFlagBits;
typedef SeFlags SeAccessFlags;
typedef enum SeDependencyFlagBits
{
typedef enum SeDependencyFlagBits {
SE_DEPENDENCY_BY_REGION_BIT = 0x00000001,
SE_DEPENDENCY_DEVICE_GROUP_BIT = 0x00000004,
SE_DEPENDENCY_VIEW_LOCAL_BIT = 0x00000002,
@@ -1738,8 +1658,7 @@ typedef enum SeDependencyFlagBits
} SeDependencyFlagBits;
typedef SeFlags SeDependencyFlags;
typedef enum SeCommandPoolCreateFlagBits
{
typedef enum SeCommandPoolCreateFlagBits {
SE_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001,
SE_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002,
SE_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x00000004,
@@ -1747,15 +1666,13 @@ typedef enum SeCommandPoolCreateFlagBits
} SeCommandPoolCreateFlagBits;
typedef SeFlags SeCommandPoolCreateFlags;
typedef enum SeCommandPoolResetFlagBits
{
typedef enum SeCommandPoolResetFlagBits {
SE_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
SE_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeCommandPoolResetFlagBits;
typedef SeFlags SeCommandPoolResetFlags;
typedef enum SeCommandBufferUsageFlagBits
{
typedef enum SeCommandBufferUsageFlagBits {
SE_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001,
SE_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002,
SE_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004,
@@ -1763,22 +1680,19 @@ typedef enum SeCommandBufferUsageFlagBits
} SeCommandBufferUsageFlagBits;
typedef SeFlags SeCommandBufferUsageFlags;
typedef enum SeQueryControlFlagBits
{
typedef enum SeQueryControlFlagBits {
SE_QUERY_CONTROL_PRECISE_BIT = 0x00000001,
SE_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeQueryControlFlagBits;
typedef SeFlags SeQueryControlFlags;
typedef enum SeCommandBufferResetFlagBits
{
typedef enum SeCommandBufferResetFlagBits {
SE_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
SE_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} SeCommandBufferResetFlagBits;
typedef SeFlags SeCommandBufferResetFlags;
typedef enum SeStencilFaceFlagBits
{
typedef enum SeStencilFaceFlagBits {
SE_STENCIL_FACE_FRONT_BIT = 0x00000001,
SE_STENCIL_FACE_BACK_BIT = 0x00000002,
SE_STENCIL_FACE_FRONT_AND_BACK = 0x00000003,
@@ -1803,7 +1717,6 @@ typedef union SeClearValue {
SeClearDepthStencilValue depthStencil;
} SeClearValue;
typedef enum SeDescriptorAccessTypeFlagBits {
SE_DESCRIPTOR_ACCESS_READ_ONLY_BIT = 0x00000001,
SE_DESCRIPTOR_ACCESS_READ_WRITE_BIT = 0x00000002,
@@ -1811,7 +1724,5 @@ typedef enum SeDescriptorAccessTypeFlagBits {
} SeDescriptorAccessTypeFlagBits;
typedef SeFlags SeDescriptorAccessTypeFlags;
} // namespace Gfx
} // namespace Seele
+3 -8
View File
@@ -1,14 +1,9 @@
#include "Graphics.h"
#include "Shader.h"
#include "Graphics.h"
using namespace Seele::Gfx;
Graphics::Graphics()
{
shaderCompiler = new ShaderCompiler(this);
}
Graphics::Graphics() { shaderCompiler = new ShaderCompiler(this); }
Graphics::~Graphics()
{
}
Graphics::~Graphics() {}
+22 -29
View File
@@ -1,14 +1,13 @@
#pragma once
#include "MinimalEngine.h"
#include "Initializer.h"
#include "Resources.h"
#include "RenderTarget.h"
#include "Containers/Array.h"
#include "Initializer.h"
#include "MinimalEngine.h"
#include "RenderTarget.h"
#include "Resources.h"
namespace Seele
{
namespace Gfx
{
namespace Seele {
namespace Gfx {
DECLARE_REF(Window)
DECLARE_REF(Viewport)
DECLARE_REF(ShaderCompiler)
@@ -33,25 +32,18 @@ DECLARE_REF(RenderCommand)
DECLARE_REF(ComputeCommand)
DECLARE_REF(BottomLevelAS)
DECLARE_REF(TopLevelAS)
class Graphics
{
public:
class Graphics {
public:
Graphics();
virtual ~Graphics();
virtual void init(GraphicsInitializer initializer) = 0;
const QueueFamilyMapping getFamilyMapping() const
{
return queueMapping;
}
const QueueFamilyMapping getFamilyMapping() const { return queueMapping; }
PShaderCompiler getShaderCompiler()
{
return shaderCompiler;
}
PShaderCompiler getShaderCompiler() { return shaderCompiler; }
virtual OWindow createWindow(const WindowCreateInfo &createInfo) = 0;
virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo &createInfo) = 0;
virtual OWindow createWindow(const WindowCreateInfo& createInfo) = 0;
virtual OViewport createViewport(PWindow owner, const ViewportCreateInfo& createInfo) = 0;
virtual ORenderPass createRenderPass(RenderTargetLayout layout, Array<SubPassDependency> dependencies, PViewport renderArea) = 0;
virtual void beginRenderPass(PRenderPass renderPass) = 0;
@@ -61,13 +53,13 @@ public:
virtual void executeCommands(Array<ORenderCommand> commands) = 0;
virtual void executeCommands(Array<OComputeCommand> commands) = 0;
virtual OTexture2D createTexture2D(const TextureCreateInfo &createInfo) = 0;
virtual OTexture3D createTexture3D(const TextureCreateInfo &createInfo) = 0;
virtual OTextureCube createTextureCube(const TextureCreateInfo &createInfo) = 0;
virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) = 0;
virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) = 0;
virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) = 0;
virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) = 0;
virtual OTexture2D createTexture2D(const TextureCreateInfo& createInfo) = 0;
virtual OTexture3D createTexture3D(const TextureCreateInfo& createInfo) = 0;
virtual OTextureCube createTextureCube(const TextureCreateInfo& createInfo) = 0;
virtual OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) = 0;
virtual OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) = 0;
virtual OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) = 0;
virtual OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) = 0;
virtual ORenderCommand createRenderCommand(const std::string& name = "") = 0;
virtual OComputeCommand createComputeCommand(const std::string& name = "") = 0;
@@ -94,7 +86,8 @@ public:
// Ray Tracing
virtual OBottomLevelAS createBottomLevelAccelerationStructure(const BottomLevelASCreateInfo& createInfo) = 0;
virtual OTopLevelAS createTopLevelAccelerationStructure(const TopLevelASCreateInfo& createInfo) = 0;
protected:
protected:
QueueFamilyMapping queueMapping;
OShaderCompiler shaderCompiler;
bool meshShadingEnabled = false;
+77 -110
View File
@@ -1,14 +1,13 @@
#pragma once
#include "Enums.h"
#include "Containers/Map.h"
#include "Enums.h"
#include "Math/Math.h"
#include "MinimalEngine.h"
#include "MeshData.h"
#include "MinimalEngine.h"
namespace Seele
{
struct GraphicsInitializer
{
namespace Seele {
struct GraphicsInitializer {
const char* applicationName;
const char* engineName;
const char* windowLayoutFile;
@@ -23,40 +22,29 @@ namespace Seele
void* windowHandle;
GraphicsInitializer()
: applicationName("SeeleEngine")
, engineName("SeeleEngine")
, windowLayoutFile(nullptr)
, layers{ "VK_LAYER_LUNARG_monitor" }
, instanceExtensions{}
, deviceExtensions{ "VK_KHR_swapchain" }
, windowHandle(nullptr)
{
}
};
struct WindowCreateInfo
{
: applicationName("SeeleEngine"), engineName("SeeleEngine"), windowLayoutFile(nullptr), layers{"VK_LAYER_LUNARG_monitor"},
instanceExtensions{}, deviceExtensions{"VK_KHR_swapchain"}, windowHandle(nullptr) {}
};
struct WindowCreateInfo {
int32 width;
int32 height;
const char* title;
Gfx::SeFormat preferredFormat = Gfx::SE_FORMAT_B8G8R8A8_UNORM;
void* windowHandle;
};
struct ViewportCreateInfo
{
};
struct ViewportCreateInfo {
URect dimensions;
float fieldOfView = 1.222f; // 70 deg
Gfx::SeSampleCountFlags numSamples;
};
// doesnt own the data, only proxy it
struct DataSource
{
};
// doesnt own the data, only proxy it
struct DataSource {
uint64 size = 0;
uint64 offset = 0;
uint8* data = nullptr;
Gfx::QueueType owner = Gfx::QueueType::GRAPHICS;
};
struct TextureCreateInfo
{
};
struct TextureCreateInfo {
DataSource sourceData = DataSource();
Gfx::SeFormat format = Gfx::SE_FORMAT_R32G32B32A32_SFLOAT;
uint32 width = 1;
@@ -69,9 +57,8 @@ namespace Seele
Gfx::SeImageUsageFlags usage = Gfx::SE_IMAGE_USAGE_SAMPLED_BIT;
Gfx::SeMemoryPropertyFlags memoryProps = Gfx::SE_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
std::string name;
};
struct SamplerCreateInfo
{
};
struct SamplerCreateInfo {
Gfx::SeSamplerCreateFlags flags;
Gfx::SeFilter magFilter = 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;
uint32 unnormalizedCoordinates = 0;
std::string name;
};
struct VertexBufferCreateInfo
{
};
struct VertexBufferCreateInfo {
DataSource sourceData = DataSource();
// bytes per vertex
uint32 vertexSize = 0;
uint32 numVertices = 0;
std::string name = "Unnamed";
};
struct IndexBufferCreateInfo
{
};
struct IndexBufferCreateInfo {
DataSource sourceData = DataSource();
Gfx::SeIndexType indexType = Gfx::SeIndexType::SE_INDEX_TYPE_UINT16;
std::string name = "Unnamed";
};
struct UniformBufferCreateInfo
{
};
struct UniformBufferCreateInfo {
DataSource sourceData = DataSource();
uint8 dynamic = 0;
std::string name = "Unnamed";
};
struct ShaderBufferCreateInfo
{
};
struct ShaderBufferCreateInfo {
DataSource sourceData = DataSource();
uint64 numElements = 1;
uint8 dynamic = 0;
uint8 vertexBuffer = 0;
std::string name = "Unnamed";
};
DECLARE_NAME_REF(Gfx, PipelineLayout)
struct ShaderCreateInfo
{
};
DECLARE_NAME_REF(Gfx, PipelineLayout)
struct ShaderCreateInfo {
std::string name; // Debug info
std::string mainModule;
Array<std::string> additionalModules;
@@ -128,36 +110,31 @@ namespace Seele
Array<Pair<const char*, const char*>> typeParameter;
Map<const char*, const char*> defines;
Gfx::PPipelineLayout rootSignature;
};
struct VertexInputBinding
{
};
struct VertexInputBinding {
uint32 binding;
uint32 stride;
Gfx::SeVertexInputRate inputRate;
};
struct VertexInputAttribute
{
};
struct VertexInputAttribute {
uint32 location;
uint32 binding;
Gfx::SeFormat format;
uint32 offset;
};
struct VertexInputStateCreateInfo
{
};
struct VertexInputStateCreateInfo {
Array<VertexInputBinding> bindings;
Array<VertexInputAttribute> attributes;
};
DECLARE_REF(MaterialInstance)
namespace Gfx
{
struct SePushConstantRange
{
};
DECLARE_REF(MaterialInstance)
DECLARE_REF(Mesh)
namespace Gfx {
struct SePushConstantRange {
SeShaderStageFlags stageFlags;
uint32 offset;
uint32 size;
};
struct RasterizationState
{
};
struct RasterizationState {
uint32 depthClampEnable = 0;
uint32 rasterizerDiscardEnable = 0;
SePolygonMode polygonMode = Gfx::SE_POLYGON_MODE_FILL;
@@ -168,17 +145,15 @@ namespace Seele
float depthBiasClamp = 0;
float depthBiasSlopeFactor = 0;
float lineWidth = 1.0;
};
struct MultisampleState
{
};
struct MultisampleState {
SeSampleCountFlags samples = 1;
uint32 sampleShadingEnable = 0;
float minSampleShading = 1;
uint8 alphaCoverageEnable = 0;
uint8 alphaToOneEnable = 0;
};
struct DepthStencilState
{
};
struct DepthStencilState {
uint32 depthTestEnable = 1;
uint32 depthWriteEnable = 1;
SeCompareOp depthCompareOp = Gfx::SE_COMPARE_OP_GREATER;
@@ -188,11 +163,9 @@ namespace Seele
SeStencilOp back = Gfx::SE_STENCIL_OP_ZERO;
float minDepthBounds = 0.0f;
float maxDepthBounds = 1.0f;
};
struct ColorBlendState
{
struct BlendAttachment
{
};
struct ColorBlendState {
struct BlendAttachment {
uint32 blendEnable = 0;
SeBlendFactor srcColorBlendFactor = 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 dstAlphaBlendFactor = Gfx::SE_BLEND_FACTOR_SRC_ALPHA;
SeBlendOp alphaBlendOp = Gfx::SE_BLEND_OP_ADD;
SeColorComponentFlags colorWriteMask = Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT;
SeColorComponentFlags colorWriteMask =
Gfx::SE_COLOR_COMPONENT_R_BIT | Gfx::SE_COLOR_COMPONENT_G_BIT | Gfx::SE_COLOR_COMPONENT_B_BIT | Gfx::SE_COLOR_COMPONENT_A_BIT;
};
uint32 logicOpEnable = 0;
SeLogicOp logicOp = Gfx::SE_LOGIC_OP_OR;
uint32 attachmentCount = 0;
StaticArray<BlendAttachment, 16> blendAttachments;
StaticArray<float, 4> blendConstants = { 1.0f, 1.0f, 1.0f, 1.0f, };
StaticArray<float, 4> blendConstants = {
1.0f,
1.0f,
1.0f,
1.0f,
};
};
DECLARE_REF(VertexInput)
DECLARE_REF(VertexShader)
DECLARE_REF(TaskShader)
DECLARE_REF(MeshShader)
DECLARE_REF(FragmentShader)
DECLARE_REF(ComputeShader)
DECLARE_REF(RenderPass)
DECLARE_REF(PipelineLayout)
struct LegacyPipelineCreateInfo
{
DECLARE_REF(VertexInput)
DECLARE_REF(VertexShader)
DECLARE_REF(TaskShader)
DECLARE_REF(MeshShader)
DECLARE_REF(FragmentShader)
DECLARE_REF(ComputeShader)
DECLARE_REF(RenderPass)
DECLARE_REF(PipelineLayout)
struct LegacyPipelineCreateInfo {
SePrimitiveTopology topology = Gfx::SE_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
PVertexInput vertexInput = nullptr;
PVertexShader vertexShader = nullptr;
@@ -229,10 +207,9 @@ namespace Seele
RasterizationState rasterizationState;
DepthStencilState depthStencilState;
ColorBlendState colorBlend;
};
};
struct MeshPipelineCreateInfo
{
struct MeshPipelineCreateInfo {
PTaskShader taskShader = nullptr;
PMeshShader meshShader = nullptr;
PFragmentShader fragmentShader = nullptr;
@@ -242,25 +219,15 @@ namespace Seele
RasterizationState rasterizationState;
DepthStencilState depthStencilState;
ColorBlendState colorBlend;
};
struct ComputePipelineCreateInfo
{
};
struct ComputePipelineCreateInfo {
Gfx::PComputeShader computeShader = nullptr;
Gfx::PPipelineLayout pipelineLayout = nullptr;
};
DECLARE_REF(ShaderBuffer)
struct BottomLevelASCreateInfo
{
PShaderBuffer positionBuffer;
PShaderBuffer indexBuffer;
MeshData meshData;
PMaterialInstance material;
uint64 verticesOffset;
uint64 indicesOffset;
};
struct TopLevelASCreateInfo
{
};
} // namespace Gfx
};
DECLARE_REF(ShaderBuffer)
struct BottomLevelASCreateInfo {
PMesh mesh;
};
struct TopLevelASCreateInfo {};
} // namespace Gfx
} // namespace Seele
+6 -11
View File
@@ -1,19 +1,15 @@
#include "Mesh.h"
#include "Graphics/Graphics.h"
#include "Asset/AssetRegistry.h"
#include "Graphics/Graphics.h"
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, vertexData->getTypeName());
Serialization::save(buffer, vertexCount);
@@ -24,8 +20,7 @@ void Mesh::save(ArchiveBuffer& buffer) const
vertexData->serializeMesh(id, vertexCount, buffer);
}
void Mesh::load(ArchiveBuffer& buffer)
{
void Mesh::load(ArchiveBuffer& buffer) {
std::string typeName;
Serialization::load(buffer, transform);
Serialization::load(buffer, typeName);
+11 -18
View File
@@ -1,13 +1,12 @@
#pragma once
#include "Asset/MaterialInstanceAsset.h"
#include "VertexData.h"
#include "Graphics/Buffer.h"
#include "VertexData.h"
namespace Seele
{
class Mesh
{
public:
namespace Seele {
class Mesh {
public:
Mesh();
~Mesh();
@@ -21,21 +20,15 @@ public:
Array<Meshlet> meshlets;
void save(ArchiveBuffer& buffer) const;
void load(ArchiveBuffer& buffer);
private:
private:
};
DEFINE_REF(Mesh)
namespace Serialization
{
template<>
void save(ArchiveBuffer& buffer, const OMesh& ptr)
{
ptr->save(buffer);
}
template<>
void load(ArchiveBuffer& buffer, OMesh& ptr)
{
namespace Serialization {
template <> void save(ArchiveBuffer& buffer, const OMesh& ptr) { ptr->save(buffer); }
template <> void load(ArchiveBuffer& buffer, OMesh& ptr) {
ptr = new Mesh();
ptr->load(buffer);
}
}
} // namespace Serialization
} // namespace Seele
+4 -7
View File
@@ -1,18 +1,15 @@
#pragma once
#include "Math/AABB.h"
namespace Seele
{
struct MeshData
{
namespace Seele {
struct MeshData {
AABB bounding;
uint32 numMeshlets = 0;
uint32 meshletOffset = 0;
uint32 firstIndex = 0;
uint32 numIndices = 0;
};
struct InstanceData
{
struct InstanceData {
Matrix4 transformMatrix;
Matrix4 inverseTransformMatrix;
};
}
} // namespace Seele
+39 -68
View File
@@ -1,29 +1,26 @@
#include "Meshlet.h"
#include "Containers/Map.h"
#include "Containers/List.h"
#include "Containers/Map.h"
#include "Containers/Set.h"
#include <iostream>
using namespace Seele;
struct AdjacencyInfo
{
struct AdjacencyInfo {
Array<uint32> trianglesPerVertex;
Array<uint32> indexBufferOffset;
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);
for (size_t i = 0; i < indices.size(); ++i)
{
for (size_t i = 0; i < indices.size(); ++i) {
info.trianglesPerVertex[indices[i]]++;
}
uint32 triangleOffset = 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;
triangleOffset += info.trianglesPerVertex[j];
}
@@ -31,8 +28,7 @@ void buildAdjacency(const uint32 numVerts, const Array<uint32>& indices, Adjacen
uint32 numTriangles = indices.size() / 3;
info.triangleData.resize(triangleOffset);
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 b = indices[k * 3 + 1];
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)
{
while (!deadEndStack.empty())
{
int32 skipDeadEnd(const Array<uint32>& liveTriCount, List<uint32>& deadEndStack, uint32& cursor) {
while (!deadEndStack.empty()) {
uint32 vertIdx = deadEndStack.front();
deadEndStack.popFront();
if (liveTriCount[vertIdx] > 0)
{
if (liveTriCount[vertIdx] > 0) {
return vertIdx;
}
}
while (cursor < liveTriCount.size())
{
if (liveTriCount[cursor] > 0)
{
while (cursor < liveTriCount.size()) {
if (liveTriCount[cursor] > 0) {
return cursor;
}
++cursor;
@@ -65,35 +56,29 @@ int32 skipDeadEnd(const Array<uint32>& liveTriCount, List<uint32>& deadEndStack,
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();
int highestPriority = -1;
for (const uint32& vertIdx : oneRing)
{
if (liveTriCount[vertIdx] > 0)
{
for (const uint32& vertIdx : oneRing) {
if (liveTriCount[vertIdx] > 0) {
int priority = 0;
if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize)
{
if (timeStamp - cacheTimeStamps[vertIdx] + 2 * liveTriCount[vertIdx] <= cacheSize) {
priority = timeStamp - cacheTimeStamps[vertIdx];
}
if (priority > highestPriority)
{
if (priority > highestPriority) {
highestPriority = priority;
bestCandidate = vertIdx;
}
}
}
if(bestCandidate == std::numeric_limits<uint32>::max())
{
if (bestCandidate == std::numeric_limits<uint32>::max()) {
bestCandidate = skipDeadEnd(liveTriCount, deadEndStack, cursor);
}
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;
buildAdjacency(numVerts, indices, adjacencyStruct);
@@ -108,14 +93,12 @@ void tipsifyIndexBuffer(const Array<uint32>& indices, const uint32 numVerts, con
int32 curVert = 0;
uint32 timeStamp = cacheSize + 1;
uint32 cursor = 1;
while (curVert != -1)
{
while (curVert != -1) {
Array<uint32> oneRing;
const uint32* startTriPointer = &adjacencyStruct.triangleData[0] + adjacencyStruct.indexBufferOffset[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;
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;
};
int findIndex(Meshlet &current, uint32 index)
{
for (uint32 i = 0; i < current.numVertices; ++i)
{
if (current.uniqueVertices[i] == index)
{
int findIndex(Meshlet& current, uint32 index) {
for (uint32 i = 0; i < current.numVertices; ++i) {
if (current.uniqueVertices[i] == index) {
return i;
}
}
if (current.numVertices == Gfx::numVerticesPerMeshlet)
{
if (current.numVertices == Gfx::numVerticesPerMeshlet) {
return -1;
}
current.uniqueVertices[current.numVertices] = index;
@@ -179,8 +157,7 @@ int findIndex(Meshlet &current, uint32 index)
return current.numVertices++;
}
void completeMeshlet(Array<Meshlet> &meshlets, Meshlet &current)
{
void completeMeshlet(Array<Meshlet>& meshlets, Meshlet& current) {
meshlets.add(current);
current = {
.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 f2 = findIndex(current, tri.indices[1]);
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;
}
current.boundingBox.adjust(positions[tri.indices[0]]);
@@ -209,36 +184,32 @@ bool addTriangle(const Array<Vector>& positions, Meshlet &current, Triangle& tri
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 = {
.numVertices = 0,
.numPrimitives = 0,
};
//Array<uint32> optimizedIndices = indices;
//tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices);
// Array<uint32> optimizedIndices = indices;
// tipsifyIndexBuffer(indices, positions.size(), 25, optimizedIndices);
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{
.indices = {
.indices =
{
indices[i * 3 + 0],
indices[i * 3 + 1],
indices[i * 3 + 2],
},
};
}
while(!triangles.empty())
{
if (!addTriangle(positions, current, triangles.back()))
{
while (!triangles.empty()) {
if (!addTriangle(positions, current, triangles.back())) {
completeMeshlet(meshlets, current);
addTriangle(positions, current, triangles.back());
}
triangles.pop();
}
if (current.numVertices > 0)
{
if (current.numVertices > 0) {
completeMeshlet(meshlets, current);
}
}
+4 -5
View File
@@ -1,11 +1,10 @@
#pragma once
#include "Math/AABB.h"
#include "Graphics/Enums.h"
#include "Math/AABB.h"
namespace Seele
{
struct Meshlet
{
namespace Seele {
struct Meshlet {
AABB boundingBox;
uint32 uniqueVertices[Gfx::numVerticesPerMeshlet]; // unique vertiex indices in the vertex data
uint8 primitiveLayout[Gfx::numPrimitivesPerMeshlet * 3]; // indices into the uniqueVertices array, only uint8 needed
+34 -34
View File
@@ -9,9 +9,8 @@
namespace Seele {
namespace Metal {
DECLARE_REF(Graphics)
class BufferAllocation : public CommandBoundResource
{
public:
class BufferAllocation : public CommandBoundResource {
public:
BufferAllocation(PGraphics graphics);
virtual ~BufferAllocation();
MTL::Buffer* buffer = nullptr;
@@ -19,17 +18,17 @@ public:
};
DECLARE_REF(BufferAllocation)
class Buffer {
public:
Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic, const std::string& name);
public:
Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name);
virtual ~Buffer();
MTL::Buffer *getHandle() const { return buffers[currentBuffer]->buffer; }
MTL::Buffer* getHandle() const { return buffers[currentBuffer]->buffer; }
PBufferAllocation getAlloc() const { return buffers[currentBuffer]; }
uint64 getSize() const { return buffers[currentBuffer]->size; }
void *map(bool writeOnly = true);
void *mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly);
void* map(bool writeOnly = true);
void* mapRegion(uint64 regionOffset, uint64 regionSize, bool writeOnly);
void unmap();
protected:
protected:
PGraphics graphics;
uint32 currentBuffer = 0;
Array<OBufferAllocation> buffers;
@@ -41,61 +40,62 @@ protected:
DEFINE_REF(Buffer)
class VertexBuffer : public Gfx::VertexBuffer, public Buffer {
public:
VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo &createInfo);
public:
VertexBuffer(PGraphics graphics, const VertexBufferCreateInfo& createInfo);
virtual ~VertexBuffer();
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
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) override;
};
DEFINE_REF(VertexBuffer)
class IndexBuffer : public Gfx::IndexBuffer, public Buffer {
public:
IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo &createInfo);
public:
IndexBuffer(PGraphics graphics, const IndexBufferCreateInfo& createInfo);
virtual ~IndexBuffer();
virtual void download(Array<uint8> &buffer) override;
protected:
virtual void download(Array<uint8>& buffer) override;
protected:
// Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) override;
};
DEFINE_REF(IndexBuffer)
DEFINE_REF(IndexBuffer)
class UniformBuffer : public Gfx::UniformBuffer, public Buffer {
public:
UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo &createInfo);
public:
UniformBuffer(PGraphics graphics, const UniformBufferCreateInfo& createInfo);
virtual ~UniformBuffer();
virtual bool updateContents(const DataSource &sourceData) override;
virtual bool updateContents(const DataSource& sourceData) override;
protected:
protected:
// Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) override;
};
DEFINE_REF(UniformBuffer)
class ShaderBuffer : public Gfx::ShaderBuffer, public Buffer {
public:
ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo &createInfo);
public:
ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo);
virtual ~ShaderBuffer();
virtual void rotateBuffer(uint64 size) override;
virtual void updateContents(const ShaderBufferCreateInfo &sourceData) override;
virtual void *mapRegion(uint64 offset, uint64 size, bool writeOnly) override;
virtual void updateContents(const ShaderBufferCreateInfo& sourceData) override;
virtual void* mapRegion(uint64 offset, uint64 size, bool writeOnly) override;
virtual void unmap() override;
protected:
protected:
// Inherited via QueueOwnedResource
virtual void executeOwnershipBarrier(Gfx::QueueType newOwner) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) override;
virtual void executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage, Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) override;
};
DEFINE_REF(ShaderBuffer)
} // namespace Metal
+96 -75
View File
@@ -11,49 +11,44 @@ using namespace Seele;
using namespace Seele::Metal;
BufferAllocation::BufferAllocation(PGraphics graphics)
: CommandBoundResource(graphics)
{}
: CommandBoundResource(graphics) {}
BufferAllocation::~BufferAllocation()
{
if(buffer != nullptr)
{
BufferAllocation::~BufferAllocation() {
if (buffer != nullptr) {
buffer->release();
}
}
Buffer::Buffer(PGraphics graphics, uint64 size, void* data, bool dynamic, const std::string& name)
: graphics(graphics)
, dynamic(dynamic)
, name(name) {
Buffer::Buffer(PGraphics graphics, uint64 size, void *data, bool dynamic,
const std::string &name)
: graphics(graphics), dynamic(dynamic), name(name) {
createBuffer(size, data);
}
Buffer::~Buffer() {
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::rotateBuffer(uint64 size)
{
void Buffer::rotateBuffer(uint64 size) {
size = std::max(getSize(), size);
for(size_t i = 0; i < buffers.size(); ++i)
{
if(buffers[i]->isCurrentlyBound())
{
for (size_t i = 0; i < buffers.size(); ++i) {
if (buffers[i]->isCurrentlyBound()) {
continue;
}
if(buffers[i]->size < size)
{
if (buffers[i]->size < size) {
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;
}
currentBuffer = i;
@@ -63,79 +58,106 @@ void Buffer::rotateBuffer(uint64 size)
currentBuffer = buffers.size() - 1;
}
void Buffer::createBuffer(uint64 size, void* data)
{
void Buffer::createBuffer(uint64 size, void *data) {
buffers.add(new BufferAllocation(graphics));
if (data != nullptr) {
buffers.back()->buffer = graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared);
buffers.back()->buffer =
graphics->getDevice()->newBuffer(data, size, MTL::StorageModeShared);
} 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)
: Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices, createInfo.vertexSize,
createInfo.sourceData.owner),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, false, createInfo.name) {}
VertexBuffer::VertexBuffer(PGraphics graphics,
const VertexBufferCreateInfo &createInfo)
: Gfx::VertexBuffer(graphics->getFamilyMapping(), createInfo.numVertices,
createInfo.vertexSize, createInfo.sourceData.owner),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, false, createInfo.name) {
}
VertexBuffer::~VertexBuffer() {}
void VertexBuffer::updateRegion(DataSource update) {
void* data = getHandle()->contents();
std::memcpy((char*)data + update.offset, update.data, update.size);
void *data = getHandle()->contents();
std::memcpy((char *)data + update.offset, update.data, update.size);
}
void VertexBuffer::download(Array<uint8>& buffer) {
void* data = getHandle()->contents();
void VertexBuffer::download(Array<uint8> &buffer) {
void *data = getHandle()->contents();
buffer.resize(getSize());
std::memcpy(buffer.data(), data, getSize());
}
void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) { currentOwner = newOwner; }
void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess, Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {
void VertexBuffer::executeOwnershipBarrier(Gfx::QueueType newOwner) {
currentOwner = newOwner;
}
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) {}
void VertexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
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() {}
void IndexBuffer::download(Array<uint8>& buffer) {
void* data = getHandle()->contents();
void IndexBuffer::download(Array<uint8> &buffer) {
void *data = getHandle()->contents();
buffer.resize(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,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {}
void IndexBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
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),
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() {}
bool UniformBuffer::updateContents(const DataSource& sourceData) {
void* data = getHandle()->contents();
std::memcpy((char*)data + sourceData.offset, sourceData.data, sourceData.size);
bool UniformBuffer::updateContents(const DataSource &sourceData) {
void *data = getHandle()->contents();
std::memcpy((char *)data + sourceData.offset, sourceData.data,
sourceData.size);
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,
Gfx::SeAccessFlags dstAccess, Gfx::SePipelineStageFlags dstStage) {}
void UniformBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) {
}
ShaderBuffer::ShaderBuffer(PGraphics graphics, const ShaderBufferCreateInfo& createInfo)
: Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements, createInfo.sourceData),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size, createInfo.sourceData.data, createInfo.dynamic, createInfo.name) {}
ShaderBuffer::ShaderBuffer(PGraphics graphics,
const ShaderBufferCreateInfo &createInfo)
: Gfx::ShaderBuffer(graphics->getFamilyMapping(), createInfo.numElements,
createInfo.sourceData),
Seele::Metal::Buffer(graphics, createInfo.sourceData.size,
createInfo.sourceData.data, createInfo.dynamic,
createInfo.name) {}
ShaderBuffer::~ShaderBuffer() {}
@@ -143,29 +165,28 @@ void ShaderBuffer::rotateBuffer(uint64 size) {
Metal::Buffer::rotateBuffer(size);
}
void ShaderBuffer::updateContents(const ShaderBufferCreateInfo& createInfo) {
void ShaderBuffer::updateContents(const ShaderBufferCreateInfo &createInfo) {
Gfx::ShaderBuffer::updateContents(createInfo);
if(createInfo.sourceData.data == nullptr)
{
if (createInfo.sourceData.data == nullptr) {
return;
}
void* data = map();
std::memcpy((char*)data + createInfo.sourceData.offset, createInfo.sourceData.data, createInfo.sourceData.size);
void *data = map();
std::memcpy((char *)data + createInfo.sourceData.offset,
createInfo.sourceData.data, createInfo.sourceData.size);
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);
}
void ShaderBuffer::unmap()
{
Metal::Buffer::unmap();
void ShaderBuffer::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, Gfx::SePipelineStageFlags dstStage) {}
void ShaderBuffer::executePipelineBarrier(Gfx::SeAccessFlags srcAccess,
Gfx::SePipelineStageFlags srcStage,
Gfx::SeAccessFlags dstAccess,
Gfx::SePipelineStageFlags dstStage) {}
+14 -18
View File
@@ -19,7 +19,7 @@ DECLARE_REF(IndexBuffer)
DECLARE_REF(GraphicsPipeline)
DECLARE_REF(ComputePipeline)
class Command {
public:
public:
Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer);
~Command();
void beginRenderPass(PRenderPass renderPass);
@@ -32,8 +32,7 @@ public:
MTL::RenderCommandEncoder* createRenderEncoder() { return parallelEncoder->renderCommandEncoder(); }
MTL::BlitCommandEncoder* getBlitEncoder() {
assert(!parallelEncoder);
if(blitEncoder == nullptr)
{
if (blitEncoder == nullptr) {
blitEncoder = cmdBuffer->blitCommandEncoder();
}
return blitEncoder;
@@ -41,7 +40,7 @@ public:
PEvent getCompletedEvent() const { return completed; }
constexpr MTL::CommandBuffer* getHandle() const { return cmdBuffer; }
private:
private:
PGraphics graphics;
OEvent completed;
MTL::CommandBuffer* cmdBuffer;
@@ -50,7 +49,7 @@ private:
};
DEFINE_REF(Command)
class RenderCommand : public Gfx::RenderCommand {
public:
public:
RenderCommand(MTL::RenderCommandEncoder* encode, const std::string& name);
virtual ~RenderCommand();
void end();
@@ -60,15 +59,13 @@ public:
virtual void bindDescriptor(const Array<Gfx::PDescriptorSet>& descriptorSets, Array<uint32> dynamicOffsets) override;
virtual void bindVertexBuffer(const Array<Gfx::PVertexBuffer>& buffers) override;
virtual void bindIndexBuffer(Gfx::PIndexBuffer indexBuffer) override;
virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size,
const void* data) override;
virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override;
virtual void draw(uint32 vertexCount, uint32 instanceCount, int32 firstVertex, uint32 firstInstance) override;
virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset,
uint32 firstInstance) override;
virtual void drawIndexed(uint32 indexCount, uint32 instanceCount, int32 firstIndex, uint32 vertexOffset, uint32 firstInstance) override;
virtual void drawMesh(uint32 groupX, uint32 groupY, uint32 groupZ) override;
virtual void drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset, uint32 drawCount, uint32 stride) override;
private:
private:
PGraphicsPipeline boundPipeline;
PIndexBuffer boundIndexBuffer;
MTL::Buffer* argumentBuffer;
@@ -77,18 +74,17 @@ private:
};
DEFINE_REF(RenderCommand)
class ComputeCommand : public Gfx::ComputeCommand {
public:
public:
ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name);
virtual ~ComputeCommand();
void end();
virtual void bindPipeline(Gfx::PComputePipeline pipeline) 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 pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size,
const void* data) override;
virtual void pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size, const void* data) override;
virtual void dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) override;
private:
private:
PComputePipeline boundPipeline;
MTL::CommandBuffer* commandBuffer;
MTL::ComputeCommandEncoder* encoder;
@@ -97,7 +93,7 @@ private:
};
DEFINE_REF(ComputeCommand)
class CommandQueue {
public:
public:
CommandQueue(PGraphics graphics);
~CommandQueue();
constexpr MTL::CommandQueue* getHandle() { return queue; }
@@ -108,21 +104,21 @@ public:
void executeCommands(Array<Gfx::OComputeCommand> commands);
void submitCommands(PEvent signal = nullptr);
private:
private:
PGraphics graphics;
MTL::CommandQueue* queue;
OCommand activeCommand;
Array<OCommand> pendingCommands;
};
class IOCommandQueue {
public:
public:
IOCommandQueue(PGraphics graphics);
~IOCommandQueue();
constexpr MTL::IOCommandQueue* getHandle() { return queue; }
PCommand getCommands() { return activeCommand; } // TODO
void submitCommands(PEvent signal = nullptr);
private:
private:
PGraphics graphics;
MTL::IOCommandQueue* queue;
OCommand activeCommand;
+87 -50
View File
@@ -16,8 +16,9 @@
using namespace Seele;
using namespace Seele::Metal;
Command::Command(PGraphics graphics, MTL::CommandBuffer* cmdBuffer)
: graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) {}
Command::Command(PGraphics graphics, MTL::CommandBuffer *cmdBuffer)
: graphics(graphics), completed(new Event(graphics)), cmdBuffer(cmdBuffer) {
}
Command::~Command() {}
@@ -27,7 +28,8 @@ void Command::beginRenderPass(PRenderPass renderPass) {
blitEncoder = nullptr;
}
renderPass->updateRenderPass();
parallelEncoder = cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor());
parallelEncoder =
cmdBuffer->parallelRenderCommandEncoder(renderPass->getDescriptor());
}
void Command::endRenderPass() {
@@ -35,7 +37,9 @@ void Command::endRenderPass() {
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) {
assert(!parallelEncoder);
@@ -49,11 +53,16 @@ void Command::end(PEvent signal) {
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) {}
RenderCommand::~RenderCommand() {}
@@ -79,15 +88,19 @@ void RenderCommand::bindPipeline(Gfx::PGraphicsPipeline pipeline) {
for (auto [_, layout] : boundPipeline->getPipelineLayout()->getLayouts()) {
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(
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>();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(descriptorSet->getLayout()->getName());
uint64* topLevelTable = (uint64*)argumentBuffer->contents();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(
descriptorSet->getLayout()->getName());
uint64 *topLevelTable = (uint64 *)argumentBuffer->contents();
topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress();
auto bindings = metalSet->getLayout()->getBindings();
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) {
bindDescriptor(set, offsets);
}
}
void RenderCommand::bindVertexBuffer(const Array<Gfx::PVertexBuffer>& buffers) {
void RenderCommand::bindVertexBuffer(const Array<Gfx::PVertexBuffer> &buffers) {
uint32 i = 0;
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>();
}
void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset, uint32 size,
const void* data) {
void RenderCommand::pushConstants(Gfx::SeShaderStageFlags stage, uint32 offset,
uint32 size, const void *data) {
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) {
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) {
encoder->drawPrimitives(boundPipeline->getPrimitive(), firstVertex, vertexCount, instanceCount, firstInstance);
void RenderCommand::draw(uint32 vertexCount, uint32 instanceCount,
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) {
encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount, cast(boundIndexBuffer->getIndexType()),
boundIndexBuffer->getHandle(), firstIndex, instanceCount, vertexOffset, firstInstance);
encoder->drawIndexedPrimitives(boundPipeline->getPrimitive(), indexCount,
cast(boundIndexBuffer->getIndexType()),
boundIndexBuffer->getHandle(), firstIndex,
instanceCount, vertexOffset, firstInstance);
}
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->setMeshBuffer(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) {
//encoder->drawMeshThreadgroups()
void RenderCommand::drawMeshIndirect(Gfx::PShaderBuffer buffer, uint64 offset,
uint32 drawCount, uint32 stride) {
// encoder->drawMeshThreadgroups()
}
ComputeCommand::ComputeCommand(MTL::CommandBuffer* cmdBuffer, const std::string& name)
: commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()), name(name) {}
ComputeCommand::ComputeCommand(MTL::CommandBuffer *cmdBuffer,
const std::string &name)
: commandBuffer(cmdBuffer), encoder(cmdBuffer->computeCommandEncoder()),
name(name) {}
ComputeCommand::~ComputeCommand() {}
@@ -180,16 +204,21 @@ void ComputeCommand::bindPipeline(Gfx::PComputePipeline pipeline) {
boundPipeline = pipeline.cast<ComputePipeline>();
encoder->setComputePipelineState(boundPipeline->getHandle());
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(
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>();
metalSet->bind();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(set->getLayout()->getName());
uint64* topLevelTable = (uint64*)argumentBuffer->contents();
uint32 parameterIndex = boundPipeline->getPipelineLayout()->findParameter(
set->getLayout()->getName());
uint64 *topLevelTable = (uint64 *)argumentBuffer->contents();
topLevelTable[parameterIndex] = metalSet->getBuffer()->gpuAddress();
auto bindings = metalSet->getLayout()->getBindings();
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) {
for (auto& set : sets) {
void ComputeCommand::bindDescriptor(const Array<Gfx::PDescriptorSet> &sets,
Array<uint32> offsets) {
for (auto &set : sets) {
bindDescriptor(set, offsets);
}
}
void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset, uint32 size,
const void* data) {
encoder->setBytes((char*)data + offset, size, 0);
void ComputeCommand::pushConstants(Gfx::SeShaderStageFlags, uint32 offset,
uint32 size, const void *data) {
encoder->setBytes((char *)data + offset, size, 0);
}
void ComputeCommand::dispatch(uint32 threadX, uint32 threadY, uint32 threadZ) {
// TODO
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) {
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));
descriptor->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);
}
OComputeCommand CommandQueue::getComputeCommand(const std::string& name) {
OComputeCommand CommandQueue::getComputeCommand(const std::string &name) {
return new ComputeCommand(queue->commandBuffer(), name);
}
void CommandQueue::executeCommands(Array<Gfx::ORenderCommand> commands) {
for (auto& command : commands) {
for (auto &command : commands) {
auto metalCmd = Gfx::PRenderCommand(command).cast<RenderCommand>();
metalCmd->end();
}
@@ -262,15 +294,17 @@ void CommandQueue::executeCommands(Array<Gfx::ORenderCommand> commands) {
void CommandQueue::executeCommands(Array<Gfx::OComputeCommand> commands) {
submitCommands();
for (auto& command : commands) {
for (auto &command : commands) {
auto metalCmd = Gfx::PComputeCommand(command).cast<ComputeCommand>();
metalCmd->end();
}
}
void CommandQueue::submitCommands(PEvent signalSemaphore) {
activeCommand->getHandle()->addCompletedHandler(MTL::CommandBufferHandler([&](MTL::CommandBuffer* cmdBuffer) {
for (auto it = pendingCommands.begin(); it != pendingCommands.end(); it++) {
activeCommand->getHandle()->addCompletedHandler(
MTL::CommandBufferHandler([&](MTL::CommandBuffer *cmdBuffer) {
for (auto it = pendingCommands.begin(); it != pendingCommands.end();
it++) {
if ((*it)->getHandle() == cmdBuffer) {
pendingCommands.remove(it);
return;
@@ -281,14 +315,17 @@ void CommandQueue::submitCommands(PEvent signalSemaphore) {
activeCommand->waitDeviceIdle();
PEvent prevCmdEvent = activeCommand->getCompletedEvent();
pendingCommands.add(std::move(activeCommand));
MTL::CommandBufferDescriptor* descriptor = MTL::CommandBufferDescriptor::alloc()->init();
descriptor->setErrorOptions(MTL::CommandBufferErrorOptionEncoderExecutionStatus);
MTL::CommandBufferDescriptor *descriptor =
MTL::CommandBufferDescriptor::alloc()->init();
descriptor->setErrorOptions(
MTL::CommandBufferErrorOptionEncoderExecutionStatus);
activeCommand = new Command(graphics, queue->commandBuffer(descriptor));
activeCommand->waitForEvent(prevCmdEvent);
}
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->setPriority(MTL::IOPriorityNormal);
queue = graphics->getDevice()->newIOCommandQueue(desc, nullptr);
+18 -24
View File
@@ -9,26 +9,26 @@ namespace Seele {
namespace Metal {
DECLARE_REF(Graphics)
class DescriptorLayout : public Gfx::DescriptorLayout {
public:
DescriptorLayout(PGraphics graphics, const std::string &name);
public:
DescriptorLayout(PGraphics graphics, const std::string& name);
virtual ~DescriptorLayout();
virtual void create() override;
private:
private:
PGraphics graphics;
};
DEFINE_REF(DescriptorLayout)
DECLARE_REF(DescriptorSet)
class DescriptorPool : public Gfx::DescriptorPool {
public:
public:
DescriptorPool(PGraphics graphics, PDescriptorLayout layout);
virtual ~DescriptorPool();
virtual Gfx::PDescriptorSet allocateDescriptorSet() override;
virtual void reset() override;
constexpr PDescriptorLayout getLayout() const { return layout; }
private:
private:
PGraphics graphics;
PDescriptorLayout layout;
Array<ODescriptorSet> allocatedSets;
@@ -36,47 +36,41 @@ private:
DEFINE_REF(DescriptorPool)
class DescriptorSet : public Gfx::DescriptorSet, public CommandBoundResource {
public:
public:
DescriptorSet(PGraphics graphics, PDescriptorPool owner);
virtual ~DescriptorSet();
virtual void writeChanges() override;
virtual void updateBuffer(uint32_t binding,
Gfx::PUniformBuffer uniformBuffer) override;
virtual void updateBuffer(uint32_t binding, Gfx::PUniformBuffer 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 updateSampler(uint32_t binding, Gfx::PSampler samplerState) override;
virtual void updateTexture(uint32_t binding, Gfx::PTexture texture,
Gfx::PSampler sampler = nullptr) override;
virtual void updateTextureArray(uint32_t binding,
Array<Gfx::PTexture> texture) override;
virtual void updateTexture(uint32_t binding, Gfx::PTexture texture, Gfx::PSampler sampler = nullptr) override;
virtual void updateTextureArray(uint32_t binding, Array<Gfx::PTexture> texture) override;
constexpr bool isCurrentlyInUse() const { return currentlyInUse; }
constexpr void allocate() { currentlyInUse = true; }
constexpr void free() { currentlyInUse = false; }
constexpr MTL::Buffer *getBuffer() const { return buffer; }
constexpr const Array<MTL::Resource *> &getBoundResources() const {
return boundResources;
}
constexpr MTL::Buffer* getBuffer() const { return buffer; }
constexpr const Array<MTL::Resource*>& getBoundResources() const { return boundResources; }
private:
private:
PGraphics graphics;
PDescriptorPool owner;
MTL::Buffer *buffer = nullptr;
uint64 *argumentBuffer = nullptr;
Array<MTL::Resource *> boundResources;
MTL::Buffer* buffer = nullptr;
uint64* argumentBuffer = nullptr;
Array<MTL::Resource*> boundResources;
bool currentlyInUse;
};
DEFINE_REF(DescriptorSet)
class PipelineLayout : public Gfx::PipelineLayout {
public:
PipelineLayout(PGraphics graphics, const std::string &name,
Gfx::PPipelineLayout baseLayout);
public:
PipelineLayout(PGraphics graphics, const std::string& name, Gfx::PPipelineLayout baseLayout);
virtual ~PipelineLayout();
virtual void create() override;
private:
private:
PGraphics graphics;
};
DEFINE_REF(PipelineLayout)
+2 -5
View File
@@ -94,11 +94,8 @@ void DescriptorSet::updateBuffer(uint32_t binding,
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,
Gfx::PSampler samplerState) {
+5 -7
View File
@@ -3,11 +3,9 @@
#include "Metal/MTLStageInputOutputDescriptor.hpp"
#include "Resources.h"
namespace Seele
{
namespace Metal
{
constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6;// something about metal vertex fetch
namespace Seele {
namespace Metal {
constexpr uint64 METAL_VERTEXBUFFER_OFFSET = 6; // something about metal vertex fetch
constexpr uint64 METAL_VERTEXATTRIBUTE_OFFSET = 11;
MTL::PixelFormat cast(Gfx::SeFormat format);
@@ -32,5 +30,5 @@ MTL::PrimitiveTopologyClass cast(Gfx::SePrimitiveTopology topology);
Gfx::SePrimitiveTopology cast(MTL::PrimitiveTopologyClass topology);
MTL::IndexType cast(Gfx::SeIndexType 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) {
case Gfx::SE_PRIMITIVE_TOPOLOGY_POINT_LIST:
return MTL::PrimitiveTopologyClassPoint;
+19 -19
View File
@@ -1,25 +1,24 @@
#pragma once
#include "Metal/Metal.hpp"
#include "Graphics/Graphics.h"
#include "Metal/Metal.hpp"
namespace Seele
{
namespace Metal
{
namespace Seele {
namespace Metal {
DECLARE_REF(CommandQueue)
DECLARE_REF(IOCommandQueue)
DECLARE_REF(PipelineCache)
class Graphics : public Gfx::Graphics
{
public:
class Graphics : public Gfx::Graphics {
public:
Graphics();
virtual ~Graphics();
virtual void init(GraphicsInitializer initializer) override;
virtual Gfx::OWindow createWindow(const WindowCreateInfo &createInfo) override;
virtual Gfx::OViewport createViewport(Gfx::PWindow owner, const ViewportCreateInfo &createInfo) override;
virtual Gfx::OWindow createWindow(const WindowCreateInfo& 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 endRenderPass() override;
virtual void waitDeviceIdle() override;
@@ -27,13 +26,13 @@ public:
virtual void executeCommands(Array<Gfx::ORenderCommand> commands) override;
virtual void executeCommands(Array<Gfx::OComputeCommand> commands) override;
virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo &createInfo) override;
virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo &createInfo) override;
virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo &createInfo) override;
virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo &bulkData) override;
virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo &bulkData) override;
virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo &bulkData) override;
virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo &bulkData) override;
virtual Gfx::OTexture2D createTexture2D(const TextureCreateInfo& createInfo) override;
virtual Gfx::OTexture3D createTexture3D(const TextureCreateInfo& createInfo) override;
virtual Gfx::OTextureCube createTextureCube(const TextureCreateInfo& createInfo) override;
virtual Gfx::OUniformBuffer createUniformBuffer(const UniformBufferCreateInfo& bulkData) override;
virtual Gfx::OShaderBuffer createShaderBuffer(const ShaderBufferCreateInfo& bulkData) override;
virtual Gfx::OVertexBuffer createVertexBuffer(const VertexBufferCreateInfo& bulkData) override;
virtual Gfx::OIndexBuffer createIndexBuffer(const IndexBufferCreateInfo& bulkData) override;
virtual Gfx::ORenderCommand createRenderCommand(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; }
PCommandQueue getQueue() const { return queue; }
PIOCommandQueue getIOQueue() const { return ioQueue; }
protected:
protected:
MTL::Device* device;
OCommandQueue queue;
OIOCommandQueue ioQueue;
+58 -79
View File
@@ -1,31 +1,25 @@
#include "Graphics.h"
#include "Buffer.h"
#include "Command.h"
#include "Graphics/Initializer.h"
#include "Graphics/Metal/Descriptor.h"
#include "Graphics/Metal/Pipeline.h"
#include "Graphics/Metal/PipelineCache.h"
#include "Graphics/Metal/Resources.h"
#include "Shader.h"
#include "RenderPass.h"
#include "Resources.h"
#include "Command.h"
#include "Shader.h"
#include "Window.h"
#include "Buffer.h"
using namespace Seele;
using namespace Seele::Metal;
Graphics::Graphics()
{
Graphics::Graphics() {}
}
Graphics::~Graphics() {}
Graphics::~Graphics()
{
}
void Graphics::init(GraphicsInitializer)
{
void Graphics::init(GraphicsInitializer) {
glfwInit();
device = MTL::CreateSystemDefaultDevice();
queue = new CommandQueue(this);
@@ -34,164 +28,149 @@ void Graphics::init(GraphicsInitializer)
meshShadingEnabled = false;
}
Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &createInfo)
{
Gfx::OWindow Graphics::createWindow(const WindowCreateInfo &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);
}
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);
}
void Graphics::beginRenderPass(Gfx::PRenderPass renderPass)
{
void Graphics::beginRenderPass(Gfx::PRenderPass renderPass) {
queue->getCommands()->beginRenderPass(renderPass.cast<RenderPass>());
}
void Graphics::endRenderPass()
{
queue->getCommands()->endRenderPass();
}
void Graphics::endRenderPass() { queue->getCommands()->endRenderPass(); }
void Graphics::waitDeviceIdle()
{
queue->getCommands()->waitDeviceIdle();
}
void Graphics::waitDeviceIdle() { queue->getCommands()->waitDeviceIdle(); }
void Graphics::executeCommands(Array<Gfx::ORenderCommand> commands)
{
void Graphics::executeCommands(Array<Gfx::ORenderCommand> 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));
}
Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &createInfo)
{
Gfx::OTexture2D Graphics::createTexture2D(const TextureCreateInfo &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);
}
Gfx::OTextureCube Graphics::createTextureCube(const TextureCreateInfo &createInfo)
{
Gfx::OTextureCube
Graphics::createTextureCube(const TextureCreateInfo &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);
}
Gfx::OShaderBuffer Graphics::createShaderBuffer(const ShaderBufferCreateInfo &bulkData)
{
Gfx::OShaderBuffer
Graphics::createShaderBuffer(const ShaderBufferCreateInfo &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);
}
Gfx::OIndexBuffer Graphics::createIndexBuffer(const IndexBufferCreateInfo &bulkData)
{
Gfx::OIndexBuffer
Graphics::createIndexBuffer(const IndexBufferCreateInfo &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);
}
Gfx::OComputeCommand Graphics::createComputeCommand(const std::string& name)
{
Gfx::OComputeCommand Graphics::createComputeCommand(const std::string &name) {
return queue->getComputeCommand(name);
}
Gfx::OVertexShader Graphics::createVertexShader(const ShaderCreateInfo& createInfo)
{
Gfx::OVertexShader
Graphics::createVertexShader(const ShaderCreateInfo &createInfo) {
OVertexShader result = new VertexShader(this);
result->create(createInfo);
return result;
}
Gfx::OFragmentShader Graphics::createFragmentShader(const ShaderCreateInfo& createInfo)
{
Gfx::OFragmentShader
Graphics::createFragmentShader(const ShaderCreateInfo &createInfo) {
OFragmentShader result = new FragmentShader(this);
result->create(createInfo);
return result;
}
Gfx::OComputeShader Graphics::createComputeShader(const ShaderCreateInfo& createInfo)
{
Gfx::OComputeShader
Graphics::createComputeShader(const ShaderCreateInfo &createInfo) {
OComputeShader result = new ComputeShader(this);
result->create(createInfo);
return result;
}
Gfx::OMeshShader Graphics::createMeshShader(const ShaderCreateInfo& createInfo)
{
Gfx::OMeshShader
Graphics::createMeshShader(const ShaderCreateInfo &createInfo) {
OMeshShader result = new MeshShader(this);
result->create(createInfo);
return result;
}
Gfx::OTaskShader Graphics::createTaskShader(const ShaderCreateInfo& createInfo)
{
Gfx::OTaskShader
Graphics::createTaskShader(const ShaderCreateInfo &createInfo) {
OTaskShader result = new TaskShader(this);
result->create(createInfo);
return result;
}
Gfx::PGraphicsPipeline Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo createInfo)
{
Gfx::PGraphicsPipeline
Graphics::createGraphicsPipeline(Gfx::LegacyPipelineCreateInfo 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));
}
Gfx::PComputePipeline Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo createInfo)
{
Gfx::PComputePipeline
Graphics::createComputePipeline(Gfx::ComputePipelineCreateInfo 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);
}
Gfx::ODescriptorLayout Graphics::createDescriptorLayout(const std::string& name)
{
Gfx::ODescriptorLayout
Graphics::createDescriptorLayout(const std::string &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);
}
Gfx::OVertexInput Graphics::createVertexInput(VertexInputStateCreateInfo createInfo)
{
Gfx::OVertexInput
Graphics::createVertexInput(VertexInputStateCreateInfo 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 Metal {
class VertexInput : public Gfx::VertexInput {
public:
public:
VertexInput(VertexInputStateCreateInfo createInfo);
virtual ~VertexInput();
};
DECLARE_REF(PipelineLayout)
DECLARE_REF(Graphics)
class GraphicsPipeline : public Gfx::GraphicsPipeline {
public:
public:
GraphicsPipeline(PGraphics graphics, MTL::PrimitiveType primitive, MTL::RenderPipelineState* pipeline, Gfx::PPipelineLayout createInfo);
virtual ~GraphicsPipeline();
constexpr MTL::RenderPipelineState* getHandle() const { return state; }
@@ -22,17 +22,19 @@ public:
PGraphics graphics;
MTL::RenderPipelineState* state;
MTL::PrimitiveType primitiveType;
private:
private:
};
DEFINE_REF(GraphicsPipeline)
class ComputePipeline : public Gfx::ComputePipeline {
public:
public:
ComputePipeline(PGraphics graphics, MTL::ComputePipelineState* pipeline, Gfx::PPipelineLayout);
virtual ~ComputePipeline();
constexpr MTL::ComputePipelineState* getHandle() const { return state; }
PGraphics graphics;
private:
private:
MTL::ComputePipelineState* state;
};
DEFINE_REF(ComputePipeline)

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