/* * RRT-GPU: Rotating Wireframe Box Demo * ===================================== * Target: Linux, Vulkan, SDL2 * Language: C * * Implements the RRT-GPU architecture: * - Numerator = model transform (rotation) * - Denominator = view x projection * - Reduced = numerator x denominator (CPU reference) * - Residual = max normalized difference (CPU vs independent check) * - Certificate = caller-managed verification level * * Build: * 1. Compile shaders: * glslangValidator -V shaders/vert.glsl -o shaders/vert.spv * glslangValidator -V shaders/frag.glsl -o shaders/frag.spv * 2. Compile: * gcc -o rrt_gpu_demo rrt_gpu_demo.c \ * $(pkg-config --cflags --libs sdl2 vulkan) -lm * 3. Run: * ./rrt_gpu_demo * * Shaders (shaders/vert.glsl): * #version 450 * layout(push_constant) uniform RRTPushConstants { * mat4 numerator; * mat4 denominator; * } rrt; * layout(location = 0) in vec3 inPosition; * layout(location = 1) in vec4 inColor; * layout(location = 0) out vec4 fragColor; * void main() { * gl_Position = rrt.denominator * rrt.numerator * vec4(inPosition, 1.0); * fragColor = inColor; * } * * Shaders (shaders/frag.glsl): * #version 450 * layout(location = 0) in vec4 fragColor; * layout(location = 0) out vec4 outColor; * void main() { outColor = fragColor; } */ #include #include #include #include #include #include #include #include /* ─── Constants ─────────────────────────────────────────────────────── */ #define MAX_FRAMES_IN_FLIGHT 2 #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define VERTEX_COUNT 24 /* 12 line segments * 2 vertices */ /* ─── RRT Types ──────────────────────────────────────────────────────── */ typedef struct { float position[3]; float color[4]; } RRTVertex; typedef struct { float numerator[16]; float denominator[16]; float reduced[16]; float residual; uint32_t certificate_order; } RRTDrawState; /* Push constants: 128 bytes (Vulkan minimum guarantee) */ typedef struct { float numerator[16]; float denominator[16]; } RRTPushConstants; /* ─── Vulkan Context ────────────────────────────────────────────────── */ typedef struct { SDL_Window *window; VkInstance instance; VkSurfaceKHR surface; VkPhysicalDevice physical_device; VkDevice device; VkQueue graphics_queue; VkQueue present_queue; uint32_t graphics_family; uint32_t present_family; VkSwapchainKHR swapchain; VkFormat swapchain_format; VkExtent2D swapchain_extent; uint32_t image_count; VkImage *swapchain_images; VkImageView *swapchain_image_views; VkFramebuffer *framebuffers; VkRenderPass render_pass; VkPipelineLayout pipeline_layout; VkPipeline pipeline; VkImage depth_image; VkDeviceMemory depth_memory; VkImageView depth_view; VkFormat depth_format; VkBuffer vertex_buffer; VkDeviceMemory vertex_memory; VkCommandPool command_pool; VkCommandBuffer command_buffers[MAX_FRAMES_IN_FLIGHT]; VkSemaphore acquire_semaphores[MAX_FRAMES_IN_FLIGHT]; VkSemaphore render_finished_semaphores[MAX_FRAMES_IN_FLIGHT]; VkFence in_flight_fences[MAX_FRAMES_IN_FLIGHT]; uint32_t current_frame; bool framebuffer_resized; float clear_color[4]; /* RRT state */ RRTDrawState rrt_state; } RRTGPU; /* ─── Matrix Utilities (column-major) ──────────────────────────────── */ static void mat4_identity(float *m) { memset(m, 0, 16 * sizeof(float)); m[0] = m[5] = m[10] = m[15] = 1.0f; } static void mat4_mul(const float *a, const float *b, float *result) { /* result = a * b (column-major) */ for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { float sum = 0.0f; for (int k = 0; k < 4; k++) { sum += a[k * 4 + row] * b[col * 4 + k]; } result[col * 4 + row] = sum; } } } static void mat4_rotate_y(float *m, float angle) { mat4_identity(m); float c = cosf(angle), s = sinf(angle); m[0] = c; m[2] = s; m[8] = -s; m[10] = c; } static void mat4_look_at(float *m, float ex, float ey, float ez, float cx, float cy, float cz, float ux, float uy, float uz) { float fx = cx - ex, fy = cy - ey, fz = cz - ez; float fl = sqrtf(fx*fx + fy*fy + fz*fz); fx /= fl; fy /= fl; fz /= fl; float sx = fy*uz - fz*uy; float sy = fz*ux - fx*uz; float sz = fx*uy - fy*ux; float sl = sqrtf(sx*sx + sy*sy + sz*sz); sx /= sl; sy /= sl; sz /= sl; float ux2 = sy*fz - sz*fy; float uy2 = sz*fx - sx*fz; float uz2 = sx*fy - sy*fx; m[0] = sx; m[4] = sy; m[8] = sz; m[12] = -(sx*ex + sy*ey + sz*ez); m[1] = ux2; m[5] = uy2; m[9] = uz2; m[13] = -(ux2*ex + uy2*ey + uz2*ez); m[2] = -fx; m[6] = -fy; m[10] = -fz; m[14] = (fx*ex + fy*ey + fz*ez); m[3] = 0; m[7] = 0; m[11] = 0; m[15] = 1; } static void mat4_perspective(float *m, float fov, float aspect, float near, float far) { memset(m, 0, 16 * sizeof(float)); float f = 1.0f / tanf(fov / 2.0f); m[0] = f / aspect; m[5] = -f; /* Invert Y for Vulkan NDC */ m[10] = far / (near - far); /* Vulkan [0, 1] depth projection */ m[11] = -1.0f; m[14] = (far * near) / (near - far); } /* ─── RRT Reduction & Residual ─────────────────────────────────────── */ static void rrt_compute_reduced(RRTDrawState *state) { /* reduced = numerator * denominator (CPU reference path) */ mat4_mul(state->numerator, state->denominator, state->reduced); } static float rrt_compute_residual(RRTDrawState *state) { /* * Independent reference path: compute reduced through a different * code path (element-by-element with explicit accumulation) to * detect matrix-layout or multiplication-order defects. */ float ref[16]; memset(ref, 0, sizeof(ref)); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { float sum = 0.0f; for (int k = 0; k < 4; k++) { sum += state->numerator[k * 4 + i] * state->denominator[j * 4 + k]; } ref[j * 4 + i] = sum; } } /* Normalized infinity-norm residual */ float diff_max = 0.0f; float norm_max = 0.0f; for (int i = 0; i < 16; i++) { float d = fabsf(state->reduced[i] - ref[i]); if (d > diff_max) diff_max = d; float n = fabsf(state->reduced[i]); if (n > norm_max) norm_max = n; } float denom = (norm_max > 1.0f) ? norm_max : 1.0f; float residual = diff_max / denom; state->residual = residual; return residual; } /* ─── Vulkan Helpers ────────────────────────────────────────────────── */ static void check_vk(VkResult r, const char *msg) { if (r != VK_SUCCESS) { fprintf(stderr, "Vulkan error: %s (code %d)\n", msg, r); exit(1); } } static uint32_t find_memory_type(VkPhysicalDevice pd, uint32_t type_filter, VkMemoryPropertyFlags props) { VkPhysicalDeviceMemoryProperties mem_props; vkGetPhysicalDeviceMemoryProperties(pd, &mem_props); for (uint32_t i = 0; i < mem_props.memoryTypeCount; i++) { if ((type_filter & (1 << i)) && (mem_props.memoryTypes[i].propertyFlags & props) == props) { return i; } } fprintf(stderr, "Failed to find suitable memory type\n"); exit(1); } static bool is_device_suitable(VkPhysicalDevice device, VkSurfaceKHR surface, uint32_t *gfx_family, uint32_t *pres_family) { uint32_t count = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &count, NULL); VkQueueFamilyProperties *families = malloc(count * sizeof(VkQueueFamilyProperties)); vkGetPhysicalDeviceQueueFamilyProperties(device, &count, families); bool found_gfx = false, found_pres = false; for (uint32_t i = 0; i < count; i++) { if (families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { *gfx_family = i; found_gfx = true; } VkBool32 pres_support = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &pres_support); if (pres_support) { *pres_family = i; found_pres = true; } if (found_gfx && found_pres) { free(families); return true; } } free(families); return false; } /* ─── Shader Loading ────────────────────────────────────────────────── */ static char *read_file(const char *path, size_t *size_out) { FILE *f = fopen(path, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); char *buf = malloc(sz); fread(buf, 1, sz, f); fclose(f); *size_out = (size_t)sz; return buf; } static VkShaderModule load_shader(VkDevice device, const char *path) { size_t size; char *code = read_file(path, &size); if (!code) { fprintf(stderr, "Failed to read shader: %s\n", path); fprintf(stderr, "Compile shaders first:\n"); fprintf(stderr, " glslangValidator -V shaders/vert.glsl -o shaders/vert.spv\n"); fprintf(stderr, " glslangValidator -V shaders/frag.glsl -o shaders/frag.spv\n"); exit(1); } VkShaderModuleCreateInfo ci = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = (const uint32_t *)code }; VkShaderModule module; check_vk(vkCreateShaderModule(device, &ci, NULL, &module), "create shader module"); free(code); return module; } /* ─── Swapchain ─────────────────────────────────────────────────────── */ static void create_swapchain(RRTGPU *gpu) { /* Surface capabilities */ VkSurfaceCapabilitiesKHR caps; vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu->physical_device, gpu->surface, &caps); /* Format */ uint32_t fmt_count = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(gpu->physical_device, gpu->surface, &fmt_count, NULL); VkSurfaceFormatKHR *formats = malloc(fmt_count * sizeof(VkSurfaceFormatKHR)); vkGetPhysicalDeviceSurfaceFormatsKHR(gpu->physical_device, gpu->surface, &fmt_count, formats); VkSurfaceFormatKHR chosen_format = formats[0]; for (uint32_t i = 0; i < fmt_count; i++) { if (formats[i].format == VK_FORMAT_B8G8R8A8_SRGB && formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { chosen_format = formats[i]; break; } } free(formats); gpu->swapchain_format = chosen_format.format; /* Extent */ if (caps.currentExtent.width != UINT32_MAX) { gpu->swapchain_extent = caps.currentExtent; } else { int w, h; SDL_GetWindowSize(gpu->window, &w, &h); gpu->swapchain_extent.width = (uint32_t)w; gpu->swapchain_extent.height = (uint32_t)h; if (gpu->swapchain_extent.width < caps.minImageExtent.width) gpu->swapchain_extent.width = caps.minImageExtent.width; if (gpu->swapchain_extent.height < caps.minImageExtent.height) gpu->swapchain_extent.height = caps.minImageExtent.height; if (gpu->swapchain_extent.width > caps.maxImageExtent.width) gpu->swapchain_extent.width = caps.maxImageExtent.width; if (gpu->swapchain_extent.height > caps.maxImageExtent.height) gpu->swapchain_extent.height = caps.maxImageExtent.height; } /* Present mode */ uint32_t pm_count = 0; vkGetPhysicalDeviceSurfacePresentModesKHR(gpu->physical_device, gpu->surface, &pm_count, NULL); VkPresentModeKHR *pmodes = malloc(pm_count * sizeof(VkPresentModeKHR)); vkGetPhysicalDeviceSurfacePresentModesKHR(gpu->physical_device, gpu->surface, &pm_count, pmodes); VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR; for (uint32_t i = 0; i < pm_count; i++) { if (pmodes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { present_mode = VK_PRESENT_MODE_MAILBOX_KHR; break; } } free(pmodes); /* Image count */ uint32_t image_count = caps.minImageCount + 1; if (caps.maxImageCount > 0 && image_count > caps.maxImageCount) { image_count = caps.maxImageCount; } /* Create swapchain */ VkSwapchainCreateInfoKHR ci = { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .surface = gpu->surface, .minImageCount = image_count, .imageFormat = chosen_format.format, .imageColorSpace = chosen_format.colorSpace, .imageExtent = gpu->swapchain_extent, .imageArrayLayers = 1, .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, .preTransform = caps.currentTransform, .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, .presentMode = present_mode, .clipped = VK_TRUE, .oldSwapchain = VK_NULL_HANDLE }; uint32_t queue_families[] = {gpu->graphics_family, gpu->present_family}; if (gpu->graphics_family != gpu->present_family) { ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT; ci.queueFamilyIndexCount = 2; ci.pQueueFamilyIndices = queue_families; } check_vk(vkCreateSwapchainKHR(gpu->device, &ci, NULL, &gpu->swapchain), "create swapchain"); /* Get images */ vkGetSwapchainImagesKHR(gpu->device, gpu->swapchain, &gpu->image_count, NULL); gpu->swapchain_images = malloc(gpu->image_count * sizeof(VkImage)); vkGetSwapchainImagesKHR(gpu->device, gpu->swapchain, &gpu->image_count, gpu->swapchain_images); /* Image views */ gpu->swapchain_image_views = malloc(gpu->image_count * sizeof(VkImageView)); for (uint32_t i = 0; i < gpu->image_count; i++) { VkImageViewCreateInfo ivci = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = gpu->swapchain_images[i], .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = gpu->swapchain_format, .subresourceRange = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1 } }; check_vk(vkCreateImageView(gpu->device, &ivci, NULL, &gpu->swapchain_image_views[i]), "create image view"); } } static void destroy_swapchain(RRTGPU *gpu) { if (gpu->depth_view) { vkDestroyImageView(gpu->device, gpu->depth_view, NULL); gpu->depth_view = VK_NULL_HANDLE; } if (gpu->depth_image) { vkDestroyImage(gpu->device, gpu->depth_image, NULL); gpu->depth_image = VK_NULL_HANDLE; } if (gpu->depth_memory) { vkFreeMemory(gpu->device, gpu->depth_memory, NULL); gpu->depth_memory = VK_NULL_HANDLE; } for (uint32_t i = 0; i < gpu->image_count; i++) { if (gpu->framebuffers[i]) { vkDestroyFramebuffer(gpu->device, gpu->framebuffers[i], NULL); } if (gpu->swapchain_image_views[i]) { vkDestroyImageView(gpu->device, gpu->swapchain_image_views[i], NULL); } } free(gpu->framebuffers); free(gpu->swapchain_image_views); free(gpu->swapchain_images); gpu->framebuffers = NULL; gpu->swapchain_image_views = NULL; gpu->swapchain_images = NULL; if (gpu->swapchain) { vkDestroySwapchainKHR(gpu->device, gpu->swapchain, NULL); gpu->swapchain = VK_NULL_HANDLE; } } /* ─── Depth Attachment ──────────────────────────────────────────────── */ static VkFormat find_depth_format(VkPhysicalDevice pd) { VkFormat candidates[] = {VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT}; for (int i = 0; i < 3; i++) { VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(pd, candidates[i], &props); if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { return candidates[i]; } } return VK_FORMAT_D32_SFLOAT; } static void create_depth_resources(RRTGPU *gpu) { gpu->depth_format = find_depth_format(gpu->physical_device); VkImageCreateInfo ici = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = gpu->depth_format, .extent = {gpu->swapchain_extent.width, gpu->swapchain_extent.height, 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED }; check_vk(vkCreateImage(gpu->device, &ici, NULL, &gpu->depth_image), "create depth image"); VkMemoryRequirements mem_req; vkGetImageMemoryRequirements(gpu->device, gpu->depth_image, &mem_req); VkMemoryAllocateInfo mai = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = mem_req.size, .memoryTypeIndex = find_memory_type(gpu->physical_device, mem_req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) }; check_vk(vkAllocateMemory(gpu->device, &mai, NULL, &gpu->depth_memory), "alloc depth memory"); check_vk(vkBindImageMemory(gpu->device, gpu->depth_image, gpu->depth_memory, 0), "bind depth memory"); VkImageViewCreateInfo ivci = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = gpu->depth_image, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = gpu->depth_format, .subresourceRange = { .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1 } }; check_vk(vkCreateImageView(gpu->device, &ivci, NULL, &gpu->depth_view), "create depth view"); } /* ─── Render Pass & Pipeline ────────────────────────────────────────── */ static void create_render_pass(RRTGPU *gpu) { VkAttachmentDescription color_attach = { .format = gpu->swapchain_format, .samples = VK_SAMPLE_COUNT_1_BIT, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE, .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR }; VkAttachmentDescription depth_attach = { .format = gpu->depth_format, .samples = VK_SAMPLE_COUNT_1_BIT, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL }; VkAttachmentReference color_ref = { .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkAttachmentReference depth_ref = { .attachment = 1, .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpass = { .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1, .pColorAttachments = &color_ref, .pDepthStencilAttachment = &depth_ref }; VkSubpassDependency dep = { .srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0, .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, .srcAccessMask = 0, .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT }; VkAttachmentDescription attachments[] = {color_attach, depth_attach}; VkRenderPassCreateInfo rpci = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 2, .pAttachments = attachments, .subpassCount = 1, .pSubpasses = &subpass, .dependencyCount = 1, .pDependencies = &dep }; check_vk(vkCreateRenderPass(gpu->device, &rpci, NULL, &gpu->render_pass), "create render pass"); } static void create_pipeline(RRTGPU *gpu) { VkShaderModule vert = load_shader(gpu->device, "shaders/vert.spv"); VkShaderModule frag = load_shader(gpu->device, "shaders/frag.spv"); VkPipelineShaderStageCreateInfo stages[] = { { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vert, .pName = "main" }, { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = frag, .pName = "main" } }; /* Vertex input */ VkVertexInputBindingDescription binding = { .binding = 0, .stride = sizeof(RRTVertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX }; VkVertexInputAttributeDescription attrs[] = { { .binding = 0, .location = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(RRTVertex, position) }, { .binding = 0, .location = 1, .format = VK_FORMAT_R32G32B32A32_SFLOAT, .offset = offsetof(RRTVertex, color) } }; VkPipelineVertexInputStateCreateInfo vertex_input = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .vertexBindingDescriptionCount = 1, .pVertexBindingDescriptions = &binding, .vertexAttributeDescriptionCount = 2, .pVertexAttributeDescriptions = attrs }; VkPipelineInputAssemblyStateCreateInfo input_assembly = { .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST, .primitiveRestartEnable = VK_FALSE }; /* Viewport & scissor (dynamic) */ VkPipelineViewportStateCreateInfo viewport_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1 }; VkPipelineRasterizationStateCreateInfo rasterizer = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .depthClampEnable = VK_FALSE, .rasterizerDiscardEnable = VK_FALSE, .polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1.0f, .cullMode = VK_CULL_MODE_NONE, .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .depthBiasEnable = VK_FALSE }; VkPipelineMultisampleStateCreateInfo multisampling = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .sampleShadingEnable = VK_FALSE, .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT }; VkPipelineDepthStencilStateCreateInfo depth_stencil = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, .depthTestEnable = VK_TRUE, .depthWriteEnable = VK_TRUE, .depthCompareOp = VK_COMPARE_OP_LESS, .depthBoundsTestEnable = VK_FALSE, .stencilTestEnable = VK_FALSE }; VkPipelineColorBlendAttachmentState blend_attach = { .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, .blendEnable = VK_FALSE }; VkPipelineColorBlendStateCreateInfo color_blend = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .logicOpEnable = VK_FALSE, .attachmentCount = 1, .pAttachments = &blend_attach }; VkDynamicState dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, .dynamicStateCount = 2, .pDynamicStates = dynamic_states }; /* Push constant range */ VkPushConstantRange push_range = { .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(RRTPushConstants) }; VkPipelineLayoutCreateInfo plci = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .pushConstantRangeCount = 1, .pPushConstantRanges = &push_range }; check_vk(vkCreatePipelineLayout(gpu->device, &plci, NULL, &gpu->pipeline_layout), "create pipeline layout"); VkGraphicsPipelineCreateInfo gpci = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2, .pStages = stages, .pVertexInputState = &vertex_input, .pInputAssemblyState = &input_assembly, .pViewportState = &viewport_state, .pRasterizationState = &rasterizer, .pMultisampleState = &multisampling, .pDepthStencilState = &depth_stencil, .pColorBlendState = &color_blend, .pDynamicState = &dynamic_state, .layout = gpu->pipeline_layout, .renderPass = gpu->render_pass, .subpass = 0 }; check_vk(vkCreateGraphicsPipelines(gpu->device, VK_NULL_HANDLE, 1, &gpci, NULL, &gpu->pipeline), "create graphics pipeline"); vkDestroyShaderModule(gpu->device, vert, NULL); vkDestroyShaderModule(gpu->device, frag, NULL); } /* ─── Framebuffers ──────────────────────────────────────────────────── */ static void create_framebuffers(RRTGPU *gpu) { gpu->framebuffers = malloc(gpu->image_count * sizeof(VkFramebuffer)); for (uint32_t i = 0; i < gpu->image_count; i++) { VkImageView attachments[] = {gpu->swapchain_image_views[i], gpu->depth_view}; VkFramebufferCreateInfo fci = { .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = gpu->render_pass, .attachmentCount = 2, .pAttachments = attachments, .width = gpu->swapchain_extent.width, .height = gpu->swapchain_extent.height, .layers = 1 }; check_vk(vkCreateFramebuffer(gpu->device, &fci, NULL, &gpu->framebuffers[i]), "create framebuffer"); } } /* ─── Vertex Buffer ─────────────────────────────────────────────────── */ static void create_vertex_buffer(RRTGPU *gpu) { /* Cube: 12 edges, 2 vertices each = 24 vertices */ RRTVertex vertices[VERTEX_COUNT]; /* Define cube corners */ float c[8][3] = { {-1,-1,-1}, {1,-1,-1}, {1,1,-1}, {-1,1,-1}, {-1,-1, 1}, {1,-1, 1}, {1,1, 1}, {-1,1, 1} }; /* 12 edges: pairs of corner indices */ int edges[12][2] = { {0,1},{1,2},{2,3},{3,0}, /* front face */ {4,5},{5,6},{6,7},{7,4}, /* back face */ {0,4},{1,5},{2,6},{3,7} /* connecting edges */ }; /* Colors per edge (cycle through a few) */ float colors[4][4] = { {1.0f, 0.3f, 0.3f, 1.0f}, /* red */ {0.3f, 1.0f, 0.3f, 1.0f}, /* green */ {0.3f, 0.3f, 1.0f, 1.0f}, /* blue */ {1.0f, 1.0f, 0.3f, 1.0f} /* yellow */ }; int vi = 0; for (int e = 0; e < 12; e++) { for (int v = 0; v < 2; v++) { int ci = edges[e][v]; vertices[vi].position[0] = c[ci][0]; vertices[vi].position[1] = c[ci][1]; vertices[vi].position[2] = c[ci][2]; int color_idx = e % 4; vertices[vi].color[0] = colors[color_idx][0]; vertices[vi].color[1] = colors[color_idx][1]; vertices[vi].color[2] = colors[color_idx][2]; vertices[vi].color[3] = colors[color_idx][3]; vi++; } } VkDeviceSize size = sizeof(vertices); /* Staging buffer */ VkBuffer staging; VkDeviceMemory staging_mem; VkBufferCreateInfo bci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size, .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE }; check_vk(vkCreateBuffer(gpu->device, &bci, NULL, &staging), "create staging buffer"); VkMemoryRequirements mem_req; vkGetBufferMemoryRequirements(gpu->device, staging, &mem_req); VkMemoryAllocateInfo mai = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = mem_req.size, .memoryTypeIndex = find_memory_type(gpu->physical_device, mem_req.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) }; check_vk(vkAllocateMemory(gpu->device, &mai, NULL, &staging_mem), "alloc staging memory"); check_vk(vkBindBufferMemory(gpu->device, staging, staging_mem, 0), "bind staging memory"); void *data; vkMapMemory(gpu->device, staging_mem, 0, size, 0, &data); memcpy(data, vertices, size); vkUnmapMemory(gpu->device, staging_mem); /* Device-local buffer */ bci.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; check_vk(vkCreateBuffer(gpu->device, &bci, NULL, &gpu->vertex_buffer), "create vertex buffer"); vkGetBufferMemoryRequirements(gpu->device, gpu->vertex_buffer, &mem_req); mai.allocationSize = mem_req.size; mai.memoryTypeIndex = find_memory_type(gpu->physical_device, mem_req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); check_vk(vkAllocateMemory(gpu->device, &mai, NULL, &gpu->vertex_memory), "alloc vertex memory"); check_vk(vkBindBufferMemory(gpu->device, gpu->vertex_buffer, gpu->vertex_memory, 0), "bind vertex memory"); /* Copy staging -> device */ VkCommandBufferAllocateInfo cbai = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = gpu->command_pool, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 1 }; VkCommandBuffer cb; vkAllocateCommandBuffers(gpu->device, &cbai, &cb); VkCommandBufferBeginInfo bi = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT }; vkBeginCommandBuffer(cb, &bi); VkBufferCopy copy = { .size = size }; vkCmdCopyBuffer(cb, staging, gpu->vertex_buffer, 1, ©); vkEndCommandBuffer(cb); VkSubmitInfo si = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cb }; vkQueueSubmit(gpu->graphics_queue, 1, &si, VK_NULL_HANDLE); vkQueueWaitIdle(gpu->graphics_queue); vkFreeCommandBuffers(gpu->device, gpu->command_pool, 1, &cb); vkDestroyBuffer(gpu->device, staging, NULL); vkFreeMemory(gpu->device, staging_mem, NULL); } /* ─── Command Pool & Sync ───────────────────────────────────────────── */ static void create_command_pool(RRTGPU *gpu) { VkCommandPoolCreateInfo cpci = { .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, .queueFamilyIndex = gpu->graphics_family }; check_vk(vkCreateCommandPool(gpu->device, &cpci, NULL, &gpu->command_pool), "create command pool"); } static void create_sync_objects(RRTGPU *gpu) { VkSemaphoreCreateInfo sci = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; VkFenceCreateInfo fci = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .flags = VK_FENCE_CREATE_SIGNALED_BIT }; for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { check_vk(vkCreateSemaphore(gpu->device, &sci, NULL, &gpu->acquire_semaphores[i]), "create acquire semaphore"); check_vk(vkCreateSemaphore(gpu->device, &sci, NULL, &gpu->render_finished_semaphores[i]), "create render semaphore"); check_vk(vkCreateFence(gpu->device, &fci, NULL, &gpu->in_flight_fences[i]), "create fence"); } } static void create_command_buffers(RRTGPU *gpu) { VkCommandBufferAllocateInfo cbai = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = gpu->command_pool, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = MAX_FRAMES_IN_FLIGHT }; check_vk(vkAllocateCommandBuffers(gpu->device, &cbai, gpu->command_buffers), "allocate command buffers"); } /* ─── Record Command Buffer ─────────────────────────────────────────── */ static void record_command_buffer(RRTGPU *gpu, VkCommandBuffer cb, uint32_t image_index, RRTDrawState *state) { VkCommandBufferBeginInfo bi = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; check_vk(vkBeginCommandBuffer(cb, &bi), "begin command buffer"); VkRenderPassBeginInfo rpbi = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = gpu->render_pass, .framebuffer = gpu->framebuffers[image_index], .renderArea = { .offset = {0,0}, .extent = gpu->swapchain_extent }, .clearValueCount = 2 }; VkClearValue clear_values[2]; clear_values[0].color.float32[0] = gpu->clear_color[0]; clear_values[0].color.float32[1] = gpu->clear_color[1]; clear_values[0].color.float32[2] = gpu->clear_color[2]; clear_values[0].color.float32[3] = gpu->clear_color[3]; clear_values[1].depthStencil.depth = 1.0f; clear_values[1].depthStencil.stencil = 0; rpbi.pClearValues = clear_values; vkCmdBeginRenderPass(cb, &rpbi, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, gpu->pipeline); VkViewport viewport = { .x = 0, .y = 0, .width = (float)gpu->swapchain_extent.width, .height = (float)gpu->swapchain_extent.height, .minDepth = 0.0f, .maxDepth = 1.0f }; vkCmdSetViewport(cb, 0, 1, &viewport); VkRect2D scissor = { .offset = {0, 0}, .extent = gpu->swapchain_extent }; vkCmdSetScissor(cb, 0, 1, &scissor); VkBuffer vb = gpu->vertex_buffer; VkDeviceSize offset = 0; vkCmdBindVertexBuffers(cb, 0, 1, &vb, &offset); /* Push constants: numerator + denominator */ RRTPushConstants pc; memcpy(pc.numerator, state->numerator, 16 * sizeof(float)); memcpy(pc.denominator, state->denominator, 16 * sizeof(float)); vkCmdPushConstants(cb, gpu->pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), &pc); /* Draw 24 vertices as 12 line segments */ vkCmdDraw(cb, VERTEX_COUNT, 1, 0, 0); vkCmdEndRenderPass(cb); check_vk(vkEndCommandBuffer(cb), "end command buffer"); } /* ─── Recreate Swapchain ────────────────────────────────────────────── */ static void recreate_swapchain(RRTGPU *gpu) { /* Wait for device idle */ vkDeviceWaitIdle(gpu->device); destroy_swapchain(gpu); create_swapchain(gpu); create_depth_resources(gpu); create_render_pass(gpu); create_pipeline(gpu); create_framebuffers(gpu); } /* ─── Render Frame ──────────────────────────────────────────────────── */ static float rrt_gpu_render(RRTGPU *gpu, RRTDrawState *state) { /* Step 1: Compute reduced transform (CPU reference) */ rrt_compute_reduced(state); /* Step 2: Compute residual (independent check) */ float residual = rrt_compute_residual(state); /* Step 3: Acquire frame slot */ vkWaitForFences(gpu->device, 1, &gpu->in_flight_fences[gpu->current_frame], VK_TRUE, UINT64_MAX); uint32_t image_index; VkResult acq = vkAcquireNextImageKHR(gpu->device, gpu->swapchain, UINT64_MAX, gpu->acquire_semaphores[gpu->current_frame], VK_NULL_HANDLE, &image_index); if (acq == VK_ERROR_OUT_OF_DATE_KHR) { recreate_swapchain(gpu); return residual; } else if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { fprintf(stderr, "Failed to acquire swapchain image\n"); exit(1); } vkResetFences(gpu->device, 1, &gpu->in_flight_fences[gpu->current_frame]); /* Reset and record command buffer */ vkResetCommandBuffer(gpu->command_buffers[gpu->current_frame], 0); record_command_buffer(gpu, gpu->command_buffers[gpu->current_frame], image_index, state); /* Step 4: Submit */ VkSemaphore wait_sem = gpu->acquire_semaphores[gpu->current_frame]; VkSemaphore signal_sem = gpu->render_finished_semaphores[gpu->current_frame]; VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; VkSubmitInfo si = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .waitSemaphoreCount = 1, .pWaitSemaphores = &wait_sem, .pWaitDstStageMask = &wait_stage, .commandBufferCount = 1, .pCommandBuffers = &gpu->command_buffers[gpu->current_frame], .signalSemaphoreCount = 1, .pSignalSemaphores = &signal_sem }; check_vk(vkQueueSubmit(gpu->graphics_queue, 1, &si, gpu->in_flight_fences[gpu->current_frame]), "queue submit"); /* Step 5: Present */ VkPresentInfoKHR pi = { .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &signal_sem, .swapchainCount = 1, .pSwapchains = &gpu->swapchain, .pImageIndices = &image_index }; VkResult pres = vkQueuePresentKHR(gpu->present_queue, &pi); if (pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || gpu->framebuffer_resized) { gpu->framebuffer_resized = false; recreate_swapchain(gpu); } else if (pres != VK_SUCCESS) { fprintf(stderr, "Failed to present\n"); exit(1); } gpu->current_frame = (gpu->current_frame + 1) % MAX_FRAMES_IN_FLIGHT; return residual; } /* ─── Creation / Destruction ────────────────────────────────────────── */ static RRTGPU *rrt_gpu_create(SDL_Window *window) { RRTGPU *gpu = calloc(1, sizeof(RRTGPU)); gpu->window = window; gpu->clear_color[0] = 0.05f; gpu->clear_color[1] = 0.05f; gpu->clear_color[2] = 0.1f; gpu->clear_color[3] = 1.0f; /* Instance */ uint32_t ext_count = 0; SDL_Vulkan_GetInstanceExtensions(window, &ext_count, NULL); const char **extensions = malloc(ext_count * sizeof(const char *)); SDL_Vulkan_GetInstanceExtensions(window, &ext_count, extensions); VkApplicationInfo app_info = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "RRT-GPU Demo", .applicationVersion = VK_MAKE_VERSION(0, 1, 0), .pEngineName = "RRT-GPU", .engineVersion = VK_MAKE_VERSION(0, 1, 0), .apiVersion = VK_API_VERSION_1_0 }; VkInstanceCreateInfo ici = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app_info, .enabledExtensionCount = ext_count, .ppEnabledExtensionNames = extensions }; check_vk(vkCreateInstance(&ici, NULL, &gpu->instance), "create instance"); free(extensions); /* Surface */ if (!SDL_Vulkan_CreateSurface(window, gpu->instance, &gpu->surface)) { fprintf(stderr, "Failed to create Vulkan surface: %s\n", SDL_GetError()); exit(1); } /* Physical device */ uint32_t dev_count = 0; vkEnumeratePhysicalDevices(gpu->instance, &dev_count, NULL); if (dev_count == 0) { fprintf(stderr, "No Vulkan-capable GPU found\n"); exit(1); } VkPhysicalDevice *devices = malloc(dev_count * sizeof(VkPhysicalDevice)); vkEnumeratePhysicalDevices(gpu->instance, &dev_count, devices); bool found = false; for (uint32_t i = 0; i < dev_count; i++) { if (is_device_suitable(devices[i], gpu->surface, &gpu->graphics_family, &gpu->present_family)) { gpu->physical_device = devices[i]; found = true; break; } } free(devices); if (!found) { fprintf(stderr, "No suitable GPU found\n"); exit(1); } /* Logical device */ float queue_priority = 1.0f; VkDeviceQueueCreateInfo queue_cis[2]; int qci_count = 1; queue_cis[0] = (VkDeviceQueueCreateInfo){ .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .queueFamilyIndex = gpu->graphics_family, .queueCount = 1, .pQueuePriorities = &queue_priority }; if (gpu->graphics_family != gpu->present_family) { qci_count = 2; queue_cis[1] = (VkDeviceQueueCreateInfo){ .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .queueFamilyIndex = gpu->present_family, .queueCount = 1, .pQueuePriorities = &queue_priority }; } const char *device_exts[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; VkDeviceCreateInfo dci = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .queueCreateInfoCount = qci_count, .pQueueCreateInfos = queue_cis, .enabledExtensionCount = 1, .ppEnabledExtensionNames = device_exts }; check_vk(vkCreateDevice(gpu->physical_device, &dci, NULL, &gpu->device), "create device"); vkGetDeviceQueue(gpu->device, gpu->graphics_family, 0, &gpu->graphics_queue); vkGetDeviceQueue(gpu->device, gpu->present_family, 0, &gpu->present_queue); /* Create everything else */ create_command_pool(gpu); create_swapchain(gpu); create_depth_resources(gpu); create_render_pass(gpu); create_pipeline(gpu); create_framebuffers(gpu); create_vertex_buffer(gpu); create_command_buffers(gpu); create_sync_objects(gpu); /* Initialize RRT state */ memset(&gpu->rrt_state, 0, sizeof(RRTDrawState)); gpu->rrt_state.certificate_order = 1; return gpu; } static void rrt_gpu_destroy(RRTGPU *gpu) { if (!gpu) return; vkDeviceWaitIdle(gpu->device); /* Swapchain resources */ destroy_swapchain(gpu); /* Vertex buffer */ if (gpu->vertex_buffer) { vkDestroyBuffer(gpu->device, gpu->vertex_buffer, NULL); gpu->vertex_buffer = VK_NULL_HANDLE; } if (gpu->vertex_memory) { vkFreeMemory(gpu->device, gpu->vertex_memory, NULL); gpu->vertex_memory = VK_NULL_HANDLE; } /* Frame sync */ for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { if (gpu->acquire_semaphores[i]) vkDestroySemaphore(gpu->device, gpu->acquire_semaphores[i], NULL); if (gpu->render_finished_semaphores[i]) vkDestroySemaphore(gpu->device, gpu->render_finished_semaphores[i], NULL); if (gpu->in_flight_fences[i]) vkDestroyFence(gpu->device, gpu->in_flight_fences[i], NULL); } /* Command pool */ if (gpu->command_pool) { vkDestroyCommandPool(gpu->device, gpu->command_pool, NULL); gpu->command_pool = VK_NULL_HANDLE; } /* Pipeline layout */ if (gpu->pipeline_layout) { vkDestroyPipelineLayout(gpu->device, gpu->pipeline_layout, NULL); gpu->pipeline_layout = VK_NULL_HANDLE; } /* Pipeline */ if (gpu->pipeline) { vkDestroyPipeline(gpu->device, gpu->pipeline, NULL); gpu->pipeline = VK_NULL_HANDLE; } /* Render pass */ if (gpu->render_pass) { vkDestroyRenderPass(gpu->device, gpu->render_pass, NULL); gpu->render_pass = VK_NULL_HANDLE; } /* Logical device */ if (gpu->device) { vkDestroyDevice(gpu->device, NULL); gpu->device = VK_NULL_HANDLE; } /* Surface */ if (gpu->surface) { vkDestroySurfaceKHR(gpu->instance, gpu->surface, NULL); gpu->surface = VK_NULL_HANDLE; } /* Instance */ if (gpu->instance) { vkDestroyInstance(gpu->instance, NULL); gpu->instance = VK_NULL_HANDLE; } free(gpu); } /* ─── Main ──────────────────────────────────────────────────────────── */ int main(int argc, char *argv[]) { (void)argc; (void)argv; if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); return 1; } SDL_Window *window = SDL_CreateWindow( "RRT-GPU: Rotating Wireframe Box", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE ); if (!window) { fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError()); SDL_Quit(); return 1; } RRTGPU *gpu = rrt_gpu_create(window); /* Animation state */ Uint64 last_time = SDL_GetPerformanceCounter(); float angle = 0.0f; bool running = true; SDL_Event event; /* Camera setup */ float view[16], proj[16]; mat4_look_at(view, 0, 0, 5, 0, 0, 0, 0, 1, 0); printf("RRT-GPU Demo running. Press ESC to quit, R to print RRT state.\n"); printf("Residual will be printed to console each second.\n"); Uint64 last_print = SDL_GetPerformanceCounter(); float accumulated_residual = 0.0f; int frame_count = 0; while (running) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) running = false; if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.key.keysym.sym == SDLK_r) { printf("RRT State:\n"); printf(" numerator (model): rotation %.2f rad\n", angle); printf(" residual: %.6e\n", gpu->rrt_state.residual); printf(" certificate: %u\n", gpu->rrt_state.certificate_order); } } if (event.type == SDL_WINDOWEVENT) { if (event.window.event == SDL_WINDOWEVENT_RESIZED) { gpu->framebuffer_resized = true; } } } /* Update animation */ Uint64 now = SDL_GetPerformanceCounter(); float dt = (float)(now - last_time) / (float)SDL_GetPerformanceFrequency(); last_time = now; angle += dt * 1.0f; /* 1 rad/sec */ /* Update projection with current aspect ratio */ float aspect = (float)gpu->swapchain_extent.width / (float)gpu->swapchain_extent.height; mat4_perspective(proj, 1.0472f, aspect, 0.1f, 100.0f); /* View * Projection = denominator */ float view_proj[16]; mat4_mul(proj, view, view_proj); /* view * proj */ /* Model = numerator (rotation around Y) */ float model[16]; mat4_rotate_y(model, angle); /* Update RRT state */ memcpy(gpu->rrt_state.numerator, model, 16 * sizeof(float)); memcpy(gpu->rrt_state.denominator, view_proj, 16 * sizeof(float)); /* Render */ float residual = rrt_gpu_render(gpu, &gpu->rrt_state); accumulated_residual += residual; frame_count++; /* Print stats every second */ if ((float)(now - last_print) / (float)SDL_GetPerformanceFrequency() >= 1.0f) { printf("FPS: %d | Avg residual: %.3e | Cert: %u\n", frame_count, accumulated_residual / frame_count, gpu->rrt_state.certificate_order); frame_count = 0; accumulated_residual = 0.0f; last_print = now; } } rrt_gpu_destroy(gpu); SDL_DestroyWindow(window); SDL_Quit(); return 0; }