examples: import mach-examples@20ceb359231ff284cf343dddba8cf25112ffe717
Helps hexops/mach#1165 Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
parent
f25f435275
commit
0a8e22bb49
19 changed files with 3147 additions and 0 deletions
211
examples/glyphs/Game.zig
Normal file
211
examples/glyphs/Game.zig
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
const std = @import("std");
|
||||
const mach = @import("mach");
|
||||
const core = mach.core;
|
||||
const gpu = mach.gpu;
|
||||
const ecs = mach.ecs;
|
||||
const Sprite = mach.gfx.Sprite;
|
||||
const math = mach.math;
|
||||
const vec2 = math.vec2;
|
||||
const vec3 = math.vec3;
|
||||
const Vec2 = math.Vec2;
|
||||
const Vec3 = math.Vec3;
|
||||
const Mat3x3 = math.Mat3x3;
|
||||
const Mat4x4 = math.Mat4x4;
|
||||
|
||||
const Text = @import("Text.zig");
|
||||
|
||||
timer: mach.Timer,
|
||||
player: mach.ecs.EntityID,
|
||||
direction: Vec2 = vec2(0, 0),
|
||||
spawning: bool = false,
|
||||
spawn_timer: mach.Timer,
|
||||
fps_timer: mach.Timer,
|
||||
frame_count: usize,
|
||||
sprites: usize,
|
||||
rand: std.rand.DefaultPrng,
|
||||
time: f32,
|
||||
|
||||
const d0 = 0.000001;
|
||||
|
||||
// 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 `.game` 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 const Pipeline = enum(u32) {
|
||||
default,
|
||||
text,
|
||||
};
|
||||
|
||||
pub fn init(
|
||||
engine: *mach.Engine.Mod,
|
||||
sprite_mod: *Sprite.Mod,
|
||||
text_mod: *Text.Mod,
|
||||
game: *Mod,
|
||||
) !void {
|
||||
// The Mach .core is where we set window options, etc.
|
||||
core.setTitle("gfx.Sprite example");
|
||||
|
||||
// Initialize mach.gfx.Text module
|
||||
try text_mod.send(.init, .{});
|
||||
|
||||
// Tell sprite_mod to use the texture
|
||||
try sprite_mod.send(.init, .{});
|
||||
try sprite_mod.send(.initPipeline, .{Sprite.PipelineOptions{
|
||||
.pipeline = @intFromEnum(Pipeline.text),
|
||||
.texture = text_mod.state.texture,
|
||||
}});
|
||||
|
||||
// We can create entities, and set components on them. Note that components live in a module
|
||||
// namespace, e.g. the `Sprite` module could have a 3D `.location` component with a different
|
||||
// type than the `.physics2d` module's `.location` component if you desire.
|
||||
|
||||
const r = text_mod.state.regions.get('?').?;
|
||||
const player = try engine.newEntity();
|
||||
try sprite_mod.set(player, .transform, Mat4x4.translate(vec3(-0.02, 0, 0)));
|
||||
try sprite_mod.set(player, .size, vec2(@floatFromInt(r.width), @floatFromInt(r.height)));
|
||||
try sprite_mod.set(player, .uv_transform, Mat3x3.translate(vec2(@floatFromInt(r.x), @floatFromInt(r.y))));
|
||||
try sprite_mod.set(player, .pipeline, @intFromEnum(Pipeline.text));
|
||||
try sprite_mod.send(.updated, .{@intFromEnum(Pipeline.text)});
|
||||
|
||||
game.state = .{
|
||||
.timer = try mach.Timer.start(),
|
||||
.spawn_timer = try mach.Timer.start(),
|
||||
.player = player,
|
||||
.fps_timer = try mach.Timer.start(),
|
||||
.frame_count = 0,
|
||||
.sprites = 0,
|
||||
.rand = std.rand.DefaultPrng.init(1337),
|
||||
.time = 0,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn tick(
|
||||
engine: *mach.Engine.Mod,
|
||||
sprite_mod: *Sprite.Mod,
|
||||
text_mod: *Text.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_transform = sprite_mod.get(game.state.player, .transform).?;
|
||||
var player_pos = player_transform.translation();
|
||||
if (!spawning and game.state.spawn_timer.read() > 1.0 / 60.0) {
|
||||
// Spawn new entities
|
||||
_ = game.state.spawn_timer.lap();
|
||||
for (0..50) |_| {
|
||||
var new_pos = player_pos;
|
||||
new_pos.v[0] += game.state.rand.random().floatNorm(f32) * 25;
|
||||
new_pos.v[1] += game.state.rand.random().floatNorm(f32) * 25;
|
||||
|
||||
const rand_index = game.state.rand.random().intRangeAtMost(usize, 0, text_mod.state.regions.count() - 1);
|
||||
const r = text_mod.state.regions.entries.get(rand_index).value;
|
||||
|
||||
const new_entity = try engine.newEntity();
|
||||
try sprite_mod.set(new_entity, .transform, Mat4x4.translate(new_pos).mul(&Mat4x4.scaleScalar(0.3)));
|
||||
try sprite_mod.set(new_entity, .size, vec2(@floatFromInt(r.width), @floatFromInt(r.height)));
|
||||
try sprite_mod.set(new_entity, .uv_transform, Mat3x3.translate(vec2(@floatFromInt(r.x), @floatFromInt(r.y))));
|
||||
try sprite_mod.set(new_entity, .pipeline, @intFromEnum(Pipeline.text));
|
||||
game.state.sprites += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Multiply by delta_time to ensure that movement is the same speed regardless of the frame rate.
|
||||
const delta_time = game.state.timer.lap();
|
||||
|
||||
// Animate entities
|
||||
var archetypes_iter = engine.entities.query(.{ .all = &.{
|
||||
.{ .mach_gfx_sprite = &.{.transform} },
|
||||
} });
|
||||
while (archetypes_iter.next()) |archetype| {
|
||||
const ids = archetype.slice(.entity, .id);
|
||||
const transforms = archetype.slice(.mach_gfx_sprite, .transform);
|
||||
for (ids, transforms) |id, *old_transform| {
|
||||
var location = old_transform.translation();
|
||||
if (location.x() < -@as(f32, @floatFromInt(core.size().width)) / 1.5 or location.x() > @as(f32, @floatFromInt(core.size().width)) / 1.5 or location.y() < -@as(f32, @floatFromInt(core.size().height)) / 1.5 or location.y() > @as(f32, @floatFromInt(core.size().height)) / 1.5) {
|
||||
try engine.entities.remove(id);
|
||||
game.state.sprites -= 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
var transform = Mat4x4.ident;
|
||||
transform = transform.mul(&Mat4x4.scale(Vec3.splat(1.0 + (0.2 * delta_time))));
|
||||
transform = transform.mul(&Mat4x4.translate(location));
|
||||
transform = transform.mul(&Mat4x4.rotateZ(2 * math.pi * game.state.time));
|
||||
transform = transform.mul(&Mat4x4.scale(Vec3.splat(@max(math.cos(game.state.time / 2.0), 0.2))));
|
||||
|
||||
// TODO: .set() API is substantially slower due to internals
|
||||
// try sprite_mod.set(id, .transform, transform);
|
||||
old_transform.* = transform;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the player position, by moving in the direction the player wants to go
|
||||
// by the speed amount.
|
||||
const speed = 200.0;
|
||||
player_pos.v[0] += direction.x() * speed * delta_time;
|
||||
player_pos.v[1] += direction.y() * speed * delta_time;
|
||||
player_transform = Mat4x4.translate(player_pos).mul(
|
||||
&Mat4x4.scale(Vec3.splat(1.0)),
|
||||
);
|
||||
try sprite_mod.set(game.state.player, .transform, player_transform);
|
||||
|
||||
try sprite_mod.send(.updated, .{@intFromEnum(Pipeline.text)});
|
||||
|
||||
// Perform pre-render work
|
||||
try sprite_mod.send(.preRender, .{@intFromEnum(Pipeline.text)});
|
||||
|
||||
// Render a frame
|
||||
try engine.send(.beginPass, .{gpu.Color{ .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 }});
|
||||
try sprite_mod.send(.render, .{@intFromEnum(Pipeline.text)});
|
||||
try engine.send(.endPass, .{});
|
||||
try engine.send(.present, .{}); // Present the frame
|
||||
|
||||
// Every second, update the window title with the FPS
|
||||
if (game.state.fps_timer.read() >= 1.0) {
|
||||
try core.printTitle("gfx.Sprite example [ FPS: {d} ] [ Sprites: {d} ]", .{ game.state.frame_count, game.state.sprites });
|
||||
game.state.fps_timer.reset();
|
||||
game.state.frame_count = 0;
|
||||
}
|
||||
game.state.frame_count += 1;
|
||||
game.state.time += delta_time;
|
||||
}
|
||||
123
examples/glyphs/Text.zig
Normal file
123
examples/glyphs/Text.zig
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
const mach = @import("mach");
|
||||
const gpu = mach.gpu;
|
||||
const ecs = mach.ecs;
|
||||
const ft = @import("freetype");
|
||||
const std = @import("std");
|
||||
const assets = @import("assets");
|
||||
|
||||
pub const name = .game_text;
|
||||
pub const Mod = mach.Mod(@This());
|
||||
|
||||
const RegionMap = std.AutoArrayHashMapUnmanaged(u21, mach.gfx.Atlas.Region);
|
||||
|
||||
texture_atlas: mach.gfx.Atlas,
|
||||
texture: *gpu.Texture,
|
||||
ft: ft.Library,
|
||||
face: ft.Face,
|
||||
regions: RegionMap = .{},
|
||||
|
||||
pub fn deinit(
|
||||
engine: *mach.Engine.Mod,
|
||||
text_mod: *Mod,
|
||||
) !void {
|
||||
text_mod.state.texture_atlas.deinit(engine.allocator);
|
||||
text_mod.state.texture.release();
|
||||
text_mod.state.face.deinit();
|
||||
text_mod.state.ft.deinit();
|
||||
text_mod.state.regions.deinit(engine.allocator);
|
||||
}
|
||||
|
||||
pub const local = struct {
|
||||
pub fn init(
|
||||
engine: *mach.Engine.Mod,
|
||||
text_mod: *Mod,
|
||||
) !void {
|
||||
const device = engine.state.device;
|
||||
|
||||
// rgba32_pixels
|
||||
const img_size = gpu.Extent3D{ .width = 1024, .height = 1024 };
|
||||
|
||||
// Create a GPU texture
|
||||
const texture = device.createTexture(&.{
|
||||
.size = img_size,
|
||||
.format = .rgba8_unorm,
|
||||
.usage = .{
|
||||
.texture_binding = true,
|
||||
.copy_dst = true,
|
||||
.render_attachment = true,
|
||||
},
|
||||
});
|
||||
|
||||
var s = &text_mod.state;
|
||||
s.texture = texture;
|
||||
s.texture_atlas = try mach.gfx.Atlas.init(
|
||||
engine.allocator,
|
||||
img_size.width,
|
||||
.rgba,
|
||||
);
|
||||
|
||||
// TODO: state fields' default values do not work
|
||||
s.regions = .{};
|
||||
|
||||
s.ft = try ft.Library.init();
|
||||
s.face = try s.ft.createFaceMemory(assets.roboto_medium_ttf, 0);
|
||||
|
||||
try text_mod.send(.prepare, .{&[_]u21{ '?', '!', 'a', 'b', '#', '@', '%', '$', '&', '^', '*', '+', '=', '<', '>', '/', ':', ';', 'Q', '~' }});
|
||||
}
|
||||
|
||||
pub fn prepare(
|
||||
engine: *mach.Engine.Mod,
|
||||
text_mod: *Mod,
|
||||
codepoints: []const u21,
|
||||
) !void {
|
||||
const device = engine.state.device;
|
||||
const queue = device.getQueue();
|
||||
var s = &text_mod.state;
|
||||
|
||||
for (codepoints) |codepoint| {
|
||||
const font_size = 48 * 1;
|
||||
try s.face.setCharSize(font_size * 64, 0, 50, 0);
|
||||
try s.face.loadChar(codepoint, .{ .render = true });
|
||||
const glyph = s.face.glyph();
|
||||
const metrics = glyph.metrics();
|
||||
|
||||
const glyph_bitmap = glyph.bitmap();
|
||||
const glyph_width = glyph_bitmap.width();
|
||||
const glyph_height = glyph_bitmap.rows();
|
||||
|
||||
// Add 1 pixel padding to texture to avoid bleeding over other textures
|
||||
const margin = 1;
|
||||
const glyph_data = try engine.allocator.alloc([4]u8, (glyph_width + (margin * 2)) * (glyph_height + (margin * 2)));
|
||||
defer engine.allocator.free(glyph_data);
|
||||
const glyph_buffer = glyph_bitmap.buffer().?;
|
||||
for (glyph_data, 0..) |*data, i| {
|
||||
const x = i % (glyph_width + (margin * 2));
|
||||
const y = i / (glyph_width + (margin * 2));
|
||||
if (x < margin or x > (glyph_width + margin) or y < margin or y > (glyph_height + margin)) {
|
||||
data.* = [4]u8{ 0, 0, 0, 0 };
|
||||
} else {
|
||||
const alpha = glyph_buffer[((y - margin) * glyph_width + (x - margin)) % glyph_buffer.len];
|
||||
data.* = [4]u8{ 0, 0, 0, alpha };
|
||||
}
|
||||
}
|
||||
var glyph_atlas_region = try s.texture_atlas.reserve(engine.allocator, glyph_width + (margin * 2), glyph_height + (margin * 2));
|
||||
s.texture_atlas.set(glyph_atlas_region, @as([*]const u8, @ptrCast(glyph_data.ptr))[0 .. glyph_data.len * 4]);
|
||||
|
||||
glyph_atlas_region.x += margin;
|
||||
glyph_atlas_region.y += margin;
|
||||
glyph_atlas_region.width -= margin * 2;
|
||||
glyph_atlas_region.height -= margin * 2;
|
||||
|
||||
try s.regions.put(engine.allocator, codepoint, glyph_atlas_region);
|
||||
_ = metrics;
|
||||
}
|
||||
|
||||
// rgba32_pixels
|
||||
const img_size = gpu.Extent3D{ .width = 1024, .height = 1024 };
|
||||
const data_layout = gpu.Texture.DataLayout{
|
||||
.bytes_per_row = @as(u32, @intCast(img_size.width * 4)),
|
||||
.rows_per_image = @as(u32, @intCast(img_size.height)),
|
||||
};
|
||||
queue.writeTexture(&.{ .texture = s.texture }, &data_layout, &img_size, s.texture_atlas.data);
|
||||
}
|
||||
};
|
||||
16
examples/glyphs/main.zig
Normal file
16
examples/glyphs/main.zig
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// Experimental ECS app example. Not yet ready for actual use.
|
||||
const mach = @import("mach");
|
||||
|
||||
const Game = @import("Game.zig");
|
||||
const Text = @import("Text.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,
|
||||
mach.gfx.Sprite,
|
||||
Text,
|
||||
Game,
|
||||
};
|
||||
|
||||
pub const App = mach.App;
|
||||
Loading…
Add table
Add a link
Reference in a new issue