GUI image implementation, player hotbar

This commit is contained in:
2026-09-20 22:31:46 +02:00
parent ff72311979
commit c3fa7115c8
6 changed files with 423 additions and 136 deletions

View File

@@ -1,3 +1,4 @@
import "includes/math";
import "includes/structs";
struct Varyings {
@@ -48,6 +49,6 @@ Varyings vertexMain(uint vertexID : SV_VulkanVertexID, uint instanceID : SV_Vulk
[shader("fragment")]
float4 fragmentMain(Varyings frag) : SV_Target {
let image = _Images[frag.instance];
let texel = _Textures[image.texture].Sample(_Sampler, frag.texCoord);
let texel = texture2DAA(_Textures[image.texture], _Sampler, frag.texCoord);
return texel * image.tint;
}

View File

@@ -713,6 +713,28 @@ pub fn init() !Game {
},
},
},
.{
.dst_set = gui.image_descriptor_set,
.dst_binding = 0,
.dst_array_element = 0,
.descriptor_type = .uniform_buffer,
.descriptor_infos = .{
.buffer = &.{
.{
.buffer = global_uniforms.buffer,
.offset = 0,
.range = vk.WHOLE_SIZE,
},
},
},
},
.{
.dst_set = gui.image_descriptor_set,
.dst_binding = 3,
.dst_array_element = 0,
.descriptor_type = .sampled_image,
.descriptor_infos = .{ .image = descriptor_images },
},
},
});
@@ -782,74 +804,7 @@ pub fn deinit(self: *Game) void {
}
pub fn update(self: *Game, dt: f32) void {
const swapchain = ctx.swapchain;
const gui = ctx.gui;
self.player.update(dt, &self.chunks);
const extent = swapchain.extent;
const framebuffer_size = vm.Vector2.init(
@floatFromInt(extent.width),
@floatFromInt(extent.height),
);
const crosshair_half_extent_px = 8;
const crosshair_half_width_px = 1;
gui.pushBox(.{
.background_color = .init(1, 1, 1, 0.5),
.border_color = .init(0, 0, 0, 1),
.position_sspx = framebuffer_size.mulScalar(0.5).add(.init(-crosshair_half_extent_px, -crosshair_half_width_px)),
.size_px = .init(2.0 * crosshair_half_extent_px, 2.0 * crosshair_half_width_px),
.border_width_px = 0,
.border_radius_px = 0,
});
gui.pushBox(.{
.background_color = .init(1, 1, 1, 0.5),
.border_color = .init(0, 0, 0, 1),
.position_sspx = framebuffer_size.mulScalar(0.5).add(.init(-crosshair_half_width_px, -crosshair_half_extent_px)),
.size_px = .init(2.0 * crosshair_half_width_px, 2.0 * crosshair_half_extent_px),
.border_width_px = 0,
.border_radius_px = 0,
});
{
const margin: f16 = 8;
const font_size: f32 = 16;
const player_position_sv = self.player.position_sv;
gui.pushBox(.{
.background_color = .init(0, 0, 0, 0.75),
.border_color = .init(0, 0, 0, 1),
.position_sspx = .init(0, 0),
.size_px = .init(157, 4 * margin + 3 * font_size),
.border_width_px = 0,
.border_radius_px = 0,
});
gui.printLine("X {X:0>8}", .{@as(u32, @bitCast(player_position_sv.x))}, .{
.position_sspx = .init(margin, margin + font_size),
.font_id = self.font,
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
gui.printLine("Y {X:0>8}", .{@as(u32, @bitCast(player_position_sv.y))}, .{
.position_sspx = .init(margin, 2 * (margin + font_size)),
.font_id = self.font,
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
gui.printLine("Z {X:0>8}", .{@as(u32, @bitCast(player_position_sv.z))}, .{
.position_sspx = .init(margin, 3 * (margin + font_size)),
.font_id = self.font,
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
}
self.player.update(dt, self);
self.render() catch |err| {
std.log.err("Failed to render: {s}", .{@errorName(err)});

View File

@@ -2,6 +2,7 @@ const Player = @This();
const std = @import("std");
const c = @import("const.zig");
const ctx = @import("AppContext.zig");
const glfw = @import("zglfw");
const math = @import("math.zig");
const vm = @import("vecmath");
@@ -231,7 +232,6 @@ pub fn onKeyDown(self: *Player, key: glfw.Key) void {
const key_code = @intFromEnum(key);
if (key_code >= @intFromEnum(glfw.Key.one) and key_code <= @intFromEnum(glfw.Key.nine)) {
self.block_index = @intCast(key_code - @intFromEnum(glfw.Key.one));
std.log.info("Picked block {s}", .{blocks[self.block_index]});
}
}
@@ -281,7 +281,11 @@ pub fn onMouseDown(self: *Player, button: glfw.MouseButton, game: *Game) void {
}
}
pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
pub fn update(self: *Player, dt: f32, game: *Game) void {
const swapchain = ctx.swapchain;
const materials = ctx.materials;
const gui = ctx.gui;
defer self.resetAllButtons();
const raycast_origin_sv = self.position_sv
@@ -294,7 +298,7 @@ pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
))
.round()
.asInt();
self.maybe_raycast_hit = chunks.raycast(raycast_origin_sv, raycast_ray_sv);
self.maybe_raycast_hit = game.chunks.raycast(raycast_origin_sv, raycast_ray_sv);
// --- GATHER INPUTS -------------------------------------------------------
@@ -343,7 +347,7 @@ pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
var max_sv = position_sv.add(.init(collision_half_width_sv, collision_half_width_sv, collision_height_sv));
if (vertical_displacement_sv > 0) {
if (chunks.sweepCastUp(min_sv, max_sv, vertical_displacement_sv)) |hit| {
if (game.chunks.sweepCastUp(min_sv, max_sv, vertical_displacement_sv)) |hit| {
vertical_displacement_sv -= hit.projected_distance_sv;
}
position_sv = .add(position_sv, .init(0, 0, vertical_displacement_sv));
@@ -353,7 +357,7 @@ pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
var i: usize = 0;
while (i < 2) : (i += 1) {
if (chunks.sweepCastHorizontal(min_sv, max_sv, horizontal_displacement_sv)) |hit| {
if (game.chunks.sweepCastHorizontal(min_sv, max_sv, horizontal_displacement_sv)) |hit| {
const adjustment = math.mulFrac2(hit.normal_frac.dropZ(), hit.projected_distance_sv);
horizontal_displacement_sv = .add(
horizontal_displacement_sv,
@@ -368,7 +372,7 @@ pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
if (vertical_displacement_sv < 0.0) {
min_sv = .add(min_sv, horizontal_displacement_sv.withZ(0));
max_sv = .add(max_sv, horizontal_displacement_sv.withZ(0));
if (chunks.sweepCastDown(min_sv, max_sv, -vertical_displacement_sv)) |hit| {
if (game.chunks.sweepCastDown(min_sv, max_sv, -vertical_displacement_sv)) |hit| {
vertical_displacement_sv += hit.projected_distance_sv;
}
position_sv = .add(position_sv, .init(0, 0, vertical_displacement_sv));
@@ -377,6 +381,131 @@ pub fn update(self: *Player, dt: f32, chunks: *const Chunks) void {
self.position_sv = position_sv;
},
}
// --- GUI -----------------------------------------------------------------
const extent = swapchain.extent;
const framebuffer_size = vm.Vector2.init(
@floatFromInt(extent.width),
@floatFromInt(extent.height),
);
// --- CROSSHAIR ---
{
const crosshair_half_extent_px = 8;
const crosshair_half_width_px = 1;
gui.pushBox(.{
.background_color = .init(1, 1, 1, 0.5),
.border_color = .init(0, 0, 0, 1),
.position_sspx = framebuffer_size.mulScalar(0.5).add(.init(-crosshair_half_extent_px, -crosshair_half_width_px)),
.size_px = .init(2.0 * crosshair_half_extent_px, 2.0 * crosshair_half_width_px),
.border_width_px = 0,
.border_radius_px = 0,
});
gui.pushBox(.{
.background_color = .init(1, 1, 1, 0.5),
.border_color = .init(0, 0, 0, 1),
.position_sspx = framebuffer_size.mulScalar(0.5).add(.init(-crosshair_half_width_px, -crosshair_half_extent_px)),
.size_px = .init(2.0 * crosshair_half_width_px, 2.0 * crosshair_half_extent_px),
.border_width_px = 0,
.border_radius_px = 0,
});
}
// --- COORDINATES ---
{
const margin: f16 = 8;
const font_size: f32 = 16;
gui.pushBox(.{
.background_color = .init(0, 0, 0, 0.75),
.border_color = .init(0, 0, 0, 1),
.position_sspx = .init(0, 0),
.size_px = .init(157, 4 * margin + 3 * font_size),
.border_width_px = 0,
.border_radius_px = 0,
});
gui.printLine("X {X:0>8}", .{@as(u32, @bitCast(self.position_sv.x))}, .{
.position_sspx = .init(margin, margin + font_size),
.font_id = @enumFromInt(0),
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
gui.printLine("Y {X:0>8}", .{@as(u32, @bitCast(self.position_sv.y))}, .{
.position_sspx = .init(margin, 2 * (margin + font_size)),
.font_id = @enumFromInt(0),
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
gui.printLine("Z {X:0>8}", .{@as(u32, @bitCast(self.position_sv.z))}, .{
.position_sspx = .init(margin, 3 * (margin + font_size)),
.font_id = @enumFromInt(0),
.cap_height_px = font_size,
.color = .init(1, 1, 1, 1),
});
}
// --- HOTBAR ---
{
const block_selection_outline_width_px: f32 = 4;
const block_image_size_px: f32 = 48;
const block_image_gap_px: f32 = 8;
const block_image_margin_px: f32 = 8;
const hotbar_width_px: f32 = @as(f32, @floatFromInt(blocks.len)) * block_image_size_px + @as(f32, @floatFromInt(blocks.len - 1)) * block_image_gap_px;
const hotbar_left_px: f32 = 0.5 * (framebuffer_size.x - hotbar_width_px);
const hotbar_top_px: f32 = framebuffer_size.y - block_image_margin_px - block_image_size_px;
gui.pushBox(.{
.background_color = .init(0, 0, 0, 0.75),
.border_color = .init(0, 0, 0, 1),
.position_sspx = .init(hotbar_left_px - block_image_margin_px, hotbar_top_px - block_image_margin_px),
.size_px = .init(hotbar_width_px + 2 * block_image_margin_px, block_image_size_px + 2 * block_image_margin_px),
.border_width_px = 4,
.border_radius_px = 0,
});
var cx: f32 = hotbar_left_px;
for (blocks, 0..) |filename, i| {
defer cx += block_image_size_px + block_image_gap_px;
const id = game.blocks.getOrLoad(filename) catch |err| {
std.log.err("Error while rendering hotbar block {s}: {}", .{ filename, err });
continue;
};
const definition = &game.blocks.array.items[@intFromEnum(id)];
const material_id = definition.walls.positive_z.material;
const material = &materials.array.items[@intFromEnum(material_id)];
if (i == self.block_index) {
gui.pushBox(.{
.background_color = .initScalar(0),
.border_color = .init(1, 1, 1, 1),
.position_sspx = vm.Vector2.init(cx, hotbar_top_px).sub(.initScalar(block_selection_outline_width_px)),
.size_px = .initScalar(block_image_size_px + 2 * block_selection_outline_width_px),
.border_width_px = block_selection_outline_width_px,
.border_radius_px = block_selection_outline_width_px,
});
}
const texture_id = material.base_color_texture;
gui.pushImage(.{
.position_sspx = .init(cx, hotbar_top_px),
.size_px = .initScalar(block_image_size_px),
.texture_id = texture_id,
});
}
}
}
fn resetAllButtons(self: *Player) void {

View File

@@ -33,11 +33,11 @@ pub const Draw = struct {
};
pub const Image = extern struct {
tint: vm.Vector4,
tint: vm.Vector4 = .initScalar(1),
position_sspx: vm.Vector2,
size_px: vm.Vector2,
uv_min: vm.Vector2,
uv_max: vm.Vector2,
uv_min: vm.Vector2 = .initScalar(0),
uv_max: vm.Vector2 = .initScalar(1),
texture_id: Textures.Id,
};
};
@@ -69,9 +69,14 @@ text_descriptor_set_layout: vk.DescriptorSetLayout,
text_pipeline_layout: vk.PipelineLayout,
text_pipeline: vk.Pipeline,
image_descriptor_set_layout: vk.DescriptorSetLayout,
image_pipeline_layout: vk.PipelineLayout,
image_pipeline: vk.Pipeline,
descriptor_pool: vk.DescriptorPool,
box_descriptor_set: vk.DescriptorSet,
text_descriptor_set: vk.DescriptorSet,
image_descriptor_set: vk.DescriptorSet,
pub const max_box_draws = 1024;
pub const max_image_draws = 1024;
@@ -113,7 +118,18 @@ pub fn init() !*Gui {
const box_cpu_buffer: std.ArrayList(Draw.Box) = try .initCapacity(allocator_persistent, max_box_draws);
const text_cpu_buffer: std.ArrayList(Draw.Text) = try .initCapacity(allocator_persistent, max_text_draws);
const image_cpu_buffer: std.ArrayList(Draw.Image) = try .initCapacity(allocator_persistent, max_image_draws);
const batches: std.ArrayList(Batch) = try .initCapacity(allocator_persistent, max_batches);
var index_buffer = try shaders.IndexBuffer.init(.{
.usage = .index,
.target_queue = .graphics,
.array_capacity = 6,
.name = "QuadIB",
});
errdefer index_buffer.deinit();
try index_buffer.write(.{
.elements = &.{ 0, 1, 2, 2, 1, 3 },
});
const sampler = try engine.createSampler(.{
.mag_filter = .linear,
@@ -165,17 +181,6 @@ pub fn init() !*Gui {
defer engine.destroyShaderModule(box_shader);
engine.setObjectName(box_shader, "SM gui_box", .{});
var index_buffer = try shaders.IndexBuffer.init(.{
.usage = .index,
.target_queue = .graphics,
.array_capacity = 6,
.name = "QuadIB",
});
errdefer index_buffer.deinit();
try index_buffer.write(.{
.elements = &.{ 0, 1, 2, 2, 1, 3 },
});
const box_pipeline = try engine.createGraphicsPipeline(.{
.stages = &.{
.{
@@ -429,18 +434,174 @@ pub fn init() !*Gui {
errdefer engine.destroyPipeline(text_pipeline);
engine.setObjectName(text_pipeline, "P GUI Box", .{});
const image_descriptor_set_layout = try engine.createDescriptorSetLayout(.{
.bindings = &.{
.{
.binding = 0,
.descriptor_type = .uniform_buffer,
.descriptor_count = 1,
.stage_flags = .{ .vertex_bit = true, .fragment_bit = true },
},
.{
.binding = 1,
.descriptor_type = .storage_buffer,
.descriptor_count = 1,
.stage_flags = .{ .vertex_bit = true, .fragment_bit = true },
},
.{
.binding = 2,
.descriptor_type = .sampler,
.descriptor_count = 1,
.stage_flags = .{ .vertex_bit = true, .fragment_bit = true },
.immutable_samplers = &.{sampler},
},
.{
.binding = 3,
.descriptor_type = .sampled_image,
.descriptor_count = Textures.max_textures,
.stage_flags = .{ .vertex_bit = true, .fragment_bit = true },
},
},
});
errdefer engine.destroyDescriptorSetLayout(image_descriptor_set_layout);
engine.setObjectName(box_descriptor_set_layout, "DSL GUI Image", .{});
const image_pipeline_layout = try engine.createPipelineLayout(.{
.set_layouts = &.{
image_descriptor_set_layout,
},
});
errdefer engine.destroyPipelineLayout(image_pipeline_layout);
engine.setObjectName(box_pipeline_layout, "PL GUI Image", .{});
const image_shader = try engine.createShaderModule(.{ .code = &shaders.gui_image_spv });
defer engine.destroyShaderModule(image_shader);
engine.setObjectName(text_shader, "SM gui_image", .{});
const image_pipeline = try engine.createGraphicsPipeline(.{
.stages = &.{
.{
.stage = .{ .vertex_bit = true },
.module = image_shader,
.name = "vertexMain",
},
.{
.stage = .{ .fragment_bit = true },
.module = image_shader,
.name = "fragmentMain",
},
},
.vertex_input_state = .{},
.input_assembly_state = .{
.topology = .triangle_list,
.primitive_restart_enable = .false,
},
.viewport_state = .{
.viewports = &.{undefined}, // dynamic
.scissors = &.{undefined}, // dynamic
},
.rasterization_state = .{
.depth_clamp_enable = .false,
.rasterizer_discard_enable = .false,
.polygon_mode = .fill,
.cull_mode = .{},
.front_face = .counter_clockwise,
.depth_bias_enable = .false,
.depth_bias_constant_factor = 0,
.depth_bias_clamp = 0,
.depth_bias_slope_factor = 0,
.line_width = 1,
},
.multisample_state = .{
.rasterization_samples = .{ .@"1_bit" = true },
.sample_shading_enable = .false,
.min_sample_shading = 1,
.alpha_to_coverage_enable = .false,
.alpha_to_one_enable = .false,
},
.depth_stencil_state = .{
.depth_test_enable = .false,
.depth_write_enable = .false,
.depth_compare_op = .always,
.depth_bounds_test_enable = .false,
.stencil_test_enable = .false,
.front = .{
.fail_op = .keep,
.pass_op = .keep,
.depth_fail_op = .keep,
.compare_op = .never,
.compare_mask = 0,
.write_mask = 0,
.reference = 0,
},
.back = .{
.fail_op = .keep,
.pass_op = .keep,
.depth_fail_op = .keep,
.compare_op = .never,
.compare_mask = 0,
.write_mask = 0,
.reference = 0,
},
.min_depth_bounds = 0,
.max_depth_bounds = 1,
},
.color_blend_state = .{
.logic_op_enable = .false,
.logic_op = .copy,
.attachments = &.{
.{
.blend_enable = .true,
.src_color_blend_factor = .one,
.dst_color_blend_factor = .one_minus_src_alpha,
.color_blend_op = .add,
.src_alpha_blend_factor = .one,
.dst_alpha_blend_factor = .one_minus_src_alpha,
.alpha_blend_op = .add,
.color_write_mask = .{
.r_bit = true,
.g_bit = true,
.b_bit = true,
.a_bit = true,
},
},
},
.blend_constants = .{ 0, 0, 0, 0 },
},
.dynamic_state = .{
.dynamic_states = &.{ .viewport, .scissor },
},
.layout = image_pipeline_layout,
.view_mask = 0,
.color_attachment_formats = &.{swapchain.params.surface_format.format},
.depth_attachment_format = Texture.Usage.depth.vkFormat(),
.stencil_attachment_format = .undefined,
});
errdefer engine.destroyPipeline(image_pipeline);
engine.setObjectName(image_pipeline, "P GUI Image", .{});
const descriptor_pool = try engine.createDescriptorPool(.{
.max_sets = 2,
.max_sets = 3,
.pool_sizes = &.{
.{
.type = .uniform_buffer,
.descriptor_count = 1 + // box
1, // text
1 + // text
1, // image
},
.{
.type = .storage_buffer,
.descriptor_count = 1 + // box
(1 + 3 * Fonts.max_fonts), // text
(1 + 3 * Fonts.max_fonts) + // text
1, // image
},
.{
.type = .sampled_image,
.descriptor_count = Textures.max_textures, // image
},
.{
.type = .sampler,
.descriptor_count = 1, // image
},
},
});
@@ -459,6 +620,12 @@ pub fn init() !*Gui {
});
engine.setObjectName(text_descriptor_set, "DS GUI Text", .{});
const image_descriptor_set = try engine.allocateDescriptorSet(.{
.descriptor_pool = descriptor_pool,
.set_layout = image_descriptor_set_layout,
});
engine.setObjectName(image_descriptor_set, "DS GUI Image", .{});
try engine.updateDescriptorSets(.{
.writes = &.{
.{
@@ -491,6 +658,21 @@ pub fn init() !*Gui {
},
},
},
.{
.dst_set = image_descriptor_set,
.dst_binding = 1,
.dst_array_element = 0,
.descriptor_type = .storage_buffer,
.descriptor_infos = .{
.buffer = &.{
.{
.buffer = image_gpu_buffer.buffer,
.offset = 0,
.range = vk.WHOLE_SIZE,
},
},
},
},
},
});
@@ -516,9 +698,14 @@ pub fn init() !*Gui {
.text_pipeline_layout = text_pipeline_layout,
.text_pipeline = text_pipeline,
.image_descriptor_set_layout = image_descriptor_set_layout,
.image_pipeline_layout = image_pipeline_layout,
.image_pipeline = image_pipeline,
.descriptor_pool = descriptor_pool,
.box_descriptor_set = box_descriptor_set,
.text_descriptor_set = text_descriptor_set,
.image_descriptor_set = image_descriptor_set,
};
return gui;
@@ -530,11 +717,14 @@ pub fn deinit(self: *Gui) void {
std.log.scoped(.deinit).debug("Deinitializing {*}", .{self});
engine.destroyDescriptorPool(self.descriptor_pool);
engine.destroyPipeline(self.image_pipeline);
engine.destroyPipeline(self.text_pipeline);
engine.destroyPipeline(self.box_pipeline);
self.index_buffer.deinit();
engine.destroyPipelineLayout(self.image_pipeline_layout);
engine.destroyPipelineLayout(self.text_pipeline_layout);
engine.destroyPipelineLayout(self.box_pipeline_layout);
engine.destroyDescriptorSetLayout(self.image_descriptor_set_layout);
engine.destroyDescriptorSetLayout(self.text_descriptor_set_layout);
engine.destroyDescriptorSetLayout(self.box_descriptor_set_layout);
engine.destroySampler(self.sampler);
@@ -667,8 +857,8 @@ pub fn draw(self: *const Gui, command_buffer: CommandBuffer) !void {
command_buffer.bindDescriptorSet(.graphics, self.text_pipeline_layout, 0, self.text_descriptor_set, null);
},
.Image => {
std.log.warn("GUI Image not implemented; skipping batch", .{});
continue;
command_buffer.bindPipeline(.graphics, self.image_pipeline);
command_buffer.bindDescriptorSet(.graphics, self.image_pipeline_layout, 0, self.image_descriptor_set, null);
},
}

View File

@@ -60,11 +60,14 @@ pub const Key = struct {
/// Maps a key value to a material ID. Preallocated with `allocator_persistent`.
map: std.AutoHashMapUnmanaged(Key, Id),
/// Stores all material data and maps a material ID to its data. Preallocated
/// with `allocator_persistent`.
///
/// Stores the same data as `material_buffer`, but is available on the CPU.
array: std.ArrayList(shaders.Material),
/// Stores all material data in a single contiguous storage buffer. Use the
/// material ID as an index into this buffer.
material_buffer: shaders.MaterialBuffer,
/// The amount of materials currently loaded.
material_count: usize,
/// With `@sizeOf(Material) == 52` and `max_materials == 4096`, the material
/// storage buffer should take 208 kiB in VRAM.
@@ -77,11 +80,12 @@ pub fn init() !*Materials {
materials.* = .{
.map = .empty,
.array = .empty,
.material_buffer = undefined,
.material_count = 0,
};
try materials.map.ensureTotalCapacity(allocator_persistent, max_materials);
try materials.array.ensureTotalCapacityPrecise(allocator_persistent, max_materials);
materials.material_buffer = try .init(.{
.usage = .storage,
@@ -93,27 +97,30 @@ pub fn init() !*Materials {
// VOLATILE Synchronize with explicit values on top of `Id` type.
const material_data = [_]shaders.Material{
.{
.base_color = .zero,
.emissive = .init(1, 0, 1),
.ior = 1.45,
.metallic = 0,
.normal_scale = 1,
.occlusion_texture_strength = 1,
.roughness = 1,
.base_color_texture = .empty_base_color,
.emissive_texture = .empty_emissive,
.normal_texture = .empty_normal,
.occlusion_roughness_metallic_texture = .empty_occlusion_roughness_metallic,
},
};
materials.array.appendSliceAssumeCapacity(&material_data);
try materials.material_buffer.write(.{
.element_offset = Id.empty.toInt(),
.elements = &.{
.{
.base_color = .zero,
.emissive = .init(1, 0, 1),
.ior = 1.45,
.metallic = 0,
.normal_scale = 1,
.occlusion_texture_strength = 1,
.roughness = 1,
.base_color_texture = .empty_base_color,
.emissive_texture = .empty_emissive,
.normal_texture = .empty_normal,
.occlusion_roughness_metallic_texture = .empty_occlusion_roughness_metallic,
},
},
.elements = &material_data,
});
materials.material_count += 1;
std.debug.assert(materials.material_count == @typeInfo(Id).@"enum".fields.len);
std.debug.assert(materials.array.items.len == @typeInfo(Id).@"enum".fields.len);
return materials;
}
@@ -176,13 +183,13 @@ pub fn getOrLoad(self: *Materials, maybe_filename: ?[]const u8) !Id {
if (self.map.get(key)) |id| {
return id;
} else {
const id = Id.fromIndexSafe(self.material_count) catch |err| switch (err) {
const id = Id.fromIndexSafe(self.array.items.len) catch |err| switch (err) {
error.Overflow => return error.OutOfMaterials,
};
try self.loadMaterial(filename, id.toInt());
const material = try self.loadMaterial(filename, id.toInt());
self.map.putAssumeCapacityNoClobber(key, id);
self.material_count += 1;
self.array.appendAssumeCapacity(material);
return id;
}
@@ -214,13 +221,13 @@ pub fn getOrLoadAtom(self: *Materials, filename: Atom) !Id {
if (self.map.get(key)) |id| {
return id;
} else {
const id = Id.fromIndexSafe(self.material_count) catch |err| switch (err) {
const id = Id.fromIndexSafe(self.array.items.len) catch |err| switch (err) {
error.Overflow => return error.OutOfMaterials,
};
try self.loadMaterial(filename.toString(), id.toInt());
const material = try self.loadMaterial(filename.toString(), id.toInt());
self.map.putAssumeCapacityNoClobber(key, id);
self.material_count += 1;
self.array.appendAssumeCapacity(material);
return id;
}
@@ -266,7 +273,7 @@ pub fn loadAll(self: *Materials) void {
}
}
fn loadMaterial(self: *Materials, filename: []const u8, index: u32) !void {
fn loadMaterial(self: *Materials, filename: []const u8, index: u32) !shaders.Material {
const allocator_frame = ctx.allocator_frame;
const io = ctx.io;
const textures = ctx.textures;
@@ -307,22 +314,26 @@ fn loadMaterial(self: *Materials, filename: []const u8, index: u32) !void {
.allocate = .alloc_if_needed,
});
const material_data = [_]shaders.Material{
.{
.base_color = .initArray(material_json.baseColor),
.emissive = .initArray(material_json.emissive),
.ior = material_json.ior,
.metallic = material_json.metallic,
.normal_scale = material_json.normalScale,
.occlusion_texture_strength = material_json.occlusionTextureStrength,
.roughness = material_json.roughness,
.base_color_texture = try textures.getOrLoad(material_json.baseColorTexture, .base_color),
.emissive_texture = try textures.getOrLoad(material_json.emissiveTexture, .emissive),
.normal_texture = try textures.getOrLoad(material_json.normalTexture, .normal),
.occlusion_roughness_metallic_texture = try textures.getOrLoad(material_json.occlusionRoughnessMetallicTexture, .occlusion_roughness_metallic),
},
};
try self.material_buffer.write(.{
.element_offset = index,
.elements = &.{
.{
.base_color = .initArray(material_json.baseColor),
.emissive = .initArray(material_json.emissive),
.ior = material_json.ior,
.metallic = material_json.metallic,
.normal_scale = material_json.normalScale,
.occlusion_texture_strength = material_json.occlusionTextureStrength,
.roughness = material_json.roughness,
.base_color_texture = try textures.getOrLoad(material_json.baseColorTexture, .base_color),
.emissive_texture = try textures.getOrLoad(material_json.emissiveTexture, .emissive),
.normal_texture = try textures.getOrLoad(material_json.normalTexture, .normal),
.occlusion_roughness_metallic_texture = try textures.getOrLoad(material_json.occlusionRoughnessMetallicTexture, .occlusion_roughness_metallic),
},
},
.elements = &material_data,
});
return material_data[0];
}

View File

@@ -111,5 +111,6 @@ pub const GlyphData = extern struct {
pub const equirect_to_cube_spv align(4) = @embedFile("shaders/equirect_to_cube").*;
pub const gui_box_spv align(4) = @embedFile("shaders/gui_box").*;
pub const gui_text_spv align(4) = @embedFile("shaders/gui_text").*;
pub const gui_image_spv align(4) = @embedFile("shaders/gui_image").*;
pub const main_spv align(4) = @embedFile("shaders/main").*;
pub const skybox_spv align(4) = @embedFile("shaders/skybox").*;