> HOT LOADING FRAGMENT SHADERS AND TEXTURES ARE LOADED

This commit is contained in:
Peter Li 2025-04-20 17:09:51 -07:00
parent 2ec0cd8c31
commit 8647ac8bc9
31 changed files with 394 additions and 74 deletions

View File

@ -1,5 +1,20 @@
float4 main(float2 UV : TEXCOORD0) : SV_Target0
Texture2D<float4> Texture : register(t0, space2);
SamplerState Sampler : register(s0, space2);
cbuffer Uniforms : register(b0, space3)
{
return float4(UV, 0.0, 1.0);
float time;
};
float4 main(float2 UV : TEXCOORD0, float3 WorldPos: TEXCOORD1) : SV_Target0
{
float4 col = pow(Texture.Sample(Sampler, UV), 0.4545);
float SPEEEEEEEEEEEEEED = 0;
float strength = 0.0;
col.r = col.r + strength * sin(time * SPEEEEEEEEEEEEEED) * WorldPos.x + strength * cos(time * SPEEEEEEEEEEEEEED) * WorldPos.y;
return col;
}

View File

@ -18,5 +18,21 @@
"name" : "out.var.SV_Target0",
"location" : 0
}
],
"separate_images" : [
{
"type" : "texture2D",
"name" : "Texture",
"set" : 2,
"binding" : 0
}
],
"separate_samplers" : [
{
"type" : "sampler",
"name" : "Sampler",
"set" : 2,
"binding" : 0
}
]
}

View File

@ -13,6 +13,7 @@ struct Input
struct Output
{
float2 TexCoord : TEXCOORD0;
float3 WorldPos : TEXCOORD1;
float4 Position : SV_Position;
};
@ -36,11 +37,13 @@ Output main(Input input)
output.TexCoord = input.UV;
float4 pos = float4(input.Position, 1.0);
pos.y = pos.y - 50;
// pos.x += 0.2 * sin(time * 0.5 ) * pos.y * 0.5;
// pos.y += 0.2 * cos(time * 0.5 ) * pos.z * 0.5;
output.Position = mul(ViewProjection, mul(scene[input.Instance].Model, pos));
output.WorldPos = pos.xyz;
return output;
}

View File

@ -6,7 +6,7 @@
}
],
"types" : {
"_8" : {
"_9" : {
"name" : "Scene",
"members" : [
{
@ -18,12 +18,12 @@
}
]
},
"_7" : {
"_8" : {
"name" : "type.StructuredBuffer.Scene",
"members" : [
{
"name" : "_m0",
"type" : "_8",
"type" : "_9",
"array" : [
0
],
@ -35,7 +35,7 @@
}
]
},
"_10" : {
"_11" : {
"name" : "type.Uniforms",
"members" : [
{
@ -70,11 +70,16 @@
"type" : "vec2",
"name" : "out.var.TEXCOORD0",
"location" : 0
},
{
"type" : "vec3",
"name" : "out.var.TEXCOORD1",
"location" : 1
}
],
"ssbos" : [
{
"type" : "_7",
"type" : "_8",
"name" : "scene",
"readonly" : true,
"block_size" : 0,
@ -84,7 +89,7 @@
],
"ubos" : [
{
"type" : "_10",
"type" : "_11",
"name" : "type.Uniforms",
"block_size" : 68,
"set" : 1,

View File

@ -1,10 +1,12 @@
mesh: ?meshes.IndexedMesh = null,
textureId: ?u32 = null,
visibility: bool = true,
textureName: core.Name = core.NameInvalid,
meshName: core.Name = core.NameInvalid,
mesh: ?meshes.IndexedMesh = null,
texture: ?*Texture = null,
entity: core.Entity = undefined,
pub var BaseContainer: *MeshSet = undefined;
@ -30,6 +32,12 @@ pub fn updateMesh(self: *@This()) void {
}
}
pub fn updateTexture(self: *@This()) void {
if (self.textureName.handle() != 0) {
self.setMeshByName(&self.textureName);
}
}
pub fn setMeshByName(self: *@This(), meshName: *core.Name) void {
self.mesh = rend.getMeshByName(meshName);
self.meshName = meshName.*;
@ -41,16 +49,15 @@ pub fn setMesh(self: *@This(), meshName: []const u8) void {
self.setMeshByName(&name);
}
// pub fn setTextureByName(self: *@This(), n: []const u8) void {
// var name = core.MakeName(n);
// self.mesh = rend.getTextureByName(&name);
// self.textureName = name;
// }
pub fn setTextureByName(self: *@This(), name: *core.Name) void {
self.texture = rend.getTexture(name);
self.textureName = name.*;
}
// pub fn setTexture(self: *@This(), n: []const u8) void {
// var name = core.MakeName(n);
// self.textureName = rend.getTextureByName(&name);
// }
pub fn setTexture(self: *@This(), n: []const u8) void {
var name = core.MakeName(n);
self.setTextureByName(&name);
}
// animator: ?*Animator = null, todo.. implement animator
pub const MeshSet = core.SparseSet(@This());
@ -59,3 +66,4 @@ const meshes = @import("meshes.zig");
const core = @import("core");
const std = @import("std");
const rend = @import("../rend.zig");
const Texture = rend.Texture;

View File

@ -32,6 +32,7 @@ pub const registerRendererObject = renderer.registerRendererObject;
pub const getTexture = renderer.getTexture;
pub const texture = @import("texture/texture.zig");
pub const Texture = texture.Texture;
var rendAllocator: std.mem.Allocator = undefined;
pub fn getAllocator() std.mem.Allocator {

View File

@ -39,9 +39,13 @@ pub const Renderer = struct {
textureList: *TextureList = undefined,
blockySampler: *gpu.GPUSampler = undefined,
// transients DO NOT TOUCH
swapchainTexture: *gpu.GPUTexture = undefined,
defaultTexture: *rend.Texture = undefined,
pub var NeonObjectTable: core.EngineObjectVTable = core.EngineObjectVTable.from(@This());
pub const MaxObjectCount = 50000;
@ -59,6 +63,55 @@ pub const Renderer = struct {
return self;
}
pub fn startRenderer(self: *@This()) !void {
self.device = gpu.createGPUDevice(.{
.shaderformatSpirv = true,
.shaderformatDxil = true,
.shaderformatMsl = true,
}, true, null);
self.window = platform.getInstance().window;
if (!self.device.claimWindowForGPUDevice(self.window))
return error.UnableToClaimGpu;
try self.discoverFormats();
core.engine_log("sgpu device created, using shader format: {s}", .{self.shaderSuffix});
// try self.createPipeline();
try self.createMeshPipeline();
try self.createDepthTexture();
self.meshPool = try self.createRendererObject(MeshPool);
self.textureList = try self.createRendererEngineObject(TextureList);
try self.createSamplers();
try assets.load(
assets.MakeImportRefOptions(
"Texture",
"t_default",
.{ .path = "textures/texture_sample.png" },
),
);
var defaultTextureName = core.MakeName("t_default");
self.defaultTexture = getTexture(&defaultTextureName).?;
}
pub fn createSamplers(self: *@This()) !void {
core.engine_log("creating blocky sampler", .{});
self.blockySampler = self.device.createGPUSampler(&std.mem.zeroInit(gpu.GPUSamplerCreateInfo, .{
.min_filter = .filterNearest,
.mag_filter = .filterNearest,
.mipmap_mode = .samplermipmapmodeNearest,
.address_mode_u = .sampleraddressmodeRepeat,
.address_mode_v = .sampleraddressmodeRepeat,
.address_mode_w = .sampleraddressmodeRepeat,
}));
}
// registers a pre-existing render object, does not add to destroys
pub fn registerRendererObject(self: *@This(), T: type, object: *anyopaque) !void {
if (@hasDecl(T, "onUpload")) {
@ -109,30 +162,6 @@ pub const Renderer = struct {
self.depthTexture = self.device.createGPUTexture(&gci);
}
pub fn startRenderer(self: *@This()) !void {
self.device = gpu.createGPUDevice(.{
.shaderformatSpirv = true,
.shaderformatDxil = true,
.shaderformatMsl = true,
}, true, null);
self.window = platform.getInstance().window;
if (!self.device.claimWindowForGPUDevice(self.window))
return error.UnableToClaimGpu;
try self.discoverFormats();
core.engine_log("sgpu device created, using shader format: {s}", .{self.shaderSuffix});
// try self.createPipeline();
try self.createMeshPipeline();
try self.createDepthTexture();
self.meshPool = try self.createRendererObject(MeshPool);
self.textureList = try self.createRendererEngineObject(TextureList);
}
pub fn discoverFormats(self: *@This()) !void {
const formats = self.device.getGPUShaderFormats();
@ -324,15 +353,24 @@ pub const Renderer = struct {
}
pub fn uploadUniforms(self: *@This(), cmd: *gpu.GPUCommandBuffer) !void {
var data = std.mem.zeroes([@sizeOf(meshes_vert.Uniforms) / 8 + 1]usize);
const ptr: *meshes_vert.Uniforms = @ptrCast(@alignCast(&data));
if (self.activeCamera) |camera| {
ptr.ViewProjection = @bitCast(camera.final);
{
var data = std.mem.zeroes([@sizeOf(meshes_vert.Uniforms) / 8 + 1]usize);
const ptr: *meshes_vert.Uniforms = @ptrCast(@alignCast(&data));
if (self.activeCamera) |camera| {
ptr.ViewProjection = @bitCast(camera.final);
}
ptr.time = @floatCast(self.totalTime);
cmd.pushGPUVertexUniformData(0, &data, @sizeOf(meshes_vert.Uniforms));
}
{
var data = std.mem.zeroes([@sizeOf(lit_mesh_frag.Uniforms) / 8 + 1]usize);
const ptr: *lit_mesh_frag.Uniforms = @ptrCast(@alignCast(&data));
ptr.time = @floatCast(self.totalTime);
cmd.pushGPUVertexUniformData(0, &data, @sizeOf(meshes_vert.Uniforms));
ptr.time = @floatCast(self.totalTime);
cmd.pushGPUFragmentUniformData(0, &data, @sizeOf(lit_mesh_frag.Uniforms));
}
}
pub fn frameUploads(self: *@This()) void {
@ -408,9 +446,11 @@ pub const Renderer = struct {
renderpass.bindGPUVertexStorageBuffers(0, &self.ssboScene, 1);
renderpass.bindGPUVertexBuffers(0, &.{ .buffer = self.meshPool.vertexBuffer, .offset = 0 }, 1);
renderpass.bindGPUIndexBuffer(&.{ .buffer = self.meshPool.indexBuffer, .offset = 0 }, .indexelementsize32bit);
// todo move into materials system
renderpass.setGPUScissor(&self.scissor);
//SDL_BindGPUFragmentSamplers(renderPass, 0, &(SDL_GPUTextureSamplerBinding){ .texture = Texture, .sampler = Samplers[CurrentSamplerIndex] }, 1);
//rendering each mesh
{
const container = rend.MeshComponent.BaseContainer;
@ -419,10 +459,21 @@ pub const Renderer = struct {
// core.engine_log("pushing draw {d}", .{i});
const component = &container.dense.items[i].value;
// todo move this to slow tick? only update once every 1 second or so?
if (component.mesh == null) {
component.updateMesh();
}
if (component.texture == null) {
component.updateTexture();
}
var t = component.texture;
if (t == null) {
t = self.defaultTexture;
}
renderpass.bindGPUFragmentSamplers(0, &.{ .texture = t.?.texture, .sampler = self.blockySampler }, 1);
if (component.mesh) |mesh| {
// core.engine_log("pushing draw for instance {d}", .{i});
renderpass.drawGPUIndexedPrimitives(mesh.index.size, 1, mesh.index.start, @intCast(mesh.vertex.start), @intCast(i));
@ -464,6 +515,7 @@ pub var gAllocator: std.mem.Allocator = undefined;
const rend = @import("../rend.zig");
const std = @import("std");
const assets = @import("assets");
const core = @import("core");
const platform = @import("platform");
const sdl3 = @import("sdl3");
@ -523,7 +575,10 @@ pub fn registerRendererObject(comptime T: type, object: *anyopaque) !void {
pub const getMesh = mesh_pool.getMesh;
pub const getMeshByName = mesh_pool.getMeshByName;
pub const pushMeshUpdate = mesh_pool.pushMeshUpdate;
pub fn getTexture(name: *core.Name) ?*rend.Texture {
return gRenderer.textureList.map.get(name.handle());
}
pub const GPUTextureType = gpu.GPUTexture;

View File

@ -11,31 +11,15 @@ pub const mat4 = shaderTypes.mat4;
pub const float = shaderTypes.float;
pub const BufferInfo = shaderTypes.BufferInfo;
pub const Scene = struct {
color: vec4,
pub const Buffer: BufferInfo = .{ .storage = 0 };
};
pub const Scene2 = struct {
color: vec4,
lmfao: vec4,
pub const Buffer: BufferInfo = .{ .storage = 1 };
};
pub const TransformBuffer = struct {
modelMatrix: mat4,
viewMatrix: mat4,
projectionMatrix: mat4,
pub const Uniforms = struct {
time: float,
pub const Buffer: BufferInfo = .{ .uniform = 0 };
};
pub const LoadArgs = shaderTypes.ShaderLoadArgs{
.num_samplers = 0, // The number of samplers defined in the shader.
.num_samplers = 1, // The number of samplers defined in the shader.
.num_storage_textures = 0, // The number of storage textures defined in the shader.
.num_storage_buffers = 2, // The number of storage buffers defined in the shader.
.num_uniform_buffers = 0, // The number of uniform buffers defined in the shader.
.num_storage_buffers = 0, // The number of storage buffers defined in the shader.
.num_uniform_buffers = 1, // The number of uniform buffers defined in the shader.
};

View File

@ -65,6 +65,9 @@ pub const BufferInfo = shaderTypes.BufferInfo;
zs = parseTypeToZig(types, uniform['type'], "uniform", uniform['binding'])
ostring += zs + "\n"
if 'separate_samplers' in reflect:
samplerIndex += len(reflect['separate_samplers'])
zs = "pub const LoadArgs = shaderTypes.ShaderLoadArgs{"
zs += f"""

View File

@ -13,10 +13,12 @@ struct main0_in
float2 in_var_TEXCOORD0 [[user(locn0)]];
};
fragment main0_out main0(main0_in in [[stage_in]])
fragment main0_out main0(main0_in in [[stage_in]], texture2d<float> Texture [[texture(0)]], sampler Sampler [[sampler(0)]])
{
main0_out out = {};
out.out_var_SV_Target0 = float4(in.in_var_TEXCOORD0, 0.0, 1.0);
float4 _27 = powr(Texture.sample(Sampler, in.in_var_TEXCOORD0), float4(0.4544999897480010986328125));
_27.x = _27.x;
out.out_var_SV_Target0 = _27;
return out;
}

View File

@ -22,6 +22,7 @@ struct type_Uniforms
struct main0_out
{
float2 out_var_TEXCOORD0 [[user(locn0)]];
float3 out_var_TEXCOORD1 [[user(locn1)]];
float4 gl_Position [[position]];
};
@ -34,8 +35,11 @@ struct main0_in
vertex main0_out main0(main0_in in [[stage_in]], constant type_Uniforms& Uniforms [[buffer(0)]], const device type_StructuredBuffer_Scene& scene [[buffer(1)]], uint gl_InstanceIndex [[instance_id]])
{
main0_out out = {};
float4 _42 = float4(in.in_var_TEXCOORD0, 1.0);
_42.y = in.in_var_TEXCOORD0.y - 50.0;
out.out_var_TEXCOORD0 = in.in_var_TEXCOORD3;
out.gl_Position = Uniforms.ViewProjection * (scene._m0[gl_InstanceIndex].Model * float4(in.in_var_TEXCOORD0, 1.0));
out.out_var_TEXCOORD1 = _42.xyz;
out.gl_Position = Uniforms.ViewProjection * (scene._m0[gl_InstanceIndex].Model * _42);
return out;
}

View File

@ -30,10 +30,15 @@ const assetReferences = [_]assets.AssetImportReference{
"m_fox",
.{ .path = "gltf-samples/Fox/glTF/Fox.gltf" },
),
assets.MakeImportRefOptions(
"Texture",
"t_fox",
.{ .path = "gltf-samples/Fox/glTF/Texture.png" },
),
assets.MakeImportRefOptions(
"Texture",
"t_empire",
.{ .path = "textures/texture_sample.png" },
.{ .path = "textures/lost_empire-RGBA.png" },
),
};
@ -62,6 +67,7 @@ pub fn prepare(self: *@This()) !void {
scene.setPosition(.{ .y = -20 });
const empireMesh = lostEmpire.addComponent(rend.MeshComponent).?;
empireMesh.setMesh("m_empire");
empireMesh.setTexture("t_empire");
}
{
@ -71,6 +77,7 @@ pub fn prepare(self: *@This()) !void {
// scene.setScale();
const mesh = fox.addComponent(rend.MeshComponent).?;
mesh.setMesh("m_fox");
mesh.setTexture("t_fox");
}
rend.setActiveCamera(camera);

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,22 @@
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct main0_out
{
float4 out_var_SV_Target0 [[color(0)]];
};
struct main0_in
{
float2 in_var_TEXCOORD0 [[user(locn0)]];
};
fragment main0_out main0(main0_in in [[stage_in]], texture2d<float> Texture [[texture(0)]], sampler Sampler [[sampler(0)]])
{
main0_out out = {};
out.out_var_SV_Target0 = Texture.sample(Sampler, in.in_var_TEXCOORD0);
return out;
}

View File

@ -0,0 +1,41 @@
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct Scene
{
float4x4 Model;
};
struct type_StructuredBuffer_Scene
{
Scene _m0[1];
};
struct type_Uniforms
{
float4x4 ViewProjection;
float time;
};
struct main0_out
{
float2 out_var_TEXCOORD0 [[user(locn0)]];
float4 gl_Position [[position]];
};
struct main0_in
{
float3 in_var_TEXCOORD0 [[attribute(0)]];
float2 in_var_TEXCOORD3 [[attribute(3)]];
};
vertex main0_out main0(main0_in in [[stage_in]], constant type_Uniforms& Uniforms [[buffer(0)]], const device type_StructuredBuffer_Scene& scene [[buffer(1)]], uint gl_InstanceIndex [[instance_id]])
{
main0_out out = {};
out.out_var_TEXCOORD0 = in.in_var_TEXCOORD3;
out.gl_Position = Uniforms.ViewProjection * (scene._m0[gl_InstanceIndex].Model * float4(in.in_var_TEXCOORD0, 1.0));
return out;
}

View File

@ -0,0 +1,22 @@
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct main0_out
{
float4 out_var_SV_Target0 [[color(0)]];
};
struct main0_in
{
float4 in_var_TEXCOORD0 [[user(locn0)]];
};
fragment main0_out main0(main0_in in [[stage_in]])
{
main0_out out = {};
out.out_var_SV_Target0 = in.in_var_TEXCOORD0;
return out;
}

View File

@ -0,0 +1,66 @@
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct Scene
{
float3 color;
};
struct type_StructuredBuffer_Scene
{
Scene _m0[1];
};
constant float2 _31 = {};
constant float4 _32 = {};
struct main0_out
{
float4 out_var_TEXCOORD0 [[user(locn0)]];
float4 gl_Position [[position]];
};
vertex main0_out main0(const device type_StructuredBuffer_Scene& test [[buffer(0)]], uint gl_VertexIndex [[vertex_id]])
{
main0_out out = {};
float4 _71;
float2 _72;
if (gl_VertexIndex == 0u)
{
_71 = float4(test._m0[0u].color, 1.0);
_72 = float2(-1.0);
}
else
{
float4 _69;
float2 _70;
if (gl_VertexIndex == 1u)
{
_69 = float4(test._m0[1u].color, 1.0);
_70 = float2(1.0, -1.0);
}
else
{
bool _57 = gl_VertexIndex == 2u;
float4 _66;
if (_57)
{
_66 = float4(test._m0[2u].color, 1.0);
}
else
{
_66 = _32;
}
_69 = _66;
_70 = select(_31, float2(0.0, 1.0), bool2(_57));
}
_71 = _69;
_72 = _70;
}
out.out_var_TEXCOORD0 = _71;
out.gl_Position = float4(_72, 0.0, 1.0);
return out;
}

View File

@ -0,0 +1,66 @@
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct Scene
{
float4 color;
};
struct type_StructuredBuffer_Scene
{
Scene _m0[1];
};
constant float2 _30 = {};
constant float4 _31 = {};
struct main0_out
{
float4 out_var_TEXCOORD0 [[user(locn0)]];
float4 gl_Position [[position]];
};
vertex main0_out main0(const device type_StructuredBuffer_Scene& test [[buffer(0)]], uint gl_VertexIndex [[vertex_id]])
{
main0_out out = {};
float4 _58;
float2 _59;
if (gl_VertexIndex == 0u)
{
_58 = test._m0[0u].color;
_59 = float2(-1.0);
}
else
{
float4 _56;
float2 _57;
if (gl_VertexIndex == 1u)
{
_56 = test._m0[1u].color;
_57 = float2(1.0, -1.0);
}
else
{
bool _48 = gl_VertexIndex == 2u;
float4 _53;
if (_48)
{
_53 = test._m0[2u].color;
}
else
{
_53 = _31;
}
_56 = _53;
_57 = select(_30, float2(0.0, 1.0), bool2(_48));
}
_58 = _56;
_59 = _57;
}
out.out_var_TEXCOORD0 = _58;
out.gl_Position = float4(_59, 0.0, 1.0);
return out;
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.