cleaned up renderer

This commit is contained in:
Jorijn van der Graaf 2026-03-09 20:10:19 +01:00
commit d661c88ee2
58 changed files with 3030 additions and 4722 deletions

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or

View file

@ -18,13 +18,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:DescriptorPoolVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
import :Types;
import :DescriptorSetLayoutVulkan;
import Crafter.Event;
@ -155,7 +155,7 @@ export namespace Crafter {
public:
void BuildPool(std::span<const VkDescriptorPoolSize> poolSizes, std::span<const VkDescriptorSetLayout> setLayouts) {
if(descriptorPool != VK_NULL_HANDLE) {
vkDestroyDescriptorPool(VulkanDevice::device, descriptorPool, nullptr);
vkDestroyDescriptorPool(Device::device, descriptorPool, nullptr);
}
@ -166,7 +166,7 @@ export namespace Crafter {
.pPoolSizes = poolSizes.data()
};
VulkanDevice::CheckVkResult(vkCreateDescriptorPool(VulkanDevice::device, &descriptorPoolInfo, nullptr, &descriptorPool));
Device::CheckVkResult(vkCreateDescriptorPool(Device::device, &descriptorPoolInfo, nullptr, &descriptorPool));
VkDescriptorSetAllocateInfo allocInfo {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
@ -175,7 +175,7 @@ export namespace Crafter {
.pSetLayouts = setLayouts.data(),
};
VulkanDevice::CheckVkResult(vkAllocateDescriptorSets(VulkanDevice::device, &allocInfo, sets.data()));
Device::CheckVkResult(vkAllocateDescriptorSets(Device::device, &allocInfo, sets.data()));
}
};
}

View file

@ -18,13 +18,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:DescriptorSetLayoutVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
import :Types;
import Crafter.Event;
@ -39,7 +39,7 @@ export namespace Crafter {
.bindingCount = static_cast<std::uint32_t>(descriptors.size()),
.pBindings = descriptors.data()
};
VulkanDevice::CheckVkResult(vkCreateDescriptorSetLayout(VulkanDevice::device, &descriptorLayoutInfoMesh, nullptr, &layout));
Device::CheckVkResult(vkCreateDescriptorSetLayout(Device::device, &descriptorLayoutInfoMesh, nullptr, &layout));
}
};
@ -54,7 +54,7 @@ export namespace Crafter {
.bindingCount = DescriptorCount,
.pBindings = Descriptors.data()
};
VulkanDevice::CheckVkResult(vkCreateDescriptorSetLayout(VulkanDevice::device, &descriptorLayoutInfoMesh, nullptr, &layout));
Device::CheckVkResult(vkCreateDescriptorSetLayout(Device::device, &descriptorLayoutInfoMesh, nullptr, &layout));
}
};
}

View file

@ -0,0 +1,125 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#include "../lib/xdg-shell-client-protocol.h"
#include "../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
#include "../lib/fractional-scale-v1.h"
#include "../lib/viewporter.h"
#include <xkbcommon/xkbcommon.h>
#endif
export module Crafter.Graphics:Device;
import std;
export namespace Crafter {
struct Window;
struct Device {
static void Initialize();
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
inline static wl_display* display = nullptr;
inline static wl_seat* seat = nullptr;
inline static xdg_wm_base* xdgWmBase = nullptr;
inline static wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr;
inline static zxdg_decoration_manager_v1* manager = nullptr;
inline static xkb_keymap* xkb_keymap;
inline static wl_compositor* compositor = nullptr;
inline static Window* focusedWindow = nullptr;
inline static wl_shm* shm = nullptr;
inline static wp_viewporter* wpViewporter = nullptr;
inline static xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
inline static xkb_state* xkb_state;
inline static std::vector<Window*> windows;
static void seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities);
static void xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale);
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial);
static void handle_global(void* data, wl_registry* registry, std::uint32_t name, const char* interface, std::uint32_t version);
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name);
static void keyboard_keymap(void* data, wl_keyboard* keyboard, uint32_t format, int fd, uint32_t size);
static void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys);
static void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface);
static void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state);
static void keyboard_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group);
static void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay);
static void pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state);
static void PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, std::uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value);
static void PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, std::uint32_t serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleLeave(void*, wl_pointer*, std::uint32_t, wl_surface*);
constexpr static wl_pointer_listener pointer_listener = {
.enter = PointerListenerHandleEnter,
.leave = PointerListenerHandleLeave,
.motion = PointerListenerHandleMotion,
.button = pointer_handle_button,
.axis = PointerListenerHandleAxis,
};
constexpr static wl_keyboard_listener keyboard_listener = {
.keymap = keyboard_keymap,
.enter = keyboard_enter,
.leave = keyboard_leave,
.key = keyboard_key,
.modifiers = keyboard_modifiers,
.repeat_info = keyboard_repeat_info,
};
constexpr static wl_seat_listener seat_listener = {
.capabilities = seat_handle_capabilities,
};
constexpr static wl_registry_listener registry_listener = {
.global = handle_global,
.global_remove = handle_global_remove,
};
constexpr static xdg_wm_base_listener xdgWmBaseListener = {
.ping = xdg_wm_base_handle_ping,
};
#endif
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
inline static VkInstance instance = VK_NULL_HANDLE;
inline static VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
inline static VkPhysicalDevice physDevice = VK_NULL_HANDLE;
inline static VkDevice device = VK_NULL_HANDLE;
inline static std::uint32_t queueFamilyIndex = 0;
inline static VkQueue queue = VK_NULL_HANDLE;
inline static VkCommandPool commandPool = VK_NULL_HANDLE;
inline static VkSwapchainKHR swapchain = VK_NULL_HANDLE;
inline static PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR;
inline static PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR;
inline static PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR;
inline static PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddressKHR;
inline static PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR;
inline static PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR;
inline static PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR;
inline static VkPhysicalDeviceMemoryProperties memoryProperties;
inline static VkPhysicalDeviceRayTracingPipelinePropertiesKHR rayTracingProperties = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR
};
static void CheckVkResult(VkResult result);
static std::uint32_t GetMemoryType(std::uint32_t typeBits, VkMemoryPropertyFlags properties);
#endif
};
}

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
@ -19,11 +19,11 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
export module Crafter.Graphics:GridElement;
import std;
import :Transform;
import :Transform2D;
import :Types;
export namespace Crafter {
class GridElement : public Transform {
class GridElement : public Transform2D {
public:
std::uint32_t columns;
std::uint32_t rows;
@ -31,9 +31,9 @@ export namespace Crafter {
std::int32_t spacingY;
std::int32_t paddingX;
std::int32_t paddingY;
GridElement(std::uint32_t columns, std::uint32_t rows, std::int32_t spacingX, std::int32_t spacingY, std::int32_t paddingX, std::int32_t paddingY, Anchor anchor);
void UpdatePositionScaled(Window& window);
void UpdatePosition(Window& window) override;
void UpdatePosition(Window& window, Transform& parent) override;
GridElement(std::uint32_t columns, std::uint32_t rows, std::int32_t spacingX, std::int32_t spacingY, std::int32_t paddingX, std::int32_t paddingY, Anchor2D anchor);
void UpdatePositionScaled(Rendertarget& window);
void UpdatePosition(Rendertarget& window) override;
void UpdatePosition(Rendertarget& window, Transform2D& parent) override;
};
}

View file

@ -1,34 +0,0 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
export module Crafter.Graphics:Image;
import std;
import :Types;
namespace Crafter {
export struct Image {
std::vector<Pixel_BU8_GU8_RU8_AU8> buffer;
std::uint_fast32_t width;
std::uint_fast32_t height;
OpaqueType opaque;
Image(const std::string_view path);
};
}

View file

@ -19,7 +19,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 0215-1301 USA
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
@ -28,7 +28,7 @@ import std;
import :VulkanBuffer;
export namespace Crafter {
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
template <typename PixelType>
class ImageVulkan {
public:
@ -61,18 +61,18 @@ export namespace Crafter {
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VulkanDevice::CheckVkResult(vkCreateImage(VulkanDevice::device, &imageInfo, nullptr, &image));
Device::CheckVkResult(vkCreateImage(Device::device, &imageInfo, nullptr, &image));
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(VulkanDevice::device, image, &memRequirements);
vkGetImageMemoryRequirements(Device::device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = VulkanDevice::GetMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
allocInfo.memoryTypeIndex = Device::GetMemoryType(memRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VulkanDevice::CheckVkResult(vkAllocateMemory(VulkanDevice::device, &allocInfo, nullptr, &imageMemory));
vkBindImageMemory(VulkanDevice::device, image, imageMemory, 0);
Device::CheckVkResult(vkAllocateMemory(Device::device, &allocInfo, nullptr, &imageMemory));
vkBindImageMemory(Device::device, image, imageMemory, 0);
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
@ -85,7 +85,7 @@ export namespace Crafter {
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VulkanDevice::CheckVkResult(vkCreateImageView(VulkanDevice::device, &viewInfo, nullptr, &imageView));
Device::CheckVkResult(vkCreateImageView(Device::device, &viewInfo, nullptr, &imageView));
// Final transition to shader read-only layout
TransitionImageLayout(cmd, image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 0, 5);

View file

@ -19,7 +19,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
@ -29,8 +29,7 @@ import Crafter.Math;
import :VulkanBuffer;
export namespace Crafter {
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
class Mesh {
public:
VulkanBuffer<char, false, true, false> scratchBuffer;

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
@ -21,29 +21,24 @@ export module Crafter.Graphics:MouseElement;
import std;
import Crafter.Event;
import :Types;
import :Transform;
import :Transform2D;
export namespace Crafter {
class Window;
class WindowMouse;
class MouseElement : public Transform {
public:
Event<MouseMoveEvent> onMouseMove;
Event<MouseMoveEvent> onMouseEnter;
Event<MouseMoveEvent> onMouseLeave;
Event<MousePoint> onMouseRightClick;
Event<MousePoint> onMouseLeftClick;
Event<MousePoint> onMouseRightHold;
Event<MousePoint> onMouseLeftHold;
Event<MousePoint> onMouseRightRelease;
Event<MousePoint> onMouseLeftRelease;
ScaleDataBoundless mouseScaled;
struct MouseElement : Transform2D {
Event<void> onMouseMove;
Event<void> onMouseEnter;
Event<void> onMouseLeave;
Event<void> onMouseRightClick;
Event<void> onMouseLeftClick;
Event<void> onMouseRightHold;
Event<void> onMouseLeftHold;
Event<void> onMouseRightRelease;
Event<void> onMouseLeftRelease;
MouseElement();
MouseElement(WindowMouse& window);
MouseElement(Anchor anchor);
MouseElement(Anchor anchor, WindowMouse& window);
void UpdatePosition(Window& window) override;
void UpdatePosition(Window& window, Transform& parent) override;
MouseElement(Window& window);
MouseElement(Anchor2D anchor);
MouseElement(Anchor2D anchor, Window& window);
};
}

View file

@ -18,13 +18,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:PipelineRTVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
import :VulkanBuffer;
import :ShaderBindingTableVulkan;
import :Types;
@ -48,7 +48,7 @@ export namespace Crafter {
.pSetLayouts = setLayouts.data()
};
VulkanDevice::CheckVkResult(vkCreatePipelineLayout(VulkanDevice::device, &pipelineLayoutInfo, nullptr, &pipelineLayout));
Device::CheckVkResult(vkCreatePipelineLayout(Device::device, &pipelineLayoutInfo, nullptr, &pipelineLayout));
std::vector<VkRayTracingShaderGroupCreateInfoKHR> groups;
groups.reserve(raygenGroups.size() + missGroups.size() + hitGroups.size());
@ -67,24 +67,24 @@ export namespace Crafter {
.layout = pipelineLayout
};
VulkanDevice::CheckVkResult(VulkanDevice::vkCreateRayTracingPipelinesKHR(VulkanDevice::device, {}, {}, 1, &rtPipelineInfo, nullptr, &pipeline));
Device::CheckVkResult(Device::vkCreateRayTracingPipelinesKHR(Device::device, {}, {}, 1, &rtPipelineInfo, nullptr, &pipeline));
std::size_t dataSize = VulkanDevice::rayTracingProperties.shaderGroupHandleSize * rtPipelineInfo.groupCount;
std::size_t dataSize = Device::rayTracingProperties.shaderGroupHandleSize * rtPipelineInfo.groupCount;
shaderHandles.resize(dataSize);
VulkanDevice::CheckVkResult(VulkanDevice::vkGetRayTracingShaderGroupHandlesKHR(VulkanDevice::device, pipeline, 0, rtPipelineInfo.groupCount, dataSize, shaderHandles.data()));
Device::CheckVkResult(Device::vkGetRayTracingShaderGroupHandlesKHR(Device::device, pipeline, 0, rtPipelineInfo.groupCount, dataSize, shaderHandles.data()));
std::uint32_t sbtStride = AlignUp(VulkanDevice::rayTracingProperties.shaderGroupHandleSize, VulkanDevice::rayTracingProperties.shaderGroupHandleAlignment);
std::uint32_t sbtStride = AlignUp(Device::rayTracingProperties.shaderGroupHandleSize, Device::rayTracingProperties.shaderGroupHandleAlignment);
raygenRegion.stride = sbtStride;
raygenRegion.deviceAddress = 0;
raygenRegion.size = raygenGroups.size() * sbtStride;
missRegion.stride = sbtStride;
missRegion.deviceAddress = AlignUp(raygenRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
missRegion.deviceAddress = AlignUp(raygenRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
missRegion.size = missGroups.size() * sbtStride;
hitRegion.stride = sbtStride;
hitRegion.deviceAddress = AlignUp(missRegion.deviceAddress + missRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
hitRegion.deviceAddress = AlignUp(missRegion.deviceAddress + missRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
hitRegion.size = hitGroups.size() * sbtStride;
std::size_t bufferSize = hitRegion.deviceAddress + hitRegion.size;
@ -93,15 +93,15 @@ export namespace Crafter {
std::uint8_t* offset = sbtBuffer.value;
std::uint8_t* handleOffset = shaderHandles.data();
std::memcpy(offset, handleOffset, raygenGroups.size() * VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
offset += AlignUp(raygenRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
handleOffset += raygenGroups.size() * VulkanDevice::rayTracingProperties.shaderGroupHandleSize;
std::memcpy(offset, handleOffset, raygenGroups.size() * Device::rayTracingProperties.shaderGroupHandleSize);
offset += AlignUp(raygenRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
handleOffset += raygenGroups.size() * Device::rayTracingProperties.shaderGroupHandleSize;
std::memcpy(offset, handleOffset, missGroups.size() * VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
offset += AlignUp(missRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
handleOffset += missGroups.size() * VulkanDevice::rayTracingProperties.shaderGroupHandleSize;
std::memcpy(offset, handleOffset, missGroups.size() * Device::rayTracingProperties.shaderGroupHandleSize);
offset += AlignUp(missRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
handleOffset += missGroups.size() * Device::rayTracingProperties.shaderGroupHandleSize;
std::memcpy(offset, handleOffset, hitGroups.size() * VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
std::memcpy(offset, handleOffset, hitGroups.size() * Device::rayTracingProperties.shaderGroupHandleSize);
sbtBuffer.FlushDevice(cmd, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR);
@ -142,7 +142,7 @@ export namespace Crafter {
.pSetLayouts = setLayouts.data()
};
VulkanDevice::CheckVkResult(vkCreatePipelineLayout(VulkanDevice::device, &pipelineLayoutInfo, nullptr, &pipelineLayout));
Device::CheckVkResult(vkCreatePipelineLayout(Device::device, &pipelineLayoutInfo, nullptr, &pipelineLayout));
constexpr auto groupIndexSeq = std::make_index_sequence<std::tuple_size_v<ShaderGroups>>{};
@ -158,24 +158,24 @@ export namespace Crafter {
.layout = pipelineLayout
};
VulkanDevice::CheckVkResult(VulkanDevice::vkCreateRayTracingPipelinesKHR(VulkanDevice::device, {}, {}, 1, &rtPipelineInfo, nullptr, &pipeline));
Device::CheckVkResult(Device::vkCreateRayTracingPipelinesKHR(Device::device, {}, {}, 1, &rtPipelineInfo, nullptr, &pipeline));
std::size_t dataSize = VulkanDevice::rayTracingProperties.shaderGroupHandleSize * rtPipelineInfo.groupCount;
std::size_t dataSize = Device::rayTracingProperties.shaderGroupHandleSize * rtPipelineInfo.groupCount;
shaderHandles.resize(dataSize);
VulkanDevice::CheckVkResult(VulkanDevice::vkGetRayTracingShaderGroupHandlesKHR(VulkanDevice::device, pipeline, 0, rtPipelineInfo.groupCount, dataSize, shaderHandles.data()));
Device::CheckVkResult(Device::vkGetRayTracingShaderGroupHandlesKHR(Device::device, pipeline, 0, rtPipelineInfo.groupCount, dataSize, shaderHandles.data()));
std::uint32_t sbtStride = AlignUp(VulkanDevice::rayTracingProperties.shaderGroupHandleSize, VulkanDevice::rayTracingProperties.shaderGroupHandleAlignment);
std::uint32_t sbtStride = AlignUp(Device::rayTracingProperties.shaderGroupHandleSize, Device::rayTracingProperties.shaderGroupHandleAlignment);
raygenRegion.stride = sbtStride;
raygenRegion.deviceAddress = 0;
raygenRegion.size = GetGroupCount<VK_SHADER_STAGE_RAYGEN_BIT_KHR>(groupIndexSeq) * sbtStride;
missRegion.stride = sbtStride;
missRegion.deviceAddress = AlignUp(raygenRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
missRegion.deviceAddress = AlignUp(raygenRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
missRegion.size = GetGroupCount<VK_SHADER_STAGE_MISS_BIT_KHR>(groupIndexSeq) * sbtStride;
hitRegion.stride = sbtStride;
hitRegion.deviceAddress = AlignUp(missRegion.deviceAddress + missRegion.size, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
hitRegion.deviceAddress = AlignUp(missRegion.deviceAddress + missRegion.size, Device::rayTracingProperties.shaderGroupBaseAlignment);
hitRegion.size = (GetGroupCount<VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR>(groupIndexSeq) * sbtStride) + (GetGroupCount<VK_SHADER_STAGE_ANY_HIT_BIT_KHR>(groupIndexSeq) * sbtStride);
std::size_t bufferSize = hitRegion.deviceAddress + hitRegion.size;
@ -263,19 +263,19 @@ export namespace Crafter {
if constexpr(groupTemplate::generalShader != VK_SHADER_UNUSED_KHR) {
using shaderTemplate = std::tuple_element_t<groupTemplate::generalShader, Shaders>;
if constexpr(shaderTemplate::_stage == stage) {
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * VulkanDevice::rayTracingProperties.shaderGroupHandleSize, VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * Device::rayTracingProperties.shaderGroupHandleSize, Device::rayTracingProperties.shaderGroupHandleSize);
offset += sbtStride;
}
} else if constexpr(groupTemplate::closestHitShader != VK_SHADER_UNUSED_KHR) {
using shaderTemplate = std::tuple_element_t<groupTemplate::closestHitShader, Shaders>;
if constexpr(shaderTemplate::_stage == stage) {
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * VulkanDevice::rayTracingProperties.shaderGroupHandleSize, VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * Device::rayTracingProperties.shaderGroupHandleSize, Device::rayTracingProperties.shaderGroupHandleSize);
offset += sbtStride;
}
} else if constexpr(groupTemplate::anyHitShader != VK_SHADER_UNUSED_KHR) {
using shaderTemplate = std::tuple_element_t<groupTemplate::anyHitShader, Shaders>;
if constexpr(shaderTemplate::_stage == stage) {
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * VulkanDevice::rayTracingProperties.shaderGroupHandleSize, VulkanDevice::rayTracingProperties.shaderGroupHandleSize);
std::memcpy(sbtBuffer.value + offset, shaderHandles.data() + index * Device::rayTracingProperties.shaderGroupHandleSize, Device::rayTracingProperties.shaderGroupHandleSize);
offset += sbtStride;
}
} else {
@ -290,9 +290,9 @@ export namespace Crafter {
static void AddShaderGroupsToBuffer(std::uint32_t sbtStride, std::index_sequence<Is...>) {
std::uint32_t offset = 0;
(AddShaderGroupToBuffer<Is, VK_SHADER_STAGE_RAYGEN_BIT_KHR>(sbtStride, offset), ...);
offset = AlignUp(offset, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
offset = AlignUp(offset, Device::rayTracingProperties.shaderGroupBaseAlignment);
(AddShaderGroupToBuffer<Is, VK_SHADER_STAGE_MISS_BIT_KHR>(sbtStride, offset), ...);
offset = AlignUp(offset, VulkanDevice::rayTracingProperties.shaderGroupBaseAlignment);
offset = AlignUp(offset, Device::rayTracingProperties.shaderGroupBaseAlignment);
(AddShaderGroupToBuffer<Is, VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR>(sbtStride, offset), ...);
(AddShaderGroupToBuffer<Is, VK_SHADER_STAGE_ANY_HIT_BIT_KHR>(sbtStride, offset), ...);
}

View file

@ -1,652 +0,0 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include "../lib/stb_image.h"
#include "../lib/stb_truetype.h"
export module Crafter.Graphics:RenderingElement;
import std;
import :Transform;
import :Font;
import :Types;
import :Image;
import :Window;
export namespace Crafter {
enum class TextAlignment {
Left,
Center,
Right
};
enum class TextOverflowMode {
Clip,
Wrap
};
enum class TextScaleMode {
None,
Font,
Element,
Buffer
};
struct RenderElementScalingOwning {
std::vector<Pixel_BU8_GU8_RU8_AU8> scalingBuffer;
std::uint32_t bufferWidth;
std::uint32_t bufferHeight;
bool bufferUpdated = true;
RenderElementScalingOwning() = default;
RenderElementScalingOwning(std::uint32_t bufferWidth, std::uint32_t bufferHeight) : scalingBuffer(bufferWidth*bufferHeight), bufferWidth(bufferWidth), bufferHeight(bufferHeight) {
}
};
struct RenderElementScalingNonOwning {
Pixel_BU8_GU8_RU8_AU8* scalingBuffer;
std::uint32_t bufferWidth;
std::uint32_t bufferHeight;
bool bufferUpdated = true;
RenderElementScalingNonOwning() = default;
RenderElementScalingNonOwning(Pixel_BU8_GU8_RU8_AU8* scalingBuffer, std::uint32_t bufferWidth, std::uint32_t bufferHeight) : scalingBuffer(scalingBuffer), bufferWidth(bufferWidth), bufferHeight(bufferHeight) {
}
};
struct RenderElementRotating {
std::uint32_t rotation;
bool rotationUpdated = true;
RenderElementRotating() = default;
RenderElementRotating(std::uint32_t rotation) : rotation(rotation) {
}
};
struct EmptyScalingBase {};
struct EmptyRotatingBase {};
template<bool Scaling, bool Owning>
using ScalingBase =
std::conditional_t<
Scaling,
std::conditional_t<Owning,
RenderElementScalingOwning,
RenderElementScalingNonOwning>,
EmptyScalingBase
>;
template<bool Rotating>
using RotatingBase =
std::conditional_t<
Rotating,
RenderElementRotating,
EmptyRotatingBase
>;
class RenderingElementBase : public Transform {
public:
std::vector<Pixel_BU8_GU8_RU8_AU8> buffer;
OpaqueType opaque;
RenderingElementBase(Anchor anchor) : Transform(anchor) {
scaled.width = 0;
}
RenderingElementBase(Anchor anchor, OpaqueType opaque) : Transform(anchor), opaque(opaque) {
scaled.width = 0;
}
};
template<bool Scaling, bool Owning, bool Rotating> requires ((!Rotating || Scaling) && (!Owning || Scaling))
class RenderingElement : public RenderingElementBase, public ScalingBase<Scaling, Owning>, public RotatingBase<Rotating> {
public:
RenderingElement() = default;
RenderingElement(Anchor anchor, OpaqueType opaque) : RenderingElementBase(anchor, opaque) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, std::uint32_t rotation) requires(Rotating) : RenderingElementBase(anchor, opaque), RotatingBase<Rotating>(rotation) {
}
RenderingElement(Anchor anchor, const std::string_view imagePath) : RenderingElementBase(anchor) {
LoadImage(imagePath);
}
RenderingElement(Anchor anchor, const std::string_view imagePath, std::uint32_t rotation) requires(Rotating) : RenderingElementBase(anchor), RotatingBase<Rotating>(rotation) {
LoadImage(imagePath);
}
RenderingElement(Anchor anchor, const std::string_view imagePath, OpaqueType opaque) : RenderingElementBase(anchor, opaque) {
LoadImageNoOpaqueCheck(imagePath);
}
RenderingElement(Anchor anchor, const std::string_view imagePath, OpaqueType opaque, std::uint32_t rotation) requires(Rotating) : RenderingElementBase(anchor, opaque), RotatingBase<Rotating>(rotation) {
LoadImageNoOpaqueCheck(imagePath);
}
RenderingElement(Anchor anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, Pixel_BU8_GU8_RU8_AU8* scalingBuffer) requires(Scaling && !Owning) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight, scalingBuffer) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, Pixel_BU8_GU8_RU8_AU8* scalingBuffer, std::uint32_t rotation) requires(Scaling && !Owning && Rotating) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight, scalingBuffer), RotatingBase<Rotating>(rotation) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, Image& image) requires(Scaling && !Owning) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(image.buffer.data(), image.width, image.height) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, Image& image, std::uint32_t rotation) requires(Scaling && !Owning && Rotating) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(image.buffer.data(), image.width, image.height), RotatingBase<Rotating>(rotation) {
}
RenderingElement(Anchor anchor, Image& image) requires(Scaling && !Owning) : RenderingElementBase(anchor, image.opaque), ScalingBase<Scaling, Owning>(image.buffer.data(), image.width, image.height) {
}
RenderingElement(Anchor anchor, Image& image, std::uint32_t rotation) requires(Scaling && !Owning && Rotating) : RenderingElementBase(anchor, image.opaque), ScalingBase<Scaling, Owning>(image.buffer.data(), image.width, image.height), RotatingBase<Rotating>(rotation) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight) requires(Owning) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight) {
}
RenderingElement(Anchor anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, std::uint32_t rotation) requires(Owning && Rotating) : RenderingElementBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight) , RotatingBase<Rotating>(rotation) {
}
RenderingElement(RenderingElement&) = delete;
RenderingElement& operator=(RenderingElement&) = delete;
void ScaleNearestNeighbor() requires(Scaling) {
for (std::uint32_t y = 0; y < scaled.height; y++) {
std::uint32_t srcY = y * ScalingBase<true, Owning>::bufferHeight / scaled.height;
for (std::uint32_t x = 0; x < scaled.width; x++) {
std::uint32_t srcX = x * ScalingBase<true, Owning>::bufferWidth / scaled.width;
buffer[y * scaled.width + x] = ScalingBase<true, Owning>::scalingBuffer[srcY * ScalingBase<true, Owning>::bufferWidth + srcX];
}
}
}
void ScaleRotating() requires(Scaling) {
const double rad = (static_cast<double>(RotatingBase<true>::rotation) / static_cast<double>(std::numeric_limits<std::uint32_t>::max())) * 2.0 * std::numbers::pi;
const std::uint32_t dstWidth = scaled.width;
const std::uint32_t dstHeight = scaled.height;
const double c2 = std::abs(std::cos(rad));
const double s2 = std::abs(std::sin(rad));
const double rotatedWidth = dstWidth * c2 + dstHeight * s2;
const double rotatedHeight = dstWidth * s2 + dstHeight * c2;
const std::uint32_t diffX = static_cast<std::uint32_t>(std::ceil((rotatedWidth - dstWidth) * 0.5));
const std::uint32_t diffY = static_cast<std::uint32_t>(std::ceil((rotatedHeight - dstHeight) * 0.5));
scaled.width += diffX + diffX;
scaled.height += diffY + diffY;
scaled.x -= diffX;
scaled.y -= diffY;
buffer.clear();
buffer.resize(scaled.width * scaled.height);
// Destination center
const double dstCx = (static_cast<double>(scaled.width) - 1.0) * 0.5;
const double dstCy = (static_cast<double>(scaled.height) - 1.0) * 0.5;
// Source center
const double srcCx = (static_cast<double>(ScalingBase<true, Owning>::bufferWidth) - 1.0) * 0.5;
const double srcCy = (static_cast<double>(ScalingBase<true, Owning>::bufferHeight) - 1.0) * 0.5;
const double c = std::cos(rad);
const double s = std::sin(rad);
// Scale factors (destination → source)
const double scaleX = static_cast<double>(ScalingBase<true, Owning>::bufferWidth) / dstWidth;
const double scaleY = static_cast<double>(ScalingBase<true, Owning>::bufferHeight) / dstHeight;
for (std::uint32_t yB = 0; yB < scaled.height; ++yB) {
for (std::uint32_t xB = 0; xB < scaled.width; ++xB) {
// ---- Destination pixel relative to center ----
const double dx = (static_cast<double>(xB) - dstCx) * scaleX;
const double dy = (static_cast<double>(yB) - dstCy) * scaleY;
// ---- Inverse rotation ----
const double sx = (c * dx - s * dy) + srcCx;
const double sy = (s * dx + c * dy) + srcCy;
// ---- Nearest neighbour sampling ----
const std::int32_t srcX = static_cast<std::int32_t>(std::round(sx));
const std::int32_t srcY = static_cast<std::int32_t>(std::round(sy));
if (srcX >= 0 && srcX < ScalingBase<true, Owning>::bufferWidth && srcY >= 0 && srcY < ScalingBase<true, Owning>::bufferHeight) {
buffer[yB * scaled.width + xB] = ScalingBase<true, Owning>::scalingBuffer[srcY * ScalingBase<true, Owning>::bufferWidth + srcX];
}
}
}
}
void UpdatePosition(Window& window, ScaleData oldScale) {
if constexpr(Scaling && !Rotating) {
if(oldScale.width != scaled.width || oldScale.height != scaled.height) {
buffer.resize(scaled.width * scaled.height);
ScaleNearestNeighbor();
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
} else if(oldScale.x != scaled.x || oldScale.y != scaled.y) {
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
if(ScalingBase<true, Owning>::bufferUpdated) {
ScaleNearestNeighbor();
ScalingBase<true, Owning>::bufferUpdated = false;
}
} else if(ScalingBase<true, Owning>::bufferUpdated) {
ScaleNearestNeighbor();
ScalingBase<true, Owning>::bufferUpdated = false;
}
} else if constexpr(Rotating) {
if(oldScale.width != scaled.width || oldScale.height != scaled.height) {
buffer.resize(scaled.width * scaled.height);
ScaleRotating();
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
} else if(oldScale.x != scaled.x || oldScale.y != scaled.y) {
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
if(ScalingBase<true, Owning>::bufferUpdated || RotatingBase<true>::rotationUpdated) {
ScaleRotating();
ScalingBase<true, Owning>::bufferUpdated = false;
RotatingBase<true>::rotationUpdated = false;
}
} else if(ScalingBase<true, Owning>::bufferUpdated || RotatingBase<true>::rotationUpdated) {
ScaleRotating();
ScalingBase<true, Owning>::bufferUpdated = false;
RotatingBase<true>::rotationUpdated = false;
}
} else {
if(oldScale.width != scaled.width || oldScale.height != scaled.height) {
buffer.resize(scaled.width * scaled.height);
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
}
if(oldScale.x != scaled.x || oldScale.y != scaled.y) {
window.AddDirtyRect(oldScale);
window.AddDirtyRect(scaled);
}
}
}
void UpdatePosition(Window& window) override {
ScaleData oldScale = scaled;
window.ScaleElement(*this);
UpdatePosition(window, oldScale);
for(Transform* child : children) {
child->UpdatePosition(window, *this);
}
}
void UpdatePosition(Window& window, Transform& parent) override {
ScaleData oldScale = scaled;
window.ScaleElement(*this, parent);
UpdatePosition(window, oldScale);
for(Transform* child : children) {
child->UpdatePosition(window, *this);
}
}
void LoadImage(const std::string_view imagePath) {
std::filesystem::path abs = std::filesystem::absolute(imagePath);
int xSize;
int ySize;
unsigned char* bgData = stbi_load(abs.string().c_str(), &xSize, &ySize, nullptr, 4);
if constexpr(Scaling && !Owning) {
ScalingBase<true, false>::bufferUpdated = true;
} else if constexpr(Scaling && Owning) {
ScalingBase<true, true>::bufferWidth = xSize;
ScalingBase<true, true>::bufferHeight = ySize;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(xSize*ySize);
} else {
buffer.resize(xSize*ySize);
}
opaque = OpaqueType::FullyOpaque;
if constexpr(Scaling) {
for(std::uint32_t x = 0; x < xSize; x++) {
for(std::uint32_t y = 0; y < ySize; y++) {
std::uint32_t idx = (x*ySize+y)*4;
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].r = bgData[idx];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].g = bgData[idx+1];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].b = bgData[idx+2];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].a = bgData[idx+3];
}
}
for(std::uint32_t i = 0; i < xSize*ySize; i++) {
if(ScalingBase<true, Owning>::scalingBuffer[i].a != 255) {
opaque = OpaqueType::SemiOpaque;
for(std::uint32_t i2 = 0; i2 < xSize*ySize; i2++) {
if(ScalingBase<true, Owning>::scalingBuffer[i2].a != 0 && ScalingBase<true, Owning>::scalingBuffer[i2].a != 255) {
opaque = OpaqueType::Transparent;
return;
}
}
return;
}
}
} else {
for(std::uint32_t x = 0; x < xSize; x++) {
for(std::uint32_t y = 0; y < ySize; y++) {
std::uint32_t idx = (x*ySize+y)*4;
buffer[x*ySize+y].r = bgData[idx];
buffer[x*ySize+y].g = bgData[idx+1];
buffer[x*ySize+y].b = bgData[idx+2];
buffer[x*ySize+y].a = bgData[idx+3];
}
}
for(std::uint32_t i = 0; i < xSize*ySize; i++) {
if(buffer[i].a != 255) {
opaque = OpaqueType::SemiOpaque;
for(std::uint32_t i2 = 0; i2 < xSize*ySize; i2++) {
if(buffer[i2].a != 0 && buffer[i2].a != 255) {
opaque = OpaqueType::Transparent;
return;
}
}
return;
}
}
}
}
void LoadImageNoOpaqueCheck(const std::string_view imagePath) {
std::filesystem::path abs = std::filesystem::absolute(imagePath);
int xSize;
int ySize;
unsigned char* bgData = stbi_load(abs.string().c_str(), &xSize, &ySize, nullptr, 4);
if constexpr(Scaling && !Owning) {
ScalingBase<true, false>::bufferUpdated = true;
} else if constexpr(Scaling && Owning) {
ScalingBase<true, true>::bufferWidth = xSize;
ScalingBase<true, true>::bufferHeight = ySize;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(xSize*ySize);
} else {
buffer.resize(xSize*ySize);
}
if constexpr(Scaling) {
for(std::uint32_t x = 0; x < xSize; x++) {
for(std::uint32_t y = 0; y < ySize; y++) {
std::uint32_t idx = (x*ySize+y)*4;
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].r = bgData[idx];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].g = bgData[idx+1];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].b = bgData[idx+2];
ScalingBase<true, Owning>::scalingBuffer[x*ySize+y].a = bgData[idx+3];
}
}
} else {
for(std::uint32_t x = 0; x < xSize; x++) {
for(std::uint32_t y = 0; y < ySize; y++) {
std::uint32_t idx = (x*ySize+y)*4;
buffer[x*ySize+y].r = bgData[idx];
buffer[x*ySize+y].g = bgData[idx+1];
buffer[x*ySize+y].b = bgData[idx+2];
buffer[x*ySize+y].a = bgData[idx+3];
}
}
}
}
std::vector<std::string_view> ResizeText(Window& window, const std::string_view text, float size, Font& font, TextOverflowMode overflowMode = TextOverflowMode::Clip, TextScaleMode scaleMode = TextScaleMode::None, Transform* parent = nullptr) {
float scale = stbtt_ScaleForPixelHeight(&font.font, size);
int baseline = (int)(font.ascent * scale);
std::vector<std::string_view> lines;
std::string_view remaining = text;
std::uint32_t lineHeight = (font.ascent - font.descent) * scale;
if(overflowMode == TextOverflowMode::Clip) {
while (!remaining.empty()) {
// Find next newline or end of string
auto newlinePos = remaining.find('\n');
if (newlinePos != std::string_view::npos) {
lines.emplace_back(remaining.substr(0, newlinePos));
remaining = remaining.substr(newlinePos + 1);
} else {
lines.emplace_back(remaining);
break;
}
}
std::uint32_t maxWidth = 0;
for(const std::string_view line: lines) {
std::uint32_t lineWidth = 0;
for (const char c : line) {
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (int)(advance * scale);
}
if(lineWidth > maxWidth) {
maxWidth = lineWidth;
}
}
if(scaleMode == TextScaleMode::Element) {
std::int32_t logicalPerPixelY = anchor.height / scaled.height;
std::int32_t oldHeight = anchor.height;
std::int32_t logicalPerPixelX = anchor.width / scaled.width;
std::int32_t oldwidth = anchor.width;
anchor.height = lineHeight * logicalPerPixelY;
anchor.width = maxWidth * logicalPerPixelX;
if(oldHeight != anchor.height || oldwidth != anchor.width) {
if(parent) {
UpdatePosition(window, *parent);
} else {
UpdatePosition(window);
}
}
} else if(scaleMode == TextScaleMode::Font) {
//todo
} else if(scaleMode == TextScaleMode::Buffer) {
if constexpr(Scaling && Owning) {
std::uint32_t neededHeight = lines.size() * lineHeight;
if(neededHeight != ScalingBase<true, true>::bufferHeight || maxWidth != ScalingBase<true, true>::bufferWidth) {
ScalingBase<true, true>::bufferHeight = neededHeight;
ScalingBase<true, true>::bufferWidth = maxWidth;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(neededHeight*maxWidth);
}
}
} else {
if constexpr(Scaling) {
lines.resize(ScalingBase<true, Owning>::bufferHeight / lines.size());
} else {
lines.resize(scaled.height / lines.size());
}
}
} else {
while (!remaining.empty()) {
std::string_view line;
auto newlinePos = remaining.find('\n');
if (newlinePos != std::string_view::npos) {
line = remaining.substr(0, newlinePos);
remaining = remaining.substr(newlinePos + 1);
} else {
line = remaining;
remaining = "";
}
std::uint32_t lineWidth = 0;
std::size_t lastWrapPos = 0; // position of last space that can be used to wrap
std::size_t startPos = 0;
for (std::size_t i = 0; i < line.size(); ++i) {
char c = line[i];
// get width of this character
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (std::uint32_t)(advance * scale);
// remember last space for wrapping
if (c == ' ') {
lastWrapPos = i;
}
// if line exceeds width, wrap
if (lineWidth > scaled.width) {
std::size_t wrapPos;
if (lastWrapPos > startPos) {
wrapPos = lastWrapPos; // wrap at last space
} else {
wrapPos = i; // no space, hard wrap
}
// push the line up to wrapPos
lines.push_back(line.substr(startPos, wrapPos - startPos));
// skip any spaces at the beginning of next line
startPos = wrapPos;
while (startPos < line.size() && line[startPos] == ' ') {
++startPos;
}
// reset width and i
lineWidth = 0;
i = startPos - 1; // -1 because loop will increment i
}
}
// add the remaining part of the line
if (startPos < line.size()) {
lines.push_back(line.substr(startPos));
}
}
if(scaleMode == TextScaleMode::Element) {
std::int32_t logicalPerPixelY = anchor.height / scaled.height;
std::int32_t oldHeight = anchor.height;
anchor.height = lineHeight * logicalPerPixelY;
if(oldHeight != anchor.height) {
if(parent) {
UpdatePosition(window, *parent);
} else {
UpdatePosition(window);
}
}
} else if(scaleMode == TextScaleMode::Font) {
//todo
} else if(scaleMode == TextScaleMode::Buffer) {
if constexpr(Scaling && Owning) {
std::uint32_t neededHeight = lines.size() * lineHeight;
if(neededHeight != ScalingBase<true, true>::bufferHeight) {
ScalingBase<true, true>::bufferHeight = neededHeight;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(neededHeight*ScalingBase<true, true>::bufferWidth);
}
}
} else {
if constexpr(Scaling) {
lines.resize(ScalingBase<true, Owning>::bufferHeight / lines.size());
} else {
lines.resize(scaled.height / lines.size());
}
}
}
return lines;
}
void RenderText(Window& window, std::span<const std::string_view> lines, float size, Pixel_BU8_GU8_RU8_AU8 color, Font& font, TextAlignment alignment = TextAlignment::Left, std::uint32_t offsetX = 0, std::uint32_t offsetY = 0) {
float scale = stbtt_ScaleForPixelHeight(&font.font, size);
int baseline = (int)(font.ascent * scale);
std::uint32_t lineHeight = (font.ascent - font.descent) * scale;
std::uint32_t currentY = baseline;
for(std::string_view line : lines) {
std::uint32_t lineWidth = 0;
for (const char c : line) {
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (int)(advance * scale);
}
std::uint32_t startX = 0;
switch (alignment) {
case TextAlignment::Left:
startX = 0;
break;
case TextAlignment::Center:
startX = (scaled.width - lineWidth) / 2;
break;
case TextAlignment::Right:
startX = scaled.width - lineWidth;
break;
}
std::uint32_t x = startX;
for (std::size_t i = 0; i < line.size(); ++i) {
int codepoint = line[i];
int ax;
int lsb;
stbtt_GetCodepointHMetrics(&font.font, codepoint, &ax, &lsb);
int c_x1, c_y1, c_x2, c_y2;
stbtt_GetCodepointBitmapBox(&font.font, codepoint, scale, scale, &c_x1, &c_y1, &c_x2, &c_y2);
int w = c_x2 - c_x1;
int h = c_y2 - c_y1;
std::vector<unsigned char> bitmap(w * h);
stbtt_MakeCodepointBitmap(&font.font, bitmap.data(), w, h, w, scale, scale, codepoint);
// Only render characters that fit within the scaled bounds
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
int bufferX = x + i + c_x1 + offsetX;
int bufferY = currentY + j + c_y1 + offsetY;
// Only draw pixels that are within our scaled buffer bounds
if constexpr(Scaling) {
if (bufferX >= 0 && bufferX < ScalingBase<true, Owning>::bufferWidth && bufferY >= 0 && bufferY < ScalingBase<true, Owning>::bufferHeight) {
ScalingBase<true, Owning>::scalingBuffer[bufferY * ScalingBase<true, Owning>::bufferWidth + bufferX] = {color.r, color.g, color.b, bitmap[j * w + i]};
}
} else {
if (bufferX >= 0 && bufferX < (int)scaled.width && bufferY >= 0 && bufferY < (int)scaled.height) {
buffer[bufferY * scaled.width + bufferX] = {color.r, color.g, color.b, bitmap[j * w + i]};
}
}
}
}
x += (int)(ax * scale);
if (i + 1 < line.size()) {
x += (int)stbtt_GetCodepointKernAdvance(&font.font, codepoint, line[i+1]);
}
}
currentY += lineHeight;
}
}
};
}

View file

@ -0,0 +1,508 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include "../lib/stb_truetype.h"
export module Crafter.Graphics:RenderingElement2D;
import std;
import :Transform2D;
import :Font;
import :Types;
import :Window;
export namespace Crafter {
enum class TextAlignment {
Left,
Center,
Right
};
enum class TextOverflowMode {
Clip,
Wrap
};
enum class TextScaleMode {
None,
Font,
Element,
Buffer
};
struct RenderElement2DScalingOwning {
std::vector<Vector<std::uint8_t, 4>> scalingBuffer;
std::uint32_t bufferWidth;
std::uint32_t bufferHeight;
bool bufferUpdated = true;
RenderElement2DScalingOwning() = default;
RenderElement2DScalingOwning(std::uint32_t bufferWidth, std::uint32_t bufferHeight) : scalingBuffer(bufferWidth*bufferHeight), bufferWidth(bufferWidth), bufferHeight(bufferHeight) {
}
};
struct RenderElement2DScalingNonOwning {
Vector<std::uint8_t, 4>* scalingBuffer;
std::uint32_t bufferWidth;
std::uint32_t bufferHeight;
bool bufferUpdated = true;
RenderElement2DScalingNonOwning() = default;
RenderElement2DScalingNonOwning(Vector<std::uint8_t, 4>* scalingBuffer, std::uint32_t bufferWidth, std::uint32_t bufferHeight) : scalingBuffer(scalingBuffer), bufferWidth(bufferWidth), bufferHeight(bufferHeight) {
}
};
struct RenderElement2DRotating {
float rotation;
bool rotationUpdated = true;
RenderElement2DRotating() = default;
RenderElement2DRotating(float rotation) : rotation(rotation) {
}
};
struct EmptyScalingBase {};
struct EmptyRotatingBase {};
template<bool Scaling, bool Owning>
using ScalingBase =
std::conditional_t<
Scaling,
std::conditional_t<Owning,
RenderElement2DScalingOwning,
RenderElement2DScalingNonOwning>,
EmptyScalingBase
>;
template<bool Rotating>
using RotatingBase =
std::conditional_t<
Rotating,
RenderElement2DRotating,
EmptyRotatingBase
>;
struct RenderingElement2DBase : Transform2D {
std::vector<Vector<std::uint8_t, 4>> buffer;
OpaqueType opaque;
RenderingElement2DBase(Anchor2D anchor) : Transform2D(anchor) {
scaled.size.x = 0;
}
RenderingElement2DBase(Anchor2D anchor, OpaqueType opaque) : Transform2D(anchor), opaque(opaque) {
scaled.size.x = 0;
}
};
template<bool Scaling, bool Owning, bool Rotating> requires ((!Rotating || Scaling) && (!Owning || Scaling))
struct RenderingElement2D : RenderingElement2DBase, ScalingBase<Scaling, Owning>, RotatingBase<Rotating> {
RenderingElement2D() = default;
RenderingElement2D(Anchor2D anchor, OpaqueType opaque) : RenderingElement2DBase(anchor, opaque) {
}
RenderingElement2D(Anchor2D anchor, OpaqueType opaque, std::uint32_t rotation) requires(Rotating) : RenderingElement2DBase(anchor, opaque), RotatingBase<Rotating>(rotation) {
}
RenderingElement2D(Anchor2D anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, Vector<std::uint8_t, 4>* scalingBuffer) requires(Scaling && !Owning) : RenderingElement2DBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight, scalingBuffer) {
}
RenderingElement2D(Anchor2D anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, Vector<std::uint8_t, 4>* scalingBuffer, std::uint32_t rotation) requires(Scaling && !Owning && Rotating) : RenderingElement2DBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight, scalingBuffer), RotatingBase<Rotating>(rotation) {
}
RenderingElement2D(Anchor2D anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight) requires(Owning) : RenderingElement2DBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight) {
}
RenderingElement2D(Anchor2D anchor, OpaqueType opaque, std::uint32_t bufferWidth, std::uint32_t bufferHeight, std::uint32_t rotation) requires(Owning && Rotating) : RenderingElement2DBase(anchor, opaque), ScalingBase<Scaling, Owning>(bufferWidth, bufferHeight) , RotatingBase<Rotating>(rotation) {
}
RenderingElement2D(RenderingElement2D&) = delete;
RenderingElement2D& operator=(RenderingElement2D&) = delete;
void ScaleNearestNeighbor() requires(Scaling) {
for (std::uint32_t y = 0; y < scaled.size.y; y++) {
std::uint32_t srcY = y * ScalingBase<true, Owning>::bufferHeight / scaled.size.y;
for (std::uint32_t x = 0; x < scaled.size.x; x++) {
std::uint32_t srcX = x * ScalingBase<true, Owning>::bufferWidth / scaled.size.x;
buffer[y * scaled.size.x + x] = ScalingBase<true, Owning>::scalingBuffer[srcY * ScalingBase<true, Owning>::bufferWidth + srcX];
}
}
}
void ScaleRotating() requires(Scaling) {
const std::uint32_t dstWidth = scaled.size.x;
const std::uint32_t dstHeight = scaled.size.y;
const float c2 = std::abs(std::cos(RotatingBase<true>::rotation));
const float s2 = std::abs(std::sin(RotatingBase<true>::rotation));
const float rotatedWidth = dstWidth * c2 + dstHeight * s2;
const float rotatedHeight = dstWidth * s2 + dstHeight * c2;
const std::uint32_t diffX = static_cast<std::uint32_t>(std::ceil((rotatedWidth - dstWidth) * 0.5));
const std::uint32_t diffY = static_cast<std::uint32_t>(std::ceil((rotatedHeight - dstHeight) * 0.5));
scaled.size.x += diffX + diffX;
scaled.size.y += diffY + diffY;
scaled.position.x -= diffX;
scaled.position.y -= diffY;
buffer.clear();
buffer.resize(scaled.size.x * scaled.size.y);
// Destination center
const float dstCx = (static_cast<float>(scaled.size.x) - 1.0) * 0.5;
const float dstCy = (static_cast<float>(scaled.size.y) - 1.0) * 0.5;
// Source center
const float srcCx = (static_cast<float>(ScalingBase<true, Owning>::bufferWidth) - 1.0) * 0.5;
const float srcCy = (static_cast<float>(ScalingBase<true, Owning>::bufferHeight) - 1.0) * 0.5;
const float c = std::cos(RotatingBase<true>::rotation);
const float s = std::sin(RotatingBase<true>::rotation);
// Scale factors (destination → source)
const float scaleX = static_cast<float>(ScalingBase<true, Owning>::bufferWidth) / dstWidth;
const float scaleY = static_cast<float>(ScalingBase<true, Owning>::bufferHeight) / dstHeight;
for (std::uint32_t yB = 0; yB < scaled.size.y; ++yB) {
for (std::uint32_t xB = 0; xB < scaled.size.x; ++xB) {
// ---- Destination pixel relative to center ----
const float dx = (static_cast<float>(xB) - dstCx) * scaleX;
const float dy = (static_cast<float>(yB) - dstCy) * scaleY;
// ---- Inverse rotation ----
const float sx = (c * dx - s * dy) + srcCx;
const float sy = (s * dx + c * dy) + srcCy;
// ---- Nearest neighbour sampling ----
const std::int32_t srcX = static_cast<std::int32_t>(std::round(sx));
const std::int32_t srcY = static_cast<std::int32_t>(std::round(sy));
if (srcX >= 0 && srcX < ScalingBase<true, Owning>::bufferWidth && srcY >= 0 && srcY < ScalingBase<true, Owning>::bufferHeight) {
buffer[yB * scaled.size.x + xB] = ScalingBase<true, Owning>::scalingBuffer[srcY * ScalingBase<true, Owning>::bufferWidth + srcX];
}
}
}
}
void UpdatePosition(Rendertarget& renderer, ScaleData2D oldScale) {
if constexpr(Scaling && !Rotating) {
if(oldScale.size.x != scaled.size.x || oldScale.size.y != scaled.size.y) {
buffer.resize(scaled.size.x * scaled.size.y);
ScaleNearestNeighbor();
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
} else if(oldScale.position.x != scaled.position.x || oldScale.position.y != scaled.position.y) {
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
if(ScalingBase<true, Owning>::bufferUpdated) {
ScaleNearestNeighbor();
ScalingBase<true, Owning>::bufferUpdated = false;
}
} else if(ScalingBase<true, Owning>::bufferUpdated) {
ScaleNearestNeighbor();
ScalingBase<true, Owning>::bufferUpdated = false;
}
} else if constexpr(Rotating) {
if(oldScale.size.x != scaled.size.x || oldScale.size.y != scaled.size.y) {
buffer.resize(scaled.size.x * scaled.size.y);
ScaleRotating();
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
} else if(oldScale.position.x != scaled.position.x || oldScale.position.y != scaled.position.y) {
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
if(ScalingBase<true, Owning>::bufferUpdated || RotatingBase<true>::rotationUpdated) {
ScaleRotating();
ScalingBase<true, Owning>::bufferUpdated = false;
RotatingBase<true>::rotationUpdated = false;
}
} else if(ScalingBase<true, Owning>::bufferUpdated || RotatingBase<true>::rotationUpdated) {
ScaleRotating();
ScalingBase<true, Owning>::bufferUpdated = false;
RotatingBase<true>::rotationUpdated = false;
}
} else {
if(oldScale.size.x != scaled.size.x || oldScale.size.y != scaled.size.y) {
buffer.resize(scaled.size.x * scaled.size.y);
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
}
if(oldScale.position.x != scaled.position.x || oldScale.position.y != scaled.position.y) {
renderer.AddDirtyRect(oldScale);
renderer.AddDirtyRect(scaled);
}
}
}
void UpdatePosition(Rendertarget& window) override {
ScaleData2D oldScale = scaled;
ScaleElement(window.transform);
UpdatePosition(window, oldScale);
for(Transform2D* child : children) {
child->UpdatePosition(window, *this);
}
}
void UpdatePosition(Rendertarget& window, Transform2D& parent) override {
ScaleData2D oldScale = scaled;
ScaleElement(parent);
UpdatePosition(window, oldScale);
for(Transform2D* child : children) {
child->UpdatePosition(window, *this);
}
}
std::vector<std::string_view> ResizeText(Window& window, const std::string_view text, float size, Font& font, TextOverflowMode overflowMode = TextOverflowMode::Clip, TextScaleMode scaleMode = TextScaleMode::None, Transform2D* parent = nullptr) {
float scale = stbtt_ScaleForPixelHeight(&font.font, size);
int baseline = (int)(font.ascent * scale);
std::vector<std::string_view> lines;
std::string_view remaining = text;
std::uint32_t lineHeight = (font.ascent - font.descent) * scale;
if(overflowMode == TextOverflowMode::Clip) {
while (!remaining.empty()) {
// Find next newline or end of string
auto newlinePos = remaining.find('\n');
if (newlinePos != std::string_view::npos) {
lines.emplace_back(remaining.substr(0, newlinePos));
remaining = remaining.substr(newlinePos + 1);
} else {
lines.emplace_back(remaining);
break;
}
}
std::uint32_t maxWidth = 0;
for(const std::string_view line: lines) {
std::uint32_t lineWidth = 0;
for (const char c : line) {
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (int)(advance * scale);
}
if(lineWidth > maxWidth) {
maxWidth = lineWidth;
}
}
if(scaleMode == TextScaleMode::Element) {
std::int32_t logicalPerPixelY = anchor.height / scaled.size.y;
std::int32_t oldHeight = anchor.height;
std::int32_t logicalPerPixelX = anchor.width / scaled.size.x;
std::int32_t oldwidth = anchor.width;
anchor.height = lineHeight * logicalPerPixelY;
anchor.width = maxWidth * logicalPerPixelX;
if(oldHeight != anchor.height || oldwidth != anchor.width) {
if(parent) {
UpdatePosition(window, *parent);
} else {
UpdatePosition(window);
}
}
} else if(scaleMode == TextScaleMode::Font) {
//todo
} else if(scaleMode == TextScaleMode::Buffer) {
if constexpr(Scaling && Owning) {
std::uint32_t neededHeight = lines.size() * lineHeight;
if(neededHeight != ScalingBase<true, true>::bufferHeight || maxWidth != ScalingBase<true, true>::bufferWidth) {
ScalingBase<true, true>::bufferHeight = neededHeight;
ScalingBase<true, true>::bufferWidth = maxWidth;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(neededHeight*maxWidth);
}
}
} else {
if constexpr(Scaling) {
lines.resize(ScalingBase<true, Owning>::bufferHeight / lines.size());
} else {
lines.resize(scaled.size.y / lines.size());
}
}
} else {
while (!remaining.empty()) {
std::string_view line;
auto newlinePos = remaining.find('\n');
if (newlinePos != std::string_view::npos) {
line = remaining.substr(0, newlinePos);
remaining = remaining.substr(newlinePos + 1);
} else {
line = remaining;
remaining = "";
}
std::uint32_t lineWidth = 0;
std::size_t lastWrapPos = 0; // position of last space that can be used to wrap
std::size_t startPos = 0;
for (std::size_t i = 0; i < line.size(); ++i) {
char c = line[i];
// get width of this character
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (std::uint32_t)(advance * scale);
// remember last space for wrapping
if (c == ' ') {
lastWrapPos = i;
}
// if line exceeds width, wrap
if (lineWidth > scaled.size.x) {
std::size_t wrapPos;
if (lastWrapPos > startPos) {
wrapPos = lastWrapPos; // wrap at last space
} else {
wrapPos = i; // no space, hard wrap
}
// push the line up to wrapPos
lines.push_back(line.substr(startPos, wrapPos - startPos));
// skip any spaces at the beginning of next line
startPos = wrapPos;
while (startPos < line.size() && line[startPos] == ' ') {
++startPos;
}
// reset width and i
lineWidth = 0;
i = startPos - 1; // -1 because loop will increment i
}
}
// add the remaining part of the line
if (startPos < line.size()) {
lines.push_back(line.substr(startPos));
}
}
if(scaleMode == TextScaleMode::Element) {
float logicalPerPixelY = anchor.height / scaled.size.y;
float oldHeight = anchor.height;
anchor.height = lineHeight * logicalPerPixelY;
if(oldHeight != anchor.height) {
if(parent) {
UpdatePosition(window, *parent);
} else {
UpdatePosition(window);
}
}
} else if(scaleMode == TextScaleMode::Font) {
//todo
} else if(scaleMode == TextScaleMode::Buffer) {
if constexpr(Scaling && Owning) {
float neededHeight = lines.size() * lineHeight;
if(neededHeight != ScalingBase<true, true>::bufferHeight) {
ScalingBase<true, true>::bufferHeight = neededHeight;
ScalingBase<true, true>::bufferUpdated = true;
ScalingBase<true, Owning>::scalingBuffer.resize(neededHeight*ScalingBase<true, true>::bufferWidth);
}
}
} else {
if constexpr(Scaling) {
lines.resize(ScalingBase<true, Owning>::bufferHeight / lines.size());
} else {
lines.resize(scaled.size.y / lines.size());
}
}
}
return lines;
}
void RenderText(Window& window, std::span<const std::string_view> lines, float size, Vector<std::uint8_t, 4> color, Font& font, TextAlignment alignment = TextAlignment::Left, std::uint32_t offsetX = 0, std::uint32_t offsetY = 0) {
float scale = stbtt_ScaleForPixelHeight(&font.font, size);
int baseline = (int)(font.ascent * scale);
std::uint32_t lineHeight = (font.ascent - font.descent) * scale;
std::uint32_t currentY = baseline;
for(std::string_view line : lines) {
std::uint32_t lineWidth = 0;
for (const char c : line) {
int advance, lsb;
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
lineWidth += (int)(advance * scale);
}
std::uint32_t startX = 0;
switch (alignment) {
case TextAlignment::Left:
startX = 0;
break;
case TextAlignment::Center:
startX = (scaled.size.x - lineWidth) / 2;
break;
case TextAlignment::Right:
startX = scaled.size.x - lineWidth;
break;
}
std::uint32_t x = startX;
for (std::size_t i = 0; i < line.size(); ++i) {
int codepoint = line[i];
int ax;
int lsb;
stbtt_GetCodepointHMetrics(&font.font, codepoint, &ax, &lsb);
int c_x1, c_y1, c_x2, c_y2;
stbtt_GetCodepointBitmapBox(&font.font, codepoint, scale, scale, &c_x1, &c_y1, &c_x2, &c_y2);
int w = c_x2 - c_x1;
int h = c_y2 - c_y1;
std::vector<unsigned char> bitmap(w * h);
stbtt_MakeCodepointBitmap(&font.font, bitmap.data(), w, h, w, scale, scale, codepoint);
// Only render characters that fit within the scaled bounds
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
int bufferX = x + i + c_x1 + offsetX;
int bufferY = currentY + j + c_y1 + offsetY;
// Only draw pixels that are within our scaled buffer bounds
if constexpr(Scaling) {
if (bufferX >= 0 && bufferX < ScalingBase<true, Owning>::bufferWidth && bufferY >= 0 && bufferY < ScalingBase<true, Owning>::bufferHeight) {
ScalingBase<true, Owning>::scalingBuffer[bufferY * ScalingBase<true, Owning>::bufferWidth + bufferX] = {color.r, color.g, color.b, bitmap[j * w + i]};
}
} else {
if (bufferX >= 0 && bufferX < (int)scaled.size.x && bufferY >= 0 && bufferY < (int)scaled.size.y) {
buffer[bufferY * scaled.size.x + bufferX] = {color.r, color.g, color.b, bitmap[j * w + i]};
}
}
}
}
x += (int)(ax * scale);
if (i + 1 < line.size()) {
x += (int)stbtt_GetCodepointKernAdvance(&font.font, codepoint, line[i+1]);
}
}
currentY += lineHeight;
}
}
};
}

View file

@ -18,28 +18,27 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:RenderingElement3DVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
export module Crafter.Graphics:RenderingElement3D;
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :Mesh;
import :VulkanBuffer;
import Crafter.Math;
export namespace Crafter {
struct TlasWithBuffer {
VulkanBuffer<char, false, true, false> buffer;
VkAccelerationStructureKHR accelerationStructure;
VulkanBuffer<VkAccelerationStructureInstanceKHR, true, true, false> instanceBuffer;
};
class RenderingElement3DVulkan {
class RenderingElement3D {
public:
VkAccelerationStructureInstanceKHR instance;
static std::vector<RenderingElement3DVulkan*> elements;
static std::vector<RenderingElement3D*> elements;
inline static VulkanBuffer<char, false, true, false> scratchBuffer;
inline static std::vector<TlasWithBuffer> tlases;
static void BuildTLAS(VkCommandBuffer cmd, std::uint32_t index);

View file

@ -0,0 +1,43 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
export module Crafter.Graphics:Rendertarget;
import Crafter.Math;
import std;
import :Types;
import :Transform2D;
export namespace Crafter {
struct RenderingElement2DBase;
struct Window;
struct Rendertarget {
Vector<std::uint8_t, 4>* buffer;
#ifdef CRAFTER_TIMING
std::vector<std::tuple<const Transform*, std::uint32_t, std::uint32_t, std::chrono::nanoseconds>> renderTimings;
#endif
Transform2D transform;
std::int32_t sizeX;
std::int32_t sizeY;
std::vector<RenderingElement2DBase*> elements;
std::vector<ClipRect> dirtyRects;
Rendertarget(std::int32_t sizeX, std::int32_t sizeY);
void RenderElement(RenderingElement2DBase* transform);
void AddDirtyRect(ScaleData2D rect);
void Render();
};
}

View file

@ -19,7 +19,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
@ -29,7 +29,7 @@ import :VulkanBuffer;
import :ImageVulkan;
export namespace Crafter {
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
template <typename PixelType>
class SamplerVulkan {
public:
@ -53,7 +53,7 @@ export namespace Crafter {
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = VK_LOD_CLAMP_NONE;
VulkanDevice::CheckVkResult(vkCreateSampler(VulkanDevice::device, &samplerInfo, nullptr, &textureSampler));
Device::CheckVkResult(vkCreateSampler(Device::device, &samplerInfo, nullptr, &textureSampler));
imageInfo = {
.sampler = textureSampler

View file

@ -18,13 +18,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:ShaderBindingTableVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
import :VulkanBuffer;
import :ShaderVulkan;
import :Types;

View file

@ -18,13 +18,13 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:ShaderVulkan;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
import :Types;
export namespace Crafter {
@ -66,7 +66,7 @@ export namespace Crafter {
module_info.codeSize = spirv.size() * sizeof(uint32_t);
module_info.pCode = spirv.data();
VulkanDevice::CheckVkResult(vkCreateShaderModule(VulkanDevice::device, &module_info, nullptr, &shader));
Device::CheckVkResult(vkCreateShaderModule(Device::device, &module_info, nullptr, &shader));
}
};
@ -104,7 +104,7 @@ export namespace Crafter {
module_info.codeSize = spirv.size() * sizeof(uint32_t);
module_info.pCode = spirv.data();
VulkanDevice::CheckVkResult(vkCreateShaderModule(VulkanDevice::device, &module_info, nullptr, &shader));
Device::CheckVkResult(vkCreateShaderModule(Device::device, &module_info, nullptr, &shader));
}
};
}

View file

@ -1,33 +0,0 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#include <stdio.h>
export module Crafter.Graphics:Shm;
import std;
export namespace Crafter {
#ifdef CRAFTER_BUILD_CONFIGURATION_TARGET_x86_64_pc_linux_gnu
void randname(char *buf);
int anonymous_shm_open();
int create_shm_file(off_t size);
#endif
}

View file

@ -1,51 +0,0 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
export module Crafter.Graphics:Transform;
import std;
import :Types;
export namespace Crafter {
class Window;
struct Anchor {
std::int32_t x;
std::int32_t y;
std::uint32_t width;
std::uint32_t height;
std::int32_t offsetX;
std::int32_t offsetY;
std::int32_t z;
bool maintainAspectRatio;
Anchor() = default;
Anchor(std::int32_t x, std::int32_t y, std::uint32_t width, std::uint32_t height, std::int32_t offsetX, std::int32_t offsetY, std::int32_t z, bool maintainAspectRatio = false);
};
class Transform {
public:
Anchor anchor;
ScaleData scaled;
std::vector<Transform*> children;
Transform(Anchor anchor);
Transform(Transform&) = delete;
Transform(Transform&&) = delete;
Transform& operator=(Transform&) = delete;
virtual ~Transform() = default;
virtual void UpdatePosition(Window& window);
virtual void UpdatePosition(Window& window, Transform& parent);
};
}

View file

@ -0,0 +1,51 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
export module Crafter.Graphics:Transform2D;
import std;
import :Types;
export namespace Crafter {
struct Rendertarget;
struct Anchor2D {
float x;
float y;
float width;
float height;
float offsetX;
float offsetY;
std::int32_t z;
bool maintainAspectRatio;
Anchor2D() = default;
Anchor2D(float x, float y, float width, float height, float offsetX, float offsetY, std::int32_t z, bool maintainAspectRatio = false);
};
struct Transform2D {
Anchor2D anchor;
ScaleData2D scaled;
std::vector<Transform2D*> children;
Transform2D(Anchor2D anchor);
Transform2D(Transform2D&) = delete;
Transform2D(Transform2D&&) = delete;
Transform2D& operator=(Transform2D&) = delete;
virtual ~Transform2D() = default;
void ScaleElement(Transform2D& parent);
virtual void UpdatePosition(Rendertarget& window);
virtual void UpdatePosition(Rendertarget& window, Transform2D& parent);
};
}

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
@ -18,41 +18,23 @@ License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:Types;
import std;
import Crafter.Math;
export namespace Crafter {
struct MousePoint {
std::uint32_t x;
std::uint32_t y;
};
struct MouseDelta {
std::int64_t x;
std::int64_t y;
};
struct MouseMoveEvent {
MousePoint lastMousePos;
MousePoint currentMousePos;
MouseDelta mouseDelta;
Vector<float, 2> lastMousePos;
Vector<float, 2> currentMousePos;
Vector<float, 2> mouseDelta;
};
struct ScaleData {
std::int32_t x;
std::int32_t y;
std::int32_t width;
std::int32_t height;
};
struct ScaleDataBoundless {
std::uint32_t x;
std::uint32_t y;
std::uint32_t width;
std::uint32_t height;
struct ScaleData2D {
Vector<std::int32_t, 2> position;
Vector<std::int32_t, 2> size;
};
struct ClipRect {
@ -62,67 +44,6 @@ export namespace Crafter {
std::int32_t bottom;
};
struct __attribute__((packed)) Pixel_BU8_GU8_RU8_AU8 {
std::uint8_t b;
std::uint8_t g;
std::uint8_t r;
std::uint8_t a;
};
struct __attribute__((packed)) Pixel_RU8_GU8_BU8_AU8 {
std::uint8_t r;
std::uint8_t g;
std::uint8_t b;
std::uint8_t a;
};
struct __attribute__((packed)) Pixel_RU8_GU8_BU8 {
std::uint8_t r;
std::uint8_t g;
std::uint8_t b;
};
// struct __attribute__((packed)) Vertex {
// float x;
// float y;
// float z;
// float w;
// };
// struct __attribute__((packed)) VertexUV {
// float x;
// float y;
// float z;
// float w;
// float u;
// float v;
// float pad[2];
// };
// struct __attribute__((packed)) VertexRGBA {
// float x;
// float y;
// float z;
// float w;
// float r;
// float g;
// float b;
// float a;
// };
// struct __attribute__((packed)) HeightRGBA {
// float height;
// float pad[3];
// float r;
// float g;
// float b;
// float a;
// };
struct FrameTime {
std::chrono::time_point<std::chrono::high_resolution_clock> now;
std::chrono::duration<double> delta;
@ -134,191 +55,6 @@ export namespace Crafter {
Transparent // Color blending is used
};
constexpr std::int8_t BOUND8 = 9;
constexpr std::int8_t SCALE8 = std::numeric_limits<std::int8_t>::max() / BOUND8;
constexpr std::uint8_t SCALEBOUNDLESS8 = std::numeric_limits<std::uint8_t>::max();
constexpr double SCALEDOUBLE8 = static_cast<double>(std::numeric_limits<std::int8_t>::max() / BOUND8);
constexpr double SCALEBOUNDLESSDOUBLE8 = static_cast<double>(std::numeric_limits<std::uint8_t>::max());
constexpr std::int16_t BOUND16 = 9;
constexpr std::int16_t SCALE16 = std::numeric_limits<std::int16_t>::max() / BOUND16;
constexpr std::uint16_t SCALEBOUNDLESS16 = std::numeric_limits<std::uint16_t>::max();
constexpr double SCALEDOUBLE16 = static_cast<double>(std::numeric_limits<std::int16_t>::max() / BOUND16);
constexpr double SCALEBOUNDLESSDOUBLE16 = static_cast<double>(std::numeric_limits<std::uint16_t>::max());
constexpr std::int32_t BOUND32 = 9;
constexpr std::int32_t SCALE32 = std::numeric_limits<std::int32_t>::max() / BOUND32;
constexpr std::uint32_t SCALEBOUNDLESS32 = std::numeric_limits<std::uint32_t>::max();
constexpr double SCALEDOUBLE32 = static_cast<double>(std::numeric_limits<std::int32_t>::max() / BOUND32);
constexpr double SCALEBOUNDLESSDOUBLE32 = static_cast<double>(std::numeric_limits<std::uint32_t>::max());
constexpr std::int64_t BOUND64 = 9;
constexpr std::int64_t SCALE64 = std::numeric_limits<std::int64_t>::max() / BOUND64;
constexpr std::uint64_t SCALEBOUNDLESS64 = std::numeric_limits<std::uint64_t>::max();
constexpr double SCALEDOUBLE64 = static_cast<double>(std::numeric_limits<std::int64_t>::max() / BOUND64);
constexpr double SCALEBOUNDLESSDOUBLE64 = static_cast<double>(std::numeric_limits<std::uint64_t>::max());
template <typename T>
constexpr T FractionalToMapped(double f) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::int8_t> || std::is_same_v<T, std::uint8_t>) {
return T(f * SCALEDOUBLE8);
} else if constexpr (std::is_same_v<T, std::int16_t> || std::is_same_v<T, std::uint16_t>) {
return T(f * SCALEDOUBLE16);
} else if constexpr (std::is_same_v<T, std::int32_t> || std::is_same_v<T, std::uint32_t>) {
return T(f * SCALEDOUBLE32);
} else {
return T(f * SCALEDOUBLE64);
}
}
template <typename T>
constexpr T FractionalToMappedBoundless(double f) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t>) {
return T(f * SCALEBOUNDLESSDOUBLE8);
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return T(f * SCALEBOUNDLESSDOUBLE16);
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return T(f * SCALEBOUNDLESSDOUBLE32);
} else {
return T(f * SCALEBOUNDLESSDOUBLE64);
}
}
template <typename T>
constexpr double MappedToFractional(T mapped) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::int8_t> || std::is_same_v<T, std::uint8_t>) {
return mapped / SCALEDOUBLE8;
} else if constexpr (std::is_same_v<T, std::int16_t> || std::is_same_v<T, std::uint16_t>) {
return mapped / SCALEDOUBLE16;
} else if constexpr (std::is_same_v<T, std::int32_t> || std::is_same_v<T, std::uint32_t>) {
return mapped / SCALEDOUBLE32;
} else {
return mapped / SCALEDOUBLE64;
}
}
template <typename T>
constexpr double MappedToFractionalBoundless(T mapped) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t>) {
return mapped / SCALEBOUNDLESSDOUBLE8;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return mapped / SCALEBOUNDLESSDOUBLE16;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return mapped / SCALEBOUNDLESSDOUBLE32;
} else {
return mapped / SCALEBOUNDLESSDOUBLE64;
}
}
template <typename T>
constexpr double MappedToNDCBoundless(T mapped, std::uint32_t size) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t>) {
return mapped / SCALEBOUNDLESSDOUBLE8 - 0.5;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return mapped / SCALEBOUNDLESSDOUBLE16 - 0.5;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return mapped / SCALEBOUNDLESSDOUBLE32 - 0.5;
} else {
return mapped / SCALEBOUNDLESSDOUBLE64 - 0.5;
}
}
template <typename T, typename T2>
constexpr T MappedToAbsolute(T mapped, T2 absolute) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::int8_t> || std::is_same_v<T, std::uint8_t>) {
return static_cast<std::int16_t>(mapped) * absolute / SCALE8;
} else if constexpr (std::is_same_v<T, std::int16_t> || std::is_same_v<T, std::uint16_t>) {
return static_cast<std::int32_t>(mapped) * absolute / SCALE16;
} else if constexpr (std::is_same_v<T, std::int32_t> || std::is_same_v<T, std::uint32_t>) {
return static_cast<std::int64_t>(mapped) * absolute / SCALE32;
} else {
return static_cast<__int128>(mapped) * absolute / SCALE64;
}
}
template <typename T, typename T2>
constexpr T MappedToAbsoluteBoundless(T mapped, T2 absolute) requires(std::is_integral_v<T>) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t>) {
return static_cast<std::uint16_t>(mapped) * absolute / SCALEBOUNDLESS8;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return static_cast<std::uint32_t>(mapped) * absolute / SCALEBOUNDLESS16;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return static_cast<std::uint64_t>(mapped) * absolute / SCALEBOUNDLESS32;
} else {
return static_cast<unsigned __int128>(mapped) * absolute / SCALEBOUNDLESS64;
}
}
// template <typename T, typename T2>
// constexpr T PixelToMappedBoundless(T pixel, T2 screen) requires(std::is_integral_v<T>) {
// if constexpr (std::is_same_v<T, std::uint8_t>) {
// return (static_cast<std::uint16_t>(relative) * SCALE8) / (static_cast<std::uint16_t>(absolute) * SCALE8);
// } else if constexpr (std::is_same_v<T, std::uint16_t>) {
// return (static_cast<std::uint32_t>(relative) * SCALE16) / (static_cast<std::uint32_t>(absolute) * SCALE16);
// } else if constexpr (std::is_same_v<T, std::uint32_t>) {
// return (static_cast<std::uint64_t>(relative) * SCALE32) / (static_cast<std::uint64_t>(absolute) * SCALE32);
// } else {
// return (static_cast<unsigned __int128>(relative) * SCALE32) / (static_cast<unsigned __int128>(absolute) * SCALE32);
// }
// }
template <typename T, typename T2>
constexpr T AbsoluteToMapped(T absolute, T2 mapped) {
if constexpr (std::is_same_v<T, std::int8_t> || std::is_same_v<T, std::uint8_t>) {
return static_cast<std::int16_t>(absolute) * SCALE8 / mapped;
} else if constexpr (std::is_same_v<T, std::int16_t> || std::is_same_v<T, std::uint16_t> ) {
return static_cast<std::int32_t>(absolute) * SCALE16 / mapped;
} else if constexpr (std::is_same_v<T, std::int32_t>|| std::is_same_v<T, std::uint32_t>) {
return static_cast<std::int64_t>(absolute) * SCALE32 / mapped;
} else {
return static_cast<__int128>(absolute) * SCALE64 / mapped;
}
}
template <typename T, typename T2>
constexpr T AbsoluteToMappedBoundless(T absolute, T2 mapped) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t> ) {
return static_cast<std::uint16_t>(absolute) * SCALEBOUNDLESS8 / mapped;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return static_cast<std::uint32_t>(absolute) * SCALEBOUNDLESS16 / mapped;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return static_cast<std::uint64_t>(absolute) * SCALEBOUNDLESS32 / mapped;
} else {
return static_cast<unsigned __int128>(absolute) * SCALEBOUNDLESS64 / mapped;
}
}
template <typename T>
constexpr T BoundToBoundless(T mapped) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t>) {
return mapped * BOUND8 * 2;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return mapped * BOUND16 * 2;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return mapped * BOUND32 * 2;
} else {
return mapped * BOUND64 * 2;
}
}
template <typename T>
constexpr T BoundlessToBound(T mapped) {
if constexpr (std::is_same_v<T, std::uint8_t> || std::is_same_v<T, std::int8_t> ) {
return mapped / 2;
} else if constexpr (std::is_same_v<T, std::uint16_t> || std::is_same_v<T, std::int16_t>) {
return mapped / 2;
} else if constexpr (std::is_same_v<T, std::uint32_t> || std::is_same_v<T, std::int32_t>) {
return mapped / 2;
} else {
return mapped / 2;
}
}
enum class CrafterKeys {
// Alphabetic keys
A, B, C, D, E, F, G, H, I, J, K, L, M,
@ -372,7 +108,7 @@ export namespace Crafter {
return std::tan(fov * std::numbers::pi / 360.0);
}
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
struct DescriptorBinding {
VkDescriptorType type;
std::uint32_t slot;

View file

@ -19,14 +19,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:VulkanBuffer;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
import :VulkanDevice;
import :Device;
namespace Crafter {
export class VulkanBufferBase {
@ -95,14 +95,14 @@ namespace Crafter {
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.usage = usageFlags;
bufferCreateInfo.size = sizeof(T)*count;
VulkanDevice::CheckVkResult(vkCreateBuffer(VulkanDevice::device, &bufferCreateInfo, nullptr, &buffer));
Device::CheckVkResult(vkCreateBuffer(Device::device, &bufferCreateInfo, nullptr, &buffer));
VkMemoryRequirements memReqs;
vkGetBufferMemoryRequirements(VulkanDevice::device, buffer, &memReqs);
vkGetBufferMemoryRequirements(Device::device, buffer, &memReqs);
VkMemoryAllocateInfo memAlloc {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = memReqs.size,
.memoryTypeIndex = VulkanDevice::GetMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags)
.memoryTypeIndex = Device::GetMemoryType(memReqs.memoryTypeBits, memoryPropertyFlags)
};
if constexpr(Adressable) {
VkMemoryAllocateFlagsInfoKHR allocFlagsInfo {
@ -110,36 +110,36 @@ namespace Crafter {
.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR,
};
memAlloc.pNext = &allocFlagsInfo;
VulkanDevice::CheckVkResult(vkAllocateMemory(VulkanDevice::device, &memAlloc, nullptr, &memory));
Device::CheckVkResult(vkAllocateMemory(Device::device, &memAlloc, nullptr, &memory));
} else {
VulkanDevice::CheckVkResult(vkAllocateMemory(VulkanDevice::device, &memAlloc, nullptr, &memory));
Device::CheckVkResult(vkAllocateMemory(Device::device, &memAlloc, nullptr, &memory));
}
descriptor.offset = 0;
descriptor.buffer = buffer;
descriptor.range = VK_WHOLE_SIZE;
VulkanDevice::CheckVkResult(vkBindBufferMemory(VulkanDevice::device, buffer, memory, 0));
Device::CheckVkResult(vkBindBufferMemory(Device::device, buffer, memory, 0));
if constexpr(Adressable) {
VkBufferDeviceAddressInfo addressInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO,
.buffer = buffer
};
VulkanBufferAdressableConditional<true>::address = vkGetBufferDeviceAddress(VulkanDevice::device, &addressInfo);
VulkanBufferAdressableConditional<true>::address = vkGetBufferDeviceAddress(Device::device, &addressInfo);
}
if constexpr(Mapped) {
VulkanDevice::CheckVkResult(vkMapMemory(VulkanDevice::device, memory, 0, memReqs.size, 0, reinterpret_cast<void**>(&(VulkanBufferMappedConditional<T, true>::value))));
Device::CheckVkResult(vkMapMemory(Device::device, memory, 0, memReqs.size, 0, reinterpret_cast<void**>(&(VulkanBufferMappedConditional<T, true>::value))));
}
}
void Clear() {
if constexpr(Mapped) {
vkUnmapMemory(VulkanDevice::device, memory);
vkUnmapMemory(Device::device, memory);
}
vkDestroyBuffer(VulkanDevice::device, buffer, nullptr);
vkFreeMemory(VulkanDevice::device, memory, nullptr);
vkDestroyBuffer(Device::device, buffer, nullptr);
vkFreeMemory(Device::device, memory, nullptr);
buffer = VK_NULL_HANDLE;
if constexpr(Staged) {
delete VulkanBufferMappedConditional<T, true>::stagingBuffer;
@ -201,7 +201,7 @@ namespace Crafter {
.offset = 0,
.size = VK_WHOLE_SIZE
};
vkFlushMappedMemoryRanges(VulkanDevice::device, 1, &range);
vkFlushMappedMemoryRanges(Device::device, 1, &range);
}
void FlushDevice(VkCommandBuffer cmd, VkAccessFlags dstAccessMask, VkPipelineStageFlags dstStageMask) requires(Mapped) {
@ -235,7 +235,7 @@ namespace Crafter {
.offset = 0,
.size = VK_WHOLE_SIZE
};
vkInvalidateMappedMemoryRanges(VulkanDevice::device, 1, &range);
vkInvalidateMappedMemoryRanges(Device::device, 1, &range);
}
void FlushDevice(VkCommandBuffer cmd) requires(Staged) {

View file

@ -1,59 +0,0 @@
/*
Crafter®.Graphics
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 3.0 as published by the Free Software Foundation;
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#include "vulkan/vulkan.h"
#endif
export module Crafter.Graphics:VulkanDevice;
#ifdef CRAFTER_GRAPHICS_VULKAN
import std;
export namespace Crafter {
class VulkanDevice {
public:
inline static VkInstance instance = VK_NULL_HANDLE;
inline static VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
inline static VkPhysicalDevice physDevice = VK_NULL_HANDLE;
inline static VkDevice device = VK_NULL_HANDLE;
inline static std::uint32_t queueFamilyIndex = 0;
inline static VkQueue queue = VK_NULL_HANDLE;
inline static VkCommandPool commandPool = VK_NULL_HANDLE;
inline static VkSwapchainKHR swapchain = VK_NULL_HANDLE;
inline static PFN_vkCmdDrawMeshTasksEXT vkCmdDrawMeshTasksEXTProc;
inline static PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHRProc;
inline static PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHRProc;
inline static PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR;
inline static PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR;
inline static PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR;
inline static PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddressKHR;
inline static PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR;
inline static PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR;
inline static PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR;
inline static VkPhysicalDeviceMemoryProperties memoryProperties;
inline static VkPhysicalDeviceRayTracingPipelinePropertiesKHR rayTracingProperties = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR
};
static void CreateDevice();
static void CheckVkResult(VkResult result);
static std::uint32_t GetMemoryType(std::uint32_t typeBits, VkMemoryPropertyFlags properties);
};
}
#endif

View file

@ -18,12 +18,12 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#include <assert.h>
#endif
export module Crafter.Graphics:VulkanTransition;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import std;
export namespace Crafter {

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
catcrafts.net
This library is free software; you can redistribute it and/or
@ -18,7 +18,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
module;
#ifdef CRAFTER_GRAPHICS_WAYLAND
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
@ -32,95 +32,46 @@ module;
#include <linux/input.h>
#include <sys/mman.h>
#include <wayland-cursor.h>
#include <xkbcommon/xkbcommon.h>
#include <errno.h>
#include <fcntl.h>
#include <print>
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#endif
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifndef CRAFTER_GRAPHICS_WINDOWS
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input-event-codes.h>
#include <xkbcommon/xkbcommon.h>
#include "../lib/xdg-shell-client-protocol.h"
#include "../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
#include "../lib/fractional-scale-v1.h"
#include "../lib/viewporter.h"
#include <string.h>
#include <linux/input.h>
#include <sys/mman.h>
#include <wayland-cursor.h>
#include <xkbcommon/xkbcommon.h>
#include <errno.h>
#include <fcntl.h>
#include <print>
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
#include "vulkan/vulkan.h"
#include "vulkan/vulkan_wayland.h"
#else
#include "vulkan/vulkan.h"
#endif
#endif
export module Crafter.Graphics:Window;
import std;
import :Types;
import :Rendertarget;
import :Transform2D;
import Crafter.Event;
#ifdef CRAFTER_GRAPHICS_VULKAN
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
import :PipelineRTVulkan;
#endif
export namespace Crafter {
class Transform;
class MouseElement;
class Window {
public:
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
struct Semaphores {
// Swap chain image presentation
VkSemaphore presentComplete;
// Command buffer submission and execution
VkSemaphore renderComplete;
};
#endif
struct MouseElement;
struct Window {
FrameTime currentFrameTime;
std::int32_t width;
std::int32_t height;
std::uint32_t width;
std::uint32_t height;
std::chrono::time_point<std::chrono::high_resolution_clock> lastFrameBegin;
std::vector<Transform*> elements;
Event<void> onClose;
Event<FrameTime> onUpdate;
bool open = true;
bool updating = false;
std::vector<ClipRect> dirtyRects;
float scale;
Window() = default;
Window(std::int32_t width, std::int32_t height);
Window(Window&) = delete;
Window(Window&&) = delete;
virtual ~Window() = default;
Window& operator=(const Window&) = delete;
void AddDirtyRect(ScaleData rect);
virtual void StartSync() = 0;
virtual void StartUpdate() = 0;
virtual void StopUpdate() = 0;
void ScaleElement(Transform& element, Transform& parent);
void ScaleElement(Transform& element);
void ScaleMouse(MouseElement& element, Transform& parent);
void ScaleMouse(MouseElement& element);
#ifdef CRAFTER_TIMING
std::chrono::nanoseconds totalUpdate;
std::vector<std::pair<const EventListener<FrameTime>*, std::chrono::nanoseconds>> updateTimings;
std::chrono::nanoseconds totalRender;
std::vector<std::tuple<const Transform*, std::uint32_t, std::uint32_t, std::chrono::nanoseconds>> renderTimings;
std::chrono::nanoseconds vblank;
std::chrono::nanoseconds totalFrame;
std::chrono::time_point<std::chrono::high_resolution_clock> frameEnd;
std::vector<std::chrono::nanoseconds> frameTimes;
void LogTiming();
#endif
};
class WindowKeyboard {
public:
bool heldkeys[static_cast<std::uint32_t>(CrafterKeys::CrafterKeysMax)] = {};
Event<void> onKeyDown[static_cast<std::uint32_t>(CrafterKeys::CrafterKeysMax)];
Event<void> onKeyHold[static_cast<std::uint32_t>(CrafterKeys::CrafterKeysMax)];
@ -128,134 +79,69 @@ export namespace Crafter {
Event<CrafterKeys> onAnyKeyDown;
Event<CrafterKeys> onAnyKeyHold;
Event<CrafterKeys> onAnyKeyUp;
};
class MouseElement;
class WindowMouse {
public:
Event<MousePoint> onMouseRightClick;
Event<MousePoint> onMouseLeftClick;
Event<MousePoint> onMouseRightHold;
Event<MousePoint> onMouseLeftHold;
Event<MousePoint> onMouseRightRelease;
Event<MousePoint> onMouseLeftRelease;
Event<MouseMoveEvent> onMouseMove;
Event<MouseMoveEvent> onMouseEnter;
Event<MouseMoveEvent> onMouseLeave;
Event<void> onMouseRightClick;
Event<void> onMouseLeftClick;
Event<void> onMouseRightHold;
Event<void> onMouseLeftHold;
Event<void> onMouseRightRelease;
Event<void> onMouseLeftRelease;
Event<void> onMouseMove;
Event<void> onMouseEnter;
Event<void> onMouseLeave;
Event<std::uint32_t> onMouseScroll;
MousePoint currentMousePos;
MousePoint lastMousePos;
MouseDelta mouseDelta;
Vector<float, 2> currentMousePos;
Vector<float, 2> lastMousePos;
Vector<float, 2> mouseDelta;
bool mouseLeftHeld = false;
bool mouseRightHeld = false;
std::vector<MouseElement*> mouseElements;
std::vector<MouseElement*> pendingMouseElements;
};
class WindowTitle {
public:
virtual void SetTitle(const std::string_view title) = 0;
};
Window(std::uint32_t width, std::uint32_t height);
Window(std::uint32_t width, std::uint32_t height, const std::string_view title);
Window(Window&) = delete;
Window(Window&&) = delete;
Window& operator=(const Window&) = delete;
class Transform;
class WindowFramebuffer : public Window {
public:
WindowFramebuffer() = default;
WindowFramebuffer(std::uint32_t width, std::uint32_t height);
virtual void Resize(std::uint32_t width, std::uint32_t height) = 0;
virtual void Write(Pixel_BU8_GU8_RU8_AU8* pixels) = 0;
virtual void Write(std::uint32_t x, std::uint32_t y, Pixel_BU8_GU8_RU8_AU8 pixel) = 0;
virtual Pixel_BU8_GU8_RU8_AU8 Read(std::uint32_t x, std::uint32_t y) const = 0;
virtual const Pixel_BU8_GU8_RU8_AU8* Read() const = 0;
virtual Pixel_BU8_GU8_RU8_AU8* Get() = 0;
virtual void Store() = 0;
virtual void Render() = 0;
};
void StartSync();
void StartUpdate();
void StopUpdate();
void SetTitle(const std::string_view title);
void Resize(std::uint32_t width, std::uint32_t height);
void Render();
void Update();
#ifdef CRAFTER_GRAPHICS_WAYLAND
class WindowWayland final : public WindowKeyboard, public WindowMouse, public WindowFramebuffer, public WindowTitle {
public:
Pixel_BU8_GU8_RU8_AU8* framebuffer = nullptr;
WindowWayland(std::uint32_t width, std::uint32_t height);
WindowWayland(std::uint32_t width, std::uint32_t height, const std::string_view title);
~WindowWayland();
#ifdef CRAFTER_TIMING
std::chrono::nanoseconds totalUpdate;
std::vector<std::pair<const EventListener<FrameTime>*, std::chrono::nanoseconds>> updateTimings;
std::chrono::nanoseconds totalRender;
std::chrono::nanoseconds vblank;
std::chrono::nanoseconds totalFrame;
std::chrono::time_point<std::chrono::high_resolution_clock> frameEnd;
std::vector<std::chrono::nanoseconds> frameTimes;
void LogTiming();
#endif
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
float scale;
#ifdef CRAFTER_GRAPHICS_RENDERER_SOFTWARE
Rendertarget renderer;
#endif
bool configured = false;
wl_shm* shm = nullptr;
wl_seat* seat = nullptr;
wp_fractional_scale_v1* wp_scale = nullptr;
xdg_toplevel* xdgToplevel = nullptr;
wp_viewport* wpViewport = nullptr;
wp_viewporter* wpViewporter = nullptr;
xdg_wm_base* xdgWmBase = nullptr;
zxdg_decoration_manager_v1* manager = nullptr;
wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr;
wl_surface* surface = nullptr;
wl_buffer* buffer = nullptr;
wl_buffer* backBuffer = nullptr;
xdg_surface* xdgSurface = nullptr;
wl_display* display = nullptr;
wl_callback* cb = nullptr;
xkb_keymap* xkb_keymap;
xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
xkb_state* xkb_state;
void RenderElement(Transform* transform);
void Render() override;
void QueueRender();
void StartSync() override;
void StartUpdate() override;
void StopUpdate() override;
void SetTitle(const std::string_view title) override;
void Resize(std::uint32_t width, std::uint32_t height) override;
void Write(Pixel_BU8_GU8_RU8_AU8* pixels) override;
void Write(std::uint32_t x, std::uint32_t y, Pixel_BU8_GU8_RU8_AU8 pixel) override;
Pixel_BU8_GU8_RU8_AU8 Read(std::uint32_t x, std::uint32_t y) const override;
const Pixel_BU8_GU8_RU8_AU8* Read() const override;
Pixel_BU8_GU8_RU8_AU8* Get() override;
void Store() override;
inline static wl_compositor* compositor = nullptr;
static void wl_surface_frame_done(void *data, wl_callback *cb, uint32_t time);
static void PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value);
static void PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleLeave(void*, wl_pointer*, std::uint32_t, wl_surface*);
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void handle_global(void* data, wl_registry* registry, std::uint32_t name, const char* interface, std::uint32_t version);
static void pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state);
static void seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
static void xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale);
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial);
static void keyboard_keymap(void* data, wl_keyboard* keyboard, uint32_t format, int fd, uint32_t size);
static void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys);
static void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface);
static void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state);
static void keyboard_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group);
static void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay);
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name);
static void wl_surface_frame_done(void *data, wl_callback *cb, uint32_t time);
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
static void xdg_toplevel_configure(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*);
constexpr static wl_pointer_listener pointer_listener = {
.enter = PointerListenerHandleEnter,
.leave = PointerListenerHandleLeave,
.motion = PointerListenerHandleMotion,
.button = pointer_handle_button,
.axis = PointerListenerHandleAxis,
};
constexpr static wl_keyboard_listener keyboard_listener = {
.keymap = keyboard_keymap,
.enter = keyboard_enter,
.leave = keyboard_leave,
.key = keyboard_key,
.modifiers = keyboard_modifiers,
.repeat_info = keyboard_repeat_info,
};
constexpr static wl_seat_listener seat_listener = {
.capabilities = seat_handle_capabilities,
};
constexpr static wl_registry_listener registry_listener = {
.global = handle_global,
.global_remove = handle_global_remove,
};
constexpr static xdg_toplevel_listener xdg_toplevel_listener = {
.configure = xdg_toplevel_configure,
.close = xdg_toplevel_handle_close,
@ -263,60 +149,17 @@ export namespace Crafter {
constexpr static wl_callback_listener wl_callback_listener = {
.done = wl_surface_frame_done,
};
constexpr static xdg_wm_base_listener xdgWmBaseListener = {
.ping = xdg_wm_base_handle_ping,
};
constexpr static xdg_surface_listener xdg_surface_listener = {
.configure = xdg_surface_handle_configure,
};
constexpr static wp_fractional_scale_v1_listener wp_fractional_scale_v1_listener = {
.preferred_scale = xdg_surface_handle_preferred_scale,
};
};
#endif
inline static wp_fractional_scale_v1* wp_scale = nullptr;
#endif
#ifdef CRAFTER_GRAPHICS_VULKAN
struct Semaphores {
// Swap chain image presentation
VkSemaphore presentComplete;
// Command buffer submission and execution
VkSemaphore renderComplete;
};
#ifndef CRAFTER_GRAPHICS_WINDOWS
class WindowVulkan final : public Window, public WindowKeyboard, public WindowMouse, public WindowTitle {
public:
WindowVulkan(std::uint32_t width, std::uint32_t height);
WindowVulkan(std::uint32_t width, std::uint32_t height, const std::string_view title);
~WindowVulkan();
bool configured = false;
wl_shm* shm = nullptr;
wl_seat* seat = nullptr;
wp_fractional_scale_v1* wp_scale = nullptr;
xdg_toplevel* xdgToplevel = nullptr;
wp_viewport* wpViewport = nullptr;
wp_viewporter* wpViewporter = nullptr;
xdg_wm_base* xdgWmBase = nullptr;
zxdg_decoration_manager_v1* manager = nullptr;
wp_fractional_scale_manager_v1* fractionalScaleManager = nullptr;
wl_surface* surface = nullptr;
xdg_surface* xdgSurface = nullptr;
wl_display* display = nullptr;
wl_callback* cb = nullptr;
xkb_keymap* xkb_keymap;
xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
xkb_state* xkb_state;
Event<void> onRender;
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
std::vector<VkDescriptorSet> descriptorsRt;
void Render();
void QueueRender();
void Resize(std::uint32_t width, std::uint32_t height);
void StartSync() override;
void StartUpdate() override;
void StopUpdate() override;
void SetTitle(const std::string_view title) override;
VkCommandBuffer StartInit();
void FinishInit();
template <typename Pipeline>
void SetPipelineRT() {
rtPipeline = Pipeline::pipeline;
@ -326,77 +169,11 @@ export namespace Crafter {
hitRegion = Pipeline::hitRegion;
callableRegion = Pipeline::callableRegion;
}
void SetPipelineRT(PipelineRTVulkan& pipeline) {
rtPipeline = pipeline.pipeline;
rtPipelineLayout = pipeline.pipelineLayout;
raygenRegion = pipeline.raygenRegion;
missRegion = pipeline.missRegion;
hitRegion = pipeline.hitRegion;
callableRegion = pipeline.callableRegion;
}
inline static wl_compositor* compositor = nullptr;
static void wl_surface_frame_done(void *data, wl_callback *cb, uint32_t time);
static void PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value);
static void PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y);
static void PointerListenerHandleLeave(void*, wl_pointer*, std::uint32_t, wl_surface*);
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void handle_global(void* data, wl_registry* registry, std::uint32_t name, const char* interface, std::uint32_t version);
static void pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state);
static void seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
static void xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale);
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial);
static void keyboard_keymap(void* data, wl_keyboard* keyboard, uint32_t format, int fd, uint32_t size);
static void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys);
static void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface);
static void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state);
static void keyboard_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group);
static void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay);
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name);
static void xdg_toplevel_configure(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*);
constexpr static wl_pointer_listener pointer_listener = {
.enter = PointerListenerHandleEnter,
.leave = PointerListenerHandleLeave,
.motion = PointerListenerHandleMotion,
.button = pointer_handle_button,
.axis = PointerListenerHandleAxis,
};
constexpr static wl_keyboard_listener keyboard_listener = {
.keymap = keyboard_keymap,
.enter = keyboard_enter,
.leave = keyboard_leave,
.key = keyboard_key,
.modifiers = keyboard_modifiers,
.repeat_info = keyboard_repeat_info,
};
constexpr static wl_seat_listener seat_listener = {
.capabilities = seat_handle_capabilities,
};
constexpr static wl_registry_listener registry_listener = {
.global = handle_global,
.global_remove = handle_global_remove,
};
constexpr static xdg_toplevel_listener xdg_toplevel_listener = {
.configure = xdg_toplevel_configure,
.close = xdg_toplevel_handle_close,
};
constexpr static wl_callback_listener wl_callback_listener = {
.done = wl_surface_frame_done,
};
constexpr static xdg_wm_base_listener xdgWmBaseListener = {
.ping = xdg_wm_base_handle_ping,
};
constexpr static xdg_surface_listener xdg_surface_listener = {
.configure = xdg_surface_handle_configure,
};
constexpr static wp_fractional_scale_v1_listener wp_fractional_scale_v1_listener = {
.preferred_scale = xdg_surface_handle_preferred_scale,
};
void SetPipelineRT(PipelineRTVulkan& pipeline);
VkCommandBuffer StartInit();
void FinishInit();
void CreateSwapchain();
static constexpr std::uint32_t numFrames = 3;
static constexpr std::uint8_t numFrames = 3;
VkSurfaceKHR vulkanSurface = VK_NULL_HANDLE;
VkSwapchainKHR swapChain = VK_NULL_HANDLE;
VkFormat colorFormat;
@ -407,7 +184,7 @@ export namespace Crafter {
VkCommandBuffer drawCmdBuffers[numFrames];
VkSubmitInfo submitInfo;
Semaphores semaphores;
uint32_t currentBuffer = 0;
std::uint32_t currentBuffer = 0;
VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkPipeline rtPipeline;
VkPipelineLayout rtPipelineLayout;
@ -415,64 +192,6 @@ export namespace Crafter {
VkStridedDeviceAddressRegionKHR missRegion;
VkStridedDeviceAddressRegionKHR hitRegion;
VkStridedDeviceAddressRegionKHR callableRegion;
#endif
};
#else
class WindowVulkan final : public Window, public WindowKeyboard, public WindowMouse, public WindowTitle {
public:
WindowVulkan(std::uint32_t width, std::uint32_t height);
WindowVulkan(std::uint32_t width, std::uint32_t height, const std::string_view title);
~WindowVulkan();
Event<void> onRender;
std::vector<VkDescriptorSet> descriptorsRt;
void Render();
void QueueRender();
void Resize(std::uint32_t width, std::uint32_t height);
void StartSync() override;
void StartUpdate() override;
void StopUpdate() override;
void SetTitle(const std::string_view title) override;
VkCommandBuffer StartInit();
void FinishInit();
template <typename Pipeline>
void SetPipelineRT() {
rtPipeline = Pipeline::pipeline;
rtPipelineLayout = Pipeline::pipelineLayout;
raygenRegion = Pipeline::raygenRegion;
missRegion = Pipeline::missRegion;
hitRegion = Pipeline::hitRegion;
callableRegion = Pipeline::callableRegion;
}
void SetPipelineRT(PipelineRTVulkan& pipeline) {
rtPipeline = pipeline.pipeline;
rtPipelineLayout = pipeline.pipelineLayout;
raygenRegion = pipeline.raygenRegion;
missRegion = pipeline.missRegion;
hitRegion = pipeline.hitRegion;
callableRegion = pipeline.callableRegion;
}
void CreateSwapchain();
static constexpr std::uint32_t numFrames = 3;
VkSurfaceKHR vulkanSurface = VK_NULL_HANDLE;
VkSwapchainKHR swapChain = VK_NULL_HANDLE;
VkFormat colorFormat;
VkColorSpaceKHR colorSpace;
VkImage images[numFrames];
VkImageView imageViews[numFrames];
std::thread thread;
VkCommandBuffer drawCmdBuffers[numFrames];
VkSubmitInfo submitInfo;
Semaphores semaphores;
uint32_t currentBuffer = 0;
VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkPipeline rtPipeline;
VkPipelineLayout rtPipelineLayout;
VkStridedDeviceAddressRegionKHR raygenRegion;
VkStridedDeviceAddressRegionKHR missRegion;
VkStridedDeviceAddressRegionKHR hitRegion;
VkStridedDeviceAddressRegionKHR callableRegion;
};
#endif
#endif
}

View file

@ -1,6 +1,6 @@
/*
Crafter®.Graphics
Copyright (C) 2025 Catcrafts®
Copyright (C) 2026 Catcrafts®
Catcrafts.net
This library is free software; you can redistribute it and/or
@ -21,26 +21,26 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
export module Crafter.Graphics;
export import :Window;
export import :Transform;
export import :RenderingElement;
export import :Transform2D;
export import :RenderingElement2D;
export import :MouseElement;
export import :GridElement;
export import :Types;
export import :Device;
export import :Font;
export import :Image;
export import :Shm;
export import :Animation;
export import :Mesh;
export import :Rendertarget;
#ifdef CRAFTER_GRAPHICS_VULKAN
export import :VulkanDevice;
#ifdef CRAFTER_GRAPHICS_RENDERER_VULKAN
export import :Device;
export import :VulkanTransition;
export import :VulkanBuffer;
export import :DescriptorPoolVulkan;
export import :ShaderVulkan;
export import :ShaderBindingTableVulkan;
export import :PipelineRTVulkan;
export import :RenderingElement3DVulkan;
export import :RenderingElement3D;
export import :ImageVulkan;
export import :SamplerVulkan;
export import :DescriptorSetLayoutVulkan;
@ -55,6 +55,6 @@ export import :DescriptorSetLayoutVulkan;
// export import :TextureShader;
// export import :DescriptorSet;
// export import :HeightmapShader;
// export import :VulkanDevice;
// export import :Device;
// export import :VulkanPipeline;
// export import :VulkanShader;