commit 279f292225fa5cf8c56fb01fcd1417fddf22d323 Author: bigboss Date: Sun Nov 29 00:38:13 2026 +0100 Initial commit - Migration from cmake to gradle diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d6fe383 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +# Ignore Kotlin plugin data +.kotlin + +.vscode + +vcpkg_installed +vcpkg diff --git a/ApplicationDemo/build.gradle b/ApplicationDemo/build.gradle new file mode 100644 index 0000000..a640ad7 --- /dev/null +++ b/ApplicationDemo/build.gradle @@ -0,0 +1,55 @@ +plugins { id 'cpp-application' } +apply from: rootProject.file('gradle/common.gradle') + +application { + targetMachines.add(machines.windows.x86_64) + targetMachines.add(machines.linux.x86_64) + source.from('src/main') + privateHeaders.setFrom('src/main') + dependencies { implementation project(':CosmicEngine') } +} + +// Nom du projet du module de scripts (adapter si renommé dans settings.gradle) +def scriptsProject = ':ScriptsModule' +evaluationDependsOn(scriptsProject) // pour retrouver ses tâches de link + +def fsOps = project.services.get(FileSystemOperations) +def runtimeDir = rootProject.ext.runtimeDir +def assetDir = rootProject.ext.assetDir // CosmicEngine/src/main/resources +def appAssetDir = file('src/main/resources') // assets propres à cette application + +// Le module de scripts est chargé dynamiquement par le moteur (dlopen/LoadLibrary) : il est copié, pas lié. +tasks.withType(InstallExecutable).configureEach { installTask -> + // installDebugLinux -> linkDebugLinux (le suffixe dépend des targetMachines) + // On prend le fichier produit par la tâche de link : plus de chemin à deviner. + def scriptsLib = project(scriptsProject).tasks + .named(name.replaceFirst('^install', 'link'), LinkSharedLibrary) + .flatMap { it.linkedFile } + // 'libs' = fichiers installés dans lib/ par la tâche (suivis par Gradle : dépendance + up-to-date). + libs.from(scriptsLib) + + doLast { + def destDir = installTask.installDirectory.get().dir('lib').asFile + destDir.mkdirs() + + // DLL/SO vcpkg (non récursif, ignore les liens cassés) + if (runtimeDir.exists()) { + runtimeDir.listFiles().each { f -> + if (f.isFile() && (f.name.endsWith('.dll') || f.name.endsWith('.dylib') || + f.name.endsWith('.so') || f.name.contains('.so.'))) { + java.nio.file.Files.copy(f.toPath(), new File(destDir, f.name).toPath(), + java.nio.file.StandardCopyOption.REPLACE_EXISTING) + } + } + } + // Assets du moteur (obligatoires), puis ceux de l'application (ajoutent / surchargent) + [assetDir, appAssetDir].each { dir -> + if (dir.exists()) { + fsOps.copy { + from dir + into destDir + } + } + } + } +} \ No newline at end of file diff --git a/ApplicationDemo/src/main/main.cpp b/ApplicationDemo/src/main/main.cpp new file mode 100644 index 0000000..a123a3a --- /dev/null +++ b/ApplicationDemo/src/main/main.cpp @@ -0,0 +1,33 @@ + +//#include "Engine/Headers/Core.hpp" +//#include "Engine/Headers/Components.hpp" + +//#include + +/*#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include */ + +#include "Engine/Core/Kernel/CKernel.hpp" + +int main(int argc, char** argv) { + // test(); + using namespace CosmicCore; + CKernel g("Mon jeu", "Jeu"); + g.start(); + g.loop(); + return 0; +} \ No newline at end of file diff --git a/ApplicationDemo/src/main/resources/assets/475uja.jpg b/ApplicationDemo/src/main/resources/assets/475uja.jpg new file mode 100644 index 0000000..1a7cbf5 Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/475uja.jpg differ diff --git a/ApplicationDemo/src/main/resources/assets/F.O.O.L - Criminals.ogg b/ApplicationDemo/src/main/resources/assets/F.O.O.L - Criminals.ogg new file mode 100644 index 0000000..4c19563 Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/F.O.O.L - Criminals.ogg differ diff --git a/ApplicationDemo/src/main/resources/assets/ccccc.png b/ApplicationDemo/src/main/resources/assets/ccccc.png new file mode 100644 index 0000000..ee8d27c Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/ccccc.png differ diff --git a/ApplicationDemo/src/main/resources/assets/exotique-1_0.jpg b/ApplicationDemo/src/main/resources/assets/exotique-1_0.jpg new file mode 100644 index 0000000..92e44c3 Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/exotique-1_0.jpg differ diff --git a/ApplicationDemo/src/main/resources/assets/scenes/scene_menu.json b/ApplicationDemo/src/main/resources/assets/scenes/scene_menu.json new file mode 100644 index 0000000..c605b5b --- /dev/null +++ b/ApplicationDemo/src/main/resources/assets/scenes/scene_menu.json @@ -0,0 +1,139 @@ +{ + "name" : "Scene test", + "description": "Scene de test", + "entities": [ + ], + "entities2D": [ + { + "entityref": 1, + "parent": null, + "children": [], + "name": "Camera2D", + "description": "Une camera en 2D", + "components": { + "transform": { + "position": [0,0], + "size": [1,1], + "scale": [1,1], + "pivot" : [0,0], + "rotation": 0.0, + "anchor": [0,0], + "zorder": 0, + "visible": true + }, + "camera": + { + "zoom": 1.0 + } + } + }, + { + "entityref": 2, + "parent": 5, + "children": [], + "name": "QuitButton_text", + "description": "", + "components": { + "transform": { + "position": [0, 0], + "size": [50,50], + "scale": [1,1], + "pivot" : [0,0], + "rotation": 0.0, + "anchor": [0,0], + "zorder": 1, + "visible": true + }, + "text": + { + "text": "Quit game", + "shader": "ui_text", + "color": [1,1,1,1], + "font": "assets/fonts/Arial" + } + } + }, + { + "entityref": 5, + "parent": null, + "children": [2], + "name": "QuitButton_col", + "description": "", + "components": { + "transform": { + "position": [320, 386], + "size": [60,35], + "scale": [5,2], + "pivot" : [0,0], + "anchor": [0,0], + "rotation": 0.0, + "zorder": 0, + "visible": true + }, + "collider" : { + "type": 0 + }, + "renderer": + { + "model": "assets/models/2D/rectangle.json", + "shader": "ui" + }, + "script": ["QuitHandler"] + } + }, + { + "entityref": 3, + "parent": 4, + "children": [], + "name": "PlayButton_text", + "description": "", + "components": { + "transform": { + "position": [0, 0], + "size": [50,50], + "scale": [1,1], + "pivot" : [0,0], + "rotation": 0.0, + "anchor": [0,0], + "zorder": 1, + "visible": true + }, + "text": + { + "text": "Play", + "shader": "ui_text", + "color": [1,1,1,1], + "font": "assets/fonts/Arial" + } + } + }, + { + "entityref": 4, + "parent": null, + "children": [3], + "name": "PlayButton_col", + "description": "", + "components": { + "transform": { + "position": [250, 186], + "size": [70,30], + "scale": [2,2], + "pivot" : [0,0], + "rotation": 0.0, + "anchor": [0,0], + "zorder": 0, + "visible": true + }, + "collider" : { + "type": 0 + }, + "renderer": + { + "model": "assets/models/2D/rectangle.json", + "shader": "ui" + }, + "script": ["LaunchSceneTest"] + } + } + ] +} \ No newline at end of file diff --git a/ApplicationDemo/src/main/resources/assets/scenes/scene_test.json b/ApplicationDemo/src/main/resources/assets/scenes/scene_test.json new file mode 100644 index 0000000..d828228 --- /dev/null +++ b/ApplicationDemo/src/main/resources/assets/scenes/scene_test.json @@ -0,0 +1,123 @@ +{ + "name" : "Scene test", + "description": "Scene de test", + "entities": [ + { + "entityref": 0, + "name": "Cube", + "description": "Un cube", + "parent" : null, + "children": [], + "components": { + "transform": { + "position": [0,0,0], + "rotation": [0,0,0], + "scale": [1,1,1] + }, + "renderer": + { + "model": "assets/models/3D/cube.glb", + "shader": "triangle", + "albedo": "assets/shrekt.png" + } + } + }, + { + "entityref": 3, + "name": "Light", + "description": "A light", + "parent" : null, + "children": [], + "components": { + "transform": { + "position": [2,4,-1], + "rotation": [0,0,0], + "scale": [1,1,1] + }, + "light": + { + "type": 1, + "color": [1,1,1], + "intensity": 10.0, + "range": 50, + "attenuation": 1, + "innerangle": 15, + "outerangle": 90, + "castshadow": false + } + } + }, + { + "entityref": 1, + "name": "Camera", + "description": "Une camera", + "parent" : null, + "children": [], + "components": { + "transform": { + "position": [0,0,5], + "rotation": [0,0,0], + "scale": [1,1,1] + }, + "camera": + { + "fov": 75, + "near": 0.1, + "far": 100 + }, + "script": ["CExampleScript"] + } + } + ], + "entities2D": [ + { + "entityref": 2, + "parent": null, + "children": [], + "name": "Camera2D", + "description": "Une camera en 2D", + "components": { + "transform": { + "position": [0,0], + "size": [1,1], + "scale": [1,1], + "pivot" : [0,0], + "anchor": [0,0], + "rotation": 0.0, + "zorder": 0, + "visible": true + }, + "camera": + { + "zoom": 1.0 + } + } + }, + { + "entityref": 4, + "parent": null, + "children": [], + "name": "Texte", + "description": "Du texte", + "components": { + "transform": { + "position": [200, 360], + "size": [50,50], + "scale": [1,1], + "pivot" : [0,0], + "anchor": [0,0], + "rotation": 0.0, + "zorder": 0, + "visible": true + }, + "text": + { + "text": "Test de la scene avec texte en 2D", + "shader": "ui_text", + "color": [1,1,1,1], + "font": "assets/fonts/Arial" + } + } + } + ] +} \ No newline at end of file diff --git a/ApplicationDemo/src/main/resources/assets/shrekt.png b/ApplicationDemo/src/main/resources/assets/shrekt.png new file mode 100644 index 0000000..803ae4e Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/shrekt.png differ diff --git a/ApplicationDemo/src/main/resources/assets/spaceEngine.png b/ApplicationDemo/src/main/resources/assets/spaceEngine.png new file mode 100644 index 0000000..a7208a1 Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/spaceEngine.png differ diff --git a/ApplicationDemo/src/main/resources/assets/spaceEngineIcon.png b/ApplicationDemo/src/main/resources/assets/spaceEngineIcon.png new file mode 100644 index 0000000..d3cf38c Binary files /dev/null and b/ApplicationDemo/src/main/resources/assets/spaceEngineIcon.png differ diff --git a/CosmicEngine/build.gradle b/CosmicEngine/build.gradle new file mode 100644 index 0000000..984f31f --- /dev/null +++ b/CosmicEngine/build.gradle @@ -0,0 +1,32 @@ +plugins { + id 'cpp-library' + id 'cpp-unit-test' +} +apply from: rootProject.file('gradle/common.gradle') + +library { + baseName = 'CosmicEngine' + linkage = [Linkage.SHARED] + targetMachines.add(machines.windows.x86_64) + targetMachines.add(machines.linux.x86_64) + source.from('src/main') + publicHeaders.from('src/main') // visibles par App et Scripts +} + +// Seul le moteur lie les libs vcpkg (SDL, Jolt, assimp...). +tasks.withType(AbstractLinkTask).configureEach { + dependsOn ':vcpkg' + linkerArgs.addAll("-L${rootProject.ext.vcpkgLibDir}", "@${rootProject.ext.vcpkgRsp}") + if (!org.gradle.internal.os.OperatingSystem.current().isWindows()) { + linkerArgs.add('-lopenal') + } +} + +// Pour les tests +tasks.withType(RunTestExecutable).configureEach { + args("--gtest_color=yes") + args("--gtest_output=xml:report.xml") + // Les DLL/SO vcpkg doivent être trouvables à l'exécution des tests. + def pathVar = org.gradle.internal.os.OperatingSystem.current().isWindows() ? 'PATH' : 'LD_LIBRARY_PATH' + environment pathVar, rootProject.ext.runtimeDir.absolutePath + File.pathSeparator + (System.getenv(pathVar) ?: '') +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.cpp b/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.cpp new file mode 100644 index 0000000..bc966a1 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.cpp @@ -0,0 +1,25 @@ +#include "CAbstractComponent.hpp" + +namespace CosmicCore { + constexpr std::string typeToString(EComponentType type) + { + switch (type) { + case EComponentType::COMPONENT_SCRIPT: + return "Script"; + case EComponentType::COMPONENT_CAMERA: + return "Camera"; + case EComponentType::COMPONENT_LIGHT: + return "Light"; + case EComponentType::COMPONENT_RIGIDBODY: + return "Rigidbody"; + case EComponentType::COMPONENT_COLLIDER: + return "Collider"; + case EComponentType::COMPONENT_CUSTOM: + return "Custom"; + case EComponentType::COMPONENT_META: + return "Meta"; + default: + return "UNKNOWN_COMPONENT"; + } + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.hpp b/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.hpp new file mode 100644 index 0000000..273d13b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/CAbstractComponent.hpp @@ -0,0 +1,50 @@ +#ifndef CABSTRACT_COMPONENT_HPP +#define CABSTRACT_COMPONENT_HPP + +#include "../../Utils/JsonParser/CSerializable.hpp" +#include "../Entity/CEntity.hpp" +namespace CosmicCore { + + /** + * @brief Enum representing every type of component that can be created. + */ + enum class EComponentType : unsigned char { + COMPONENT_SCRIPT, + COMPONENT_CAMERA, + COMPONENT_LIGHT, + COMPONENT_RIGIDBODY, + COMPONENT_COLLIDER, + COMPONENT_CUSTOM, + COMPONENT_RENDERER, + COMPONENT_META, + COMPONENT_COUNT + }; + + constexpr std::string typeToString(EComponentType type); + + class CAbstractComponent : public CSerializable{ + public: + CAbstractComponent(CEntity& entity): m_owningEntity(entity){}; + CAbstractComponent(CAbstractComponent&& other) = default; + CAbstractComponent& operator=(CAbstractComponent&&) = default; + + virtual ~CAbstractComponent() = default; + + CEntity& getEntity() { + return m_owningEntity; + } + + const CEntity& getEntity() const { + return m_owningEntity; + } + + virtual nlohmann::json to_json() = 0; + private: + /** + * @brief The entity to which the component is linked. + */ + CEntity m_owningEntity; + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera.hpp b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera.hpp new file mode 100644 index 0000000..6b69e27 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera.hpp @@ -0,0 +1,158 @@ +#ifndef CCAMERA_HPP +#define CCAMERA_HPP + +#include "../CAbstractComponent.hpp" +//pour vulkan depth 0-1 (opengl [-1,1]) +#define GLM_FORCE_DEPTH_ZERO_TO_ONE +#include +#include +#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include "../Geometry/CTransform.hpp" +namespace CosmicCore { + +class CCamera : public CAbstractComponent { +private: + // paramètres de la caméra + float m_fov = 45.0f; + float m_near = 0.1f; + float m_far = 1000.0f; + float m_aspect = 16.0f / 9.0f; + + // matrices calculées + glm::mat4 m_view = glm::mat4(1.0f); + glm::mat4 m_projection = glm::mat4(1.0f); + + // GPU + struct CameraUBOData { + glm::mat4 view; + glm::mat4 projection; + glm::vec4 position; + }; + + std::array m_uniformBuffers; + std::array m_mappedData{}; + std::array m_descriptorSets; + + void recalcProjection() { + m_projection = glm::perspective(glm::radians(m_fov), m_aspect, m_near, m_far); + // Vulkan a l'axe Y inversé par rapport à OpenGL + m_projection[1][1] *= -1; + } + +public: + CCamera(CEntity& entity) : CAbstractComponent(entity) { + recalcProjection(); + } + + ~CCamera(){ + destroy(); + } + + void setFov(float fov) { + m_fov = fov; + recalcProjection(); + } + + void setAspect(float aspect) { + m_aspect = aspect; + recalcProjection(); + } + + void setNearFar(float near, float far) { + m_near = near; + m_far = far; + recalcProjection(); + } + + // getters + glm::mat4 getView(const CTransform& transform) const { + /*glm::quat q = transform.getOrientation(); + glm::vec3 position = transform.getCenter(); + + // rotation inverse (conjugué du quaternion) + translation inverse + glm::mat4 rotInverse = glm::toMat4(glm::conjugate(q)); + glm::mat4 transInverse = glm::translate(glm::mat4(1.0f), -position);*/ + + //return rotInverse * transInverse; + return glm::inverse(transform.getInheritedTransformation()); + } + glm::mat4 getProjection() const { return m_projection; } + + // GPU + void initUniformBuffer(VmaAllocator allocator) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + VkBufferCreateInfo bufferInfo{}; + bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferInfo.size = sizeof(CameraUBOData); + bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VmaAllocationInfo info{}; + vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, + &m_uniformBuffers[i].buffer, + &m_uniformBuffers[i].allocation, + &info); + m_mappedData[i] = info.pMappedData; + + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate( + *api->getCameraLayout() + ); + + vk::DescriptorBufferInfo descriptorBufferInfo{ + vk::Buffer(m_uniformBuffers[i].buffer), + 0, + sizeof(CameraUBOData) + }; + vk::WriteDescriptorSet descriptorWrite{ + *m_descriptorSets[i].set, + 0, 0, 1, + vk::DescriptorType::eUniformBuffer, + {}, &descriptorBufferInfo + }; + static_cast(api->getDevice())->updateDescriptorSets(descriptorWrite, {}); + } + } + + void destroyUniformBuffer(VmaAllocator allocator) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + api->getDescriptorPoolManager().free(m_descriptorSets[i]); + vmaDestroyBuffer(allocator, m_uniformBuffers[i].buffer, + m_uniformBuffers[i].allocation); + } + } + + void updateUniformBuffer(uint32_t frameIndex, const CTransform& transform) { + glm::mat4 worldTransform = transform.getInheritedTransformation(); + glm::vec3 worldPosition = glm::vec3(worldTransform[3]); + CameraUBOData data{ getView(transform), m_projection, glm::vec4(worldPosition, 1.0f)}; + memcpy(m_mappedData[frameIndex], &data, sizeof(data)); + } + + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } + + void destroy() + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + + api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex()); + api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex()); + } + } + + nlohmann::json to_json(){ + return nlohmann::json(); + }; +}; + +} // namespace CosmicCore +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.cpp b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.cpp new file mode 100644 index 0000000..86a5a4b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.cpp @@ -0,0 +1,15 @@ +#include "CCamera2D.hpp" +#include "Engine/Core/Kernel/CKernel.hpp" + +namespace CosmicCore { + void CCamera2D::recalcProjection() { + //todo + float width = CKernelBase::instance()->getWindowWidth(); + float height = CKernelBase::instance()->getWindowHeight(); + //m_projection = glm::ortho(0.0f, width, 0.0f, height, -1.0f, 1.0f); + //m_projection //= glm::perspective(glm::radians(m_fov), m_aspect, m_near, m_far); + m_projection = glm::ortho(0.0f, width, 0.0f, height, -1.0f, 1.0f); + + //m_projection[1][1] *= -1; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.hpp b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.hpp new file mode 100644 index 0000000..3d94e8f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Camera/CCamera2D.hpp @@ -0,0 +1,117 @@ +#ifndef CCAMERA2D_HPP +#define CCAMERA2D_HPP + +#include "../CAbstractComponent.hpp" +//pour vulkan depth 0-1 (opengl [-1,1]) +#include +#include +#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include "../Geometry/CTransform2D.hpp" +namespace CosmicCore { + + //TODO LES MAJ REELLES DUN MOUVEMENT TRANSFORM + //AJOUT DONC DE LA VUE ET AUTRE PARAM + //Pour le moment ne gère qu'une caméra fixe (UI) +class CCamera2D : public CAbstractComponent { +private: + glm::mat4 m_projection = glm::mat4(1.0f); + + // GPU + struct Camera2DUBOData { + glm::mat4 projection; + }; + + std::array m_uniformBuffers; + std::array m_mappedData{}; + std::array m_descriptorSets; + + void recalcProjection(); + +public: + CCamera2D(CEntity& entity) : CAbstractComponent(entity) { + recalcProjection(); + } + + ~CCamera2D(){ + destroy(); + } + + glm::mat4 getProjection() const { return m_projection; } + + // GPU + void initUniformBuffer(VmaAllocator allocator) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + VkBufferCreateInfo bufferInfo{}; + bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferInfo.size = sizeof(Camera2DUBOData); + bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VmaAllocationInfo info{}; + vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, + &m_uniformBuffers[i].buffer, + &m_uniformBuffers[i].allocation, + &info); + m_mappedData[i] = info.pMappedData; + + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate( + *api->getProjection2DLayout() + ); + + vk::DescriptorBufferInfo descriptorBufferInfo{ + vk::Buffer(m_uniformBuffers[i].buffer), + 0, + sizeof(Camera2DUBOData) + }; + vk::WriteDescriptorSet descriptorWrite{ + *m_descriptorSets[i].set, + 0, 0, 1, + vk::DescriptorType::eUniformBuffer, + {}, &descriptorBufferInfo + }; + static_cast(api->getDevice())->updateDescriptorSets(descriptorWrite, {}); + } + } + + void destroyUniformBuffer(VmaAllocator allocator) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + api->getDescriptorPoolManager().free(m_descriptorSets[i]); + vmaDestroyBuffer(allocator, m_uniformBuffers[i].buffer, + m_uniformBuffers[i].allocation); + } + } + + void updateUniformBuffer(uint32_t frameIndex, const CTransform2D& transform) { + + Camera2DUBOData data{ m_projection}; + memcpy(m_mappedData[frameIndex], &data, sizeof(data)); + } + + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } + + void destroy() + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + + api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex()); + api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex()); + } + } + + nlohmann::json to_json(){ + return nlohmann::json(); + }; +}; + +} // namespace CosmicCore +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CAbstractCollider.cpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CAbstractCollider.cpp new file mode 100644 index 0000000..e69de29 diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CAbstractCollider.hpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CAbstractCollider.hpp new file mode 100644 index 0000000..e9ffc5b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Collider/CAbstractCollider.hpp @@ -0,0 +1,11 @@ +#ifndef CABSTRACTCOLLIDER_HPP +#define CABSTRACTCOLLIDER_HPP +#include "../CAbstractComponent.hpp" +namespace CosmicCore { + class CAbstractCollider: public CAbstractComponent + { + public: + CAbstractCollider(CEntity& entity): CAbstractComponent(entity){}; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.cpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.cpp new file mode 100644 index 0000000..847dc9a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.cpp @@ -0,0 +1,78 @@ +#include "CCollider.hpp" +#include "CAbstractCollider.hpp" +#include +#include +#include +#include +#include +namespace CosmicCore { + CCollider::CCollider(CEntity& e, EColliderType type): CAbstractCollider(e), m_type(type) + { + buildDefaultShape(); + } + + void CCollider::buildFromMesh(CMesh* mesh) { + if (m_type == EColliderType::ConvexHull) { + JPH::ConvexHullShapeSettings settings; + for (auto& v : mesh->getVertices()) + settings.mPoints.push_back({v.m_position.x, + v.m_position.y, + v.m_position.z}); + m_shape = settings.Create().Get(); + } + /*else if (m_type == EColliderType::Mesh) { + // pour les statiques + JPH::MeshShapeSettings settings; + // remplir triangles depuis vertices + indices + m_shape = settings.Create().Get(); + }*/ + } + + void CCollider::buildDefaultShape() + { + switch (m_type) { + case CosmicCore::EColliderType::Box: + setBoxSize({1.0f,1.0f,1.0f}); + break; + case EColliderType::Sphere: + setSphereRadius(1.0f); + break; + case EColliderType::Capsule: + setCapsule(2.0f, 1.0f); + break; + case EColliderType::ConvexHull: + break; + case EColliderType::Mesh: + break; + case EColliderType::Compound: + break; + } + } + + // override manuel de la taille + void CCollider::setBoxSize(glm::vec3 size) { + m_type = EColliderType::Box; + m_shape = new JPH::BoxShape(JPH::Vec3(size.x, size.y, size.z)); + } + + void CCollider::setSphereRadius(float radius) { + m_type = EColliderType::Sphere; + m_shape = new JPH::SphereShape(radius); + } + + void CCollider::setCapsule(float halfHeight, float radius) { + m_type = EColliderType::Capsule; + m_shape = new JPH::CapsuleShape(halfHeight, radius); + } + + // build depuis le mesh du renderer si présent + void CCollider::buildFromRenderer() { + /*auto& registry = getEntity().getRegistry(); + if (!registry.all_of(getEntity().getHandle())) return; + + auto* model = registry.get(getEntity().getHandle()).getModel(); + if (model->getMeshes().empty()) return; + + buildFromMesh(model->getMeshes()[0]);*/ + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.hpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.hpp new file mode 100644 index 0000000..6d880dc --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider.hpp @@ -0,0 +1,42 @@ +#ifndef CCOLLIDER_HPP +#define CCOLLIDER_HPP +#include "CAbstractCollider.hpp" +#include +#include +#include "../../Systems/Graphics/Data/Mesh/CMesh.hpp" +#include "nlohmann/json_fwd.hpp" + +namespace CosmicCore { + + enum class EColliderType { + Box, + Sphere, + Capsule, + ConvexHull, + Mesh, + Compound + }; + + class CCollider : public CAbstractCollider{ + private: + EColliderType m_type; + JPH::ShapeRefC m_shape = nullptr; + public: + CCollider(CEntity& e, EColliderType type); + + void buildFromMesh(CMesh* mesh); + void buildDefaultShape(); + + JPH::ShapeRefC getShape() const { return m_shape; } + EColliderType getType() const { return m_type; } + + void setCapsule(float halfHeight, float radius); + void setSphereRadius(float radius); + void setBoxSize(glm::vec3 size); + void buildFromRenderer(); + + nlohmann::json to_json(){return nlohmann::json();}; + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.cpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.cpp new file mode 100644 index 0000000..a29be32 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.cpp @@ -0,0 +1,29 @@ +#include "CCollider2D.hpp" +#include "Engine/Core/Component/Geometry/CTransform2D.hpp" +#include "Engine/Core/Kernel/CKernel.hpp" + +namespace CosmicCore { + bool CCollider2D::shapeContains(glm::vec2 point) const { + auto& registry = getEntity().getRegistry(); + + // récupère le transform + auto& transform = registry.registry.get(*getEntity()); + + glm::vec2 abs = transform.getAbsolutePosition(); + float y = CKernelBase::instance()->getWindowHeight(); + + switch (m_shape) { + + case E2DShape::RECTANGLE: { + bool isX = point.x >= abs.x - transform.getSize().x*transform.getScale().x * 0.5f && point.x <= abs.x + transform.getSize().x*transform.getScale().x * 0.5f; + bool isY = point.y >= abs.y - transform.getSize().y*transform.getScale().y * 0.5f && point.y <= abs.y + transform.getSize().y*transform.getScale().y * 0.5f; + return isX && isY; + } + case E2DShape::CIRCLE: break;//TODO + case E2DShape::TEXT: break; + case E2DShape::POLYGON: break; + break; + } + return false; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.hpp b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.hpp new file mode 100644 index 0000000..e94ee7c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Collider/CCollider2D.hpp @@ -0,0 +1,31 @@ +#ifndef CCOLLIDER2D_HPP +#define CCOLLIDER2D_HPP + +#include "Engine/Core/Component/CAbstractComponent.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "glm/ext/vector_float2.hpp" +namespace CosmicCore { + + enum class E2DShape + { + RECTANGLE, + CIRCLE, + TEXT, + POLYGON + }; + + class CCollider2D: public CAbstractComponent + { + private: + E2DShape m_shape = E2DShape::RECTANGLE; + public: + CCollider2D(CEntity& entity, E2DShape shape): CAbstractComponent(entity), m_shape(shape){}; + + bool shapeContains(glm::vec2 point) const; + nlohmann::json to_json(){return nlohmann::json();}; + + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.cpp b/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.cpp new file mode 100644 index 0000000..f811c44 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.cpp @@ -0,0 +1,34 @@ +#include "CAbstractCustomComponent.hpp" + +namespace CosmicCore { + CAbstractCustomComponent::CAbstractCustomComponent(CEntity& entity): CAbstractComponent(entity) + { + } + + void CAbstractCustomComponent::addProperty(std::string name, float value) + { + m_properties[name] = value; + } + + float CAbstractCustomComponent::getProperty(std::string name) + { + return m_properties[name]; + } + + void CAbstractCustomComponent::setProperty(std::string name, float value) + { + if (m_properties.count(name) != 0) + { + m_properties[name] = value; + } + } + + nlohmann::json CAbstractCustomComponent::to_json() + { + nlohmann::json j; + j["ComponentType"] = EComponentType::COMPONENT_CUSTOM; + return j; + } +} + + diff --git a/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.hpp b/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.hpp new file mode 100644 index 0000000..0b4eced --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Custom/CAbstractCustomComponent.hpp @@ -0,0 +1,40 @@ +#ifndef CABSTRACTCUSTOMCOMPONENT_HPP +#define CABSTRACTCUSTOMCOMPONENT_HPP + +#include "../CAbstractComponent.hpp" +#include + +namespace CosmicCore { + /** + * @brief Class representing a Data Dictonnary. Is a component. + */ + class CAbstractCustomComponent : public CAbstractComponent{ + private: + std::unordered_map m_properties; + public: + + /** + * @brief CData's default constructor, disabled. + */ + CAbstractCustomComponent() = delete; + virtual ~CAbstractCustomComponent() = default; + + /** + * @brief CData's constructor. + * @param[in, out] entity The entity to which we want to attach specific informations. + */ + CAbstractCustomComponent(CEntity& entity); + + + void addProperty(std::string name, float value); + + float getProperty(std::string name); + + void setProperty(std::string name, float value); + + nlohmann::json to_json(); + }; +} + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.cpp b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.cpp new file mode 100644 index 0000000..f7ace30 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.cpp @@ -0,0 +1,231 @@ +#include "CTransform.hpp" +#include "../../Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include "../Relationships/CRelationship.hpp" +namespace CosmicCore +{ + + void CTransform::calcTranslation(void) { + m_translation = glm::translate(glm::mat4(1.0f), m_center); + } + + void CTransform::calcRotation(void) { + m_rotation = glm::toMat4(m_orientation); + } + + void CTransform::calcHomothety(void) { + m_homothety = glm::scale(glm::mat4(1.0f), m_scale); + } + + void CTransform::calcTranformation(void) { + m_transformation = m_translation * m_rotation * m_homothety; + } + + CTransform::CTransform(CEntity& entity) : CAbstractComponent(entity), + m_center(0.0f, 0.0f, 0.0f), + m_scale(1.0f, 1.0f, 1.0f), + m_orientation(glm::identity()), + m_observers() { + calcTranslation(); + calcRotation(); + calcHomothety(); + calcTranformation(); + } + + CTransform::CTransform(CEntity& entity, glm::vec3 center, glm::vec3 scale, glm::vec3 eulerAngle) : CAbstractComponent(entity), + m_center(center), + m_scale(scale), + m_orientation(eulerAngle), + m_observers() { + calcTranslation(); + calcRotation(); + calcHomothety(); + calcTranformation(); + } + + CTransform::~CTransform() + { + destroyUniformBuffer(); + } + + glm::mat4 CTransform::getTranslation(void) const { + return m_translation; + } + + glm::mat4 CTransform::getRotation(void) const { + return m_rotation; + } + + glm::mat4 CTransform::getHomothety(void) const { + return m_homothety; + } + + glm::mat4 CTransform::getTransormation(void) const { + return m_transformation; + } + + glm::mat4 CTransform::getInheritedTransformation(void) const { + auto& registry = getEntity().getRegistry(); + + if (!registry().all_of(*getEntity())) + return m_transformation; + + auto& rel = registry().get(*getEntity()); + + if (!rel.getParent().has_value()) + return m_transformation; + + auto& parentTransform = registry().get(rel.getParent().value()); + return parentTransform.getInheritedTransformation() * m_transformation; + } + + + glm::vec3 CTransform::getCenter(void) const { + return m_center; + } + + glm::vec3* CTransform::getCenterReference(void) + { + return &m_center; + } + + glm::vec3 CTransform::getScale(void) const { + return m_scale; + } + + glm::vec3& CTransform::getScalePtr(void) + { + return m_scale; + } + + glm::vec3 CTransform::getEulerAngle(void) const { + return glm::eulerAngles(m_orientation); + } + + glm::quat CTransform::getOrientation(void) const + { + return m_orientation; + } + + void CTransform::setCenter(glm::vec3 newCenter) { + m_center = newCenter; + calcTranslation(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onCenterChange(); + } + } + + void CTransform::setUniformScale(float newScale) { + m_scale = glm::vec3(newScale, newScale, newScale); + calcHomothety(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onScaleChange(); + } + } + + void CTransform::setScale(glm::vec3 newScale) { + m_scale = newScale; + calcHomothety(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onScaleChange(); + } + } + + void CTransform::rotate(glm::vec3 axis, float angle) { + m_orientation = glm::rotate(m_orientation, angle, axis); + calcRotation(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onRotationChange(); + } + } + + void CTransform::setEulerAngle(glm::vec3 newEulerAngle) { + m_orientation = glm::quat(newEulerAngle); + calcRotation(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onRotationChange(); + } + } + + void CTransform::setQuaternion(glm::quat newQuaternion) { + m_orientation = newQuaternion; + calcRotation(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onRotationChange(); + } + } + + void CTransform::forward(glm::vec3 value) { + glm::vec3 relValue = m_orientation * value; + m_center += relValue; + calcTranslation(); + calcTranformation(); + for (auto const& obs : m_observers) { + if(auto ptrObs = obs.lock()) + ptrObs->onCenterChange(); + } + } + + void CTransform::addObserver(std::weak_ptr newObserver) { + m_observers.emplace_back(newObserver); + } + + void CTransform::removeObserver(std::weak_ptr obs) + { + //TODO + } + + void CTransform::updateUniformBuffer(uint32_t frameIndex) { + auto data{ getInheritedTransformation() }; // utilise la transformation héritée + memcpy(m_mappedData[frameIndex], &data, sizeof(data)); + } + + void CTransform::initUniformBuffer(VmaAllocator allocator) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + VkBufferCreateInfo bufferInfo{}; + bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferInfo.size = sizeof(glm::mat4); + bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VmaAllocationInfo info{}; + vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, + &m_uniformBuffers[i].buffer, + &m_uniformBuffers[i].allocation, + &info); + m_mappedData[i] = info.pMappedData; + + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(api->getTransformLayout()); + + vk::DescriptorBufferInfo descriptorBufferInfo{vk::Buffer(m_uniformBuffers[i].buffer), 0, sizeof(glm::mat4)}; + vk::WriteDescriptorSet descriptorWrite{m_descriptorSets[i].set, 0, 0,1, vk::DescriptorType::eUniformBuffer, {}, &descriptorBufferInfo}; + static_cast(api->getDevice())->updateDescriptorSets(descriptorWrite, {}); + } + } + + void CTransform::destroyUniformBuffer() { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + + api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex()); + api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex()); + } + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.hpp b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.hpp new file mode 100644 index 0000000..1ba8124 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform.hpp @@ -0,0 +1,267 @@ +#ifndef CTRANSFORM_HPP +#define CTRANSFORM_HPP + +#include "../../Observer/CTransformObserver.hpp" +#include "../CAbstractComponent.hpp" +#include + +#include +#include +#include +#include "../../Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp" +#include "../../Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp" + +namespace CosmicCore +{ + /** + * @brief Class representing the transformations of the object in the space. + */ + class CTransform : public CAbstractComponent { + private: + + /** + * @brief A 3D vector representing the position of the entity . + */ + glm::vec3 m_center; + + /** + * @brief A 3D vector representing the scale of the entity on each axis. + */ + glm::vec3 m_scale; + + /** + * @brief A quaternion which represent the rotation. + */ + glm::quat m_orientation; + + /** + * @brief A mat4 matrix representing the translation transformation. + */ + glm::mat4 m_translation; + + /** + * @brief A mat4 matrix representing the rotation transformation. + */ + glm::mat4 m_rotation; + + /** + * @brief A mat4 representing the scale of the object on each axis. + */ + glm::mat4 m_homothety; + + /** + * @brief Full transformation of the object. + * result of m_translation * m_rotation * m_homothety. + */ + glm::mat4 m_transformation; + + /** + * @brief a list of observer. + */ + std::vector> m_observers; + + /** + * @brief Compute the translation matrix. + */ + void calcTranslation(void); + + /** + * @brief Compute the rotation matrix. + */ + void calcRotation(void); + + /** + * @brief Compute the homothety matrix. + */ + void calcHomothety(void); + + /** + * @brief Compute the full transformation of the object. + */ + void calcTranformation(void); + + std::array m_uniformBuffers; + std::array m_mappedData{}; + std::array m_descriptorSets; + public: + + /** + * @brief CTransform's constructor. Assign the center to (0,0,0) and the scale to (1,1,1). + * @param[in, out] m_entity The entity to which the transform belongs. + */ + CTransform(CEntity& m_entity); + + ~CTransform(); + + CTransform(CTransform&&) = default; + CTransform& operator=(CTransform&&) = default; + + CTransform(const CTransform&) = delete; + CTransform& operator=(const CTransform&) = delete; + /** + * @brief CTransform's constructor. + * @param[in, out] m_entity The entity to which the transform belongs. + * @param[in] center A 3D vector which represent the initial position of the entity. + * @param[in] scale A 3D vector which represent the scale of the entity on each axis. + * @param[in] eulerAngle A 3D vector wich represent the initial rotation of the entity. + */ + CTransform(CEntity& m_entity, glm::vec3 center, glm::vec3 scale, glm::vec3 eulerAngle); + + /** + * @brief Getter to the translation matrix. + * @return A mat4 equal to m_translation. + */ + glm::mat4 getTranslation(void) const; + + /** + * @brief Getter to the rotation matrix. + * @return A mat4 equal to m_rotation. + */ + glm::mat4 getRotation(void) const; + + /** + * @brief Getter to the homothety. + * @return A mat4 equal to m_homothety . + */ + glm::mat4 getHomothety(void) const; + + /** + * @brief Getter to the full transformation. + * @return A mat4 equal to m_transformation. + */ + glm::mat4 getTransormation(void) const; + + /** + * @brief Getter to the full inherited transformation. + * Return the current entity's transformation if there is no parent or the transformation of each parent recursively times the current transformation. + * @return A mat4 representing the actual transformation of the entity (in the global scale). + */ + glm::mat4 getInheritedTransformation(void) const; + + /** + * @brief Getter to the entity's center. + * @return The 3D vector of the position. + */ + glm::vec3 getCenter(void) const; + + /** + * @brief Getter to the entity's center by its pointer. + * @return The 3D vector of the position. + */ + glm::vec3* getCenterReference(void); + + + /** + * @brief Getter to the scale. + * @return The 3D vector of the scale. + */ + glm::vec3 getScale(void) const; + + glm::vec3& getScalePtr(void); + + /** + * @brief Getter to the angles of the rotation on each axis. + * @return The 3D vector of the rotation angles, determining the orientation of the object. + */ + glm::vec3 getEulerAngle(void) const; + + + /** + * @brief Getter to the quaternion. + * @return A quaternion representing the orientation of the object. + */ + glm::quat getOrientation(void) const; + + /** + * @brief Setter of the position. + * @param[in] newCenter The new position of the object. + */ + void setCenter(glm::vec3 newCenter); + + /** + * @brief Setter of the uniform scale (same scale on the 3-axis). + * @param[in] newScale The new uniform scale. + */ + void setUniformScale(float newScale); + + /** + * @brief Setter of the scale. + * @param[in] newScale The new scale on each axis (3D vector). + */ + void setScale(glm::vec3 newScale); + + /** + * @brief Rotate the object on a given axis with the given angle. + * @param[in] axis The axis on which the rotation will occur. + * @param[in] angle The angle the rotation must reach. + */ + void rotate(glm::vec3 axis, float angle); + + /** + * @brief Translate the object on the given axis with the given value on each axis. + * @param[in] value The 3D vector of the translation. + */ + void forward(glm::vec3 value); + + /** + * @brief Setter of the Angles. + * @param[in] newEulerAngle The new orientation of the object. + */ + void setEulerAngle(glm::vec3 newEulerAngle); + + /** + * @brief Setter of the orientation quaternion. + * @param[in] newQuaternion The new orientation of the object. + */ + void setQuaternion(glm::quat newQuaternion); + + /** + * @brief Add an observer on the transform. Can be from any class if the said class is child class of CTransformObserver. + * @param[in, out] newObserver The observer to add. + */ + void addObserver(std::weak_ptr newObserver); + + /** + * @brief Remove an observer of the transform. Does nothing if the observer doesn't exist. + * @param[in, out] obs The observer to remove. + */ + void removeObserver(std::weak_ptr obs); + + nlohmann::json to_json() { + nlohmann::json j; + j["Position"]["x"] = m_center.x; + j["Position"]["y"] = m_center.y; + j["Position"]["z"] = m_center.z; + + j["Rotation"]["x"] = getEulerAngle().x; + j["Rotation"]["y"] = getEulerAngle().y; + j["Rotation"]["z"] = getEulerAngle().z; + + j["Scale"]["x"] = getScale().x; + j["Scale"]["y"] = getScale().y; + j["Scale"]["z"] = getScale().z; + return j; + }; + + static CTransform from_json(CEntity entity,nlohmann::json& j) + { + CTransform t(entity); + t.setCenter(glm::vec3(j["Position"]["x"], j["Position"]["y"], j["Position"]["z"])); + t.setEulerAngle(glm::vec3(j["Rotation"]["x"], j["Rotation"]["y"], j["Rotation"]["z"])); + t.setScale(glm::vec3(j["Scale"]["x"], j["Scale"]["y"], j["Scale"]["z"])); + return t; + }; + + void initUniformBuffer(VmaAllocator allocator); + void destroyUniformBuffer(); + void updateUniformBuffer(uint32_t frameIndex); + + VMABuffer& getUniformBuffer(uint32_t frameIndex) { + return m_uniformBuffers[frameIndex]; + }; + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + }; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.cpp b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.cpp new file mode 100644 index 0000000..979aa56 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.cpp @@ -0,0 +1,64 @@ +#include "CTransform2D.hpp" +#include "Engine/Core/Kernel/CKernel.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include + +namespace CosmicCore { + void CTransform2D::initUniformBuffer(VmaAllocator allocator) + { + if(m_gpuInitialized) return; + + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + VkBufferCreateInfo bufferInfo{}; + bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferInfo.size = sizeof(Transform2DUBO); + bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VmaAllocationInfo info{}; + vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, + &m_uniformBuffers[i].buffer, + &m_uniformBuffers[i].allocation, + &info); + m_mappedData[i] = info.pMappedData; + + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate(api->getTransform2DLayout()); + + vk::DescriptorBufferInfo descriptorBufferInfo{vk::Buffer(m_uniformBuffers[i].buffer), 0, sizeof(Transform2DUBO)}; + vk::WriteDescriptorSet descriptorWrite{m_descriptorSets[i].set, 0, 0,1, vk::DescriptorType::eUniformBuffer, {}, &descriptorBufferInfo}; + static_cast(api->getDevice())->updateDescriptorSets(descriptorWrite, {}); + } + m_gpuInitialized = true; + } + + void CTransform2D::destroyUniformBuffer() + { + if(!m_gpuInitialized) return; + + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + + api->destroyBuffer(m_uniformBuffers[i], api->getCurrentFrameIndex()); + api->destroyDescriptorSet(m_descriptorSets[i], api->getCurrentFrameIndex()); + } + } + + void CTransform2D::updateUniformBuffer(uint32_t frameIndex) + { + if (!m_gpuInitialized) return; + Transform2DUBO data{ + getMatrix(), + m_size, + m_zOrder, + 0.0f + }; + memcpy(m_mappedData[frameIndex], &data, sizeof(data)); + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.hpp b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.hpp new file mode 100644 index 0000000..1820a33 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Geometry/CTransform2D.hpp @@ -0,0 +1,107 @@ +#ifndef CTRANSFORM2D_HPP +#define CTRANSFORM2D_HPP + +#include "Engine/Core/Component/CAbstractComponent.hpp" +#include "Engine/Core/Component/Relationships/CRelationship.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp" +#include "glm/ext/matrix_float4x4.hpp" +#include "glm/ext/vector_float2.hpp" +#include "glm/gtx/transform.hpp" + +namespace CosmicCore { + + struct Transform2DUBO { + glm::mat4 transform; // matrice 2D + glm::vec2 size; // taille pour le shader SDF + float zOrder; // = 0 => pas utilse géré dans l'ordre de render de scene + float padding; // = 0 => pas utilse (pour l'instant ?) + }; + + class CTransform2D : public CAbstractComponent { + glm::vec2 m_position = {0, 0}; + glm::vec2 m_size = {100, 100}; + glm::vec2 m_scale = {1, 1}; // scale indépendant de la taille + glm::vec2 m_anchor = {0, 0}; // 0=topleft, 0.5=center, 1=bottomright + glm::vec2 m_pivot = {0, 0}; + float m_rotation = 0.0f; + float m_zOrder = 0.0f; // ordre de rendu UI + bool m_visible = true; + + std::array m_uniformBuffers; + std::array m_mappedData{}; + std::array m_descriptorSets; + bool m_gpuInitialized = false; + + public: + explicit CTransform2D(CEntity& entity) : CAbstractComponent(entity) {} + + ~CTransform2D() { + if (m_gpuInitialized) destroyUniformBuffer(); + } + + CTransform2D(CTransform2D&&) = default; + CTransform2D& operator=(CTransform2D&&) = default; + CTransform2D(const CTransform2D&) = delete; + CTransform2D& operator=(const CTransform2D&) = delete; + + CTransform2D& setPosition(glm::vec2 pos) { m_position = pos; return *this; } + CTransform2D& setSize(glm::vec2 size) { m_size = size; return *this; } + CTransform2D& setScale(glm::vec2 scale) { m_scale = scale;return *this; } + CTransform2D& setRotation(float rot) { m_rotation = rot; return *this; } + CTransform2D& setZOrder(float z) { m_zOrder = z; return *this; } + CTransform2D& setVisible(bool v) { m_visible = v; return *this; } + CTransform2D& setAnchor(glm::vec2 anchor) { m_anchor = anchor; return *this; } + CTransform2D& setPivot(glm::vec2 pivot) { m_pivot = pivot; return *this; } + + glm::vec2 getPosition() const { return m_position; } + glm::vec2 getSize() const { return m_size; } + glm::vec2 getScale() const { return m_scale; } + float getRotation() const { return m_rotation; } + float getZOrder() const { return m_zOrder; } + bool isVisible() const { return m_visible; } + + glm::vec2 getAbsolutePosition() const { + + auto& registry = getEntity().getRegistry(); + + if (!registry().all_of(*getEntity())) + return m_position; + + auto& rel = registry().get(*getEntity()); + + if (!rel.getParent().has_value()) + return m_position; + + auto& parentTransform = registry().get(rel.getParent().value()); + return parentTransform.getAbsolutePosition() + m_anchor * parentTransform.getSize() + m_position; + } + + glm::mat4 getMatrix() const { + glm::vec2 absPos = getAbsolutePosition(); + glm::vec2 pivotPx = m_pivot * m_size; + + glm::mat4 mat = glm::mat4(1.0f); + mat = glm::translate(mat, glm::vec3(absPos + pivotPx, 0)); + mat = glm::rotate(mat, glm::radians(m_rotation), {0, 0, 1}); + mat = glm::scale(mat, glm::vec3(m_size * m_scale, 1)); + mat = glm::translate(mat, glm::vec3(-m_pivot, 0)); + return mat; + } + + // ── GPU ─────────────────────────────────────────────────────────── + void initUniformBuffer(VmaAllocator allocator); + void destroyUniformBuffer(); + void updateUniformBuffer(uint32_t frameIndex); + + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } + + nlohmann::json to_json() { + return {}; + } + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CAbstractRenderer.cpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CAbstractRenderer.cpp new file mode 100644 index 0000000..e69de29 diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CAbstractRenderer.hpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CAbstractRenderer.hpp new file mode 100644 index 0000000..fb17963 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CAbstractRenderer.hpp @@ -0,0 +1,11 @@ +#ifndef CABSTRACTRENDERER_HPP +#define CABSTRACTRENDERER_HPP +#include "../CAbstractComponent.hpp" +namespace CosmicCore { + class CAbstractRenderer : public CAbstractComponent + { + public: + CAbstractRenderer(CEntity& e): CAbstractComponent(e){}; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.cpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.cpp new file mode 100644 index 0000000..8579fc9 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.cpp @@ -0,0 +1,3 @@ +#include "CRenderer.hpp" +namespace CosmicCore { +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.hpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.hpp new file mode 100644 index 0000000..365f51c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer.hpp @@ -0,0 +1,18 @@ +#ifndef CTESTRENDERER_HPP +#define CTESTRENDERER_HPP +#include "CAbstractRenderer.hpp" +#include "../../Systems/Graphics/Data/Model/CModel.hpp" +namespace CosmicCore { + class CRenderer: public CAbstractRenderer + { + CModel* m_model = nullptr; + public: + CRenderer() = delete; + CRenderer(CEntity& e): CAbstractRenderer(e){}; + CRenderer(CEntity& e, CModel* mod): CAbstractRenderer(e), m_model(mod){}; + nlohmann::json to_json() override{return nlohmann::json();}; + CModel* getModel(){return m_model;}; + }; +} +#endif + diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.cpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.cpp new file mode 100644 index 0000000..0779df8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.cpp @@ -0,0 +1,5 @@ +#include "CRenderer2D.hpp" + +namespace CosmicCore { + +} // namespace CosmicCore \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.hpp b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.hpp new file mode 100644 index 0000000..0b7be8b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Graphics/CRenderer2D.hpp @@ -0,0 +1,21 @@ +#ifndef CUIRENDERER_HPP +#define CUIRENDERER_HPP + +#include "Engine/Core/Component/Graphics/CAbstractRenderer.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp" +namespace CosmicCore { + class CRenderer2D : public CAbstractRenderer{ + + CModel2D* m_model; + + public: + CRenderer2D() = delete; + CRenderer2D(CEntity& e): CAbstractRenderer(e){}; + CRenderer2D(CEntity& e, CModel2D* mod): CAbstractRenderer(e), m_model(mod){}; + nlohmann::json to_json() override{return nlohmann::json();}; + CModel2D* getModel(){return m_model;}; + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.cpp b/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.cpp new file mode 100644 index 0000000..1ccd533 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.cpp @@ -0,0 +1,85 @@ +#include "CInputManager.hpp" +#include "Engine/Core/Systems/Input/API/CInputAPI.hpp" + +namespace CosmicCore { + + void CInputManager::onPressed(const std::string& actionName, std::function cb) + { + m_onPressed.push_back({actionName, cb, 0, false}); + } + + void CInputManager::onHeld(const std::string& actionName, std::function cb) + { + m_onHeld.push_back({actionName, cb, 0, false}); + } + + void CInputManager::onReleased(const std::string& actionName, std::function cb) + { + m_onReleased.push_back({actionName, cb, 0, false}); + } + + void CInputManager::addOnMouseMove(std::function cb) + { + m_onMouseMove.emplace_back(cb); + } + + void CInputManager::addOnGenericMouseLeftClick(std::function cb) + { + m_onMouseLeftClickReleased.emplace_back(GenericMouseClickAction(cb)); + } + + // appelé par CInputWorld::updateWorld() + void CInputManager::dispatch(const CInputDispatcher& inputWorld) { + if (!m_enabled) return; + auto& entity = getEntity(); + + // résolution lazy — une seule fois par action + for (auto& bound : m_onHeld) { + if (!bound.resolved) { + auto action = CInputAPI::getAction(bound.name); + if (action) { + bound.resolvedId = *action; + bound.resolved = true; + } + // si pas encore enregistrée → retry au prochain frame + } + if (bound.resolved && inputWorld.isActive(bound.resolvedId)) + bound.cb(entity); + } + + for (auto& bound : m_onPressed) { + if (!bound.resolved) { + auto action = CInputAPI::getAction(bound.name); + if (action) { bound.resolvedId = *action; bound.resolved = true; } + } + if (bound.resolved && inputWorld.isJustPressed(bound.resolvedId)) + bound.cb(entity); + } + + for (auto& bound : m_onReleased) { + if (!bound.resolved) { + auto action = CInputAPI::getAction(bound.name); + if (action) { bound.resolvedId = *action; bound.resolved = true; } + } + if (bound.resolved && inputWorld.isJustReleased(bound.resolvedId)) + bound.cb(entity); + } + + glm::vec2 mouseRel = inputWorld.getMouseRelative(); + if (!m_onMouseMove.empty() && (mouseRel.x != 0 || mouseRel.y != 0)) + { + for(auto& cbH : m_onMouseMove) + { + cbH.cb(entity, mouseRel); + } + } + //todo other click (onClick and right click) + if(!m_onMouseLeftClickReleased.empty() && inputWorld.isLeftMouseButtonJustReleased()) + { + for(auto& clickCB : m_onMouseLeftClickReleased) + { + clickCB.cb(entity); + } + } + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.hpp b/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.hpp new file mode 100644 index 0000000..a9ffd4a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Input/CInputManager.hpp @@ -0,0 +1,62 @@ +#ifndef CINPUTMANAGER_HPP +#define CINPUTMANAGER_HPP + +#include "Engine/Core/Component/CAbstractComponent.hpp" +#include "Engine/Core/Systems/Input/API/CInputAPI.hpp" +#include "Engine/Core/Systems/Input/CInputDispatcher.hpp" +#include "glm/fwd.hpp" +#include "nlohmann/json_fwd.hpp" +#include + +namespace CosmicCore { + + class CInputManager : public CAbstractComponent + { + private: + + struct BoundAction { + std::string name; + std::function cb; + InputAction resolvedId = 0; + bool resolved = false; + }; + + struct GenericMouseClickAction{ + std::function cb; + }; + + struct MouseMovementAction{ + std::function cb; + }; + + std::vector m_onHeld; + std::vector m_onPressed; + std::vector m_onReleased; + + std::vector m_onMouseMove; + std::vector m_onMouseLeftClickPressed; + std::vector m_onMouseLeftClickReleased; + std::vector m_onMouseRightClickPressed; + std::vector m_onMouseRightClickReleased; + bool m_enabled = true; + + public: + CInputManager(CEntity& entity) : CAbstractComponent(entity) {} + + + void onPressed(const std::string& actionName, std::function cb); + void onHeld(const std::string& actionName, std::function cb); + void onReleased(const std::string& actionName, std::function cb); + void addOnMouseMove(std::function cb); + void addOnGenericMouseLeftClick(std::function cb); + + void setEnabled(bool enabled) { m_enabled = enabled; } + + void dispatch(const CInputDispatcher& inputWorld); + + nlohmann::json to_json(){return nlohmann::json();} + + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.cpp b/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.cpp new file mode 100644 index 0000000..0954e62 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.cpp @@ -0,0 +1,5 @@ +#include "CLight.hpp" + +namespace CosmicCore { + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.hpp b/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.hpp new file mode 100644 index 0000000..fdec1ab --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Light/CLight.hpp @@ -0,0 +1,71 @@ +#ifndef CLIGHT_HPP +#define CLIGHT_HPP +#include "../CAbstractComponent.hpp" +#include "glm/ext/vector_float3.hpp" +namespace CosmicCore { + + enum class ELightType { + Directional, // soleil + Point, // ampoule + Spot // lampe torche + }; + + class CLight: public CAbstractComponent + { + // données communes + glm::vec3 color = {1.0f, 1.0f, 1.0f}; + float intensity = 1.0f; + bool castShadow = false; + + // Point + Spot + float range = 10.0f; + float attenuation = 1.0f; // falloff + + // Spot uniquement + float innerAngle = 15.0f; // degrés + float outerAngle = 30.0f; // degrés + + ELightType type = ELightType::Directional; + + public: + + CLight(CEntity& entity, ELightType type = ELightType::Directional) + : CAbstractComponent(entity), type(type) {} + + CLight(CLight&&) = default; + CLight& operator=(CLight&&) = default; + CLight(const CLight&) = delete; + CLight& operator=(const CLight&) = delete; + + + const glm::vec3& getColor() const {return color;}; + float getRange(){return range;}; + float getIntensity(){return intensity;}; + float getInnerAngle(){return innerAngle;}; + float getOuterAngle(){return outerAngle;}; + float getAttenuation(){return attenuation;} + ELightType getType(){return type;} + + void setColor(const glm::vec3& c) { color = c; } + void setRange(float r) { range = r; } + void setIntensity(float i) { intensity = i; } + void setInnerAngle(float angle) { innerAngle = angle; } + void setOuterAngle(float angle) { outerAngle = angle; } + void setAttenuation(float a) { attenuation = a; } + void setType(ELightType t) { type = t; } + void setCastShadow(bool shadow) { castShadow = shadow; } + + nlohmann::json to_json() { + nlohmann::json j; + j["type"] = (int)type; + j["color"] = {color.r, color.g, color.b}; + j["intensity"] = intensity; + j["range"] = range; + j["innerAngle"] = innerAngle; + j["outerAngle"] = outerAngle; + j["castShadow"] = castShadow; + return j; + } + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Meta/CMetaData.hpp b/CosmicEngine/src/main/Engine/Core/Component/Meta/CMetaData.hpp new file mode 100644 index 0000000..2cd88e6 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Meta/CMetaData.hpp @@ -0,0 +1,23 @@ +#ifndef CMETADATA_HPP +#define CMETADATA_HPP + +#include "../CAbstractComponent.hpp" +#include "nlohmann/json_fwd.hpp" +#include + +namespace CosmicCore { + class CMetaData : public CAbstractComponent{ + private: + std::string m_name; + std::string m_description; + public: + CMetaData(CEntity& entity): CAbstractComponent(entity){} + CMetaData(CEntity& entity, std::string na, std::string desc): CAbstractComponent(entity), m_name(std::move(na)), m_description(std::move(desc)){} + nlohmann::json to_json(){return nlohmann::json();} + void setName(std::string name){m_name = std::move(name);} + void setDescription(std::string desc){m_description = std::move(desc);} + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Relationships/CRelationship.hpp b/CosmicEngine/src/main/Engine/Core/Component/Relationships/CRelationship.hpp new file mode 100644 index 0000000..3c5fcba --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Relationships/CRelationship.hpp @@ -0,0 +1,31 @@ +#ifndef CRELATIONSHIP_HPP +#define CRELATIONSHIP_HPP + +#include "../CAbstractComponent.hpp" +#include "nlohmann/json_fwd.hpp" +#include +#include + +namespace CosmicCore { + class CRelationship : public CAbstractComponent{ + private: + std::optional parent; + std::vector children; + public: + CRelationship(CEntity& entity): CAbstractComponent(entity){} + CRelationship(CEntity& entity, std::optional p): CAbstractComponent(entity), parent(p){} + CRelationship(CEntity& entity, std::vector childs): CAbstractComponent(entity), children(childs){} + CRelationship(CEntity& entity, std::optional p, std::vector childs): CAbstractComponent(entity), parent(p), children(childs){} + + nlohmann::json to_json(){return nlohmann::json();} + void setParent(EntityId par){parent = par;} + void addChild(EntityId child){children.emplace_back(child);} + std::optional getParent(){return parent;} + const std::optional getParent() const {return parent;} + + std::vector& getChildren(){return children;} + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.cpp b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.cpp new file mode 100644 index 0000000..6314dde --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.cpp @@ -0,0 +1,6 @@ +#include "CAbstractRigidbody.hpp" +namespace CosmicCore { + CAbstractRigidBody::CAbstractRigidBody(CEntity& entity): CAbstractComponent(entity) + { + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.hpp b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.hpp new file mode 100644 index 0000000..44cc767 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CAbstractRigidbody.hpp @@ -0,0 +1,17 @@ +#ifndef CABSTRACTRIGIDBODY_HPP +#define CABSTRACTRIGIDBODY_HPP +#include "../CAbstractComponent.hpp" +#include "nlohmann/json_fwd.hpp" +namespace CosmicCore { + class CAbstractRigidBody: public CAbstractComponent + { + public: + /** + * @brief CData's constructor. + * @param[in, out] entity The entity to which we want to attach specific informations. + */ + CAbstractRigidBody(CEntity& entity); + nlohmann::json to_json(){return nlohmann::json();}; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.cpp b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.cpp new file mode 100644 index 0000000..7c271cc --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.cpp @@ -0,0 +1,121 @@ +#include "CRigidBody.hpp" +#include "../../Systems/Physics/PhysicsLayers.hpp" +#include "../../Scene/CScene.hpp" +#include "../Geometry/CTransform.hpp" +#include "../Collider/CCollider.hpp" +#include "Jolt/Physics/EActivation.h" + +namespace CosmicCore { + CRigidBody::CRigidBody(CEntity& entity, EBodyType type): CAbstractRigidBody(entity), m_bodyType(type) + { + } + + // initialise le body dans le monde physique + // doit être appelé après CCollider et CTransform + void CRigidBody::init() { + + + auto& registry = getEntity().getRegistry(); + + // récupère le transform + auto& transform = registry.registry.get(*getEntity()); + auto& collider = registry.registry.get(*getEntity()); + glm::vec3 pos = transform.getCenter(); + glm::quat ori = transform.getOrientation(); + + // motion type + JPH::EMotionType motionType; + JPH::ObjectLayer layer; + switch (m_bodyType) { + case EBodyType::Static: + motionType = JPH::EMotionType::Static; + layer = Layers::NON_MOVING; + break; + case EBodyType::Kinematic: + motionType = JPH::EMotionType::Kinematic; + layer = Layers::MOVING; + break; + case EBodyType::Dynamic: + default: + motionType = JPH::EMotionType::Dynamic; + layer = Layers::MOVING; + break; + } + + // création du body + JPH::BodyCreationSettings settings( + collider.getShape(), + JPH::RVec3(pos.x, pos.y, pos.z), + JPH::Quat(ori.x, ori.y, ori.z, ori.w), + motionType, + layer + ); + settings.mFriction = m_friction; + settings.mRestitution = m_restitution; + if (m_bodyType == EBodyType::Static) + { + settings.mMotionType = JPH::EMotionType::Static; + } + else + { + settings.mOverrideMassProperties = JPH::EOverrideMassProperties::CalculateInertia; + settings.mMassPropertiesOverride.mMass = m_mass; + } + + auto& bodyInterface = getEntity().getScene()->getTangibleWorld().getBodyInterface(); + m_bodyID = bodyInterface.CreateAndAddBody( + settings, + m_bodyType != EBodyType::Static ? JPH::EActivation::Activate : JPH::EActivation::DontActivate + ); + m_initialized = true; + } + + void CRigidBody::destroy() { + if (!m_initialized) return; + // récupère le world via le kernel + auto* scene = getEntity().getScene(); + if (!scene) return; + auto& bodyInterface = scene->getTangibleWorld() + .getPhysicsSystem() + .GetBodyInterface(); + if (bodyInterface.IsAdded(m_bodyID)) + bodyInterface.RemoveBody(m_bodyID); + bodyInterface.DestroyBody(m_bodyID); + m_initialized = false; + } + + // sync CTransform depuis la physique + void CRigidBody::syncTransform() { + if (!m_initialized) return; + auto& registry = getEntity().getRegistry(); + auto& transform = registry.registry.get(*getEntity()); + auto& bodyInterface = getEntity().getScene() + ->getTangibleWorld() + .getBodyInterface(); + + JPH::RVec3 pos = bodyInterface.GetCenterOfMassPosition(m_bodyID); + JPH::Quat ori = bodyInterface.GetRotation(m_bodyID); + + transform.setCenter({pos.GetX(), pos.GetY(), pos.GetZ()}); + transform.setQuaternion({ori.GetW(), ori.GetX(), ori.GetY(), ori.GetZ()}); + } + + // forces + void CRigidBody::addForce(glm::vec3 force) { + if (!m_initialized) return; + auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface(); + bi.AddForce(m_bodyID, JPH::Vec3(force.x, force.y, force.z)); + } + + void CRigidBody::addImpulse(glm::vec3 impulse) { + if (!m_initialized) return; + auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface(); + bi.AddImpulse(m_bodyID, JPH::Vec3(impulse.x, impulse.y, impulse.z)); + } + + void CRigidBody::setLinearVelocity(glm::vec3 velocity) { + if (!m_initialized) return; + auto& bi = getEntity().getScene()->getTangibleWorld().getBodyInterface(); + bi.SetLinearVelocity(m_bodyID, JPH::Vec3(velocity.x, velocity.y, velocity.z)); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.hpp b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.hpp new file mode 100644 index 0000000..ea2c6b2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Rigidbody/CRigidBody.hpp @@ -0,0 +1,62 @@ +#ifndef CRIGIDBODY_HPP +#define CRIGIDBODY_HPP + +#include "CAbstractRigidbody.hpp" +#include "glm/fwd.hpp" +#include +#include +#include +#include + +namespace CosmicCore { + +enum class EBodyType { + Static, // ne bouge pas (décors, terrain) + Kinematic, // bouge mais pas affecté par la physique (plateformes) + Dynamic // affecté par la physique (objets normaux) +}; + +class CRigidBody : public CAbstractRigidBody { +private: + JPH::BodyID m_bodyID; + EBodyType m_bodyType = EBodyType::Dynamic; + float m_mass = 1.0f; + float m_friction = 0.5f; + float m_restitution = 0.0f; // rebond + bool m_initialized = false; + +public: + CRigidBody(CEntity& entity, EBodyType type = EBodyType::Dynamic); + + ~CRigidBody() { + destroy(); + } + + CRigidBody(const CRigidBody&) = delete; + CRigidBody& operator=(const CRigidBody&) = delete; + + void setLinearVelocity(glm::vec3 velocity); + void addImpulse(glm::vec3 impulse); + void addForce(glm::vec3 force); + void syncTransform(); + void destroy(); + void init(); + + + // setters + void setMass(float mass) { m_mass = mass; } + void setFriction(float friction) { m_friction = friction; } + void setRestitution(float restitution){ m_restitution = restitution; } + void setBodyType(EBodyType type) { m_bodyType = type; } + + // getters + JPH::BodyID getBodyID() const { return m_bodyID; } + EBodyType getBodyType() const { return m_bodyType; } + float getMass() const { return m_mass; } + bool isInitialized() const { return m_initialized; } + + nlohmann::json to_json() { return {}; } +}; + +} // namespace CosmicCore +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.cpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.cpp new file mode 100644 index 0000000..4ea8f6a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.cpp @@ -0,0 +1,10 @@ +#include "CAbstractScript.hpp" + +namespace CosmicCore { + + CAbstractScript::CAbstractScript(CEntity& entity, const std::string& name) : CAbstractComponent(entity), m_scriptName(name) + { + } +} + + diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.hpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.hpp new file mode 100644 index 0000000..a325e5b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CAbstractScript.hpp @@ -0,0 +1,29 @@ +#ifndef CABSTRACTSCRIPT_HPP +#define CABSTRACTSCRIPT_HPP + +#include "../CAbstractComponent.hpp" +#include "../../Entity/CEntity.hpp" + +namespace CosmicCore { + + class CAbstractScript : public CAbstractComponent + { + private: + std::string m_scriptName; + public: + CAbstractScript(CEntity& entity, const std::string& name); + CAbstractScript(CAbstractScript&& other) = default; + CAbstractScript& operator=(CAbstractScript&&) = default; + virtual void onCreate() = 0; + virtual void start() = 0; + virtual void update() = 0; + virtual void destroy() = 0; + virtual nlohmann::json to_json() = 0; + virtual ~CAbstractScript() = default; + std::string getName() { return m_scriptName; }; + void setName(const std::string& name) { m_scriptName = name; }; + }; +} + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.cpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.cpp new file mode 100644 index 0000000..9185dfa --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.cpp @@ -0,0 +1,44 @@ +#include "CScript.hpp" +#include "Engine/Core/Component/Script/CAbstractScript.hpp" +#include "Engine/Core/Systems/Scripts/API/CScriptAPI.hpp" + +namespace CosmicCore { + + CScript::CScript(CEntity& entity, const std::string& name, std::unique_ptr&& innerScript) : CAbstractScript(entity, name), m_innerScript(std::move(innerScript)) + { + onCreate(); + } + + CScript::CScript(CEntity& entity, const std::string& name) : CAbstractScript(entity, name) + { + m_innerScript = CScriptAPI::scripts().create(name, entity, name); + onCreate(); + } + + void CScript::start() + { + m_innerScript->start(); + } + + void CScript::update() + { + m_innerScript->update(); + } + + void CScript::destroy() + { + m_innerScript->destroy(); + } + + void CScript::onCreate() + { + m_innerScript->onCreate(); + } + + nlohmann::json CScript::to_json() + { + return m_innerScript->to_json(); + } + +} + diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.hpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.hpp new file mode 100644 index 0000000..dcd63d5 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CScript.hpp @@ -0,0 +1,30 @@ +#ifndef CSCRIPT_HPP +#define CSCRIPT_HPP + +#include "Engine//Core/Component/Script/CAbstractScript.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include + +namespace CosmicCore { + + class CScript : public CAbstractScript + { + private: + std::unique_ptr m_innerScript; + + public: + CScript(CEntity& entity, const std::string& name, std::unique_ptr&& innerScript); + CScript(CEntity& entity, const std::string& name); + CScript(CScript&& mov) = default; + CScript& operator=(CScript&&) = default; + void onCreate() override; + void start() override; + void update() override; + void destroy() override; + nlohmann::json to_json() override; + virtual ~CScript() = default; + }; +} + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.cpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.cpp new file mode 100644 index 0000000..31a693d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.cpp @@ -0,0 +1,23 @@ +#include "CScriptManager.hpp" +#include "Engine/Core/Component/Script/CScript.hpp" +#include "nlohmann/json_fwd.hpp" + +namespace CosmicCore { + + void CScriptManager::emplace(const std::string& name) + { + m_scripts.emplace_back(getEntity(), name); + } + + nlohmann::json CScriptManager::to_json(){ + return nlohmann::json(); + } + void CScriptManager::updateAll() + { + for(auto& sc : m_scripts) + { + sc.update(); + } + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.hpp b/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.hpp new file mode 100644 index 0000000..16a31e9 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Script/CScriptManager.hpp @@ -0,0 +1,27 @@ +#ifndef CSCRIPTMANAGER_HPP +#define CSCRIPTMANAGER_HPP + +#include "Engine/Core/Component/CAbstractComponent.hpp" +#include "Engine/Core/Component/Script/CScript.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include +namespace CosmicCore { + + class CScriptManager: public CAbstractComponent + { + private: + std::vector m_scripts; + public: + CScriptManager(CEntity& entity) : CAbstractComponent(entity) {}; + CScriptManager(CScriptManager&& mov) = default; + ~CScriptManager() = default; + CScriptManager& operator=(CScriptManager&&) = default; + + void emplace(const std::string& name); + void updateAll(); + nlohmann::json to_json(); + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.cpp b/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.cpp new file mode 100644 index 0000000..5f699cc --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.cpp @@ -0,0 +1,121 @@ +#include "CSpeaker.hpp" +#include "../../Systems/Resources/API/CResourceAPI.hpp" + +namespace CosmicCore { + + CSpeaker::CSpeaker(CEntity& entity): CAbstractComponent(entity) + { + + } + + + void CSpeaker::addClip(const std::string& name, const std::string& path, float gain, float pitch, bool loop, bool spatial) { + auto* clip = CResourceAPI::resources().sounds().loadClip(path); + + SoundInstance instance; + instance.clip = clip; + instance.gain = gain; + instance.pitch = pitch; + instance.spatial = spatial; + instance.loop = loop; + alGenSources(1, &instance.source); + + alSourcei(instance.source, AL_SOURCE_RELATIVE, AL_FALSE); + //TODO + // à passer dans la config + alSourcef(instance.source, AL_ROLLOFF_FACTOR, 1.3f); + alSourcef(instance.source, AL_REFERENCE_DISTANCE, 0.2f); // distance à partir de laquelle le son diminue + alSourcef(instance.source, AL_MAX_DISTANCE, 100.0f); // distance max + + alSourcei(instance.source, AL_BUFFER, clip->buffer); + alSourcef(instance.source, AL_GAIN, m_masterGain*instance.gain); + alSourcei(instance.source, AL_LOOPING, instance.loop); + alSource3f(instance.source, AL_POSITION, 0, 0, 0); + m_clips[name] = instance; + } + + void CSpeaker::addClip(const std::string& name, CAudioClip* clip, float gain, float pitch, bool loop, bool spatial) { + SoundInstance instance; + instance.clip = clip; + instance.gain = gain; + instance.pitch = pitch; + instance.spatial = spatial; + instance.loop = loop; + alGenSources(1, &instance.source); + + alSourcei(instance.source, AL_SOURCE_RELATIVE, AL_FALSE); + //TODO + // à passer dans la config + alSourcef(instance.source, AL_ROLLOFF_FACTOR, 1.3f); + alSourcef(instance.source, AL_REFERENCE_DISTANCE, 0.2f); // distance à partir de laquelle le son diminue + alSourcef(instance.source, AL_MAX_DISTANCE, 100.0f); // distance max + + alSourcei(instance.source, AL_BUFFER, clip->buffer); + alSourcef(instance.source, AL_GAIN, m_masterGain*instance.gain); + alSourcei(instance.source, AL_LOOPING, instance.loop); + alSource3f(instance.source, AL_POSITION, 0, 0, 0); + m_clips[name] = instance; + } + + void CSpeaker::play(const std::string& name) { + auto it = m_clips.find(name); + if (it == m_clips.end()) return; + alSourcePlay(it->second.source); + } + + void CSpeaker::stop(const std::string& name) { + auto it = m_clips.find(name); + if (it == m_clips.end()) return; + alSourceStop(it->second.source); + } + + void CSpeaker::pause(const std::string& name) { + auto it = m_clips.find(name); + if (it == m_clips.end()) return; + alSourcePause(it->second.source); + } + + void CSpeaker::stopAll() { + for (auto& [name, instance] : m_clips) + alSourceStop(instance.source); + } + + void CSpeaker::setLoop(const std::string& name, bool loop) { + auto it = m_clips.find(name); + if (it == m_clips.end()) return; + it->second.loop = loop; + alSourcei(it->second.source, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); + } + + void CSpeaker::setGain(const std::string& name, float gain) { + auto it = m_clips.find(name); + if (it == m_clips.end()) return; + it->second.gain = gain; + alSourcef(it->second.source, AL_GAIN, gain * m_masterGain); + } + + void CSpeaker::updatePosition(const CTransform& transform, glm::vec3 velocity) { + for (auto& [name, instance] : m_clips) { + auto center = transform.getCenter(); + if (!instance.spatial) continue; + alSource3f(instance.source, AL_POSITION, + center.x, center.y, center.z); + alSource3f(instance.source, AL_VELOCITY, + velocity.x, velocity.y, velocity.z); + } + } + + bool CSpeaker::isPlaying(const std::string& name) const { + auto it = m_clips.find(name); + if (it == m_clips.end()) return false; + ALint state; + alGetSourcei(it->second.source, AL_SOURCE_STATE, &state); + return state == AL_PLAYING; + } + + CSpeaker::~CSpeaker() { + for (auto& [name, instance] : m_clips) + alDeleteSources(1, &instance.source); + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.hpp b/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.hpp new file mode 100644 index 0000000..d31c905 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Component/Speaker/CSpeaker.hpp @@ -0,0 +1,58 @@ +#ifndef CSPEAKER_HPP +#define CSPEAKER_HPP +#include +#include +#include "../CAbstractComponent.hpp" +#include "../Geometry/CTransform.hpp" +#include "../../Systems/Audio/Sound/CAudioClip.hpp" +#include "nlohmann/json_fwd.hpp" +namespace CosmicCore { + + struct SoundInstance { + CAudioClip* clip = nullptr; + ALuint source = 0; + float gain = 1.0f; + float pitch = 1.0f; + bool loop = false; + bool spatial = true; + }; + + class CSpeaker : public CAbstractComponent { + std::unordered_map m_clips; + bool m_muted = false; + float m_masterGain = 1.0f; + + public: + CSpeaker(CEntity& entity); + // charge et enregistre un son + void addClip(const std::string& name, const std::string& path, float gain = 1.0f, float pitch = 1.0f, bool loop = false, bool spatial = true); + void addClip(const std::string& name, CAudioClip* clip, float gain = 1.0f, float pitch = 1.0f, bool loop = false, bool spatial = true); + + void play(const std::string& name); + + void stop(const std::string& name); + + void pause(const std::string& name); + + void stopAll(); + + void setLoop(const std::string& name, bool loop); + + void setGain(const std::string& name, float gain); + + bool isPlaying(const std::string& name) const; + + ~CSpeaker(); + + // paramètres globaux du speaker + void setMuted(bool muted); + void setMasterGain(float gain); + + void updatePosition(const CTransform& transform, glm::vec3 velocity = {0,0,0}); + + nlohmann::json to_json(){return nlohmann::json();}; + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Entity/CEntity.cpp b/CosmicEngine/src/main/Engine/Core/Entity/CEntity.cpp new file mode 100644 index 0000000..e4f292e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Entity/CEntity.cpp @@ -0,0 +1,40 @@ +#include "CEntity.hpp" +#include "nlohmann/json_fwd.hpp" + +#include + +namespace CosmicCore +{ + + CEntity::CEntity(std::reference_wrapper registry, EntityId handle, CScene* scene) : CSerializable(), m_scene(scene), m_registryReference(registry), m_handle(handle) + { + } + + CEntity::CEntity(const CEntity& cop): m_scene(cop.m_scene), m_registryReference(cop.m_registryReference), m_handle(cop.m_handle){ + + } + + CEntity& CEntity::operator=(const CEntity& ent) + { + m_handle = ent.m_handle; + m_registryReference = ent.m_registryReference; + m_scene = ent.m_scene; + return *this; + } + + CScene* CEntity::getScene() + { + return m_scene; + } + + void CEntity::setScene(CScene* s) + { + m_scene = s; + } + + /*CEntity CEntity::getParent() { + //to implement + }*/ + + nlohmann::json CEntity::to_json(){return nlohmann::json();}; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Entity/CEntity.hpp b/CosmicEngine/src/main/Engine/Core/Entity/CEntity.hpp new file mode 100644 index 0000000..559737b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Entity/CEntity.hpp @@ -0,0 +1,91 @@ +#ifndef CENTITY_HPP +#define CENTITY_HPP + +#include +#include +#include "../../Utils/JsonParser/CSerializable.hpp" +#include "EntityComponentManager.hpp" + +namespace CosmicCore +{ + class CScene; + + class CEntity : public CSerializable { + + private: + + /** + * @brief A pointer to the scene containing the entity. + */ + CScene* m_scene; + + std::reference_wrapper m_registryReference; + + EntityId m_handle; + + public: + + /** + * @brief CEntity's default constructor, disabled. + */ + CEntity() = delete; + + CEntity(std::reference_wrapper registry, EntityId handle, CScene* scene); + + CEntity(const CEntity& cop); + + CEntity& operator=(const CEntity& ent); + /** + * @brief CEntity's destructor. + */ + ~CEntity(void) = default; + + /** + * @brief Getter to the parent entity. + * @return a pointer to the parent entity m_parent. nullptr if there is not. + */ + //CEntity getParent(); + + template + void addComponent(Args&&... args) + { + m_registryReference().emplace(m_handle, *this, std::forward(args)...); + } + + template + void addComponent() + { + m_registryReference().emplace(m_handle, *this); + } + + EntityComponentManager& getRegistry(){return m_registryReference;}; + const EntityComponentManager& getRegistry() const {return m_registryReference;}; + + EntityId getHandle(){return m_handle;}; + + /** + * @brief Getter to the entity's scene. + * @return The pointer m_scene. + */ + CScene* getScene(); + + /** + * @brief Setter of the scene. + * @param[in, out] e The scene in which the entity will be set. + */ + void setScene(CScene* s); + + EntityId operator*(){ + return m_handle; + } + + const EntityId operator*() const { + return m_handle; + } + //TODO GET COMPONENT VECTOR OF SPECIFIC TYPE ? si utile + + nlohmann::json to_json(); + }; + +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Entity/EntityComponentManager.hpp b/CosmicEngine/src/main/Engine/Core/Entity/EntityComponentManager.hpp new file mode 100644 index 0000000..ebb1679 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Entity/EntityComponentManager.hpp @@ -0,0 +1,26 @@ +#ifndef ENTITYCOMPONENTMANAGER_HPP +#define ENTITYCOMPONENTMANAGER_HPP + +#include + +namespace CosmicCore { + + using ECManager = entt::registry; + using EntityId = entt::entity; + + class EntityComponentManager{ + public: + ECManager registry; + ECManager& operator()(){ + return registry; + } + + const ECManager& operator()() const { + return registry; + } + }; +}; + + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CException.cpp new file mode 100644 index 0000000..929c63b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CException.cpp @@ -0,0 +1,56 @@ +#include "CException.hpp" + +void CException::makeFullMessage(void) { + /*std::stringstream sstring; + sstring << "Error : " << m_code << std::endl << m_message << std::endl; + boost::stacktrace::stacktrace stacktrace = boost::stacktrace::stacktrace(); + std::size_t frames = stacktrace.size(); + + for (size_t i = 4; i < frames; i++) { + sstring << " #" << i - 4 << " : " << stacktrace[i].name() << " : "; + if (stacktrace[i].source_file().empty()) { + sstring << "no source"; + } + else { + sstring << stacktrace[i].source_file() << " at line : " << stacktrace[i].source_line(); + } + sstring << " (" << stacktrace[i].address() << ')' << std::endl; + } + + m_fullMessage = sstring.str();*/ +} + +CException::CException(void) noexcept : + std::exception(), + m_message("A error occurred"), + m_code(0), + m_fullMessage() { + makeFullMessage(); +} + +CException::CException(std::string message, unsigned int code) noexcept : + std::exception(), + m_message(message), + m_code(code), + m_fullMessage() { + makeFullMessage(); +} + +CException::~CException(void) noexcept { +} + +const char* CException::what() const noexcept { + return m_fullMessage.c_str(); +} + +unsigned int CException::getCode() const noexcept { + return m_code; +} + +std::string CException::getMessage() const noexcept { + return m_message; +} + +void CException::setMessage(std::string newMessage) noexcept { + m_message = newMessage; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CException.hpp new file mode 100644 index 0000000..6d77859 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CException.hpp @@ -0,0 +1,75 @@ +#ifndef CEXCEPTION_HPP +#define CEXCEPTION_HPP + +#include +#include + +/** + * @file CException.hpp + * @brief File of CException, a class to handle program exception. + */ + + /** + * @brief Class to handle program exception. + */ +class CException : public std::exception { + +private: + // The message of the exception. + std::string m_message; + + // The code of the exception. + unsigned int m_code; + + // The full message of the exception. + std::string m_fullMessage; + + /** + * @brief Create the full message. + */ + void makeFullMessage(void); + +public: + /** + * @brief The default constructor, build a exception with default message : "An error occurred" and the code 0. + */ + CException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the given code. + * @param[in] message The wanted message. + * @param[in] code The wanted code. + */ + CException(const std::string message, const unsigned int code) noexcept; + + /** + * @brief The destructor. + */ + ~CException(void) noexcept; + + /** + * @brief Give some point about the current exception. + * @return char*, Ready to print string, error description. + */ + virtual const char* what(void) const noexcept; + + /** + * @brief The error code getter. + * @return unsigned int, The code of the error. + */ + unsigned int getCode(void) const noexcept; + + /** + * @brief The error message getter. + * @return std::string, The message of the error. + */ + std::string getMessage(void) const noexcept; + + /** + * @brief The error message setter. + * @param[in] newMessage The new error message. + */ + void setMessage(const std::string newMessage) noexcept; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.cpp new file mode 100644 index 0000000..00a7770 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.cpp @@ -0,0 +1,34 @@ +#include "CExceptionManager.hpp" + +/*void HandleException(const CException& e, bool fatal) { + + std::string windowMessage(e.getMessage()); + windowMessage += "\nException reported in \""; + windowMessage += DEFAULT_REPORT_PATH; + windowMessage += "\"."; + + CFileManager fm(DEFAULT_REPORT_PATH); + + try { + fm.write(e.what()); + } + catch (const std::exception& nothandled) { + (void)nothandled; + } + + if (!fatal) { + // Just warning. + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, + "Error !", + windowMessage.c_str(), + NULL); + } else { + // Fatal error. + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "Fatal error !", + windowMessage.c_str(), + NULL); + // It's fatal, so we quit. + exit(EXIT_FAILURE); + } +}*/ \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.hpp new file mode 100644 index 0000000..db62298 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CExceptionManager.hpp @@ -0,0 +1,23 @@ +#ifndef CEXCEPTIONMANAGER_HPP +#define CEXCEPTIONMANAGER_HPP + +#include "CException.hpp" + +/** + * @file CExceptionManager.hpp + * @brief File contain some function to handle program exception. + */ + +/** + * @def DEFAULT_PATH default path for crash-report file. + */ +#define DEFAULT_REPORT_PATH "../exception-report.txt" + +/** + * @brief Simple function to handle program exception + * @param[in] e The Exception instance to hanlde. + * @param[in] fatal A flag to make this Exception as fatal, so the program will quit. + */ +void HandleException(const CException& e, bool fatal); + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CFileException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CFileException.cpp new file mode 100644 index 0000000..f03dd6b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CFileException.cpp @@ -0,0 +1,9 @@ +#include "CFileException.hpp" + +CFileException::CFileException(void) noexcept : + CException("A file error occurred", FILE_EXC_CODE) { +} + +CFileException::CFileException(std::string message) noexcept : + CException(message, FILE_EXC_CODE){ +} diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CFileException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CFileException.hpp new file mode 100644 index 0000000..5f851c2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CFileException.hpp @@ -0,0 +1,40 @@ +#ifndef CFILEEXCEPTION_HPP +#define CFILEEXCEPTION_HPP + +#include "CException.hpp" + +#include +#include + +/** + * @file CFileException.hpp + * @brief File of CFileException, a class to handle program file exception. + */ + +/** + * @def FILE_EXC_CODE default code for this kind of Exception. + */ +#define FILE_EXC_CODE 4 + + /** + * @brief Class to handle program file exception. + */ +class CFileException : public CException { + +private: + +public: + /** + * @brief The default constructor, build a exception with default message : "A file error occurred" and the code FILE_EXC_CODE. + */ + CFileException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the code FILE_EXC_CODE. + * @param[in] message The wanted message. + */ + CFileException(const std::string message) noexcept; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.cpp new file mode 100644 index 0000000..bfa60a7 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.cpp @@ -0,0 +1,9 @@ +#include "CJsonException.hpp" + +CJsonException::CJsonException(void) noexcept : + CException("A json error occurred", JSON_EXC_CODE) { +} + +CJsonException::CJsonException(std::string message) noexcept : + CException(message, JSON_EXC_CODE){ +} diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.hpp new file mode 100644 index 0000000..c1f8ea7 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CJsonException.hpp @@ -0,0 +1,40 @@ +#ifndef CJSONEXCEPTION_HPP +#define CJSONEXCEPTION_HPP + +#include "CException.hpp" + +#include +#include + +/** + * @file CJsonException.hpp + * @brief File of CJsonException, a class to handle program json parse/handle exception. + */ + + /** + * @def JSON_EXC_CODE default code for this kind of Exception. + */ +#define JSON_EXC_CODE 5 + + /** + * @brief Class to handle program file exception. + */ +class CJsonException : public CException { + +private: + +public: + /** + * @brief The default constructor, build a exception with default message : "A json error occurred" and the code JSON_EXC_CODE. + */ + CJsonException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the code JSON_EXC_CODE. + * @param[in] message The wanted message. + */ + CJsonException(const std::string message) noexcept; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CLibException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CLibException.cpp new file mode 100644 index 0000000..b59eac8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CLibException.cpp @@ -0,0 +1,9 @@ +#include "CLibException.hpp" + +CLibException::CLibException(void) noexcept : + CException("A lib error occurred", LIB_EXC_CODE) { +} + +CLibException::CLibException(std::string message) noexcept : + CException(message, LIB_EXC_CODE){ +} diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CLibException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CLibException.hpp new file mode 100644 index 0000000..c17847e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CLibException.hpp @@ -0,0 +1,40 @@ +#ifndef CLIBEXCEPTION_HPP +#define CLIBEXCEPTION_HPP + +#include "CException.hpp" + +#include +#include + +/** + * @file CLibException.hpp + * @brief File of CLibException, a class to handle program library runtine exception. + */ + +/** + * @def LIB_EXC_CODE default code for this kind of Exception. + */ +#define LIB_EXC_CODE 3 + +/** + * @brief Class to handle program file exception. + */ +class CLibException : public CException { + +private: + +public: + /** + * @brief The default constructor, build a exception with default message : "A library error occurred" and the code LIB_EXC_CODE. + */ + CLibException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the code LIB_EXC_CODE. + * @param[in] message The wanted message. + */ + CLibException(const std::string message) noexcept; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.cpp new file mode 100644 index 0000000..0bc6c67 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.cpp @@ -0,0 +1,9 @@ +#include "CLogicException.hpp" + +CLogicException::CLogicException(void) noexcept : + CException("A logic error occurred", LOGIC_EXC_CODE) { +} + +CLogicException::CLogicException(std::string message) noexcept : + CException(message, LOGIC_EXC_CODE){ +} diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.hpp new file mode 100644 index 0000000..5a4a0b2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CLogicException.hpp @@ -0,0 +1,40 @@ +#ifndef CLOGICEXCEPTION_HPP +#define CLOGICEXCEPTION_HPP + +#include "CException.hpp" + +#include +#include + +/** + * @file CLogicException.hpp + * @brief File of CLogicException, a class to handle program logic exception, it's mean error caused by bad use of function/class by user. + */ + +/** + * @def LOGIC_EXC_CODE default code for this kind of Exception. + */ +#define LOGIC_EXC_CODE 1 + +/** + * @brief Class to handle program file exception. + */ +class CLogicException : public CException { + +private: + +public: + /** + * @brief The default constructor, build a exception with default message : "A logic error occurred" and the code LOGIC_EXC_CODE. + */ + CLogicException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the code LOGIC_EXC_CODE. + * @param[in] message The wanted message. + */ + CLogicException(const std::string message) noexcept; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.cpp b/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.cpp new file mode 100644 index 0000000..9e51156 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.cpp @@ -0,0 +1,9 @@ +#include "CRuntimeException.hpp" + +CRuntimeException::CRuntimeException(void) noexcept : + CException("A runtime error occurred", RUNTIME_EXC_CODE) { +} + +CRuntimeException::CRuntimeException(std::string message) noexcept : + CException(message, RUNTIME_EXC_CODE){ +} diff --git a/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.hpp b/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.hpp new file mode 100644 index 0000000..157be4d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Exception/CRuntimeException.hpp @@ -0,0 +1,40 @@ +#ifndef CRUNTIMEEXCEPTION_HPP +#define CRUNTIMEEXCEPTION_HPP + +#include "CException.hpp" + +#include +#include + +/** + * @file CRuntimeException.hpp + * @brief File of CRuntimeException, a class to handle program runtime exception. + */ + +/** + * @def LOGIC_EXC_CODE default code for this kind of Exception. + */ +#define RUNTIME_EXC_CODE 2 + +/** + * @brief Class to handle program file exception. + */ +class CRuntimeException : public CException { + +private: + +public: + /** + * @brief The default constructor, build a exception with default message : "A runtime error occurred" and the code RUNTIME_EXC_CODE. + */ + CRuntimeException(void) noexcept; + + /** + * @brief The usage constructor, build a exception with a given message and the code RUNTIME_EXC_CODE. + * @param[in] message The wanted message. + */ + CRuntimeException(const std::string message) noexcept; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Input/CInput.cpp b/CosmicEngine/src/main/Engine/Core/Input/CInput.cpp new file mode 100644 index 0000000..d4d60a5 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Input/CInput.cpp @@ -0,0 +1,165 @@ +#include "CInput.hpp" +/* +#include "../CKernel.hpp" + +#include + +CInput::CInput(CKernel* kernel) : + m_kernel(kernel), + m_event(), + m_mouse(), + m_keyboard(), + m_controllers(){ + m_keyboard.addObserver(this); +} + +CInput::~CInput(void) { + for (std::map::iterator it = m_controllers.begin(); it != m_controllers.end(); ++it) { + delete it->second; + } +} + +void CInput::updateEvent(void) { + // Reset the mouse relative pos. + m_mouse.reset(); + + // For each event in the SDL event queue. + while(SDL_PollEvent(&m_event) == 1) { + + // Switch on the event type. + switch(m_event.type) { + unsigned int id; + CController* controller; + + // On key button pressed. + case SDL_KEYDOWN: + m_keyboard.onKeyDown(m_event.key.keysym.scancode); + break; + + // On key button released. + case SDL_KEYUP: + m_keyboard.onKeyUp(m_event.key.keysym.scancode); + break; + + // On mouse button pressed. + case SDL_MOUSEBUTTONDOWN: + m_mouse.onButtonDown(m_event.button.button); + break; + + // On mouse button released. + case SDL_MOUSEBUTTONUP: + m_mouse.onButtonUp(m_event.button.button); + break; + + // On mouse cursor moved. + case SDL_MOUSEMOTION: + m_mouse.onMove(m_event.motion.x, m_event.motion.y, m_event.motion.xrel, m_event.motion.yrel); + break; + + // On mouse wheel moved. + case SDL_MOUSEWHEEL: + m_mouse.onWheel(m_event.wheel.x, m_event.wheel.y); + break; + + // On joystick unplugged. + case SDL_JOYDEVICEREMOVED: + id = m_event.jdevice.which; + controller = m_controllers[id]; + delete controller; + m_controllers.erase(id); + break; + + // On joystick plugged. + case SDL_JOYDEVICEADDED: + try { + // Give a test id for opening. + id = m_event.jdevice.which; + CController* controller = new CController(id); + // Get the final id. + id = controller->getId(); + // Push the controller in the list. + m_controllers.insert(std::pair(id, controller)); + } + catch (const CException& e) { + HandleException(e, false); + } + break; + + // On joystick axis moved. + case SDL_JOYAXISMOTION: + controller = m_controllers[m_event.jaxis.which]; + controller->onAxis(m_event.jaxis.axis, m_event.jaxis.value); + break; + + // On joystick hat moved. + case SDL_JOYHATMOTION: + controller = m_controllers[m_event.jhat.which]; + controller->onHat(m_event.jhat.hat, m_event.jhat.value); + break; + + // On joystick button pressed. + case SDL_JOYBUTTONDOWN: + controller = m_controllers[m_event.jaxis.which]; + controller->onButtonDown(m_event.jbutton.button); + break; + + // On joystick button released. + case SDL_JOYBUTTONUP: + controller = m_controllers[m_event.jaxis.which]; + controller->onButtonUp(m_event.jbutton.button); + break; + + // Case of window event. + case SDL_WINDOWEVENT: + + // If the window is closed. + if (m_event.window.event == SDL_WINDOWEVENT_CLOSE) { + m_kernel->quit(); + } + + // If the window is focused. + if (m_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) { + m_kernel->focus(); + } + break; + + default: + break; + } + } +} + +CKeyboard* CInput::getKeyboard(void) { + return &m_keyboard; +} + +CMouse* CInput::getMouse(void) { + return &m_mouse; +} + +CController* CInput::getController(unsigned int id) { + return m_controllers[id]; +} + +std::map CInput::getControllers(void) { + return m_controllers; +} + +void CInput::onKKeyDown(unsigned int which) { + // 40 is enter. + if (which == 40) { + // If 226 is pressed. + if (m_keyboard.getKey(226)) { + m_kernel->fullscreen(); + } + } + + // 227 is command/windows/meta. + if (which == 227) { + m_kernel->desktop(); + } +} + +void CInput::onKKeyUp(unsigned int which) { + (void)which; +}*/ \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Input/CInput.hpp b/CosmicEngine/src/main/Engine/Core/Input/CInput.hpp new file mode 100644 index 0000000..54d8d0f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Input/CInput.hpp @@ -0,0 +1,100 @@ +#ifndef CINPUT_HPP +#define CINPUT_HPP + +/*#include "../../Model/Input/CMouse.hpp" +#include "../../Model/Input/CKeyboard.hpp" +#include "../../Model/Input/CController.hpp" +#include "../Exception/CException.hpp" +#include "../../Model/Observer/CKeyObserver.hpp" +#include "../Exception/CExceptionManager.hpp" +#include "../CKernel.fwd.hpp"*/ + +/*#include +#include +#include */ + +/** + * @file CInput.hpp + * @brief file of the CInput class, class to handle all input event. + */ + +/** + * @brief Class to handle all input event. + */ +/*class CInput : public CKeyObserver { +private:*/ + // A pointer to the game. + //CKernel* m_kernel; + + // The event handler. + //SDL_Event m_event; + + // The mouse model. + //CMouse m_mouse; + + // The keyboard model. + //CKeyboard m_keyboard; + + // The controllers model, sorted by id. + //std::map m_controllers; + +/*public: + CInput(void) = delete; + CInput(const CInput& param) = delete; + CInput& operator=(const CInput& param) = delete;*/ + + /** + * @brief The usage constructor. + * @param[in] game A pointer to the game object, to handle specific event, like quit. + */ + //CInput(CKernel* game); + + /** + * @brief The destructor. + */ + //~CInput(void); + + /** + * @brief Function to handle all event of the game, SDL and CGame must be initialized. This function is call once per game frame. + */ + void updateEvent(void); + + /** + * @brief The keyboard getter. + * @return CKeyboard*, The keyboard. + */ + //CKeyboard* getKeyboard(void); + + /** + * @brief The mouse getter. + * @return CMouse*, The mouse. + */ + //CMouse* getMouse(void); + + /** + * @brief The controller getter. + * @param[in] id The id of the wanted controller. + * @return CController*, The controller. + */ + //CController* getController(unsigned int id); + + /** + * @brief The controllers getter. + * @return std::map, All the controllers, ordered by id. + */ + //std::map getControllers(void); + + /** + * @brief Handle key down event. + * @param[in] which The code of the key. + */ + /*virtual void onKKeyDown(unsigned int which);*/ + + /** + * @brief Handle key down event. + * @param[in] which The code of the key. + */ + //virtual void onKKeyUp(unsigned int which); +//}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.cpp b/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.cpp new file mode 100644 index 0000000..de58ca6 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.cpp @@ -0,0 +1,6 @@ + +#include "CKernel.hpp" +namespace CosmicCore { + CKernelBase* CKernelBase::m_kernelBase = nullptr; +} + diff --git a/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.hpp b/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.hpp new file mode 100644 index 0000000..64ca649 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Kernel/CKernel.hpp @@ -0,0 +1,294 @@ +#ifndef CKERNEL_HPP +#define CKERNEL_HPP + +#include "Engine/Core/Systems/Input/CInputDispatcher.hpp" +#include "../../Utils/Configurations/CBasicConfiguration.hpp" +#include +#include +#include +#include + +#include "../Systems/Graphics/Window/CGameWindow.hpp" + +#include "../Scene/CScene.hpp" +#include "../../Utils/Configurations/CEngineConfiguration.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Engine/Core/Systems/Graphics/CContext.hpp" +#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp" +#include "Engine/Core/Systems/Physics/API/CPhysicsAPI.hpp" +#include "Engine/Core/Scene/CScene.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Utils/Factory/CEntityFactory.hpp" +#include "Engine/Utils/JsonParser/Identifier.hpp" + +#include "Engine/Core/Systems/Scripts/API/CScriptAPI.hpp" +//CShader* CKernel::m_mainShader; + +// #define NAME "Cosmic Engine" +#define LOGO "assets/spaceEngineIcon.png" +// #define SPLASH "../assets/shrekt.png" +// #define SPLASH_HEIGHT 512 +// #define SPLASH_WIDTH 512 +// #define GAME_HEIGHT 360 +// #define GAME_WIDTH 640 + + +namespace CosmicCore { + using namespace CosmicUtils; + + class CKernelBase { + private: + static CKernelBase* m_kernelBase; + + public: + static CKernelBase* instance() { return m_kernelBase; } + static void setKernelInstance(CKernelBase* ins){m_kernelBase = ins;} + // Méthodes virtuelles que tous les kernels doivent avoir + virtual std::string getName() = 0; + virtual unsigned int getDeltatime() = 0; + virtual void setDeltatime(unsigned int delta) = 0; + virtual CScene* getActiveScene() = 0; + virtual void quit() = 0; + virtual void cleanup() = 0; + virtual unsigned int getWindowHeight() = 0; + virtual unsigned int getWindowWidth() = 0; + + virtual ~CKernelBase() = default; + virtual void loadScene(std::string name) = 0; + + }; + + /** + * @file CKernel.hpp + * @brief Central class of the game, handle window and I/O. + */ + + /** + * @brief Central class of the game, handle window and I/O. + */ + template + class CKernel : public CKernelBase{ + private: + std::string m_configPath; + std::string m_gameName; + // The config. + CEngineConfiguration m_engineConfig; + TGameConfig m_gameConfig; + + // The windows. + //CLoadingWindow m_loadingWindow; + CGameWindow m_window; + CInputDispatcher m_inputWorld; + + // Global game var. + bool m_finished; + unsigned int m_deltaTime; + + // The Scenes. + CScene* m_activeScene; + std::map> m_sceneMap; + + public: + + CKernel() = delete; + + std::string getName() override { return m_gameName; }; + unsigned int getWindowHeight() override {return m_window.getHeight();}; + unsigned int getWindowWidth() override {return m_window.getWidth();}; + + void cleanup() override {m_sceneMap.clear();}; + + unsigned int getDeltatime(void) override { + return m_deltaTime; + } + + void setDeltatime(unsigned int delta) override{ + m_deltaTime = delta; + } + + CKernel(std::string name, std::string gameName) : + m_gameName(gameName), m_window(gameName, LOGO, 1270, 720, true, false) + { + setKernelInstance(this); + } + + ~CKernel() + { + } + + CScene* getActiveScene() override + { + return m_activeScene; + } + + void loadScene(std::string name) + { + const char* pathBaseExe = SDL_GetBasePath(); + std::filesystem::path pathToScene = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / name; + + if(!m_sceneMap.contains(name)) + { + m_sceneMap[name] = CScene::load(pathToScene.string()); + } + + m_activeScene = m_sceneMap[name].get(); + } + + void start(bool isPreview = false) { + loadConfigurations(); + CContext::init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC); + CScriptAPI::init(); + //CScriptRegister::registerAllScripts(); + CPhysicsAPI::init(); + const char* pathBaseExe = SDL_GetBasePath(); + std::filesystem::path pathToSchema = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "schema_json.json"; + CosmicUtils::JsonValidator::init(pathToSchema); + if(!isPreview) + { + m_window.initialization(); + std::filesystem::path pathToScene = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/scenes/scene_menu.json"; + auto scene = CScene::load(pathToScene.string()); + m_activeScene = scene.get(); + m_sceneMap[scene->getName()] = std::move(scene); + } + } + + void loadConfigurations() + { + const char* pathBaseExe = SDL_GetBasePath(); + std::filesystem::path pathToEngineConf = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/configs/engine/engine.json"; + std::filesystem::path pathToGameConf = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / "assets/configs/game/game.json"; + + if(m_engineConfig.load(pathToEngineConf.string())) + { + // Configuration fenêtre + // TODO: appliquer les settings de fenêtre via CGameWindow ou GraphicsAPI + m_window.setSize(m_engineConfig.window.width, m_engineConfig.window.height); + m_window.setTitle(m_engineConfig.window.title); + if(m_engineConfig.window.fullscreen) m_window.setFullscreen(true); + + // Configuration input + std::filesystem::path pathToActions = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.actionsPath; + std::filesystem::path pathToBindings = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.bindingsPath; + + m_inputWorld.loadActions(pathToActions.string()); + m_inputWorld.loadBindings(pathToBindings.string()); + + m_inputWorld.getMapping().setMouseSensitivity(m_engineConfig.input.mouseSensitivity); + } + if(m_gameConfig.load(pathToGameConf.string())) + { + m_window.setSize(m_gameConfig.window.width, m_gameConfig.window.height); + m_window.setTitle(m_gameConfig.window.title); + if(m_gameConfig.window.fullscreen) m_window.setFullscreen(true); + + std::filesystem::path pathToActions = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.actionsPath; + std::filesystem::path pathToBindings = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / m_engineConfig.input.bindingsPath; + + + m_inputWorld.loadActions(pathToActions.string()); + m_inputWorld.loadBindings(pathToBindings.string()); + m_inputWorld.getMapping().setMouseSensitivity(m_gameConfig.input.mouseSensitivity); + } + // Configuration graphique + // TODO: GraphicsAPI::getAPI()->setValidationLayers(m_gameConfig.graphics.validationLayers); + // TODO: GraphicsAPI::getAPI()->setMaxFramesInFlight(m_gameConfig.graphics.maxFramesInFlight); + + // Configuration audio + // TODO: C AudioAPI::setMasterGain(m_gameConfig.audio.masterGain); + // TODO: C AudioAPI::setMusicGain(m_gameConfig.audio.musicGain); + + } + + void loop() { + + unsigned int frameRate(1000 / 144); + unsigned int beginIterationTime(0); + unsigned int endIterationTime(0); + unsigned int spendedIterationTime(0); + unsigned int lastFrame = 0; + m_window.setVisible(true); + m_window.setResizable(true); + while (!m_finished) { + // Define the starting time. + beginIterationTime = SDL_GetTicks(); + + // Compute the delta time. + unsigned int currentFrame = beginIterationTime; + m_deltaTime = currentFrame - lastFrame; + lastFrame = currentFrame; + + // Update event system. + //m_inputHandler.updateEvent(); + // ####### start render ####### + + SDL_Event event; + while (SDL_PollEvent(&event)) + { + if (event.type == SDL_EVENT_QUIT) + m_finished = true; + if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(m_window.getWindow())) + m_finished = true; + + m_inputWorld.processEvent(event); + } + + if(m_activeScene) + { + m_inputWorld.dispatch(m_activeScene); + m_activeScene->getScriptWorld().updateWorld(1.0f/60.0f); + m_activeScene->getTangibleWorld().updateWorld(1.0f/60.0f); + m_activeScene->getAudioWorld().updateWorld(1.0f/60.0f); + + //TODO scne update -> physics + audio + scripts ? + GraphicsAPI::getAPI()->drawFrame(); + } + + // ####### end render ####### + + // Compute the end and spended time . + endIterationTime = SDL_GetTicks(); + + spendedIterationTime = endIterationTime - beginIterationTime; + // If need, we pause the programm to have the right fps amount. + if (spendedIterationTime < frameRate) { + SDL_Delay(frameRate - spendedIterationTime); + } + } + GraphicsAPI::getAPI()->cleanup(); + CPhysicsAPI::cleanup(); + CContext::quit(); + } + + void quit() override { + m_finished = true; + } + + + void fullscreen() { + } + + void desktop() { + } + + void focus() { + } + + + }; + //template CKernel* CKernel::m_kernel; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Observer/CControllerObserver.hpp b/CosmicEngine/src/main/Engine/Core/Observer/CControllerObserver.hpp new file mode 100644 index 0000000..d35b6dd --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Observer/CControllerObserver.hpp @@ -0,0 +1,39 @@ +#ifndef CCONTROLLEROBSERVER_HPP +#define CCONTROLLEROBSERVER_HPP + +/** + * @file CControllerObserver.hpp + * @brief file of the CControllerObserver class, abstract class to extend, alloy the daugther class to handle controller event. + */ + +/** + * @brief Abstract class to extend, alloy the daugther class to handle controller event. + */ +class CControllerObserver { +private: + +public: + /** + * @brief Handle button down event. + * @param[in] controllerId The controller id. + * @param[in] which The code of the button. + */ + virtual void onCButtonDown(unsigned int controllerId, unsigned int which) = 0; + + /** + * @brief Handle button up event. + * @param[in] controllerId The controller id. + * @param[in] which The code of the button. + */ + virtual void onCButtonUp(unsigned int controllerId, unsigned int which) = 0; + + /** + * @brief Handle axis event. + * @param[in] controllerId The controller id. + * @param[in] which The id of the axis. + * @param[in] value the new Value of the axis. + */ + virtual void onCAxis(unsigned int controllerId, unsigned int which, int value) = 0; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Observer/CKeyObserver.hpp b/CosmicEngine/src/main/Engine/Core/Observer/CKeyObserver.hpp new file mode 100644 index 0000000..fcfc0f2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Observer/CKeyObserver.hpp @@ -0,0 +1,29 @@ +#ifndef CKEYOBSERVER_HPP +#define CKEYOBSERVER_HPP + +/** + * @file CKeyObserver.hpp + * @brief file of the CKeyObserver class, abstract class to extend, alloy the daugther class to handle key event. + */ + +/** + * @brief Abstract class to extend, alloy the daugther class to handle key event. + */ +class CKeyObserver { +private: + +public: + /** + * @brief Handle key down event. + * @param[in] which The code of the key. + */ + virtual void onKKeyDown(unsigned int which) = 0; + + /** + * @brief Handle key down event. + * @param[in] which The code of the key. + */ + virtual void onKKeyUp(unsigned int which) = 0; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Observer/CMouseObserver.hpp b/CosmicEngine/src/main/Engine/Core/Observer/CMouseObserver.hpp new file mode 100644 index 0000000..d094d54 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Observer/CMouseObserver.hpp @@ -0,0 +1,45 @@ +#ifndef CMOUSEOBSERVER_HPP +#define CMOUSEOBSERVER_HPP + +/** + * @file CMouseObserver.hpp + * @brief file of the CMouseObserver class, abstract class to extend, alloy the daugther class to handle mouse event. + */ + +/** + * @brief Abstract class to extend, alloy the daugther class to handle mouse event. + */ +class CMouseObserver { +private: + +public: + /** + * @brief Handle key down event. + * @param[in] which The code of the button. + */ + virtual void onMButtonDown(unsigned int which) = 0; + + /** + * @brief Handle key up event. + * @param[in] which The code of the button. + */ + virtual void onMButtonUp(unsigned int which) = 0; + + /** + * @brief Handle wheel event. + * @param[in] x The relative x value. + * @param[in] y The relative y value. + */ + virtual void onMWheel(int x, int y) = 0; + + /** + * @brief Handle move event. + * @param[in] x The new x value. + * @param[in] y The new y value. + * @param[in] xRel The relative x value. + * @param[in] yRel The relative y value. + */ + virtual void onMMove(int x, int y, int xRel, int yRel) = 0; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Observer/CTransformObserver.hpp b/CosmicEngine/src/main/Engine/Core/Observer/CTransformObserver.hpp new file mode 100644 index 0000000..3c1b8cd --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Observer/CTransformObserver.hpp @@ -0,0 +1,30 @@ +#ifndef CTRANSFORMOBSERVER_HPP +#define CTRANSFORMOBSERVER_HPP + +/** + * @file CTransformObserver.hpp + * @brief file of the CTransformObserver class, abstract class to extend, alloy the daugther class to handle transform change event. + */ + +/** + * @brief Abstract class to extend, alloy the daugther class to handle transform change event. + */ +class CTransformObserver { +public: + /** + * @brief Handle center change event. + */ + virtual void onCenterChange(void) = 0; + + /** + * @brief Handle scale change event. + */ + virtual void onScaleChange(void) = 0; + + /** + * @brief Handle rotation change event. + */ + virtual void onRotationChange(void) = 0; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Scene/CScene.cpp b/CosmicEngine/src/main/Engine/Core/Scene/CScene.cpp new file mode 100644 index 0000000..3f0d35b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Scene/CScene.cpp @@ -0,0 +1,488 @@ +#include "CScene.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Component/Graphics/CRenderer.hpp" +#include "Engine/Core/Component/Meta/CMetaData.hpp" +#include "Engine/Core/Component/Geometry/CTransform.hpp" +#include "Engine/Core/Component/Camera/CCamera.hpp" +#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp" +#include "Engine/Utils/JsonParser/Identifier.hpp" +#include "Engine/Utils/Factory/CEntityFactory.hpp" +#include "Engine/Utils/Factory/ComponentFactory.hpp" + +#include "Engine/Core/Component/Camera/CCamera2D.hpp" +#include "Engine/Core/Component/Geometry/CTransform2D.hpp" +#include "Engine/Core/Component/Graphics/CRenderer2D.hpp" +#include "Engine/Core/Component/Light/CLight.hpp" +#include "Engine/Core/Entity/EntityComponentManager.hpp" +#include "glm/ext/vector_float3.hpp" +#include "glm/gtc/type_ptr.hpp" +#include "nlohmann/json_fwd.hpp" + +#include +#include +#include +#include +#include +#include "../Systems/Graphics/Data/Light/CLightsBuffer.hpp" +namespace CosmicCore { + + CScene::CScene(std::string name) : CSerializable(), + m_name(std::move(name)), + m_tangibleWorld(this), + m_audioWorld(this), + m_scriptWorld(this) + { + m_tangibleWorld.initWorld(); + m_audioWorld.initWorld(); + m_scriptWorld.initWorld(); + m_lightsBuffer.init(); + //m_uiWorld.init(); + + m_ecManager.registry.sort([](const CTransform2D& lhs, const CTransform2D& rhs) { + return lhs.getZOrder() > rhs.getZOrder(); + }); + } + + + std::string CScene::getName(void) const { + return m_name; + } + + CScene::~CScene() + { + m_tangibleWorld.destroy(); + m_audioWorld.destroy(); + m_scriptWorld.destroy(); + m_lightsBuffer.destroy(); + //m_uiWorld.destroy(); + } + + CEntity CScene::createEntity(){ + auto handle = m_ecManager.registry.create(); + CEntity handler(m_ecManager, handle, this); + return handler; + } + + unsigned int CScene::getNumEntity(void) const { + return m_ecManager().view()->size(); + } + + void CScene::removeEntity(unsigned int index, bool destroy) + { + + } + + void CScene::collectLights(vk::raii::CommandBuffer& cmd, uint32_t frameIndex) { + auto& registry = m_ecManager.registry; + auto view = registry.view(); + + SLightsUBOData lightsData{}; + + for (auto entity : view) { + if (lightsData.lightCount >= MAX_LIGHTS) break; + + auto& light = registry.get(entity); + auto& transform = registry.get(entity); + + SLightData data{}; + glm::vec3 pos = transform.getCenter(); + glm::vec3 dir = transform.getOrientation() * glm::vec3(0, -1, 0); + + data.position = {pos.x, pos.y, pos.z, (float)light.getType()}; + data.direction = {dir.x, dir.y, dir.z, light.getRange()}; + data.color = {light.getColor().x, light.getColor().y, + light.getColor().z, light.getIntensity()}; + data.innerCosAngle = glm::cos(glm::radians(light.getInnerAngle())); + data.outerCosAngle = glm::cos(glm::radians(light.getOuterAngle())); + data.attenuation = light.getAttenuation(); + + lightsData.lights[lightsData.lightCount++] = data; + } + + // upload dans le SSBO + m_lightsBuffer.update(frameIndex, lightsData); + } + + void CScene::render3D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){ + auto entities = m_ecManager.registry.view(); + + if(entities.begin() != entities.end()) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto cam = m_ecManager.registry.view(); + auto& camera = m_ecManager.registry.get(cam.front()); + auto& transform = m_ecManager.registry.get(cam.front()); + + collectLights(cmd, frameIndex); + + camera.updateUniformBuffer(frameIndex, transform); + + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + api->getDefaultPipelineLayout(), // layout du pipeline + 0, + *camera.getDescriptorSet(frameIndex), + {} + ); + + //bind lumières (set 3) + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, + api->getDefaultPipelineLayout(), 3, + *m_lightsBuffer.getDescriptorSet(frameIndex), {}); + + + for (auto& entity : entities) { + auto model = m_ecManager.registry.get(entity).getModel(); + auto& transform = m_ecManager.registry.get(entity); + + transform.updateUniformBuffer(frameIndex); + //trier meshes par matérial ? + + // bind transform UBO (set = 1) + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + api->getDefaultPipelineLayout(), // layout du pipeline + 1, // set = 1 + *transform.getDescriptorSet(frameIndex), + {} + ); + + for (auto& mm : model->getMeshMaterials()) { + // ne rebind le pipeline que si le material change + //if (mesh.getMaterial() != boundMaterial) { + //boundMaterial = mesh.getMaterial(); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, + *mm.material->getPipeline()); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, + *mm.material->getPipelineLayout(), + 2, + *mm.material->getDescriptorSet(frameIndex), + {}); + //} + + cmd.bindVertexBuffers(0, vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getVertexOffset()); + cmd.bindIndexBuffer(vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getIndexOffset(), vk::IndexType::eUint32); + cmd.drawIndexed(mm.mesh->getIndexCount(), 1, 0, 0, 0); + } + } + } + } + + void CScene::render2D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){ + + auto entities = m_ecManager.registry.view(); + + if(entities.begin() != entities.end()) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto cam = m_ecManager.registry.view(); + auto& camera = m_ecManager.registry.get(cam.front()); + auto& trCam = m_ecManager.registry.get(cam.front()); + camera.updateUniformBuffer(frameIndex, trCam); + // + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + api->getDefault2DPipelineLayout(), // layout du pipeline + 2, + *camera.getDescriptorSet(frameIndex), + {} + ); + + struct ENT_DRAW { entt::entity e; float z; }; + std::vector entitiesSortedToDraw; + entitiesSortedToDraw.reserve(entities.size_hint()); + + for (auto e : entities) + entitiesSortedToDraw.push_back({ e, m_ecManager.registry.get(e).getZOrder() }); + + std::ranges::sort(entitiesSortedToDraw, [](const ENT_DRAW& a, const ENT_DRAW& b) { return a.z < b.z; }); + + for (auto& entity : entitiesSortedToDraw) { + auto model = m_ecManager.registry.get(entity.e).getModel(); + auto& transform = m_ecManager.registry.get(entity.e); + + transform.updateUniformBuffer(frameIndex); + + // bind transform UBO (set = 1) + cmd.bindDescriptorSets( + vk::PipelineBindPoint::eGraphics, + api->getDefault2DPipelineLayout(), // layout du pipeline + 0, // set = 1 + *transform.getDescriptorSet(frameIndex), + {} + ); + + for (auto& mm : model->getMeshMaterials()) { + // ne rebind le pipeline que si le material change + //if (mesh.getMaterial() != boundMaterial) { + //boundMaterial = mesh.getMaterial(); + cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, + *mm.material->getPipeline()); + cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, + *mm.material->getPipelineLayout(), + 1, + *mm.material->getDescriptorSet(frameIndex), + {}); + //} + + cmd.bindVertexBuffers(0, vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getVertexOffset()); + cmd.bindIndexBuffer(vk::Buffer(mm.mesh->getVertexIndexBuffer().buffer), mm.mesh->getIndexOffset(), vk::IndexType::eUint32); + cmd.drawIndexed(mm.mesh->getIndexCount(), 1, 0, 0, 0); + } + } + } + } + + void CScene::render(vk::raii::CommandBuffer& cmd, uint32_t frameIndex){ + render3D(cmd, frameIndex); + render2D(cmd, frameIndex); + } + + nlohmann::json CScene::to_json() + { + return nlohmann::json(); + } + + std::unique_ptr CScene::load(const std::string &path) + { + const char* pathBaseExe = SDL_GetBasePath(); + std::string prefix = (pathBaseExe ? std::string(pathBaseExe) : ".") + '/'; + + + + std::ifstream file(path); + nlohmann::json sceneJson = nlohmann::json::parse(file); + if(CosmicUtils::JsonValidator::validate(sceneJson)) + { + std::string sceneName = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Name)]; + + std::unordered_map idToHandle; + std::unordered_map idToParent; + std::unordered_map> idToChildren; + + //TODO add descritpion to members + std::string sceneDescription = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Description)]; + auto scene = std::make_unique(sceneName); + nlohmann::json& entities = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Entities)]; + for(auto& entity : entities.items()) + { + nlohmann::json& entityObj = entity.value(); + auto ref = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Ref)].get(); + std::optional parent = !entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].is_null() ? std::optional(entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].get()) : std::nullopt; + auto children = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Children)].get>(); + + nlohmann::json& components = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Components)]; + nlohmann::json& transform = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Transform)]; + nlohmann::json& camera = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Camera)]; + nlohmann::json& collider = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Collider)]; + nlohmann::json& rigidbody = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Rigidbody)]; + nlohmann::json& renderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Renderer)]; + nlohmann::json& speaker = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Speaker)]; + nlohmann::json& script = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Script)]; + nlohmann::json& light = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Light)]; + + auto trConfig(!transform.is_null() ? std::optional({ + glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Position)].get>().data()), + glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Rotation)].get>().data()), + glm::make_vec3(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Scale)].get>().data()) + }) : std::nullopt); + + auto camConfig(!camera.is_null() ? std::optional({ + camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Fov)].get(), + camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Near)].get(), + camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Far)].get() + }) : std::nullopt); + + auto colliderConfig(!collider.is_null() ? std::optional({ + static_cast(collider[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Collider_Type)].get()), + glm::vec3(), + 0, + 0, + }) : std::nullopt); + + auto rigidbodyConfig(!rigidbody.is_null() ? std::optional({ + static_cast(rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Type)].get()), + rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Mass)].get(), + rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Friction)].get(), + rigidbody[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::RigidBody_Restitution)].get() + }) : std::nullopt); + + auto rendererConfig(!renderer.is_null() ? std::optional({ + prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Model)].get(), + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Shader)].get(), + !renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Albedo)].is_null() ? std::optional(prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Albedo)].get()) : std::nullopt, + }) : std::nullopt); + + auto scriptConfig(!script.is_null() ? std::optional({ + script.get>() + }): std::nullopt); + + std::optional speakerConfig = std::nullopt; + if(!speaker.is_null()) + { + if(!speaker[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Clips)].empty()) + { + speakerConfig = std::optional(CosmicUtils::ComponentFactory::SpeakerConfig()); + for(auto clipConf : speaker[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Clips)]) + { + CosmicUtils::ComponentFactory::SpeakerConfig::SoundClipConfig conf + { + prefix + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Path)].get(), + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Gain)].get(), + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Pitch)].get(), + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Loop)].get(), + clipConf[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Speaker_Spatial)].get() + }; + speakerConfig->clips.push_back(conf); + } + } + } + + auto lightConfig(!light.is_null() ? std::optional( + { + static_cast(light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Type)].get()), + glm::make_vec3(light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Color)].get>().data()), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Intensity)].get(), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Range)].get(), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_Attenuation)].get(), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_InnerAngle)].get(), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_OuterAngle)].get(), + light[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Light_CastShadow)].get() + }) : std::nullopt); + + CosmicUtils::CEntityFactory::EntityConfig config = { + entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Name)], + entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Description)], + trConfig, + camConfig, + rendererConfig, + colliderConfig, + rigidbodyConfig, + speakerConfig, + scriptConfig, + lightConfig + }; + + auto entityHandle = CosmicUtils::CEntityFactory::create(scene.get(), config); + idToHandle.emplace(std::make_pair(ref, entityHandle)); + if(parent.has_value()) + idToParent[ref] = parent.value(); + + for(auto i : children) + { + idToChildren[ref].push_back(i); + } + } + + nlohmann::json& entities2D = sceneJson[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Scene_Entities2D)]; + for(auto& entity : entities2D.items()) + { + nlohmann::json& entityObj = entity.value(); + auto ref = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Ref)].get(); + + std::optional parent = !entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].is_null() ? std::optional(entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Parent)].get()) : std::nullopt; + auto children = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity_Children)].get>(); + + nlohmann::json& components = entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Components)]; + nlohmann::json& transform = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Transform2D)]; + nlohmann::json& camera = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Camera2D)]; + nlohmann::json& collider = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Collider2D)]; + nlohmann::json& renderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Renderer2D)]; + nlohmann::json& script = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_Script)]; + nlohmann::json& textRenderer = components[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Component_TextRenderer2D)]; + + auto trConfig(!transform.is_null() ? std::optional({ + glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Position2D)].get>().data()), + glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Size2D)].get>().data()), + glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Scale2D)].get>().data()), + glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Pivot2D)].get>().data()), + glm::make_vec2(transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Anchor2D)].get>().data()), + transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Rotation2D)].get(), + transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_zOrder2D)].get(), + transform[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Transform_Visible2D)].get() + }) : std::nullopt); + + auto camConfig(!camera.is_null() ? std::optional({ + camera[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Camera_Zoom2D)].get() + }) : std::nullopt); + + auto colliderConfig(!collider.is_null() ? std::optional({ + static_cast(collider[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Collider_Shape2D)].get()) + }) : std::nullopt); + + auto rendererConfig(!renderer.is_null() ? std::optional({ + prefix + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Model2D)].get(), + renderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Renderer_Shader2D)].get(), + }) : std::nullopt); + + auto scriptConfig(!script.is_null() ? std::optional({ + script.get>() + }): std::nullopt); + + auto textRenderer2DConfig(!textRenderer.is_null() ? std::optional({ + textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Text2D)].get(), + textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Shader2D)].get(), + glm::make_vec4(textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Color2D)].get>().data()), + prefix + textRenderer[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::TextRenderer_Font2D)].get() + }) : std::nullopt); + + + CosmicUtils::CEntityFactory::Entity2DConfig config = { + entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Name)], + entityObj[CosmicUtils::JsonKeyRegistry::key(CosmicUtils::EJsonKeys::Entity2D_Description)], + trConfig, + camConfig, + rendererConfig, + colliderConfig, + scriptConfig, + textRenderer2DConfig + }; + + auto entityHandle = CosmicUtils::CEntityFactory::create(scene.get(), config); + + idToHandle.emplace(std::make_pair(ref, entityHandle)); + if(parent.has_value()) + idToParent[ref] = parent.value(); + + for(auto i : children) + { + idToChildren[ref].push_back(i); + } + + } + + //Connect entities to relationships + for(auto& [entityNb, handle]: idToHandle) + { + CosmicUtils::ComponentFactory::RelationshipConfig cnf; + if(idToParent.find(entityNb) != idToParent.end()) + { + cnf.parent = std::optional(idToHandle.at(idToParent.at(entityNb)).getHandle()); + } + else + { + cnf.parent = std::nullopt; + } + + for(auto& child : idToChildren[entityNb]) + { + cnf.children.push_back(idToHandle.at(child).getHandle()); + } + CosmicUtils::ComponentFactory::addRelationship(handle, cnf); + } + + return scene; + } + return nullptr; + } + + void CScene::save(CScene *scene, const std::string &path) + { + + } + + void CScene::save(const std::string& path) + { + save(this, path); + } +} diff --git a/CosmicEngine/src/main/Engine/Core/Scene/CScene.hpp b/CosmicEngine/src/main/Engine/Core/Scene/CScene.hpp new file mode 100644 index 0000000..edd7274 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Scene/CScene.hpp @@ -0,0 +1,121 @@ +#ifndef CSCENE_HPP +#define CSCENE_HPP + +#include "Engine/Core/Entity/EntityComponentManager.hpp" +#include "Engine/Utils/JsonParser/CSerializable.hpp" +#include +#include +#include "Engine/Core/Systems/Physics/CTangibleWorld.hpp" +#include "Engine/Core/Systems/Audio/CAudioWorld.hpp" +#include "Engine/Core/Systems/Scripts/CScriptWorld.hpp" +#include "Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.hpp" +#include "Engine/Core/Systems/Graphics/UserInterface/CUIWorld.hpp" + +namespace CosmicCore { + class CEntity; + class CScene : public CSerializable { + private: + // The name of the scene. + std::string m_name; + EntityComponentManager m_ecManager; + CTangibleWorld m_tangibleWorld; + CAudioWorld m_audioWorld; + CScriptWorld m_scriptWorld; + CLightsBuffer m_lightsBuffer; + //CUIWorld m_uiWorld; + + void render3D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex); + void render2D(vk::raii::CommandBuffer& cmd, uint32_t frameIndex); + + public: + CScene() = delete; + CScene(std::string name); + CScene(CScene&&) = delete; + CScene& operator=(CScene&&) = delete; + CScene(const CScene&) = delete; + CScene& operator=(const CScene&) = delete; + + virtual ~CScene(); + + unsigned int getNumEntity() const; + + CEntity createEntity(); + + std::string getName() const; + + EntityComponentManager& getECManager(){return m_ecManager;}; + + void removeEntity(unsigned int index, bool destroy = true); + + CTangibleWorld& getTangibleWorld() {return m_tangibleWorld;}; + + CAudioWorld& getAudioWorld() {return m_audioWorld;}; + + CScriptWorld& getScriptWorld() {return m_scriptWorld;}; + + //CUIWorld& getUIWorld() {return m_uiWorld;}; + //CEntity* getActiveCamera(); + //void setActiveCamera(CEntity* newCamera); + + /** + * @brief Getter to the light. + * @return The pointer m_mainLight. + */ + //CEntity* getMainLight(); + + /** + * @brief Setter of the light. + * @param light : The light to set as main light. + */ + //void setMainLight(CEntity* light); + + /** + * @brief Setter of the ODE world handling class. + * @param[in, out] world The pointer to the physical world. + */ + //void setTangibleWorld(CTangibleWorld* world); + + /** + * @brief Getter to the physical world of the environment. + * @return The pointer m_tangibleWorld. + */ + //std::weak_ptr getTangibleWorld(); + + /** + * @brief Setter of the layer mask. + * @param[in] mask The new mask value. + */ + void setMask(unsigned int mask); + + /** + * @brief Getter to the layer mask. + * @return The value of m_maskLayer. + */ + //unsigned int getMask(); + + void render(vk::raii::CommandBuffer& cmd, uint32_t frameIndex); + + void collectLights(vk::raii::CommandBuffer& cmd, uint32_t frameIndex); + //void updateScript(); + + nlohmann::json to_json(); + + /*static CScene* from_json(nlohmann::json& j) + { + CScene* s = new CScene(j["Name"]); + for (nlohmann::json& entity : j["Entities"]) + { + CEntity* e = CEntity::from_json(s, entity); + s->addEntity(e); + } + return s; + };*/ + + static std::unique_ptr load(const std::string& path); + static void save(CScene* scene, const std::string& path); + + void save(const std::string& path); + + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.cpp new file mode 100644 index 0000000..59c8495 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.cpp @@ -0,0 +1,8 @@ +#include "CAudioAPI.hpp" + +namespace CosmicCore { + CAudioAPI::~CAudioAPI() + { + + } +} diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.hpp new file mode 100644 index 0000000..ed169b8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Audio/API/CAudioAPI.hpp @@ -0,0 +1,25 @@ +#ifndef CAUDIOAPI_HPP +#define CAUDIOAPI_HPP +namespace CosmicCore { + + class CScene; + /** + * @brief Class representing any audio world - abstract. + */ + class CAudioAPI { + + private: + CScene* m_scene; + public: + CAudioAPI(CScene* scene): m_scene(scene){}; + virtual ~CAudioAPI(); + + virtual void updateWorld(float delta) = 0; + + virtual void initWorld() = 0; + virtual void destroy() = 0; + + CScene* getScene(){return m_scene;}; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.cpp new file mode 100644 index 0000000..0d2486e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.cpp @@ -0,0 +1,61 @@ +#include "CAudioWorld.hpp" +#include "Engine/Core/Scene/CScene.hpp" +#include "Engine/Core/Component/Camera/CCamera.hpp" +#include "Engine/Core/Component/Speaker/CSpeaker.hpp" + +#include + +namespace CosmicCore { + + CAudioWorld::~CAudioWorld() + { + + } + + void CAudioWorld::initWorld() { + m_device = alcOpenDevice(nullptr); + m_context = alcCreateContext(m_device, nullptr); + alcMakeContextCurrent(m_context); + + // active le distance model + alDistanceModel(AL_LINEAR_DISTANCE_CLAMPED); + alListenerf(AL_GAIN, 1.0f); + } + + void CAudioWorld::updateWorld(float delta) { + auto& registry = getScene()->getECManager().registry; + + // met à jour la position de l'écouteur depuis la caméra + auto camView = registry.view(); + if (camView.begin() != camView.end()) { + auto& camTransform = registry.get(camView.front()); + glm::vec3 pos = camTransform.getCenter(); + glm::vec3 forward = camTransform.getOrientation() * glm::vec3(0,0,-1); + glm::vec3 up = camTransform.getOrientation() * glm::vec3(0,1,0); + + alListener3f(AL_POSITION, pos.x, pos.y, pos.z); + float orientation[6] = { + forward.x, forward.y, forward.z, + up.x, up.y, up.z + }; + alListenerfv(AL_ORIENTATION, orientation); + } + + // met à jour la position de chaque speaker + auto view = registry.view(); + for (auto entity : view) { + auto& speaker = registry.get(entity); + auto& transform = registry.get(entity); + speaker.updatePosition( + transform, + {0.0f,0.0f,0.0f} // si tu as une vélocité dans CTransform + ); + } + } + + void CAudioWorld::destroy() { + alcMakeContextCurrent(nullptr); + alcDestroyContext(m_context); + alcCloseDevice(m_device); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.hpp new file mode 100644 index 0000000..8dccb34 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Audio/CAudioWorld.hpp @@ -0,0 +1,26 @@ +#ifndef CAUDIOWORLD_HPP +#define CAUDIOWORLD_HPP + +#include + +#include "API/CAudioAPI.hpp" + +namespace CosmicCore { + + class CAudioWorld : public CAudioAPI{ + ALCdevice* m_device = nullptr; + ALCcontext* m_context = nullptr; + + public: + CAudioWorld(CScene* scene) : CAudioAPI(scene) {} + ~CAudioWorld(); + void initWorld(); + + void updateWorld(float delta); + + void destroy(); + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Audio/Sound/CAudioClip.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Audio/Sound/CAudioClip.hpp new file mode 100644 index 0000000..dead8ed --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Audio/Sound/CAudioClip.hpp @@ -0,0 +1,20 @@ +#ifndef CAUDIOCLIP_HPP +#define CAUDIOCLIP_HPP +#include + +#include + +class CAudioClip { + private: + public: + ALuint buffer = 0; + std::string path; + float duration = 0.0f; + + + ~CAudioClip() { + if (buffer) alDeleteBuffers(1, &buffer); + } +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.cpp new file mode 100644 index 0000000..523f665 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.cpp @@ -0,0 +1,10 @@ +#include "GraphicsAPI.hpp" +#include "VulkanImplementation/VulkanImpl.hpp" +#include + +std::unique_ptr GraphicsAPI::impl = nullptr; + +void GraphicsAPI::initAPI(){ + //todo check config for chosen api + impl = std::make_unique(); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp new file mode 100644 index 0000000..79c05cb --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp @@ -0,0 +1,26 @@ +#ifndef GRAPHICAPI_HPP +#define GRAPHICAPI_HPP + +#include +#include + +enum class GraphicsBackend{ + Vulkan, + OpenGL, + Metal +}; + +class GraphicsAPI{ + static std::unique_ptr impl; + public: + static void initAPI(); + static std::unique_ptr& getAPI(){return impl;}; + virtual void init(SDL_Window* window) = 0; + virtual void cleanup() = 0; + virtual ~GraphicsAPI(){}; + virtual void* getDevice() = 0; + virtual void drawFrame() = 0; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/Constants.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/Constants.hpp new file mode 100644 index 0000000..085e987 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/Constants.hpp @@ -0,0 +1 @@ +#define MAX_FRAMES_IN_FLIGHT 2 \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/DeletionQueue.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/DeletionQueue.hpp new file mode 100644 index 0000000..4daa1f3 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/DeletionQueue.hpp @@ -0,0 +1,54 @@ +#ifndef DELETIONQUEUE_HPP +#define DELETIONQUEUE_HPP + +#include +#include +#include +#include +#include "Constants.hpp" + +class DeletionQueue { +private: + // une queue par frame + une queue immédiate + std::array>, MAX_FRAMES_IN_FLIGHT> m_frameQueues; + std::deque> m_immediateQueue; + +public: + // destruction différée - attendre MAX_FRAMES_IN_FLIGHT frames + void push(uint32_t currentFrame, std::function&& func) { + // on enfile dans la frame "opposée" pour attendre un cycle complet + uint32_t targetFrame = (currentFrame + MAX_FRAMES_IN_FLIGHT - 1) % MAX_FRAMES_IN_FLIGHT; + m_frameQueues[targetFrame].push_back(std::move(func)); + } + + // destruction immédiate - device.waitIdle() doit avoir été appelé avant + void pushImmediate(std::function&& func) { + m_immediateQueue.push_back(std::move(func)); + } + + // appelé au début de chaque frame - détruit les ressources de cette frame + void flush(uint32_t frameIndex) { + auto& queue = m_frameQueues[frameIndex]; + while (!queue.empty()) { + queue.front()(); + queue.pop_front(); + } + } + + // appelé à la fermeture - détruit tout + void flushAll() { + // vider toutes les frame queues + for (auto& queue : m_frameQueues) { + while (!queue.empty()) { + queue.front()(); + queue.pop_front(); + } + } + // vider la queue immédiate + while (!m_immediateQueue.empty()) { + m_immediateQueue.front()(); + m_immediateQueue.pop_front(); + } + } +}; +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp new file mode 100644 index 0000000..ec4ed0b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp @@ -0,0 +1,21 @@ +#ifndef MANAGEDDESCRIPTORSET_HPP +#define MANAGEDDESCRIPTORSET_HPP + +#include +#include + +#define MAX_FRAMES_IN_FLIGHT 2 + +struct ManagedDescriptorSet { + vk::raii::DescriptorSet set = nullptr; + VkDescriptorPool ownerPool = VK_NULL_HANDLE; + + ManagedDescriptorSet() = default; + ManagedDescriptorSet(ManagedDescriptorSet&&) = default; + ManagedDescriptorSet& operator=(ManagedDescriptorSet&&) = default; + + ManagedDescriptorSet(const ManagedDescriptorSet&) = delete; + ManagedDescriptorSet& operator=(const ManagedDescriptorSet&) = delete; +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp new file mode 100644 index 0000000..6bce8f1 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp @@ -0,0 +1,15 @@ +#ifndef VMABUFFER_HPP +#define VMABUFFER_HPP + +#include "vk_mem_alloc.h" + +typedef struct vmaBufferStruct { + VkBuffer buffer = VK_NULL_HANDLE; + VmaAllocation allocation = VK_NULL_HANDLE; + + void destroy(VmaAllocator allocator) { + vmaDestroyBuffer(allocator, buffer, allocation); + } +}VMABuffer; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMAUsage.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMAUsage.cpp new file mode 100644 index 0000000..00317e0 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VMAUsage.cpp @@ -0,0 +1,2 @@ +#define VMA_IMPLEMENTATION +#include "vk_mem_alloc.h" \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.cpp new file mode 100644 index 0000000..a074277 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.cpp @@ -0,0 +1,862 @@ +#include "VulkanImpl.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../../Kernel/CKernel.hpp" +#include "DeletionQueue.hpp" +#include "vulkan/vulkan.hpp" +#include "../../../Resources/API/CResourceAPI.hpp" + +static uint32_t chooseSwapMinImageCount(vk::SurfaceCapabilitiesKHR const &surfaceCapabilities) +{ + auto minImageCount = std::max(3u, surfaceCapabilities.minImageCount); + if ((0 < surfaceCapabilities.maxImageCount) && (surfaceCapabilities.maxImageCount < minImageCount)) + { + minImageCount = surfaceCapabilities.maxImageCount; + } + return minImageCount; +} + +static vk::SurfaceFormatKHR chooseSwapSurfaceFormat(std::vector const &availableFormats) +{ + assert(!availableFormats.empty()); + const auto formatIt = std::ranges::find_if( + availableFormats, + [](const auto &format) { return format.format == vk::Format::eB8G8R8A8Srgb && format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear; }); + return formatIt != availableFormats.end() ? *formatIt : availableFormats[0]; +} + +static vk::PresentModeKHR chooseSwapPresentMode(const std::vector &availablePresentModes) +{ + assert(std::ranges::any_of(availablePresentModes, [](auto presentMode) { return presentMode == vk::PresentModeKHR::eFifo; })); + return std::ranges::any_of(availablePresentModes, + [](const vk::PresentModeKHR value) { return vk::PresentModeKHR::eMailbox == value; }) ? + vk::PresentModeKHR::eMailbox : + vk::PresentModeKHR::eFifo; +} + +vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR &capabilities, SDL_Window* window) +{ + if (capabilities.currentExtent.width != 0xFFFFFFFF) + { + return capabilities.currentExtent; + } + int width, height; + SDL_GetWindowSizeInPixels(window, &width, &height); + + return { + std::clamp(width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width), + std::clamp(height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height)}; +} + +void VulkanImpl::init(SDL_Window* window){ + m_window = window; + createInstance(); + createSurface(); + pickPhysicalDevice(); + createLogicalDevice(); + + //getShaders after creating device + CResourceAPI::resources().shaders().create(); + CResourceAPI::resources().shaders().compile(); + + createSwapChain(); + createImageViews(); + createDescriptorSetLayouts(); + //createGraphicsPipeline(); + createDepthResources(); + createCommandPool(); + createDescriptorPool(); + createDefaultTexture(); + createCommandBuffer(); + createSyncObjects(); +} + +void VulkanImpl::cleanup(){ + device.waitIdle(); + // détruire les ressources dans le ResourceManager + // (buffers, pipelines, descriptor sets...) + m_deletionQueue.flushAll(); + + CosmicCore::CKernelBase::instance()->cleanup(); + CResourceAPI::resources().cleanup(); + + m_deletionQueue.flushAll(); + + // 2. sync objects + inFlightFences.clear(); + renderFinishedSemaphores.clear(); + presentCompleteSemaphores.clear(); + + // 3. command buffers puis command pool + commandBuffers.clear(); + commandPool = nullptr; + + // 4. swapchain + cleanupSwapChain(); + + // descriptor set layouts + pipeline layout avant le device + defaultPipelineLayoutInfo = nullptr; + default2DPipelineLayoutInfo = nullptr; + cameraLayout = nullptr; + transformLayout = nullptr; + materialLayout = nullptr; + lightLayout = nullptr; + + projection2DLayout = nullptr; + transform2DLayout = nullptr; + material2DLayout = nullptr; + VmaTotalStatistics stats; + vmaCalculateStatistics(allocator, &stats); + if (stats.total.statistics.allocationCount > 0) { + std::cout << "VMA: " << stats.total.statistics.allocationCount + << " allocations non libérées !" << std::endl; + std::cout << "VMA: " << stats.total.statistics.allocationBytes + << " bytes non libérés" << std::endl; + } + + //Vulkan memory allocator + vmaDestroyAllocator(allocator); + + // surface + surface = nullptr; + + // device en avant-dernier + device = nullptr; + + // instance en dernier + instance = nullptr; +} + +void VulkanImpl::createInstance(){ + + constexpr vk::ApplicationInfo appInfo{ "CosmicEngine", + VK_MAKE_VERSION( 1, 0, 0 ), + "No Engine", + VK_MAKE_VERSION( 1, 0, 0 ), + vk::ApiVersion13}; + + uint32_t sdl_extensions_count = 0; + + const char* const* sdl_extensions = SDL_Vulkan_GetInstanceExtensions(&sdl_extensions_count); + auto extensionProp = context.enumerateInstanceExtensionProperties(); + for (uint32_t i = 0; i < sdl_extensions_count; ++i) + { + if (std::ranges::none_of(extensionProp, + [sdlExtension = sdl_extensions[i]](auto const& extensionProperty) + { return strcmp(extensionProperty.extensionName, sdlExtension) == 0; })) + { + throw std::runtime_error("Required SDL extension not supported: " + std::string(sdl_extensions[i])); + } + } + + + // Get the required layers + std::vector requiredLayers; + if (enableValidationLayers) + { + requiredLayers.assign(validationLayers.begin(), validationLayers.end()); + } + + // Check if the required layers are supported by the Vulkan implementation. + auto layerProperties = context.enumerateInstanceLayerProperties(); + auto unsupportedLayerIt = std::ranges::find_if(requiredLayers, + [&layerProperties](auto const &requiredLayer) { + return std::ranges::none_of(layerProperties, + [requiredLayer](auto const &layerProperty) { return strcmp(layerProperty.layerName, requiredLayer) == 0; }); + }); + if (unsupportedLayerIt != requiredLayers.end()) + { + throw std::runtime_error("Required layer not supported: " + std::string(*unsupportedLayerIt)); + } + + vk::InstanceCreateInfo createInfo{{},&appInfo, static_cast(requiredLayers.size()), requiredLayers.data(), sdl_extensions_count, sdl_extensions}; + + + instance = vk::raii::Instance(context, createInfo); +} + +void VulkanImpl::pickPhysicalDevice() +{ + std::vector devices = instance.enumeratePhysicalDevices(); + const auto devIter = std::ranges::find_if( + devices, + [&](auto const &device) { + // Check if the device supports the Vulkan 1.3 API version + bool supportsVulkan1_3 = device.getProperties().apiVersion >= VK_API_VERSION_1_3; + + // Check if any of the queue families support graphics operations + auto queueFamilies = device.getQueueFamilyProperties(); + bool supportsGraphics = + std::ranges::any_of(queueFamilies, [](auto const &qfp) { return !!(qfp.queueFlags & vk::QueueFlagBits::eGraphics); }); + + // Check if all required device extensions are available + auto availableDeviceExtensions = device.enumerateDeviceExtensionProperties(); + bool supportsAllRequiredExtensions = + std::ranges::all_of(requiredDeviceExtension, + [&availableDeviceExtensions](auto const &requiredDeviceExtension) { + return std::ranges::any_of(availableDeviceExtensions, + [requiredDeviceExtension](auto const &availableDeviceExtension) { return strcmp(availableDeviceExtension.extensionName, requiredDeviceExtension) == 0; }); + }); + + auto features = device.template getFeatures2(); + bool supportsRequiredFeatures = features.template get().dynamicRendering && + features.template get().extendedDynamicState; + + return supportsVulkan1_3 && supportsGraphics && supportsAllRequiredExtensions && supportsRequiredFeatures; + }); + if (devIter != devices.end()) + { + physicalDevice = *devIter; + } + else + { + throw std::runtime_error("failed to find a suitable GPU!"); + } +} + +void VulkanImpl::createLogicalDevice() +{ + // find the index of the first queue family that supports graphics + std::vector queueFamilyProperties = physicalDevice.getQueueFamilyProperties(); + + // get the first index into queueFamilyProperties which supports graphics + auto graphicsQueueFamilyProperty = std::ranges::find_if(queueFamilyProperties, [](auto const &qfp) { return (qfp.queueFlags & vk::QueueFlagBits::eGraphics) != static_cast(0); }); + assert(graphicsQueueFamilyProperty != queueFamilyProperties.end() && "No graphics queue family found!"); + + auto graphicsIndex = static_cast(std::distance(queueFamilyProperties.begin(), graphicsQueueFamilyProperty)); + + // determine a queueFamilyIndex that supports present + // first check if the graphicsIndex is good enough + auto presentIndex = physicalDevice.getSurfaceSupportKHR( graphicsIndex, *surface ) + ? graphicsIndex + : static_cast( queueFamilyProperties.size() ); + if ( presentIndex == queueFamilyProperties.size() ) + { + // the graphicsIndex doesn't support present -> look for another family index that supports both + // graphics and present + for ( size_t i = 0; i < queueFamilyProperties.size(); i++ ) + { + if ( ( queueFamilyProperties[i].queueFlags & vk::QueueFlagBits::eGraphics ) && + physicalDevice.getSurfaceSupportKHR( static_cast( i ), *surface ) ) + { + graphicsIndex = static_cast( i ); + presentIndex = graphicsIndex; + queueIndex = graphicsIndex; + break; + } + } + if ( presentIndex == queueFamilyProperties.size() ) + { + // there's nothing like a single family index that supports both graphics and present -> look for another + // family index that supports present + for ( size_t i = 0; i < queueFamilyProperties.size(); i++ ) + { + if ( physicalDevice.getSurfaceSupportKHR( static_cast( i ), *surface ) ) + { + presentIndex = static_cast( i ); + break; + } + } + } + } + if ( ( graphicsIndex == queueFamilyProperties.size() ) || ( presentIndex == queueFamilyProperties.size() ) ) + { + throw std::runtime_error( "Could not find a queue for graphics or present -> terminating" ); + } + + queueIndex = graphicsIndex; + + // query for Vulkan 1.3 features + + auto features = physicalDevice.getFeatures2(); + vk::PhysicalDeviceVulkan11Features vulkan11Features; + vulkan11Features.shaderDrawParameters = vk::True; + + vk::PhysicalDeviceVulkan13Features vulkan13Features; + vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures; + vulkan13Features.dynamicRendering = vk::True; + vulkan13Features.synchronization2 = vk::True; + extendedDynamicStateFeatures.extendedDynamicState = vk::True; + vulkan11Features.pNext = &vulkan13Features; + vulkan13Features.pNext = &extendedDynamicStateFeatures; + features.pNext = &vulkan11Features; + + // create a Device + float queuePriority = 0.5f; + vk::DeviceQueueCreateInfo deviceQueueCreateInfo{{}, + graphicsIndex, + 1, + &queuePriority}; + + vk::DeviceCreateInfo deviceCreateInfo{{}, + 1, + &deviceQueueCreateInfo, + {}, + {}, + static_cast(requiredDeviceExtension.size()), + requiredDeviceExtension.data(), + {}, + &features + }; + + + device = vk::raii::Device(physicalDevice, deviceCreateInfo); + graphicsQueue = vk::raii::Queue(device, graphicsIndex, 0); + presentQueue = vk::raii::Queue( device, presentIndex, 0 ); + + VmaAllocatorCreateInfo allocatorInfo{}; + allocatorInfo.physicalDevice = *physicalDevice; + allocatorInfo.device = *device; + allocatorInfo.instance = *instance; + allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3; + vmaCreateAllocator(&allocatorInfo, &allocator); +} + +void VulkanImpl::createSurface() +{ + VkSurfaceKHR _surface; + if (!SDL_Vulkan_CreateSurface(m_window, *instance, nullptr, &_surface)) { + throw std::runtime_error("failed to create window surface!"); + } + surface = vk::raii::SurfaceKHR(instance, _surface); +} + +void VulkanImpl::createSwapChain() +{ + auto surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(*surface); + swapChainExtent = chooseSwapExtent(surfaceCapabilities, m_window); + swapChainSurfaceFormat = chooseSwapSurfaceFormat(physicalDevice.getSurfaceFormatsKHR(*surface)); + vk::SwapchainCreateInfoKHR swapChainCreateInfo{ {}, + *surface, + chooseSwapMinImageCount(surfaceCapabilities), + swapChainSurfaceFormat.format, + swapChainSurfaceFormat.colorSpace, + swapChainExtent, + 1, + vk::ImageUsageFlagBits::eColorAttachment, + vk::SharingMode::eExclusive, + {}, + surfaceCapabilities.currentTransform, + vk::CompositeAlphaFlagBitsKHR::eOpaque, + chooseSwapPresentMode(physicalDevice.getSurfacePresentModesKHR(*surface)), + true}; + + swapChain = vk::raii::SwapchainKHR(device, swapChainCreateInfo); + + swapChainImages = swapChain.getImages(); +} + +void VulkanImpl::createImageViews() +{ + vk::ImageViewCreateInfo imageViewCreateInfo{ + {}, + {}, + vk::ImageViewType::e2D, + swapChainSurfaceFormat.format, + {}, + {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1} + }; + for (auto& image : swapChainImages) + { + imageViewCreateInfo.image = image; + swapChainImageViews.emplace_back(device, imageViewCreateInfo); + } +} + +vk::raii::ImageView VulkanImpl::createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags) +{ + vk::ImageViewCreateInfo imageViewCreateInfo{ + {}, + image, + vk::ImageViewType::e2D, + format, + {}, + {aspectFlags, 0, 1, 0, 1} + }; + return vk::raii::ImageView(device, imageViewCreateInfo); +} + +void VulkanImpl::createCommandPool() +{ + vk::CommandPoolCreateInfo poolInfo{vk::CommandPoolCreateFlagBits::eResetCommandBuffer, queueIndex}; + commandPool = vk::raii::CommandPool(device, poolInfo); +} + +void VulkanImpl::createCommandBuffer() +{ + vk::CommandBufferAllocateInfo allocInfo{commandPool, vk::CommandBufferLevel::ePrimary, MAX_FRAMES_IN_FLIGHT}; + commandBuffers = vk::raii::CommandBuffers(device, allocInfo); +} + + +void VulkanImpl::recordCommandBuffer(uint32_t imageIndex) +{ + auto &commandBuffer = commandBuffers[frameIndex]; + commandBuffer.begin({}); + // Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL + transitionImageLayout( + swapChainImages[imageIndex], + vk::ImageLayout::eUndefined, + vk::ImageLayout::eColorAttachmentOptimal, + {}, // srcAccessMask (no need to wait for previous operations) + vk::AccessFlagBits2::eColorAttachmentWrite, // dstAccessMask + vk::PipelineStageFlagBits2::eColorAttachmentOutput, // srcStage + vk::PipelineStageFlagBits2::eColorAttachmentOutput, // dstStage + vk::ImageAspectFlagBits::eColor + ); + + // Transition depth image to depth attachment optimal layout + transitionImageLayout( + depthImage, + vk::ImageLayout::eUndefined, + vk::ImageLayout::eDepthAttachmentOptimal, + vk::AccessFlagBits2::eDepthStencilAttachmentWrite, + vk::AccessFlagBits2::eDepthStencilAttachmentWrite, + vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests, + vk::PipelineStageFlagBits2::eEarlyFragmentTests | vk::PipelineStageFlagBits2::eLateFragmentTests, + vk::ImageAspectFlagBits::eDepth); + + vk::ClearValue clearColor = vk::ClearColorValue(0.0f, 0.0f, 0.0f, 1.0f); + vk::ClearValue clearDepth = vk::ClearDepthStencilValue(1.0f, 0); + //color + vk::RenderingAttachmentInfo attachmentInfo = { + swapChainImageViews[imageIndex], + vk::ImageLayout::eColorAttachmentOptimal, + {}, + {}, + {}, + vk::AttachmentLoadOp::eClear, + vk::AttachmentStoreOp::eStore, + clearColor + }; + //depth + vk::RenderingAttachmentInfo depthAttachmentInfo = { + depthImageView, + vk::ImageLayout::eDepthAttachmentOptimal, + {}, + {}, + {}, + vk::AttachmentLoadOp::eClear, + vk::AttachmentStoreOp::eDontCare, + clearDepth}; + + vk::RenderingInfo renderingInfo = {{},{{0, 0}, swapChainExtent}, + 1, + {}, + 1, + &attachmentInfo, + &depthAttachmentInfo}; + + commandBuffer.beginRendering(renderingInfo); + + commandBuffer.setViewport(0, vk::Viewport(0.0f, 0.0f, static_cast(swapChainExtent.width), static_cast(swapChainExtent.height), 0.0f, 1.0f)); + commandBuffer.setScissor(0, vk::Rect2D(vk::Offset2D(0, 0), swapChainExtent)); + + CosmicCore::CKernelBase::instance()->getActiveScene()->render(commandBuffer, frameIndex); + + commandBuffer.endRendering(); + // After rendering, transition the swapchain image to PRESENT_SRC + transitionImageLayout( + swapChainImages[imageIndex], + vk::ImageLayout::eColorAttachmentOptimal, + vk::ImageLayout::ePresentSrcKHR, + vk::AccessFlagBits2::eColorAttachmentWrite, // srcAccessMask + {}, // dstAccessMask + vk::PipelineStageFlagBits2::eColorAttachmentOutput, // srcStage + vk::PipelineStageFlagBits2::eBottomOfPipe, // dstStage + vk::ImageAspectFlagBits::eColor + ); + commandBuffer.end(); +} + +void VulkanImpl::transitionImageLayout( + vk::Image image, + vk::ImageLayout old_layout, + vk::ImageLayout new_layout, + vk::AccessFlags2 src_access_mask, + vk::AccessFlags2 dst_access_mask, + vk::PipelineStageFlags2 src_stage_mask, + vk::PipelineStageFlags2 dst_stage_mask, vk::ImageAspectFlags image_aspect_flags) +{ + + vk::ImageMemoryBarrier2 barrier = {src_stage_mask, src_access_mask, dst_stage_mask, dst_access_mask, old_layout, new_layout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, {image_aspect_flags,0,1,0,1}}; + vk::DependencyInfo dependency_info = {{},{},{},{}, {}, 1,&barrier}; + commandBuffers[frameIndex].pipelineBarrier2(dependency_info); +} + +void VulkanImpl::createSyncObjects() +{ + for (size_t i = 0; i < swapChainImages.size(); i++) + { + renderFinishedSemaphores.emplace_back(device, vk::SemaphoreCreateInfo()); + } + + for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) + { + presentCompleteSemaphores.emplace_back(device, vk::SemaphoreCreateInfo()); + inFlightFences.emplace_back(device, vk::FenceCreateInfo{vk::FenceCreateFlagBits::eSignaled}); + } +} + +void VulkanImpl::drawFrame() +{ + auto fenceResult = device.waitForFences(*inFlightFences[frameIndex], vk::True, UINT64_MAX); + m_deletionQueue.flush(frameIndex); // détruit les ressources de cette frame + if (fenceResult != vk::Result::eSuccess) + { + throw std::runtime_error("failed to wait for fence!"); + } + device.resetFences(*inFlightFences[frameIndex]); + + auto [result, imageIndex] = swapChain.acquireNextImage(UINT64_MAX, *presentCompleteSemaphores[frameIndex], nullptr); + commandBuffers[frameIndex].reset(); + recordCommandBuffer(imageIndex); + + vk::PipelineStageFlags waitDestinationStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput); + const vk::SubmitInfo submitInfo{1, &*presentCompleteSemaphores[frameIndex], &waitDestinationStageMask, 1, &*commandBuffers[frameIndex], 1, &*renderFinishedSemaphores[imageIndex]}; + presentQueue.submit(submitInfo, *inFlightFences[frameIndex]); + + const vk::PresentInfoKHR presentInfoKHR{1, &*renderFinishedSemaphores[imageIndex], 1, &*swapChain, &imageIndex}; + result = presentQueue.presentKHR(presentInfoKHR); + // Due to VULKAN_HPP_HANDLE_ERROR_OUT_OF_DATE_AS_SUCCESS being defined, eErrorOutOfDateKHR can be checked as a result + // here and does not need to be caught by an exception. + if ((result == vk::Result::eSuboptimalKHR) || (result == vk::Result::eErrorOutOfDateKHR) || framebufferResized) + { + framebufferResized = false; + recreateSwapChain(); + } + else + { + // There are no other success codes than eSuccess; on any error code, presentKHR already threw an exception. + assert(result == vk::Result::eSuccess); + } + frameIndex = (frameIndex + 1) % MAX_FRAMES_IN_FLIGHT; +} + +void VulkanImpl::cleanupSwapChain() +{ + depthImageView = nullptr; + depthImage = nullptr; + depthImageMemory = nullptr; + + swapChainImageViews.clear(); + swapChain = nullptr; + swapChainImages.clear(); +} + +void VulkanImpl::recreateSwapChain() +{ + int width = 0, height = 0; + SDL_GetWindowSizeInPixels(m_window, &width, &height); + while (width == 0 || height == 0) { + SDL_GetWindowSizeInPixels(m_window, &width, &height); + SDL_WaitEvent(nullptr); + } + + device.waitIdle(); + + cleanupSwapChain(); + createSwapChain(); + createImageViews(); + createDepthResources(); +} + +uint32_t VulkanImpl::findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties) +{ + vk::PhysicalDeviceMemoryProperties memProperties = physicalDevice.getMemoryProperties(); + + for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) + { + if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) + { + return i; + } + } + + throw std::runtime_error("failed to find suitable memory type!"); +} + +void VulkanImpl::copyBuffer(VkBuffer src, VkBuffer dst, VkDeviceSize size) { + vk::raii::CommandBuffer commandCopyBuffer = beginSingleTimeCommands(); + commandCopyBuffer.copyBuffer(vk::Buffer(src), vk::Buffer(dst), vk::BufferCopy(0, 0, size)); + endSingleTimeCommands(commandCopyBuffer); +} + +void VulkanImpl::createDescriptorSetLayouts() +{ + // set 0 - Camera : un UBO en vertex shader + vk::DescriptorSetLayoutBinding cameraBinding{ + 0, // binding + vk::DescriptorType::eUniformBuffer, // type + 1, // count + vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, // stage + nullptr + }; + cameraLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, 1, &cameraBinding} + ); + + // set 1 - Transform : un UBO en vertex shader + vk::DescriptorSetLayoutBinding transformBinding{ + 0, + vk::DescriptorType::eUniformBuffer, + 1, + vk::ShaderStageFlagBits::eVertex, + nullptr + }; + transformLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, 1, &transformBinding} + ); + + // set 2 - Material : un UBO + deux samplers en fragment shader + std::array materialBindings{{ + {0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr}, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr}, + {2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr}, + }}; + materialLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, + static_cast(materialBindings.size()), + materialBindings.data()} + ); + + //set 3 - Light : un storage buffer en fragmentshader + vk::DescriptorSetLayoutBinding lightBinding{ + 0, + vk::DescriptorType::eStorageBuffer, + 1, + vk::ShaderStageFlagBits::eFragment, + nullptr + }; + lightLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, 1, &lightBinding} + ); + + std::array layouts{ + *cameraLayout, + *transformLayout, + *materialLayout, + *lightLayout + }; + vk::PipelineLayoutCreateInfo layoutInfo{{}, + static_cast(layouts.size()), + layouts.data() + }; + defaultPipelineLayoutInfo = vk::raii::PipelineLayout(device, layoutInfo); + + //Create 2D dfault pipeline + + // set 0 - Transform : un UBO en vertex shader + vk::DescriptorSetLayoutBinding transform2DBinding{ + 0, + vk::DescriptorType::eUniformBuffer, + 1, + vk::ShaderStageFlagBits::eVertex, + nullptr + }; + transform2DLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, 1, &transform2DBinding} + ); + + // set 2 - Material : un UBO + deux samplers en fragment shader + std::array material2DBindings{{ + {0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment, nullptr}, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment, nullptr} + }}; + material2DLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, + static_cast(material2DBindings.size()), + material2DBindings.data()} + ); + + // set 2 - Projection : un UBO en vertex shader + vk::DescriptorSetLayoutBinding projBinding{ + 0, // binding + vk::DescriptorType::eUniformBuffer, // type + 1, // count + vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, // stage + nullptr + }; + projection2DLayout = vk::raii::DescriptorSetLayout( + device, + vk::DescriptorSetLayoutCreateInfo{{}, 1, &projBinding} + ); + + std::array layouts2D{ + *transform2DLayout, + *material2DLayout, + *projection2DLayout + }; + vk::PipelineLayoutCreateInfo layout2DInfo{{}, + static_cast(layouts2D.size()), + layouts2D.data() + }; + default2DPipelineLayoutInfo = vk::raii::PipelineLayout(device, layout2DInfo); +} + +//Fonction d'ajout de descriptor set qui regarde la taille de la pool, si la pool est dépassée, on ajoute une pool 2x plus grande +void VulkanImpl::createDescriptorPool() +{ + descriptorPoolManager.init(device); +} + +void VulkanImpl::createDepthResources() +{ + vk::Format depthFormat = findDepthFormat(); + createImage(swapChainExtent.width, swapChainExtent.height, depthFormat, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, depthImage, depthImageMemory); + depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth); +} + +vk::Format VulkanImpl::findSupportedFormat(const std::vector& candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features) +{ + for (const auto format : candidates) { + vk::FormatProperties props = physicalDevice.getFormatProperties(format); + + if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features) { + return format; + } + if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features) { + return format; + } + } + + throw std::runtime_error("failed to find supported format!"); +} + +vk::Format VulkanImpl::findDepthFormat() { + return findSupportedFormat( + {vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint}, + vk::ImageTiling::eOptimal, + vk::FormatFeatureFlagBits::eDepthStencilAttachment + ); + } + +bool VulkanImpl::hasStencilComponent(vk::Format format) { + return format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD24UnormS8Uint; +} + +void VulkanImpl::createImage(uint32_t width, uint32_t height, vk::Format format, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::raii::Image &image, vk::raii::DeviceMemory &imageMemory) +{ + vk::ImageCreateInfo imageInfo{{},vk::ImageType::e2D, format, {width, height, 1}, 1, 1, vk::SampleCountFlagBits::e1, tiling, usage, vk::SharingMode::eExclusive}; + + image = vk::raii::Image(device, imageInfo); + + vk::MemoryRequirements memRequirements = image.getMemoryRequirements(); + vk::MemoryAllocateInfo allocInfo{memRequirements.size, + findMemoryType(memRequirements.memoryTypeBits, properties)}; + imageMemory = vk::raii::DeviceMemory(device, allocInfo); + image.bindMemory(imageMemory, 0); +} + +vk::raii::CommandBuffer VulkanImpl::beginSingleTimeCommands() { + vk::CommandBufferAllocateInfo allocInfo{ commandPool, vk::CommandBufferLevel::ePrimary, 1 }; + vk::raii::CommandBuffer commandBuffer = std::move(device.allocateCommandBuffers(allocInfo).front()); + + vk::CommandBufferBeginInfo beginInfo{ vk::CommandBufferUsageFlagBits::eOneTimeSubmit }; + commandBuffer.begin(beginInfo); + + return commandBuffer; +} + +void VulkanImpl::endSingleTimeCommands(vk::raii::CommandBuffer& commandBuffer) { + commandBuffer.end(); + + vk::SubmitInfo submitInfo{{},{},{},1, &*commandBuffer }; + graphicsQueue.submit(submitInfo, nullptr); + graphicsQueue.waitIdle(); +} + + +void VulkanImpl::transitionImageLayout(vk::Image image, vk::ImageLayout oldLayout, vk::ImageLayout newLayout) +{ + auto commandBuffer = beginSingleTimeCommands(); + + vk::ImageMemoryBarrier barrier{{},{},oldLayout, newLayout,{}, {}, image, {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}}; + + vk::PipelineStageFlags sourceStage; + vk::PipelineStageFlags destinationStage; + + if (oldLayout == vk::ImageLayout::eUndefined && newLayout == vk::ImageLayout::eTransferDstOptimal) + { + barrier.srcAccessMask = {}; + barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite; + + sourceStage = vk::PipelineStageFlagBits::eTopOfPipe; + destinationStage = vk::PipelineStageFlagBits::eTransfer; + } + else if (oldLayout == vk::ImageLayout::eTransferDstOptimal && newLayout == vk::ImageLayout::eShaderReadOnlyOptimal) + { + barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + + sourceStage = vk::PipelineStageFlagBits::eTransfer; + destinationStage = vk::PipelineStageFlagBits::eFragmentShader; + } + else + { + throw std::invalid_argument("unsupported layout transition!"); + } + commandBuffer.pipelineBarrier(sourceStage, destinationStage, {}, {}, nullptr, barrier); + endSingleTimeCommands(commandBuffer); +} + +void VulkanImpl::copyBufferToImage(const vk::raii::Buffer &buffer, vk::raii::Image &image, uint32_t width, uint32_t height) +{ + auto commandBuffer = beginSingleTimeCommands(); + vk::BufferImageCopy region{0, 0, 0, {vk::ImageAspectFlagBits::eColor, 0, 0, 1}, {0, 0, 0}, {width, height, 1}}; + commandBuffer.copyBufferToImage(buffer, image, vk::ImageLayout::eTransferDstOptimal, {region}); + endSingleTimeCommands(commandBuffer); +} + +void VulkanImpl::destroyBuffer(VMABuffer& buffer, uint32_t frame) { + VmaAllocator& alloc = allocator; + VkBuffer& buf = buffer.buffer; + VmaAllocation& mem = buffer.allocation; + + m_deletionQueue.push(frame, [alloc, buf, mem]() { + vmaDestroyBuffer(alloc, buf, mem); + }); + + buffer.buffer = VK_NULL_HANDLE; + buffer.allocation = VK_NULL_HANDLE; +} + +// destruction d'un descriptor set +void VulkanImpl::destroyDescriptorSet(ManagedDescriptorSet& set, uint32_t frame) { + auto s = std::make_shared(std::move(set)); + m_deletionQueue.push(frame, [&dpm = descriptorPoolManager, s]() mutable { + dpm.free(*s); + }); +} + +void VulkanImpl::destroyPipeline(vk::raii::Pipeline& pipeline, vk::raii::PipelineLayout& layout) +{ + auto p = std::make_shared(std::move(pipeline)); + auto pl = std::make_shared(std::move(layout)); + + m_deletionQueue.push(frameIndex, [p, pl]() mutable { + p = nullptr; + pl = nullptr; + }); +} + +void VulkanImpl::createDefaultTexture() +{ + auto def = std::make_unique(""); + def.get()->initDefaultTexture(); + m_defaultTexture = def.get(); + CResourceAPI::resources().textures().add("default", std::move(def)); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp new file mode 100644 index 0000000..2562450 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp @@ -0,0 +1,241 @@ +#ifndef VULKANIMPL_HPP +#define VULKANIMPL_HPP + +#include "../GraphicsAPI.hpp" +#include "DeletionQueue.hpp" +#include +#include +#include + +#include "VMABuffer.hpp" +#include "vk_mem_alloc.h" +#include "vulkan/vulkan.hpp" +#include "ManagedDescriptorSet.hpp" + +#include "../../Data/Texture/CTexture.hpp" + +const std::vector validationLayers = { + "VK_LAYER_KHRONOS_validation" +}; + +#ifdef NDEBUG +constexpr bool enableValidationLayers = false; +#else +constexpr bool enableValidationLayers = true; +#endif +class DescriptorAllocator { + struct Pool { + vk::raii::DescriptorPool pool = nullptr; + uint32_t capacity = 0; + uint32_t allocated = 0; + + bool isFull() const { return allocated >= capacity; } + bool isEmpty() const { return allocated == 0; } + }; + + vk::raii::Device* m_device = nullptr; + uint32_t m_baseSize = 64; + std::vector m_pools; + + Pool createPool(uint32_t size) { + std::vector sizes = { + {vk::DescriptorType::eUniformBuffer, size * 2}, + {vk::DescriptorType::eCombinedImageSampler, size * 2}, + {vk::DescriptorType::eStorageBuffer, size * 2}, + }; + Pool p; + p.capacity = size; + p.pool = vk::raii::DescriptorPool(*m_device, + vk::DescriptorPoolCreateInfo{ + vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, + size, + static_cast(sizes.size()), + sizes.data() + } + ); + return p; + } + + Pool& getAvailablePool() { + // cherche une pool non pleine + for (auto& p : m_pools) + if (!p.isFull()) return p; + + //nouvelle pool x2 + uint32_t newSize = m_pools.empty() + ? m_baseSize + : m_pools.back().capacity * 2; + + return m_pools.emplace_back(createPool(newSize)); + } + +public: + void init(vk::raii::Device& device) { m_device = &device; } + + ManagedDescriptorSet allocate(vk::DescriptorSetLayout layout) { + auto& p = getAvailablePool(); + + vk::DescriptorSetAllocateInfo allocInfo{*p.pool, 1, &layout}; + auto sets = m_device->allocateDescriptorSets(allocInfo); + p.allocated++; + ManagedDescriptorSet mds; + mds.set = std::move(sets[0]); + mds.ownerPool = *p.pool; + return mds; + } + + void free(ManagedDescriptorSet& man) { + // retrouve la pool du set pour décrémenter + VkDescriptorPool rawPool = man.ownerPool; // handle de la pool parente + man.set = nullptr; // libère vk::raii free + + for (auto it = m_pools.begin(); it != m_pools.end(); ++it) { + if (*it->pool == rawPool) { + it->allocated--; + if (it->isEmpty()) + m_pools.erase(it); + return; + } + } + } +}; + + +class VulkanImpl: public GraphicsAPI{ + private: + vk::raii::Context context; + vk::raii::Instance instance = nullptr; + vk::raii::PhysicalDevice physicalDevice = nullptr; + std::vector requiredDeviceExtension = { + vk::KHRSwapchainExtensionName}; + + vk::raii::Device device = nullptr; + vk::raii::Queue graphicsQueue = nullptr; + vk::raii::Queue presentQueue = nullptr; + uint32_t queueIndex = ~0; + vk::raii::SurfaceKHR surface = nullptr; + + vk::raii::SwapchainKHR swapChain = nullptr; + std::vector swapChainImages; + vk::SurfaceFormatKHR swapChainSurfaceFormat; + vk::Extent2D swapChainExtent; + std::vector swapChainImageViews; + + vk::raii::CommandPool commandPool = nullptr; + std::vector commandBuffers; + + std::vector presentCompleteSemaphores; + std::vector renderFinishedSemaphores; + std::vector inFlightFences; + uint32_t frameIndex = 0; + SDL_Window* m_window; + + bool framebufferResized = false; + + VmaAllocator allocator = nullptr; + + vk::raii::DescriptorSetLayout cameraLayout = nullptr; // set 0 + vk::raii::DescriptorSetLayout transformLayout = nullptr; // set 1 + vk::raii::DescriptorSetLayout materialLayout = nullptr; // set 2 + vk::raii::DescriptorSetLayout lightLayout = nullptr; // set 3 + + vk::raii::DescriptorSetLayout transform2DLayout = nullptr; // set 0 + vk::raii::DescriptorSetLayout material2DLayout = nullptr; // set 1 + vk::raii::DescriptorSetLayout projection2DLayout = nullptr; // set 2 + + + DescriptorAllocator descriptorPoolManager; + vk::raii::PipelineLayout defaultPipelineLayoutInfo = nullptr; + vk::raii::PipelineLayout default2DPipelineLayoutInfo = nullptr; + + vk::raii::Image depthImage = nullptr; + vk::raii::DeviceMemory depthImageMemory = nullptr; + vk::raii::ImageView depthImageView = nullptr; + + DeletionQueue m_deletionQueue; + + CTexture* m_defaultTexture = nullptr; + public: + virtual ~VulkanImpl(){}; + void init(SDL_Window* window) override; + void cleanup()override; + void createInstance(); + void pickPhysicalDevice(); + void createLogicalDevice(); + void createSurface(); + void createSwapChain(); + void createImageViews(); + //void createGraphicsPipeline(); + void createCommandPool(); + void createCommandBuffer(); + void createSyncObjects(); + void drawFrame() override; + void recreateSwapChain(); + void createDescriptorSetLayouts(); + void cleanupSwapChain(); + void createDepthResources(); + void createDescriptorPool(); + + void transitionImageLayout(vk::Image image, vk::ImageLayout old_layout, vk::ImageLayout new_layout, vk::AccessFlags2 src_access_mask, vk::AccessFlags2 dst_access_mask, vk::PipelineStageFlags2 src_stage_mask, vk::PipelineStageFlags2 dst_stage_mask, vk::ImageAspectFlags image_aspect_flags); + void transitionImageLayout(vk::Image image, vk::ImageLayout oldLayout, vk::ImageLayout newLayout); + void recordCommandBuffer(uint32_t imageIndex); + void* getDevice()override {return &device;}; + uint32_t findMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties); + vk::SurfaceFormatKHR& getSwapChainFormat(){return swapChainSurfaceFormat;}; + uint32_t getGraphicsQueueIndex() const { return queueIndex; } + vk::Extent2D getSwapChainExtent() const { return swapChainExtent; } + + vk::raii::CommandBuffer beginSingleTimeCommands(); + void endSingleTimeCommands(vk::raii::CommandBuffer& commandBuffer); + + // accès au command buffer courant pour que le Renderer puisse enregistrer + vk::raii::CommandBuffer& getCurrentCommandBuffer(); + + // accès à l'image view courante pour le color attachment + vk::raii::ImageView& getCurrentSwapChainImageView(); + + // pour que le Renderer sache quelle frame est en cours + uint32_t getCurrentFrameIndex() const { return frameIndex; } + + VmaAllocator getAllocator() { return allocator; } + vk::raii::PhysicalDevice& getPhysicalDevice() { return physicalDevice; } + vk::raii::DescriptorSetLayout& getCameraLayout() { return cameraLayout; } + vk::raii::DescriptorSetLayout& getTransformLayout() { return transformLayout; } + vk::raii::DescriptorSetLayout& getMaterialLayout() { return materialLayout; } + vk::raii::DescriptorSetLayout& getLightLayout() { return lightLayout; } + + vk::raii::DescriptorSetLayout& getTransform2DLayout() { return transform2DLayout; } + vk::raii::DescriptorSetLayout& getMaterial2DLayout() { return material2DLayout; } + vk::raii::DescriptorSetLayout& getProjection2DLayout() { return projection2DLayout; } + + vk::raii::ImageView createImageView(vk::raii::Image& image, vk::Format format, vk::ImageAspectFlags aspectFlags); + + void copyBuffer(VkBuffer src, VkBuffer dst, VkDeviceSize size); + + vk::Format findSupportedFormat(const std::vector& candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features); + vk::Format findDepthFormat(); + + bool hasStencilComponent(vk::Format format); + void createImage(uint32_t width, uint32_t height, vk::Format format, vk::ImageTiling tiling, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties, vk::raii::Image &image, vk::raii::DeviceMemory &imageMemory); + + DescriptorAllocator& getDescriptorPoolManager(){return descriptorPoolManager;}; + + vk::raii::PipelineLayout& getDefaultPipelineLayout(){return defaultPipelineLayoutInfo;}; + vk::raii::PipelineLayout& getDefault2DPipelineLayout(){return default2DPipelineLayoutInfo;}; + + void copyBufferToImage(const vk::raii::Buffer &buffer, vk::raii::Image &image, uint32_t width, uint32_t height); + + void destroyBuffer(VMABuffer& buffer, uint32_t frame); + + // destruction d'un descriptor set + void destroyDescriptorSet(ManagedDescriptorSet& set, uint32_t frame); + + void destroyPipeline(vk::raii::Pipeline& pipeline, vk::raii::PipelineLayout& layout); + + DeletionQueue& getDeletionQueue(){return m_deletionQueue;}; + + CTexture* getDefaultTexture() { return m_defaultTexture; } + + void createDefaultTexture(); + }; +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.cpp new file mode 100644 index 0000000..a29b8e2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.cpp @@ -0,0 +1,42 @@ +#include "CContext.hpp" +#include "API/GraphicsAPI.hpp" +#include +#include + +bool CContext::m_screenSaver = false; + +void CContext::init(SDL_InitFlags sdlFlags) { + // Log initialisation. + initLog(); + + + // SDL Initialization. + if (SDL_Init(sdlFlags)) { + SDL_Quit(); + //HandleException(CLibException(std::string("Unable to initialize SDL: ") + SDL_GetError()), true); + } + + GraphicsAPI::initAPI(); +} + +bool CContext::isScreenSaverEnable(void) { + return m_screenSaver; +} + +void CContext::setScreenSaverEnable(bool newScreenSaver) { + m_screenSaver = newScreenSaver; + if (m_screenSaver) { + SDL_EnableScreenSaver(); + } + else { + SDL_DisableScreenSaver(); + } +} + +void CContext::quit(void) { + SDL_Quit(); +} + +void CContext::initLog(void) { + //todo +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.hpp new file mode 100644 index 0000000..fc5ff25 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/CContext.hpp @@ -0,0 +1,34 @@ +#ifndef CCONTEXT_HPP +#define CCONTEXT_HPP + +#include +#include +#include + +#define LOG_FILE "CosmicEngine_%3N.log" +#define LOG_ROTATION_SIZE 1 * 1024 * 1024 +#define LOG_MAX_SIZE 50 * 1024 * 1024 + +class CContext { +private: + // Say if the screenSaver is enabled. + static bool m_screenSaver; + +public: + CContext(void) = delete; + + static void init(SDL_InitFlags sdlFlags); + + static void quit(void); + + static bool isScreenSaverEnable(void); + + + static void setScreenSaverEnable(bool newScreenSaver); + +private: + + static void initLog(void); +}; + +#endif diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.cpp new file mode 100644 index 0000000..6a42a9b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.cpp @@ -0,0 +1,337 @@ +#include "CModelLoader.hpp" +#include +#include "Engine/Core/Systems/Graphics/API/GraphicsAPI.hpp" +#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp" +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp" +#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp" +#include "nlohmann/json_fwd.hpp" +#include +#include + +CModel* CModelLoader::loadModel(std::string fileName, const ModelLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + auto cached = rm.models().get(fileName); + if (cached && !config.forceReload) { + if (config.materialOverrides.empty()) + return cached.value(); + return cloneWithOverrides(cached.value(), fileName, config); + } + + Assimp::Importer importer; + + const aiScene* scene = importer.ReadFile(fileName.c_str(), + aiProcess_Triangulate | + aiProcess_FlipUVs | + aiProcess_CalcTangentSpace | + aiProcess_GenNormals + ); + + if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) + throw std::runtime_error("Assimp: " + std::string(importer.GetErrorString())); + + // dossier de base pour les textures relatives + std::vector meshMaterials; + processNode(scene->mRootNode, scene, fileName, meshMaterials, config); + + for (auto& [index, mat] : config.materialOverrides) + { + if (index < meshMaterials.size()) + meshMaterials[index].material = mat; + } + + // crée et enregistre le model + auto model = std::make_unique(meshMaterials); + return rm.models().add(fileName, std::move(model));; +} + +CModel* CModelLoader::cloneWithOverrides(CModel* original, + const std::string& originalKey, + const ModelLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + + // clé unique pour ce clone + std::string cloneKey = originalKey; + for (auto& [index, mat] : config.materialOverrides) + cloneKey += "_" + std::to_string(index) + "_" + std::to_string((size_t)mat); + + auto cached = rm.models().get(cloneKey); + if (cached) return cached.value(); + + // clone avec overrides + auto meshMaterials = original->getMeshMaterials(); + for (auto& [index, mat] : config.materialOverrides) + { + if (index < meshMaterials.size()) + meshMaterials[index].material = mat; + } + + auto cloned = std::make_unique(meshMaterials); + return rm.models().add(cloneKey, std::move(cloned)); +} + + +void CModelLoader::processNode(aiNode* node, const aiScene* scene, const std::string& directory, std::vector& meshes, const ModelLoadConfig& config) +{ + // process all the node's meshes (if any) + for (uint32_t i = 0; i < node->mNumMeshes; i++) { + aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; + meshes.push_back(processMesh(mesh, scene, directory, config)); + } + // then do the same for each of its children + for (uint32_t i = 0; i < node->mNumChildren; i++) { + processNode(node->mChildren[i], scene, directory, meshes, config); + } +} + +MeshMaterial CModelLoader::processMesh(aiMesh* mesh, const aiScene* scene, const std::string& directory, const ModelLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + std::vector vertices; + std::vector indices; + + // vertices + for (uint32_t i = 0; i < mesh->mNumVertices; i++) { + SVertex vertex{}; + vertex.m_position = { + mesh->mVertices[i].x, + mesh->mVertices[i].y, + mesh->mVertices[i].z + }; + vertex.m_normal = mesh->HasNormals() ? + glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z) : + glm::vec3(0.0f); + + vertex.m_texCoords = mesh->mTextureCoords[0] ? + glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y) : + glm::vec2(0.0f); + + vertex.m_tangent = mesh->HasTangentsAndBitangents() ? + glm::vec3(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z) : + glm::vec3(0.0f); + + vertex.m_bitangent = mesh->HasTangentsAndBitangents() ? + glm::vec3(mesh->mBitangents[i].x, mesh->mBitangents[i].y, mesh->mBitangents[i].z) : + glm::vec3(0.0f); + + vertices.push_back(vertex); + } + + // indices + for (uint32_t i = 0; i < mesh->mNumFaces; i++) { + aiFace face = mesh->mFaces[i]; + for (uint32_t j = 0; j < face.mNumIndices; j++) + indices.push_back(face.mIndices[j]); + } + + // crée et enregistre le mesh + std::string meshKey = directory + "_mesh_" + std::to_string(rm.meshes().size()); + auto newMesh = std::make_unique(); + newMesh->setVertices(vertices); + newMesh->setIndexes(indices); + newMesh->load(); + CMesh* meshPtr = rm.meshes().add(meshKey, std::move(newMesh)); + + // material + CMaterial* material = nullptr; + if (mesh->mMaterialIndex >= 0) { + material = processMaterial( + scene->mMaterials[mesh->mMaterialIndex], + directory, + config + ); + } + return MeshMaterial{meshPtr, material}; +} + +CMaterial* CModelLoader::processMaterial(aiMaterial* mat, const std::string& directory, const ModelLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + aiString aiName; + mat->Get(AI_MATKEY_NAME, aiName); + std::string matKey = directory + "_" + aiName.C_Str() + "_" + config.shaderName; + + auto cached = rm.materials().get(matKey); + if (cached) return cached.value(); + + // textures + CTexture* albedo = nullptr; + CTexture* normal = nullptr; + + // albedo + if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0) { + aiString path; + mat->GetTexture(aiTextureType_DIFFUSE, 0, &path); + albedo = rm.textures().loadTexture(directory + "/" + path.C_Str()); + } + + // normal + if (mat->GetTextureCount(aiTextureType_NORMALS) > 0) { + aiString path; + mat->GetTexture(aiTextureType_NORMALS, 0, &path); + normal = rm.textures().loadTexture(directory + "/" + path.C_Str()); + } + + auto shader = CResourceAPI::resources().shaders().get(config.shaderName); + + return rm.materials().createMaterial(matKey, static_cast(shader), albedo, normal); +} + + +/*CTexture* CModelLoader::loadTexture(const std::string& directory, CResourceManager& rm) +{ + auto text = rm.getTextureManager().get(directory); + if(rm.getTextureManager().get(directory)) + { + return text.value(); + } + else { + auto tex = std::make_unique(directory); + tex->init(); + + auto* ptr = tex.get(); + rm.getTextureManager().addTexture(directory, std::move(tex)); + return ptr; + } +}*/ + +CosmicCore::CModel2D* CModelLoader::loadModel2D(std::string filename, const Model2DLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + + // Check cache first + auto cached = rm.models2D().get(filename); + if (cached) { + return cached.value(); + } + + // Load and parse JSON file + std::ifstream file(filename); + if (!file.is_open()) { + throw std::runtime_error("Failed to open 2D model file: " + filename); + } + nlohmann::json jsonData = nlohmann::json::parse(file); + + std::vector meshMaterials; + for(auto& mesh : jsonData["meshes"]) + { + loadMesh2D(mesh, filename, meshMaterials, config); + } + + + // Create and register model2D + auto model2D = std::make_unique(meshMaterials); + return rm.models2D().add(filename, std::move(model2D)); +} + +void CModelLoader::loadMesh2D(nlohmann::json& mesh, std::string filename, std::vector& meshes, const Model2DLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + + // Parse vertices + std::vector vertices; + if (mesh.contains("vertices") && mesh["vertices"].is_array()) { + for (const auto& v : mesh["vertices"]) { + Vertex2D vertex; + + // Position (required: x, y) + vertex.m_position = glm::vec2(v["x"], v["y"]); + + // TexCoords (optional, defaults to 0,0) + if (v.contains("u") && v.contains("v")) { + vertex.m_uv = glm::vec2(v["u"], v["v"]); + } else { + vertex.m_uv = glm::vec2(0.0f); + } + + // Color (optional, defaults to white) + if (v.contains("r") && v.contains("g") && v.contains("b") && v.contains("a")) { + vertex.m_color = glm::vec4(v["r"], v["g"], v["b"], v["a"]); + } else { + vertex.m_color = glm::vec4(1.0f); + } + + vertices.push_back(vertex); + } + } + + // Parse indices + std::vector indices; + if (mesh.contains("indices") && mesh["indices"].is_array()) { + for (const auto& i : mesh["indices"]) { + indices.push_back(i.get()); + } + } + + if (vertices.empty() || indices.empty()) { + throw std::runtime_error("Invalid 2D model file: missing vertices or indices in " + filename); + } + + + // Create mesh key + std::string meshKey = filename + "_" + std::to_string(meshes.size()) + "_mesh2d"; + + // Create and setup CMesh2D + auto mesh2D = std::make_unique(); + mesh2D->setVertices(vertices); + mesh2D->setIndexes(indices); + mesh2D->load(); + + CMesh2D* meshPtr = rm.meshes2D().add(meshKey, std::move(mesh2D)); + CMaterial2D* matPtr = loadMaterial2D(mesh["material"], filename, config); + meshes.push_back({meshPtr, matPtr}); +} + +CosmicCore::CMaterial2D* CModelLoader::loadMaterial2D(nlohmann::json& material, std::string filename, const Model2DLoadConfig& config) +{ + auto& rm = CResourceAPI::resources(); + + // Create material2D + CMaterial2D* material2D = nullptr; + + + std::string matKey = filename + "_mat2d"; + auto cachedMat = rm.materials2D().get(matKey); + + if (!cachedMat) { + auto mat = std::make_unique(); + + // Parse material from JSON + if (material.contains("material")) { + auto& matJson = material["material"]; + + if (matJson.contains("color")) { + auto& color = matJson["color"]; + mat->m_color = glm::vec4( + color.value("r", 1.0f), + color.value("g", 1.0f), + color.value("b", 1.0f), + color.value("a", 1.0f) + ); + } + + if (matJson.contains("alpha_blend")) { + mat->m_alphaBlend = matJson["alpha_blend"].get(); + } + + if (matJson.contains("texture")) { + std::string texPath = matJson["texture"]; + mat->m_texture = rm.textures().loadTexture(texPath); + } + } + + // Get shader from config + auto shader = rm.shaders().get(config.shaderName); + if (!shader) { + throw std::runtime_error("Shader not found: " + config.shaderName); + } + mat->shader = static_cast(shader); + mat->build(); + + material2D = rm.materials2D().add(matKey, std::move(mat)); + } else { + material2D = cachedMat.value(); + } + return material2D; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.hpp new file mode 100644 index 0000000..9d62b5e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/CModelLoader.hpp @@ -0,0 +1,82 @@ +#ifndef CMODELLOADER_HPP +#define CMODELLOADER_HPP + + +#include +#include +#include + +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp" +#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp" +#include "Model/CModel.hpp" +#include "Texture/CTexture.hpp" +#include "nlohmann/json_fwd.hpp" + +struct ModelLoadConfig { + std::string shaderName = "triangle"; + // override des materials par index de mesh + std::unordered_map materialOverrides; + // si true, recharge même si déjà en cache + bool forceReload = false; +}; + +struct Model2DLoadConfig { + std::string shaderName = "ui"; + // override des materials par index de mesh + //std::unordered_map materialOverrides; + // si true, recharge même si déjà en cache + //bool forceReload = false; +}; + +/** + * @brief Class allowing to load models from obj files. + */ +class CModelLoader { +private: + /** + * @brief Compute every node in the loaded meshes. + * @param[in] node The assimp created node. + * @param[in] scene The assimp created scene. + * @param[in] meshes The mesh list. + * @param[in] material A pointer to a material. It's optionnal and override the obj's material. + */ + static void processNode(aiNode* node, const aiScene* scene, const std::string& directory, std::vector& meshes, const ModelLoadConfig& config); + + /** + * @brief Compute every meshes. + * @param[in] mesh The assimp created mesh. + * @param[in] scene The assimp created scene. + * @param[in] meshes The list of meshes. + * @param[in] material A pointer to a material. It's optionnal and override the obj's material. + */ + static MeshMaterial processMesh(aiMesh* mesh, const aiScene* scene, const std::string& directory, const ModelLoadConfig& config); + + /** + * @brief Load Textures from the obj file. + * @param[in] mat The assimp created material. + * @param[in] type The assimp's texture type. + * @param[in] typeName The texture's type. + */ + static CTexture* loadTexture(const std::string& directory); + + static CMaterial* processMaterial(aiMaterial* mat, const std::string& directory, const ModelLoadConfig& config); + + static CModel* cloneWithOverrides(CModel* original, const std::string& originalKey, const ModelLoadConfig& config); + + static void loadMesh2D(nlohmann::json& mesh, std::string filename, std::vector& meshes, const Model2DLoadConfig& config = {}); + static CosmicCore::CMaterial2D* loadMaterial2D(nlohmann::json& material, std::string filename, const Model2DLoadConfig& config = {}); + +public: + + /** + * @brief main function of the class, starts loading the obj file. + * @param[in] fileName Path to the OBJ file. + * @param[in] material Pointer to a material. It's optionnal and override the obj's material. + * @return A dynamically allocated CModel. + */ + static CModel* loadModel(std::string filename, const ModelLoadConfig& config = {}); + static CosmicCore::CModel2D* loadModel2D(std::string filename, const Model2DLoadConfig& config = {}); + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.cpp new file mode 100644 index 0000000..8617438 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.cpp @@ -0,0 +1,77 @@ +// CFont.cpp +#include "CFont.hpp" +#include "Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp" +#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp" +#include +#include +#include + +namespace CosmicCore { + +void CFont::init(const std::string& jsonPath, const std::string& atlasPath) { + // charge l'atlas comme texture + auto& rm = CResourceAPI::resources().textures(); + m_atlas = rm.loadTexture(atlasPath, TextureType::MSDFFont); + + // parse le JSON + std::ifstream file(jsonPath); + if (!file.good()) + throw std::runtime_error("Font JSON not found: " + jsonPath); + + nlohmann::json j = nlohmann::json::parse(file); + + // métriques globales + if (j.contains("metrics")) { + auto& m = j["metrics"]; + m_metrics.emSize = m.value("emSize", 1.0f); + m_metrics.lineHeight = m.value("lineHeight", 1.0f); + m_metrics.ascender = m.value("ascender", 1.0f); + m_metrics.descender = m.value("descender", 0.0f); + } + + // dimensions de l'atlas + if (j.contains("atlas")) { + m_atlasWidth = j["atlas"].value("width", 512u); + m_atlasHeight = j["atlas"].value("height", 512u); + } + + // glyphes + if (!j.contains("glyphs")) return; + + for (auto& g : j["glyphs"]) { + SGlyph glyph{}; + glyph.unicode = g.value("unicode", 0u); + glyph.advance = g.value("advance", 0.0f); + + if (g.contains("atlasBounds")) { + auto& ab = g["atlasBounds"]; + float atlasW = (float)m_atlasWidth; + float atlasH = (float)m_atlasHeight; + glyph.atlasMin = {ab["left"].get() / atlasW, + ab["bottom"].get() / atlasH}; + glyph.atlasMax = {ab["right"].get() / atlasW, + ab["top"].get() / atlasH}; + } + + if (g.contains("planeBounds")) { + auto& pb = g["planeBounds"]; + glyph.planeMin = {pb["left"].get(), + pb["bottom"].get()}; + glyph.planeMax = {pb["right"].get(), + pb["top"].get()}; + } + + m_glyphs[glyph.unicode] = glyph; + } +} + +const SGlyph* CFont::getGlyph(uint32_t unicode) const { + auto it = m_glyphs.find(unicode); + if (it != m_glyphs.end()) return &it->second; + // fallback sur '?' si le glyphe n'existe pas + auto fallback = m_glyphs.find('?'); + if (fallback != m_glyphs.end()) return &fallback->second; + return nullptr; +} + +} // namespace CosmicCore \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.hpp new file mode 100644 index 0000000..b5d85e8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Font/CFont.hpp @@ -0,0 +1,57 @@ +#ifndef CFONT_HPP +#define CFONT_HPP + +#include +#include +#include +#include "../Texture/CTexture.hpp" + +namespace CosmicCore { + +struct SGlyph { + uint32_t unicode; + float advance; // largeur pour avancer le curseur + + // position dans l'atlas (UV) + glm::vec2 atlasMin; // UV coin bas-gauche + glm::vec2 atlasMax; // UV coin haut-droit + + // position relative au curseur (plane bounds) + glm::vec2 planeMin; // offset bas-gauche + glm::vec2 planeMax; // offset haut-droit +}; + +struct SFontMetrics { + float emSize = 1.0f; + float lineHeight = 1.0f; + float ascender = 1.0f; + float descender = 0.0f; +}; + +class CFont { + std::unordered_map m_glyphs; + CTexture* m_atlas; + SFontMetrics m_metrics; + uint32_t m_atlasWidth = 0; + uint32_t m_atlasHeight = 0; + + public: + CFont() = default; + ~CFont() = default; + + CFont(const CFont&) = delete; + CFont& operator=(const CFont&) = delete; + CFont(CFont&&) = default; + CFont& operator=(CFont&&) = default; + + void init(const std::string& jsonPath, const std::string& atlasPath); + + const SGlyph* getGlyph(uint32_t unicode) const; + CTexture* getAtlas() const { return m_atlas; } + SFontMetrics getMetrics() const { return m_metrics; } + uint32_t getAtlasWidth() const { return m_atlasWidth; } + uint32_t getAtlasHeight() const { return m_atlasHeight; } +}; + +} // namespace CosmicCore +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.cpp new file mode 100644 index 0000000..df6fafe --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.cpp @@ -0,0 +1,73 @@ +#include "CLightsBuffer.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" + +namespace CosmicCore { + void CLightsBuffer::init() { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto* device = static_cast(api->getDevice()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + // SSBO + VkBufferCreateInfo bufferInfo{}; + bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + bufferInfo.size = sizeof(SLightsUBOData); + bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + + VmaAllocationCreateInfo allocInfo{}; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VmaAllocationInfo info{}; + vmaCreateBuffer(api->getAllocator(), &bufferInfo, &allocInfo, + &m_buffers[i].buffer, + &m_buffers[i].allocation, + &info); + m_mappedData[i] = info.pMappedData; + + // descriptor set (set 3) + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate( + *api->getLightLayout() + ); + + vk::DescriptorBufferInfo descriptorBufferInfo{ + vk::Buffer(m_buffers[i].buffer), + 0, + sizeof(SLightsUBOData) + }; + vk::WriteDescriptorSet descriptorWrite{ + *m_descriptorSets[i].set, + 0, 0, 1, + vk::DescriptorType::eStorageBuffer, + {}, &descriptorBufferInfo + }; + device->updateDescriptorSets(descriptorWrite, {}); + } + m_initialized = true; + } + + void CLightsBuffer::update(uint32_t frameIndex, const SLightsUBOData& data) { + if (!m_initialized) return; + memcpy(m_mappedData[frameIndex], &data, sizeof(SLightsUBOData)); + } + + void CLightsBuffer::destroy() { + if (!m_initialized) return; + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + api->getDeletionQueue().push(api->getCurrentFrameIndex(), + [alloc = api->getAllocator(), + buf = m_buffers[i].buffer, + mem = m_buffers[i].allocation]() { + vmaDestroyBuffer(alloc, buf, mem); + }); + api->destroyDescriptorSet(m_descriptorSets[i], + api->getCurrentFrameIndex()); + } + m_initialized = false; + } + + vk::raii::DescriptorSet& CLightsBuffer::getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.hpp new file mode 100644 index 0000000..697cfe6 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Light/CLightsBuffer.hpp @@ -0,0 +1,55 @@ +// CLightsBuffer.hpp +#ifndef CLIGHTSBUFFER_HPP +#define CLIGHTSBUFFER_HPP + +#include +#include +#include "../../API/VulkanImplementation/VMABuffer.hpp" +#include "../../API/VulkanImplementation/ManagedDescriptorSet.hpp" + +constexpr uint32_t MAX_LIGHTS = 32; + +namespace CosmicCore { + +struct SLightData { + glm::vec4 position; // xyz = pos, w = type (0=dir, 1=point, 2=spot) + glm::vec4 direction; // xyz = dir, w = range + glm::vec4 color; // xyz = color, w = intensity + float innerCosAngle; + float outerCosAngle; + float attenuation; + float padding; // alignement 16 bytes +}; + +struct SLightsUBOData { + SLightData lights[MAX_LIGHTS]; + int lightCount = 0; + //glm::vec3 padding; +}; + +class CLightsBuffer { + std::array m_buffers; + std::array m_mappedData{}; + std::array m_descriptorSets; + bool m_initialized = false; + +public: + CLightsBuffer() = default; + ~CLightsBuffer() { }//destroy(); } + + CLightsBuffer(const CLightsBuffer&) = delete; + CLightsBuffer& operator=(const CLightsBuffer&) = delete; + CLightsBuffer(CLightsBuffer&&) = default; + CLightsBuffer& operator=(CLightsBuffer&&) = default; + + void init(); + + void update(uint32_t frameIndex, const SLightsUBOData& data); + + void destroy(); + + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex); +}; + +} // namespace CosmicCore +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.cpp new file mode 100644 index 0000000..a8b7bd3 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.cpp @@ -0,0 +1,137 @@ +#include "CMaterial.hpp" +#include "../Mesh/SVertex.hpp" +#include "../../API/VulkanImplementation/VulkanImpl.hpp" +#include + +void CMaterial::build() +{ + if(isInit) + { + destroy(); + } + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto* device= static_cast(api->getDevice()); + auto shaderStages = shader->getShaderStages(0, vk::ShaderStageFlagBits::eVertex, vk::ShaderStageFlagBits::eFragment); + + auto bindingDescription = Vertex::getBindingDescription(); + auto attributeDescriptions = Vertex::getAttributeDescriptions(); + vk::PipelineVertexInputStateCreateInfo vertexInputInfo{{}, 1, &bindingDescription, static_cast(attributeDescriptions.size()), attributeDescriptions.data()}; + + vk::PipelineInputAssemblyStateCreateInfo inputAssembly{{},vk::PrimitiveTopology::eTriangleList}; + vk::PipelineViewportStateCreateInfo viewportState{{},1, {},1}; + + vk::PipelineRasterizationStateCreateInfo rasterizer{{},vk::False, vk::False, vk::PolygonMode::eFill,vk::CullModeFlagBits::eBack, vk::FrontFace::eCounterClockwise, vk::False, {}, {}, 1.0f, 1.0f}; + + vk::PipelineMultisampleStateCreateInfo multisampling{{}, vk::SampleCountFlagBits::e1, vk::False}; + + vk::PipelineColorBlendAttachmentState colorBlendAttachment{vk::False, {}, {}, {}, {}, {}, {}, vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}; + + vk::PipelineColorBlendStateCreateInfo colorBlending{{},vk::False, vk::LogicOp::eCopy, 1, &colorBlendAttachment}; + + vk::PipelineDepthStencilStateCreateInfo depthStencil{{}, + vk::True, + vk::True, + vk::CompareOp::eLess, + vk::False, + vk::False}; + + std::vector dynamicStates = { + vk::DynamicState::eViewport, + vk::DynamicState::eScissor}; + vk::PipelineDynamicStateCreateInfo dynamicState{{}, static_cast(dynamicStates.size()), dynamicStates.data()}; + + std::array layouts{ + *api->getCameraLayout(), // set 0 + *api->getTransformLayout(), // set 1 + *api->getMaterialLayout(), // set 2 + *api->getLightLayout() //set 3 + }; + + vk::PipelineLayoutCreateInfo pipelineLayoutInfo{{},4,layouts.data(), 0}; + + pipelineLayout = vk::raii::PipelineLayout(*static_cast(api->getDevice()), pipelineLayoutInfo); + + vk::StructureChain pipelineCreateInfoChain = { + {{}, + 2, + shaderStages.data(), + &vertexInputInfo, + &inputAssembly, + {}, + &viewportState, + &rasterizer, + &multisampling, + &depthStencil, + &colorBlending, + &dynamicState, + pipelineLayout, + nullptr + }, + {{}, + 1, + &api->getSwapChainFormat().format, + api->findDepthFormat() + } + }; + + pipeline = vk::raii::Pipeline(*static_cast(api->getDevice()), nullptr, pipelineCreateInfoChain.get()); + + // descriptor sets du material (set 2) + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate( + *api->getMaterialLayout() + ); + + std::vector writes; + + // binding 1 : albedo (si présent) + vk::DescriptorImageInfo albedoInfo; + if (textureAlbedo) { + albedoInfo = { + *textureAlbedo->getSampler(), + *textureAlbedo->getImageView(), + vk::ImageLayout::eShaderReadOnlyOptimal + }; + writes.push_back({ + *m_descriptorSets[i].set, + 1, 0, 1, + vk::DescriptorType::eCombinedImageSampler, + &albedoInfo + }); + } + else { + albedoInfo = { + api->getDefaultTexture()->getSampler(), + api->getDefaultTexture()->getImageView(), + vk::ImageLayout::eShaderReadOnlyOptimal + }; + writes.push_back({ + *m_descriptorSets[i].set, + 1, 0, 1, + vk::DescriptorType::eCombinedImageSampler, + &albedoInfo + }); + } + + if (!writes.empty()) + device->updateDescriptorSets(writes, {}); + } + isInit = true; +} + +CMaterial::~CMaterial() +{ + destroy(); +} + +void CMaterial::destroy() +{ + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + api->destroyPipeline(pipeline, pipelineLayout); + + // descriptor sets + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + api->destroyDescriptorSet(m_descriptorSets[i], i); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.hpp new file mode 100644 index 0000000..09c8cfc --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial.hpp @@ -0,0 +1,28 @@ +#ifndef SMATERIAL_HPP +#define SMATERIAL_HPP + +#include "../../Shader/Implementations/CShaderImplVulkan.hpp" +#include "../../API/VulkanImplementation/ManagedDescriptorSet.hpp" +#include "../Texture/CTexture.hpp" + +class CMaterial { + public: + + ~CMaterial(); + void destroy(); + bool isInit = false; + CTexture* textureAlbedo = nullptr; + CTexture* textureNormal = nullptr; + CShaderImplVulkan* shader; + vk::raii::PipelineLayout pipelineLayout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + std::array m_descriptorSets; + void build(); + vk::raii::Pipeline& getPipeline(){return pipeline;}; + vk::raii::PipelineLayout& getPipelineLayout(){return pipelineLayout;}; + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.cpp new file mode 100644 index 0000000..ea84891 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.cpp @@ -0,0 +1,157 @@ +#include "CMaterial2D.hpp" +#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp" +#include "Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include + +namespace CosmicCore { + +void CMaterial2D::build() { + + if(isInit) + { + destroy(); + } + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto* device= static_cast(api->getDevice()); + auto shaderStages = shader->getShaderStages(0, vk::ShaderStageFlagBits::eVertex, vk::ShaderStageFlagBits::eFragment); + + auto bindingDescription = Vertex2D::getBindingDescription(); + auto attributeDescriptions = Vertex2D::getAttributeDescriptions(); + vk::PipelineVertexInputStateCreateInfo vertexInputInfo{{}, 1, &bindingDescription, static_cast(attributeDescriptions.size()), attributeDescriptions.data()}; + + vk::PipelineInputAssemblyStateCreateInfo inputAssembly{{},vk::PrimitiveTopology::eTriangleList}; + vk::PipelineViewportStateCreateInfo viewportState{{},1, {},1}; + + vk::PipelineRasterizationStateCreateInfo rasterizer{{},vk::False, vk::False, vk::PolygonMode::eFill,vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, vk::False, {}, {}, 1.0f, 1.0f}; + + vk::PipelineMultisampleStateCreateInfo multisampling{{}, vk::SampleCountFlagBits::e1, vk::False}; + + vk::PipelineColorBlendAttachmentState colorBlendAttachment{ + vk::True, + vk::BlendFactor::eSrcAlpha, + vk::BlendFactor::eOneMinusSrcAlpha, + vk::BlendOp::eAdd, + vk::BlendFactor::eOne, + vk::BlendFactor::eZero, + vk::BlendOp::eAdd, + vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}; + + vk::PipelineColorBlendStateCreateInfo colorBlending{{},vk::False, vk::LogicOp::eCopy, 1, &colorBlendAttachment}; + + vk::PipelineDepthStencilStateCreateInfo depthStencil{{}, + vk::False, + vk::False, + vk::CompareOp::eAlways, + vk::False, + vk::False}; + + std::vector dynamicStates = { + vk::DynamicState::eViewport, + vk::DynamicState::eScissor}; + vk::PipelineDynamicStateCreateInfo dynamicState{{}, static_cast(dynamicStates.size()), dynamicStates.data()}; + + std::array layouts{ + *api->getTransform2DLayout(), // set 0 + *api->getMaterial2DLayout(), // set 1 + *api->getProjection2DLayout(), // set 2 + + }; + + vk::PipelineLayoutCreateInfo pipelineLayoutInfo{{},3,layouts.data(), 0}; + + pipelineLayout = vk::raii::PipelineLayout(*static_cast(api->getDevice()), pipelineLayoutInfo); + + vk::StructureChain pipelineCreateInfoChain = { + {{}, + 2, + shaderStages.data(), + &vertexInputInfo, + &inputAssembly, + {}, + &viewportState, + &rasterizer, + &multisampling, + &depthStencil, + &colorBlending, + &dynamicState, + pipelineLayout, + nullptr + }, + {{}, + 1, + &api->getSwapChainFormat().format, + api->findDepthFormat() + } + }; + + pipeline = vk::raii::Pipeline(*static_cast(api->getDevice()), nullptr, pipelineCreateInfoChain.get()); + + // descriptor sets du material (set 2) + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + m_descriptorSets[i] = api->getDescriptorPoolManager().allocate( + *api->getMaterial2DLayout() + ); + + std::vector writes; + + // binding 1 : albedo (si présent) + vk::DescriptorImageInfo albedoInfo; + if (m_texture) { + albedoInfo = { + *m_texture->getSampler(), + *m_texture->getImageView(), + vk::ImageLayout::eShaderReadOnlyOptimal + }; + writes.push_back({ + *m_descriptorSets[i].set, + 1, 0, 1, + vk::DescriptorType::eCombinedImageSampler, + &albedoInfo + }); + } + else if (m_font) { + albedoInfo = { + *m_font->getAtlas()->getSampler(), + *m_font->getAtlas()->getImageView(), + vk::ImageLayout::eShaderReadOnlyOptimal + }; + writes.push_back({ + *m_descriptorSets[i].set, + 1, 0, 1, + vk::DescriptorType::eCombinedImageSampler, + &albedoInfo + }); + } + else { + albedoInfo = { + api->getDefaultTexture()->getSampler(), + api->getDefaultTexture()->getImageView(), + vk::ImageLayout::eShaderReadOnlyOptimal + }; + writes.push_back({ + *m_descriptorSets[i].set, + 1, 0, 1, + vk::DescriptorType::eCombinedImageSampler, + &albedoInfo + }); + } + + if (!writes.empty()) + device->updateDescriptorSets(writes, {}); + } + isInit = true; +} + +void CMaterial2D::destroy() { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + api->destroyPipeline(pipeline, pipelineLayout); + + // descriptor sets + for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { + api->destroyDescriptorSet(m_descriptorSets[i], i); + } +} + +} // namespace CosmicCore \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp new file mode 100644 index 0000000..0ca4352 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp @@ -0,0 +1,48 @@ +#ifndef CUIPIPELINE_HPP +#define CUIPIPELINE_HPP + +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/Constants.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/ManagedDescriptorSet.hpp" +#include "Engine/Core/Systems/Graphics/Data/Font/CFont.hpp" +#include "Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp" +#include "Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp" +#include + +namespace CosmicCore { + + class CMaterial2D { + private: + + + public: + glm::vec4 m_color = {1, 1, 1, 1}; + CTexture* m_texture = nullptr; + CFont* m_font = nullptr; + bool m_alphaBlend = true; + + bool isInit = false; + CTexture* texture = nullptr; + CShaderImplVulkan* shader; + vk::raii::PipelineLayout pipelineLayout = nullptr; + vk::raii::Pipeline pipeline = nullptr; + std::array m_descriptorSets; + void build(); + void destroy(); + + vk::raii::Pipeline& getPipeline() { return pipeline; } + vk::raii::PipelineLayout& getPipelineLayout() { return pipelineLayout; } + vk::raii::DescriptorSet& getDescriptorSet(uint32_t frameIndex) { + return m_descriptorSets[frameIndex].set; + } + + CMaterial2D() = default; + ~CMaterial2D() { destroy(); } + + CMaterial2D(CMaterial2D&&) = default; + CMaterial2D& operator=(CMaterial2D&&) = default; + CMaterial2D(const CMaterial2D&) = delete; + CMaterial2D& operator=(const CMaterial2D&) = delete; + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/SColor.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/SColor.hpp new file mode 100644 index 0000000..1be4ff2 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Material/SColor.hpp @@ -0,0 +1,39 @@ +#ifndef SCOLOR_HPP +#define SCOLOR_HPP + +#include + +/** + * @file SColor.hpp + * @brief File for the color struct of a material. + */ + +/** + * @brief the number of type in the enum EColorType. + */ +#define COLOR_TYPE_NUMBER 2 + +/** + * @brief The enum for color type in the material. + */ +enum EColorType { + COLOR_DIFFUSE, + COLOR_SPECULAR, +}; + +/** + * @brief The struct color of the material. + */ +typedef struct { + /** + * @brief 4D Vector representing the RGBA color. + */ + glm::vec4 m_vector; + + /** + * @brief The color's type. + */ + EColorType m_type; +} SColor; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.cpp new file mode 100644 index 0000000..1c5652d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.cpp @@ -0,0 +1,85 @@ +#include "CMesh.hpp" +#include "../../API/VulkanImplementation/VulkanImpl.hpp" +#include +#include +CMesh::CMesh(void) : + m_vertexes() { +} + +CMesh::~CMesh(void) { + destroy(); +} + +void CMesh::destroy() +{ + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + api->destroyBuffer(vertexIndexBuffer, api->getCurrentFrameIndex()); +} +std::vector& CMesh::getVertices(void) { + return m_vertexes; +} + + +void CMesh::setVertices(std::vector vertices) +{ + m_vertexes = vertices; +} +void CMesh::setIndexes(std::vector indexes){ + m_indexes = indexes; +} + +std::vector& CMesh::getIndexes(void){ + return m_indexes; +} + +void CMesh::load(void) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + VmaAllocator allocator = api->getAllocator(); + + VkDeviceSize vertexSize = sizeof(m_vertexes[0]) * m_vertexes.size(); + VkDeviceSize indexSize = sizeof(m_indexes[0]) * m_indexes.size(); + VkDeviceSize totalSize = vertexSize + indexSize; + + // 1. staging buffer - CPU visible, temporaire + VkBufferCreateInfo stagingBufferInfo{}; + stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + stagingBufferInfo.size = totalSize; + stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + + VmaAllocationCreateInfo stagingAllocInfo{}; + stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; + stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VMABuffer stagingBuffer; + VmaAllocationInfo stagingInfo{}; + vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, + &stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo); + + // 2. copie des données CPU → staging + memcpy(stagingInfo.pMappedData, m_vertexes.data(), vertexSize); + memcpy((char*)stagingInfo.pMappedData + vertexSize, m_indexes.data(), indexSize); + vmaFlushAllocation(allocator, stagingBuffer.allocation, 0, VK_WHOLE_SIZE); + + // 3. vertex buffer final - DEVICE_LOCAL, rapide + VkBufferCreateInfo vertexBufferInfo{}; + vertexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + vertexBufferInfo.size = totalSize; + vertexBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT + | VK_BUFFER_USAGE_INDEX_BUFFER_BIT + | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + + VmaAllocationCreateInfo vertexAllocInfo{}; + vertexAllocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + + vmaCreateBuffer(allocator, &vertexBufferInfo, &vertexAllocInfo, + &vertexIndexBuffer.buffer, &vertexIndexBuffer.allocation, nullptr); + + // 4. copie GPU staging → vertex buffer via command buffer + api->copyBuffer(stagingBuffer.buffer, vertexIndexBuffer.buffer, totalSize); + + m_vertexOffset = 0; + m_indexOffset = vertexSize; + m_indexCount = m_indexes.size(); + // 5. détruire le staging buffer + vmaDestroyBuffer(allocator, stagingBuffer.buffer, stagingBuffer.allocation); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.hpp new file mode 100644 index 0000000..bb7c273 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh.hpp @@ -0,0 +1,44 @@ +#ifndef CMESH_HPP +#define CMESH_HPP + +#include "SVertex.hpp" + +#include +#include +#include +#include +#include "../../API/VulkanImplementation/VMABuffer.hpp" + +class CMesh { +private: + + std::vector m_vertexes; + std::vector m_indexes; + + VMABuffer vertexIndexBuffer; + VkDeviceSize m_vertexOffset = 0; + VkDeviceSize m_indexOffset = 0; + uint32_t m_indexCount = 0; + +public: + + CMesh(void); + + ~CMesh(void); + + std::vector& getVertices(void); + std::vector& getIndexes(void); + + void setVertices(std::vector vertices); + void setIndexes(std::vector indexes); + + void load(void); + + VMABuffer& getVertexIndexBuffer(){return vertexIndexBuffer;}; + VkDeviceSize getVertexOffset(){return m_vertexOffset;} + VkDeviceSize getIndexOffset(){return m_indexOffset;}; + uint32_t getIndexCount(){return m_indexCount;}; + void destroy(); +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.cpp new file mode 100644 index 0000000..a6138bf --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.cpp @@ -0,0 +1,186 @@ +#include "CMesh2D.hpp" +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VulkanImpl.hpp" +#include "Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp" +#include "glm/ext/vector_float2.hpp" +#include +#include +namespace CosmicCore { + + CMesh2D::CMesh2D(void) : + m_vertexes() { + } + + CMesh2D::~CMesh2D(void) { + destroy(); + } + + void CMesh2D::destroy() + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + api->destroyBuffer(vertexIndexBuffer, api->getCurrentFrameIndex()); + } + std::vector& CMesh2D::getVertices(void) { + return m_vertexes; + } + + + void CMesh2D::setVertices(std::vector vertices) + { + m_vertexes = vertices; + computeCenter(); + } + void CMesh2D::setIndexes(std::vector indexes){ + m_indexes = indexes; + } + + std::vector& CMesh2D::getIndexes(void){ + return m_indexes; + } + + void CMesh2D::computeCenter() + { + if (m_vertexes.empty()) + m_center = glm::vec2(0.0f, 0.0f); + + glm::vec2 mn{ m_vertexes[0].m_position.x, m_vertexes[0].m_position.y }; + glm::vec2 mx = mn; + + for (const auto& v : m_vertexes) { + mn.x = std::min(mn.x, v.m_position.x); + mn.y = std::min(mn.y, v.m_position.y); + mx.x = std::max(mx.x, v.m_position.x); + mx.y = std::max(mx.y, v.m_position.y); + } + m_center = (mn + mx) * 0.5f; + } + + + void CMesh2D::load(void) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + VmaAllocator allocator = api->getAllocator(); + + VkDeviceSize vertexSize = sizeof(m_vertexes[0]) * m_vertexes.size(); + VkDeviceSize indexSize = sizeof(m_indexes[0]) * m_indexes.size(); + VkDeviceSize totalSize = vertexSize + indexSize; + + //staging buffer CPU visible, temporaire + VkBufferCreateInfo stagingBufferInfo{}; + stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + stagingBufferInfo.size = totalSize; + stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + + VmaAllocationCreateInfo stagingAllocInfo{}; + stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; + stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VMABuffer stagingBuffer; + VmaAllocationInfo stagingInfo{}; + vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, + &stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo); + + // copie des données CPU → staging + memcpy(stagingInfo.pMappedData, m_vertexes.data(), vertexSize); + memcpy((char*)stagingInfo.pMappedData + vertexSize, m_indexes.data(), indexSize); + vmaFlushAllocation(allocator, stagingBuffer.allocation, 0, VK_WHOLE_SIZE); + + //vertex buffer final - DEVICE_LOCAL + VkBufferCreateInfo vertexBufferInfo{}; + vertexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + vertexBufferInfo.size = totalSize; + vertexBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT + | VK_BUFFER_USAGE_INDEX_BUFFER_BIT + | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + + VmaAllocationCreateInfo vertexAllocInfo{}; + vertexAllocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; + + vmaCreateBuffer(allocator, &vertexBufferInfo, &vertexAllocInfo, + &vertexIndexBuffer.buffer, &vertexIndexBuffer.allocation, nullptr); + + // copie GPU staging vertex buffer via command buffer + api->copyBuffer(stagingBuffer.buffer, vertexIndexBuffer.buffer, totalSize); + + m_vertexOffset = 0; + m_indexOffset = vertexSize; + m_indexCount = m_indexes.size(); + //détruire le staging buffer + vmaDestroyBuffer(allocator, stagingBuffer.buffer, stagingBuffer.allocation); + } + + glm::vec2 CMesh2D::buildFromText(CFont* font, const std::string& text) + { + //destroy check before load if text is edited ? + if (!font || text.empty()) { + setVertices({}); + setIndexes({}); + return {0.0f, 0.0f}; + } + + std::vector vertices; + std::vector indices; + + float scale = font->getMetrics().emSize; + float cursorX = 0.0f; + float cursorY = 0.0f; + float maxWidth = 0.0f; + float maxHeight = 0.0f; + int lineCount = 1; + + for (char c : text) { + if (c == '\n') { + maxWidth = std::max(maxWidth, cursorX); + cursorX = 0.0f; + cursorY += font->getMetrics().lineHeight * scale; + lineCount++; + continue; + } + + const SGlyph* glyph = font->getGlyph((uint32_t)c); + if (!glyph) continue; + + // positions des coins du quad (espace local au mesh) + glm::vec2 p0 = { + cursorX + glyph->planeMin.x * scale, + cursorY - glyph->planeMin.y * scale + }; + glm::vec2 p1 = { + cursorX + glyph->planeMax.x * scale, + cursorY - glyph->planeMax.y * scale + }; + maxHeight = std::max(maxHeight, glyph->planeMax.y); + // UVs dans l'atlas — flip V pour Vulkan + glm::vec2 uv0 = {glyph->atlasMin.x, 1.0f - glyph->atlasMax.y}; + glm::vec2 uv1 = {glyph->atlasMax.x, 1.0f - glyph->atlasMin.y}; + + uint32_t base = (uint32_t)vertices.size(); + + vertices.push_back({{p0.x, p1.y}, {uv0.x, uv0.y}, {1, 1, 1, 1}}); + vertices.push_back({{p0.x, p0.y}, {uv0.x, uv1.y}, {1, 1, 1, 1}}); + vertices.push_back({{p1.x, p0.y}, {uv1.x, uv1.y}, {1, 1, 1, 1}}); + vertices.push_back({{p1.x, p1.y}, {uv1.x, uv0.y}, {1, 1, 1, 1}}); + + + indices.insert(indices.end(), + {base, base+1, base+2, base+2, base+3, base}); + + cursorX += glyph->advance * scale; + } + + maxWidth = std::max(maxWidth, cursorX); + float totalHeight = lineCount * font->getMetrics().lineHeight * scale; + + setVertices(vertices); + setIndexes(indices); + + //recentrer le mesh sur le centre du texte + for (auto& v : m_vertexes) { + v.m_position.x -= m_center.x; + v.m_position.y -= m_center.y; + } + + load(); // upload GPU + + return {maxWidth, totalHeight}; + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.hpp new file mode 100644 index 0000000..8d4042e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.hpp @@ -0,0 +1,45 @@ +#ifndef CMESH2D_HPP +#define CMESH2D_HPP + +#include "Engine/Core/Systems/Graphics/API/VulkanImplementation/VMABuffer.hpp" +#include "Engine/Core/Systems/Graphics/Data/Font/CFont.hpp" +#include "Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp" +#include "glm/ext/vector_float2.hpp" +namespace CosmicCore { + class CMesh2D + { + private: + std::vector m_vertexes; + std::vector m_indexes; + + VMABuffer vertexIndexBuffer; + VkDeviceSize m_vertexOffset = 0; + VkDeviceSize m_indexOffset = 0; + uint32_t m_indexCount = 0; + + glm::vec2 m_center; + void computeCenter(); + public: + + CMesh2D(void); + + ~CMesh2D(void); + + std::vector& getVertices(void); + std::vector& getIndexes(void); + + void setVertices(std::vector vertices); + void setIndexes(std::vector indexes); + + void load(void); + + VMABuffer& getVertexIndexBuffer(){return vertexIndexBuffer;}; + VkDeviceSize getVertexOffset(){return m_vertexOffset;} + VkDeviceSize getIndexOffset(){return m_indexOffset;}; + uint32_t getIndexCount(){return m_indexCount;}; + void destroy(); + glm::vec2 buildFromText(CFont* font, const std::string& text); + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp new file mode 100644 index 0000000..356d952 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Mesh/SVertex.hpp @@ -0,0 +1,96 @@ +#ifndef SVERTEX_HPP +#define SVERTEX_HPP + +#include "vulkan/vulkan.hpp" +#include + +/** + * @file SVertex.hpp + * @brief File for the vertex struct. + */ + +/** + * @brief the struct Vertex, use to represent vertex and vertex attribute. + */ +typedef struct SVertex{ + /** + * @brief Position attribute. + * 3D vector. + */ + glm::vec3 m_position; + + /** + * @brief Position attribute. + * 3D vector. + */ + glm::vec4 m_color; + /** + * @brief Normal attribute. + * 3D vector. + */ + glm::vec3 m_normal; + + /** + * @brief Texture coordinates attribute. + * 2D vector. + */ + glm::vec2 m_texCoords; + + /** + * @brief Tangent attribute. + * 3D vector. + */ + glm::vec3 m_tangent; + + /** + * @brief Bitangent attribute. + * 3D vector (perpendicular to m_tangent vector). + */ + glm::vec3 m_bitangent; + + // m_normal, m_tangent, m_bitangent are supposed to create a vector base to compute normal map. + + static vk::VertexInputBindingDescription getBindingDescription() { + return { 0, sizeof(SVertex), vk::VertexInputRate::eVertex }; + } + + static std::array getAttributeDescriptions() { + return { + vk::VertexInputAttributeDescription( 0, 0, vk::Format::eR32G32B32Sfloat, offsetof(SVertex, m_position) ), + vk::VertexInputAttributeDescription( 1, 0, vk::Format::eR32G32B32A32Sfloat, offsetof(SVertex, m_color) ), + vk::VertexInputAttributeDescription( 2, 0, vk::Format::eR32G32B32Sfloat, offsetof(SVertex, m_normal) ), + vk::VertexInputAttributeDescription( 3, 0, vk::Format::eR32G32Sfloat, offsetof(SVertex, m_texCoords) ), + vk::VertexInputAttributeDescription( 4, 0, vk::Format::eR32G32B32Sfloat, offsetof(SVertex, m_tangent) ), + vk::VertexInputAttributeDescription( 5, 0, vk::Format::eR32G32B32Sfloat, offsetof(SVertex, m_bitangent) ) + }; + } + +} Vertex; + +/** + * @brief the struct Vertex, use to represent vertex and vertex attribute. + */ + typedef struct SVertex2D{ + + glm::vec2 m_position; + glm::vec2 m_uv; + glm::vec4 m_color; + + + static vk::VertexInputBindingDescription getBindingDescription() { + return { 0, sizeof(SVertex2D), vk::VertexInputRate::eVertex }; + } + + static std::array getAttributeDescriptions() { + return {{ + {0, 0, vk::Format::eR32G32Sfloat, offsetof(SVertex2D, m_position)}, + {1, 0, vk::Format::eR32G32Sfloat, offsetof(SVertex2D, m_uv)}, + {2, 0, vk::Format::eR32G32B32A32Sfloat, offsetof(SVertex2D, m_color)} + }}; + } + +} Vertex2D; + + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.cpp new file mode 100644 index 0000000..b26771f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.cpp @@ -0,0 +1,24 @@ +#include "CModel.hpp" + +CModel::CModel(std::vector meshes) : + m_meshes(meshes), + m_loaded(false) { +} + +CModel::~CModel(void) { +} + +std::vector& CModel::getMeshMaterials() +{ + return m_meshes; +} + +void CModel::setMeshMaterials(std::vector meshes) +{ + m_meshes = meshes; +} + +bool CModel::isLoaded() +{ + return m_loaded; +} diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.hpp new file mode 100644 index 0000000..4e4e758 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel.hpp @@ -0,0 +1,40 @@ +#ifndef CMODEL_HPP +#define CMODEL_HPP + +#include "../Material/CMaterial.hpp" +#include "../Mesh/CMesh.hpp" +#include + +struct MeshMaterial{ + CMesh* mesh = nullptr; + CMaterial* material = nullptr; +}; + +class CModel { +private: + + std::vector m_meshes; + + bool m_loaded; + +public: + + CModel(void) = delete; + + CModel(std::vector meshes); + + ~CModel(void); + + //void load(void); + + //void draw(glm::mat4 model, glm::mat4 view, glm::mat4 projection, glm::vec3 lightPos, float intensity); + + std::vector& getMeshMaterials(void); + + void setMeshMaterials(std::vector meshes); + + bool isLoaded(void); + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.cpp new file mode 100644 index 0000000..39ffb84 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.cpp @@ -0,0 +1,28 @@ +#include "CModel2D.hpp" + +namespace CosmicCore { + + CModel2D::CModel2D(std::vector meshes) : + m_meshes(meshes), + m_loaded(false) { + } + + CModel2D::~CModel2D(void) { + } + + std::vector& CModel2D::getMeshMaterials() + { + return m_meshes; + } + + void CModel2D::setMeshMaterials(std::vector meshes) + { + m_meshes = meshes; + } + + bool CModel2D::isLoaded() + { + return m_loaded; + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp new file mode 100644 index 0000000..9920e75 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp @@ -0,0 +1,36 @@ +#ifndef CMODEL2D_HPP +#define CMODEL2D_HPP + +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp" +#include "Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.hpp" +namespace CosmicCore { + struct MeshMaterial2D{ + CMesh2D* mesh = nullptr; + CMaterial2D* material = nullptr; + }; + + class CModel2D { + private: + + std::vector m_meshes; + + bool m_loaded; + + public: + + CModel2D(void) = delete; + + CModel2D(std::vector meshes); + + ~CModel2D(void); + + std::vector& getMeshMaterials(void); + + void setMeshMaterials(std::vector meshes); + + bool isLoaded(void); + + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.cpp new file mode 100644 index 0000000..6987c05 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.cpp @@ -0,0 +1,241 @@ +#include "CTexture.hpp" + +#include "../../API/VulkanImplementation/VulkanImpl.hpp" +#include + +CTexture::CTexture(std::string filePath, TextureType type) : + m_filePath(filePath), m_type(type) { +} + +std::string CTexture::getFilePath(void) { + return m_filePath; +} + +void CTexture::setFilePath(std::string filePath) { + m_filePath = filePath; +} + +void CTexture::init(void) { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto* device= static_cast(api->getDevice()); + // Read the image file. + SDL_Surface* sdlSurface = IMG_Load(m_filePath.c_str()); + + if (!sdlSurface) { + throw std::runtime_error("Failed to load: " + m_filePath); + } + + // Choix du format en fonction du type de texture + vk::Format formatCol = (m_type == TextureType::MSDFFont) + ? vk::Format::eR8G8B8A8Unorm + : vk::Format::eR8G8B8A8Srgb; + + vk::Format bgraFormat = (m_type == TextureType::MSDFFont) + ? vk::Format::eB8G8R8A8Unorm + : vk::Format::eB8G8R8A8Srgb; + + SDL_PixelFormat sdlFormat = sdlSurface->format; + + SDL_Surface* converted = nullptr; + + if (sdlFormat == SDL_PIXELFORMAT_RGBA32) { + // déjà RGBA, pas de conversion + converted = sdlSurface; + m_format = formatCol; + } else if (sdlFormat == SDL_PIXELFORMAT_BGRA32) { + // déjà BGRA, pas de conversion mais format différent + converted = sdlSurface; + m_format = bgraFormat; + } else { + // tout autre format → on force RGBA32 + converted = SDL_ConvertSurface(sdlSurface, SDL_PIXELFORMAT_RGBA32); + if (!converted) + throw std::runtime_error("Failed to convert surface: " + m_filePath); + SDL_DestroySurface(sdlSurface); + m_format = formatCol; + } + + + m_width = converted->w; + m_height = converted->h; + VkDeviceSize imageSize = m_width * m_height * 4; + + // staging buffer + VkBufferCreateInfo stagingBufferInfo{}; + stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + stagingBufferInfo.size = imageSize; + stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + + VmaAllocationCreateInfo stagingAllocInfo{}; + stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; + stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VMABuffer stagingBuffer; + VmaAllocationInfo stagingInfo{}; + vmaCreateBuffer(api->getAllocator(), &stagingBufferInfo, &stagingAllocInfo, + &stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo); + + memcpy(stagingInfo.pMappedData, converted->pixels, imageSize); + // Free the surface. + SDL_DestroySurface(converted); + + // crée l'image GPU + api->createImage( + m_width, m_height, + m_format, + vk::ImageTiling::eOptimal, + vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, + vk::MemoryPropertyFlagBits::eDeviceLocal, + m_textureImage, + m_textureImageMemory + ); + + // transitions et copie + api->transitionImageLayout(m_textureImage, + vk::ImageLayout::eUndefined, + vk::ImageLayout::eTransferDstOptimal); + + { + auto cmd = api->beginSingleTimeCommands(); + vk::BufferImageCopy region{ + 0, 0, 0, + {vk::ImageAspectFlagBits::eColor, 0, 0, 1}, + {0, 0, 0}, + {static_cast(m_width), static_cast(m_height), 1} + }; + cmd.copyBufferToImage( + vk::Buffer(stagingBuffer.buffer), + m_textureImage, + vk::ImageLayout::eTransferDstOptimal, + region + ); + api->endSingleTimeCommands(cmd); + } + + api->transitionImageLayout(m_textureImage, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal); + + vmaDestroyBuffer(api->getAllocator(), stagingBuffer.buffer, stagingBuffer.allocation); + + // image view + m_imageView = api->createImageView(m_textureImage, m_format, vk::ImageAspectFlagBits::eColor); + + // sampler + vk::SamplerCreateInfo samplerInfo{}; + samplerInfo.magFilter = vk::Filter::eLinear; + samplerInfo.minFilter = vk::Filter::eLinear; + samplerInfo.unnormalizedCoordinates = vk::False; + samplerInfo.compareEnable = vk::False; + samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack; + + if (m_type == TextureType::MSDFFont) { + samplerInfo.addressModeU = vk::SamplerAddressMode::eClampToEdge; + samplerInfo.addressModeV = vk::SamplerAddressMode::eClampToEdge; + samplerInfo.addressModeW = vk::SamplerAddressMode::eClampToEdge; + samplerInfo.anisotropyEnable = vk::False; + samplerInfo.maxAnisotropy = 1.0f; + samplerInfo.mipmapMode = vk::SamplerMipmapMode::eNearest; + samplerInfo.minLod = 0.0f; + samplerInfo.maxLod = 0.0f; + } else { + samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat; + samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat; + samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat; + samplerInfo.anisotropyEnable = vk::True; + samplerInfo.maxAnisotropy = api->getPhysicalDevice().getProperties().limits.maxSamplerAnisotropy; + samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear; + } + + m_sampler = vk::raii::Sampler(*device, samplerInfo); + +} + +void CTexture::initDefaultTexture() +{ + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto* device= static_cast(api->getDevice()); + + // pixel rouge RGBA + uint32_t whitePixel = 0x00000ff0; + uint32_t width = 1; + uint32_t height = 1; + VkDeviceSize imageSize = sizeof(uint32_t); + + // staging buffer + VkBufferCreateInfo stagingBufferInfo{}; + stagingBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + stagingBufferInfo.size = imageSize; + stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + + VmaAllocationCreateInfo stagingAllocInfo{}; + stagingAllocInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; + stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; + + VMABuffer stagingBuffer; + VmaAllocationInfo stagingInfo{}; + vmaCreateBuffer(api->getAllocator(), &stagingBufferInfo, &stagingAllocInfo, + &stagingBuffer.buffer, &stagingBuffer.allocation, &stagingInfo); + + memcpy(stagingInfo.pMappedData, &whitePixel, imageSize); + + // image GPU + api->createImage(width, height, + vk::Format::eR8G8B8A8Srgb, + vk::ImageTiling::eOptimal, + vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, + vk::MemoryPropertyFlagBits::eDeviceLocal, + m_textureImage, + m_textureImageMemory + ); + + api->transitionImageLayout(m_textureImage, + vk::ImageLayout::eUndefined, + vk::ImageLayout::eTransferDstOptimal); + + { + auto cmd = api->beginSingleTimeCommands(); + vk::BufferImageCopy region{ + 0, 0, 0, + {vk::ImageAspectFlagBits::eColor, 0, 0, 1}, + {0, 0, 0}, + {width, height, 1} + }; + cmd.copyBufferToImage( + vk::Buffer(stagingBuffer.buffer), + m_textureImage, + vk::ImageLayout::eTransferDstOptimal, + region + ); + api->endSingleTimeCommands(cmd); + } + + api->transitionImageLayout(m_textureImage, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal); + + vmaDestroyBuffer(api->getAllocator(), stagingBuffer.buffer, stagingBuffer.allocation); + + // image view + m_imageView = api->createImageView( + m_textureImage, + vk::Format::eR8G8B8A8Srgb, + vk::ImageAspectFlagBits::eColor + ); + + // sampler + vk::SamplerCreateInfo samplerInfo{}; + samplerInfo.magFilter = vk::Filter::eLinear; + samplerInfo.minFilter = vk::Filter::eLinear; + samplerInfo.addressModeU = vk::SamplerAddressMode::eRepeat; + samplerInfo.addressModeV = vk::SamplerAddressMode::eRepeat; + samplerInfo.addressModeW = vk::SamplerAddressMode::eRepeat; + samplerInfo.anisotropyEnable = vk::False; + samplerInfo.maxAnisotropy = 1.0f; + samplerInfo.borderColor = vk::BorderColor::eIntOpaqueBlack; + samplerInfo.unnormalizedCoordinates = vk::False; + samplerInfo.compareEnable = vk::False; + samplerInfo.mipmapMode = vk::SamplerMipmapMode::eLinear; + + m_sampler = vk::raii::Sampler(*device, samplerInfo); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp new file mode 100644 index 0000000..8595fc7 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp @@ -0,0 +1,49 @@ +#ifndef CTEXTURE_HPP +#define CTEXTURE_HPP + +#include +#include +#include +#include + +enum class TextureType { + Color, // image classique (sprite, icône, etc.) + MSDFFont // atlas de glyphes MSDF +}; + +class CTexture{ +private: + // Path of the file. + std::string m_filePath; + vk::raii::Image m_textureImage = nullptr; + vk::raii::DeviceMemory m_textureImageMemory = nullptr; + vk::raii::ImageView m_imageView = nullptr; + vk::raii::Sampler m_sampler = nullptr; + TextureType m_type; + uint32_t m_width = 0; + uint32_t m_height = 0; + vk::Format m_format = vk::Format::eR8G8B8A8Srgb; + +public: + CTexture(void) = delete; + CTexture(const CTexture&) = delete; + CTexture& operator=(const CTexture&) = delete; + ~CTexture(void) { + m_sampler = nullptr; + m_imageView = nullptr; + m_textureImage = nullptr; + m_textureImageMemory = nullptr; + }; + CTexture(std::string filePath, TextureType type = TextureType::Color); + std::string getFilePath(void); + void setFilePath(std::string filePath); + void init(void); + void initDefaultTexture(); + + vk::raii::ImageView& getImageView() { return m_imageView; } + vk::raii::Sampler& getSampler() { return m_sampler; } + uint32_t getWidth() const { return m_width; } + uint32_t getHeight() const { return m_height; } +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Tint/CTint.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Data/Tint/CTint.hpp new file mode 100644 index 0000000..e69de29 diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.cpp new file mode 100644 index 0000000..349768d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.cpp @@ -0,0 +1,6 @@ +#include "CShader.hpp" + +CShader::~CShader() +{ + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.hpp new file mode 100644 index 0000000..283a46d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/CShader.hpp @@ -0,0 +1,159 @@ +#ifndef CSHADER_HPP +#define CSHADER_HPP + +#include +#include + +/** + * @file CShader.hpp + * @brief File of CShader, a class to manage complete shader program, composed of a vertex shader, + * a fragment shader and sometime a geometry shader. + */ + +/** + * @brief Class to manage complete shader program, composed of a vertex shader, + * a fragment shader and sometime a geometry shader. + */ +class CShader { +public: + virtual ~CShader(); + /** + * @brief Get the id of the shader. + * @return unsigned int, the id. + */ + virtual unsigned int getId(void) const = 0; + + /** + * @brief Get the name of the shader. + * @return std::string, the name. + */ + virtual std::string getName(void) const = 0; + + /** + * @brief Get the vertex of the shader. + * @return std::string, the path. + */ + virtual std::string getVertexPath(void) const = 0; + + /** + * @brief Get the geometry of the shader. + * @return std::string, the path. + */ + virtual std::string getGeomPath(void) const = 0; + + /** + * @brief Get the fragment of the shader. + * @return std::string, the path. + */ + virtual std::string getFragmentPath(void) const = 0; + + /** + * @brief set the name of the shader. + * @param[in] name the name. + */ + virtual void setName(std::string name) = 0; + + /** + * @brief Get the vertex source path of the shader. + * @param[in] vp the path. + */ + virtual void setVertexPath(std::string vp) = 0; + + /** + * @brief Get the geometry source path of the shader. + * @param[in] gp the path. + */ + virtual void setGeomPath(std::string gp) = 0; + + /** + * @brief Get the fragment source path of the shader. + * @param[in] fp the path. + */ + virtual void setFragmentPath(std::string fp) = 0; + + /** + * @brief Return true if the shader is ready to use (compiled and linked). + * @return bool. + */ + virtual bool isReady(void) const = 0; + + /** + * @brief Return true if the shader program has a geometry shader. + * @return bool. + */ + virtual bool hasGeom(void) const = 0; + + /** + * @brief Set this shader as active, so it will be used for the next draw. + */ + virtual void use(void) = 0; + + /** + * @brief Init the shader to make it ready to use (read the fiel, compile, link...). + */ + virtual void init(void) = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setBool(const std::string& name, bool value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setInt(const std::string& name, int value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setFloat(const std::string& name, float value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setMat2(const std::string& name, glm::mat2 value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setMat3(const std::string& name, glm::mat3 value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setMat4(const std::string& name, glm::mat4 value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setVec2(const std::string& name, glm::vec2 value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setVec3(const std::string& name, glm::vec3 value) const = 0; + + /** + * @brief give a const value to a shader. + * @param[in] name The name of the uniform constant. + * @param[in] value The value. + */ + virtual void setVec4(const std::string& name, glm::vec4 value) const = 0; +}; +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.cpp new file mode 100644 index 0000000..98b2c06 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.cpp @@ -0,0 +1,107 @@ +#include "CShaderImplVulkan.hpp" +#include "vulkan/vulkan.hpp" +#include "../../API/GraphicsAPI.hpp" +#include +#include +#include +#include +#include + + +CShaderImplVulkan::CShaderImplVulkan(std::string name, std::filesystem::path spvPath): m_name(name), spirvPath(spvPath) +{ + +} + +std::string CShaderImplVulkan::getName(void) const { + return m_name; +} + +void CShaderImplVulkan::setName(std::string name) { + m_name = name; +} + +void CShaderImplVulkan::init() +{ + std::ifstream fileShader(spirvPath, std::ios::binary | std::ios::ate); + size_t fileSize = fileShader.tellg(); + fileShader.seekg(0); + + std::vector spirv(fileSize / sizeof(uint32_t)); + fileShader.read(reinterpret_cast(spirv.data()), fileSize); + //spirv.push_back('\0'); + //fileSize++; + fileShader.close(); + + vk::ShaderModuleCreateInfo createInfo{ {},fileSize,spirv.data() }; + shaderModule = vk::raii::ShaderModule(*static_cast(GraphicsAPI::getAPI()->getDevice()), createInfo); + + SpvReflectShaderModule module; + SpvReflectResult result = spvReflectCreateShaderModule( + spirv.size() * sizeof(uint32_t), + spirv.data(), + &module + ); + if(result == SPV_REFLECT_RESULT_SUCCESS) + { + uint32_t entryPointCount = module.entry_point_count; + for (uint32_t i = 0; i < entryPointCount; i++) { + const SpvReflectEntryPoint& entry = module.entry_points[i]; + + switch (entry.shader_stage) { + case SPV_REFLECT_SHADER_STAGE_VERTEX_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eVertex].push_back(entry.name); + break; + case SPV_REFLECT_SHADER_STAGE_FRAGMENT_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eFragment].push_back(entry.name); + break; + case SPV_REFLECT_SHADER_STAGE_GEOMETRY_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eGeometry].push_back(entry.name); + break; + case SPV_REFLECT_SHADER_STAGE_TESSELLATION_CONTROL_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eTessellationControl].push_back(entry.name); + break; + case SPV_REFLECT_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eTessellationEvaluation].push_back(entry.name); + break; + case SPV_REFLECT_SHADER_STAGE_COMPUTE_BIT: + stageEntryPoints[vk::ShaderStageFlagBits::eCompute].push_back(entry.name); + break; + default: + continue; + } + } + } + + spvReflectDestroyShaderModule(&module); +} + +void CShaderImplVulkan::setBool(const std::string& name, bool value) const +{ +} + +void CShaderImplVulkan::setInt(const std::string& name, int value) const +{ +} + +void CShaderImplVulkan::setFloat(const std::string& name, float value) const +{ +} + +void CShaderImplVulkan::setMat2(const std::string& name, glm::mat2 value) const { +} + +void CShaderImplVulkan::setMat3(const std::string& name, glm::mat3 value) const { +} + +void CShaderImplVulkan::setMat4(const std::string& name, glm::mat4 value) const { +} + +void CShaderImplVulkan::setVec2(const std::string& name, glm::vec2 value) const { +} + +void CShaderImplVulkan::setVec3(const std::string& name, glm::vec3 value) const { +} + +void CShaderImplVulkan::setVec4(const std::string& name, glm::vec4 value) const { +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp new file mode 100644 index 0000000..d916d5c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp @@ -0,0 +1,98 @@ +#ifndef CSHADEROPENGLIMPLHPP +#define CSHADEROPENGLIMPLHPP + +#include "../CShader.hpp" +#include "vulkan/vulkan.hpp" + +#include +#include +#include +#include + +/** + * @file CShaderImplVulkan.hpp + * @brief File of CShaderImplVulkan, a Vulkan impl. of CShader to manage shader program. + */ + + /** + * @brief a Vulkan impl. of CShader to manage shader program. + */ +class CShaderImplVulkan : public CShader { +private: + + std::string m_name; + std::filesystem::path spirvPath; + vk::raii::ShaderModule shaderModule = nullptr; + std::unordered_map> stageEntryPoints; + +public: + + CShaderImplVulkan() = delete; + + CShaderImplVulkan(std::string name, std::string vertexPath, std::string fragmentPath) = delete; + + CShaderImplVulkan(std::string name, std::string vertexPath, std::string fragmentPath, std::string geomPath) = delete; + + CShaderImplVulkan(std::string name, std::filesystem::path spvPath); + + virtual unsigned int getId(void) const {return 0;}; + + virtual std::string getName(void) const; + + virtual std::string getVertexPath(void) const {return "";}; + + virtual std::string getGeomPath(void) const{return "";}; + + virtual std::string getFragmentPath(void) const {return "";}; + + virtual void setName(std::string name); + + virtual void setVertexPath(std::string vp) {}; + + virtual void setGeomPath(std::string gp) {}; + + virtual void setFragmentPath(std::string fp) {}; + + virtual bool isReady(void) const {return true;}; + + virtual bool hasGeom(void) const {return true;}; + + virtual void use(void) {}; + + virtual void init(void); + + template + std::vector getShaderStages(unsigned int offset = 0, Flags... flagBits) + { + std::vector pipe; + for(auto el : std::initializer_list{ flagBits... }) + { + //todo assert exists + std::string& entry = stageEntryPoints[el][offset]; + vk::PipelineShaderStageCreateInfo info{{}, el, shaderModule, entry.c_str() };//todo check specialized info ? + pipe.push_back(info); + } + return pipe; + } + + virtual void setBool(const std::string& name, bool value) const; + + virtual void setInt(const std::string& name, int value) const; + + virtual void setFloat(const std::string& name, float value) const; + + virtual void setMat2(const std::string& name, glm::mat2 value) const; + + virtual void setMat3(const std::string& name, glm::mat3 value) const; + + virtual void setMat4(const std::string& name, glm::mat4 value) const; + + virtual void setVec2(const std::string& name, glm::vec2 value) const; + + virtual void setVec3(const std::string& name, glm::vec3 value) const; + + virtual void setVec4(const std::string& name, glm::vec4 value) const; +}; + + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/UserInterface/CUIWorld.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/UserInterface/CUIWorld.hpp new file mode 100644 index 0000000..b7c5a0a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/UserInterface/CUIWorld.hpp @@ -0,0 +1 @@ +//TODO ??????? \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.cpp new file mode 100644 index 0000000..db568ba --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.cpp @@ -0,0 +1,135 @@ +#include "CGameWindow.hpp" +#include +#include + +CGameWindow::CGameWindow(std::string title, std::string iconPath, unsigned int width, unsigned int height, bool resizable, bool fullscreen) : + CWindow(title, iconPath, width, height, false, false, SDL_WINDOW_VULKAN), + m_grabCursor(false), + m_relativeCursor(false), + m_msaa(0) { +} + +CGameWindow::CGameWindow(std::string title, SDL_Window* window) : + CWindow(title, window, SDL_WINDOW_VULKAN), + m_grabCursor(false), + m_relativeCursor(false), + m_msaa(0) { +} + +CGameWindow::~CGameWindow(void) { +} + +/*SDL_GLContext CGameWindow::getOpenGLContext(void) { + if (getWindow() == nullptr) { + //throw CLogicException("The window must be initialized before using this method !"); + } + else { + SDL_GLContext out = SDL_GL_CreateContext(getWindow()); + if (out == nullptr) { + //throw CLibException(std::string("Unable to create OpenGL context: ") + SDL_GetError()); + } + return out; + } +}*/ + +bool CGameWindow::isCursorGrabbed(void) const { + return m_grabCursor; +} + +void CGameWindow::setCursorGrabbed(bool newMouseGrab) { + m_grabCursor = newMouseGrab; + + if (m_relativeCursor && !m_grabCursor) { + setCursorRelative(false); + } + + if (getWindow() != nullptr) { + if (m_grabCursor) { + SDL_SetWindowMouseGrab(getWindow(), true); + } + else { + SDL_SetWindowMouseGrab(getWindow(), false); + } + } +} + +bool CGameWindow::isCursorRelative(void) const { + return m_relativeCursor; +} + +void CGameWindow::setCursorRelative(bool newMouseRelative) { + m_relativeCursor = newMouseRelative; + + if (m_relativeCursor && !m_grabCursor) { + setCursorGrabbed(true); + } + + if (getWindow() != nullptr) { + if (m_relativeCursor) { + SDL_SetWindowRelativeMouseMode(getWindow(), true); + } + else { + SDL_SetWindowRelativeMouseMode(getWindow(), false); + } + } +} + +unsigned char CGameWindow::getAntiAliasing(void) const { + return m_msaa; +} + +void CGameWindow::setAntiAliasing(unsigned char newMsaa) { + if (getWindow() != nullptr) { + //throw CLogicException("The window must be uninitialized before using this method !"); + } + else { + if (newMsaa == 2 || newMsaa == 4 || newMsaa == 8 || newMsaa == 16) { + m_msaa = newMsaa; + } + else { + m_msaa = 0; + } + } +} + +void CGameWindow::preinitialization(void) { + // We want OpenGL version 3.3. + /*SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); + + // Anti-aliasing Configuration. + if (m_msaa == 0) { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); + } + else { + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); + SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, m_msaa); + } + + // Double Buffer. + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + + // Depht Buffer. + SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);*/ + //TODO init graphic generic (opengl vulkan etc.... commence par vulkan ?) + +} + +void CGameWindow::postinitialization(void) { + + // Set the cursorGrab property. + if (m_grabCursor) { + SDL_SetWindowMouseGrab(getWindow(), true); + } + else { + SDL_SetWindowMouseGrab(getWindow(), false); + } + + // Set the cursorRelative property. + if (m_relativeCursor) { + SDL_SetWindowRelativeMouseMode(getWindow(), true); + } + else { + SDL_SetWindowRelativeMouseMode(getWindow(), false); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.hpp new file mode 100644 index 0000000..734124e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CGameWindow.hpp @@ -0,0 +1,49 @@ +#ifndef CGAMEWINDOW_HPP +#define CGAMEWINDOW_HPP + +#include "CWindow.hpp" + +#include + +class CGameWindow : public CWindow { +private: + // Say if the mouse is grabbed. + bool m_grabCursor; + + // Say if the mouse is in relative mode. + bool m_relativeCursor; + + // The anti-aliasing. + unsigned char m_msaa; + +public: + CGameWindow(void) = delete; + CGameWindow(const CGameWindow& param) = delete; + CGameWindow& operator=(const CGameWindow& param) = delete; + + CGameWindow(std::string title, std::string iconPath, unsigned int width, unsigned int height, bool resizable, bool fullscreen); + + CGameWindow(std::string title, SDL_Window* window); + + ~CGameWindow(void); + + bool isCursorGrabbed(void) const; + + void setCursorGrabbed(bool newMouseGrab); + + bool isCursorRelative(void) const; + + void setCursorRelative(bool newMouseRelative); + + unsigned char getAntiAliasing(void) const; + + void setAntiAliasing(unsigned char newMsaa); + + virtual void preinitialization(); + + virtual void postinitialization(); + + //SDL_GLContext getOpenGLContext(void); +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.cpp new file mode 100644 index 0000000..8e75aa8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.cpp @@ -0,0 +1,40 @@ +/*#include "CLoadingWindow.hpp" + +CLoadingWindow::CLoadingWindow(std::string title, std::string iconPath, std::string splashPath, unsigned int width, unsigned int height) : + CWindow(title, iconPath, width, height, false, false, SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALWAYS_ON_TOP), + m_splashPath(splashPath), + m_psurface(nullptr) { +} + +CLoadingWindow::~CLoadingWindow(void) { +} + +void CLoadingWindow::preinitialization(void) { +} + +void CLoadingWindow::postinitialization(void) { + m_psurface = SDL_GetWindowSurface(getWindow()); + + // Set the icon. + SDL_Surface* splash; + splash = IMG_Load(m_splashPath.c_str()); + if (splash != nullptr) { + SDL_Renderer* renderer = SDL_CreateRenderer(getWindow(), -1, SDL_RENDERER_ACCELERATED); + if (renderer == NULL) { + throw CLibException(std::string("Unable to create renderer: ") + SDL_GetError()); + } + + SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, splash); + if (tex == NULL) { + throw CLibException(std::string("Unable to create texture: ") + SDL_GetError()); + } + + SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0); + + SDL_FreeSurface(splash); + + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, tex, NULL, NULL); + SDL_RenderPresent(renderer); + } +}*/ \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.hpp new file mode 100644 index 0000000..957fc66 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CLoadingWindow.hpp @@ -0,0 +1,42 @@ +/*#ifndef CLOADINGWINDOW_HPP +#define CLOADINGWINDOW_HPP + +#include "CWindow.hpp" +#include "../../Controller/Exception/CLibException.hpp" +#include "../../Controller/Exception/CLogicException.hpp" + +#include +#include +#include +#include +#include +#include +#ifdef WIN32 + #include +#else + #include +#endif + +class CLoadingWindow : public CWindow { +private: + // The path to the splash image. + std::string m_splashPath; + + // The pointer to the surface. + SDL_Surface* m_psurface; + +public: + CLoadingWindow(void) = delete; + CLoadingWindow(const CLoadingWindow& param) = delete; + CLoadingWindow& operator=(const CLoadingWindow& param) = delete; + + CLoadingWindow(std::string title, std::string iconPath, std::string splashPath, unsigned int width, unsigned int height); + + ~CLoadingWindow(void); + + virtual void preinitialization(); + + virtual void postinitialization(); +}; + +#endif*/ \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.cpp new file mode 100644 index 0000000..faf644e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.cpp @@ -0,0 +1,187 @@ +#include "CWindow.hpp" +#include +#include +#include "../API/GraphicsAPI.hpp" +CWindow::CWindow(std::string title, std::string iconPath, unsigned int width, unsigned int height, bool resizable, bool fullscreen, SDL_WindowFlags sdlFlags) : + m_title(title), + m_iconPath(iconPath), + m_size(width, height), + m_fullscreen(fullscreen), + m_visible(false), + m_resizable(resizable), + m_sdlFlags(sdlFlags) { + m_pwindow = nullptr; +} + +CWindow::CWindow(std::string title, SDL_Window* window, SDL_WindowFlags sdlFlags): m_title(title), m_size(600,400), m_sdlFlags(sdlFlags), m_pwindow(window) +{ + +} + +CWindow::~CWindow(void) { + if (m_pwindow != nullptr) { + SDL_DestroyWindow(m_pwindow); + } +} + +SDL_Window* CWindow::getWindow(void) { + return m_pwindow; +} + +bool CWindow::isVisible(void) const { + return m_visible; +} + +void CWindow::setVisible(bool newVisible) { + m_visible = newVisible; + if (m_pwindow != nullptr) { + if (m_visible) { + SDL_ShowWindow(m_pwindow); + } + else { + SDL_HideWindow(m_pwindow); + } + } +} + +std::string CWindow::getTitle(void) const { + return m_title; +} + +void CWindow::setTitle(std::string newTitle) { + m_title = newTitle; + if (m_pwindow != nullptr) { + SDL_SetWindowTitle(m_pwindow, m_title.c_str()); + } +} + +std::string CWindow::getIconPath(void) const { + return m_iconPath; +} + +void CWindow::setIconPath(std::string newIconPath) { + m_iconPath = newIconPath; + if (m_pwindow != nullptr) { + SDL_Surface* image; + image = IMG_Load(m_iconPath.c_str()); + if (image != nullptr) { + SDL_SetWindowIcon(m_pwindow, image); + SDL_DestroySurface(image); + } + } +} + +unsigned int CWindow::getWidth(void) const { + return m_size.first; +} + +unsigned int CWindow::getHeight(void) const { + return m_size.second; +} + +std::pair CWindow::getSize(void) const { + return m_size; +} + +void CWindow::setSize(std::pair newSize) { + m_size = newSize; + if (m_pwindow != nullptr) { + SDL_SetWindowSize(m_pwindow, m_size.first, m_size.second); + } +} + +void CWindow::setSize(unsigned int newWidth, unsigned int newHeight) { + m_size.first = newWidth; + m_size.second = newHeight; + if (m_pwindow != nullptr) { + SDL_SetWindowSize(m_pwindow, m_size.first, m_size.second); + } +} + +bool CWindow::isResizable(void) const { + return m_resizable; +} + +void CWindow::setResizable(bool newResizable) { + m_resizable = newResizable; + if (m_pwindow != nullptr) { + if (m_resizable) { + SDL_SetWindowResizable(m_pwindow, true); + } + else { + SDL_SetWindowResizable(m_pwindow, true); + } + } +} + +bool CWindow::isFullscreen(void) const { + return m_fullscreen; +} + +void CWindow::setFullscreen(bool newFullscreen) { + m_fullscreen = newFullscreen; + if (m_pwindow != nullptr) { + // Set the fullscreen property. + if (m_fullscreen) { + SDL_SetWindowFullscreen(m_pwindow, SDL_WINDOW_FULLSCREEN); + } + else { + SDL_SetWindowFullscreen(m_pwindow, 0); + } + } +} + +bool CWindow::isInitialized(void) const { + return m_pwindow != nullptr; +} + +void CWindow::initialization(void) { + // Lancement de la preinitialisation. + preinitialization(); + + // Création de la fenetre. + m_pwindow = SDL_CreateWindow(m_title.c_str(), m_size.first, m_size.second, SDL_WINDOW_HIDDEN | m_sdlFlags); + + // Handle error. + if (m_pwindow == nullptr) { + //throw CLibException(std::string("Unable to create window: ") + SDL_GetError());//todo exceptions + } + + // Set the icon. + SDL_Surface* image; + image = IMG_Load(m_iconPath.c_str()); + if (image != nullptr) { + SDL_SetWindowIcon(m_pwindow, image); + SDL_DestroySurface(image); + } + + GraphicsAPI::getAPI()->init(m_pwindow); + + + // Set the rezisable property. + if (m_resizable) { + SDL_SetWindowResizable(m_pwindow, true); + } + else { + SDL_SetWindowResizable(m_pwindow, false); + } + + // Set the fullscreen property. + if (m_fullscreen) { + SDL_SetWindowFullscreen(m_pwindow, SDL_WINDOW_FULLSCREEN); + } + else { + SDL_SetWindowFullscreen(m_pwindow, 0); + } + + // Set the visible property. + if (m_visible) { + SDL_ShowWindow(m_pwindow); + } + else { + SDL_HideWindow(m_pwindow); + } + + // Lancement de la postinitialisation. + postinitialization(); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.hpp new file mode 100644 index 0000000..518be44 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Graphics/Window/CWindow.hpp @@ -0,0 +1,95 @@ +#ifndef CWINDOW_HPP +#define CWINDOW_HPP + +#include +#define SDL_MAIN_USE_CALLBACKS // This is necessary for the new callbacks API. To use the legacy API, don't define this. + +#include +#include +#include +#include +#include + +class CWindow { +private: + // The title of the window. + std::string m_title; + + // The path to the icon. + std::string m_iconPath; + + // First is the width, second is the height. + std::pair m_size; + + // Say if the window is fullscreen. + bool m_fullscreen; + + // Say if the window is visible. + bool m_visible; + + // Say if the window is resizable. + bool m_resizable; + + // SDL flags for creating the window. + SDL_WindowFlags m_sdlFlags; + + // The pointer to the window. + SDL_Window* m_pwindow; + +public: + CWindow(void) = delete; + CWindow(const CWindow& param) = delete; + CWindow& operator=(const CWindow& param) = delete; + + CWindow(std::string title, std::string iconPath, unsigned int width, unsigned int height, bool resizable, bool fullscreen, SDL_WindowFlags sdlFlags); + + CWindow(std::string title, SDL_Window* window, SDL_WindowFlags sdlFlags); + + + ~CWindow(void); + + + SDL_Window* getWindow(void); + + void setWindow(SDL_Window* window){m_pwindow = window; }; + + bool isFullscreen(void) const; + + void setFullscreen(bool newFullscreen); + + bool isVisible(void) const; + + void setVisible(bool newVisible); + + std::string getIconPath(void) const; + + std::string getTitle(void) const; + + void setTitle(std::string newTitle); + + void setIconPath(std::string newIconPath); + + unsigned int getWidth(void) const; + + unsigned int getHeight(void) const; + + std::pair getSize(void) const; + + void setSize(std::pair newSize); + + void setSize(unsigned int newWidth, unsigned int newHeight); + + bool isResizable(void) const; + + void setResizable(bool newResizable); + + bool isInitialized(void) const; + + void initialization(); + + virtual void preinitialization() = 0; + + virtual void postinitialization() = 0; +}; + +#endif diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.cpp new file mode 100644 index 0000000..fbc4044 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.cpp @@ -0,0 +1,18 @@ +#include "CInputAPI.hpp" + +namespace CosmicCore { + + std::unordered_map CInputAPI::m_nameToId = {}; + std::unordered_map CInputAPI::m_idToName = {}; + InputAction CInputAPI::m_nextId = 0; + + InputAction CInputAPI::registerAction(const std::string& name) { + auto it = m_nameToId.find(name); + if (it != m_nameToId.end()) return it->second; + + InputAction id = m_nextId++; + m_nameToId[name] = id; + m_idToName[id] = name; + return id; + } +} diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.hpp new file mode 100644 index 0000000..efed153 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/API/CInputAPI.hpp @@ -0,0 +1,39 @@ +#ifndef CINPUTAPI_HPP +#define CINPUTAPI_HPP + + +#include +#include +#include +#include +#include +namespace CosmicCore { + + using InputAction = uint32_t; + + class CScene; + + class CInputAPI + { + private: + static std::unordered_map m_nameToId; + static std::unordered_map m_idToName; + static InputAction m_nextId; + + public: + static InputAction registerAction(const std::string& name); + + static std::optional getAction(const std::string& name) { + return (m_nameToId.find(name) != m_nameToId.end() ? std::optional(m_nameToId[name]) : std::nullopt);}; + + }; + + + + // macro helper + #define REGISTER_ACTION(name) \ + namespace EAction { \ + inline const InputAction name = CInputAPI::registerAction(#name);\ + } +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputBinding.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputBinding.hpp new file mode 100644 index 0000000..5b2745e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputBinding.hpp @@ -0,0 +1,39 @@ +#ifndef CINPUTBINDING_HPP +#define CINPUTBINDING_HPP + +#include + +namespace CosmicCore { + enum class EInputDevice { + Keyboard, + Mouse, + GamepadButton, + GamepadAxis + }; + + struct CInputBinding + { + EInputDevice device = EInputDevice::Keyboard; + + SDL_Keycode key = SDLK_UNKNOWN; // keyboard + uint8_t button = 0; // mouse button / gamepad button + uint8_t axis = 0; // gamepad axis + float scale = 1.0f; // pour inverser ou pondérer + + // constructeurs helpers + static CInputBinding fromKey(SDL_Keycode key, float scale = 1.0f) { + return {EInputDevice::Keyboard, key, 0, 0, scale}; + } + static CInputBinding fromMouseButton(uint8_t button, float scale = 1.0f) { + return {EInputDevice::Mouse, SDLK_UNKNOWN, button, 0, scale}; + } + static CInputBinding fromGamepadAxis(uint8_t axis, float scale = 1.0f) { + return {EInputDevice::GamepadAxis, SDLK_UNKNOWN, 0, axis, scale}; + } + static CInputBinding fromGamepadButton(uint8_t button, float scale = 1.0f) { + return {EInputDevice::GamepadButton, SDLK_UNKNOWN, button, 0, scale}; + } + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.cpp new file mode 100644 index 0000000..4ae22e3 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.cpp @@ -0,0 +1,130 @@ +#include "CInputDispatcher.hpp" +#include "Engine/Core/Scene/CScene.hpp" +#include "Engine/Core/Component/Input/CInputManager.hpp" +#include "Engine/Core/Systems/Input/API/CInputAPI.hpp" +#include +#include +#include +namespace CosmicCore { + + glm::vec2 CInputDispatcher::global_mouse_position = {0,0}; + + CInputDispatcher::~CInputDispatcher() + { + + } + + void CInputDispatcher::dispatch(CScene* scene) { + auto& registry = scene->getECManager().registry; + auto view = registry.view(); + + for (auto entity : view) { + auto& input = registry.get(entity); + input.dispatch(*this); + } + + // reset souris relative après dispatch + m_mouseRelative = {0, 0}; + genericLeftMouseButtonJustClicked = false; + genericLeftMouseButtonJustReleased = false; + genericRightMouseButtonJustClicked = false; + genericRightMouseButtonJustReleased = false; + } + + void CInputDispatcher::processEvent(const SDL_Event& event) + { + m_justPressed.clear(); + m_justReleased.clear(); + + switch (event.type) { + case SDL_EVENT_KEY_DOWN: { + auto action = m_mapping.findAction(event.key.key); + if (action) { + if (!m_activeActions.count(*action)) + m_justPressed.insert(*action); + m_activeActions.insert(*action); + } + break; + } + case SDL_EVENT_KEY_UP: { + auto action = m_mapping.findAction(event.key.key); + if (action) { + m_activeActions.erase(*action); + m_justReleased.insert(*action); + } + break; + } + + case SDL_EVENT_MOUSE_BUTTON_DOWN: { + switch (event.button.button) { + case SDL_BUTTON_LEFT: genericLeftMouseButtonJustClicked = true; genericLeftMouseButtonJustReleased = false; break; + case SDL_BUTTON_RIGHT: genericRightMouseButtonJustClicked = true; genericRightMouseButtonJustReleased = false; break; + default: break; + } + break; + } + + case SDL_EVENT_MOUSE_BUTTON_UP: { + switch (event.button.button) { + case SDL_BUTTON_LEFT: genericLeftMouseButtonJustReleased = true; genericLeftMouseButtonJustClicked = false; break; + case SDL_BUTTON_RIGHT: genericRightMouseButtonJustReleased = true; genericRightMouseButtonJustClicked = false; break; + default: break; + } + break; + } + + case SDL_EVENT_MOUSE_MOTION: { + m_mouseRelative = {event.motion.xrel, event.motion.yrel}; + global_mouse_position = {event.motion.x, event.motion.y}; + break; + } + } + } + + void CInputDispatcher::loadActions(const std::string& path) { + std::ifstream file(path); + nlohmann::json j = nlohmann::json::parse(file); + + for (auto& name : j["actions"]) + CInputAPI::registerAction(name.get()); + } + + void CInputDispatcher::loadBindings(const std::string& path) { + std::ifstream file(path); + nlohmann::json j = nlohmann::json::parse(file); + + m_mapping.clearAll(); + + for (auto& binding : j["bindings"]) { + std::string actionName = binding["action"]; + auto action = CInputAPI::getAction(actionName); + if (!action) { + continue; + } + + std::string device = binding["device"]; + if (device == "keyboard") { + SDL_Keycode key = SDL_GetKeyFromName( + binding["key"].get().c_str() + ); + m_mapping.bind(*action, CInputBinding::fromKey(key)); + } + else if (device == "mouse") { + m_mapping.bind(*action, + CInputBinding::fromMouseButton(binding["button"])); + } + else if (device == "gamepad_button") { + m_mapping.bind(*action, + CInputBinding::fromGamepadButton(binding["button"])); + } + else if (device == "gamepad_axis") { + float scale = binding.value("scale", 1.0f); + m_mapping.bind(*action, + CInputBinding::fromGamepadAxis(binding["axis"], scale)); + } + } + + if (j.contains("mouse_sensitivity")) + m_mapping.setMouseSensitivity(j["mouse_sensitivity"]); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.hpp new file mode 100644 index 0000000..2dc17da --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputDispatcher.hpp @@ -0,0 +1,61 @@ +#ifndef CINPUTWORLD_HPP +#define CINPUTWORLD_HPP + +#include "API/CInputAPI.hpp" +#include "CInputMapping.hpp" +#include "Engine/Core/Scene/CScene.hpp" +#include "glm/ext/vector_float2.hpp" +#include +#include + +namespace CosmicCore { + + class CInputDispatcher{ + + private: + static glm::vec2 global_mouse_position; + std::unordered_set m_activeActions; + std::unordered_set m_justPressed; + std::unordered_set m_justReleased; + glm::vec2 m_mouseRelative; + glm::vec2& m_mousePosition = global_mouse_position; + CInputMapping m_mapping; + //Todo left and right click ? + bool genericLeftMouseButtonJustClicked = false; + bool genericLeftMouseButtonJustReleased = false; + + bool genericRightMouseButtonJustClicked = false; + bool genericRightMouseButtonJustReleased = false; + + public: + CInputDispatcher() {} + ~CInputDispatcher(); + + void dispatch(CScene* scene); + + void processEvent(const SDL_Event& event); + + bool isLeftMouseButtonJustClicked() const {return genericLeftMouseButtonJustClicked;}; + bool isLeftMouseButtonJustReleased() const {return genericLeftMouseButtonJustReleased;}; + bool isRightMouseButtonJustClicked() const {return genericRightMouseButtonJustClicked;}; + bool isRightMouseButtonJustReleased() const {return genericRightMouseButtonJustReleased;}; + + glm::vec2 getMouseRelative() const { return m_mouseRelative; } + glm::vec2 getMousePosition() const { return m_mousePosition; } + static glm::vec2 mousePosition() { return global_mouse_position;} + float getSensitivity() const { return m_mapping.getMouseSensitivity(); } + + bool isActive(InputAction action) const { return m_activeActions.count(action); } + bool isJustPressed(InputAction action) const { return m_justPressed.count(action); } + bool isJustReleased(InputAction action)const { return m_justReleased.count(action); } + + + void loadActions(const std::string& path); + void loadBindings(const std::string& path); + + CInputMapping& getMapping() { return m_mapping; } + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.cpp new file mode 100644 index 0000000..438711c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.cpp @@ -0,0 +1,49 @@ +#include "CInputMapping.hpp" + +namespace CosmicCore { + // ajoute un binding à une action + void CInputMapping::bind(InputAction action, CInputBinding binding) + { + m_bindings[action].push_back(binding); + } + + // remplace tous les bindings d'une action + void CInputMapping::rebind(InputAction action, CInputBinding binding) + { + m_bindings[action] = {binding}; + } + + // ajoute un binding supplémentaire + void CInputMapping::addBinding(InputAction action, CInputBinding binding) + { + m_bindings[action].push_back(binding); + } + + // supprime tous les bindings d'une action + void CInputMapping::clearBindings(InputAction action) + { + m_bindings[action].clear(); + } + + // retourne les bindings d'une action + const std::vector& CInputMapping::getBindings(InputAction action) + { + static std::vector empty; + auto it = m_bindings.find(action); + return it != m_bindings.end() ? it->second : empty; + } + + // trouve l'action correspondant à une touche + std::optional CInputMapping::findAction(SDL_Keycode key) + { + for (auto& [action, bindings] : m_bindings) + { + for (auto& binding : bindings) + { + if (binding.device == EInputDevice::Keyboard && binding.key == key) + return action; + } + } + return std::nullopt; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.hpp new file mode 100644 index 0000000..3968045 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Input/CInputMapping.hpp @@ -0,0 +1,45 @@ +#ifndef CINPUTMAPPING_HPP +#define CINPUTMAPPING_HPP + +#include "API/CInputAPI.hpp" +#include "CInputBinding.hpp" +#include +#include + +namespace CosmicCore { + class CInputMapping { + // une action peut avoir plusieurs bindings + std::unordered_map> m_bindings; + + float m_mouseSensitivity = 0.1f; + + public: + CInputMapping() {} + + // ajoute un binding à une action + void bind(InputAction action, CInputBinding binding); + + // remplace tous les bindings d'une action + void rebind(InputAction action, CInputBinding binding); + + // ajoute un binding supplémentaire + void addBinding(InputAction action, CInputBinding binding); + + // supprime tous les bindings d'une action + void clearBindings(InputAction action); + + // retourne les bindings d'une action + const std::vector& getBindings(InputAction action); + + // trouve l'action correspondant à une touche + std::optional findAction(SDL_Keycode key); + + float getMouseSensitivity() const { return m_mouseSensitivity; } + void setMouseSensitivity(float s){ m_mouseSensitivity = s; } + + void clearAll(){return m_bindings.clear();} + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.cpp new file mode 100644 index 0000000..cd73ce5 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.cpp @@ -0,0 +1,26 @@ +#include "CPhysicsAPI.hpp" + +#include "Jolt/Jolt.h" +#include +#include + +namespace CosmicCore { + CPhysicsAPI::~CPhysicsAPI() + { + + } + void CPhysicsAPI::init() + { + JPH::RegisterDefaultAllocator(); + JPH::Factory::sInstance = new JPH::Factory(); + JPH::RegisterTypes(); + } + + void CPhysicsAPI::cleanup() + { + JPH::UnregisterTypes(); + // Destroy the factory + delete JPH::Factory::sInstance; + JPH::Factory::sInstance = nullptr; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.hpp new file mode 100644 index 0000000..c62ba1f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Physics/API/CPhysicsAPI.hpp @@ -0,0 +1,27 @@ +#ifndef CPHYSICSAPI_HPP +#define CPHYSICSAPI_HPP + +namespace CosmicCore { + + class CScene; + /** + * @brief Class representing any physical world - abstract. + */ + class CPhysicsAPI { + + private: + CScene* m_scene; + public: + CPhysicsAPI(CScene* scene): m_scene(scene){}; + virtual ~CPhysicsAPI(); + + virtual void updateWorld(float delta) = 0; + + virtual void initWorld() = 0; + virtual void destroy() = 0; + static void init(); + static void cleanup(); + CScene* getScene(){return m_scene;}; + }; +} +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.cpp new file mode 100644 index 0000000..8f00de1 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.cpp @@ -0,0 +1,61 @@ +#include "CTangibleWorld.hpp" +#include +#include +#include "Jolt/Core/Memory.h" +#include "Jolt/RegisterTypes.h" +#include +#include "Engine/Core/Scene/CScene.hpp" +#include "Engine/Core/Component/Rigidbody/CRigidBody.hpp" +namespace CosmicCore { + + CTangibleWorld::~CTangibleWorld() + { + + } + /*static void JoltTraceImpl(const char* inFMT, ...) { + va_list list; + va_start(list, inFMT); + char buffer[1024]; + vsnprintf(buffer, sizeof(buffer), inFMT, list); + va_end(list); + std::cout << "[JOLT] " << buffer << std::endl; + }*/ + void CTangibleWorld::initWorld() + { + JPH::RegisterDefaultAllocator(); + //JPH::Trace = JoltTraceImpl; + JPH::Factory::sInstance = new JPH::Factory(); + JPH::RegisterTypes(); + m_tempAllocator = std::make_unique(10 * 1024 * 1024); + m_jobSystem = std::make_unique(JPH::cMaxPhysicsJobs, JPH::cMaxPhysicsBarriers, JPH::thread::hardware_concurrency() - 1); + m_physicsSystem.Init(cMaxBodies, cNumBodyMutexes, cMaxBodyPairs, cMaxContactConstraints, m_broadPhaseLayer, m_objectVsBroadPhase, m_objectLayerPairFilter); + m_physicsSystem.SetGravity( {0.0, -9.81, 0.0}); + } + + void CTangibleWorld::updateWorld(float deltaTime){ + m_physicsSystem.Update(deltaTime, 1, m_tempAllocator.get(), m_jobSystem.get()); + auto& registry = getScene()->getECManager(); // accès via scene + auto view = registry.registry.view(); + for (auto entity : view) { + auto& rb = registry.registry.get(entity); + + // ne sync que les bodies dynamiques et kinématiques + if (rb.getBodyType() == EBodyType::Static) continue; + + registry.registry.get(entity).syncTransform(); + } + } + + void CTangibleWorld::destroy(){ + + getScene()->getECManager().registry.view().each([](CRigidBody& rb) { + rb.destroy(); + }); + + //JPH::UnregisterTypes(); + // Destroy the factory + //delete JPH::Factory::sInstance; + //JPH::Factory::sInstance = nullptr; + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.hpp new file mode 100644 index 0000000..8bc1a02 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Physics/CTangibleWorld.hpp @@ -0,0 +1,128 @@ +#ifndef CTANGIBLEWORLD_HPP +#define CTANGIBLEWORLD_HPP +#include "API/CPhysicsAPI.hpp" +#include "PhysicsLayers.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace CosmicCore { + +// BroadPhaseLayerInterface implementation +// This defines a mapping between object and broadphase layers. +class BPLayerInterfaceImpl final : public JPH::BroadPhaseLayerInterface +{ + public: + BPLayerInterfaceImpl() + { + // Create a mapping table from object to broad phase layer + mObjectToBroadPhase[Layers::NON_MOVING] = BroadPhaseLayers::NON_MOVING; + mObjectToBroadPhase[Layers::MOVING] = BroadPhaseLayers::MOVING; + } + + uint GetNumBroadPhaseLayers() const override + { + return BroadPhaseLayers::NUM_LAYERS; + } + + JPH::BroadPhaseLayer GetBroadPhaseLayer(JPH::ObjectLayer inLayer) const override + { + JPH_ASSERT(inLayer < Layers::NUM_LAYERS); + return mObjectToBroadPhase[inLayer]; + } + + #if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED) + const char* GetBroadPhaseLayerName(JPH::BroadPhaseLayer inLayer) const override { + switch ((JPH::BroadPhaseLayer::Type)inLayer) { + case (JPH::BroadPhaseLayer::Type)BroadPhaseLayers::NON_MOVING: return "NON_MOVING"; + case (JPH::BroadPhaseLayer::Type)BroadPhaseLayers::MOVING: return "MOVING"; + default: return "UNKNOWN"; + } + } + #endif + + private: + JPH::BroadPhaseLayer mObjectToBroadPhase[Layers::NUM_LAYERS]; +}; + +/// Class that determines if an object layer can collide with a broadphase layer +class ObjectVsBroadPhaseLayerFilterImpl : public JPH::ObjectVsBroadPhaseLayerFilter +{ +public: + virtual bool ShouldCollide(JPH::ObjectLayer inLayer1, JPH::BroadPhaseLayer inLayer2) const override + { + switch (inLayer1) + { + case Layers::NON_MOVING: + return inLayer2 == BroadPhaseLayers::MOVING; + case Layers::MOVING: + return true; + default: + JPH_ASSERT(false); + return false; + } + } +}; + + +/// Class that determines if two object layers can collide +class ObjectLayerPairFilterImpl : public JPH::ObjectLayerPairFilter +{ +public: + virtual bool ShouldCollide(JPH::ObjectLayer inObject1, JPH::ObjectLayer inObject2) const override + { + switch (inObject1) + { + case Layers::NON_MOVING: + return inObject2 == Layers::MOVING; // Non moving only collides with moving + case Layers::MOVING: + return true; // Moving collides with everything + default: + JPH_ASSERT(false); + return false; + } + } +}; + + class CTangibleWorld : public CPhysicsAPI{ + + JPH::PhysicsSystem m_physicsSystem; + std::unique_ptr m_tempAllocator; + std::unique_ptr m_jobSystem; + + const uint cMaxBodies = 65536; + const uint cNumBodyMutexes = 0; + const uint cMaxBodyPairs = 65536; + const uint cMaxContactConstraints = 10240; + + BPLayerInterfaceImpl m_broadPhaseLayer; + ObjectVsBroadPhaseLayerFilterImpl m_objectVsBroadPhase; + ObjectLayerPairFilterImpl m_objectLayerPairFilter; + + public: + CTangibleWorld(CScene* scene): CPhysicsAPI(scene), m_physicsSystem(), m_broadPhaseLayer(){}; + ~CTangibleWorld(); + CTangibleWorld() = delete; + CTangibleWorld(CTangibleWorld&&) = delete; + CTangibleWorld& operator=(CTangibleWorld&&) = delete; + CTangibleWorld(const CTangibleWorld&) = delete; + CTangibleWorld& operator=(const CTangibleWorld&) = delete; + + void initWorld(); + void updateWorld(float deltaTime); + void destroy(); + + JPH::PhysicsSystem& getPhysicsSystem() { return m_physicsSystem; } + JPH::BodyInterface& getBodyInterface() { + return m_physicsSystem.GetBodyInterface(); + } + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Physics/PhysicsLayers.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Physics/PhysicsLayers.hpp new file mode 100644 index 0000000..c33d85b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Physics/PhysicsLayers.hpp @@ -0,0 +1,29 @@ +#ifndef PHYSICSLAYERS_HPP +#define PHYSICSLAYERS_HPP + +#include +#include +#include +namespace CosmicCore { + + // Layer that objects can be in, determines which other objects it can collide with + // Typically you at least want to have 1 layer for moving bodies and 1 layer for static bodies, but you can have more + // layers if you want. E.g. you could have a layer for high detail collision (which is not used by the physics simulation + // but only if you do collision testing). + namespace Layers + { + static constexpr JPH::ObjectLayer NON_MOVING = 0; + static constexpr JPH::ObjectLayer MOVING = 1; + static constexpr JPH::ObjectLayer NUM_LAYERS = 2; + }; + + namespace BroadPhaseLayers + { + static constexpr JPH::BroadPhaseLayer NON_MOVING(0); + static constexpr JPH::BroadPhaseLayer MOVING(1); + static constexpr unsigned int NUM_LAYERS(2); + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.cpp new file mode 100644 index 0000000..6a3d2e1 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.cpp @@ -0,0 +1,3 @@ +#include "CResourceAPI.hpp" + +CResourceManager CResourceAPI::resourceManager; \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.hpp new file mode 100644 index 0000000..90c6aa0 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/API/CResourceAPI.hpp @@ -0,0 +1,13 @@ +#ifndef RESOURCEAPI_HPP +#define RESOURCEAPI_HPP + +#include "../CResourceManager.hpp" + +class CResourceAPI{ + static CResourceManager resourceManager; + public: + static CResourceManager& resources(){return resourceManager;}; + +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.cpp new file mode 100644 index 0000000..a4d3c10 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.cpp @@ -0,0 +1,104 @@ +#include "CAudioManager.hpp" +#include +#include +#include +#define DR_WAV_IMPLEMENTATION +#include "dr_wav.h" +#define DR_MP3_IMPLEMENTATION +#include "dr_mp3.h" +#define DR_FLAC_IMPLEMENTATION +#include "dr_flac.h" +CAudioClip* CAudioManager::loadClip(const std::string& path) +{ + auto cached = get(path); + if (cached) return cached.value(); + + auto clip = std::make_unique(); + clip->path = path; + + // Détection du format par l'extension + std::string ext = path.substr(path.find_last_of(".") + 1); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + + void* pcmData = nullptr; + unsigned int channels = 0; + unsigned int sampleRate = 0; + drwav_uint64 totalFrames = 0; + ALenum format = AL_FORMAT_MONO16; + int type = -1; + + if (ext == "wav") { + // Décodage WAV en 16-bit PCM + pcmData = drwav_open_file_and_read_pcm_frames_s16( + path.c_str(), &channels, &sampleRate, &totalFrames, NULL + ); + type = 0; + } + //TODO MP3 + /*else if (ext == "mp3") { + // Décodage MP3 en 16-bit PCM + pcmData = drmp3_open_file_and_read_pcm_frames_s16( + path.c_str(), &channels, &sampleRate, &totalFrames, NULL + ); + type = 1; + }*/ + else if (ext == "flac") { + pcmData = drflac_open_file_and_read_pcm_frames_s16( + path.c_str(), &channels, &sampleRate, &totalFrames, NULL + ); + type = 2; + } + else { + return nullptr; // Format non supporté + } + + if (pcmData) { + // Déterminer le format OpenAL + int16_t* finalData = static_cast(pcmData); + uint64_t finalFrames = totalFrames; + std::vector monoBuffer; // pour garder les données en vie + + // conversion stéréo → mono obligatoire pour la spatialisation + if (channels == 2) { + monoBuffer.resize(totalFrames); + int16_t* src = static_cast(pcmData); + for (uint64_t i = 0; i < totalFrames; i++) { + int32_t left = src[i * 2]; + int32_t right = src[i * 2 + 1]; + monoBuffer[i] = static_cast((left + right) / 2); + } + finalData = monoBuffer.data(); + finalFrames = totalFrames; + format = AL_FORMAT_MONO16; + } else if (channels == 1) { + format = AL_FORMAT_MONO16; + } else { + // > 2 canaux non supporté + switch(type) { + case 0: drwav_free(pcmData, NULL); break; + case 2: drflac_free(pcmData, NULL); break; + default: break; + } + return nullptr; + } + + // Créer le buffer OpenAL + alGenBuffers(1, &clip->buffer); + + ALsizei size = static_cast(finalFrames * sizeof(int16_t)); + alBufferData(clip->buffer, format, finalData, size, static_cast(sampleRate)); + + // Calculer la durée + clip->duration = static_cast(totalFrames) / static_cast(sampleRate); + + // Libérer les données PCM (OpenAL a sa propre copie) + switch(type) { + case 0: drwav_free(pcmData, NULL); break; + case 2: drflac_free(pcmData, NULL); break; + default: break; + } + + return add(path, std::move(clip)); + } + return nullptr; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.hpp new file mode 100644 index 0000000..81b0f62 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Audio/CAudioManager.hpp @@ -0,0 +1,11 @@ +#ifndef CAUDIOMANAGER_HPP +#define CAUDIOMANAGER_HPP +#include "../../Audio/Sound/CAudioClip.hpp" +#include "../CAbstractResourceManager.hpp" +class CAudioManager : public CAbstractResourceManager{ + public: + + CAudioClip* loadClip(const std::string& path); +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/CAbstractResourceManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/CAbstractResourceManager.hpp new file mode 100644 index 0000000..e9fd222 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/CAbstractResourceManager.hpp @@ -0,0 +1,71 @@ +#ifndef CABSTRACTRESOURCEMANAGERBASE_HPP +#define CABSTRACTRESOURCEMANAGERBASE_HPP + +#include +#include +#include +#include +#include + +template +class CAbstractResourceManager { +protected: + std::list> m_resources; + std::unordered_map m_map; + +public: + // ajout + T* add(const std::string& key, std::unique_ptr&& resource) { + auto* ptr = resource.get(); + m_resources.push_back(std::move(resource)); + m_map[key] = ptr; + return ptr; + } + + // ajout sans clé (généré automatiquement) + /*T* add(std::unique_ptr&& resource) { + auto key = "_auto_" + std::to_string(m_resources.size()); + return add(key, std::move(resource)); + }*/ + + // get par clé + std::optional get(const std::string& key) const { + auto it = m_map.find(key); + if (it != m_map.end()) return it->second; + return std::nullopt; + } + + // get ou créer + template + T* getOrCreate(const std::string& key, Args&&... args) { + auto cached = get(key); + if (cached) return cached.value(); + return add(key, std::make_unique(std::forward(args)...)); + } + + // contient + bool contains(const std::string& key) const { + return m_map.find(key) != m_map.end(); + } + + // remove + void remove(const std::string& key) { + auto it = m_map.find(key); + if (it == m_map.end()) return; + + T* ptr = it->second; + m_map.erase(it); + m_resources.remove_if([ptr](const auto& r) { return r.get() == ptr; }); + } + + // itération + auto begin() { return m_resources.begin(); } + auto end() { return m_resources.end(); } + auto begin() const { return m_resources.begin(); } + auto end() const { return m_resources.end(); } + + size_t size() const { return m_resources.size(); } + + void clear() { m_resources.clear(); m_map.clear(); } +}; +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/CResourceManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/CResourceManager.hpp new file mode 100644 index 0000000..37b01c4 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/CResourceManager.hpp @@ -0,0 +1,61 @@ +#ifndef CRESOURCEMANAGER_HPP +#define CRESOURCEMANAGER_HPP + +#include "Model/CModelManager.hpp" +#include "Mesh/CMeshManager.hpp" +#include "Material/CMaterialManager.hpp" +#include "Audio/CAudioManager.hpp" +#include "Shader/CShadersManager.hpp" +#include "Texture/CTextureManager.hpp" +#include "Font/CFontManager.hpp" + +class CResourceManager{ + private: + CModelManager m_modelManager; + CMeshManager m_meshManager; + CMaterialManager m_materialManager; + CTextureManager m_textureManager; + CAudioManager m_audioManager; + CShadersManager m_shaderManager; + CFontManager m_fontManager; + CModel2DManager m_model2DManager; + CMaterial2DManager m_material2DManager; + CMesh2DManager m_mesh2DManager; + public: + CModelManager& models() { return m_modelManager; } + CMeshManager& meshes() { return m_meshManager; } + CMaterialManager& materials() { return m_materialManager; } + CTextureManager& textures() { return m_textureManager; } + CAudioManager& sounds() { return m_audioManager; } + CShadersManager& shaders() { return m_shaderManager; } + CFontManager& fonts() { return m_fontManager; } + CModel2DManager& models2D() {return m_model2DManager;} + CMaterial2DManager& materials2D() {return m_material2DManager;} + CMesh2DManager& meshes2D() { return m_mesh2DManager; } + + const CModelManager& models() const { return m_modelManager; } + const CMeshManager& meshes() const { return m_meshManager; } + const CMaterialManager& materials() const { return m_materialManager; } + const CTextureManager& textures() const { return m_textureManager; } + const CAudioManager& sounds() const { return m_audioManager; } + const CShadersManager& shaders() const { return m_shaderManager; } + const CFontManager& fonts() const { return m_fontManager; } + const CModel2DManager& models2D() const {return m_model2DManager;} + const CMaterial2DManager& materials2D() const {return m_material2DManager;} + const CMesh2DManager& meshes2D() const { return m_mesh2DManager; } + + void cleanup() { + m_modelManager.clear(); + m_materialManager.clear(); + m_meshManager.clear(); + m_textureManager.clear(); + m_audioManager.clear(); + m_fontManager.clear(); + m_model2DManager.clear(); + m_material2DManager.clear(); + m_mesh2DManager.clear(); + m_shaderManager.clear(); + } +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Font/CFontManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Font/CFontManager.hpp new file mode 100644 index 0000000..575cef8 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Font/CFontManager.hpp @@ -0,0 +1,48 @@ +#ifndef CFONTMANAGER_HPP +#define CFONTMANAGER_HPP + +#include "../../Graphics/Data/Font/CFont.hpp" + +#include "../CAbstractResourceManager.hpp" +#include +#include +#include + +class CFontManager : public CAbstractResourceManager +{ + public: + + CosmicCore::CFont* loadFont(const std::string& path) { + auto cached = get(path); + if (cached) return cached.value(); + std::optional jsonPath = std::nullopt; + std::optional pngPath = std::nullopt; + + for (const auto& entry : std::filesystem::directory_iterator(path)) + { + if(entry.is_regular_file()) + { + // Converting the path to const char * in the + // subsequent lines + std::filesystem::path extension = entry.path().extension(); + if(extension == ".json") + { + jsonPath = entry.path().string(); + } + else if(extension == ".png") + { + pngPath = entry.path().string(); + } + } + } + if(!jsonPath || !pngPath) + { + throw std::runtime_error("Font is not a valid folder. Must contain a json and a png"); + } + auto font = std::make_unique(); + font->init(*jsonPath, *pngPath); + return add(path, std::move(font)); + } +}; + + #endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Material/CMaterialManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Material/CMaterialManager.hpp new file mode 100644 index 0000000..2bdeb4f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Material/CMaterialManager.hpp @@ -0,0 +1,97 @@ +#ifndef CMATERIALMANAGER_HPP +#define CMATERIALMANAGER_HPP + +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial.hpp" +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp" + +#include "Engine/Core/Systems/Resources/CAbstractResourceManager.hpp" +#include "Engine/Core/Systems/Graphics/Data/Texture/CTexture.hpp" + +class CMaterialManager : public CAbstractResourceManager +{ + public: + CMaterial* createMaterial(const std::string& key, + CShaderImplVulkan* shader, + CTexture* albedo = nullptr, + CTexture* normal = nullptr) + { + auto mat = std::make_unique(); + mat->shader = shader; + mat->textureAlbedo = albedo; + mat->textureNormal = normal; + mat->build(); + return add(key, std::move(mat)); + } +}; +using namespace CosmicCore; +class CMaterial2DManager : public CAbstractResourceManager +{ + public: + /*CMaterial2D* createRectMaterial(const std::string& key, + glm::vec4 color, + CShaderImplVulkan* shader) + { + auto mat = std::make_unique(); + mat->m_shapeType = E2DShapeType::Rect; + mat->shader = shader; + mat->m_color = color; + mat->build(); + return add(key, std::move(mat)); + } + + CMaterial2D* createCircleMaterial(const std::string& key, + glm::vec4 color, + CShaderImplVulkan* shader) + { + auto mat = std::make_unique(); + mat->m_shapeType = E2DShapeType::Circle; + mat->shader = shader; + mat->m_color = color; + mat->build(); + return add(key, std::move(mat)); + } + + CMaterial2D* createRoundedRectMaterial(const std::string& key, + glm::vec4 color, + float radius, + CShaderImplVulkan* shader) + { + auto mat = std::make_unique(); + mat->m_shapeType = E2DShapeType::RoundedRect; + mat->shader = shader; + mat->m_color = color; + mat->m_cornerRadius = radius; + mat->build(); + return add(key, std::move(mat)); + } + + CMaterial2D* createTextureMaterial(const std::string& key, + glm::vec4 color, + CTexture* texture, + CShaderImplVulkan* shader) + { + auto mat = std::make_unique(); + mat->m_shapeType = E2DShapeType::Rect; + mat->shader = shader; + mat->m_color = color; + mat->m_texture = texture; + mat->build(); + return add(key, std::move(mat)); + } + + CMaterial2D* createText(const std::string& key, + glm::vec4 color, + CFont* font, + CShaderImplVulkan* shader) + { + auto mat = std::make_unique(); + mat->m_shapeType = E2DShapeType::Rect; + mat->shader = shader; + mat->m_color = color; + mat->m_font = font; + mat->build(); + return add(key, std::move(mat)); + }*/ +}; + + #endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Mesh/CMeshManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Mesh/CMeshManager.hpp new file mode 100644 index 0000000..2971274 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Mesh/CMeshManager.hpp @@ -0,0 +1,17 @@ +#ifndef CMESHMANAGER_HPP +#define CMESHMANAGER_HPP + +#include "../../Graphics/Data/Mesh/CMesh.hpp" +#include "../../Graphics/Data/Mesh/CMesh2D.hpp" + +#include "../CAbstractResourceManager.hpp" + +class CMeshManager : public CAbstractResourceManager +{ +}; + +class CMesh2DManager : public CAbstractResourceManager +{ +}; + + #endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Model/CModelManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Model/CModelManager.hpp new file mode 100644 index 0000000..6c55400 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Model/CModelManager.hpp @@ -0,0 +1,17 @@ +#ifndef CMODELMANAGER_HPP +#define CMODELMANAGER_HPP + +#include "../../Graphics/Data//Model/CModel.hpp" +#include "../../Graphics/Data//Model/CModel2D.hpp" + +#include "../CAbstractResourceManager.hpp" + +class CModelManager : public CAbstractResourceManager +{ +}; + +class CModel2DManager : public CAbstractResourceManager +{ +}; + + #endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.cpp new file mode 100644 index 0000000..5c48202 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.cpp @@ -0,0 +1,51 @@ +#include "CShadersManager.hpp" +#include +#include +#include +#include +#include +#include "../../../../Utils/Factory/CShaderFactory.hpp" + +CShader* CShadersManager::get(std::string name) const { + std::unordered_map::const_iterator it = m_map.find(name); + if (it == m_map.end()) { + return nullptr; + } + else { + return it.operator*().second; + } +} + +void CShadersManager::create(void) { + + const char* pathBaseExe = SDL_GetBasePath(); + std::filesystem::path shaderDir = (pathBaseExe ? std::filesystem::path(pathBaseExe) : std::filesystem::path(".")) / SHADERS_FOLDER; + if (std::filesystem::is_directory(shaderDir)) { + for (std::filesystem::directory_iterator itr(shaderDir); itr != std::filesystem::directory_iterator(); ++itr) { + if (std::filesystem::is_regular_file(itr->status())) { + + std::ifstream jsonfm(itr->path().string()); + try { + + auto shader = CosmicUtils::CShaderFactory::create(itr->path().stem(), itr->path()); + m_resources.push_back(std::move(shader)); + m_map.insert(std::make_pair(itr->path().stem(), m_resources.back().get())); + } + catch (std::exception& e) { + //throw CJsonException(std::string("Failed to parse and retrieve data from the json file ") + itr->path().string() + ": " + e.what()); + } + } + } + } + else { + //throw CFileException(std::string("Failed to find the shaders folder : ") + CKernel::m_kernel->getEngineConfig()->getGlobalShadersPath().string()); + } +} + +void CShadersManager::compile(void) { + + for (auto& el: m_resources) + { + el->init(); + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.hpp new file mode 100644 index 0000000..229ec5b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Shader/CShadersManager.hpp @@ -0,0 +1,27 @@ +#ifndef CSHADERSMANAGER_HPP +#define CSHADERSMANAGER_HPP + +#include +#include + +#include + +#include "../../Graphics/Shader/CShader.hpp" +#include "../CAbstractResourceManager.hpp" + +#define SHADERS_FOLDER "assets/shaders/slang/spv" + + +class CShadersManager : public CAbstractResourceManager{ +public: + CShader* get(std::string name) const; + + std::list>::const_iterator beginShaders(){return m_resources.cbegin();}; + std::list>::const_iterator endShaders(){return m_resources.cend();}; + + void compile(void); + + void create(void); +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Resources/Texture/CTextureManager.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Texture/CTextureManager.hpp new file mode 100644 index 0000000..71bf754 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Resources/Texture/CTextureManager.hpp @@ -0,0 +1,21 @@ +#ifndef CTEXTUREMANAGER_HPP +#define CTEXTUREMANAGER_HPP + +#include "../../Graphics/Data/Texture/CTexture.hpp" +#include "../CAbstractResourceManager.hpp" + +class CTextureManager : public CAbstractResourceManager +{ + public: + + CTexture* loadTexture(const std::string& path, TextureType type = TextureType::Color) { + auto cached = get(path); + if (cached) return cached.value(); + + auto tex = std::make_unique(path, type); + tex->init(); + return add(path, std::move(tex)); + } +}; + + #endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.cpp new file mode 100644 index 0000000..0aadd3f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.cpp @@ -0,0 +1,67 @@ +#include "CScriptAPI.hpp" +#include +#include +#include +#include + +namespace CosmicCore { + CScriptRegistry CScriptAPI::scriptRegistry; + SDL_SharedObject* CScriptAPI::moduleHandle = nullptr; + + namespace { + // "ScriptsModule" -> libScriptsModule.so / ScriptsModule.dll / libScriptsModule.dylib + std::string moduleFileName(const std::string& name) { + #if defined(_WIN32) + return name + ".dll"; + #elif defined(__APPLE__) + return "lib" + name + ".dylib"; + #else + return "lib" + name + ".so"; + #endif + } + } + + + void CScriptAPI::init(const std::string& moduleName, const std::string& registerSymbol) + { + void* lib = dlopen("libScriptsModule.so", RTLD_NOW | RTLD_GLOBAL); + if (lib) { + auto registerFunc = (void(*)(CScriptRegistry* reg))dlsym(lib, "registerAllScripts"); + registerFunc(&CScriptAPI::scripts()); // Passer l'API à la lib + } + else { + std::cout << "dlopen failed: " << dlerror() << std::endl; + throw std::runtime_error("Failed to load script module"); + } + + + // Dossier de l'exécutable, pas le dossier courant : fonctionne quel que soit le lancement. + const char* base = SDL_GetBasePath(); + const auto path = (base ? std::filesystem::path(base) : std::filesystem::path(".")) + / moduleFileName(moduleName); + + moduleHandle = SDL_LoadObject(path.string().c_str()); + if (!moduleHandle) { + throw std::runtime_error("Failed to load script module '" + path.string() + "': " + SDL_GetError()); + } + + using RegisterFn = void (*)(CScriptRegistry*); + auto registerFunc = reinterpret_cast(SDL_LoadFunction(moduleHandle, registerSymbol.c_str())); + if (!registerFunc) { + const std::string err = SDL_GetError(); + destroy(); + throw std::runtime_error("Symbol '" + registerSymbol + "' not found in '" + path.string() + "': " + err); + } + registerFunc(&CScriptAPI::scripts()); + } + + + void CScriptAPI::destroy() + { + if (moduleHandle) { + SDL_UnloadObject(moduleHandle); + moduleHandle = nullptr; + } + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.hpp new file mode 100644 index 0000000..084b58e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/API/CScriptAPI.hpp @@ -0,0 +1,34 @@ +#ifndef SCRIPTAPI_HPP +#define SCRIPTAPI_HPP + +#include +#ifndef COSMIC_SCRIPT_MODULE +#define COSMIC_SCRIPT_MODULE "ScriptsModule" // valeur par défaut +#endif + +#include "../CScriptRegistry.hpp" + +namespace CosmicCore { + class CScriptAPI{ + private: + CScene* m_scene; + static CScriptRegistry scriptRegistry; + static SDL_SharedObject* moduleHandle; + public: + static CScriptRegistry& scripts(){return scriptRegistry;}; + + static void init(const std::string& moduleName = COSMIC_SCRIPT_MODULE, const std::string& registerSymbol = "registerAllScripts"); + + CScriptAPI(CScene* scene): m_scene(scene){}; + virtual ~CScriptAPI() = default; + + virtual void updateWorld(float delta) = 0; + + static void destroy(); + + CScene* getScene(){return m_scene;}; + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptRegistry.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptRegistry.hpp new file mode 100644 index 0000000..a7ec87b --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptRegistry.hpp @@ -0,0 +1,50 @@ +#ifndef CSCRIPTREGISTRY_HPP +#define CSCRIPTREGISTRY_HPP + +#include "Engine/Core/Component/Script/CAbstractScript.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include + +using ScriptFactory = std::function(CosmicCore::CEntity&, const std::string&)>; + +class CScriptRegistry +{ + private: + std::unordered_map m_factories; + + public: + void registerScript(const std::string& name, ScriptFactory factory) { + m_factories[name] = factory; + } + + // Helper pour enregistrer un script template + template + void registerScript(const std::string& name) { + static_assert(std::is_base_of_v, + "T must derive from CAbstractScript"); + + registerScript(name, + [](CosmicCore::CEntity& entity, const std::string& n) -> std::unique_ptr { + std::unique_ptr concreteScript = std::make_unique(entity, n); + // Cast explicite vers la classe de base + return std::unique_ptr(concreteScript.release()); + }); + } + + // Enregistre un type de script avec son nom + std::unique_ptr create(const std::string& name, + CosmicCore::CEntity& entity, + const std::string& scriptName) { + auto it = m_factories.find(name); + if (it != m_factories.end()) { + return it->second(entity, scriptName); + } + return nullptr; + } + + bool hasScript(const std::string& name) const { + return m_factories.find(name) != m_factories.end(); + } +}; + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.cpp b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.cpp new file mode 100644 index 0000000..8832cf6 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.cpp @@ -0,0 +1,31 @@ +#include "CScriptWorld.hpp" +#include "Engine/Core/Scene/CScene.hpp" +#include "Engine/Core/Component/Script/CScriptManager.hpp" +namespace CosmicCore { + + CScriptWorld::~CScriptWorld() + { + } + + void CScriptWorld::initWorld() + { + + } + + void CScriptWorld::updateWorld(float delta) + { + auto& registry = getScene()->getECManager().registry; + auto scriptView = registry.view(); + for(auto& entity : scriptView) + { + auto& scriptMan = registry.get(entity); + scriptMan.updateAll(); + } + + } + + void CScriptWorld::destroy() + { + + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.hpp b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.hpp new file mode 100644 index 0000000..7a7fc0c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Core/Systems/Scripts/CScriptWorld.hpp @@ -0,0 +1,21 @@ +#ifndef CSCRIPTWORLD_HPP +#define CSCRIPTWORLD_HPP + +#include "Engine/Core/Systems/Scripts/API/CScriptAPI.hpp" +namespace CosmicCore { + + class CScriptWorld : public CScriptAPI{ + + public: + CScriptWorld(CScene* scene) : CScriptAPI(scene) {} + ~CScriptWorld(); + void initWorld(); + + void updateWorld(float delta); + + void destroy(); + }; + +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.cpp b/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.cpp new file mode 100644 index 0000000..a4a37eb --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.cpp @@ -0,0 +1,76 @@ +#include "CBasicConfiguration.hpp" +#include + +namespace CosmicUtils { + + bool CBasicConfiguration::load(const std::string& path) { + m_data = readFile(path); + if (m_data.empty()) { reset(); return false; } + + // window + if (m_data.contains("window")) { + auto& w = m_data["window"]; + window.width = w.value("width", 1280u); + window.height = w.value("height", 720u); + window.fullscreen = w.value("fullscreen", false); + window.vsync = w.value("vsync", true); + window.title = w.value("title", "CosmicEngine"); + } + + // graphics + if (m_data.contains("graphics")) { + auto& g = m_data["graphics"]; + graphics.validationLayers = g.value("validationLayers", false); + graphics.maxFramesInFlight = g.value("maxFramesInFlight", 2u); + graphics.msaa = g.value("msaa", false); + } + + // audio + if (m_data.contains("audio")) { + auto& a = m_data["audio"]; + audio.masterGain = a.value("masterGain", 1.0f); + audio.musicGain = a.value("musicGain", 1.0f); + audio.ambianceGain = a.value("ambianceGain", 1.0f); + audio.uiGain = a.value("uiGain", 1.0f); + } + + if (m_data.contains("input")) { + auto& i = m_data["input"]; + input.mouseSensitivity = i.value("mouseSensitivity", 0.1f); + input.invertMouseX = i.value("invertMouseX", false); + input.invertMouseY = i.value("invertMouseY", false); + input.bindingsPath = i.value("bindingsPath", "config/engine/bindings_default.json"); + input.actionsPath = i.value("actionsPath", "config/engine/bindings_default.json"); + } + return true; + } + + void CBasicConfiguration::save(const std::string& path) const { + nlohmann::json j; + j["window"]["width"] = window.width; + j["window"]["height"] = window.height; + j["window"]["fullscreen"] = window.fullscreen; + j["window"]["vsync"] = window.vsync; + j["window"]["title"] = window.title; + + j["graphics"]["validationLayers"] = graphics.validationLayers; + j["graphics"]["maxFramesInFlight"] = graphics.maxFramesInFlight; + j["graphics"]["msaa"] = graphics.msaa; + + j["audio"]["masterGain"] = audio.masterGain; + j["audio"]["musicGain"] = audio.musicGain; + j["audio"]["ambianceGain"] = audio.ambianceGain; + j["audio"]["uiGain"] = audio.uiGain; + + //TODO input + + writeFile(path, j); + } + + void CBasicConfiguration::reset() { + window = WindowSettings{}; + graphics = GraphicsSettings{}; + audio = AudioSettings{}; + input = InputSettings{}; + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.hpp b/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.hpp new file mode 100644 index 0000000..d72024a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Configurations/CBasicConfiguration.hpp @@ -0,0 +1,77 @@ +#ifndef CABSTRACTCONFIGURATION_HPP +#define CABSTRACTCONFIGURATION_HPP + +#include "nlohmann/json.hpp" +#include +#include +#include +namespace CosmicUtils { + + class CBasicConfiguration { + + public: + + struct WindowSettings { + uint32_t width = 1280; + uint32_t height = 720; + bool fullscreen = false; + bool vsync = true; + std::string title = "CosmicEngine"; + }; + + struct GraphicsSettings { + bool validationLayers = false; + uint32_t maxFramesInFlight = 2; + bool msaa = false; + }; + + struct AudioSettings { + float masterGain = 1.0f; + float musicGain = 1.0f; + float ambianceGain = 1.0f; + float uiGain = 1.0f; + }; + + struct InputSettings { + float mouseSensitivity = 0.1f; + bool invertMouseX = false; + bool invertMouseY = false; + std::string bindingsPath = "config/engine/bindings_default.json"; + std::string actionsPath = "config/engine/actions.json"; + }; + + WindowSettings window; + GraphicsSettings graphics; + AudioSettings audio; + InputSettings input; + + + + virtual bool load(const std::string& path); + virtual void save(const std::string& path) const; + virtual void reset(); + virtual ~CBasicConfiguration() = default; + + protected: + nlohmann::json m_data; + + nlohmann::json readFile(const std::string& path) { + std::ifstream file(path); + + if (!file.good()) + return nlohmann::json{}; + return nlohmann::json::parse(file); + } + + void writeFile(const std::string& path, + const nlohmann::json& j) const { + std::filesystem::create_directories( + std::filesystem::path(path).parent_path() + ); + std::ofstream file(path); + file << j.dump(4); + } + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.cpp b/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.cpp new file mode 100644 index 0000000..429329c --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.cpp @@ -0,0 +1,5 @@ +#include "CEngineConfiguration.hpp" + +namespace CosmicUtils { + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.hpp b/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.hpp new file mode 100644 index 0000000..b4e0d2f --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Configurations/CEngineConfiguration.hpp @@ -0,0 +1,12 @@ +#ifndef CENGINECONFIGURATION_HPP +#define CENGINECONFIGURATION_HPP +#include "CBasicConfiguration.hpp" +namespace CosmicUtils { + + class CEngineConfiguration : public CBasicConfiguration + { + public: + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.cpp b/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.cpp new file mode 100644 index 0000000..f2127ca --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.cpp @@ -0,0 +1,111 @@ +#include "CEntityFactory.hpp" +#include "ComponentFactory.hpp" + +namespace CosmicUtils { + + namespace CEntityFactory { + + CEntity create(CScene* scene, EntityConfig& config) { + auto entity = scene->createEntity(); + ComponentFactory::addMetaData(entity, config.name, config.description); + auto& transform = config.transformConfig; + auto& camera = config.cameraConfig; + auto& collider = config.colliderConfig; + auto& rigidbody = config.rigidBodyConfig; + auto& renderer = config.rendererConfig; + auto& speaker = config.speakerConfig; + auto& script = config.scriptConfig; + auto& light = config.lightConfig; + auto& relationship = config.relationshipConfig; + + if(transform.has_value()) + { + ComponentFactory::addTransform(entity, *transform); + } + if(renderer.has_value()) + { + ComponentFactory::addRenderer(entity, *renderer); + } + if(collider.has_value() && rigidbody.has_value()) + { + ComponentFactory::addCollider(entity, *collider); + ComponentFactory::addRigidBody(entity, *rigidbody); + } + + if(speaker.has_value()) + { + ComponentFactory::addSpeaker(entity, *speaker); + } + + if(camera.has_value()) + { + ComponentFactory::addCamera(entity, *camera); + } + + if(script.has_value()) + { + ComponentFactory::addScript(entity, *script); + } + + if(light.has_value()) + { + ComponentFactory::addLight(entity, *light); + } + + if(relationship.has_value()) + { + ComponentFactory::addRelationship(entity, *relationship); + } + return entity; + } + + CEntity create(CScene* scene, Entity2DConfig& config) { + auto entity = scene->createEntity(); + ComponentFactory::addMetaData(entity, config.name, config.description); + auto& transform = config.transformConfig; + auto& camera = config.cameraConfig; + auto& collider = config.colliderConfig; + auto& renderer = config.rendererConfig; + auto& script = config.scriptConfig; + auto& textRender = config.textConfig; + auto& relationship = config.relationshipConfig; + + if(transform.has_value()) + { + ComponentFactory::addTransform2D(entity, *transform); + } + if(renderer.has_value()) + { + ComponentFactory::addRenderer2D(entity, *renderer); + } + if(collider.has_value()) + { + ComponentFactory::addCollider2D(entity, *collider); + } + + if(camera.has_value()) + { + ComponentFactory::addCamera2D(entity, *camera); + } + + if(script.has_value()) + { + ComponentFactory::addScript(entity, *script); + } + + if(textRender.has_value()) + { + ComponentFactory::addTextRenderer2D(entity, *textRender); + } + + if(relationship.has_value()) + { + ComponentFactory::addRelationship(entity, *relationship); + } + + return entity; + } + + } + +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.hpp b/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.hpp new file mode 100644 index 0000000..698f71d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/CEntityFactory.hpp @@ -0,0 +1,49 @@ +#include "../../Core/Scene/CScene.hpp" +#include "../../Core/Entity/CEntity.hpp" +#include "ComponentFactory.hpp" +#include + +namespace CosmicUtils { + + namespace CEntityFactory { + using namespace CosmicCore; + using namespace ComponentFactory; + + struct EntityConfig { + std::string name = "Entity"; + std::string description = ""; + std::optional transformConfig = std::nullopt; + std::optional cameraConfig = std::nullopt; + std::optional rendererConfig = std::nullopt; + std::optional colliderConfig = std::nullopt; + std::optional rigidBodyConfig = std::nullopt; + std::optional speakerConfig = std::nullopt; + std::optional scriptConfig = std::nullopt; + std::optional lightConfig = std::nullopt; + std::optional relationshipConfig = std::nullopt; + }; + + struct Entity2DConfig { + std::string name = "Entity"; + std::string description = ""; + std::optional transformConfig = std::nullopt; + std::optional cameraConfig = std::nullopt; + std::optional rendererConfig = std::nullopt; + std::optional colliderConfig = std::nullopt; + std::optional scriptConfig = std::nullopt; + std::optional textConfig = std::nullopt; + std::optional relationshipConfig = std::nullopt; + }; + + CEntity create(CScene* e, EntityConfig& config); + CEntity create(CScene* e, Entity2DConfig& config); + + /*CEntity createSphere(CScene* e, const EntityConfig& config); + + CEntity createCylinder(CScene* e, const EntityConfig& config); + + CEntity createPlane(CScene* e, const EntityConfig& config); + + CEntity createReferenceAxis(CScene* e, const EntityConfig& config);*/ + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.cpp b/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.cpp new file mode 100644 index 0000000..3acd272 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.cpp @@ -0,0 +1,5 @@ +#include "CShaderFactory.hpp" + +namespace CosmicUtils { + GraphicsBackend CShaderFactory::m_backend = GraphicsBackend::Vulkan; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.hpp b/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.hpp new file mode 100644 index 0000000..8e2b665 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/CShaderFactory.hpp @@ -0,0 +1,26 @@ +#ifndef CSHADERFACTORY_HPP +#define CSHADERFACTORY_HPP + +#include "../../Core/Systems/Graphics/Shader/CShader.hpp" +#include "../../Core/Systems/Graphics/API/GraphicsAPI.hpp" +#include "../../Core/Systems/Graphics/Shader/Implementations/CShaderImplVulkan.hpp" + +#include +#include +namespace CosmicUtils { + + class CShaderFactory{ + static GraphicsBackend m_backend; + public: + static std::unique_ptr create(std::string name, std::filesystem::path path) { + switch (m_backend) { + case GraphicsBackend::Vulkan: return std::make_unique(name, path); + case GraphicsBackend::OpenGL: return nullptr; + case GraphicsBackend::Metal: return nullptr; + break; + } + } + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.cpp b/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.cpp new file mode 100644 index 0000000..909542d --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.cpp @@ -0,0 +1,293 @@ +#include "ComponentFactory.hpp" +#include "Engine/Core/Systems/Graphics/Data/CModelLoader.hpp" +#include "Engine/Core/Systems/Resources/API/CResourceAPI.hpp" +#include "Engine/Core/Component/Camera/CCamera2D.hpp" +#include "Engine/Core/Component/Collider/CCollider2D.hpp" +#include "Engine/Core/Component/Geometry/CTransform2D.hpp" +#include "Engine/Core/Component/Light/CLight.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Systems/Graphics/Data/Material/CMaterial2D.hpp" +#include "Engine/Core/Systems/Graphics/Data/Mesh/CMesh2D.hpp" +#include "Engine/Core/Systems/Graphics/Data/Model/CModel2D.hpp" +#include +#include + +namespace CosmicUtils { + + namespace ComponentFactory { + using namespace CosmicCore; + + CTransform& addTransform(CEntity& entity, TransformConfig& transformConfig) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto& reg = entity.getRegistry(); + auto& tr = reg.registry.emplace(*entity, entity); + tr.setCenter(transformConfig.position); + tr.setScale(transformConfig.scale); + tr.setEulerAngle(transformConfig.rotation); + tr.initUniformBuffer(api->getAllocator()); + tr.updateUniformBuffer(0); + tr.updateUniformBuffer(1); + return tr; + } + + CCamera& addCamera(CEntity& entity, CameraConfig& cameraConfig) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto& reg = entity.getRegistry(); + + // CTransform obligatoire pour la caméra + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addCamera requires a CTransform on the entity"); + + auto& transform = reg.registry.get(*entity); + auto& cam = reg.registry.emplace(*entity, entity); + + cam.setFov(cameraConfig.fov); + cam.setNearFar(cameraConfig.near, cameraConfig.far); + cam.setAspect((float)api->getSwapChainExtent().width / + (float)api->getSwapChainExtent().height); + cam.initUniformBuffer(api->getAllocator()); + cam.updateUniformBuffer(0, transform); + cam.updateUniformBuffer(1, transform); + return cam; + } + + CRenderer& addRenderer(CEntity& entity, RendererConfig& rendererConfig) + { + auto& rm = CResourceAPI::resources(); + auto& reg = entity.getRegistry(); + + ModelLoadConfig config; + config.shaderName = rendererConfig.shader; + + // override albedo si fourni + if (rendererConfig.albedo.has_value()) { + CTexture* tex = rm.textures().loadTexture(*rendererConfig.albedo); + + // crée un material custom avec cette texture pour chaque mesh + auto* shader = static_cast( + rm.shaders().get(config.shaderName) + ); + + // clé unique model + albedo + std::string matKey = rendererConfig.model + "_" + *rendererConfig.albedo; + + // un override par mesh (tous avec la même texture pour l'instant) + CModel* baseModel = CModelLoader::loadModel(rendererConfig.model, {.forceReload = false}); + for (uint32_t i = 0; i < baseModel->getMeshMaterials().size(); i++) { + CMaterial* mat = rm.materials().contains(matKey + "_" + std::to_string(i)) ? + rm.materials().get(matKey + "_" + std::to_string(i)).value() : + rm.materials().createMaterial(matKey + "_" + std::to_string(i), shader, tex); + config.materialOverrides[i] = mat; + } + } + + CModel* model = CModelLoader::loadModel(rendererConfig.model, config); + return reg.registry.emplace(*entity, entity, model); + } + + CCollider& addCollider(CEntity& entity, ColliderConfig& colliderConfig) + { + auto& reg = entity.getRegistry(); + auto& col = reg.registry.emplace(*entity, entity, colliderConfig.colliderType); + + // taille par défaut depuis le transform si disponible + if (reg.registry.all_of(*entity)) { + auto& tr = reg.registry.get(*entity); + switch (colliderConfig.colliderType) { + case EColliderType::Box: + col.setBoxSize(tr.getScale()); + break; + case EColliderType::Sphere: + col.setSphereRadius(glm::compMax(tr.getScale()) * 0.5f); + break; + case EColliderType::Capsule: + col.setCapsule(tr.getScale().y * 0.5f, + glm::max(tr.getScale().x, tr.getScale().z) * 0.5f); + break; + case EColliderType::ConvexHull: + case EColliderType::Mesh: + // build depuis le renderer si disponible + if (reg.registry.all_of(*entity)) + col.buildFromRenderer(); + break; + default: + break; + } + } + return col; + } + + CRigidBody& addRigidBody(CEntity& entity, RigidBodyConfig& rigidBodyConfig) + { + auto& reg = entity.getRegistry(); + + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addRigidBody requires a CTransform on the entity"); + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addRigidBody requires a CCollider on the entity"); + + auto& rb = reg.registry.emplace(*entity, entity, rigidBodyConfig.bodyType); + rb.init(); + return rb; + } + + CMetaData& addMetaData(CEntity& entity, std::string n, std::string des) + { + auto& reg = entity.getRegistry(); + + auto& rb = reg.registry.emplace(*entity, entity, n, des); + return rb; + } + + CSpeaker& addSpeaker(CEntity& entity, SpeakerConfig& soundsConfig) + { + auto& rm = CResourceAPI::resources(); + auto& reg = entity.getRegistry(); + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addSpeaker requires a CTransform on the entity"); + + auto& sp = reg.registry.emplace(*entity, entity); + + for(auto& conf : soundsConfig.clips) + { + auto clip = rm.sounds().loadClip(conf.path); + sp.addClip(conf.path, clip, conf.gain, conf.pitch, conf.loop, conf.spatial); + } + return sp; + } + + CRelationship& addRelationship(CEntity& entity, RelationshipConfig& relationshipConfig) + { + auto& reg = entity.getRegistry(); + auto& relationship = reg.registry.emplace(*entity, entity, relationshipConfig.parent, relationshipConfig.children); + return relationship; + } + + CScriptManager& addScript(CEntity& entity, ScriptConfig& scriptConfig) + { + auto& reg = entity.getRegistry(); + auto& scriptMan = reg.registry.get_or_emplace(*entity, entity); + + for(auto& name : scriptConfig.scriptNames) + { + scriptMan.emplace(name); + } + return scriptMan; + } + + CLight& addLight(CEntity& entity, LightConfig& lightConfig) + { + auto& reg = entity.getRegistry(); + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addLight requires a CTransform on the entity"); + + auto& light = reg.registry.emplace(*entity, entity); + light.setType(lightConfig.type); + light.setColor(lightConfig.color); + light.setAttenuation(lightConfig.attenuation); + light.setInnerAngle(lightConfig.innerAngle); + light.setRange(lightConfig.range); + light.setOuterAngle(lightConfig.outerAngle); + light.setIntensity(lightConfig.intensity); + light.setCastShadow(lightConfig.castShadow); + return light; + } + + CCamera2D& addCamera2D(CEntity& entity, Camera2DConfig& cameraConfig) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + auto& reg = entity.getRegistry(); + + // CTransform obligatoire pour la caméra + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addCamera2D requires a CTransform2D on the entity"); + + auto& transform = reg.registry.get(*entity); + auto& camera = reg.registry.emplace(*entity, entity); + camera.initUniformBuffer(api->getAllocator()); + camera.updateUniformBuffer(0, transform); + camera.updateUniformBuffer(1, transform); + return camera; + } + + CCollider2D& addCollider2D(CEntity& entity, Collider2DConfig& colliderConfig) + { + auto& reg = entity.getRegistry(); + auto& collider = reg.registry.emplace(*entity, entity, colliderConfig.shape); + return collider; + } + + CTransform2D& addTransform2D(CEntity& entity, Transform2DConfig& transformConfig) + { + VulkanImpl* api = dynamic_cast(GraphicsAPI::getAPI().get()); + + auto& reg = entity.getRegistry(); + auto& transform = reg.registry.emplace(*entity, entity); + transform.setSize(transformConfig.m_size); + transform.setPivot(transformConfig.m_pivot); + transform.setPosition(transformConfig.m_position); + transform.setScale(transformConfig.m_scale); + transform.setRotation(transformConfig.m_rotation); + transform.setVisible(transformConfig.m_visible); + transform.setZOrder(transformConfig.m_zOrder); + transform.setAnchor(transformConfig.m_anchor); + transform.initUniformBuffer(api->getAllocator()); + transform.updateUniformBuffer(0); + transform.updateUniformBuffer(1); + return transform; + } + + CRenderer2D& addRenderer2D(CEntity& entity, Renderer2DConfig& rendererConfig) + { + auto& reg = entity.getRegistry(); + + // CTransform obligatoire + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addRenderer2D requires a CTransform2D on the entity"); + + Model2DLoadConfig config; + config.shaderName = rendererConfig.shader; + + CModel2D* model = CModelLoader::loadModel2D(rendererConfig.model, config); + return reg.registry.emplace(*entity, entity, model); + } + + CRenderer2D& addTextRenderer2D(CEntity& entity, TextRenderer2DConfig& rendererConfig) + { + auto& reg = entity.getRegistry(); + + // CTransform obligatoire + if (!reg.registry.all_of(*entity)) + throw std::runtime_error("addTextRenderer2D requires a CTransform2D on the entity"); + + auto font = CResourceAPI::resources().fonts().loadFont(rendererConfig.font); + + auto shader = CResourceAPI::resources().shaders().get(rendererConfig.shader); + MeshMaterial2D mm2d; + auto material2D = std::make_unique(); + mm2d.material = material2D.get(); + mm2d.material->m_color = rendererConfig.color; + mm2d.material->m_font = font; + mm2d.material->shader = static_cast(shader); + mm2d.material->build(); + auto mesh2D = std::make_unique(); + mm2d.mesh = mesh2D.get(); + mm2d.mesh->buildFromText(mm2d.material->m_font, rendererConfig.text); + std::vector mm2DVec = {mm2d}; + auto model2D = std::make_unique(mm2DVec); + CModel2D* model = model2D.get(); + std::string prefixMat = mm2d.material->shader->getName() + mm2d.material->m_font->getAtlas()->getFilePath(); + std::string keyMat = prefixMat + "_MAT2DTEXT"; + std::string keyMeshes = prefixMat + std::to_string(std::hash{}(rendererConfig.text)) + "_MESH2DTEXT"; + std::string keyModel2D = keyMat + keyMeshes; + CResourceAPI::resources().materials2D().add(keyMat, std::move(material2D)); + CResourceAPI::resources().meshes2D().add(keyMeshes, std::move(mesh2D)); + CResourceAPI::resources().models2D().add(keyModel2D, std::move(model2D)); + + return reg.registry.emplace(*entity, entity, model); + } + + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.hpp b/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.hpp new file mode 100644 index 0000000..61dc87a --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/Factory/ComponentFactory.hpp @@ -0,0 +1,159 @@ +#ifndef CCOMPONENTFACTORY_HPP +#define CCOMPONENTFACTORY_HPP + +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Component/Collider/CCollider.hpp" +#include "Engine/Core/Component/Geometry/CTransform.hpp" +#include "Engine/Core/Component/Rigidbody/CRigidBody.hpp" +#include "Engine/Core/Component/Graphics/CRenderer.hpp" +#include "Engine/Core/Component/Camera/CCamera.hpp" +#include "Engine/Core/Component/Meta/CMetaData.hpp" +#include "Engine/Core/Component/Speaker/CSpeaker.hpp" +#include "Engine/Core/Component/Relationships/CRelationship.hpp" +#include "Engine/Core/Component/Camera/CCamera2D.hpp" +#include "Engine/Core/Component/Collider/CCollider2D.hpp" +#include "Engine/Core/Component/Geometry/CTransform2D.hpp" +#include "Engine/Core/Component/Graphics/CRenderer2D.hpp" +#include "Engine/Core/Component/Light/CLight.hpp" +#include "Engine/Core/Component/Script/CScriptManager.hpp" +#include "glm/ext/vector_float3.hpp" + +#include +#include + +namespace CosmicUtils { + namespace ComponentFactory { + using namespace CosmicCore; + + struct TransformConfig { + glm::vec3 position = {0.0f, 0.0f, 0.0f}; + glm::vec3 rotation = {0.0f, 0.0f, 0.0f}; + glm::vec3 scale = {1.0f, 1.0f, 1.0f}; + }; + + struct CameraConfig { + float fov = 45.0f; + float near = 0.1f; + float far = 1000.0f; + }; + + struct RendererConfig { + std::string model = ""; + std::string shader = ""; + std::optional albedo = ""; + }; + + struct ColliderConfig { + EColliderType colliderType = EColliderType::Box; + glm::vec3 size = {1.0f, 1.0f, 1.0f}; + float radius = 1.0f; + float halfHeight = 0.5f; + }; + + struct RigidBodyConfig { + EBodyType bodyType = EBodyType::Dynamic; + float mass = 1.0f; + float friction = 1.0f; + float restitution = 0.0f; + }; + + struct SpeakerConfig { + struct SoundClipConfig{ + std::string path; + float gain = 1.0f; + float pitch = 1.0f; + bool loop = false; + bool spatial = true; + }; + std::vector clips; + }; + + struct RelationshipConfig{ + std::optional parent = std::nullopt; + std::vector children; + }; + + struct ScriptConfig{ + std::vector scriptNames; + }; + + struct LightConfig{ + ELightType type = ELightType::Directional; + glm::vec3 color = {1.0f, 1.0f, 1.0f}; + float intensity = 1.0f; + float range = 10.0f; + float attenuation = 1.0f; + float innerAngle = 15.0f; + float outerAngle = 30.0f; + bool castShadow = false; + }; + + struct Camera2DConfig{ + float zoom = 1; + }; + + struct Collider2DConfig{ + E2DShape shape = E2DShape::RECTANGLE; + }; + + struct Transform2DConfig{ + glm::vec2 m_position = {0, 0}; + glm::vec2 m_size = {100, 100}; + glm::vec2 m_scale = {1, 1}; + glm::vec2 m_pivot = {0, 0}; + glm::vec2 m_anchor = {0, 0}; + float m_rotation = 0.0f; + float m_zOrder = 0.0f; + bool m_visible = true; + }; + + struct Renderer2DConfig{ + std::string model = ""; + std::string shader = "ui"; + }; + + struct TextRenderer2DConfig{ + std::string text = ""; + std::string shader = "ui_text"; + glm::vec4 color = {1.0,1.0,1.0, 1.0}; + std::string font = "assets/fonts/Arial"; + }; + + // crée et initialise un CTransform sur une entité existante + CTransform& addTransform(CEntity& entity, TransformConfig& transformConfig); + + // crée et initialise une CCamera sur une entité existante + CCamera& addCamera(CEntity& entity, CameraConfig& cameraConfig); + + // crée et initialise un CRenderer depuis un fichier + CRenderer& addRenderer(CEntity& entity, RendererConfig& rendererConfig); + + // crée un CCollider + CCollider& addCollider(CEntity& entity, ColliderConfig& colliderConfig); + + // crée et initialise un CRigidBody + CRigidBody& addRigidBody(CEntity& entity, RigidBodyConfig& rigidBodyConfig); + + CMetaData& addMetaData(CEntity& entity, std::string n, std::string des); + + CSpeaker& addSpeaker(CEntity& entity, SpeakerConfig& soundsConfig); + + CRelationship& addRelationship(CEntity& entity, RelationshipConfig& relationshipConfig); + + CScriptManager& addScript(CEntity& entity, ScriptConfig& scriptConfig); + + CLight& addLight(CEntity& entity, LightConfig& lightConfig); + + CCamera2D& addCamera2D(CEntity& entity, Camera2DConfig& cameraConfig); + + CCollider2D& addCollider2D(CEntity& entity, Collider2DConfig& colliderConfig); + + CTransform2D& addTransform2D(CEntity& entity, Transform2DConfig& transformConfig); + + CRenderer2D& addRenderer2D(CEntity& entity, Renderer2DConfig& rendererConfig); + + CRenderer2D& addTextRenderer2D(CEntity& entity, TextRenderer2DConfig& rendererConfig); + + }; +} +#endif diff --git a/CosmicEngine/src/main/Engine/Utils/JsonParser/CSerializable.hpp b/CosmicEngine/src/main/Engine/Utils/JsonParser/CSerializable.hpp new file mode 100644 index 0000000..a155bc4 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/JsonParser/CSerializable.hpp @@ -0,0 +1,10 @@ +#ifndef CSERIALIZABLE_HPP +#define CSERIALIZABLE_HPP + +#include + +class CSerializable { + public: + virtual nlohmann::json to_json() = 0; +}; +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.cpp b/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.cpp new file mode 100644 index 0000000..15f5a2e --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.cpp @@ -0,0 +1,29 @@ +#include "Identifier.hpp" +#include +#include +namespace CosmicUtils { + std::unordered_map JsonKeyRegistry::m_idToKey = {}; + std::unordered_map JsonKeyRegistry::m_keyToId = {}; + + nlohmann::json_schema::json_validator JsonValidator::m_validator = nlohmann::json_schema::json_validator(); + + void JsonValidator::init(std::filesystem::path& path) + { + std::ifstream file(path); + nlohmann::json json = nlohmann::json::parse(file); + JsonKeyExtractor::initRegistry(json); + file.close(); + m_validator.set_root_schema(json); + } + + bool JsonValidator::validate(nlohmann::json& json) + { + try { + m_validator.validate(json); + return true; + } catch (const std::exception& e) { + std::cout << e.what() << std::endl; + return false; + } + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.hpp b/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.hpp new file mode 100644 index 0000000..353f228 --- /dev/null +++ b/CosmicEngine/src/main/Engine/Utils/JsonParser/Identifier.hpp @@ -0,0 +1,205 @@ +#ifndef IDENTIFIER_HPP +#define IDENTIFIER_HPP + +#include +#include +#include +#include +#include +#include + +namespace CosmicUtils { + + enum class EJsonKeys : int { + // Scene + Scene_Name = 101, + Scene_Description = 102, + Scene_Entities = 103, + + // Entity + Entity_Ref = 201, + Entity_Parent = 202, + Entity_Name = 203, + Entity_Description = 204, + Entity_Children = 205, + Entity_Components = 206, + + //ComponentList + Component_Transform= 2061, + Component_Renderer = 2062, + Component_Camera = 2063, + Component_Collider = 2064, + Component_Rigidbody = 2065, + Component_Speaker = 2066, + Component_Script = 2067, + Component_Light = 2068, + + // Transform + Transform_Position = 3011, + Transform_Rotation = 3012, + Transform_Scale = 3013, + + // Renderer + Renderer_Model = 3021, + Renderer_Shader = 3022, + Renderer_Albedo = 3023, + + // Camera + Camera_Fov = 3031, + Camera_Near = 3032, + Camera_Far = 3033, + + // Collider + Collider_Type = 3041, + Collider_Size = 3042, + Collider_Radius = 3043, + Collider_HalfHeight = 3044, + + // RigidBody + RigidBody_Type = 3051, + RigidBody_Mass = 3052, + RigidBody_Friction = 3053, + RigidBody_Restitution = 3054, + + // Speaker + Speaker_Clips = 3061, + Speaker_Path = 30611, + Speaker_Gain = 30612, + Speaker_Pitch = 30613, + Speaker_Loop = 30614, + Speaker_Spatial = 30615, + + // Speaker + Light_Type = 3071, + Light_Color = 3072, + Light_Intensity = 3073, + Light_Range = 3074, + Light_Attenuation = 3075, + Light_InnerAngle = 3076, + Light_OuterAngle = 3077, + Light_CastShadow = 3078, + + + //Scripts + Script_names = 3079, + + //2D + Scene_Entities2D = 104, + + // Entity + Entity2D_Ref = 207, + Entity2D_Name = 208, + Entity2D_Description = 209, + Entity2D_Components = 210, + + //ComponentList + Component_Transform2D= 2069, + Component_Renderer2D = 2070, + Component_Camera2D = 2071, + Component_Collider2D = 2072, + Component_TextRenderer2D = 2073, + Component_Script2D = 2074, + // Transform + Transform_Position2D = 4011, + Transform_Rotation2D = 4012, + Transform_Scale2D = 4013, + Transform_Size2D = 4014, + Transform_Pivot2D = 4015, + Transform_zOrder2D = 4016, + Transform_Visible2D = 4017, + Transform_Anchor2D = 4018, + + // Renderer + Renderer_Model2D = 4021, + Renderer_Shader2D = 4022, + + //Camera + Camera_Zoom2D = 4031, + + // Collider + Collider_Shape2D = 4041, + + //Text2D + TextRenderer_Text2D = 4051, + TextRenderer_Shader2D = 4052, + TextRenderer_Color2D = 4053, + TextRenderer_Font2D = 4054 + + }; + + + class JsonKeyRegistry{ + private: + static std::unordered_map m_idToKey; + static std::unordered_map m_keyToId; + public: + static void registerKey(int id, const std::string& key) { + m_idToKey[id] = key; + m_keyToId[key] = id; + } + + static const std::string& key(EJsonKeys id) { + auto it = m_idToKey.find(static_cast(id)); + if (it == m_idToKey.end()) + throw std::runtime_error("Unknown schema key ID: " + std::to_string(static_cast(id))); + return it->second; + } + + static EJsonKeys id(const std::string& key) { + auto it = m_keyToId.find(key); + if (it == m_keyToId.end()) + throw std::runtime_error("Unknown schema key: " + key); + return static_cast(it->second); + } + }; + + + + + class JsonKeyExtractor{ + static void extractIdsRecursive(const nlohmann::json& obj, const std::string& property = "") { + if (obj.is_object()) { + // Vérifier si cet objet a un ID + if (obj.contains("ID") && obj["ID"].is_number_integer()) { + int id = obj["ID"].get(); + JsonKeyRegistry::registerKey(id, property); + } + + // Parcourir toutes les propriétés + for (auto& [key, value] : obj.items()) { + if(key == "items" && value.contains("type") && value["type"] == "object") + { + extractIdsRecursive(value, ""); + } + + if ((key == "properties" || key == "definitions") && value.is_object()) { + // Traiter les propriétés + for (auto& [propName, propValue] : value.items()) { + extractIdsRecursive(propValue, propName); + } + } + } + } + } + + public: + + static void initRegistry(nlohmann::json& json) + { + extractIdsRecursive(json); + } + + }; + + class JsonValidator + { + private: + static nlohmann::json_schema::json_validator m_validator; + public: + static void init(std::filesystem::path& path); + + static bool validate(nlohmann::json& json); + }; +} + +#endif \ No newline at end of file diff --git a/CosmicEngine/src/main/Modules/Module/CModuleLoader.cpp b/CosmicEngine/src/main/Modules/Module/CModuleLoader.cpp new file mode 100644 index 0000000..8faa366 --- /dev/null +++ b/CosmicEngine/src/main/Modules/Module/CModuleLoader.cpp @@ -0,0 +1,5 @@ + +#include "CModuleLoader.hpp" +/*namespace CosmicCore { + std::vector CModuleLoader::handles; +}*/ \ No newline at end of file diff --git a/CosmicEngine/src/main/Modules/Module/CModuleLoader.hpp b/CosmicEngine/src/main/Modules/Module/CModuleLoader.hpp new file mode 100644 index 0000000..f0214c7 --- /dev/null +++ b/CosmicEngine/src/main/Modules/Module/CModuleLoader.hpp @@ -0,0 +1,66 @@ + +#ifndef CMODULELOADER_HPP +#define CMODULELOADER_HPP +#include +#include +#include +/*#include "../../../Configurations/Configuration/CConfiguration.hpp" +namespace CosmicCore +{ + class CModuleLoader { + public: + static std::vector handles; + + static int loadAll(){ + std::filesystem::directory_entry rootDir(CConfiguration::moduleConfiguration.getModulesDirectory()); + if(rootDir.exists() && rootDir.is_directory()) + { + std::filesystem::directory_iterator iteR(rootDir); + for(auto fileEntry : iteR) + { + if(fileEntry.is_regular_file()) + { + auto ext = fileEntry.path().extension().string(); + if(ext == ".so") + { + if(load(fileEntry.path())) + return 1; + } + } + } + } + return 0; + } + + static int load(std::filesystem::path moduleFile){ + void* handle = dlopen(moduleFile.c_str(), RTLD_LAZY); + if (!handle) { + std::cerr << "Failed to load shared library: " << dlerror() << std::endl; + return 1; + } + // Get the registration function + typedef void (*RegisterModuleFunc)(); + auto registerModule = (RegisterModuleFunc)dlsym(handle, "registerModule"); + if (!registerModule) { + std::cerr << "Failed to find registration function: " << dlerror() << std::endl; + dlclose(handle); + return 1; + } + + // Register the components + registerModule(); + handles.emplace_back(handle); + return 0; + } + + static int releaseAll() + { + for(auto handle : handles) + { + dlclose(handle); + } + return 0; + } + }; +}*/ +#endif diff --git a/CosmicEngine/src/main/resources/assets/configs/config.json b/CosmicEngine/src/main/resources/assets/configs/config.json new file mode 100644 index 0000000..37f347b --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/config.json @@ -0,0 +1,15 @@ +{ + "config": { + "video": { + "windowedHeight": 360, + "windowedWidth": 640, + "fullscreenHeight": 1080, + "fullscreenWidth": 1920, + "fullscreenSizeAuto": false, + "fullscreen": true, + "msaa": 16, + "vSync": 1, + "framerate": 60 + } + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/engine/actions_default.json b/CosmicEngine/src/main/resources/assets/configs/engine/actions_default.json new file mode 100644 index 0000000..8459313 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/engine/actions_default.json @@ -0,0 +1,6 @@ +{ + "actions": [ + "MoveForward", + "MoveBackward" + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/engine/bindings_default.json b/CosmicEngine/src/main/resources/assets/configs/engine/bindings_default.json new file mode 100644 index 0000000..a8c740a --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/engine/bindings_default.json @@ -0,0 +1,14 @@ +{ + "bindings": [ + { + "action": "MoveForward", + "device": "keyboard", + "key": "z" + }, + { + "action": "MoveBackward", + "device": "keyboard", + "key": "s" + } + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/engine/engine.json b/CosmicEngine/src/main/resources/assets/configs/engine/engine.json new file mode 100644 index 0000000..3c5f916 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/engine/engine.json @@ -0,0 +1,27 @@ +{ + "window": { + "width": 1280, + "height": 720, + "fullscreen": false, + "vsync": false, + "title": "CosmicEngine" + }, + "graphics": { + "validationLayers": false, + "maxFramesInFlight": 2, + "msaa": false + }, + "audio": { + "masterGain": 1.0, + "musicGain": 1.0, + "ambianceGain": 1.0, + "uiGain": 1.0 + }, + "input": { + "mouseSensitivity": 0.1, + "invertMouseX": false, + "invertMouseY": false, + "bindingsPath": "assets/configs/engine/bindings_default.json", + "actionsPath": "assets/configs/engine/actions_default.json" + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/game/actions_default.json b/CosmicEngine/src/main/resources/assets/configs/game/actions_default.json new file mode 100644 index 0000000..8459313 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/game/actions_default.json @@ -0,0 +1,6 @@ +{ + "actions": [ + "MoveForward", + "MoveBackward" + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/game/bindings_default.json b/CosmicEngine/src/main/resources/assets/configs/game/bindings_default.json new file mode 100644 index 0000000..a8c740a --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/game/bindings_default.json @@ -0,0 +1,14 @@ +{ + "bindings": [ + { + "action": "MoveForward", + "device": "keyboard", + "key": "z" + }, + { + "action": "MoveBackward", + "device": "keyboard", + "key": "s" + } + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/configs/game/game.json b/CosmicEngine/src/main/resources/assets/configs/game/game.json new file mode 100644 index 0000000..99471c7 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/configs/game/game.json @@ -0,0 +1,27 @@ +{ + "window": { + "width": 1280, + "height": 720, + "fullscreen": false, + "vsync": false, + "title": "My game" + }, + "graphics": { + "validationLayers": false, + "maxFramesInFlight": 2, + "msaa": false + }, + "audio": { + "masterGain": 1.0, + "musicGain": 1.0, + "ambianceGain": 1.0, + "uiGain": 1.0 + }, + "input": { + "mouseSensitivity": 0.1, + "invertMouseX": false, + "invertMouseY": false, + "bindingsPath": "assets/configs/game/bindings_default.json", + "actionsPath": "assets/configs/game/actions_default.json" + } +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.json b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.json new file mode 100644 index 0000000..35cc83e --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.json @@ -0,0 +1,2011 @@ +{ + "atlas": { + "type": "msdf", + "distanceRange": 2, + "distanceRangeMiddle": 0, + "size": 32.15625, + "width": 212, + "height": 212, + "yOrigin": "bottom" + }, + "metrics": { + "emSize": 1, + "lineHeight": 1.14990234375, + "ascender": 0.9052734375, + "descender": -0.2119140625, + "underlineY": -0.142578125, + "underlineThickness": 0.0732421875 + }, + "glyphs": [ + { + "unicode": 32, + "advance": 0.27783203125 + }, + { + "unicode": 33, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.047086398733600585, + "bottom": -0.046647230320699708, + "right": 0.2336753200163994, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 41.5, + "bottom": 151.5, + "right": 47.5, + "top": 177.5 + } + }, + { + "unicode": 34, + "advance": 0.35498046875, + "planeBounds": { + "left": 0.0059621086157677378, + "bottom": 0.41982507288629739, + "right": 0.34804179763423226, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 198.5, + "bottom": 98.5, + "right": 209.5, + "top": 109.5 + } + }, + { + "unicode": 35, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.034126066721331338, + "bottom": -0.046647230320699708, + "right": 0.58783700422133145, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 48.5, + "bottom": 151.5, + "right": 68.5, + "top": 177.5 + } + }, + { + "unicode": 36, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0074224444241981959, + "bottom": -0.13994169096209913, + "right": 0.55234431942419826, + "top": 0.82410106899902813 + }, + "atlasBounds": { + "left": 117.5, + "bottom": 180.5, + "right": 135.5, + "top": 211.5 + } + }, + { + "unicode": 37, + "advance": 0.88916015625, + "planeBounds": { + "left": 0.023046020863702679, + "bottom": -0.077745383867832848, + "right": 0.86269616663629745, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 162.5, + "bottom": 184.5, + "right": 189.5, + "top": 211.5 + } + }, + { + "unicode": 38, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.001426170356535526, + "bottom": -0.077745383867832848, + "right": 0.68558554839346453, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 150.5, + "right": 22.5, + "top": 177.5 + } + }, + { + "unicode": 39, + "advance": 0.19091796875, + "planeBounds": { + "left": 0.00069967998360058285, + "bottom": 0.41982507288629739, + "right": 0.1872886012663994, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 203.5, + "bottom": 49.5, + "right": 209.5, + "top": 60.5 + } + }, + { + "unicode": 40, + "advance": 0.3330078125, + "planeBounds": { + "left": 0.023220169764334303, + "bottom": -0.26433430515063167, + "right": 0.33420170523566567, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 178.5, + "right": 10.5, + "top": 211.5 + } + }, + { + "unicode": 41, + "advance": 0.3330078125, + "planeBounds": { + "left": 0.023220169764334303, + "bottom": -0.26433430515063167, + "right": 0.33420170523566567, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 11.5, + "bottom": 178.5, + "right": 21.5, + "top": 211.5 + } + }, + { + "unicode": 42, + "advance": 0.38916015625, + "planeBounds": { + "left": -0.009511044931365403, + "bottom": 0.38872691933916426, + "right": 0.39476495118136534, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 198.5, + "bottom": 110.5, + "right": 211.5, + "top": 122.5 + } + }, + { + "unicode": 43, + "advance": 0.583984375, + "planeBounds": { + "left": 0.012108805575801804, + "bottom": 0.077745383867832848, + "right": 0.57187556942419826, + "top": 0.63751214771622933 + }, + "atlasBounds": { + "left": 158.5, + "bottom": 23.5, + "right": 176.5, + "top": 41.5 + } + }, + { + "unicode": 44, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.042691867483600585, + "bottom": -0.2021379980563654, + "right": 0.2292807887663994, + "top": 0.1399416909620991 + }, + "atlasBounds": { + "left": 194.5, + "bottom": 30.5, + "right": 200.5, + "top": 41.5 + } + }, + { + "unicode": 45, + "advance": 0.3330078125, + "planeBounds": { + "left": -0.0042917976342322622, + "bottom": 0.17103984450923226, + "right": 0.33778789138423226, + "top": 0.35762876579203107 + }, + "atlasBounds": { + "left": 100.5, + "bottom": 1.5, + "right": 111.5, + "top": 7.5 + } + }, + { + "unicode": 46, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.047574679983600585, + "bottom": -0.046647230320699708, + "right": 0.2341636012663994, + "top": 0.13994169096209913 + }, + "atlasBounds": { + "left": 201.5, + "bottom": 35.5, + "right": 207.5, + "top": 41.5 + } + }, + { + "unicode": 47, + "advance": 0.27783203125, + "planeBounds": { + "left": -0.032123828884232264, + "bottom": -0.046647230320699708, + "right": 0.30995586013423226, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 87.5, + "bottom": 151.5, + "right": 98.5, + "top": 177.5 + } + }, + { + "unicode": 48, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0049810381741981959, + "bottom": -0.046647230320699708, + "right": 0.55478572567419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 122.5, + "bottom": 151.5, + "right": 140.5, + "top": 177.5 + } + }, + { + "unicode": 49, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.069682811740767736, + "bottom": -0.046647230320699708, + "right": 0.41176250075923226, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 18.5, + "bottom": 123.5, + "right": 29.5, + "top": 149.5 + } + }, + { + "unicode": 50, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.013076741299198216, + "bottom": -0.046647230320699708, + "right": 0.5466900225491983, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 48.5, + "bottom": 123.5, + "right": 66.5, + "top": 149.5 + } + }, + { + "unicode": 51, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0035161944241981959, + "bottom": -0.046647230320699708, + "right": 0.55625056942419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 67.5, + "bottom": 123.5, + "right": 85.5, + "top": 149.5 + } + }, + { + "unicode": 52, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.019629475674198198, + "bottom": -0.046647230320699708, + "right": 0.54013728817419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 86.5, + "bottom": 123.5, + "right": 104.5, + "top": 149.5 + } + }, + { + "unicode": 53, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0010747881741981959, + "bottom": -0.046647230320699708, + "right": 0.55869197567419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 105.5, + "bottom": 123.5, + "right": 123.5, + "top": 149.5 + } + }, + { + "unicode": 54, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0059576006741981959, + "bottom": -0.046647230320699708, + "right": 0.55380916317419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 124.5, + "bottom": 123.5, + "right": 142.5, + "top": 149.5 + } + }, + { + "unicode": 55, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.014718429224368374, + "bottom": -0.046647230320699708, + "right": 0.54338703952563172, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 155.5, + "bottom": 123.5, + "right": 172.5, + "top": 149.5 + } + }, + { + "unicode": 56, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0035161944241981959, + "bottom": -0.046647230320699708, + "right": 0.55625056942419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 158.5, + "bottom": 42.5, + "right": 176.5, + "top": 68.5 + } + }, + { + "unicode": 57, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0030279131741981959, + "bottom": -0.046647230320699708, + "right": 0.55673885067419826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 177.5, + "bottom": 42.5, + "right": 195.5, + "top": 68.5 + } + }, + { + "unicode": 58, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.047086398733600585, + "bottom": -0.046647230320699708, + "right": 0.2336753200163994, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 39.5, + "bottom": 0.5, + "right": 45.5, + "top": 20.5 + } + }, + { + "unicode": 59, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.042691867483600585, + "bottom": -0.2021379980563654, + "right": 0.2292807887663994, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 196.5, + "bottom": 43.5, + "right": 202.5, + "top": 68.5 + } + }, + { + "unicode": 60, + "advance": 0.583984375, + "planeBounds": { + "left": 0.011864664950801804, + "bottom": 0.077745383867832848, + "right": 0.57163142879919826, + "top": 0.63751214771622933 + }, + "atlasBounds": { + "left": 139.5, + "bottom": 23.5, + "right": 157.5, + "top": 41.5 + } + }, + { + "unicode": 61, + "advance": 0.583984375, + "planeBounds": { + "left": 0.012108805575801804, + "bottom": 0.17103984450923226, + "right": 0.57187556942419826, + "top": 0.54421768707482987 + }, + "atlasBounds": { + "left": 100.5, + "bottom": 8.5, + "right": 118.5, + "top": 20.5 + } + }, + { + "unicode": 62, + "advance": 0.583984375, + "planeBounds": { + "left": 0.011864664950801804, + "bottom": 0.077745383867832848, + "right": 0.57163142879919826, + "top": 0.63751214771622933 + }, + "atlasBounds": { + "left": 120.5, + "bottom": 23.5, + "right": 138.5, + "top": 41.5 + } + }, + { + "unicode": 63, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.010568038599368374, + "bottom": -0.046647230320699708, + "right": 0.53923664890063172, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 93.5, + "bottom": 42.5, + "right": 110.5, + "top": 68.5 + } + }, + { + "unicode": 64, + "advance": 1.01513671875, + "planeBounds": { + "left": 0.019031105745869775, + "bottom": -0.26433430515063167, + "right": 1.0141720192541301, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 54.5, + "bottom": 178.5, + "right": 86.5, + "top": 211.5 + } + }, + { + "unicode": 65, + "advance": 0.6669921875, + "planeBounds": { + "left": -0.039681748815597606, + "bottom": -0.046647230320699708, + "right": 0.70667393631559772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 44.5, + "bottom": 42.5, + "right": 68.5, + "top": 68.5 + } + }, + { + "unicode": 66, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.032524323903668668, + "bottom": -0.046647230320699708, + "right": 0.65448739484633145, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 23.5, + "bottom": 42.5, + "right": 43.5, + "top": 68.5 + } + }, + { + "unicode": 67, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.008582171707968959, + "bottom": -0.046647230320699708, + "right": 0.72383970329203107, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 69.5, + "bottom": 42.5, + "right": 92.5, + "top": 68.5 + } + }, + { + "unicode": 68, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.030967185981535528, + "bottom": -0.046647230320699708, + "right": 0.71512656401846453, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 42.5, + "right": 22.5, + "top": 68.5 + } + }, + { + "unicode": 69, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.035209870778668668, + "bottom": -0.046647230320699708, + "right": 0.65717294172133145, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 177.5, + "bottom": 69.5, + "right": 197.5, + "top": 95.5 + } + }, + { + "unicode": 70, + "advance": 0.61083984375, + "planeBounds": { + "left": 0.043602946200801809, + "bottom": -0.046647230320699708, + "right": 0.60336971004919826, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 158.5, + "bottom": 69.5, + "right": 176.5, + "top": 95.5 + } + }, + { + "unicode": 71, + "advance": 0.77783203125, + "planeBounds": { + "left": 0.011099501184402389, + "bottom": -0.046647230320699708, + "right": 0.75745518631559772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 133.5, + "bottom": 69.5, + "right": 157.5, + "top": 95.5 + } + }, + { + "unicode": 72, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.034309231505102102, + "bottom": -0.046647230320699708, + "right": 0.68737045599489799, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 111.5, + "bottom": 69.5, + "right": 132.5, + "top": 95.5 + } + }, + { + "unicode": 73, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.047330539358600585, + "bottom": -0.046647230320699708, + "right": 0.2339194606413994, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 104.5, + "bottom": 69.5, + "right": 110.5, + "top": 95.5 + } + }, + { + "unicode": 74, + "advance": 0.5, + "planeBounds": { + "left": -0.007687065518592882, + "bottom": -0.046647230320699708, + "right": 0.45878523768840418, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 88.5, + "bottom": 69.5, + "right": 103.5, + "top": 95.5 + } + }, + { + "unicode": 75, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.027060935981535528, + "bottom": -0.046647230320699708, + "right": 0.71122031401846453, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 65.5, + "bottom": 69.5, + "right": 87.5, + "top": 95.5 + } + }, + { + "unicode": 76, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.032540694849368376, + "bottom": -0.046647230320699708, + "right": 0.56120930515063172, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 47.5, + "bottom": 69.5, + "right": 64.5, + "top": 95.5 + } + }, + { + "unicode": 77, + "advance": 0.8330078125, + "planeBounds": { + "left": 0.042593641809402394, + "bottom": -0.046647230320699708, + "right": 0.78894932694059772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 22.5, + "bottom": 69.5, + "right": 46.5, + "top": 95.5 + } + }, + { + "unicode": 78, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.031623684630102102, + "bottom": -0.046647230320699708, + "right": 0.68468490911989799, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 69.5, + "right": 21.5, + "top": 95.5 + } + }, + { + "unicode": 79, + "advance": 0.77783203125, + "planeBounds": { + "left": 0.0018980806608358183, + "bottom": -0.046647230320699708, + "right": 0.77935191933916426, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 111.5, + "bottom": 42.5, + "right": 136.5, + "top": 68.5 + } + }, + { + "unicode": 80, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.039360261403668668, + "bottom": -0.046647230320699708, + "right": 0.66132333234633145, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 137.5, + "bottom": 42.5, + "right": 157.5, + "top": 68.5 + } + }, + { + "unicode": 81, + "advance": 0.77783203125, + "planeBounds": { + "left": 0.0033629244108358183, + "bottom": -0.10884353741496598, + "right": 0.78081676308916426, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 136.5, + "bottom": 183.5, + "right": 161.5, + "top": 211.5 + } + }, + { + "unicode": 82, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.036414202957968961, + "bottom": -0.046647230320699708, + "right": 0.75167173454203107, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 149.5, + "bottom": 96.5, + "right": 172.5, + "top": 122.5 + } + }, + { + "unicode": 83, + "advance": 0.6669921875, + "planeBounds": { + "left": 0.0033033721301020964, + "bottom": -0.046647230320699708, + "right": 0.65636459661989788, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 127.5, + "bottom": 96.5, + "right": 148.5, + "top": 122.5 + } + }, + { + "unicode": 84, + "advance": 0.61083984375, + "planeBounds": { + "left": -0.019401705994897905, + "bottom": -0.046647230320699708, + "right": 0.63365951849489788, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 105.5, + "bottom": 96.5, + "right": 126.5, + "top": 122.5 + } + }, + { + "unicode": 85, + "advance": 0.72216796875, + "planeBounds": { + "left": 0.033576809630102102, + "bottom": -0.046647230320699708, + "right": 0.68663803411989799, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 83.5, + "bottom": 96.5, + "right": 104.5, + "top": 122.5 + } + }, + { + "unicode": 86, + "advance": 0.6669921875, + "planeBounds": { + "left": -0.041390733190597613, + "bottom": -0.046647230320699708, + "right": 0.70496495194059772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 58.5, + "bottom": 96.5, + "right": 82.5, + "top": 122.5 + } + }, + { + "unicode": 87, + "advance": 0.94384765625, + "planeBounds": { + "left": -0.025158347379130169, + "bottom": -0.046647230320699708, + "right": 0.96998256612913014, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 25.5, + "bottom": 96.5, + "right": 57.5, + "top": 122.5 + } + }, + { + "unicode": 88, + "advance": 0.6669921875, + "planeBounds": { + "left": -0.040658311315597613, + "bottom": -0.046647230320699708, + "right": 0.70569737381559772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 96.5, + "right": 24.5, + "top": 122.5 + } + }, + { + "unicode": 89, + "advance": 0.6669921875, + "planeBounds": { + "left": -0.042123155065597613, + "bottom": -0.046647230320699708, + "right": 0.70423253006559772, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 173.5, + "bottom": 96.5, + "right": 197.5, + "top": 122.5 + } + }, + { + "unicode": 90, + "advance": 0.61083984375, + "planeBounds": { + "left": -0.023552096619897905, + "bottom": -0.046647230320699708, + "right": 0.62950912786989788, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 173.5, + "bottom": 123.5, + "right": 194.5, + "top": 149.5 + } + }, + { + "unicode": 91, + "advance": 0.27783203125, + "planeBounds": { + "left": 0.024853230912900877, + "bottom": -0.23323615160349853, + "right": 0.30473661283709913, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 97.5, + "bottom": 179.5, + "right": 106.5, + "top": 211.5 + } + }, + { + "unicode": 92, + "advance": 0.27783203125, + "planeBounds": { + "left": -0.032123828884232264, + "bottom": -0.046647230320699708, + "right": 0.30995586013423226, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 143.5, + "bottom": 123.5, + "right": 154.5, + "top": 149.5 + } + }, + { + "unicode": 93, + "advance": 0.27783203125, + "planeBounds": { + "left": -0.02397489408709913, + "bottom": -0.23323615160349853, + "right": 0.25590848783709907, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 107.5, + "bottom": 179.5, + "right": 116.5, + "top": 211.5 + } + }, + { + "unicode": 94, + "advance": 0.46923828125, + "planeBounds": { + "left": -0.014166087752065111, + "bottom": 0.29543245869776485, + "right": 0.48340436900206513, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 177.5, + "bottom": 26.5, + "right": 193.5, + "top": 41.5 + } + }, + { + "unicode": 95, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.050407565369897905, + "bottom": -0.23323615160349853, + "right": 0.60265365911989788, + "top": -0.077745383867832835 + }, + "atlasBounds": { + "left": 112.5, + "bottom": 2.5, + "right": 133.5, + "top": 7.5 + } + }, + { + "unicode": 96, + "advance": 0.3330078125, + "planeBounds": { + "left": 0.010861292061467446, + "bottom": 0.54421768707482987, + "right": 0.25964652043853254, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 203.5, + "bottom": 61.5, + "right": 211.5, + "top": 68.5 + } + }, + { + "unicode": 97, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0049810381741981959, + "bottom": -0.046647230320699708, + "right": 0.55478572567419826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 56.5, + "bottom": 21.5, + "right": 74.5, + "top": 41.5 + } + }, + { + "unicode": 98, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.025948897974368376, + "bottom": -0.046647230320699708, + "right": 0.55461750827563172, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 30.5, + "bottom": 123.5, + "right": 47.5, + "top": 149.5 + } + }, + { + "unicode": 99, + "advance": 0.5, + "planeBounds": { + "left": 0.00055827297436837446, + "bottom": -0.046647230320699708, + "right": 0.52922688327563172, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 38.5, + "bottom": 21.5, + "right": 55.5, + "top": 41.5 + } + }, + { + "unicode": 100, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0053011020256316255, + "bottom": -0.046647230320699708, + "right": 0.52336750827563172, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 123.5, + "right": 17.5, + "top": 149.5 + } + }, + { + "unicode": 101, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0042486162991981959, + "bottom": -0.046647230320699708, + "right": 0.55551814754919826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 46.5, + "bottom": 0.5, + "right": 64.5, + "top": 20.5 + } + }, + { + "unicode": 102, + "advance": 0.27783203125, + "planeBounds": { + "left": -0.025700249407798831, + "bottom": -0.046647230320699708, + "right": 0.3474775931577988, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 182.5, + "bottom": 151.5, + "right": 194.5, + "top": 177.5 + } + }, + { + "unicode": 103, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0035921176506316255, + "bottom": -0.26433430515063167, + "right": 0.52507649265063172, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 23.5, + "bottom": 150.5, + "right": 40.5, + "top": 177.5 + } + }, + { + "unicode": 104, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.028314380997934922, + "bottom": -0.046647230320699708, + "right": 0.52588483775206518, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 147.5, + "bottom": 151.5, + "right": 163.5, + "top": 177.5 + } + }, + { + "unicode": 105, + "advance": 0.22216796875, + "planeBounds": { + "left": 0.032606178632167158, + "bottom": -0.046647230320699708, + "right": 0.18809694636783286, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 141.5, + "bottom": 151.5, + "right": 146.5, + "top": 177.5 + } + }, + { + "unicode": 106, + "advance": 0.22216796875, + "planeBounds": { + "left": -0.08623075346209913, + "bottom": -0.26433430515063167, + "right": 0.1936526284620991, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 87.5, + "bottom": 178.5, + "right": 96.5, + "top": 211.5 + } + }, + { + "unicode": 107, + "advance": 0.5, + "planeBounds": { + "left": 0.032464771622934922, + "bottom": -0.046647230320699708, + "right": 0.53003522837706518, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 105.5, + "bottom": 151.5, + "right": 121.5, + "top": 177.5 + } + }, + { + "unicode": 108, + "advance": 0.22216796875, + "planeBounds": { + "left": 0.030164772382167158, + "bottom": -0.046647230320699708, + "right": 0.18565554011783286, + "top": 0.76190476190476186 + }, + "atlasBounds": { + "left": 99.5, + "bottom": 151.5, + "right": 104.5, + "top": 177.5 + } + }, + { + "unicode": 109, + "advance": 0.8330078125, + "planeBounds": { + "left": 0.02850940878583582, + "bottom": -0.046647230320699708, + "right": 0.80596324746416426, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 94.5, + "bottom": 21.5, + "right": 119.5, + "top": 41.5 + } + }, + { + "unicode": 110, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.027826099747934922, + "bottom": -0.046647230320699708, + "right": 0.52539655650206518, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 195.5, + "bottom": 157.5, + "right": 211.5, + "top": 177.5 + } + }, + { + "unicode": 111, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0037603350491981959, + "bottom": -0.046647230320699708, + "right": 0.55600642879919826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 21.5, + "right": 18.5, + "top": 41.5 + } + }, + { + "unicode": 112, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.026681319849368376, + "bottom": -0.23323615160349853, + "right": 0.55534993015063172, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 164.5, + "bottom": 151.5, + "right": 181.5, + "top": 177.5 + } + }, + { + "unicode": 113, + "advance": 0.55615234375, + "planeBounds": { + "left": -0.0045686801506316255, + "bottom": -0.23323615160349853, + "right": 0.52409993015063172, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 69.5, + "bottom": 151.5, + "right": 86.5, + "top": 177.5 + } + }, + { + "unicode": 114, + "advance": 0.3330078125, + "planeBounds": { + "left": 0.019221625592201169, + "bottom": -0.046647230320699708, + "right": 0.3923994681577988, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 26.5, + "bottom": 0.5, + "right": 38.5, + "top": 20.5 + } + }, + { + "unicode": 115, + "advance": 0.5, + "planeBounds": { + "left": -0.0026914783770651107, + "bottom": -0.046647230320699708, + "right": 0.49487897837706513, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 65.5, + "bottom": 0.5, + "right": 81.5, + "top": 20.5 + } + }, + { + "unicode": 116, + "advance": 0.27783203125, + "planeBounds": { + "left": -0.026996875759232264, + "bottom": -0.046647230320699708, + "right": 0.31508281325923226, + "top": 0.73080660835762878 + }, + "atlasBounds": { + "left": 198.5, + "bottom": 70.5, + "right": 209.5, + "top": 95.5 + } + }, + { + "unicode": 117, + "advance": 0.55615234375, + "planeBounds": { + "left": 0.025384693497934922, + "bottom": -0.046647230320699708, + "right": 0.52295515025206518, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 195.5, + "bottom": 129.5, + "right": 211.5, + "top": 149.5 + } + }, + { + "unicode": 118, + "advance": 0.5, + "planeBounds": { + "left": -0.029395100674198198, + "bottom": -0.046647230320699708, + "right": 0.53037166317419826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 19.5, + "bottom": 21.5, + "right": 37.5, + "top": 41.5 + } + }, + { + "unicode": 119, + "advance": 0.72216796875, + "planeBounds": { + "left": -0.030084341214164187, + "bottom": -0.046647230320699708, + "right": 0.74736949746416426, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 0.5, + "bottom": 0.5, + "right": 25.5, + "top": 20.5 + } + }, + { + "unicode": 120, + "advance": 0.5, + "planeBounds": { + "left": -0.029883381924198198, + "bottom": -0.046647230320699708, + "right": 0.52988338192419826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 75.5, + "bottom": 21.5, + "right": 93.5, + "top": 41.5 + } + }, + { + "unicode": 121, + "advance": 0.5, + "planeBounds": { + "left": -0.026221272549198198, + "bottom": -0.26433430515063167, + "right": 0.53354549129919826, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 190.5, + "bottom": 184.5, + "right": 208.5, + "top": 211.5 + } + }, + { + "unicode": 122, + "advance": 0.5, + "planeBounds": { + "left": -0.015310867650631626, + "bottom": -0.046647230320699708, + "right": 0.51335774265063172, + "top": 0.57531584062196306 + }, + "atlasBounds": { + "left": 82.5, + "bottom": 0.5, + "right": 99.5, + "top": 20.5 + } + }, + { + "unicode": 123, + "advance": 0.333984375, + "planeBounds": { + "left": -0.017399468157798831, + "bottom": -0.26433430515063167, + "right": 0.3557783744077988, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 41.5, + "bottom": 178.5, + "right": 53.5, + "top": 211.5 + } + }, + { + "unicode": 124, + "advance": 0.259765625, + "planeBounds": { + "left": 0.052381569257167152, + "bottom": -0.26433430515063167, + "right": 0.20787233699283286, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 35.5, + "bottom": 178.5, + "right": 40.5, + "top": 211.5 + } + }, + { + "unicode": 125, + "advance": 0.333984375, + "planeBounds": { + "left": -0.022282280657798831, + "bottom": -0.26433430515063167, + "right": 0.3508955619077988, + "top": 0.76190476190476175 + }, + "atlasBounds": { + "left": 22.5, + "bottom": 178.5, + "right": 34.5, + "top": 211.5 + } + }, + { + "unicode": 126, + "advance": 0.583984375, + "planeBounds": { + "left": -0.0031961305727647629, + "bottom": 0.23323615160349853, + "right": 0.5876687868227648, + "top": 0.4820213799805636 + }, + "atlasBounds": { + "left": 119.5, + "bottom": 12.5, + "right": 138.5, + "top": 20.5 + } + } + ], + "kerning": [ + { + "unicode1": 32, + "unicode2": 65, + "advance": -0.05517578125 + }, + { + "unicode1": 32, + "unicode2": 84, + "advance": -0.01806640625 + }, + { + "unicode1": 32, + "unicode2": 89, + "advance": -0.01806640625 + }, + { + "unicode1": 49, + "unicode2": 49, + "advance": -0.07421875 + }, + { + "unicode1": 65, + "unicode2": 32, + "advance": -0.05517578125 + }, + { + "unicode1": 65, + "unicode2": 84, + "advance": -0.07421875 + }, + { + "unicode1": 65, + "unicode2": 86, + "advance": -0.07421875 + }, + { + "unicode1": 65, + "unicode2": 87, + "advance": -0.037109375 + }, + { + "unicode1": 65, + "unicode2": 89, + "advance": -0.07421875 + }, + { + "unicode1": 65, + "unicode2": 118, + "advance": -0.01806640625 + }, + { + "unicode1": 65, + "unicode2": 119, + "advance": -0.01806640625 + }, + { + "unicode1": 65, + "unicode2": 121, + "advance": -0.01806640625 + }, + { + "unicode1": 70, + "unicode2": 44, + "advance": -0.11083984375 + }, + { + "unicode1": 70, + "unicode2": 46, + "advance": -0.11083984375 + }, + { + "unicode1": 70, + "unicode2": 65, + "advance": -0.05517578125 + }, + { + "unicode1": 76, + "unicode2": 32, + "advance": -0.037109375 + }, + { + "unicode1": 76, + "unicode2": 84, + "advance": -0.07421875 + }, + { + "unicode1": 76, + "unicode2": 86, + "advance": -0.07421875 + }, + { + "unicode1": 76, + "unicode2": 87, + "advance": -0.07421875 + }, + { + "unicode1": 76, + "unicode2": 89, + "advance": -0.07421875 + }, + { + "unicode1": 76, + "unicode2": 121, + "advance": -0.037109375 + }, + { + "unicode1": 80, + "unicode2": 32, + "advance": -0.01806640625 + }, + { + "unicode1": 80, + "unicode2": 44, + "advance": -0.12890625 + }, + { + "unicode1": 80, + "unicode2": 46, + "advance": -0.12890625 + }, + { + "unicode1": 80, + "unicode2": 65, + "advance": -0.07421875 + }, + { + "unicode1": 82, + "unicode2": 84, + "advance": -0.01806640625 + }, + { + "unicode1": 82, + "unicode2": 86, + "advance": -0.01806640625 + }, + { + "unicode1": 82, + "unicode2": 87, + "advance": -0.01806640625 + }, + { + "unicode1": 82, + "unicode2": 89, + "advance": -0.01806640625 + }, + { + "unicode1": 84, + "unicode2": 32, + "advance": -0.01806640625 + }, + { + "unicode1": 84, + "unicode2": 44, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 45, + "advance": -0.05517578125 + }, + { + "unicode1": 84, + "unicode2": 46, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 58, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 59, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 65, + "advance": -0.07421875 + }, + { + "unicode1": 84, + "unicode2": 79, + "advance": -0.01806640625 + }, + { + "unicode1": 84, + "unicode2": 97, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 99, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 101, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 105, + "advance": -0.037109375 + }, + { + "unicode1": 84, + "unicode2": 111, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 114, + "advance": -0.037109375 + }, + { + "unicode1": 84, + "unicode2": 115, + "advance": -0.11083984375 + }, + { + "unicode1": 84, + "unicode2": 117, + "advance": -0.037109375 + }, + { + "unicode1": 84, + "unicode2": 119, + "advance": -0.05517578125 + }, + { + "unicode1": 84, + "unicode2": 121, + "advance": -0.05517578125 + }, + { + "unicode1": 86, + "unicode2": 44, + "advance": -0.091796875 + }, + { + "unicode1": 86, + "unicode2": 45, + "advance": -0.05517578125 + }, + { + "unicode1": 86, + "unicode2": 46, + "advance": -0.091796875 + }, + { + "unicode1": 86, + "unicode2": 58, + "advance": -0.037109375 + }, + { + "unicode1": 86, + "unicode2": 59, + "advance": -0.037109375 + }, + { + "unicode1": 86, + "unicode2": 65, + "advance": -0.07421875 + }, + { + "unicode1": 86, + "unicode2": 97, + "advance": -0.07421875 + }, + { + "unicode1": 86, + "unicode2": 101, + "advance": -0.05517578125 + }, + { + "unicode1": 86, + "unicode2": 105, + "advance": -0.01806640625 + }, + { + "unicode1": 86, + "unicode2": 111, + "advance": -0.05517578125 + }, + { + "unicode1": 86, + "unicode2": 114, + "advance": -0.037109375 + }, + { + "unicode1": 86, + "unicode2": 117, + "advance": -0.037109375 + }, + { + "unicode1": 86, + "unicode2": 121, + "advance": -0.037109375 + }, + { + "unicode1": 87, + "unicode2": 44, + "advance": -0.05517578125 + }, + { + "unicode1": 87, + "unicode2": 45, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 46, + "advance": -0.05517578125 + }, + { + "unicode1": 87, + "unicode2": 58, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 59, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 65, + "advance": -0.037109375 + }, + { + "unicode1": 87, + "unicode2": 97, + "advance": -0.037109375 + }, + { + "unicode1": 87, + "unicode2": 101, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 111, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 114, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 117, + "advance": -0.01806640625 + }, + { + "unicode1": 87, + "unicode2": 121, + "advance": -0.0087890625 + }, + { + "unicode1": 89, + "unicode2": 32, + "advance": -0.01806640625 + }, + { + "unicode1": 89, + "unicode2": 44, + "advance": -0.12890625 + }, + { + "unicode1": 89, + "unicode2": 45, + "advance": -0.091796875 + }, + { + "unicode1": 89, + "unicode2": 46, + "advance": -0.12890625 + }, + { + "unicode1": 89, + "unicode2": 58, + "advance": -0.05517578125 + }, + { + "unicode1": 89, + "unicode2": 59, + "advance": -0.06494140625 + }, + { + "unicode1": 89, + "unicode2": 65, + "advance": -0.07421875 + }, + { + "unicode1": 89, + "unicode2": 97, + "advance": -0.07421875 + }, + { + "unicode1": 89, + "unicode2": 101, + "advance": -0.091796875 + }, + { + "unicode1": 89, + "unicode2": 105, + "advance": -0.037109375 + }, + { + "unicode1": 89, + "unicode2": 111, + "advance": -0.091796875 + }, + { + "unicode1": 89, + "unicode2": 112, + "advance": -0.07421875 + }, + { + "unicode1": 89, + "unicode2": 113, + "advance": -0.091796875 + }, + { + "unicode1": 89, + "unicode2": 117, + "advance": -0.05517578125 + }, + { + "unicode1": 89, + "unicode2": 118, + "advance": -0.05517578125 + }, + { + "unicode1": 102, + "unicode2": 102, + "advance": -0.01806640625 + }, + { + "unicode1": 114, + "unicode2": 44, + "advance": -0.05517578125 + }, + { + "unicode1": 114, + "unicode2": 46, + "advance": -0.05517578125 + }, + { + "unicode1": 118, + "unicode2": 44, + "advance": -0.07421875 + }, + { + "unicode1": 118, + "unicode2": 46, + "advance": -0.07421875 + }, + { + "unicode1": 119, + "unicode2": 44, + "advance": -0.05517578125 + }, + { + "unicode1": 119, + "unicode2": 46, + "advance": -0.05517578125 + }, + { + "unicode1": 121, + "unicode2": 44, + "advance": -0.07421875 + }, + { + "unicode1": 121, + "unicode2": 46, + "advance": -0.07421875 + } + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.png b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.png new file mode 100644 index 0000000..21349df Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.png differ diff --git a/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.ttf b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.ttf new file mode 100644 index 0000000..12cc15c Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/fonts/Arial/arial.ttf differ diff --git a/CosmicEngine/src/main/resources/assets/icons/spaceEngine.png b/CosmicEngine/src/main/resources/assets/icons/spaceEngine.png new file mode 100644 index 0000000..a7208a1 Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/icons/spaceEngine.png differ diff --git a/CosmicEngine/src/main/resources/assets/models/2D/rectangle.json b/CosmicEngine/src/main/resources/assets/models/2D/rectangle.json new file mode 100644 index 0000000..11efcd3 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/models/2D/rectangle.json @@ -0,0 +1,19 @@ +{ + "meshes": [ + { + "vertices": [ + { "x": -0.5, "y": -0.5, "u": 0.0, "v": 0.0, "r": 1.0, "g": 1.0, "b": 1.0, "a": 1.0 }, + { "x": 0.5, "y": -0.5, "u": 1.0, "v": 0.0, "r": 1.0, "g": 1.0, "b": 1.0, "a": 1.0 }, + { "x": 0.5, "y": 0.5, "u": 1.0, "v": 1.0, "r": 1.0, "g": 1.0, "b": 1.0, "a": 1.0 }, + { "x": -0.5, "y": 0.5, "u": 0.0, "v": 1.0, "r": 1.0, "g": 1.0, "b": 1.0, "a": 1.0 } + ], + "indices": [0, 1, 2, 2, 3, 0], + "material": { + "material": { + "color": { "r": 0.0, "g": 0.0, "b": 1.0, "a": 1.0 }, + "alpha_blend": false + } + } + } + ] +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/models/3D/cube.glb b/CosmicEngine/src/main/resources/assets/models/3D/cube.glb new file mode 100644 index 0000000..982581a Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/models/3D/cube.glb differ diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/spv/triangle.spv b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/triangle.spv new file mode 100644 index 0000000..dda18a0 Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/triangle.spv differ diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui.spv b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui.spv new file mode 100644 index 0000000..7e74757 Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui.spv differ diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui_text.spv b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui_text.spv new file mode 100644 index 0000000..c57a998 Binary files /dev/null and b/CosmicEngine/src/main/resources/assets/shaders/slang/spv/ui_text.spv differ diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/triangle.slang b/CosmicEngine/src/main/resources/assets/shaders/slang/triangle.slang new file mode 100644 index 0000000..28918d0 --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/shaders/slang/triangle.slang @@ -0,0 +1,188 @@ +struct VSInput { + [[vk::location(0)]] float3 inPosition; + [[vk::location(1)]] float4 inColor; + [[vk::location(2)]] float3 inNormal; + [[vk::location(3)]] float2 inUV; + [[vk::location(4)]] float3 inTangent; + [[vk::location(5)]] float3 inBitangent; +}; + +struct VSOutput +{ + float4 pos : SV_Position; + float4 color : COLOR; + float2 uv : TEXCOORD0; + float3 normal : NORMAL; + float3 fragPos : TEXCOORD1; // position monde + float3 viewPos : TEXCOORD2; // position caméra +}; + +// set 0 - Camera +struct CameraUBO { + float4x4 view; + float4x4 projection; +}; +[[vk::binding(0, 0)]] ConstantBuffer camera; + +// set 1 - Transform +struct TransformUBO { + float4x4 model; +}; +[[vk::binding(0, 1)]] ConstantBuffer transform; + +// set 2 - Material +[[vk::binding(1, 2)]] Sampler2D albedoTexture; // texture + sampler combinés, pas de warning +[[vk::binding(2, 2)]] Sampler2D normalTexture; // deuxième texture si besoin + +struct LightData { + float4 position; // w = type + float4 direction; // w = range + float4 color; // w = intensity + float innerCosAngle; + float outerCosAngle; + float attenuation; + float padding; +}; + +struct LightsBuffer { + LightData lights[32]; + int lightCount; +}; + +[[vk::binding(0, 3)]] StructuredBuffer lightsBuffer; + +[shader("vertex")] +VSOutput vertMain(VSInput input) { + VSOutput output; + + float4x4 modelMatrix = transform.model; + float4 worldPos = mul(modelMatrix, float4(input.inPosition, 1.0)); + output.pos = mul(camera.projection, mul(camera.view, worldPos)); + output.color = input.inColor; + output.uv = input.inUV; + + // Pour une mise à l'échelle uniforme, on peut utiliser directement la matrice 3x3 + float3x3 normalMatrix = (float3x3)modelMatrix; + // Si mises à l'échelle non-uniforme : + // float3x3 normalMatrix = transpose(inverse((float3x3)modelMatrix)); + + output.normal = normalize(mul(normalMatrix, input.inNormal)); + output.fragPos = worldPos.xyz; + + // Position de la caméra dans le monde + float3x3 R = (float3x3)camera.view; + output.viewPos = -mul(transpose(R), camera.view[3].xyz); + + return output; +} + +float3 computeDirectional(LightData light, VSOutput vertIn) +{ + // Normaliser la normale (l'interpolation peut la dénormaliser) + float3 normal = normalize(vertIn.normal); + + // Direction de la lumière (utiliser les données de la lumière) + float3 lightDir = normalize(-light.direction.xyz); + + // Direction de la vue + float3 viewDir = normalize(vertIn.viewPos - vertIn.fragPos); + + // Diffuse (Lambertian) + float diff = max(dot(normal, lightDir), 0.0); + float3 diffuse = diff * light.color.xyz * light.color.w; + + // Specular (Blinn-Phong) + float3 halfVec = normalize(lightDir + viewDir); + float spec = pow(max(dot(normal, halfVec), 0.0), 32.0); + float3 specular = spec * light.color.xyz * light.color.w * 0.5; + + // Retourner la somme + return (diffuse + specular) * light.attenuation; +} + +float3 computePoint(LightData light, VSOutput vertIn) +{ + float3 normal = normalize(vertIn.normal); + float3 viewDir = normalize(vertIn.viewPos - vertIn.fragPos); + + // Direction de la lumière (du point lumineux vers le fragment) + float3 lightDir = normalize(light.position.xyz - vertIn.fragPos); + + // Distance pour l'atténuation + float distance = length(light.position.xyz - vertIn.fragPos); + float attenuation = 1.0 / (1.0 + light.attenuation * distance * distance); + + // Diffuse + float diff = max(dot(normal, lightDir), 0.0); + float3 diffuse = diff * light.color.xyz * light.color.w; + + // Specular + float3 halfVec = normalize(lightDir + viewDir); + float spec = pow(max(dot(normal, halfVec), 0.0), 32.0); + float3 specular = spec * light.color.xyz * light.color.w * 0.5; + + return (diffuse + specular) * attenuation; +} + +float3 computeSpot(LightData light, VSOutput vertIn) +{ + float3 normal = normalize(vertIn.normal); + float3 viewDir = normalize(vertIn.viewPos - vertIn.fragPos); + + // Direction du fragment vers la lumière + float3 lightDir = normalize(light.position.xyz - vertIn.fragPos); + + // Distance et atténuation + float distance = length(light.position.xyz - vertIn.fragPos); + float attenuation = 1.0 / (1.0 + light.attenuation * distance * distance); + + // Spot light (cosinus de l'angle entre la direction du spot et la direction vers le fragment) + float cosAngle = dot(-light.direction.xyz, lightDir); + float spotFactor = smoothstep(light.outerCosAngle, light.innerCosAngle, cosAngle); + + // Diffuse + float diff = max(dot(normal, lightDir), 0.0); + float3 diffuse = diff * light.color.xyz * light.color.w; + + // Specular + float3 halfVec = normalize(lightDir + viewDir); + float spec = pow(max(dot(normal, halfVec), 0.0), 32.0); + float3 specular = spec * light.color.xyz * light.color.w * 0.5; + + return (diffuse + specular) * attenuation * spotFactor; +} + +[shader("fragment")] +float4 fragMain(VSOutput vertIn) : SV_Target { + // Sample textures + float3 albedo = albedoTexture.Sample(vertIn.uv).rgb; + + // Ambient + float3 ambient = 0.03 * albedo; + + // Lighting accumulé + float3 lighting = float3(0.0, 0.0, 0.0); + + // Récupérer les lumières + LightsBuffer lb = lightsBuffer[0]; + + for (int i = 0; i < lb.lightCount; i++) { + LightData light = lb.lights[i]; + int lightType = (int)light.position.w; + + if (lightType == 0) + lighting += computeDirectional(light, vertIn); + else if (lightType == 1) + lighting += computePoint(light, vertIn); + else if (lightType == 2) + lighting += computeSpot(light, vertIn); + } + + // Résultat final + float3 finalColor = (ambient + lighting) * albedo; + + // Tone mapping simple (optionnel) + // finalColor = finalColor / (finalColor + 1.0); + + return float4(finalColor, 1.0); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/ui.slang b/CosmicEngine/src/main/resources/assets/shaders/slang/ui.slang new file mode 100644 index 0000000..a17821b --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/shaders/slang/ui.slang @@ -0,0 +1,59 @@ +// ===================================================== +// UI Shader pour CosmicCore +// Set 0 : Transform (UBO - par objet) +// Set 1 : Material (UBO + Texture) +// Set 2 : Projection (UBO - global) +// ===================================================== + +// ─── Inputs ──────────────────────────────────────────── +struct VSInput { + [[vk::location(0)]] float2 inPosition; + [[vk::location(1)]] float2 inUV; + [[vk::location(2)]] float4 inColor; +}; + +// ─── Outputs ─────────────────────────────────────────── +struct VSOutput { + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : COLOR; +}; + +// ─── Set 0 : Transform (UBO par objet) ───────────────── +struct TransformUBO { + float4x4 model; + float2 size; + float zOrder; + float padding; +}; + +[[vk::binding(0, 0)]] ConstantBuffer transform; + +[[vk::binding(1, 1)]] Sampler2D uiTexture; + +// ─── Set 2 : Projection (UBO global) ────────────────── +[[vk::binding(0, 2)]] ConstantBuffer projection; + +// ─── Vertex Shader ────────────────────────────────────── +[shader("vertex")] +VSOutput vertMain(VSInput input) { + VSOutput output; + + // Transforme local vers monde + float4 worldPos = mul(transform.model, float4(input.inPosition, 0.0, 1.0)); + + // Applique la projection + output.pos = mul(projection, worldPos); + output.pos.z = 0.0; + output.uv = input.inUV; + output.color = input.inColor; + + return output; +} + +// ─── Fragment Shader ──────────────────────────────────── +[shader("fragment")] +float4 fragMain(VSOutput vertIn) : SV_Target { + float4 texColor = uiTexture.Sample(vertIn.uv); + return float4(1.0, 0.0, 0.0, 1.0);//vertIn.color * texColor; +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/assets/shaders/slang/ui_text.slang b/CosmicEngine/src/main/resources/assets/shaders/slang/ui_text.slang new file mode 100644 index 0000000..a53c84b --- /dev/null +++ b/CosmicEngine/src/main/resources/assets/shaders/slang/ui_text.slang @@ -0,0 +1,71 @@ +// ===================================================== +// UI Shader pour CosmicCore +// Set 0 : Transform (UBO - par objet) +// Set 1 : Material (UBO + Texture) +// Set 2 : Projection (UBO - global) +// ===================================================== + +// ─── Inputs ──────────────────────────────────────────── +struct VSInput { + [[vk::location(0)]] float2 inPosition; + [[vk::location(1)]] float2 inUV; + [[vk::location(2)]] float4 inColor; +}; + +// ─── Outputs ─────────────────────────────────────────── +struct VSOutput { + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : COLOR; +}; + +// ─── Set 0 : Transform (UBO par objet) ───────────────── +struct TransformUBO { + float4x4 model; + float2 size; + float zOrder; + float padding; +}; + +[[vk::binding(0, 0)]] ConstantBuffer transform; + +[[vk::binding(1, 1)]] Sampler2D uiTexture; + +// ─── Set 2 : Projection (UBO global) ────────────────── +[[vk::binding(0, 2)]] ConstantBuffer projection; + +// ─── Vertex Shader ────────────────────────────────────── +[shader("vertex")] +VSOutput vertMain(VSInput input) { + VSOutput output; + + // Transforme local vers monde + float4 worldPos = mul(transform.model, float4(input.inPosition, 0.0, 1.0)); + + // Applique la projection + output.pos = mul(projection, worldPos); + output.pos.z = 0.0; + output.uv = input.inUV; + output.color = input.inColor; + + return output; +} + +float median(float r, float g, float b) { + return max(min(r, g), min(max(r, g), b)); +} + +[shader("fragment")] +float4 fragMain(VSOutput vertIn) : SV_Target { + float3 msd = uiTexture.Sample(vertIn.uv).rgb; + float sigDist = median(msd.r, msd.g, msd.b) - 0.5; + + // largeur du dégradé en pixels écran (anti-aliasing correct) + float2 unitRange = float2(1.0, 1.0) / float2(212.0, 212.0); + float2 screenTexSize = 1.0 / fwidth(vertIn.uv); + float screenPxRange = max(0.5 * dot(unitRange, screenTexSize), 1.0); + + float opacity = clamp(screenPxRange * sigDist + 0.5, 0.0, 1.0); + + return float4(vertIn.color.rgb, vertIn.color.a * opacity); +} \ No newline at end of file diff --git a/CosmicEngine/src/main/resources/schema_json.json b/CosmicEngine/src/main/resources/schema_json.json new file mode 100644 index 0000000..e8bb365 --- /dev/null +++ b/CosmicEngine/src/main/resources/schema_json.json @@ -0,0 +1,276 @@ +{ + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "name": { "type": "string", "ID": 101}, + "description": { "type": "string", "ID": 102}, + "entities": { + "type": "array", + "ID": 103, + "items": { "$ref": "#/definitions/Entity" } + }, + "entities2D": { + "type": "array", + "ID": 104, + "items": { "$ref": "#/definitions/Entity2D" } + } + }, + "required": ["name", "entities"], + "definitions": { + + "Entity": { + "type": "object", + "properties": { + "entityref": { "type": "integer", "ID": 201 }, + "parent": { "type": ["integer", "null"] , "ID": 202}, + "name": { "type": "string", "ID": 203 }, + "description": { "type": "string", "ID": 204 }, + "children": { + "type": "array", + "ID": 205, + "items": { "type": "integer" } + }, + "components": { "ID": 206, "$ref": "#/definitions/Components" } + }, + "required": ["entityref", "name", "components"] + }, + + "Entity2D": { + "type": "object", + "properties": { + "entityref": { "type": "integer", "ID": 207 }, + "parent": { "type": ["integer", "null"] , "ID": 202}, + "name": { "type": "string", "ID": 208 }, + "description": { "type": "string", "ID": 209}, + "children": { + "type": "array", + "ID": 205, + "items": { "type": "integer" } + }, + "components": { "ID": 210, "$ref": "#/definitions/Components2D" } + }, + "required": ["entityref", "name", "components"] + }, + + "Components": { + "type": "object", + "properties": { + "transform": { "ID": 2061, "$ref": "#/definitions/Transform" }, + "renderer": { "ID": 2062, "$ref": "#/definitions/Renderer" }, + "camera": { "ID": 2063, "$ref": "#/definitions/Camera" }, + "collider": { "ID": 2064, "$ref": "#/definitions/Collider" }, + "rigidbody": { "ID": 2065, "$ref": "#/definitions/RigidBody" }, + "speaker": { "ID": 2066, "$ref": "#/definitions/Speaker" }, + "script": { "ID": 2067, "$ref": "#/definitions/Script" }, + "light": { "ID": 2068, "$ref": "#/definitions/Light" } + } + }, + + "Components2D": { + "type": "object", + "properties": { + "transform": { "ID": 2069, "$ref": "#/definitions/Transform2D" }, + "renderer": { "ID": 2070, "$ref": "#/definitions/Renderer2D" }, + "camera": { "ID": 2071, "$ref": "#/definitions/Camera2D" }, + "collider": { "ID": 2072, "$ref": "#/definitions/Collider2D" }, + "text": { "ID": 2073, "$ref": "#/definitions/TextRenderer2D"}, + "script": { "ID": 2074, "$ref": "#/definitions/Script" } + } + }, + + "Vec2": { + "type": "array", + "items": { "type": "number" }, + "minItems": 2, + "maxItems": 2 + }, + + "Vec3": { + "type": "array", + "items": { "type": "number" }, + "minItems": 3, + "maxItems": 3 + }, + + "Vec4": { + "type": "array", + "items": { "type": "number" }, + "minItems": 4, + "maxItems": 4 + }, + + "Transform": { + "type": "object", + "properties": { + "position": { "ID": 3011, "$ref": "#/definitions/Vec3" }, + "rotation": { "ID": 3012, "$ref": "#/definitions/Vec3" }, + "scale": { "ID": 3013, "$ref": "#/definitions/Vec3" } + }, + "required": ["position", "rotation", "scale"] + }, + + "Transform2D": { + "type": "object", + "properties": { + "position": { "ID": 4011, "$ref": "#/definitions/Vec2" }, + "rotation": { "ID": 4012, "type": "number" }, + "scale": { "ID": 4013, "$ref": "#/definitions/Vec2" }, + "size": { "ID": 4014, "$ref": "#/definitions/Vec2" }, + "pivot": { "ID": 4015, "$ref": "#/definitions/Vec2" }, + "anchor": { "ID": 4018, "$ref": "#/definitions/Vec2" }, + "zorder": { "ID": 4016, "type": "integer", "minimum": 0 }, + "visible": { "ID": 4017, "type": "boolean" } + }, + "required": ["position", "size"] + }, + + "Renderer": { + "type": ["object", "null"], + "properties": { + "model": { "type": ["string", "null"], "ID": 3021 }, + "shader": { "type": "string", "ID": 3022 }, + "albedo": { "type": ["string", "null"], "ID": 3023 } + }, + "required": ["model", "shader"] + }, + + "Renderer2D": { + "type": ["object", "null"], + "properties": { + "model": { "type": "string", "ID": 4021 }, + "shader": { "type": "string", "ID": 4022 } + }, + "required": ["model", "shader"] + }, + + "TextRenderer2D": { + "type": ["object", "null"], + "properties": { + "text": { "type": "string", "ID": 4051 }, + "shader": { "type": "string", "ID": 4052 }, + "color": { "$ref": "#/definitions/Vec4", "ID": 4053}, + "font": { "type": "string", "ID": 4054} + }, + "required": ["text", "shader", "color", "font"] + }, + + "Camera": { + "type": ["object", "null"], + "properties": { + "fov": { "type": "number", "minimum": 1, "maximum": 179, "ID": 3031 }, + "near": { "type": "number", "minimum": 0.001, "ID": 3032 }, + "far": { "type": "number", "minimum": 0.1, "ID": 3033 } + }, + "required": ["fov", "near", "far"] + }, + + "Camera2D": { + "type": ["object", "null"], + "properties": { + "zoom": { "type": "number", "minimum": 1.0, "ID": 4031 } + }, + "required": ["zoom"] + }, + + "Collider": { + "type": ["object", "null"], + "properties": { + "type": { + "type": "integer", + "ID": 3041, + "enum": [0,1,2,3,4,5] + }, + "size": { "$ref": "#/definitions/Vec3", "ID": 3042 }, + "radius": { "type": "number", "minimum": 0, "ID": 3043 }, + "halfHeight": { "type": "number", "minimum": 0, "ID": 3044 } + }, + "required": ["type"], + "allOf": [ + { + "if": { "properties": { "type": { "const": 0 } } }, + "then": { "required": ["size"] } + }, + { + "if": { "properties": { "type": { "const": 1 } } }, + "then": { "required": ["radius"] } + }, + { + "if": { "properties": { "type": { "const": 2 } } }, + "then": { "required": ["radius", "halfHeight"] } + } + ] + }, + + "Collider2D": { + "type": ["object", "null"], + "properties": { + "type": { + "type": "integer", + "ID": 4041, + "enum": [0,1,2,3] + } + }, + "required": ["type"] + }, + + "RigidBody": { + "type": ["object", "null"], + "properties": { + "type": { + "type": "integer", + "ID": 3051, + "enum": [0,1,2] + }, + "mass": { "type": "number", "minimum": 0, "ID": 3052 }, + "friction": { "type": "number", "minimum": 0, "maximum": 1, "ID": 3053 }, + "restitution": { "type": "number", "minimum": 0, "maximum": 1, "ID": 3054 } + }, + "required": ["type"] + }, + + "Speaker": { + "type": ["object", "null"], + "properties": { + "clips": { + "type": "array", + "ID": 3061, + "items": { + "type": "object", + "properties": { + "path": { "type": "string", "ID": 30611 }, + "gain": { "type": "number", "minimum": 0, "ID": 30612 }, + "pitch": { "type": "number", "minimum": 0, "ID": 30613 }, + "loop": { "type": "boolean", "ID": 30614 }, + "spatial": { "type": "boolean", "ID": 30615 } + }, + "required": ["path"] + }} + }, + "required": ["clips"] + }, + + "Light": { + "type": ["object", "null"], + "properties": { + "type": { + "type": "integer", + "ID": 3071, + "enum": [0,1,2] + }, + "color": { "$ref": "#/definitions/Vec3", "ID": 3072 }, + "intensity": { "type": "number", "minimum": 0, "ID": 3073 }, + "range": { "type": "number", "minimum": 0, "ID": 3074 }, + "attenuation": { "type": "number", "minimum": 0, "ID": 3075 }, + "innerangle": { "type": "number", "minimum": 0, "ID": 3076 }, + "outerangle": { "type": "number", "minimum": 0, "ID": 3077 }, + "castshadow": { "type": "boolean", "ID": 3078 } + }, + "required": ["type", "color", "intensity", "range", "attenuation", "innerangle", "outerangle", "castshadow"] + }, + + "Script": { + "type": "array", + "items": {"type" : "string", "ID": 3079} + } + } +} diff --git a/ScriptsModule/build.gradle b/ScriptsModule/build.gradle new file mode 100644 index 0000000..3d8c040 --- /dev/null +++ b/ScriptsModule/build.gradle @@ -0,0 +1,12 @@ +plugins { id 'cpp-library' } +apply from: rootProject.file('gradle/common.gradle') + +library { + baseName = 'ScriptsModule' + linkage = [Linkage.SHARED] + targetMachines.add(machines.windows.x86_64) + targetMachines.add(machines.linux.x86_64) + source.setFrom('src/main') + privateHeaders.setFrom('src/main') + dependencies { implementation project(':CosmicEngine') } +} \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/CScriptRegister.cpp b/ScriptsModule/src/main/Scripts/CScriptRegister.cpp new file mode 100644 index 0000000..ff8e3bc --- /dev/null +++ b/ScriptsModule/src/main/Scripts/CScriptRegister.cpp @@ -0,0 +1,21 @@ +#include "CScriptRegister.hpp" +#include + +std::vector& CScriptRegister::getRegistrars() { + static std::vector registrars; + return registrars; +} + +void CScriptRegister::addScriptRegistrar(ScriptRegisterFunc func) { + getRegistrars().push_back(func); +} + +void CScriptRegister::registerAllScripts(CScriptRegistry* reg) { + for (auto& registrar : getRegistrars()) { + registrar(reg); + } +} + +extern "C" void registerAllScripts(CScriptRegistry* reg) { + CScriptRegister::registerAllScripts(reg); +} \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/CScriptRegister.hpp b/ScriptsModule/src/main/Scripts/CScriptRegister.hpp new file mode 100644 index 0000000..b9997eb --- /dev/null +++ b/ScriptsModule/src/main/Scripts/CScriptRegister.hpp @@ -0,0 +1,56 @@ +#ifndef CSCRIPTREGISTER_HPP +#define CSCRIPTREGISTER_HPP + +// Forward declarations des types de l'Engine +#include "Engine/Core/Systems/Scripts/CScriptRegistry.hpp" +#include +namespace CosmicEngine { + class CAbstractScript; + class CEntity; +} + +// Définition des macros d'exportation +#ifdef _WIN32 + #ifdef SCRIPT_MODULE_EXPORTS + #define SCRIPT_API __declspec(dllexport) + #else + #define SCRIPT_API __declspec(dllimport) + #endif +#else + #define SCRIPT_API __attribute__((visibility("default"))) +#endif + +// Type de fonction d'enregistrement +using ScriptRegisterFunc = std::function; + +class SCRIPT_API CScriptRegister +{ + public: + // Point d'entrée que l'Engine appellera + static void registerAllScripts(CScriptRegistry* reg); + // Macro pour enregistrer un script automatiquement + static void addScriptRegistrar(ScriptRegisterFunc func); + + private: + static std::vector& getRegistrars(); +}; + +extern "C" { + SCRIPT_API void registerAllScripts(CScriptRegistry* reg); +} + +// Macro à utiliser dans chaque script .cpp +#define REGISTER_SCRIPT(ClassName) \ + namespace { \ + struct ClassName##_AutoReg { \ + ClassName##_AutoReg() { \ + CScriptRegister::addScriptRegistrar([](CScriptRegistry* reg) { \ + reg->registerScript(#ClassName); \ + }); \ + } \ + }; \ + static ClassName##_AutoReg className##_autoReg; \ + } + +#endif + diff --git a/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.cpp b/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.cpp new file mode 100644 index 0000000..ecd0eac --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.cpp @@ -0,0 +1,67 @@ +#include "CExampleScript.hpp" +#include "nlohmann/json_fwd.hpp" +#include "Scripts/CScriptRegister.hpp" +#include + +#include "Engine/Core/Component/Input/CInputManager.hpp" + +#include "Engine/Core/Component/Geometry/CTransform.hpp" + +void CExampleScript::start() +{ + std::cout << "Hello example script" << std::endl; +} + +void CExampleScript::onCreate() +{ + using namespace CosmicCore; + auto& reg = getEntity().getRegistry().registry; + + // vérifie que l'entité a un CInputComponent + if (!reg.all_of(getEntity().getHandle())) + reg.emplace(getEntity().getHandle(), getEntity()); + + auto& input = reg.get(getEntity().getHandle()); + + // bind les actions depuis le script + input.onHeld("MoveForward", [](CEntity& e) { + e.getRegistry().registry.get(e.getHandle()) + .forward({0, 0, -0.05f}); + }); + + input.onHeld("MoveBackward", [](CEntity& e) { + e.getRegistry().registry.get(e.getHandle()) + .forward({0, 0, 0.05f}); + }); + + input.addOnMouseMove([](CEntity& e, glm::vec2 delta) { + auto& tr = e.getRegistry().registry.get(e.getHandle()); + float sensitivity = 0.3f; + glm::quat yaw = glm::angleAxis( + glm::radians(-delta.x * sensitivity), glm::vec3(0,1,0)); + glm::quat pitch = glm::angleAxis( + glm::radians(-delta.y * sensitivity), glm::vec3(1,0,0)); + tr.setQuaternion(yaw * tr.getOrientation() * pitch); + }); +} + +void CExampleScript::update() +{ + +} + +void CExampleScript::destroy() +{ + +} + +nlohmann::json CExampleScript::to_json() +{ + return nlohmann::json(); +} + +CExampleScript::~CExampleScript(){ + +} + +REGISTER_SCRIPT(CExampleScript); \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.hpp b/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.hpp new file mode 100644 index 0000000..c9a26a6 --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/CExampleScript.hpp @@ -0,0 +1,18 @@ +#ifndef CEXAMPLESCRIPT_HPP +#define CEXAMPLESCRIPT_HPP +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Component/Script/CAbstractScript.hpp" + +class CExampleScript : public CosmicCore::CAbstractScript +{ + public: + CExampleScript(CosmicCore::CEntity& entity, std::string name): CosmicCore::CAbstractScript(entity, name){}; + void start() override; + void update() override; + void destroy() override; + void onCreate() override; + virtual nlohmann::json to_json() override; + virtual ~CExampleScript(); +}; + +#endif \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.cpp b/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.cpp new file mode 100644 index 0000000..5a37ceb --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.cpp @@ -0,0 +1,58 @@ +#include "LaunchSceneTest.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Kernel/CKernel.hpp" +#include "nlohmann/json_fwd.hpp" +#include "Scripts/CScriptRegister.hpp" +#include +#include + +#include "Engine/Core/Component/Input/CInputManager.hpp" +#include "Engine/Core/Component/Geometry/CTransform.hpp" +void LaunchSceneTest::start() +{ +} + +void LaunchSceneTest::onCreate() +{ + using namespace CosmicCore; + auto& reg = getEntity().getRegistry().registry; + // vérifie que l'entité a un CInputComponent + if (!reg.all_of(getEntity().getHandle())) + reg.emplace(getEntity().getHandle(), getEntity()); + + auto& input = reg.get(getEntity().getHandle()); + + // bind les actions depuis le script + input.addOnGenericMouseLeftClick([](CEntity& entity){ + + auto& collider = entity.getRegistry().registry.get(entity.getHandle()); + + if(collider.shapeContains(CInputDispatcher::mousePosition())) + { + CosmicCore::CKernelBase::instance()->loadScene("assets/scenes/scene_test.json"); + } + + }); + +} + +void LaunchSceneTest::update() +{ + +} + +void LaunchSceneTest::destroy() +{ + +} + +nlohmann::json LaunchSceneTest::to_json() +{ + return nlohmann::json(); +} + +LaunchSceneTest::~LaunchSceneTest(){ + +} + +REGISTER_SCRIPT(LaunchSceneTest); \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.hpp b/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.hpp new file mode 100644 index 0000000..8d50b08 --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/LaunchSceneTest.hpp @@ -0,0 +1,18 @@ +#ifndef LAUNCHSCENETEST_HPP +#define LAUNCHSCENETEST_HPP +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Component/Script/CAbstractScript.hpp" + +class LaunchSceneTest : public CosmicCore::CAbstractScript +{ + public: + LaunchSceneTest(CosmicCore::CEntity& entity, std::string name): CosmicCore::CAbstractScript(entity, name){}; + void start() override; + void update() override; + void destroy() override; + void onCreate() override; + virtual nlohmann::json to_json() override; + virtual ~LaunchSceneTest(); +}; + +#endif \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.cpp b/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.cpp new file mode 100644 index 0000000..4107b5d --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.cpp @@ -0,0 +1,58 @@ +#include "QuitHandler.hpp" +#include "Engine/Core/Component/Collider/CCollider2D.hpp" +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Kernel/CKernel.hpp" +#include "Engine/Core/Systems/Input/CInputDispatcher.hpp" +#include "nlohmann/json_fwd.hpp" +#include "Scripts/CScriptRegister.hpp" +#include +#include + +#include "Engine/Core/Component/Input/CInputManager.hpp" +#include "Engine/Core/Component/Geometry/CTransform.hpp" +void QuitHandler::start() +{ +} + +void QuitHandler::onCreate() +{ + using namespace CosmicCore; + auto& reg = getEntity().getRegistry().registry; + // vérifie que l'entité a un CInputComponent + if (!reg.all_of(getEntity().getHandle())) + reg.emplace(getEntity().getHandle(), getEntity()); + + auto& input = reg.get(getEntity().getHandle()); + + // bind les actions depuis le script + input.addOnGenericMouseLeftClick([](CEntity& entity){ + auto& collider = entity.getRegistry().registry.get(entity.getHandle()); + + if(collider.shapeContains(CInputDispatcher::mousePosition())) + { + kill(getpid(), SIGTERM); + } + }); + +} + +void QuitHandler::update() +{ + +} + +void QuitHandler::destroy() +{ + +} + +nlohmann::json QuitHandler::to_json() +{ + return nlohmann::json(); +} + +QuitHandler::~QuitHandler(){ + +} + +REGISTER_SCRIPT(QuitHandler); \ No newline at end of file diff --git a/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.hpp b/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.hpp new file mode 100644 index 0000000..970df7b --- /dev/null +++ b/ScriptsModule/src/main/Scripts/UserScripts/QuitHandler.hpp @@ -0,0 +1,18 @@ +#ifndef QUITHANDLER_HPP +#define QUITHANDLER_HPP +#include "Engine/Core/Entity/CEntity.hpp" +#include "Engine/Core/Component/Script/CAbstractScript.hpp" + +class QuitHandler : public CosmicCore::CAbstractScript +{ + public: + QuitHandler(CosmicCore::CEntity& entity, std::string name): CosmicCore::CAbstractScript(entity, name){}; + void start() override; + void update() override; + void destroy() override; + void onCreate() override; + virtual nlohmann::json to_json() override; + virtual ~QuitHandler(); +}; + +#endif \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..b42d454 --- /dev/null +++ b/build.gradle @@ -0,0 +1,90 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This is a general purpose Gradle build. + * Learn more about Gradle by exploring our Samples at https://docs.gradle.org/9.9.0/samples + */ +plugins { + id("org.ysb33r.doxygen") version "3.0.0" +} + +def isWindows = org.gradle.internal.os.OperatingSystem.current().isWindows() + +/** + * Récupération du triplet vcpkg (x64-windows, x64-linux…). + */ +def triplet = project.findProperty('vcpkg.triplet') ?: 'x64-windows' + +def assetDir = file("CosmicEngine/src/main/resources") + +/** + * Répertoires générés par vcpkg. + */ +def includeDir = file("./vcpkg_installed/${triplet}/include") +def libDir = file("./vcpkg_installed/${triplet}/lib") +def binDir = file("./vcpkg_installed/${triplet}/bin") + +// DLL (Windows: bin/) ou SO (Linux: lib/) à copier à côté de l'exécutable. +def runtimeDir = isWindows ? binDir : libDir + +// Fichier de réponse généré APRÈS l'install vcpkg (liste des libs à lier). +def rspFile = layout.buildDirectory.file('vcpkg/libs.rsp').get().asFile + +// Partagé avec les sous-projets (CosmicEngine, Scripts, App). +ext.vcpkgInclude = includeDir +ext.vcpkgLibDir = libDir +ext.vcpkgRsp = rspFile +ext.runtimeDir = runtimeDir +ext.assetDir = assetDir + +def vcpkgRoot = file('vcpkg') +def vcpkgExe = new File(vcpkgRoot, isWindows ? 'vcpkg.exe' : 'vcpkg') +def tripletsDir = file('vcpkg/triplets') // pour les triplets custom (x64-linux-dynamic, x64-clang-dynamic...) si jamais + +/** + * Tâche "vcpkg" – lance vcpkg. + */ +tasks.register('vcpkg', Exec) { + commandLine vcpkgExe.absolutePath, 'install', + '--triplet', triplet, + '--host-triplet', triplet, + "--overlay-triplets=${tripletsDir.absolutePath}" + environment 'VCPKG_ROOT', vcpkgRoot.absolutePath + workingDir '.' + description = 'Installe les dépendances via vcpkg.' + group = 'build' + + // Liste les libs installées dans un fichier @rsp lu par le linker. + doLast { + def libs = libDir.exists() ? libDir.listFiles().findAll { + it.isFile() && !it.name.contains('VkLayer') && + (it.name.endsWith('.lib') || it.name.endsWith('.a') || it.name.endsWith('.so')) + }.sort { it.name } : [] + def lines = libs.collect { '"' + it.absolutePath.replace('\\', '/') + '"' } + if (!isWindows) { + lines = ['-Wl,--as-needed', '-Wl,--start-group'] + lines + ['-Wl,--end-group'] + } + rspFile.parentFile.mkdirs() + rspFile.text = lines.join('\n') + '\n' + } +} + +/** + * Nettoyage complet (incluant vcpkg_installed). + */ +tasks.named('clean') { + delete 'vcpkg_installed' +} + +doxygen { + sourceSets { + main { + option 'generate_html', true + + sources new File(projectDir,'CosmicEngine/src/main') + } + internal { + options generate_latex: false + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0e1c111 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties + +org.gradle.configuration-cache=true +org.gradle.parallel=true +org.gradle.caching=true + +#vcpkg.triplet=x64-mingw-dynamic +vcpkg.triplet=x64-linux \ No newline at end of file diff --git a/gradle/common.gradle b/gradle/common.gradle new file mode 100644 index 0000000..d52986f --- /dev/null +++ b/gradle/common.gradle @@ -0,0 +1,5 @@ +// Réglages communs à tous les projets C++ (appliqué avec : apply from: rootProject.file('gradle/native.gradle')) +tasks.withType(CppCompile).configureEach { + dependsOn ':vcpkg' + compilerArgs.addAll('-std=c++23', '-Wall', '-DGLM_ENABLE_EXPERIMENTAL' , "-I${rootProject.ext.vcpkgInclude}") +} \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..a1a7386 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,2 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/version_catalogs.html#sec::toml-dependencies-format diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..51cbd2a Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..94c356a --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..379a658 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob//platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..3185a43 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..fa10f9e --- /dev/null +++ b/settings.gradle @@ -0,0 +1,9 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/9.9.0/userguide/multi_project_builds.html in the Gradle documentation. + */ + +rootProject.name = 'CosmicEngineWorkEnvironment' +include 'CosmicEngine', 'ScriptsModule', 'ApplicationDemo' \ No newline at end of file diff --git a/vcpkg-configuration.json b/vcpkg-configuration.json new file mode 100644 index 0000000..bfb29be --- /dev/null +++ b/vcpkg-configuration.json @@ -0,0 +1,7 @@ +{ + "default-registry": { + "kind": "git", + "baseline": "ba33ef1a2fb3c6519e819cd767bb8fd1677f1323", + "repository": "https://github.com/microsoft/vcpkg" + } +} diff --git a/vcpkg.json b/vcpkg.json new file mode 100644 index 0000000..224944c --- /dev/null +++ b/vcpkg.json @@ -0,0 +1,44 @@ +{ + "dependencies": [ + "assimp", + "drlibs", + "entt", + "glm", + { + "name": "joltphysics", + "features": [ + "debugrenderer", + "profiler" + ] + }, + "json-schema-validator", + "msdfgen", + "nlohmann-json", + { + "name": "sdl3", + "default-features": false, + "features": ["alsa", "vulkan", "wayland"] + }, + { + "name": "sdl3-image", + "default-features": false, + "features": ["avif", "jpeg", "jxl", "png", "tiff", "webp"] + }, + { + "name": "sdl3-ttf", + "default-features": false, + "features": ["harfbuzz", "svg"] + }, + "spirv-reflect", + { + "name": "vulkan-loader", + "default-features": false, + "features": ["wayland"] + }, + "vulkan", + "vulkan-memory-allocator", + "vulkan-memory-allocator-hpp", + "vulkan-validationlayers", + "gtest" + ] +}