Compare commits

6 Commits
Author SHA1 Message Date
Riyyi 163aa3052b Add basic reflection to wgpu struct and vertex attributes 2026-10-26 22:06:30 +01:00
Riyyi 426504c748 Add obj model loading and suzanne test model 2026-10-26 15:14:04 +01:00
Riyyi 30de42caca Add texture sampling 2026-10-17 12:55:59 +02:00
Riyyi 31005e0861 Add depth buffer 2026-10-14 23:10:33 +02:00
Riyyi d12118e80a Add camera uniform 2026-10-13 22:03:18 +02:00
Riyyi 8b30fa4e7c Basic vertex and index buffer 2026-10-12 18:59:50 +02:00
6 changed files with 2887 additions and 33 deletions
+2027
View File
File diff suppressed because it is too large Load Diff
+148
View File
@@ -0,0 +1,148 @@
package core
import "core:fmt"
import "core:math/linalg"
import "core:os"
import "core:strconv"
import "core:strings"
import "sindri:platform"
// Minimal OBJ loader: reads v, vt, vn and triangulates convex polygon faces.
// Produces one GPU vertex per face corner, then centers and normalizes the
// model so it fits roughly inside a [-1, 1] cube at the origin
load_obj_model :: proc(
path: string,
) -> (
vertices: []platform.Vertex,
indices: []u16,
ok: bool,
) {
data, err := os.read_entire_file_from_path(path, context.allocator)
if err != os.ERROR_NONE {
fmt.eprintfln("[core] failed to read model: %s", path)
return nil, nil, false
}
defer delete(data)
positions: [dynamic]platform.Vec3
uvs: [dynamic]platform.Vec2
normals: [dynamic]platform.Vec3
temp_vertices: [dynamic]platform.Vertex
temp_indices: [dynamic]u16
defer {
delete(positions)
delete(uvs)
delete(normals)
delete(temp_vertices)
delete(temp_indices)
}
text := string(data)
for line in strings.split_lines_iterator(&text) {
trimmed := strings.trim_space(line)
if len(trimmed) == 0 || trimmed[0] == '#' do continue
fields := strings.fields(trimmed)
defer delete(fields)
if len(fields) == 0 do continue
switch fields[0] {
case "v":
if len(fields) < 4 do continue
x, _ := strconv.parse_f32(fields[1])
y, _ := strconv.parse_f32(fields[2])
z, _ := strconv.parse_f32(fields[3])
append(&positions, platform.Vec3{x, y, z})
case "vt":
if len(fields) < 3 do continue
u, _ := strconv.parse_f32(fields[1])
v, _ := strconv.parse_f32(fields[2])
append(&uvs, platform.Vec2{u, v})
case "vn":
if len(fields) < 4 do continue
x, _ := strconv.parse_f32(fields[1])
y, _ := strconv.parse_f32(fields[2])
z, _ := strconv.parse_f32(fields[3])
append(&normals, platform.Vec3{x, y, z})
case "f":
face_indices: [dynamic]u16
defer delete(face_indices)
for i := 1; i < len(fields); i += 1 {
token := fields[i]
slash := strings.index_byte(token, '/')
vi_str := token
vti_str := ""
if slash != -1 {
vi_str = token[:slash]
slash2 := strings.index_byte(token[slash + 1:], '/')
if slash2 != -1 {
vti_str = token[slash + 1:slash + 1 + slash2]
} else {
vti_str = token[slash + 1:]
}
}
vi, _ := strconv.parse_int(vi_str)
vi -= 1 // OBJ indices are 1-based
if vi < 0 || vi >= len(positions) do continue
uv := platform.Vec2{0, 0}
if len(vti_str) > 0 {
vti, _ := strconv.parse_int(vti_str)
vti -= 1
if vti >= 0 && vti < len(uvs) {
uv = uvs[vti]
}
} else if vi < len(uvs) {
uv = uvs[vi]
}
append(
&temp_vertices,
platform.Vertex {
pos = positions[vi],
col = {1, 1, 1},
uv = uv,
},
)
append(&face_indices, cast(u16)(len(temp_vertices) - 1))
}
// Triangulate convex polygon by fanning from the first vertex
for i := 2; i < len(face_indices); i += 1 {
append(&temp_indices, face_indices[0])
append(&temp_indices, face_indices[i - 1])
append(&temp_indices, face_indices[i])
}
}
}
if len(temp_vertices) == 0 {
return nil, nil, false
}
// Center and normalize: fit the model inside a roughly [-1, 1] cube
min_p := temp_vertices[0].pos
max_p := temp_vertices[0].pos
for v in temp_vertices {
min_p = linalg.min(min_p, v.pos)
max_p = linalg.max(max_p, v.pos)
}
center := (min_p + max_p) * 0.5
size := max_p - min_p
max_size := max(size.x, size.y, size.z)
scale := 1.8 / max_size
for &v in temp_vertices {
v.pos = (v.pos - center) * scale
}
vertices = make([]platform.Vertex, len(temp_vertices))
indices = make([]u16, len(temp_indices))
copy(vertices, temp_vertices[:])
copy(indices, temp_indices[:])
return vertices, indices, true
}
+12
View File
@@ -5,6 +5,7 @@ import "core:time"
import "game:game"
import "sindri:base"
import "sindri:core"
import "sindri:platform"
VERSION :: #config(VERSION, "dev")
@@ -41,6 +42,7 @@ main :: proc() {
// Initialize GPU resources
platform.instance_init(settings)
defer platform.instance_destroy()
load_test_model()
api.init_once()
@@ -84,3 +86,13 @@ test :: proc(e: ^base.Key_Press_Event, _: rawptr) -> bool {
fmt.println("main: @@@@@@@@@@@", e)
return true
}
// Load model from disk and upload it
load_test_model :: proc() {
vertices, indices, model_ok := core.load_obj_model("assets/suzanne.obj")
if !model_ok do fmt.panicf("[main] could not load model")
defer delete(vertices)
defer delete(indices)
platform.fill_buffers_with_model(vertices, indices)
}
+1 -3
View File
@@ -21,9 +21,7 @@ OS :: struct {
// Constructor / destructor
os_init :: proc(settings: base.Settings) {
if !glfw.Init() {
panic("[glfw] init failure")
}
assert(cast(bool)glfw.Init(), "[glfw] init failure")
// Set window properties
glfw.WindowHint(glfw.CLIENT_API, glfw.NO_API) // do not create OpenGL context
+410 -17
View File
@@ -2,12 +2,31 @@ package platform
import "base:runtime"
import "core:fmt"
import "core:math"
import "core:math/linalg"
import "core:os"
import "core:slice"
import "wgpu:wgpu"
import "sindri:base"
// -----------------------------------------
// Types
Vec2 :: [2]f32
Vec3 :: [3]f32
Vertex :: struct #align (4) {
pos: Vec3,
col: Vec3,
uv: Vec2, // texture coordinate
}
Camera_Uniform :: struct {
mvp: linalg.Matrix4f32,
}
// -----------------------------------------
// Variables
@@ -28,6 +47,21 @@ state: struct {
// ----------------------------------------
capabilities: wgpu.SurfaceCapabilities,
vsync: bool,
// ----------------------------------------
depth_texture: wgpu.Texture,
depth_texture_view: wgpu.TextureView,
// ----------------------------------------
uniform_buffer: wgpu.Buffer,
bind_group_layout: wgpu.BindGroupLayout,
bind_group: wgpu.BindGroup,
// ----------------------------------------
vertex_buffer: wgpu.Buffer,
index_buffer: wgpu.Buffer,
index_count: u32,
// ----------------------------------------
diffuse_texture: wgpu.Texture,
diffuse_texture_view: wgpu.TextureView,
diffuse_sampler: wgpu.Sampler,
}
// -----------------------------------------
@@ -64,6 +98,20 @@ instance_init :: proc(settings: base.Settings) {
}
instance_destroy :: proc() {
wgpu.TextureViewRelease(state.depth_texture_view)
wgpu.TextureRelease(state.depth_texture)
wgpu.SamplerRelease(state.diffuse_sampler)
wgpu.TextureViewRelease(state.diffuse_texture_view)
wgpu.TextureRelease(state.diffuse_texture)
wgpu.BufferRelease(state.uniform_buffer)
wgpu.BufferRelease(state.vertex_buffer)
wgpu.BufferRelease(state.index_buffer)
wgpu.BindGroupRelease(state.bind_group)
wgpu.BindGroupLayoutRelease(state.bind_group_layout)
wgpu.RenderPipelineRelease(state.pipeline)
wgpu.PipelineLayoutRelease(state.pipeline_layout)
wgpu.ShaderModuleRelease(state.module)
@@ -94,6 +142,11 @@ resize :: proc "c" () {
state.config.width, state.config.height = os_get_framebuffer_size()
wgpu.SurfaceConfigure(state.surface, &state.config)
create_depth_texture()
// The projection depends on aspect, so rebuild and re-upload the matrix
upload_camera(state.queue, state.uniform_buffer, framebuffer_aspect())
}
frame :: proc "c" () {
@@ -137,18 +190,50 @@ frame :: proc "c" () {
loadOp = .Clear,
storeOp = .Store,
depthSlice = wgpu.DEPTH_SLICE_UNDEFINED,
clearValue = {0, 1, 0, 1},
clearValue = {55 / 255.0, 73 / 255.0, 73 / 255.0, 1},
},
depthStencilAttachment = &wgpu.RenderPassDepthStencilAttachment {
view = state.depth_texture_view,
depthLoadOp = .Clear,
depthStoreOp = .Store,
depthClearValue = 1.0,
},
},
)
wgpu.RenderPassEncoderSetPipeline(render_pass_encoder, state.pipeline)
wgpu.RenderPassEncoderDraw(
// The camera's MVP matrix: group 0
wgpu.RenderPassEncoderSetBindGroup(
render_pass_encoder,
vertexCount = 3,
instanceCount = 1,
firstVertex = 0,
firstInstance = 0,
0,
state.bind_group,
dynamicOffsets = nil, // reuse bind group af different byte offsets, per binding
)
wgpu.RenderPassEncoderSetVertexBuffer(
render_pass_encoder,
slot = 0,
buffer = state.vertex_buffer,
offset = 0, // offset into buffer to start from
size = wgpu.WHOLE_SIZE, // x bytes of the buffer to use
)
wgpu.RenderPassEncoderSetIndexBuffer(
render_pass_encoder,
buffer = state.index_buffer,
format = .Uint16, // type of each element in the buffer
offset = 0, // offset into buffer to start from
size = wgpu.WHOLE_SIZE, // x bytes of the buffer to use
)
wgpu.RenderPassEncoderDrawIndexed(
render_pass_encoder,
state.index_count,
instanceCount = 1, // draw x instance(s) of the mesh
firstIndex = 0, // offset into buffer to start from, useful for drawing sub-mesh
baseVertex = 0, // value added to index before vertex fetch, useful for multi-mesh vertex buffers
firstInstance = 0, // number to start instance index from
)
wgpu.RenderPassEncoderEnd(render_pass_encoder)
@@ -161,6 +246,21 @@ frame :: proc "c" () {
wgpu.SurfacePresent(state.surface)
}
// Upload arbitrary vertex/index data to GPU buffers
fill_buffers_with_model :: proc(vertices: []Vertex, indices: []u16) {
state.vertex_buffer = wgpu.DeviceCreateBufferWithData(
state.device,
&{label = "model vertices", usage = {.Vertex}},
vertices,
)
state.index_buffer = wgpu.DeviceCreateBufferWithData(
state.device,
&{label = "model indices", usage = {.Index}},
indices,
)
state.index_count = cast(u32)len(indices)
}
// -----------------------------------------
// Private functions
@@ -208,18 +308,56 @@ on_device :: proc "c" (
}
wgpu.SurfaceConfigure(state.surface, &state.config)
shader :: `
// ----------------------------------------
// Depth buffer
create_depth_texture()
// ----------------------------------------
// Compile shader
uniforms_struct := to_wgsl_struct(Camera_Uniform, "Uniforms")
defer delete(uniforms_struct)
vertex_input_struct := to_wgsl_struct(
Vertex,
"VertexInput",
locations = true,
)
defer delete(vertex_input_struct)
shader := fmt.tprintf(
`
%s
@group(0) @binding(0) var<uniform> u: Uniforms;
@group(0) @binding(1) var t_diffuse: texture_2d<f32>;
@group(0) @binding(2) var s_diffuse: sampler;
%s
struct VertexOutput {{
@builtin(position) position: vec4<f32>,
@location(0) col: vec3<f32>,
@location(1) uv: vec2<f32>,
}};
@vertex
fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4<f32> {
let x = f32(i32(in_vertex_index) - 1);
let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
return vec4<f32>(x, y, 0.0, 1.0);
}
fn vs_main(in: VertexInput) -> VertexOutput {{
var out: VertexOutput;
out.position = u.mvp * vec4<f32>(in.pos, 1.0);
out.col = in.col;
out.uv = in.uv;
return out;
}}
@fragment
fn fs_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}`
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {{
return textureSample(t_diffuse, s_diffuse, in.uv) * vec4<f32>(in.col, 1.0);
}}
`,
uniforms_struct,
vertex_input_struct,
)
state.module = wgpu.DeviceCreateShaderModule(
state.device,
@@ -231,12 +369,92 @@ on_device :: proc "c" (
},
)
state.pipeline_layout = wgpu.DeviceCreatePipelineLayout(state.device, &{})
// ----------------------------------------
// Camera uniform: buffer, then the baked layout it will be read through
state.uniform_buffer = wgpu.DeviceCreateBuffer(
state.device,
&{
label = "camera uniform",
usage = {.Uniform, .CopyDst}, // shader reads, queue writes
size = cast(u64)size_of(Camera_Uniform),
},
)
camera_layout_entries := [?]wgpu.BindGroupLayoutEntry {
{
binding = 0, // slot 0
visibility = {.Vertex},
buffer = {
type = .Uniform,
minBindingSize = cast(u64)size_of(Camera_Uniform),
},
},
{
binding = 1, // slot 1
visibility = {.Fragment},
texture = {
sampleType = .Float,
viewDimension = ._2D,
multisampled = false,
},
},
{
binding = 2, // slot 2
visibility = {.Fragment},
sampler = {type = .Filtering},
},
}
state.bind_group_layout = wgpu.DeviceCreateBindGroupLayout(
state.device,
&{
label = "camera layout",
entryCount = len(camera_layout_entries),
entries = raw_data(camera_layout_entries[:]),
},
)
// ----------------------------------------
// Diffuse texture + sampler
state.diffuse_texture, state.diffuse_texture_view, state.diffuse_sampler =
create_diffuse_texture(state.device, state.queue)
// ----------------------------------------
// Buffer shape
vertex_attributes := to_vertex_attributes(Vertex)
vertex_layout := wgpu.VertexBufferLayout {
stepMode = .Vertex,
arrayStride = size_of(Vertex),
attributeCount = len(vertex_attributes),
attributes = raw_data(vertex_attributes),
}
// ----------------------------------------
// Render pipeline
camera_group_layouts := [1]wgpu.BindGroupLayout{state.bind_group_layout}
state.pipeline_layout = wgpu.DeviceCreatePipelineLayout(
state.device,
&{
bindGroupLayoutCount = len(camera_group_layouts),
bindGroupLayouts = raw_data(camera_group_layouts[:]),
},
)
state.pipeline = wgpu.DeviceCreateRenderPipeline(
state.device,
&{
label = "pipeline",
layout = state.pipeline_layout,
vertex = {module = state.module, entryPoint = "vs_main"},
vertex = {
module = state.module,
entryPoint = "vs_main",
bufferCount = 1,
buffers = &vertex_layout,
},
fragment = &{
module = state.module,
entryPoint = "fs_main",
@@ -248,8 +466,39 @@ on_device :: proc "c" (
},
primitive = {topology = .TriangleList},
multisample = {count = 1, mask = 0xFFFFFFFF},
depthStencil = &wgpu.DepthStencilState {
format = .Depth24Plus,
depthWriteEnabled = .True,
depthCompare = .Less,
},
},
)
// ----------------------------------------
// Camera bind group
bind_group_entries := [?]wgpu.BindGroupEntry {
{
binding = 0, // slot 0
buffer = state.uniform_buffer,
offset = 0, // offset into buffer to start from
size = cast(u64)size_of(Camera_Uniform),
},
{binding = 1, textureView = state.diffuse_texture_view},
{binding = 2, sampler = state.diffuse_sampler},
}
state.bind_group = wgpu.DeviceCreateBindGroup(
state.device,
&{
label = "camera bind group",
layout = state.bind_group_layout,
entryCount = len(bind_group_entries),
entries = raw_data(bind_group_entries[:]),
},
)
// Initial upload of the matrix
upload_camera(state.queue, state.uniform_buffer, framebuffer_aspect())
}
@(private = "file")
@@ -290,3 +539,147 @@ pick_present_mode :: proc(vsync: bool) -> wgpu.PresentMode {
return .Fifo // Vsync On
}
// Depth buffer: same size as the surface, should get recreated on resize
@(private = "file")
create_depth_texture :: proc() {
if state.depth_texture != nil {
wgpu.TextureViewRelease(state.depth_texture_view)
wgpu.TextureRelease(state.depth_texture)
}
state.depth_texture = wgpu.DeviceCreateTexture(
state.device,
&{
label = "depth texture",
usage = {.RenderAttachment},
dimension = ._2D,
size = {
width = state.config.width,
height = state.config.height,
depthOrArrayLayers = 1,
},
format = .Depth24Plus,
mipLevelCount = 1,
sampleCount = 1,
},
)
state.depth_texture_view = wgpu.TextureCreateView(state.depth_texture, nil)
}
@(private = "file")
framebuffer_aspect :: proc() -> f32 {
width, height := os_get_framebuffer_size()
if height == 0 {
return 1
}
return cast(f32)width / cast(f32)height
}
// Perspective projection, WebGPU flavour
@(private = "file")
camera_perspective :: proc(
fovy_degrees, aspect, near, far: f32,
) -> linalg.Matrix4f32 {
gl := linalg.matrix4_perspective(
fovy_degrees * math.PI / 180.0,
aspect,
near,
far,
)
// GL's clip space is [-1, 1] and WebGPU's clip space is [0, 1],
// so fold z with a remap: z' = 1/2 z + 1/2 w
remap := linalg.identity(linalg.Matrix4f32)
remap[2, 2] = 0.5
remap[2, 3] = 0.5
return remap * gl
}
@(private = "file")
camera_mvp :: proc(aspect: f32) -> linalg.Matrix4f32 {
projection := camera_perspective(60, aspect, 0.1, 100)
view := linalg.matrix4_look_at_f32({0, 0.75, 2}, {0, 0, 0}, {0, 1, 0})
// model = identity: the loader already centered the model at the origin
return projection * view
}
@(private = "file")
upload_camera :: proc(queue: wgpu.Queue, buffer: wgpu.Buffer, aspect: f32) {
uniforms := Camera_Uniform {
mvp = camera_mvp(aspect),
}
// bufferOffset = offset into buffer to start from
wgpu.QueueWriteBuffer(queue, buffer, 0, &uniforms, size_of(Camera_Uniform))
}
// Test 256x256 checkerboard texture, uploaded once
@(private = "file")
create_diffuse_texture :: proc(
device: wgpu.Device,
queue: wgpu.Queue,
) -> (
wgpu.Texture,
wgpu.TextureView,
wgpu.Sampler,
) {
width, height: u32 = 256, 256
pixels := make([]u8, width * height * 4)
defer delete(pixels)
for y in 0 ..< height {
for x in 0 ..< width {
checker := ((x / 32) + (y / 32)) % 2 == 0
idx := (y * width + x) * 4
if checker {
pixels[idx + 0] = 240
pixels[idx + 1] = 240
pixels[idx + 2] = 240
pixels[idx + 3] = 255
} else {
pixels[idx + 0] = 64
pixels[idx + 1] = 64
pixels[idx + 2] = 64
pixels[idx + 3] = 255
}
}
}
texture := wgpu.DeviceCreateTexture(
device,
&{
label = "diffuse texture",
usage = {.TextureBinding, .CopyDst}, // shader samples, queue writes
dimension = ._2D,
size = {width = width, height = height, depthOrArrayLayers = 1},
format = .RGBA8Unorm,
mipLevelCount = 1,
sampleCount = 1,
},
)
// Upload texture to GPU
wgpu.QueueWriteTexture(
queue,
&{texture = texture, mipLevel = 0, origin = {0, 0, 0}, aspect = .All}, // destination
raw_data(pixels),
len(pixels),
&{offset = 0, bytesPerRow = width * 4, rowsPerImage = height}, // data layout
&{width = width, height = height, depthOrArrayLayers = 1}, // 3D extent
)
view := wgpu.TextureCreateView(texture, nil)
sampler := wgpu.DeviceCreateSampler(
device,
&{
addressModeU = .Repeat,
addressModeV = .Repeat,
magFilter = .Nearest,
minFilter = .Nearest,
mipmapFilter = .Nearest,
maxAnisotropy = 1,
},
)
return texture, view, sampler
}
+276
View File
@@ -0,0 +1,276 @@
package platform
import "core:fmt"
import "core:reflect"
import "core:strings"
import "wgpu:wgpu"
// -----------------------------------------
// Types
// -----------------------------------------
// Public functions
// Generate a WGSL struct declaration from an Odin struct type.
// The caller owns the returned string (allocated on context.allocator).
//
// If locations is true, each member is prefixed with @location(n). This is
// required for vertex input structs; uniform structs should use false.
to_wgsl_struct :: proc(
$T: typeid,
name: string,
locations := false,
) -> string {
ti := base_type_info(type_info_of(T))
s, ok := ti.variant.(reflect.Type_Info_Struct)
if !ok do fmt.panicf("[wgpu_reflect] %s is not a struct", typeid_of(T))
b: strings.Builder
strings.write_string(&b, "struct ")
strings.write_string(&b, name)
strings.write_string(&b, " {\n")
names := s.names[:s.field_count]
types := s.types[:s.field_count]
for i in 0 ..< s.field_count {
wgsl_type, type_ok := to_wgsl_type(types[i])
if !type_ok {
fmt.panicf("[wgpu_reflect] cannot map field %s to WGSL", names[i])
}
if locations {
fmt.sbprintf(
&b,
"\t@location(%d) %s: %s,\n",
i,
names[i],
wgsl_type,
)
} else {
fmt.sbprintf(&b, "\t%s: %s,\n", names[i], wgsl_type)
}
}
strings.write_string(&b, "};")
return strings.to_string(b)
}
// Generate a []wgpu.VertexAttribute array that matches the fields of struct T.
// The caller owns the returned slice (allocated on context.allocator)
to_vertex_attributes :: proc($T: typeid) -> []wgpu.VertexAttribute {
ti := base_type_info(type_info_of(T))
s, ok := ti.variant.(reflect.Type_Info_Struct)
if !ok do fmt.panicf("[wgpu_reflect] %s is not a struct", typeid_of(T))
attrs := make([]wgpu.VertexAttribute, s.field_count)
names := s.names[:s.field_count]
types := s.types[:s.field_count]
offsets := s.offsets[:s.field_count]
for i in 0 ..< s.field_count {
format, format_ok := to_vertex_format(types[i])
if !format_ok {
fmt.panicf(
"[wgpu_reflect] cannot map field %s to a vertex format",
names[i],
)
}
attrs[i] = wgpu.VertexAttribute {
format = format,
offset = cast(u64)offsets[i],
shaderLocation = u32(i),
}
}
return attrs
}
// -----------------------------------------
// Private functions
// Strips named-type wrappers so we can inspect the underlying type
@(private = "file")
base_type_info :: proc(type_info: ^reflect.Type_Info) -> ^reflect.Type_Info {
#partial switch v in type_info.variant {
case reflect.Type_Info_Named:
return base_type_info(v.base)
}
return type_info
}
// Map an Odin type to a WGSL scalar/vector/matrix type name
@(private = "file")
to_wgsl_type :: proc(type_info: ^reflect.Type_Info) -> (string, bool) {
ti := base_type_info(type_info)
#partial switch v in ti.variant {
case reflect.Type_Info_Float:
switch ti.size {
case 4:
return "f32", true
case 8:
return "f64", true
}
case reflect.Type_Info_Integer:
prefix := v.signed ? "i" : "u"
switch ti.size {
case 1:
return fmt.tprintf("%s8", prefix), true
case 2:
return fmt.tprintf("%s16", prefix), true
case 4:
return fmt.tprintf("%s32", prefix), true
case 8:
return fmt.tprintf("%s64", prefix), true
}
case reflect.Type_Info_Array:
elem_type, elem_ok := to_wgsl_type(v.elem)
if !elem_ok do return "", false
switch v.count {
case 2:
return fmt.tprintf("vec2<%s>", elem_type), true
case 3:
return fmt.tprintf("vec3<%s>", elem_type), true
case 4:
return fmt.tprintf("vec4<%s>", elem_type), true
}
case reflect.Type_Info_Matrix:
elem_type, elem_ok := to_wgsl_type(v.elem)
if !elem_ok do return "", false
return fmt.tprintf(
"mat%dx%d<%s>",
v.column_count,
v.row_count,
elem_type,
),
true
case:
fmt.panicf("[wgpu_reflect] unimplemented type translation: %v", ti)
}
return "", false
}
// Map an Odin type to a wgpu.VertexFormat.
// Only handles the scalar/vector numeric formats commonly used as vertex attributes
@(private = "file")
to_vertex_format :: proc(
type_info: ^reflect.Type_Info,
) -> (
wgpu.VertexFormat,
bool,
) {
ti := base_type_info(type_info)
#partial switch v in ti.variant {
case reflect.Type_Info_Float:
if ti.size == 2 do return .Float16, true
else if ti.size == 4 do return .Float32, true
case reflect.Type_Info_Integer:
if v.signed {
switch ti.size {
case 1:
return .Sint8, true
case 2:
return .Sint16, true
case 4:
return .Sint32, true
}
} else {
switch ti.size {
case 1:
return .Uint8, true
case 2:
return .Uint16, true
case 4:
return .Uint32, true
}
}
case reflect.Type_Info_Array:
elem := base_type_info(v.elem)
#partial switch ev in elem.variant {
case reflect.Type_Info_Float:
if elem.size == 2 {
switch v.count {
case 2:
return .Float16x2, true
case 4:
return .Float16x4, true
}
} else if elem.size == 4 {
switch v.count {
case 2:
return .Float32x2, true
case 3:
return .Float32x3, true
case 4:
return .Float32x4, true
}
}
case reflect.Type_Info_Integer:
if ev.signed {
switch elem.size {
case 1:
switch v.count {
case 2:
return .Sint8x2, true
case 4:
return .Sint8x4, true
}
case 2:
switch v.count {
case 2:
return .Sint16x2, true
case 4:
return .Sint16x4, true
}
case 4:
switch v.count {
case 2:
return .Sint32x2, true
case 3:
return .Sint32x3, true
case 4:
return .Sint32x4, true
}
}
} else {
switch elem.size {
case 1:
switch v.count {
case 2:
return .Uint8x2, true
case 4:
return .Uint8x4, true
}
case 2:
switch (v.count) {
case 2:
return .Uint16x2, true
case 4:
return .Uint16x4, true
}
case 4:
switch (v.count) {
case 2:
return .Uint32x2, true
case 3:
return .Uint32x3, true
case 4:
return .Uint32x4, true
}
}
}
}
}
return .Float32, false
}