diff --git a/zig-ecs/build.zig b/zig-ecs/build.zig index 92cdbb0..50d6f2a 100644 --- a/zig-ecs/build.zig +++ b/zig-ecs/build.zig @@ -5,6 +5,7 @@ pub fn build(b: *Builder) void { const buildMode = b.standardReleaseOptions(); const examples = [_][2][]const u8{ + [_][]const u8{ "group_sort", "examples/group_sort.zig" }, [_][]const u8{ "view_vs_group", "examples/view_vs_group.zig" }, [_][]const u8{ "simple", "examples/simple.zig" }, }; diff --git a/zig-ecs/examples/group_sort.zig b/zig-ecs/examples/group_sort.zig new file mode 100644 index 0000000..d383f29 --- /dev/null +++ b/zig-ecs/examples/group_sort.zig @@ -0,0 +1,67 @@ +const std = @import("std"); +const ecs = @import("ecs"); + +// override the EntityTraits used by ecs +pub const EntityTraits = ecs.EntityTraitsType(.medium); + +pub const Velocity = struct { x: f32, y: f32 }; +pub const Position = struct { x: f32, y: f32 }; + +const total_entities: usize = 10000; + +/// logs the timing for views vs non-owning groups vs owning groups with 1,000,000 entities +pub fn main() !void { + var reg = ecs.Registry.init(std.heap.c_allocator); + defer reg.deinit(); + + var timer = try std.time.Timer.start(); + + createEntities(®); + owningGroup(®); +} + +fn createEntities(reg: *ecs.Registry) void { + var r = std.rand.DefaultPrng.init(666); + + var timer = std.time.Timer.start() catch unreachable; + var i: usize = 0; + while (i < total_entities) : (i += 1) { + var e1 = reg.create(); + reg.add(e1, Position{ .x = 1, .y = r.random.float(f32) * 100 }); + reg.add(e1, Velocity{ .x = 1, .y = r.random.float(f32) * 100 }); + } + + var end = timer.lap(); + std.debug.warn("create entities: {d}\n", .{@intToFloat(f64, end) / 1000000000}); +} + +fn owningGroup(reg: *ecs.Registry) void { + var group = reg.group(.{ Velocity, Position }, .{}, .{}); + + // var group_iter = group.iterator(struct { vel: *Velocity, pos: *Position }); + // while (group_iter.next()) |e| { + // std.debug.warn("pos.y {d:.3}, ent: {}\n", .{e.pos.y, group_iter.entity()}); + // } + + const SortContext = struct { + fn sort(this: void, a: Position, b: Position) bool { + return a.y < b.y; + } + }; + + var timer = std.time.Timer.start() catch unreachable; + group.sort(Position, {}, SortContext.sort); + var end = timer.lap(); + std.debug.warn("group (sort): {d}\n", .{@intToFloat(f64, end) / 1000000000}); + + timer.reset(); + group.sort(Position, {}, SortContext.sort); + end = timer.lap(); + std.debug.warn("group (sort 2): {d}\n", .{@intToFloat(f64, end) / 1000000000}); + + + // var group_iter2 = group.iterator(struct { vel: *Velocity, pos: *Position }); + // while (group_iter2.next()) |e| { + // std.debug.warn("pos.y {d:.3}, ent: {}\n", .{e.pos.y, group_iter2.entity()}); + // } +}