examples: import mach-examples@20ceb359231ff284cf343dddba8cf25112ffe717

Helps hexops/mach#1165

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2024-03-06 11:08:19 -07:00
parent f25f435275
commit 0a8e22bb49
19 changed files with 3147 additions and 0 deletions

View file

@ -0,0 +1,162 @@
const std = @import("std");
const mach = @import("mach");
const ecs = mach.ecs;
const core = mach.core;
const math = mach.math;
const Renderer = @import("Renderer.zig");
const vec3 = math.vec3;
const vec2 = math.vec2;
const Vec2 = math.Vec2;
const Vec3 = math.Vec3;
timer: mach.Timer,
player: ecs.EntityID,
direction: Vec2 = vec2(0, 0),
spawning: bool = false,
spawn_timer: mach.Timer,
pub const components = struct {
pub const follower = void;
};
// Each module must have a globally unique name declared, it is impossible to use two modules with
// the same name in a program. To avoid name conflicts, we follow naming conventions:
//
// 1. `.mach` and the `.mach_foobar` namespace is reserved for Mach itself and the modules it
// provides.
// 2. Single-word names like `.renderer`, `.game`, etc. are reserved for the application itself.
// 3. Libraries which provide modules MUST be prefixed with an "owner" name, e.g. `.ziglibs_imgui`
// instead of `.imgui`. We encourage using e.g. your GitHub name, as these must be globally
// unique.
//
pub const name = .game;
pub const Mod = mach.Mod(@This());
pub fn init(
engine: *mach.Engine.Mod,
renderer: *Renderer.Mod,
game: *Mod,
) !void {
// The Mach .core is where we set window options, etc.
core.setTitle("Hello, ECS!");
// We can create entities, and set components on them. Note that components live in a module
// namespace, e.g. the `.renderer` module could have a 3D `.location` component with a different
// type than the `.physics2d` module's `.location` component if you desire.
const player = try engine.newEntity();
try renderer.set(player, .location, vec3(0, 0, 0));
try renderer.set(player, .scale, 1.0);
game.state = .{
.timer = try mach.Timer.start(),
.spawn_timer = try mach.Timer.start(),
.player = player,
};
}
pub fn tick(
engine: *mach.Engine.Mod,
renderer: *Renderer.Mod,
game: *Mod,
) !void {
// TODO(engine): event polling should occur in mach.Engine module and get fired as ECS events.
var iter = core.pollEvents();
var direction = game.state.direction;
var spawning = game.state.spawning;
while (iter.next()) |event| {
switch (event) {
.key_press => |ev| {
switch (ev.key) {
.left => direction.v[0] -= 1,
.right => direction.v[0] += 1,
.up => direction.v[1] += 1,
.down => direction.v[1] -= 1,
.space => spawning = true,
else => {},
}
},
.key_release => |ev| {
switch (ev.key) {
.left => direction.v[0] += 1,
.right => direction.v[0] -= 1,
.up => direction.v[1] -= 1,
.down => direction.v[1] += 1,
.space => spawning = false,
else => {},
}
},
.close => try engine.send(.exit, .{}),
else => {},
}
}
game.state.direction = direction;
game.state.spawning = spawning;
var player_pos = renderer.get(game.state.player, .location).?;
if (spawning and game.state.spawn_timer.read() > 1.0 / 60.0) {
for (0..10) |_| {
// Spawn a new follower entity
_ = game.state.spawn_timer.lap();
const new_entity = try engine.newEntity();
try game.set(new_entity, .follower, {});
try renderer.set(new_entity, .location, player_pos);
try renderer.set(new_entity, .scale, 1.0 / 6.0);
}
}
// Multiply by delta_time to ensure that movement is the same speed regardless of the frame rate.
const delta_time = game.state.timer.lap();
// Move following entities closer to us.
var archetypes_iter = engine.entities.query(.{ .all = &.{
.{ .game = &.{.follower} },
} });
while (archetypes_iter.next()) |archetype| {
const ids = archetype.slice(.entity, .id);
const locations = archetype.slice(.renderer, .location);
for (ids, locations) |id, location| {
// Avoid other follower entities by moving away from them if they are close to us.
const close_dist = 1.0 / 15.0;
var avoidance = Vec3.splat(0);
var avoidance_div: f32 = 1.0;
var archetypes_iter_2 = engine.entities.query(.{ .all = &.{
.{ .game = &.{.follower} },
} });
while (archetypes_iter_2.next()) |archetype_2| {
const other_ids = archetype_2.slice(.entity, .id);
const other_locations = archetype_2.slice(.renderer, .location);
for (other_ids, other_locations) |other_id, other_location| {
if (id == other_id) continue;
if (location.dist(&other_location) < close_dist) {
avoidance = avoidance.sub(&location.dir(&other_location, 0.0000001));
avoidance_div += 1.0;
}
}
}
// Avoid the player
var avoid_player_multiplier: f32 = 1.0;
if (location.dist(&player_pos) < close_dist * 6.0) {
avoidance = avoidance.sub(&location.dir(&player_pos, 0.0000001));
avoidance_div += 1.0;
avoid_player_multiplier = 4.0;
}
// Move away from things we want to avoid
const move_speed = 1.0 * delta_time;
var new_location = location.add(&avoidance.divScalar(avoidance_div).mulScalar(move_speed * avoid_player_multiplier));
// Move towards the center
new_location = new_location.lerp(&vec3(0, 0, 0), move_speed / avoidance_div);
try renderer.set(id, .location, new_location);
}
}
// Calculate the player position, by moving in the direction the player wants to go
// by the speed amount.
const speed = 1.0;
player_pos.v[0] += direction.x() * speed * delta_time;
player_pos.v[1] += direction.y() * speed * delta_time;
try renderer.set(game.state.player, .location, player_pos);
}

View file

@ -0,0 +1,166 @@
const std = @import("std");
const mach = @import("mach");
const core = mach.core;
const gpu = mach.gpu;
const math = mach.math;
const Vec3 = math.Vec3;
const num_bind_groups = 1024 * 32;
// uniform bind group offset must be 256-byte aligned
const uniform_offset = 256;
pipeline: *gpu.RenderPipeline,
queue: *gpu.Queue,
bind_groups: [num_bind_groups]*gpu.BindGroup,
uniform_buffer: *gpu.Buffer,
pub const name = .renderer;
pub const Mod = mach.Mod(@This());
pub const components = struct {
pub const location = Vec3;
pub const rotation = Vec3;
pub const scale = f32;
};
// TODO: this shouldn't be a packed struct, it should be extern.
const UniformBufferObject = packed struct {
offset: Vec3.Vector,
scale: f32,
};
pub fn init(
engine: *mach.Engine.Mod,
renderer: *Mod,
) !void {
const device = engine.state.device;
const shader_module = device.createShaderModuleWGSL("shader.wgsl", @embedFile("shader.wgsl"));
// Fragment state
const blend = gpu.BlendState{};
const color_target = gpu.ColorTargetState{
.format = core.descriptor.format,
.blend = &blend,
.write_mask = gpu.ColorWriteMaskFlags.all,
};
const fragment = gpu.FragmentState.init(.{
.module = shader_module,
.entry_point = "frag_main",
.targets = &.{color_target},
});
const uniform_buffer = device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(UniformBufferObject) * uniform_offset * num_bind_groups,
.mapped_at_creation = .false,
});
const bind_group_layout_entry = gpu.BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0);
const bind_group_layout = device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor.init(.{
.entries = &.{bind_group_layout_entry},
}),
);
var bind_groups: [num_bind_groups]*gpu.BindGroup = undefined;
for (bind_groups, 0..) |_, i| {
bind_groups[i] = device.createBindGroup(
&gpu.BindGroup.Descriptor.init(.{
.layout = bind_group_layout,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, uniform_buffer, uniform_offset * i, @sizeOf(UniformBufferObject)),
},
}),
);
}
const bind_group_layouts = [_]*gpu.BindGroupLayout{bind_group_layout};
const pipeline_layout = device.createPipelineLayout(&gpu.PipelineLayout.Descriptor.init(.{
.bind_group_layouts = &bind_group_layouts,
}));
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = pipeline_layout,
.vertex = gpu.VertexState{
.module = shader_module,
.entry_point = "vertex_main",
},
};
renderer.state = .{
.pipeline = device.createRenderPipeline(&pipeline_descriptor),
.queue = device.getQueue(),
.bind_groups = bind_groups,
.uniform_buffer = uniform_buffer,
};
shader_module.release();
}
pub fn deinit(
renderer: *Mod,
) !void {
renderer.state.pipeline.release();
renderer.state.queue.release();
for (renderer.state.bind_groups) |bind_group| bind_group.release();
renderer.state.uniform_buffer.release();
}
pub fn tick(
engine: *mach.Engine.Mod,
renderer: *Mod,
) !void {
const device = engine.state.device;
// Begin our render pass
const back_buffer_view = core.swap_chain.getCurrentTextureView().?;
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassDescriptor.init(.{
.color_attachments = &.{color_attachment},
});
// Update uniform buffer
var archetypes_iter = engine.entities.query(.{ .all = &.{
.{ .renderer = &.{ .location, .scale } },
} });
var num_entities: usize = 0;
while (archetypes_iter.next()) |archetype| {
const ids = archetype.slice(.entity, .id);
const locations = archetype.slice(.renderer, .location);
const scales = archetype.slice(.renderer, .scale);
for (ids, locations, scales) |id, location, scale| {
_ = id;
const ubo = UniformBufferObject{
.offset = location.v,
.scale = scale,
};
encoder.writeBuffer(renderer.state.uniform_buffer, uniform_offset * num_entities, &[_]UniformBufferObject{ubo});
num_entities += 1;
}
}
const pass = encoder.beginRenderPass(&render_pass_info);
for (renderer.state.bind_groups[0..num_entities]) |bind_group| {
pass.setPipeline(renderer.state.pipeline);
pass.setBindGroup(0, bind_group, &.{0});
pass.draw(3, 1, 0, 0);
}
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
renderer.state.queue.submit(&[_]*gpu.CommandBuffer{command});
command.release();
core.swap_chain.present();
back_buffer_view.release();
}

View file

@ -0,0 +1,15 @@
// Experimental ECS app example. Not yet ready for actual use.
const mach = @import("mach");
const Renderer = @import("Renderer.zig");
const Game = @import("Game.zig");
// The list of modules to be used in our application. Our game itself is implemented in our own
// module called Game.
pub const modules = .{
mach.Engine,
Renderer,
Game,
};
pub const App = mach.App;

View file

@ -0,0 +1,22 @@
struct Uniform {
pos: vec3<f32>,
scale: f32,
};
@group(0) @binding(0) var<uniform> in : Uniform;
@vertex fn vertex_main(
@builtin(vertex_index) VertexIndex : u32
) -> @builtin(position) vec4<f32> {
var positions = array<vec2<f32>, 3>(
vec2<f32>( 0.0, 0.1),
vec2<f32>(-0.1, -0.1),
vec2<f32>( 0.1, -0.1)
);
var pos = positions[VertexIndex];
return vec4<f32>((pos*in.scale)+in.pos.xy, 0.0, 1.0);
}
@fragment fn frag_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 0.0);
}