const std = @import("std"); const rl = @import("raylib"); const c = @import("common/constants.zig"); const st = @import("common/structures.zig"); const ut = @import("common/utils.zig"); const Road = @import("infrastructure/road.zig").Road; const Node = @import("infrastructure/node.zig").Node; const Car = @import("vehicles/car.zig").Car; const NodeManager = @import("infrastructure/node_manager.zig").NodeManager; const RoadManager = @import("infrastructure/road_manager.zig").RoadManager; const CarManager = @import("vehicles/car_manager.zig").CarManager; pub const Simulator = struct { /// allocator for convenience allocator: std.mem.Allocator, /// 'class' tracking all the nodes (and appropriate functions) node_man: NodeManager, /// 'class' tracking all the roads (and appropriate functions) road_man: RoadManager, /// 'class' tracking all the cars (and appropriate functions) car_man: CarManager, // vars /// Tracks whether next road will start building from the node the last road was built at auto_continue: bool, /// Tracks whether the system will delete the road cursor is pointed at /// (in such case, the road-to-be-deleted will also be highlighted) delete_mode: bool, /// Tracks whether highlighting all entities that are connected to hovered entity is enabled /// /// For example, if I hover over a node it will highlight all roads that are connected to it; /// Same goes for hovering over a road or in the future, a car (might show destination and path to it) /// /// Note: It only works outside of the delete mode show_connections: bool, /// Toggle that tracks whether ID (or possibly something more in the future) of every entity is displayed in GUI display_entity_info: bool, /// Entity (car/road/node) that is highlighed (hovered over by a mouse) highlighted_entity: ?st.Entity, /// Interface for RNG random: std.Random, /// Constructor for convenience pub fn init(new_allocator: std.mem.Allocator, rand_impl: *const std.Random.IoSource) Simulator { return .{ .allocator = new_allocator, .node_man = .init(), .road_man = .init(), .car_man = .init(), .auto_continue = false, .delete_mode = false, .show_connections = false, .display_entity_info = false, .highlighted_entity = null, .random = rand_impl.interface(), }; } /// Deinitialisation of node and road objects pub fn deinit(self: *Simulator) !void { self.car_man.deinit(self.allocator); self.road_man.deinit(self.allocator); try self.node_man.deinit(self.allocator); } /// Main draw function exposed to RayLib's loop pub fn draw(self: *const Simulator, pos: rl.Vector2) void { rl.clearBackground(c.BACKGROUND_COLOR); var highlighted_road: ?*Road = null; if (self.delete_mode) { if (self.highlighted_entity) |entity| { if (entity == .road) highlighted_road = entity.road; } } self.road_man.draw(highlighted_road, self.display_entity_info); self.node_man.draw(pos, self.display_entity_info); self.car_man.draw(self.display_entity_info); self.drawRelatedSelectedEntities(); } fn drawRelatedSelectedEntities(self: *const Simulator) void { if (!self.show_connections or self.highlighted_entity == null) return; const h_entity = self.highlighted_entity.?; switch (h_entity) { .node => { const node = h_entity.node; for (node.roads.items) |road| { road.draw(true, self.display_entity_info); } node.draw(c.NODE_RELATED_COLOUR, self.display_entity_info); }, .road => { const road = h_entity.road; road.draw(true, self.display_entity_info); road.nodes[0].draw(c.NODE_RELATED_COLOUR, self.display_entity_info); road.nodes[1].draw(c.NODE_RELATED_COLOUR, self.display_entity_info); }, .car => { // TODO draw the origin and destination, connected by the pathfinding route } } } /// Update tick pub fn update(self: *Simulator, pos: rl.Vector2) void { self.updateHighlightedEntity(pos); } /// Exposed input handling function exposed to raylib pub fn handleInput(self: *Simulator, pos: rl.Vector2) void { self.handleKeyboardInput(); self.handleMouseInput(pos); } /// Sub input handling function for keyboard input only fn handleKeyboardInput(self: *Simulator) void { self.auto_continue = rl.isKeyDown(.left_control); self.delete_mode = rl.isKeyDown(.left_shift); self.show_connections = rl.isKeyDown(.left_alt) and !self.delete_mode; if (rl.isKeyReleased(.n)) self.createCar(); if (rl.isKeyReleased(.tab)) self.display_entity_info = !self.display_entity_info; if (rl.isKeyReleased(.c)) self.clear() catch |err| { std.debug.panic("Failed to clear the entities: {}\n", .{err}); }; } /// Sub input handling function for mouse input only fn handleMouseInput(self: *Simulator, pos: rl.Vector2) void { if (rl.isMouseButtonReleased(.left)) { self.leftClickEvent(pos); return; } if (rl.isMouseButtonReleased(.right)) self.node_man.deleteTempNode(self.allocator); } /// Function that handles functionality that executes upon left click fn leftClickEvent(self: *Simulator, pos: rl.Vector2) void { if (self.delete_mode and self.highlighted_entity != null and self.highlighted_entity.? == .road) { self.deleteRoad() catch |err| { std.debug.panic("Failed to delete the road: {}\n", .{err}); }; return; } self.createRoad(pos); } /// User initiated road building functionality fn createRoad(self: *Simulator, pos: rl.Vector2) void { if (self.show_connections) return; const cur_node = self.node_man.getSelectedNode(self.allocator, pos) catch |err| { std.debug.panic("Failed to append the newly created node at pos ({d}, {d}) to node list: {}\n", .{ pos.x, pos.y, err }); }; if (self.node_man.temp_node) |temp| { // Prevents the road from being attached to 2 identical nodes (0 length road) if (temp.id == cur_node.id) return; const intersections = self.getIntersectingRoads(self.allocator, temp, cur_node) catch |err| { std.debug.panic("Intersection selection failure: {}\n", .{err}); }; defer self.allocator.free(intersections); self.splitRoadsByIntersections(intersections, temp, cur_node); self.node_man.temp_node = if (self.auto_continue) cur_node else null; return; } self.node_man.temp_node = cur_node; } /// User initiated road destroying functionality fn deleteRoad(self: *Simulator) !void { // We can trust this because this only gets called if valid and if type is road std.debug.assert(self.highlighted_entity != null and self.highlighted_entity.? == .road); const h_road = self.highlighted_entity.?.road; const start_node = h_road.nodes[0]; const end_node = h_road.nodes[1]; try self.road_man.deleteRoad(self.allocator, h_road); if (start_node.roads.items.len == 0) { const cars = try self.car_man.getCarsOnInf(self.allocator, .{ .node = start_node }); defer self.allocator.free(cars); // TODO replace with removeMultipleCars for (self.car_man.cars.items) |car| { try self.car_man.removeCar(self.allocator, car); } try self.node_man.removeNode(self.allocator, start_node); } if (end_node.roads.items.len == 0) { // TODO same as above try self.node_man.removeNode(self.allocator, end_node); // TODO after this is done, do the same with the function that removes roads } } /// Clearing node and road lists without deinitialising them (only the children) fn clear(self: *Simulator) !void { self.highlighted_entity = null; self.car_man.clear(self.allocator); self.road_man.clear(self.allocator); try self.node_man.clear(self.allocator); } /// Updates the variable that tracks the highlighted entity fn updateHighlightedEntity(self: *Simulator, pos: rl.Vector2) void { if (self.node_man.getHighlightedNode(pos)) |node| { self.highlighted_entity = .{ .node = node }; return; } if (self.road_man.getHighlightedRoad(pos)) |road| { self.highlighted_entity = .{ .road = road }; return; } self.highlighted_entity = null; } /// Returns array of IntersectionData struct, containing pointers to roads that got intersected and exact position fn getIntersectingRoads(self: *const Simulator, allocator: std.mem.Allocator, start: *const Node, end: *const Node) ![]st.IntersectionData { var intersections: std.ArrayList(st.IntersectionData) = .empty; var collision_point: rl.Vector2 = undefined; var start_node_collision: ?*Road = null; var end_node_collision: ?*Road = null; // Here we will check if any road collides with start and end node for (self.road_man.roads.items) |road| { if (start_node_collision == null and road.collides(start.pos) and !start.roadsContains(road)) start_node_collision = road; if (end_node_collision == null and road.collides(end.pos) and !end.roadsContains(road)) end_node_collision = road; if (start_node_collision != null and end_node_collision != null) break; } // if road node is placed on the road it is added as a collision with said road if (start_node_collision) |road| { try intersections.append(self.allocator, .{ .road = road, .pos = start.pos, .origin = true, }); } outer: for (self.road_man.roads.items) |road| { if (!rl.checkCollisionLines( start.pos,end.pos, road.nodes[0].pos, road.nodes[1].pos, &collision_point)) continue; const intersection = st.IntersectionData { .road = road, .pos = collision_point, .origin = false, }; // We put a 0 here, just to satisfy the constructor function, // it is not getting appended to the node list anyways const node: Node = .init(0, intersection.pos); // If the newly acquired intersection node is within the snapping radius of already existing nodes, // we don't add it to the list for (intersections.items) |inter_collision| { if (node.withinSnapRadius(inter_collision.pos)) continue :outer; } // If there is an existing node that covers our position within its snapping radius, // then such position will not be saved as intersection if (self.node_man.getNodeIfExists(node.pos) != null) continue; try intersections.append(allocator, intersection); } // if end node is placed on the road it is added as a collision with said road if (end_node_collision) |road| { try intersections.append(self.allocator, .{ .road = road, .pos = end.pos, .origin = true, }); } const sorted_intersection = try intersections.toOwnedSlice(allocator); std.sort.block(st.IntersectionData, sorted_intersection, start, ut.compareIntersections); return sorted_intersection; } /// Takes the data about intersections and adds new nodes there alongside with linking existing roads to them /// /// Important: This function assumes the intersection array is sorted by distance from the start node (ascending) fn splitRoadsByIntersections(self: *Simulator, intersections: []st.IntersectionData, start: *Node, end: *Node) void { if (intersections.len == 0) { self.road_man.addRoad(self.allocator, start, end) catch |err| { std.debug.panic("Failed creating the road out of origin nodes: {}\n", .{err}); }; return; } const first_node = self.node_man.getSelectedNode(self.allocator, intersections[0].pos) catch |err| { std.debug.panic("Failed to add the first node of the intersection: {}\n", .{err}); }; var override_node: ?*Node = null; // This if statement essentially checks that IF we only have one intersection and that one is one of the origin nodes, // it means that we have to enable one of start => intersection, or, end => intersection road building logic // // However due to the possibility that we link the road to itself (intersection[0] is start that we then connect // that one to start node; so intersection[0] => start = start => start), // we have to essentially realise which node is that first intersection and essentially store that info and only // let the opposite node form a road with the intersection // and that is what override_node, override_start and override_end variables are all about if (intersections.len == 1 and intersections[0].origin) { override_node = if (first_node == start) end else start; } const override_start = override_node != null and override_node.? == start; if (!intersections[0].origin or override_start) { // Here we connect the start node with the first intersection node (via road) self.road_man.addRoad(self.allocator, start, first_node) catch |err| { std.debug.panic("Failed to add a road of origin (start) node and the first intersection node: {}\n", .{err}); }; } for (0..intersections.len) |i| { const intersection = intersections[i]; // The node created at the point of intersection const new_node = self.node_man.getSelectedNode(self.allocator, intersection.pos) catch |err| { std.debug.panic("Failed to create a node based on the intersection index {d}: {}\n", .{ i, err }); }; // Pointer to the node that borders the road that was intersected // This node and the new_node will become nodes for the new road being created const old_node_of_road = intersection.road.nodes[1]; // The old road that was intersected now borders the new node // and the old node is removed from the road's end node reference, // as is the end node's road reference // So the intersected road loses old node (at the far end) and gets new node that intersects it intersection.road.updateNodeReference(old_node_of_road, new_node) catch |err| { std.debug.panic("Failed to update the road's node references: {}\n", .{err}); }; // Now the old node must not point at the intersection road old_node_of_road.unreferenceRoad(intersection.road) catch |err| { std.debug.panic("Failed to unreference the intersection road from the old node: {}\n", .{err}); }; new_node.referenceRoad(self.allocator, intersection.road) catch |err| { std.debug.panic("Failed to reference the intersection road to the intersecting node: {}\n", .{err}); }; // Now we add the road (to the road list) and references the road at both bounding nodes self.road_man.addRoad(self.allocator, new_node, old_node_of_road) catch |err| { std.debug.panic("Failed to create a road of new node and former node of prior intersecting road: {}\n", .{ err }); }; // Here we work on creating new roads between intersection nodes and as such because we need nodes // at 2 different intersections, it means we have to be sure next one exists if (i == intersections.len - 1) continue; const next_intersection = self.node_man.getSelectedNode(self.allocator, intersections[i+1].pos) catch |err| { std.debug.panic("Failed to create node of next intersection (current index={d}: {}\n", .{i, err}); }; // Creating the road connecting current intersection with the next one self.road_man.addRoad(self.allocator, new_node, next_intersection) catch |err| { std.debug.panic("Failed to create the road of current and next intersection nodes: {}\n", .{err}); }; } const override_end = override_node != null and override_node.? == end; // Finally we create final road by connecting last intersection node to the end origin node const final_intersection = intersections[intersections.len - 1]; const final_intersection_node = self.node_man.getSelectedNode(self.allocator, final_intersection.pos) catch |err| { std.debug.panic("Failed to create node based on last intersection position: {}\n", .{err}); }; if (final_intersection.origin and !override_end) return; self.road_man.addRoad(self.allocator, final_intersection_node, end) catch |err| { std.debug.panic("Failed to create a road of final intersection and end origin node: {}\n", .{err}); }; } /// Creates a car and calls fn createCar(self: *Simulator) void { const nodes_len = self.node_man.nodes.items.len; if (nodes_len == 0) return; // Grab random node const i = self.random.uintLessThan(usize, nodes_len); const ref_node = self.node_man.nodes.items[i]; self.car_man.addCar(self.allocator, ref_node) catch |err| { std.debug.panic("Unable to create a car or append it to the list of cars: {}\n", .{err}); }; } };