const std = @import("std"); const rl = @import("raylib"); const c = @import("../constants.zig"); const Node = @import("node.zig").Node; pub const NodeManager = struct { temp_node: ?*Node, nodes: std.ArrayList(Node), pub fn init(allocator: std.mem.Allocator) !NodeManager { return .{ .temp_node = null, .nodes = try .initCapacity(allocator, c.ALLOC_SIZE), }; } pub fn deinit(self: *NodeManager, allocator: std.mem.Allocator) void { for (self.nodes.items) |*node| { node.deinit(allocator); } self.nodes.deinit(allocator); } pub fn draw(self: *const NodeManager, display_details: bool) void { for (self.nodes.items) |node| { rl.drawCircleV(node.pos, c.NODE_RADIUS, .brown); } const pos = rl.getMousePosition(); if (self.temp_node) |node| { if (display_details) rl.drawCircleV(node.pos, c.NODE_SNAP_RADIUS * c.NODE_RADIUS, .pink); rl.drawLineEx(node.pos, pos, c.ROAD_SIZE, .black); rl.drawCircleV(node.pos, c.NODE_RADIUS, .brown); rl.drawCircleV(pos, c.NODE_RADIUS, .blue); } } pub fn add(self: *NodeManager, pos: rl.Vector2) ?*Node { const pos_node = self.getSelectedNode(pos); if (self.temp_node) |_| { return pos_node; } self.temp_node = pos_node; return null; } fn getSelectedNode(self: *NodeManager, pos: rl.Vector2) *Node { for (self.nodes.items) |*node| { if (!rl.checkCollisionPointCircle(pos, node.pos, c.NODE_SNAP_RADIUS * c.NODE_RADIUS)) continue; return node; } // We couldn't find the existing node and as such must create a new one const node: Node = .init(self.getNewID(), pos); self.nodes.appendBounded(node) catch |err| { std.debug.panic("This is because preallocated size got exceeded, TODO fix:\n{}\n", .{err}); }; return self.getLastRef().?; } fn getNewID(self: *const NodeManager) usize { const last_ref = self.getLastRef(); return if (last_ref) |ref| ref.*.id + 1 else 0; } fn getLastRef(self: *const NodeManager) ?*Node { const nlen = self.nodes.items.len; return if (nlen == 0) null else &self.nodes.items[nlen - 1]; } };