semi working wayland
This commit is contained in:
parent
e795ab880c
commit
4bb7219ccf
34 changed files with 13863 additions and 3121 deletions
|
|
@ -1,66 +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
|
||||
*/
|
||||
|
||||
module;
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
module Crafter.Graphics:Camera_impl;
|
||||
import :Camera;
|
||||
import Crafter.Math;
|
||||
import Crafter.Event;
|
||||
using namespace Crafter;
|
||||
|
||||
Camera::Camera(float fov, float aspectRatio, float near, float far) {
|
||||
projection = MatrixRowMajor<float, 4, 4, 1>::Perspective(fov, aspectRatio, near, far);
|
||||
view = MatrixRowMajor<float, 4, 4, 1>::Identity();
|
||||
}
|
||||
|
||||
void Camera::Update() {
|
||||
projectionView = projection*view;
|
||||
onUpdate.Invoke();
|
||||
}
|
||||
|
||||
Vector<float, 3> Camera::ToRay(uint32_t x, uint32_t y) {
|
||||
// // Normalize the screen coordinates
|
||||
// float mx = (2.0f * x) / sizeX - 1.0f;
|
||||
// float my = 1.0f - (2.0f * y) / sizeY;
|
||||
//
|
||||
// // Construct Ray in Homogeneous Clip Space
|
||||
// Vector<float, 3> rayOrigin = Vector<float, 3>(mx, my, 0.0f);
|
||||
// Vector<float, 3> rayEnd = Vector<float, 3>(mx, my, 1.0f);
|
||||
//
|
||||
// // Transform Ray to View Space
|
||||
// MatrixRowMajor<float, 4, 4, 1> invProjection = DirectX::XMMatrixInverse(NULL, projectionMatrix);
|
||||
// Vector<float, 3> rayOriginView = DirectX::XMVector3TransformCoord(rayOrigin, invProjection);
|
||||
// Vector<float, 3> rayEndView = DirectX::XMVector3TransformCoord(rayEnd, invProjection);
|
||||
//
|
||||
// // Transform Ray to World Space
|
||||
// DirectX::XMMATRIX viewMatrix = GetViewMatrix(); // Assuming this returns the view matrix
|
||||
// DirectX::XMMATRIX invView = DirectX::XMMatrixInverse(NULL, viewMatrix);
|
||||
// Vector<float, 3> rayOriginWorld = DirectX::XMVector3TransformCoord(rayOriginView, invView);
|
||||
// Vector<float, 3> rayEndWorld = DirectX::XMVector3TransformCoord(rayEndView, invView);
|
||||
//
|
||||
// // Compute Ray Direction
|
||||
// DirectX::XMVECTOR rayDirWorld = DirectX::XMVector3Normalize(DirectX::XMVectorSubtract(rayEndWorld, rayOriginWorld));
|
||||
//
|
||||
// return rayDirWorld;
|
||||
return Vector<float, 3>(0,0,0);
|
||||
}
|
||||
62
implementations/Crafter.Graphics-Font.cpp
Normal file
62
implementations/Crafter.Graphics-Font.cpp
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
module;
|
||||
#define STB_TRUETYPE_IMPLEMENTATION
|
||||
#include "../lib/stb_truetype.h"
|
||||
module Crafter.Graphics:Font_impl;
|
||||
import :Font;
|
||||
import std;
|
||||
|
||||
using namespace Crafter;
|
||||
|
||||
Font::Font(const std::filesystem::path& fontFilePath) {
|
||||
std::cout << "Tes3t" << std::endl;
|
||||
// 1. Load the font file into memory
|
||||
std::ifstream fontFile("inter.ttf", std::ios::binary | std::ios::ate);
|
||||
if (!fontFile.is_open()) {
|
||||
std::cerr << "Failed to open font file\n";
|
||||
}
|
||||
|
||||
std::cout << "Test" << std::endl;
|
||||
std::streamsize size = fontFile.tellg();
|
||||
fontFile.seekg(0, std::ios::beg);
|
||||
fontBuffer.resize(size);
|
||||
if (!fontFile.read((char*)fontBuffer.data(), size)) {
|
||||
std::cerr << "Failed to read font file\n";
|
||||
}
|
||||
std::cout << size << std::endl;
|
||||
|
||||
// 2. Initialize the font
|
||||
if (!stbtt_InitFont(&font, fontBuffer.data(), stbtt_GetFontOffsetForIndex(fontBuffer.data(), 0))) {
|
||||
std::cout << "Test6" << std::endl;
|
||||
std::cerr << "Failed to initialize font.\n";
|
||||
}
|
||||
|
||||
int ascent;
|
||||
int descent;
|
||||
int lineGap;
|
||||
|
||||
stbtt_GetFontVMetrics(&font, &ascent, &descent, &lineGap);
|
||||
|
||||
this->ascent = ascent;
|
||||
this->descent = descent;
|
||||
this->lineGap = lineGap;
|
||||
}
|
||||
|
|
@ -18,16 +18,99 @@ 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;
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#include "../lib/stb_image.h"
|
||||
#include "../lib/stb_truetype.h"
|
||||
module Crafter.Graphics:UiElement_impl;
|
||||
import :UiElement;
|
||||
import :Font;
|
||||
import std;
|
||||
|
||||
using namespace Crafter;
|
||||
|
||||
UiElement::UiElement(float anchorX, float anchorY, float relativeWidth, float relativeHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), relativeWidth(relativeWidth), relativeHeight(relativeHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), useRelativeSize(true), ignoreScaling(ignoreScaling) {
|
||||
|
||||
}
|
||||
|
||||
UiElement::UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, std::uint32_t absoluteWidth, std::uint32_t absoluteHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), bufferWidth(bufferWidth), bufferHeight(bufferHeight), absoluteWidth(absoluteWidth), absoluteHeight(absoluteHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), buffer(bufferWidth*bufferHeight), useRelativeSize(false), ignoreScaling(ignoreScaling) {
|
||||
|
||||
}
|
||||
|
||||
UiElement::UiElement(float anchorX, float anchorY, std::uint32_t bufferWidth, std::uint32_t bufferHeight, float relativeWidth, float relativeHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), bufferWidth(bufferWidth), bufferHeight(bufferHeight), relativeWidth(relativeWidth), relativeHeight(relativeHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), buffer(bufferWidth*bufferHeight), useRelativeSize(true), ignoreScaling(ignoreScaling) {
|
||||
|
||||
}
|
||||
|
||||
UiElement::UiElement(const std::filesystem::path& image, float anchorX, float anchorY, float relativeWidth, float relativeHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : anchorX(anchorX), anchorY(anchorY), relativeWidth(relativeWidth), relativeHeight(relativeHeight), anchorOffsetX(anchorOffsetX), anchorOffsetY(anchorOffsetY), z(z), useRelativeSize(true), ignoreScaling(ignoreScaling) {
|
||||
std::filesystem::path abs = std::filesystem::absolute(image);
|
||||
int xSize;
|
||||
int ySize;
|
||||
unsigned char* bgData = stbi_load(abs.string().c_str(), &xSize, &ySize, nullptr, 4);
|
||||
|
||||
bufferWidth = xSize;
|
||||
bufferHeight = ySize;
|
||||
|
||||
buffer.resize(bufferWidth*bufferHeight);
|
||||
|
||||
for(std::uint_fast32_t x = 0; x < xSize; x++) {
|
||||
for(std::uint_fast32_t y = 0; y < ySize; y++) {
|
||||
std::uint_fast32_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];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TextElement::TextElement(const std::string_view text, float size, Pixel_BU8_GU8_RU8_AU8 color, const Font& font, float anchorX, float anchorY, float relativeWidth, float relativeHeight, float anchorOffsetX, float anchorOffsetY, float z, bool ignoreScaling) : UiElement(anchorX, anchorY, relativeWidth, relativeHeight, anchorOffsetX, anchorOffsetY, z, ignoreScaling) {
|
||||
RenderText(text, size, color, font);
|
||||
}
|
||||
|
||||
void TextElement::RenderText(const std::string_view text, float size, Pixel_BU8_GU8_RU8_AU8 color, const Font& font) {
|
||||
float scale = stbtt_ScaleForPixelHeight(&font.font, size);
|
||||
|
||||
int baseline = (int)(font.ascent * scale);
|
||||
|
||||
bufferWidth = 0;
|
||||
bufferHeight = (int)((font.ascent -font.descent) * scale);
|
||||
for (const char c : text) {
|
||||
int advance, lsb;
|
||||
stbtt_GetCodepointHMetrics(&font.font, c, &advance, &lsb);
|
||||
bufferWidth += (int)(advance * scale);
|
||||
}
|
||||
|
||||
buffer.resize(bufferWidth * bufferHeight);
|
||||
|
||||
int x = 0;
|
||||
for (std::uint_fast32_t i = 0; i < text.size(); i++) {
|
||||
int codepoint = text[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);
|
||||
|
||||
for (int j = 0; j < h; j++) {
|
||||
for (int i = 0; i < w; i++) {
|
||||
int bufIndex = ((baseline + j + c_y1) * bufferWidth + (x + i + c_x1));
|
||||
unsigned char val = bitmap[j * w + i];
|
||||
buffer[bufIndex] = {color.r, color.g, color.b, val};
|
||||
}
|
||||
}
|
||||
|
||||
x += (int)(ax * scale);
|
||||
|
||||
if (i + 1 < text.size()) {
|
||||
x += (int)stbtt_GetCodepointKernAdvance(&font.font, codepoint, text[i+1] * scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,305 +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
|
||||
*/
|
||||
|
||||
module;
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <iostream>
|
||||
#include <exception>
|
||||
// #include <vulkan/vk_enum_string_helper.h>
|
||||
#include <cstring>
|
||||
#include <print>
|
||||
#include <cstdio>
|
||||
#include "../../lib/VulkanInitializers.hpp"
|
||||
|
||||
#define GET_EXTENSION_FUNCTION(_id) ((PFN_##_id)(vkGetInstanceProcAddr(instance, #_id)))
|
||||
|
||||
module Crafter.Graphics:VulkanDevice_impl;
|
||||
import :VulkanDevice;
|
||||
|
||||
using namespace Crafter;
|
||||
const char* const instanceExtensionNames[] = {
|
||||
"VK_EXT_debug_utils",
|
||||
"VK_KHR_surface",
|
||||
"VK_KHR_wayland_surface"
|
||||
};
|
||||
const char* const deviceExtensionNames[] = {
|
||||
"VK_KHR_swapchain",
|
||||
"VK_KHR_spirv_1_4",
|
||||
"VK_EXT_mesh_shader",
|
||||
"VK_KHR_shader_float_controls",
|
||||
"VK_KHR_dynamic_rendering"
|
||||
};
|
||||
const char* const layerNames[] = {
|
||||
"VK_LAYER_KHRONOS_validation"
|
||||
};
|
||||
|
||||
|
||||
void VulkanDevice::CHECK_VK_RESULT(VkResult result) {
|
||||
if (result != VK_SUCCESS)
|
||||
{
|
||||
throw std::runtime_error("vk error");
|
||||
}
|
||||
}
|
||||
|
||||
VkBool32 onError(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData)
|
||||
{
|
||||
printf("Vulkan ");
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT :
|
||||
printf("general ");
|
||||
break;
|
||||
case VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT :
|
||||
printf("validation ");
|
||||
break;
|
||||
case VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT :
|
||||
printf("performance ");
|
||||
break;
|
||||
}
|
||||
|
||||
switch (severity)
|
||||
{
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT :
|
||||
printf("(verbose): ");
|
||||
break;
|
||||
default :
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT :
|
||||
printf("(info): ");
|
||||
break;
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT :
|
||||
printf("(warning): ");
|
||||
break;
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT :
|
||||
printf("(error): ");
|
||||
break;
|
||||
}
|
||||
|
||||
printf("%s\n", callbackData->pMessage);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void VulkanDevice::CreateDevice() {
|
||||
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};
|
||||
app.pApplicationName = "";
|
||||
app.pEngineName = "Crafter.Graphics";
|
||||
app.apiVersion = VK_MAKE_VERSION(1, 4, 0);
|
||||
|
||||
VkInstanceCreateInfo instanceCreateInfo = {};
|
||||
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||||
instanceCreateInfo.pApplicationInfo = &app;
|
||||
instanceCreateInfo.enabledExtensionCount = sizeof(instanceExtensionNames) / sizeof(const char*);
|
||||
instanceCreateInfo.ppEnabledExtensionNames = instanceExtensionNames;
|
||||
|
||||
size_t foundInstanceLayers = 0;
|
||||
|
||||
std::uint32_t instanceLayerCount;
|
||||
CHECK_VK_RESULT(vkEnumerateInstanceLayerProperties(&instanceLayerCount, NULL));
|
||||
|
||||
std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerCount);
|
||||
CHECK_VK_RESULT(vkEnumerateInstanceLayerProperties(&instanceLayerCount, instanceLayerProperties.data()));
|
||||
|
||||
for (uint32_t i = 0; i < instanceLayerCount; i++)
|
||||
{
|
||||
for (size_t j = 0; j < sizeof(layerNames) / sizeof(const char*); j++)
|
||||
{
|
||||
if (std::strcmp(instanceLayerProperties[i].layerName, layerNames[j]) == 0)
|
||||
{
|
||||
foundInstanceLayers++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundInstanceLayers >= sizeof(layerNames) / sizeof(const char*))
|
||||
{
|
||||
instanceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
|
||||
instanceCreateInfo.ppEnabledLayerNames = layerNames;
|
||||
}
|
||||
|
||||
CHECK_VK_RESULT(vkCreateInstance(&instanceCreateInfo, NULL, &instance));
|
||||
|
||||
VkDebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfo = {};
|
||||
debugUtilsMessengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
||||
debugUtilsMessengerCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
|
||||
debugUtilsMessengerCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
|
||||
debugUtilsMessengerCreateInfo.pfnUserCallback = onError;
|
||||
CHECK_VK_RESULT(GET_EXTENSION_FUNCTION(vkCreateDebugUtilsMessengerEXT)(instance, &debugUtilsMessengerCreateInfo, NULL, &debugMessenger));
|
||||
|
||||
uint32_t physDeviceCount;
|
||||
vkEnumeratePhysicalDevices(instance, &physDeviceCount, NULL);
|
||||
|
||||
std::vector<VkPhysicalDevice> physDevices(physDeviceCount);
|
||||
vkEnumeratePhysicalDevices(instance, &physDeviceCount, physDevices.data());
|
||||
|
||||
uint32_t bestScore = 0;
|
||||
|
||||
for (uint32_t i = 0; i < physDeviceCount; i++)
|
||||
{
|
||||
VkPhysicalDevice device = physDevices[i];
|
||||
|
||||
VkPhysicalDeviceProperties properties;
|
||||
vkGetPhysicalDeviceProperties(device, &properties);
|
||||
|
||||
uint32_t score;
|
||||
|
||||
switch (properties.deviceType)
|
||||
{
|
||||
default :
|
||||
continue;
|
||||
case VK_PHYSICAL_DEVICE_TYPE_OTHER :
|
||||
score = 1;
|
||||
break;
|
||||
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU :
|
||||
score = 4;
|
||||
break;
|
||||
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU :
|
||||
score = 5;
|
||||
break;
|
||||
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU :
|
||||
score = 3;
|
||||
break;
|
||||
case VK_PHYSICAL_DEVICE_TYPE_CPU :
|
||||
score = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
if (score > bestScore)
|
||||
{
|
||||
physDevice = device;
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
uint32_t queueFamilyCount;
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(physDevice, &queueFamilyCount, NULL);
|
||||
|
||||
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(physDevice, &queueFamilyCount, queueFamilies.data());
|
||||
|
||||
for (uint32_t i = 0; i < queueFamilyCount; i++)
|
||||
{
|
||||
if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
|
||||
{
|
||||
queueFamilyIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
float priority = 1;
|
||||
|
||||
VkDeviceQueueCreateInfo queueCreateInfo = {};
|
||||
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||||
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
|
||||
queueCreateInfo.queueCount = 1;
|
||||
queueCreateInfo.pQueuePriorities = &priority;
|
||||
|
||||
VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamicRenderingFeature = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR};
|
||||
dynamicRenderingFeature.dynamicRendering = VK_TRUE;
|
||||
|
||||
VkPhysicalDeviceMeshShaderFeaturesEXT ext_feature = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT};
|
||||
ext_feature.meshShader = VK_TRUE;
|
||||
ext_feature.pNext = &dynamicRenderingFeature;
|
||||
|
||||
VkPhysicalDeviceFeatures2 physical_features2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};
|
||||
physical_features2.pNext = &ext_feature;
|
||||
|
||||
VkDeviceCreateInfo deviceCreateInfo = {};
|
||||
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||||
deviceCreateInfo.queueCreateInfoCount = 1;
|
||||
deviceCreateInfo.pQueueCreateInfos = &queueCreateInfo;
|
||||
deviceCreateInfo.enabledExtensionCount = sizeof(deviceExtensionNames) / sizeof(const char*);
|
||||
deviceCreateInfo.ppEnabledExtensionNames = deviceExtensionNames;
|
||||
deviceCreateInfo.pNext = &physical_features2;
|
||||
|
||||
uint32_t deviceLayerCount;
|
||||
CHECK_VK_RESULT(vkEnumerateDeviceLayerProperties(physDevice, &deviceLayerCount, NULL));
|
||||
|
||||
std::vector<VkLayerProperties> deviceLayerProperties(deviceLayerCount);
|
||||
CHECK_VK_RESULT(vkEnumerateDeviceLayerProperties(physDevice, &deviceLayerCount, deviceLayerProperties.data()));
|
||||
|
||||
size_t foundDeviceLayers = 0;
|
||||
|
||||
for (uint32_t i = 0; i < deviceLayerCount; i++)
|
||||
{
|
||||
for (size_t j = 0; j < sizeof(layerNames) / sizeof(const char*); j++)
|
||||
{
|
||||
if (strcmp(deviceLayerProperties[i].layerName, layerNames[j]) == 0)
|
||||
{
|
||||
foundDeviceLayers++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (foundDeviceLayers >= sizeof(layerNames) / sizeof(const char*))
|
||||
{
|
||||
deviceCreateInfo.enabledLayerCount = sizeof(layerNames) / sizeof(const char*);
|
||||
deviceCreateInfo.ppEnabledLayerNames = layerNames;
|
||||
}
|
||||
|
||||
CHECK_VK_RESULT(vkCreateDevice(physDevice, &deviceCreateInfo, NULL, &device));
|
||||
vkGetDeviceQueue(device, queueFamilyIndex, 0, &queue);
|
||||
|
||||
VkCommandPoolCreateInfo commandPoolcreateInfo = {};
|
||||
commandPoolcreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
||||
commandPoolcreateInfo.queueFamilyIndex = queueFamilyIndex;
|
||||
commandPoolcreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
||||
CHECK_VK_RESULT(vkCreateCommandPool(device, &commandPoolcreateInfo, NULL, &commandPool));
|
||||
|
||||
vkGetPhysicalDeviceMemoryProperties(physDevice, &memoryProperties);
|
||||
|
||||
std::vector<VkFormat> formatList = {
|
||||
VK_FORMAT_D32_SFLOAT,
|
||||
};
|
||||
|
||||
for (auto& format : formatList) {
|
||||
VkFormatProperties formatProps;
|
||||
vkGetPhysicalDeviceFormatProperties(physDevice, format, &formatProps);
|
||||
if (formatProps.optimalTilingFeatures)
|
||||
{
|
||||
depthFormat = format;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
vkCmdDrawMeshTasksEXTProc = reinterpret_cast<PFN_vkCmdDrawMeshTasksEXT>(vkGetDeviceProcAddr(device, "vkCmdDrawMeshTasksEXT"));
|
||||
vkCmdBeginRenderingKHRProc = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(instance, "vkCmdBeginRenderingKHR"));
|
||||
vkCmdEndRenderingKHRProc = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(instance, "vkCmdEndRenderingKHR"));
|
||||
}
|
||||
|
||||
std::uint32_t VulkanDevice::GetMemoryType(uint32_t typeBits, VkMemoryPropertyFlags properties) {
|
||||
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++)
|
||||
{
|
||||
if ((typeBits & 1) == 1)
|
||||
{
|
||||
if ((memoryProperties.memoryTypes[i].propertyFlags & properties) == properties)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
typeBits >>= 1;
|
||||
}
|
||||
|
||||
throw std::runtime_error("Could not find a matching memory type");
|
||||
}
|
||||
|
|
@ -21,15 +21,182 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|||
module;
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-cursor.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <wayland-client.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-client.h>
|
||||
#include <wayland-client-protocol.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 <string.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-cursor.h>
|
||||
#include <xkbcommon/xkbcommon.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <wayland-client.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <print>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-client.h>
|
||||
#include <wayland-client-protocol.h>
|
||||
#include <linux/input-event-codes.h>
|
||||
|
||||
module Crafter.Graphics:Window_impl;
|
||||
import :Window;
|
||||
import std;
|
||||
import Crafter.Event;
|
||||
using namespace Crafter;
|
||||
|
||||
|
||||
void randname(char *buf) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
long r = ts.tv_nsec;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
buf[i] = 'A'+(r&15)+(r&16)*2;
|
||||
r >>= 5;
|
||||
}
|
||||
}
|
||||
|
||||
int anonymous_shm_open(void) {
|
||||
char name[] = "/hello-wayland-XXXXXX";
|
||||
int retries = 100;
|
||||
|
||||
do {
|
||||
randname(name + strlen(name) - 6);
|
||||
|
||||
--retries;
|
||||
// shm_open guarantees that O_CLOEXEC is set
|
||||
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
|
||||
if (fd >= 0) {
|
||||
shm_unlink(name);
|
||||
return fd;
|
||||
}
|
||||
} while (retries > 0 && errno == EEXIST);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int create_shm_file(off_t size) {
|
||||
int fd = anonymous_shm_open();
|
||||
if (fd < 0) {
|
||||
return fd;
|
||||
}
|
||||
|
||||
if (ftruncate(fd, size) < 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return fd;
|
||||
}
|
||||
|
||||
int counter = 0;
|
||||
|
||||
void ScaleBitmapR8G8B8(Pixel_BU8_GU8_RU8_AU8* dst, const Pixel_BU8_GU8_RU8_AU8* src, std::uint32_t srcWidth, std::uint32_t srcHeight, std::uint32_t dstWidth, std::uint32_t dstHeight) {
|
||||
for (std::uint32_t y = 0; y < dstHeight; y++) {
|
||||
std::uint32_t srcY = y * srcHeight / dstHeight;
|
||||
for (std::uint32_t x = 0; x < dstWidth; x++) {
|
||||
std::uint32_t srcX = x * srcWidth / dstWidth;
|
||||
const Pixel_BU8_GU8_RU8_AU8* srcPixel = src + (srcY * srcWidth + srcX);
|
||||
Pixel_BU8_GU8_RU8_AU8* dstPixel = dst + (y * dstWidth + x);
|
||||
dstPixel[0] = srcPixel[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Window::Window(std::string name, std::uint32_t width, std::uint32_t height) : name(name), width(width), height(height) {
|
||||
display = wl_display_connect(NULL);
|
||||
if (display == NULL) {
|
||||
std::cerr << "failed to create display" << std::endl;
|
||||
}
|
||||
|
||||
wl_registry* registry = wl_display_get_registry(display);
|
||||
wl_registry_add_listener(registry, ®istry_listener, this);
|
||||
if (wl_display_roundtrip(display) == -1) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
if (shm == NULL || compositor == NULL || xdgWmBase == NULL) {
|
||||
std::cerr << "no wl_shm, wl_compositor or xdg_wm_base support" << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
surface = wl_compositor_create_surface(compositor);
|
||||
xdgSurface = xdg_wm_base_get_xdg_surface(xdgWmBase, surface);
|
||||
xdgToplevel = xdg_surface_get_toplevel(xdgSurface);
|
||||
cb = wl_surface_frame(surface);
|
||||
|
||||
wl_callback_add_listener(cb, &surface_frame_listener, this);
|
||||
xdg_surface_add_listener(xdgSurface, &xdg_surface_listener, this);
|
||||
xdg_toplevel_add_listener(xdgToplevel, &xdg_toplevel_listener, this);
|
||||
wl_surface_commit(surface);
|
||||
|
||||
xdg_toplevel_set_title(xdgToplevel, name.c_str());
|
||||
|
||||
while (wl_display_dispatch(display) != -1 && !configured) {}
|
||||
|
||||
|
||||
wl_surface_commit(surface);
|
||||
|
||||
zxdg_toplevel_decoration_v1* decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(manager, xdgToplevel);
|
||||
zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
|
||||
|
||||
// Create a wl_buffer, attach it to the surface and commit the surface
|
||||
int stride = width * 4;
|
||||
int size = stride * height;
|
||||
|
||||
// Allocate a shared memory file with the right size
|
||||
int fd = create_shm_file(size);
|
||||
if (fd < 0) {
|
||||
fprintf(stderr, "creating a buffer file for %d B failed: %m\n", size);
|
||||
}
|
||||
|
||||
// Map the shared memory file
|
||||
framebuffer = reinterpret_cast<Pixel_BU8_GU8_RU8_AU8*>(mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
|
||||
if (framebuffer == MAP_FAILED) {
|
||||
fprintf(stderr, "mmap failed: %m\n");
|
||||
close(fd);
|
||||
}
|
||||
|
||||
// Create a wl_buffer from our shared memory file descriptor
|
||||
wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
|
||||
buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888);
|
||||
wl_shm_pool_destroy(pool);
|
||||
|
||||
// Now that we've mapped the file and created the wl_buffer, we no longer
|
||||
// need to keep file descriptor opened
|
||||
close(fd);
|
||||
|
||||
if (buffer == NULL) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
wl_surface_attach(surface, buffer, 0, 0);
|
||||
wl_surface_commit(surface);
|
||||
}
|
||||
|
||||
ScaleData Window::ScaleElement(const UiElement& element) {
|
||||
|
|
@ -54,4 +221,385 @@ ScaleData Window::ScaleElement(const UiElement& element) {
|
|||
data.x = (element.anchorX*width)-(element.anchorOffsetX*data.width);
|
||||
data.y = (element.anchorY*height)-(element.anchorOffsetY*data.height);
|
||||
return data;
|
||||
}
|
||||
|
||||
ScaleData ScaleElement(const UiElement& element, const ScaleData& parent, const Window* window) {
|
||||
ScaleData data;
|
||||
if(element.ignoreScaling) {
|
||||
if(element.useRelativeSize) {
|
||||
data.width = element.relativeWidth*parent.width;
|
||||
data.height = element.relativeHeight*parent.height;
|
||||
} else {
|
||||
data.width = element.absoluteWidth;
|
||||
data.height = element.absoluteHeight;
|
||||
}
|
||||
} else {
|
||||
if(element.useRelativeSize) {
|
||||
data.width = element.relativeWidth*parent.width*window->scale;
|
||||
data.height = element.relativeHeight*parent.height*window->scale;
|
||||
} else {
|
||||
data.width = element.absoluteWidth*window->scale;
|
||||
data.height = element.absoluteHeight*window->scale;
|
||||
}
|
||||
}
|
||||
data.x = ((element.anchorX*parent.width)-(element.anchorOffsetX*data.width))+parent.x;
|
||||
data.y = ((element.anchorY*parent.height)-(element.anchorOffsetY*data.height))+parent.y;
|
||||
return data;
|
||||
}
|
||||
|
||||
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial) {
|
||||
xdg_wm_base_pong(xdg_wm_base, serial);
|
||||
}
|
||||
|
||||
xdg_wm_base_listener xdgWmBaseListener = {
|
||||
.ping = xdg_wm_base_handle_ping,
|
||||
};
|
||||
|
||||
void RenderElements(Window* window, const UiElement& parent, const ScaleData& parentScale) {
|
||||
std::vector<UiElement*> drawOrder;
|
||||
drawOrder.reserve(parent.children.size());
|
||||
for (const std::unique_ptr<UiElement>& e : parent.children) drawOrder.push_back(e.get());
|
||||
std::sort(drawOrder.begin(), drawOrder.end(), [](UiElement* a, UiElement* b){ return a->z < b->z; });
|
||||
|
||||
for(const UiElement* element : drawOrder) {
|
||||
ScaleData data = ScaleElement(*element, parentScale, window);
|
||||
std::vector<Pixel_BU8_GU8_RU8_AU8> scaled(data.width*data.height);
|
||||
ScaleBitmapR8G8B8(scaled.data(), element->buffer.data(), element->bufferWidth, element->bufferHeight, data.width, data.height);
|
||||
for (std::int32_t x = data.x; x - data.x < data.width; x++) {
|
||||
for (std::int32_t y = data.y; y - data.y < data.height; y++) {
|
||||
if (x >= 0 && x < window->width && y >= 0 && y < window->height) {
|
||||
Pixel_BU8_GU8_RU8_AU8& dst = window->framebuffer[y * window->width + x];
|
||||
const Pixel_BU8_GU8_RU8_AU8& src = scaled[(y - data.y) * data.width + (x - data.x)];
|
||||
|
||||
float srcA = src.a / 255.0f;
|
||||
float dstA = dst.a / 255.0f;
|
||||
|
||||
float outA = srcA + dstA * (1.0f - srcA);
|
||||
if (outA > 0.0f) {
|
||||
dst.r = static_cast<uint8_t>((src.r * srcA + dst.r * dstA * (1.0f - srcA)) / outA);
|
||||
dst.g = static_cast<uint8_t>((src.g * srcA + dst.g * dstA * (1.0f - srcA)) / outA);
|
||||
dst.b = static_cast<uint8_t>((src.b * srcA + dst.b * dstA * (1.0f - srcA)) / outA);
|
||||
dst.a = static_cast<uint8_t>(outA * 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RenderElements(window, *element, data);
|
||||
}
|
||||
}
|
||||
|
||||
void Window::wl_surface_frame_done(void* data, struct wl_callback *cb, uint32_t time)
|
||||
{
|
||||
wl_callback_destroy(cb);
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
cb = wl_surface_frame(window->surface);
|
||||
wl_callback_add_listener(cb, &Window::surface_frame_listener, window);
|
||||
|
||||
std::vector<UiElement*> drawOrder;
|
||||
drawOrder.reserve(window->elements.size());
|
||||
for (UiElement& e : window->elements) drawOrder.push_back(&e);
|
||||
std::sort(drawOrder.begin(), drawOrder.end(), [](UiElement* a, UiElement* b){ return a->z < b->z; });
|
||||
|
||||
for(const UiElement* element : drawOrder) {
|
||||
ScaleData data = window->ScaleElement(*element);
|
||||
std::vector<Pixel_BU8_GU8_RU8_AU8> scaled(data.width*data.height);
|
||||
ScaleBitmapR8G8B8(scaled.data(), element->buffer.data(), element->bufferWidth, element->bufferHeight, data.width, data.height);
|
||||
for (std::int32_t x = data.x; x - data.x < data.width; x++) {
|
||||
for (std::int32_t y = data.y; y - data.y < data.height; y++) {
|
||||
if (x >= 0 && x < window->width && y >= 0 && y < window->height) {
|
||||
Pixel_BU8_GU8_RU8_AU8& dst = window->framebuffer[y * window->width + x];
|
||||
const Pixel_BU8_GU8_RU8_AU8& src = scaled[(y - data.y) * data.width + (x - data.x)];
|
||||
|
||||
float srcA = src.a / 255.0f;
|
||||
float dstA = dst.a / 255.0f;
|
||||
|
||||
float outA = srcA + dstA * (1.0f - srcA);
|
||||
if (outA > 0.0f) {
|
||||
dst.r = static_cast<uint8_t>((src.r * srcA + dst.r * dstA * (1.0f - srcA)) / outA);
|
||||
dst.g = static_cast<uint8_t>((src.g * srcA + dst.g * dstA * (1.0f - srcA)) / outA);
|
||||
dst.b = static_cast<uint8_t>((src.b * srcA + dst.b * dstA * (1.0f - srcA)) / outA);
|
||||
dst.a = static_cast<uint8_t>(outA * 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RenderElements(window, *element, data);
|
||||
}
|
||||
|
||||
|
||||
wl_surface_attach(window->surface, window->buffer, 0, 0);
|
||||
wl_surface_damage(window->surface, 0, 0, window->width, window->height);
|
||||
wl_surface_commit(window->surface);
|
||||
}
|
||||
|
||||
wl_callback_listener Window::surface_frame_listener = {
|
||||
.done = wl_surface_frame_done,
|
||||
};
|
||||
|
||||
void Window::pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
if (button == BTN_LEFT) {
|
||||
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
|
||||
window->mouseLeftHeld = true;
|
||||
window->onMouseLeftClick.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeftClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
window->mouseLeftHeld = false;
|
||||
window->onMouseLeftRelease.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeftRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if(button == BTN_RIGHT){
|
||||
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
|
||||
window->mouseRightHeld = true;
|
||||
window->onMouseRightClick.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseRightClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
window->mouseRightHeld = true;
|
||||
window->onMouseRightRelease.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseRightRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Window::PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
MousePoint pos = {wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)};
|
||||
window->lastMousePos = window->currentMousePos;
|
||||
window->currentMousePos = pos;
|
||||
window->mouseDelta = {window->currentMousePos.x-window->lastMousePos.x, window->currentMousePos.y-window->lastMousePos.y};
|
||||
window->onMouseMove.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseMove.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
if(!(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height)) {
|
||||
element.onMouseEnter.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
} else if(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeave.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Window::PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
}
|
||||
|
||||
void Window::PointerListenerHandleLeave(void* data, wl_pointer*, std::uint32_t, wl_surface*) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
}
|
||||
|
||||
void Window::PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value) {
|
||||
|
||||
}
|
||||
|
||||
wl_pointer_listener Window::pointer_listener = {
|
||||
.enter = Window::PointerListenerHandleEnter,
|
||||
.leave = Window::PointerListenerHandleLeave,
|
||||
.motion = Window::PointerListenerHandleMotion,
|
||||
.button = Window::pointer_handle_button,
|
||||
.axis = Window::PointerListenerHandleAxis,
|
||||
};
|
||||
|
||||
xkb_keymap* xkb_keymap;
|
||||
xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
|
||||
xkb_state* xkb_state;
|
||||
|
||||
|
||||
void keyboard_keymap(void *data, wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {
|
||||
if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
|
||||
close(fd);
|
||||
fprintf(stderr, "Unsupported keymap format\n");
|
||||
return;
|
||||
}
|
||||
|
||||
void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (map == MAP_FAILED) {
|
||||
close(fd);
|
||||
perror("mmap");
|
||||
return;
|
||||
}
|
||||
|
||||
xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
|
||||
xkb_keymap = xkb_keymap_new_from_string(xkb_context, (const char *)map, XKB_KEYMAP_FORMAT_TEXT_V1,XKB_KEYMAP_COMPILE_NO_FLAGS);
|
||||
munmap(map, size);
|
||||
close(fd);
|
||||
|
||||
xkb_state = xkb_state_new(xkb_keymap);
|
||||
}
|
||||
|
||||
void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
|
||||
if (!xkb_state) {
|
||||
return;
|
||||
}
|
||||
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
|
||||
xkb_keycode_t keycode = key + 8;
|
||||
xkb_keysym_t keysym = xkb_state_key_get_one_sym(xkb_state, keycode);
|
||||
|
||||
char utf8[8] = {0};
|
||||
int len = xkb_keysym_to_utf8(keysym, utf8, sizeof(utf8));
|
||||
if (len != 0) {
|
||||
char keypress = utf8[0];
|
||||
if(state == WL_KEYBOARD_KEY_STATE_PRESSED) {
|
||||
if(window->heldkeys[keypress]) {
|
||||
window->onKeyHold[keypress].Invoke();
|
||||
window->onAnyKeyHold.Invoke(keypress);
|
||||
} else{
|
||||
window->heldkeys[keypress] = true;
|
||||
window->onKeyDown[keypress].Invoke();
|
||||
window->onAnyKeyDown.Invoke(keypress);
|
||||
}
|
||||
} else{
|
||||
window->heldkeys[keypress] = false;
|
||||
window->onKeyUp[keypress].Invoke();
|
||||
window->onAnyKeyUp.Invoke(keypress);
|
||||
}
|
||||
|
||||
} else {
|
||||
// // fallback for keys like Return, Escape, etc.
|
||||
// char name[64];
|
||||
// if (xkb_keysym_get_name(keysym, name, sizeof(name)) > 0) {
|
||||
// printf("Key %s pressed (non-printable or multi-char)\n", name);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay) {
|
||||
|
||||
}
|
||||
|
||||
wl_keyboard_listener Window::keyboard_listener = {
|
||||
.keymap = keyboard_keymap,
|
||||
.enter = keyboard_enter,
|
||||
.leave = keyboard_leave,
|
||||
.key = keyboard_key,
|
||||
.modifiers = keyboard_modifiers,
|
||||
.repeat_info = keyboard_repeat_info,
|
||||
};
|
||||
|
||||
void Window::seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
window->seat = seat;
|
||||
if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
|
||||
wl_pointer* pointer = wl_seat_get_pointer(seat);
|
||||
wl_pointer_add_listener(pointer, &pointer_listener, window);
|
||||
}
|
||||
if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
|
||||
wl_keyboard* keyboard = wl_seat_get_keyboard(seat);
|
||||
wl_keyboard_add_listener(keyboard, &keyboard_listener, window);
|
||||
}
|
||||
}
|
||||
|
||||
wl_seat_listener Window::seat_listener = {
|
||||
.capabilities = seat_handle_capabilities,
|
||||
};
|
||||
|
||||
void Window::handle_global(void *data, wl_registry *registry, std::uint32_t name, const char *interface, std::uint32_t version) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
if (strcmp(interface, wl_shm_interface.name) == 0) {
|
||||
window->shm = reinterpret_cast<wl_shm*>(wl_registry_bind(registry, name, &wl_shm_interface, 1));
|
||||
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
|
||||
wl_seat* seat = reinterpret_cast<wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, 1));
|
||||
wl_seat_add_listener(seat, &seat_listener, window);
|
||||
} else if (compositor == NULL && strcmp(interface, wl_compositor_interface.name) == 0) {
|
||||
compositor = reinterpret_cast<wl_compositor*>(wl_registry_bind(registry, name, &wl_compositor_interface, 1));
|
||||
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
|
||||
window->xdgWmBase = reinterpret_cast<xdg_wm_base*>(wl_registry_bind(registry, name, &xdg_wm_base_interface, 1));
|
||||
xdg_wm_base_add_listener(window->xdgWmBase, &xdgWmBaseListener, NULL);
|
||||
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
|
||||
window->manager = reinterpret_cast<zxdg_decoration_manager_v1*>(wl_registry_bind(registry, name, &zxdg_decoration_manager_v1_interface, 1));
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name) {
|
||||
|
||||
|
||||
}
|
||||
|
||||
wl_registry_listener Window::registry_listener = {
|
||||
.global = Window::handle_global,
|
||||
.global_remove = handle_global_remove,
|
||||
};
|
||||
|
||||
static void noop5(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*){
|
||||
|
||||
}
|
||||
|
||||
void Window::xdg_toplevel_handle_close(void* data, xdg_toplevel*) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
window->onClose.Invoke();
|
||||
window->open = false;
|
||||
}
|
||||
|
||||
xdg_toplevel_listener Window::xdg_toplevel_listener = {
|
||||
.configure = noop5,
|
||||
.close = Window::xdg_toplevel_handle_close,
|
||||
};
|
||||
|
||||
void Window::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial) {
|
||||
Window* window = reinterpret_cast<Window*>(data);
|
||||
// The compositor configures our surface, acknowledge the configure event
|
||||
xdg_surface_ack_configure(xdg_surface, serial);
|
||||
|
||||
if (window->configured) {
|
||||
// If this isn't the first configure event we've received, we already
|
||||
// have a buffer attached, so no need to do anything. Commit the
|
||||
// surface to apply the configure acknowledgement.
|
||||
wl_surface_commit(window->surface);
|
||||
}
|
||||
|
||||
window->configured = true;
|
||||
}
|
||||
|
||||
xdg_surface_listener Window::xdg_surface_listener = {
|
||||
.configure = xdg_surface_handle_configure,
|
||||
};
|
||||
|
||||
Window::~Window() {
|
||||
xdg_toplevel_destroy(xdgToplevel);
|
||||
xdg_surface_destroy(xdgSurface);
|
||||
wl_surface_destroy(surface);
|
||||
wl_buffer_destroy(buffer);
|
||||
}
|
||||
|
||||
void Window::StartSync() {
|
||||
while (open && wl_display_dispatch(display) != -1) {
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,389 +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
|
||||
*/
|
||||
|
||||
module;
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-cursor.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <wayland-client.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-client.h>
|
||||
#include <wayland-client-protocol.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 <string.h>
|
||||
|
||||
|
||||
module Crafter.Graphics:WindowWayland_impl;
|
||||
import :WindowWayland;
|
||||
import std;
|
||||
import Crafter.Event;
|
||||
using namespace Crafter;
|
||||
|
||||
static void xdg_wm_base_handle_ping(void* data, xdg_wm_base* xdg_wm_base, std::uint32_t serial) {
|
||||
xdg_wm_base_pong(xdg_wm_base, serial);
|
||||
}
|
||||
|
||||
xdg_wm_base_listener xdgWmBaseListener = {
|
||||
.ping = xdg_wm_base_handle_ping,
|
||||
};
|
||||
|
||||
void WindowWayland::wl_surface_frame_done(void *data, struct wl_callback *cb, uint32_t time)
|
||||
{
|
||||
/* Destroy this callback */
|
||||
wl_callback_destroy(cb);
|
||||
|
||||
/* Request another frame */
|
||||
struct client_state *state = data;
|
||||
cb = wl_surface_frame(state->wl_surface);
|
||||
wl_callback_add_listener(cb, &wl_surface_frame_listener, state);
|
||||
|
||||
/* Update scroll amount at 24 pixels per second */
|
||||
if (state->last_frame != 0) {
|
||||
int elapsed = time - state->last_frame;
|
||||
state->offset += elapsed / 1000.0 * 24;
|
||||
}
|
||||
|
||||
/* Submit a frame for this event */
|
||||
struct wl_buffer *buffer = draw_frame(state);
|
||||
wl_surface_attach(state->wl_surface, buffer, 0, 0);
|
||||
wl_surface_damage_buffer(state->wl_surface, 0, 0, INT32_MAX, INT32_MAX);
|
||||
wl_surface_commit(state->wl_surface);
|
||||
|
||||
state->last_frame = time;
|
||||
}
|
||||
|
||||
wl_callback_listener WindowWayland::surface_frame_listener = {
|
||||
.done = wl_surface_frame_done,
|
||||
};
|
||||
|
||||
void WindowWayland::pointer_handle_button(void* data, wl_pointer* pointer, std::uint32_t serial, std::uint32_t time, std::uint32_t button, std::uint32_t state) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
if (button == BTN_LEFT) {
|
||||
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
|
||||
window->mouseLeftHeld = true;
|
||||
window->onMouseLeftClick.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeftClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
window->mouseLeftHeld = false;
|
||||
window->onMouseLeftRelease.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeftRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if(button == BTN_RIGHT){
|
||||
if(state == WL_POINTER_BUTTON_STATE_PRESSED) {
|
||||
window->mouseRightHeld = true;
|
||||
window->onMouseRightClick.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseRightClick.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
window->mouseRightHeld = true;
|
||||
window->onMouseRightRelease.Invoke(window->currentMousePos);
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseRightRelease.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WindowWayland::PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, uint time, wl_fixed_t surface_x, wl_fixed_t surface_y) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
MousePoint pos = {wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)};
|
||||
window->lastMousePos = window->currentMousePos;
|
||||
window->currentMousePos = pos;
|
||||
window->mouseDelta = {window->currentMousePos.x-window->lastMousePos.x, window->currentMousePos.y-window->lastMousePos.y};
|
||||
window->onMouseMove.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
for(UiElement& element : window->elements) {
|
||||
ScaleData data = window->ScaleElement(element);
|
||||
if(window->currentMousePos.x >= data.x && window->currentMousePos.x <= data.x+data.width && window->currentMousePos.y > data.y && window->currentMousePos.y < data.y+data.height) {
|
||||
element.onMouseMove.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
if(!(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height)) {
|
||||
element.onMouseEnter.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
} else if(window->lastMousePos.x >= data.x && window->lastMousePos.x <= data.x+data.width && window->lastMousePos.y > data.y && window->lastMousePos.y < data.y+data.height) {
|
||||
element.onMouseLeave.Invoke({window->currentMousePos.x-data.x, window->currentMousePos.y-data.y});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WindowWayland::PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, uint serial, wl_surface* surface, wl_fixed_t surface_x, wl_fixed_t surface_y) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
}
|
||||
|
||||
void WindowWayland::PointerListenerHandleLeave(void* data, wl_pointer*, std::uint32_t, wl_surface*) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
window->onMouseEnter.Invoke({window->lastMousePos, window->currentMousePos, window->mouseDelta});
|
||||
}
|
||||
|
||||
void WindowWayland::PointerListenerHandleAxis(void*, wl_pointer*, std::uint32_t, std::uint32_t, wl_fixed_t value) {
|
||||
std::cout << wl_fixed_to_double(value) << std::endl;
|
||||
}
|
||||
|
||||
wl_pointer_listener WindowWayland::pointer_listener = {
|
||||
.enter = WindowWayland::PointerListenerHandleEnter,
|
||||
.leave = WindowWayland::PointerListenerHandleLeave,
|
||||
.motion = WindowWayland::PointerListenerHandleMotion,
|
||||
.button = WindowWayland::pointer_handle_button,
|
||||
.axis = WindowWayland::PointerListenerHandleAxis,
|
||||
};
|
||||
|
||||
xkb_keymap* xkb_keymap;
|
||||
xkb_context* xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
|
||||
xkb_state* xkb_state;
|
||||
|
||||
|
||||
void keyboard_keymap(void *data, wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {
|
||||
if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
|
||||
close(fd);
|
||||
fprintf(stderr, "Unsupported keymap format\n");
|
||||
return;
|
||||
}
|
||||
|
||||
void *map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (map == MAP_FAILED) {
|
||||
close(fd);
|
||||
perror("mmap");
|
||||
return;
|
||||
}
|
||||
|
||||
xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
|
||||
xkb_keymap = xkb_keymap_new_from_string(xkb_context, (const char *)map, XKB_KEYMAP_FORMAT_TEXT_V1,XKB_KEYMAP_COMPILE_NO_FLAGS);
|
||||
munmap(map, size);
|
||||
close(fd);
|
||||
|
||||
xkb_state = xkb_state_new(xkb_keymap);
|
||||
}
|
||||
|
||||
void keyboard_enter(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface, wl_array *keys) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_leave(void *data, wl_keyboard *keyboard, uint32_t serial, wl_surface *surface) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_key(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
|
||||
if (!xkb_state) {
|
||||
return;
|
||||
}
|
||||
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
|
||||
xkb_keycode_t keycode = key + 8;
|
||||
xkb_keysym_t keysym = xkb_state_key_get_one_sym(xkb_state, keycode);
|
||||
|
||||
char utf8[8] = {0};
|
||||
int len = xkb_keysym_to_utf8(keysym, utf8, sizeof(utf8));
|
||||
if (len != 0) {
|
||||
char keypress = utf8[0];
|
||||
if(state == WL_KEYBOARD_KEY_STATE_PRESSED) {
|
||||
if(window->heldkeys[keypress]) {
|
||||
window->onKeyHold[keypress].Invoke();
|
||||
window->onAnyKeyHold.Invoke(keypress);
|
||||
} else{
|
||||
window->heldkeys[keypress] = true;
|
||||
window->onKeyDown[keypress].Invoke();
|
||||
window->onAnyKeyDown.Invoke(keypress);
|
||||
}
|
||||
} else{
|
||||
window->heldkeys[keypress] = false;
|
||||
window->onKeyUp[keypress].Invoke();
|
||||
window->onAnyKeyUp.Invoke(keypress);
|
||||
}
|
||||
|
||||
} else {
|
||||
// // fallback for keys like Return, Escape, etc.
|
||||
// char name[64];
|
||||
// if (xkb_keysym_get_name(keysym, name, sizeof(name)) > 0) {
|
||||
// printf("Key %s pressed (non-printable or multi-char)\n", name);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
}
|
||||
|
||||
void keyboard_repeat_info(void *data, wl_keyboard *keyboard, int32_t rate, int32_t delay) {
|
||||
|
||||
}
|
||||
|
||||
wl_keyboard_listener WindowWayland::keyboard_listener = {
|
||||
.keymap = keyboard_keymap,
|
||||
.enter = keyboard_enter,
|
||||
.leave = keyboard_leave,
|
||||
.key = keyboard_key,
|
||||
.modifiers = keyboard_modifiers,
|
||||
.repeat_info = keyboard_repeat_info,
|
||||
};
|
||||
|
||||
void WindowWayland::seat_handle_capabilities(void* data, wl_seat* seat, uint32_t capabilities) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
window->seat = seat;
|
||||
if (capabilities & WL_SEAT_CAPABILITY_POINTER) {
|
||||
wl_pointer* pointer = wl_seat_get_pointer(seat);
|
||||
wl_pointer_add_listener(pointer, &pointer_listener, window);
|
||||
}
|
||||
if (capabilities & WL_SEAT_CAPABILITY_KEYBOARD) {
|
||||
wl_keyboard* keyboard = wl_seat_get_keyboard(seat);
|
||||
wl_keyboard_add_listener(keyboard, &keyboard_listener, window);
|
||||
}
|
||||
}
|
||||
|
||||
wl_seat_listener WindowWayland::seat_listener = {
|
||||
.capabilities = seat_handle_capabilities,
|
||||
};
|
||||
|
||||
void WindowWayland::handle_global(void *data, wl_registry *registry, std::uint32_t name, const char *interface, std::uint32_t version) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
if (strcmp(interface, wl_shm_interface.name) == 0) {
|
||||
window->shm = reinterpret_cast<wl_shm*>(wl_registry_bind(registry, name, &wl_shm_interface, 1));
|
||||
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
|
||||
wl_seat* seat = reinterpret_cast<wl_seat*>(wl_registry_bind(registry, name, &wl_seat_interface, 1));
|
||||
wl_seat_add_listener(seat, &seat_listener, window);
|
||||
} else if (compositor == NULL && strcmp(interface, wl_compositor_interface.name) == 0) {
|
||||
compositor = reinterpret_cast<wl_compositor*>(wl_registry_bind(registry, name, &wl_compositor_interface, 1));
|
||||
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
|
||||
window->xdgWmBase = reinterpret_cast<xdg_wm_base*>(wl_registry_bind(registry, name, &xdg_wm_base_interface, 1));
|
||||
xdg_wm_base_add_listener(window->xdgWmBase, &xdgWmBaseListener, NULL);
|
||||
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
|
||||
window->manager = reinterpret_cast<zxdg_decoration_manager_v1*>(wl_registry_bind(registry, name, &zxdg_decoration_manager_v1_interface, 1));
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_global_remove(void* data, wl_registry* registry, uint32_t name) {
|
||||
|
||||
|
||||
}
|
||||
|
||||
wl_registry_listener WindowWayland::registry_listener = {
|
||||
.global = WindowWayland::handle_global,
|
||||
.global_remove = handle_global_remove,
|
||||
};
|
||||
|
||||
static void noop5(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*){
|
||||
|
||||
}
|
||||
|
||||
void WindowWayland::xdg_toplevel_handle_close(void* data, xdg_toplevel*) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
window->onClose.Invoke();
|
||||
window->open = false;
|
||||
}
|
||||
|
||||
xdg_toplevel_listener WindowWayland::xdg_toplevel_listener = {
|
||||
.configure = noop5,
|
||||
.close = WindowWayland::xdg_toplevel_handle_close,
|
||||
};
|
||||
|
||||
void WindowWayland::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial) {
|
||||
WindowWayland* window = reinterpret_cast<WindowWayland*>(data);
|
||||
// The compositor configures our surface, acknowledge the configure event
|
||||
xdg_surface_ack_configure(xdg_surface, serial);
|
||||
|
||||
if (window->configured) {
|
||||
// If this isn't the first configure event we've received, we already
|
||||
// have a buffer attached, so no need to do anything. Commit the
|
||||
// surface to apply the configure acknowledgement.
|
||||
wl_surface_commit(window->surface);
|
||||
}
|
||||
|
||||
window->configured = true;
|
||||
}
|
||||
|
||||
xdg_surface_listener WindowWayland::xdg_surface_listener = {
|
||||
.configure = xdg_surface_handle_configure,
|
||||
};
|
||||
|
||||
WindowWayland::WindowWayland(std::string name, std::uint32_t width, std::uint32_t height) : Window(name, width, height) {
|
||||
// Connect to the Wayland compositor
|
||||
display = wl_display_connect(NULL);
|
||||
if (display == NULL) {
|
||||
std::cerr << "failed to create display" << std::endl;
|
||||
}
|
||||
// Obtain the wl_registry and fetch the list of globals
|
||||
wl_registry* registry = wl_display_get_registry(display);
|
||||
wl_registry_add_listener(registry, ®istry_listener, this);
|
||||
if (wl_display_roundtrip(display) == -1) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
// Check that all globals we require are available
|
||||
if (shm == NULL || compositor == NULL || xdgWmBase == NULL) {
|
||||
std::cerr << "no wl_shm, wl_compositor or xdg_wm_base support" << std::endl;
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Create a wl_surface, a xdg_surface and a xdg_toplevel
|
||||
surface = wl_compositor_create_surface(compositor);
|
||||
xdgSurface = xdg_wm_base_get_xdg_surface(xdgWmBase, surface);
|
||||
xdgToplevel = xdg_surface_get_toplevel(xdgSurface);
|
||||
cb = wl_surface_frame(surface);
|
||||
|
||||
+ wl_callback_add_listener(cb, &wl_surface_frame_listener, this);
|
||||
xdg_surface_add_listener(xdgSurface, &xdg_surface_listener, this);
|
||||
xdg_toplevel_add_listener(xdgToplevel, &xdg_toplevel_listener, this);
|
||||
wl_surface_commit(surface);
|
||||
|
||||
xdg_toplevel_set_title(xdg_toplevel, name.c_str());
|
||||
|
||||
while (wl_display_dispatch(display) != -1 && !configured) {
|
||||
// This space intentionally left blank
|
||||
}
|
||||
|
||||
wl_surface_commit(surface);
|
||||
|
||||
zxdg_toplevel_decoration_v1* decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(manager, xdgToplevel); // toplevel is from xdg_surface_get_toplevel
|
||||
zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
|
||||
}
|
||||
|
||||
WindowWayland::~WindowWayland() {
|
||||
xdg_toplevel_destroy(xdgToplevel);
|
||||
xdg_surface_destroy(xdgSurface);
|
||||
wl_surface_destroy(surface);
|
||||
wl_buffer_destroy(frontBuffer);
|
||||
wl_buffer_destroy(backBuffer);
|
||||
}
|
||||
|
|
@ -1,488 +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
|
||||
*/
|
||||
|
||||
module;
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <wayland-client.h>
|
||||
|
||||
module Crafter.Graphics;
|
||||
import std;
|
||||
import Crafter.Event;
|
||||
using namespace Crafter;
|
||||
|
||||
void WindowWaylandVulkan::CreateSwapchain()
|
||||
{
|
||||
// Store the current swap chain handle so we can use it later on to ease up recreation
|
||||
VkSwapchainKHR oldSwapchain = swapChain;
|
||||
|
||||
// Get physical device surface properties and formats
|
||||
VkSurfaceCapabilitiesKHR surfCaps;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(VulkanDevice::physDevice, vulkanSurface, &surfCaps));
|
||||
|
||||
VkExtent2D swapchainExtent = {};
|
||||
// If width (and height) equals the special value 0xFFFFFFFF, the size of the surface will be set by the swapchain
|
||||
if (surfCaps.currentExtent.width == (uint32_t)-1)
|
||||
{
|
||||
// If the surface size is undefined, the size is set to the size of the images requested
|
||||
swapchainExtent.width = width;
|
||||
swapchainExtent.height = height;
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the surface size is defined, the swap chain size must match
|
||||
swapchainExtent = surfCaps.currentExtent;
|
||||
width = surfCaps.currentExtent.width;
|
||||
height = surfCaps.currentExtent.height;
|
||||
}
|
||||
|
||||
|
||||
// Select a present mode for the swapchain
|
||||
uint32_t presentModeCount;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfacePresentModesKHR(VulkanDevice::physDevice, vulkanSurface, &presentModeCount, NULL));
|
||||
assert(presentModeCount > 0);
|
||||
|
||||
std::vector<VkPresentModeKHR> presentModes(presentModeCount);
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfacePresentModesKHR(VulkanDevice::physDevice, vulkanSurface, &presentModeCount, presentModes.data()));
|
||||
|
||||
// The VK_PRESENT_MODE_FIFO_KHR mode must always be present as per spec
|
||||
// This mode waits for the vertical blank ("v-sync")
|
||||
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
|
||||
|
||||
// Determine the number of images
|
||||
uint32_t desiredNumberOfSwapchainImages = surfCaps.minImageCount + 1;
|
||||
if ((surfCaps.maxImageCount > 0) && (desiredNumberOfSwapchainImages > surfCaps.maxImageCount))
|
||||
{
|
||||
desiredNumberOfSwapchainImages = surfCaps.maxImageCount;
|
||||
}
|
||||
|
||||
// Find the transformation of the surface
|
||||
VkSurfaceTransformFlagsKHR preTransform;
|
||||
if (surfCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
|
||||
{
|
||||
// We prefer a non-rotated transform
|
||||
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
|
||||
}
|
||||
else
|
||||
{
|
||||
preTransform = surfCaps.currentTransform;
|
||||
}
|
||||
|
||||
// Find a supported composite alpha format (not all devices support alpha opaque)
|
||||
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
||||
// Simply select the first composite alpha format available
|
||||
std::vector<VkCompositeAlphaFlagBitsKHR> compositeAlphaFlags = {
|
||||
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
|
||||
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
|
||||
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
|
||||
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
|
||||
};
|
||||
for (auto& compositeAlphaFlag : compositeAlphaFlags) {
|
||||
if (surfCaps.supportedCompositeAlpha & compositeAlphaFlag) {
|
||||
compositeAlpha = compositeAlphaFlag;
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
VkSwapchainCreateInfoKHR swapchainCI = {};
|
||||
swapchainCI.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
||||
swapchainCI.surface = vulkanSurface;
|
||||
swapchainCI.minImageCount = desiredNumberOfSwapchainImages;
|
||||
swapchainCI.imageFormat = colorFormat;
|
||||
swapchainCI.imageColorSpace = colorSpace;
|
||||
swapchainCI.imageExtent = { swapchainExtent.width, swapchainExtent.height };
|
||||
swapchainCI.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
swapchainCI.preTransform = (VkSurfaceTransformFlagBitsKHR)preTransform;
|
||||
swapchainCI.imageArrayLayers = 1;
|
||||
swapchainCI.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
swapchainCI.queueFamilyIndexCount = 0;
|
||||
swapchainCI.presentMode = swapchainPresentMode;
|
||||
// Setting oldSwapChain to the saved handle of the previous swapchain aids in resource reuse and makes sure that we can still present already acquired images
|
||||
swapchainCI.oldSwapchain = oldSwapchain;
|
||||
// Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area
|
||||
swapchainCI.clipped = VK_TRUE;
|
||||
swapchainCI.compositeAlpha = compositeAlpha;
|
||||
|
||||
// Enable transfer source on swap chain images if supported
|
||||
if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) {
|
||||
swapchainCI.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
}
|
||||
|
||||
// Enable transfer destination on swap chain images if supported
|
||||
if (surfCaps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT) {
|
||||
swapchainCI.imageUsage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
}
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateSwapchainKHR(VulkanDevice::device, &swapchainCI, nullptr, &swapChain));
|
||||
|
||||
// If an existing swap chain is re-created, destroy the old swap chain and the ressources owned by the application (image views, images are owned by the swap chain)
|
||||
if (oldSwapchain != VK_NULL_HANDLE) {
|
||||
for (auto i = 0; i < images.size(); i++) {
|
||||
vkDestroyImageView(VulkanDevice::device, imageViews[i], nullptr);
|
||||
}
|
||||
vkDestroySwapchainKHR(VulkanDevice::device, oldSwapchain, nullptr);
|
||||
}
|
||||
uint32_t imageCount{ 0 };
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetSwapchainImagesKHR(VulkanDevice::device, swapChain, &imageCount, nullptr));
|
||||
|
||||
// Get the swap chain images
|
||||
images.resize(imageCount);
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetSwapchainImagesKHR(VulkanDevice::device, swapChain, &imageCount, images.data()));
|
||||
|
||||
// Get the swap chain buffers containing the image and imageview
|
||||
imageViews.resize(imageCount);
|
||||
for (auto i = 0; i < images.size(); i++)
|
||||
{
|
||||
VkImageViewCreateInfo colorAttachmentView = {};
|
||||
colorAttachmentView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
|
||||
colorAttachmentView.pNext = NULL;
|
||||
colorAttachmentView.format = colorFormat;
|
||||
colorAttachmentView.components = {
|
||||
VK_COMPONENT_SWIZZLE_R,
|
||||
VK_COMPONENT_SWIZZLE_G,
|
||||
VK_COMPONENT_SWIZZLE_B,
|
||||
VK_COMPONENT_SWIZZLE_A
|
||||
};
|
||||
colorAttachmentView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
colorAttachmentView.subresourceRange.baseMipLevel = 0;
|
||||
colorAttachmentView.subresourceRange.levelCount = 1;
|
||||
colorAttachmentView.subresourceRange.baseArrayLayer = 0;
|
||||
colorAttachmentView.subresourceRange.layerCount = 1;
|
||||
colorAttachmentView.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
colorAttachmentView.flags = 0;
|
||||
colorAttachmentView.image = images[i];
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateImageView(VulkanDevice::device, &colorAttachmentView, nullptr, &imageViews[i]));
|
||||
}
|
||||
}
|
||||
|
||||
WindowWaylandVulkan::WindowWaylandVulkan(std::string name, std::uint32_t width, std::uint32_t height) : WindowWayland(name, width, height) {
|
||||
VkWaylandSurfaceCreateInfoKHR createInfo = {};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
|
||||
createInfo.display = display;
|
||||
createInfo.surface = surface;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateWaylandSurfaceKHR(VulkanDevice::instance, &createInfo, NULL, &vulkanSurface));
|
||||
|
||||
// Get list of supported surface formats
|
||||
std::uint32_t formatCount;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceFormatsKHR(VulkanDevice::physDevice, vulkanSurface, &formatCount, NULL));
|
||||
assert(formatCount > 0);
|
||||
|
||||
std::vector<VkSurfaceFormatKHR> surfaceFormats(formatCount);
|
||||
VulkanDevice::CHECK_VK_RESULT(vkGetPhysicalDeviceSurfaceFormatsKHR(VulkanDevice::physDevice, vulkanSurface, &formatCount, surfaceFormats.data()));
|
||||
|
||||
// We want to get a format that best suits our needs, so we try to get one from a set of preferred formats
|
||||
// Initialize the format to the first one returned by the implementation in case we can't find one of the preffered formats
|
||||
VkSurfaceFormatKHR selectedFormat = surfaceFormats[0];
|
||||
std::vector<VkFormat> preferredImageFormats = {
|
||||
VK_FORMAT_R8G8B8A8_UNORM,
|
||||
};
|
||||
|
||||
for (auto& availableFormat : surfaceFormats) {
|
||||
if (std::find(preferredImageFormats.begin(), preferredImageFormats.end(), availableFormat.format) != preferredImageFormats.end()) {
|
||||
selectedFormat = availableFormat;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
colorFormat = selectedFormat.format;
|
||||
colorSpace = selectedFormat.colorSpace;
|
||||
|
||||
CreateSwapchain();
|
||||
|
||||
std::array<VkAttachmentDescription, 2> attachments = {};
|
||||
// Color attachment
|
||||
attachments[0].format = colorFormat;
|
||||
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||||
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||||
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
|
||||
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||||
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
|
||||
// Depth attachment
|
||||
attachments[1].format = VulkanDevice::depthFormat;
|
||||
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||||
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||||
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||||
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||||
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
||||
|
||||
VkAttachmentReference colorReference = {};
|
||||
colorReference.attachment = 0;
|
||||
colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
|
||||
VkAttachmentReference depthReference = {};
|
||||
depthReference.attachment = 1;
|
||||
depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
|
||||
|
||||
VkSubpassDescription subpassDescription = {};
|
||||
subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
|
||||
subpassDescription.colorAttachmentCount = 1;
|
||||
subpassDescription.pColorAttachments = &colorReference;
|
||||
subpassDescription.pDepthStencilAttachment = &depthReference;
|
||||
subpassDescription.inputAttachmentCount = 0;
|
||||
subpassDescription.pInputAttachments = nullptr;
|
||||
subpassDescription.preserveAttachmentCount = 0;
|
||||
subpassDescription.pPreserveAttachments = nullptr;
|
||||
subpassDescription.pResolveAttachments = nullptr;
|
||||
|
||||
// Subpass dependencies for layout transitions
|
||||
std::array<VkSubpassDependency, 2> dependencies{};
|
||||
|
||||
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
|
||||
dependencies[0].dstSubpass = 0;
|
||||
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
|
||||
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
|
||||
dependencies[0].srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
|
||||
dependencies[0].dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
|
||||
dependencies[0].dependencyFlags = 0;
|
||||
|
||||
dependencies[1].srcSubpass = VK_SUBPASS_EXTERNAL;
|
||||
dependencies[1].dstSubpass = 0;
|
||||
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
||||
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
||||
dependencies[1].srcAccessMask = 0;
|
||||
dependencies[1].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
|
||||
dependencies[1].dependencyFlags = 0;
|
||||
|
||||
VkRenderPassCreateInfo renderPassInfo = {};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
|
||||
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
|
||||
renderPassInfo.pAttachments = attachments.data();
|
||||
renderPassInfo.subpassCount = 1;
|
||||
renderPassInfo.pSubpasses = &subpassDescription;
|
||||
renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
|
||||
renderPassInfo.pDependencies = dependencies.data();
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateRenderPass(VulkanDevice::device, &renderPassInfo, nullptr, &renderPass));
|
||||
|
||||
VkImageCreateInfo imageCI{};
|
||||
imageCI.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
|
||||
imageCI.imageType = VK_IMAGE_TYPE_2D;
|
||||
imageCI.format = VulkanDevice::depthFormat;
|
||||
imageCI.extent = { width, height, 1 };
|
||||
imageCI.mipLevels = 1;
|
||||
imageCI.arrayLayers = 1;
|
||||
imageCI.samples = VK_SAMPLE_COUNT_1_BIT;
|
||||
imageCI.tiling = VK_IMAGE_TILING_OPTIMAL;
|
||||
imageCI.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateImage(VulkanDevice::device, &imageCI, nullptr, &depthStencil.image));
|
||||
VkMemoryRequirements memReqs{};
|
||||
vkGetImageMemoryRequirements(VulkanDevice::device, depthStencil.image, &memReqs);
|
||||
|
||||
VkMemoryAllocateInfo memAllloc{};
|
||||
memAllloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
memAllloc.allocationSize = memReqs.size;
|
||||
memAllloc.memoryTypeIndex = VulkanDevice::GetMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VulkanDevice::CHECK_VK_RESULT(vkAllocateMemory(VulkanDevice::device, &memAllloc, nullptr, &depthStencil.memory));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkBindImageMemory(VulkanDevice::device, depthStencil.image, depthStencil.memory, 0));
|
||||
|
||||
VkImageViewCreateInfo imageViewCI{};
|
||||
imageViewCI.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
|
||||
imageViewCI.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
imageViewCI.image = depthStencil.image;
|
||||
imageViewCI.format = VulkanDevice::depthFormat;
|
||||
imageViewCI.subresourceRange.baseMipLevel = 0;
|
||||
imageViewCI.subresourceRange.levelCount = 1;
|
||||
imageViewCI.subresourceRange.baseArrayLayer = 0;
|
||||
imageViewCI.subresourceRange.layerCount = 1;
|
||||
imageViewCI.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateImageView(VulkanDevice::device, &imageViewCI, nullptr, &depthStencil.view));
|
||||
|
||||
// Create frame buffers for every swap chain image
|
||||
frameBuffers.resize(images.size());
|
||||
for (uint32_t i = 0; i < frameBuffers.size(); i++)
|
||||
{
|
||||
const VkImageView attachments[2] = {
|
||||
imageViews[i],
|
||||
depthStencil.view
|
||||
};
|
||||
VkFramebufferCreateInfo frameBufferCreateInfo{};
|
||||
frameBufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
frameBufferCreateInfo.renderPass = renderPass;
|
||||
frameBufferCreateInfo.attachmentCount = 2;
|
||||
frameBufferCreateInfo.pAttachments = attachments;
|
||||
frameBufferCreateInfo.width = width;
|
||||
frameBufferCreateInfo.height = height;
|
||||
frameBufferCreateInfo.layers = 1;
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateFramebuffer(VulkanDevice::device, &frameBufferCreateInfo, nullptr, &frameBuffers[i]));
|
||||
}
|
||||
|
||||
drawCmdBuffers.resize(images.size());
|
||||
VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo(VulkanDevice::commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, static_cast<uint32_t>(drawCmdBuffers.size()));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkAllocateCommandBuffers(VulkanDevice::device, &cmdBufAllocateInfo, drawCmdBuffers.data()));
|
||||
|
||||
VkSemaphoreCreateInfo semaphoreCreateInfo = vks::initializers::semaphoreCreateInfo();
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateSemaphore(VulkanDevice::device, &semaphoreCreateInfo, nullptr, &semaphores.presentComplete));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkCreateSemaphore(VulkanDevice::device, &semaphoreCreateInfo, nullptr, &semaphores.renderComplete));
|
||||
|
||||
// Set up submit info structure
|
||||
// Semaphores will stay the same during application lifetime
|
||||
// Command buffer submission info is set by each example
|
||||
submitInfo = vks::initializers::submitInfo();
|
||||
submitInfo.pWaitDstStageMask = &submitPipelineStages;
|
||||
submitInfo.waitSemaphoreCount = 1;
|
||||
submitInfo.pWaitSemaphores = &semaphores.presentComplete;
|
||||
submitInfo.signalSemaphoreCount = 1;
|
||||
submitInfo.pSignalSemaphores = &semaphores.renderComplete;
|
||||
}
|
||||
|
||||
WindowWaylandVulkan::~WindowWaylandVulkan() {
|
||||
if (swapChain != VK_NULL_HANDLE) {
|
||||
for (auto i = 0; i < images.size(); i++) {
|
||||
vkDestroyImageView(VulkanDevice::device, imageViews[i], nullptr);
|
||||
}
|
||||
vkDestroySwapchainKHR(VulkanDevice::device, swapChain, nullptr);
|
||||
}
|
||||
if (vulkanSurface != VK_NULL_HANDLE) {
|
||||
vkDestroySurfaceKHR(VulkanDevice::instance, vulkanSurface, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
VkCommandBuffer WindowWaylandVulkan::StartInit() {
|
||||
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
|
||||
VulkanDevice::CHECK_VK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[currentBuffer], &cmdBufInfo));
|
||||
return drawCmdBuffers[currentBuffer];
|
||||
}
|
||||
|
||||
void WindowWaylandVulkan::FinishInit() {
|
||||
VkSubmitInfo submitInfo{};
|
||||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
|
||||
VulkanDevice::CHECK_VK_RESULT(vkEndCommandBuffer(drawCmdBuffers[currentBuffer]));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkQueueSubmit(VulkanDevice::queue, 1, &submitInfo, VK_NULL_HANDLE));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkQueueWaitIdle(VulkanDevice::queue));
|
||||
}
|
||||
|
||||
void WindowWaylandVulkan::StartAsync() {
|
||||
thread = std::thread(&WindowWaylandVulkan::StartSync, this);
|
||||
}
|
||||
|
||||
void WindowWaylandVulkan::StartSync() {
|
||||
while (open && wl_display_dispatch(display) != -1) {
|
||||
// Acquire the next image from the swap chain
|
||||
VulkanDevice::CHECK_VK_RESULT(vkAcquireNextImageKHR(VulkanDevice::device, swapChain, UINT64_MAX, semaphores.presentComplete, (VkFence)nullptr, ¤tBuffer));
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
|
||||
|
||||
VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo();
|
||||
|
||||
VkClearValue clearValues[2];
|
||||
clearValues[0].color = { };;
|
||||
clearValues[1].depthStencil = { 1.0f, 0 };
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[currentBuffer], &cmdBufInfo));
|
||||
|
||||
VkImageSubresourceRange range{};
|
||||
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
range.baseMipLevel = 0;
|
||||
range.levelCount = VK_REMAINING_MIP_LEVELS;
|
||||
range.baseArrayLayer = 0;
|
||||
range.layerCount = VK_REMAINING_ARRAY_LAYERS;
|
||||
|
||||
VkImageSubresourceRange depth_range{range};
|
||||
depth_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||||
|
||||
image_layout_transition(drawCmdBuffers[currentBuffer],
|
||||
images[currentBuffer],
|
||||
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
0,
|
||||
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
range);
|
||||
|
||||
image_layout_transition(drawCmdBuffers[currentBuffer],
|
||||
depthStencil.image,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
|
||||
depth_range);
|
||||
|
||||
VkRenderingAttachmentInfoKHR color_attachment_info = {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, VK_NULL_HANDLE};
|
||||
color_attachment_info.imageView = imageViews[currentBuffer];
|
||||
color_attachment_info.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
color_attachment_info.resolveMode = VK_RESOLVE_MODE_NONE;
|
||||
color_attachment_info.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||||
color_attachment_info.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
|
||||
color_attachment_info.clearValue = { 0.0f, 0.0f, 0.2f, 1.0f };
|
||||
|
||||
VkRenderingAttachmentInfoKHR depth_attachment_info = {VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, VK_NULL_HANDLE};
|
||||
depth_attachment_info.imageView = depthStencil.view;
|
||||
depth_attachment_info.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL;
|
||||
depth_attachment_info.resolveMode = VK_RESOLVE_MODE_NONE;
|
||||
depth_attachment_info.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
|
||||
depth_attachment_info.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
|
||||
depth_attachment_info.clearValue = { 1.0f, 0 };
|
||||
|
||||
VkRenderingInfo render_info = {VK_STRUCTURE_TYPE_RENDERING_INFO_KHR,VK_NULL_HANDLE,0};
|
||||
render_info.renderArea = VkRect2D{VkOffset2D{}, VkExtent2D{width, height}};
|
||||
render_info.viewMask = 0;
|
||||
render_info.layerCount = 1;
|
||||
render_info.colorAttachmentCount = 1;
|
||||
render_info.pColorAttachments = &color_attachment_info;
|
||||
render_info.pDepthAttachment = &depth_attachment_info;
|
||||
render_info.pStencilAttachment = VK_NULL_HANDLE;
|
||||
|
||||
VulkanDevice::vkCmdBeginRenderingKHRProc(drawCmdBuffers[currentBuffer], &render_info);
|
||||
|
||||
VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f);
|
||||
vkCmdSetViewport(drawCmdBuffers[currentBuffer], 0, 1, &viewport);
|
||||
|
||||
VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0);
|
||||
vkCmdSetScissor(drawCmdBuffers[currentBuffer], 0, 1, &scissor);
|
||||
|
||||
onDraw.Invoke(drawCmdBuffers[currentBuffer]);
|
||||
mouseDelta = {0, 0};
|
||||
|
||||
VulkanDevice::vkCmdEndRenderingKHRProc(drawCmdBuffers[currentBuffer]);
|
||||
|
||||
image_layout_transition(drawCmdBuffers[currentBuffer],
|
||||
images[currentBuffer],
|
||||
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
|
||||
range
|
||||
);
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkEndCommandBuffer(drawCmdBuffers[currentBuffer]));
|
||||
|
||||
VulkanDevice::CHECK_VK_RESULT(vkQueueSubmit(VulkanDevice::queue, 1, &submitInfo, VK_NULL_HANDLE));
|
||||
VkPresentInfoKHR presentInfo = {};
|
||||
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
||||
presentInfo.pNext = NULL;
|
||||
presentInfo.swapchainCount = 1;
|
||||
presentInfo.pSwapchains = &swapChain;
|
||||
presentInfo.pImageIndices = ¤tBuffer;
|
||||
// Check if a wait semaphore has been specified to wait for before presenting the image
|
||||
if (semaphores.renderComplete != VK_NULL_HANDLE)
|
||||
{
|
||||
presentInfo.pWaitSemaphores = &semaphores.renderComplete;
|
||||
presentInfo.waitSemaphoreCount = 1;
|
||||
}
|
||||
VulkanDevice::CHECK_VK_RESULT(vkQueuePresentKHR(VulkanDevice::queue, &presentInfo));
|
||||
VulkanDevice::CHECK_VK_RESULT(vkQueueWaitIdle(VulkanDevice::queue));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,202 +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
|
||||
*/
|
||||
|
||||
module;
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/input.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-cursor.h>
|
||||
#include <xkbcommon/xkbcommon.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_wayland.h>
|
||||
#include <wayland-client.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <print>
|
||||
#include <stdbool.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <wayland-client.h>
|
||||
#include <wayland-client-protocol.h>
|
||||
#include <linux/input-event-codes.h>
|
||||
|
||||
export module Crafter.Graphics:WindowWaylandWayland_impl;
|
||||
import :WindowWaylandWayland;
|
||||
import std;
|
||||
import Crafter.Event;
|
||||
using namespace Crafter;
|
||||
|
||||
|
||||
static void randname(char *buf) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
long r = ts.tv_nsec;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
buf[i] = 'A'+(r&15)+(r&16)*2;
|
||||
r >>= 5;
|
||||
}
|
||||
}
|
||||
|
||||
static int anonymous_shm_open(void) {
|
||||
char name[] = "/hello-wayland-XXXXXX";
|
||||
int retries = 100;
|
||||
|
||||
do {
|
||||
randname(name + strlen(name) - 6);
|
||||
|
||||
--retries;
|
||||
// shm_open guarantees that O_CLOEXEC is set
|
||||
int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
|
||||
if (fd >= 0) {
|
||||
shm_unlink(name);
|
||||
return fd;
|
||||
}
|
||||
} while (retries > 0 && errno == EEXIST);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int create_shm_file(off_t size) {
|
||||
int fd = anonymous_shm_open();
|
||||
if (fd < 0) {
|
||||
return fd;
|
||||
}
|
||||
|
||||
if (ftruncate(fd, size) < 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return fd;
|
||||
}
|
||||
|
||||
|
||||
void ScaleBitmapR8G8B8(Pixel_BU8_GU8_RU8_AU8* dst, const Pixel_BU8_GU8_RU8_AU8* src, std::uint32_t srcWidth, std::uint32_t srcHeight, std::uint32_t dstWidth, std::uint32_t dstHeight) {
|
||||
for (std::uint32_t y = 0; y < dstHeight; y++) {
|
||||
std::uint32_t srcY = y * srcHeight / dstHeight;
|
||||
for (std::uint32_t x = 0; x < dstWidth; x++) {
|
||||
std::uint32_t srcX = x * srcWidth / dstWidth;
|
||||
const Pixel_BU8_GU8_RU8_AU8* srcPixel = src + (srcY * srcWidth + srcX);
|
||||
Pixel_BU8_GU8_RU8_AU8* dstPixel = dst + (y * dstWidth + x);
|
||||
dstPixel[0] = srcPixel[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WindowWaylandWayland::WindowWaylandWayland(std::string name, std::uint32_t width, std::uint32_t height) : WindowWayland(name, width, height) {
|
||||
// Create a wl_buffer, attach it to the surface and commit the surface
|
||||
int stride = width * 4;
|
||||
int size = stride * height;
|
||||
|
||||
// Allocate a shared memory file with the right size
|
||||
int fd = create_shm_file(size);
|
||||
if (fd < 0) {
|
||||
fprintf(stderr, "creating a buffer file for %d B failed: %m\n", size);
|
||||
}
|
||||
|
||||
// Map the shared memory file
|
||||
frontFramebuffer = reinterpret_cast<Pixel_BU8_GU8_RU8_AU8*>(mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
|
||||
if (frontFramebuffer == MAP_FAILED) {
|
||||
fprintf(stderr, "mmap failed: %m\n");
|
||||
close(fd);
|
||||
}
|
||||
backFramebuffer = reinterpret_cast<Pixel_BU8_GU8_RU8_AU8*>(mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
|
||||
if (backFramebuffer == MAP_FAILED) {
|
||||
fprintf(stderr, "mmap failed: %m\n");
|
||||
close(fd);
|
||||
}
|
||||
|
||||
// Create a wl_buffer from our shared memory file descriptor
|
||||
wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size);
|
||||
frontBuffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888);
|
||||
backBuffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888);
|
||||
wl_shm_pool_destroy(pool);
|
||||
|
||||
// Now that we've mapped the file and created the wl_buffer, we no longer
|
||||
// need to keep file descriptor opened
|
||||
close(fd);
|
||||
|
||||
if (frontBuffer == NULL || backBuffer == NULL) {
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
wl_surface_attach(surface, frontBuffer, 0, 0);
|
||||
wl_surface_commit(surface);
|
||||
}
|
||||
|
||||
WindowWaylandWayland::~WindowWaylandWayland() {
|
||||
open = false;
|
||||
thread.join();
|
||||
}
|
||||
|
||||
void WindowWaylandWayland::StartAsync() {
|
||||
thread = std::thread(&WindowWaylandWayland::StartSync, this);
|
||||
}
|
||||
|
||||
void WindowWaylandWayland::StartSync() {
|
||||
while (open && wl_display_dispatch(display) != -1) {
|
||||
std::vector<UiElement*> drawOrder;
|
||||
drawOrder.reserve(elements.size());
|
||||
for (UiElement& e : elements) drawOrder.push_back(&e);
|
||||
std::sort(drawOrder.begin(), drawOrder.end(), [](UiElement* a, UiElement* b){ return a->z < b->z; });
|
||||
|
||||
for(const UiElement* element : drawOrder) {
|
||||
std::cout << element->bufferWidth << std::endl;
|
||||
ScaleData data = ScaleElement(*element);
|
||||
std::vector<Pixel_BU8_GU8_RU8_AU8> scaled(data.width*data.height);
|
||||
ScaleBitmapR8G8B8(scaled.data(), element->buffer.data(), element->bufferWidth, element->bufferHeight, data.width, data.height);
|
||||
for (std::int32_t x = data.x; x - data.x < data.width; x++) {
|
||||
for (std::int32_t y = data.y; y - data.y < data.height; y++) {
|
||||
if (x >= 0 && x < width && y >= 0 && y < height) {
|
||||
Pixel_BU8_GU8_RU8_AU8& dst = backFramebuffer[y * width + x];
|
||||
const Pixel_BU8_GU8_RU8_AU8& src = scaled[(y - data.y) * data.width + (x - data.x)];
|
||||
|
||||
float srcA = src.a / 255.0f;
|
||||
float dstA = dst.a / 255.0f;
|
||||
|
||||
float outA = srcA + dstA * (1.0f - srcA);
|
||||
if (outA > 0.0f) {
|
||||
dst.r = static_cast<uint8_t>((src.r * srcA + dst.r * dstA * (1.0f - srcA)) / outA);
|
||||
dst.g = static_cast<uint8_t>((src.g * srcA + dst.g * dstA * (1.0f - srcA)) / outA);
|
||||
dst.b = static_cast<uint8_t>((src.b * srcA + dst.b * dstA * (1.0f - srcA)) / outA);
|
||||
dst.a = static_cast<uint8_t>(outA * 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
wl_surface_attach(surface, backBuffer, 0, 0);
|
||||
wl_surface_damage(surface, 0, 0, width, height);
|
||||
wl_surface_commit(surface);
|
||||
|
||||
std::swap(frontFramebuffer, backFramebuffer);
|
||||
std::swap(frontBuffer, backBuffer);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue