Compare commits

24 Commits

Author SHA1 Message Date
eca857cda1 Implementation of car removal when infrastructure where car is located gets removed itself 2026-05-02 20:48:25 +02:00
439482e5a1 Car fundamentals implemented 2026-05-02 18:59:24 +02:00
3e6438418b Implemented basic car support, and restructured few tests and other errors; errors when rng gets called TODO fix 2026-05-02 08:55:18 +02:00
b388b1e08e Finishing the renaming changes 2026-05-01 21:47:46 +02:00
4f62d5eb4c Project renamed from 'base-road-network' to 'traffic-simulator' 2026-05-01 21:41:57 +02:00
3274692631 Removed debug code 2026-05-01 21:09:17 +02:00
1558d5f57c Merge branch 'feature/road-splitting' 2026-05-01 21:07:16 +02:00
fdf672de4b Fixed splitting quirks when only one intersection is found and the intersection itself is origin node 2026-05-01 20:46:09 +02:00
f7a1340500 Fixed the issue of newly built intersecting node not connecting to all existing (intersecting) roads 2026-05-01 19:03:31 +02:00
dd64ec648a Splitting function completed 2026-05-01 17:44:30 +02:00
afd7aa50c4 Added comments and slightly refactored code for deletion of temp node 2026-05-01 16:44:52 +02:00
643712f529 Basic Entity ID display for debugging 2026-05-01 16:34:25 +02:00
2a3064b0fe Improvement to intersection data calculation 2026-05-01 14:46:30 +02:00
e475814c85 Changed resolution, switched to LLVM backend, from selfhosted one 2026-05-01 12:54:41 +02:00
c02b2a5121 Changed resolution and set the LLVM backend because bleeding edge language on bleeding edge system is fun >:) 2026-05-01 12:53:42 +02:00
680e07c976 Splitting road implementation preparation 2026-05-01 09:11:39 +02:00
5040bbbe47 Implemented function which gets all roads that get intersected by new road and returns them and the exact pos of intersection 2026-04-30 22:23:09 +02:00
0d77c912a8 Implemented right click functionality 2026-04-30 08:00:14 +02:00
e72aa8fc5f Road splitting setup (intersection data) 2026-04-29 23:57:23 +02:00
4ec32252cf Implemented relations displaying mode 2026-04-29 23:23:20 +02:00
fc0341d9ad Adjusted variables and comments 2026-04-29 21:48:35 +02:00
081e690dc3 Added comments to new functions 2026-04-29 21:47:17 +02:00
e75fc6dbe9 Implemented Entity tagged union for highlighted entity (similar to abstract class in some ways) 2026-04-29 21:45:56 +02:00
7348861145 Using implicit pointer derefs + fixing crashes on clearing entities 2026-04-29 17:16:12 +02:00
15 changed files with 725 additions and 142 deletions

View File

@@ -28,7 +28,7 @@ pub fn build(b: *std.Build) void {
// to our consumers. We must give it a name because a Zig package can expose
// multiple modules and consumers will need to be able to specify which
// module they want to access.
// const mod = b.addModule("base_road_network", .{
// const mod = b.addModule("traffic-simulator", .{
// // The root source file is the "entry point" of this module. Users of
// // this module will only be able to access public declarations contained
// // in this file, which means that if you have declarations that you
@@ -68,7 +68,8 @@ pub fn build(b: *std.Build) void {
// If neither case applies to you, feel free to delete the declaration you
// don't need and to put everything under a single module.
const exe = b.addExecutable(.{
.name = "base_road_network",
.name = "traffic-simulator",
.use_llvm = true,
.root_module = b.createModule(.{
// b.createModule defines a new module just like b.addModule but,
// unlike b.addModule, it does not expose the module to consumers of
@@ -83,12 +84,12 @@ pub fn build(b: *std.Build) void {
// List of modules available for import in source files part of the
// root module.
.imports = &.{
// Here "base_road_network" is the name you will use in your source code to
// import this module (e.g. `@import("base_road_network")`). The name is
// Here "traffic-simulator" is the name you will use in your source code to
// import this module (e.g. `@import("traffic-simulator")`). The name is
// repeated because you are allowed to rename your imports, which
// can be extremely useful in case of collisions (which can happen
// importing modules from different packages).
// .{ .name = "base_road_network", .module = mod },
// .{ .name = "traffic-simulator", .module = mod },
// Raylib import
.{ .name = "raylib", .module = raylib },
@@ -131,6 +132,7 @@ pub fn build(b: *std.Build) void {
}
const tests = b.addTest(.{
.use_llvm = true,
.root_module = b.createModule(.{
.root_source_file = b.path("src/test.zig"),
.target = target,

View File

@@ -6,7 +6,7 @@
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = .base_road_network,
.name = .traffic_simulator,
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
@@ -22,7 +22,7 @@
// original project's identity. Thus it is recommended to leave the comment
// on the following line intact, so that it shows up in code reviews that
// modify the field.
.fingerprint = 0x8da3e26c9def0629, // Changing this has security and trust implications.
.fingerprint = 0xf441f200e5d3277c, // Changing this has security and trust implications.
// Tracks the earliest Zig version that the package considers to be a
// supported use case.
.minimum_zig_version = "0.16.0",

View File

@@ -1,9 +1,9 @@
const clr = @import("raylib").Color;
/// Screen Width
pub const WIDTH = 1366;
pub const WIDTH = 1920;
/// Screen Height
pub const HEIGHT = 768;
pub const HEIGHT = 1080;
pub const BACKGROUND_COLOR = clr.light_gray;
/// Base node radius
@@ -16,6 +16,7 @@ pub const NODE_COLOUR = clr.brown;
pub const NODE_TEMP_COLOUR = clr.orange;
/// The colour of the node being at the cursor
pub const NODE_CURSOR_COLOUR = clr.blue;
pub const NODE_RELATED_COLOUR = clr.purple;
/// Road (line) size
pub const ROAD_SIZE = 20;
@@ -23,3 +24,12 @@ pub const ROAD_SIZE = 20;
pub const ROAD_COLOUR = clr.black;
/// Colour of the road that is highlighted
pub const ROAD_HIGHLIGHTED_COLOUR = clr.green;
/// Regular text size
pub const TEXT_SIZE = 50;
/// Text size that is used for displaying entity IDs
pub const ENTITY_DATA_TEXT_SIZE = TEXT_SIZE / 2;
/// Text colour in which entity IDs are displayed if toggled
pub const ENTITY_DATA_TEXT_COLOUR = clr.orange;
pub const CAR_SIZE = 20;

39
src/common/structures.zig Normal file
View File

@@ -0,0 +1,39 @@
const Vector2 = @import("raylib").Vector2;
const Road = @import("../infrastructure/road.zig").Road;
const Node = @import("../infrastructure/node.zig").Node;
const Car = @import("../vehicles/car.zig").Car;
/// This is a simple equivalent to something like abstract class, so the simulator class has only one variable
/// which tracks which object is highlighted and the logic that seeks to find the current highlighted class doesn't need
/// to figure out which highlighted entity has priority in case of overlap;
/// given that car can be on node and road, and node itself is on road(s)
///
/// TLDR: Can point to either `entity` type (node, road, etc.)
pub const Entity = union(enum) {
node: *Node,
road: *Road,
car: *Car,
};
/// Similar to `Entity` but only for infrastructure entities, so road and node only (for now)
pub const Infrastructure = union(enum) {
node: *const Node,
road: *const Road,
};
/// Represents intersection data, mainly used in cases where we draw over existing roads
/// and wish to see data about such intersections or collisions
pub const IntersectionData = struct {
/// Tracks the location of the intersection
pos: Vector2,
/// Points to the road where the intersection occured
road: *Road,
/// Tracks whether this intersection is actually an origin point
/// (In simple terms this means whether the point/node that intersects is also the start/end node)
///
/// We do this because the referencing logic is very strict and will return an error
/// if we try to reference something that is already referenced, due to stricter approach helping with
/// earlier bug and error detection
origin: bool,
};

29
src/common/utils.zig Normal file
View File

@@ -0,0 +1,29 @@
const Vector2 = @import("raylib").Vector2;
const st = @import("structures.zig");
const Node = @import("../infrastructure/node.zig").Node;
/// Returns distance between two nodes, used mostly for road length and possibly for A* heuristics
pub fn calculate_length(start: Vector2, end: Vector2) f32 {
const x_diff = end.x - start.x;
const y_diff = end.y - start.y;
const squared_solution = x_diff * x_diff + y_diff * y_diff;
return @sqrt(squared_solution);
}
/// Comparator function that compares intersection proximity from the node in order to aid the sorting function
pub fn compareIntersections(ctx: *const Node, inter_a: st.IntersectionData, inter_b: st.IntersectionData) bool {
const distance_a = ctx.getRelativeInterDistance(inter_a);
const distance_b = ctx.getRelativeInterDistance(inter_b);
return distance_a < distance_b;
}
/// Returns vector from P1 to P2
pub fn getVectorP1P2(p1: Vector2, p2: Vector2) Vector2 {
return .{
.x = p2.x - p1.x,
.y = p2.y - p1.y,
};
}

View File

@@ -1,8 +1,10 @@
const std = @import("std");
const rl = @import("raylib");
const c = @import("../constants.zig");
const e = @import("../errors.zig");
const c = @import("../common/constants.zig");
const e = @import("../common/errors.zig");
const st = @import("../common/structures.zig");
const ut = @import("../common/utils.zig");
const Road = @import("road.zig").Road;
pub const Node = struct {
@@ -33,17 +35,34 @@ pub const Node = struct {
}
/// Simple function which draws the node
pub fn draw(self: *const Node, direct_colour: ?rl.Color) void {
pub fn draw(self: *const Node, direct_colour: ?rl.Color, display_info: bool) void {
const colour = if (direct_colour) |clr| clr else c.NODE_COLOUR;
rl.drawCircleV(self.pos, c.NODE_RADIUS, colour);
if (!display_info) return;
var buf: [100]u8 = undefined;
const entity_info = std.fmt.bufPrintZ(&buf, "{d}", .{ self.id }) catch |err| {
std.debug.panic("Failed to allocate space for ID???: {}\n", .{ err });
};
const info_x = @as(i32, @trunc(self.pos.x)) - c.NODE_RADIUS / 2;
const info_y = @as(i32, @trunc(self.pos.y)) - c.NODE_RADIUS / 2;
rl.drawText(entity_info, info_x, info_y,
c.ENTITY_DATA_TEXT_SIZE, c.ENTITY_DATA_TEXT_COLOUR);
}
/// Identifies whether the pos (location) is within the snapping radius of the node
pub fn posWithinRadius(self: *const Node, pos: rl.Vector2) bool {
/// Determines whether the pos (location) is within the snapping radius of the node
pub fn withinSnapRadius(self: *const Node, pos: rl.Vector2) bool {
return rl.checkCollisionPointCircle(pos, self.pos, c.NODE_SNAP_RADIUS);
}
/// Determines whether the pos (location) is within the strict (visual representation) radius of the node
pub fn withinRadius(self: *const Node, pos: rl.Vector2) bool {
return rl.checkCollisionPointCircle(pos, self.pos, c.NODE_RADIUS);
}
/// Tries to reference the passed road to self
///
/// Returns an error if the passed road cannot be appended to the list or if said road is already in the list
@@ -71,6 +90,20 @@ pub const Node = struct {
return e.Entity.NotFound;
}
/// Returns distance between the node and intersection object location
pub fn getRelativeInterDistance(self: *const Node, intersection: st.IntersectionData) f32 {
return ut.calculate_length(intersection.pos, self.pos);
}
/// Searches for the road pointer within roads list
pub fn roadsContains(self: *const Node, road_to_search: *const Road) bool {
for (self.roads.items) |road| {
if (road == road_to_search) return true;
}
return false;
}
};
// TODO tests

View File

@@ -1,8 +1,8 @@
const std = @import("std");
const Vector2 = @import("raylib").Vector2;
const c = @import("../constants.zig");
const e = @import("../errors.zig");
const c = @import("../common/constants.zig");
const e = @import("../common/errors.zig");
const Node = @import("node.zig").Node;
const Road = @import("road.zig").Road;
@@ -26,15 +26,16 @@ pub const NodeManager = struct {
/// Deinitialises every node (pointer) within the list and then deinits the list containing the nodes itself
pub fn deinit(self: *NodeManager, allocator: std.mem.Allocator) !void {
for (self.nodes.items) |node| {
node.roads.clearRetainingCapacity();
try node.deinit(allocator);
}
self.nodes.deinit(allocator);
}
/// Regular draw function
pub fn draw(self: *const NodeManager, pos: Vector2) void {
pub fn draw(self: *const NodeManager, pos: Vector2, display_info: bool) void {
for (self.nodes.items) |node| {
node.draw(null);
node.draw(null, display_info);
}
if (self.temp_node) |node| {
@@ -42,18 +43,29 @@ pub const NodeManager = struct {
var cur_node = Node.init(0, pos);
// Temporary road that is to be drawn as one in the making
const road: Road = .init(0, node, &cur_node);
road.draw(false);
road.draw(false, false);
node.*.draw(c.NODE_TEMP_COLOUR);
cur_node.draw(c.NODE_CURSOR_COLOUR);
node.draw(c.NODE_TEMP_COLOUR, display_info);
cur_node.draw(c.NODE_CURSOR_COLOUR, false);
}
}
/// Tries to find a node which snapping radius covers the pos
///
/// If it does it returns a reference to it, otherwise null
pub fn getNodeIfExists(self: *const NodeManager, pos: Vector2) ?*Node {
for (self.nodes.items) |node| {
if (node.withinSnapRadius(pos)) return node;
}
return null;
}
/// Checks if there is a node pointer within the snap radius of pos coordinate;
/// otherwise creates a new node and returns its pointer
pub fn getSelectedNode(self: *NodeManager, allocator: std.mem.Allocator, pos: Vector2) !*Node {
for (self.nodes.items) |node| {
if (node.posWithinRadius(pos)) return node;
if (self.getNodeIfExists(pos)) |node| {
return node;
}
// No node is within that position, so we must create a new one
@@ -67,16 +79,15 @@ pub const NodeManager = struct {
/// Gets next id, resets only on clear()
fn getNextID(self: *NodeManager) usize {
const id = self.next_id;
self.next_id += 1;
return id;
defer self.next_id += 1;
return self.next_id;
}
/// Clears all existing nodes connected, not deinitialisation
pub fn clear(self: *NodeManager, allocator: std.mem.Allocator) !void {
self.temp_node = null;
for (self.nodes.items) |node| {
node.roads.clearRetainingCapacity();
try node.deinit(allocator);
}
self.nodes.clearRetainingCapacity();
@@ -84,9 +95,7 @@ pub const NodeManager = struct {
}
/// Deletes node, returns error if node still has road references
pub fn deleteNode(self: *NodeManager, allocator: std.mem.Allocator, node_to_delete: *Node) !void {
if (node_to_delete.roads.items.len != 0) return e.Entity.HasReferences;
pub fn removeNode(self: *NodeManager, allocator: std.mem.Allocator, node_to_delete: *Node) !void {
for (0..self.nodes.items.len) |i| {
if (self.nodes.items[i] != node_to_delete) continue;
@@ -97,6 +106,31 @@ pub const NodeManager = struct {
return e.Entity.NotFound;
}
/// Runs a scan through all the nodes and returns the reference to one that is within the radius
pub fn getHighlightedNode(self: *const NodeManager, pos: Vector2) ?*Node {
for (self.nodes.items) |node| {
if (node.withinRadius(pos)) return node;
}
return null;
}
/// Essentially what it does is it sets temp node pointer to null and
/// if the node it pointed at had no road references (essentially it was a new node for road building),
/// it deletes the node from the node list as well
pub fn deleteTempNode(self: *NodeManager, allocator: std.mem.Allocator) void {
if (self.temp_node == null) return;
const node = self.temp_node.?;
self.temp_node = null;
if (node.roads.items.len != 0) return;
self.removeNode(allocator, node) catch |err| {
std.debug.panic("Failed to delete the temporary node: {}\n", .{err});
};
}
};
const expect = std.testing.expect;
@@ -107,7 +141,9 @@ test "id tracking" {
const allocator = gpa.allocator();
var node_man: NodeManager = .init();
defer node_man.deinit(allocator);
defer node_man.deinit(allocator) catch |err| {
std.debug.panic("Failed to deinit nodemanager: {}\n", .{err});
};
const n = 5;
for (0..n) |_| {

View File

@@ -1,6 +1,9 @@
const rl = @import("raylib");
const c = @import("../constants.zig");
const c = @import("../common/constants.zig");
const e = @import("../common/errors.zig");
const st = @import("../common/structures.zig");
const ut = @import("../common/utils.zig");
const Node = @import("node.zig").Node;
pub const Road = struct {
@@ -19,7 +22,7 @@ pub const Road = struct {
.length = 0,
};
road.length = road.calculate_length();
road.length = ut.calculate_length(start.pos, end.pos);
return road;
}
@@ -33,8 +36,8 @@ pub const Road = struct {
const start = self.nodes[0];
const end = self.nodes[1];
const x_diff = end.*.pos.x - start.*.pos.x;
const y_diff = end.*.pos.y - start.*.pos.y;
const x_diff = end.pos.x - start.pos.x;
const y_diff = end.pos.y - start.pos.y;
const square_diff = x_diff * x_diff + y_diff * y_diff;
return @sqrt(square_diff);
@@ -44,9 +47,25 @@ pub const Road = struct {
///
/// In the future as we improve and make roads more complex with multiple lanes and such
/// it will gradually become more complex
pub fn draw(self: *const Road, highlighted: bool) void {
pub fn draw(self: *const Road, highlighted: bool, display_info: bool) void {
const colour = if (highlighted) c.ROAD_HIGHLIGHTED_COLOUR else c.ROAD_COLOUR;
rl.drawLineEx(self.nodes[0].*.pos, self.nodes[1].*.pos, c.ROAD_SIZE, colour);
rl.drawLineEx(self.nodes[0].pos, self.nodes[1].pos, c.ROAD_SIZE, colour);
if (!display_info) return;
var buf: [100]u8 = undefined;
const entity = std.fmt.bufPrintZ(&buf, "{d}", .{self.id}) catch |err| {
std.debug.panic("Could not allocate ID into string???: {}\n", .{err});
};
const distance = ut.getVectorP1P2(self.nodes[0].pos, self.nodes[1].pos);
const entity_info_pos: rl.Vector2 = .{
.x = self.nodes[0].pos.x + distance.x / 2 - c.ROAD_SIZE / 2,
.y = self.nodes[0].pos.y + distance.y / 2 - c.ROAD_SIZE / 2,
};
rl.drawText(entity, @trunc(entity_info_pos.x), @trunc(entity_info_pos.y),
c.ENTITY_DATA_TEXT_SIZE, c.ENTITY_DATA_TEXT_COLOUR);
}
/// Important: after this function executes, this road is no longer reachable from its bounding nodes
@@ -58,8 +77,22 @@ pub const Road = struct {
}
/// Checks whether pos coordinate is on the referenced road
pub fn isHighlighted(self: *const Road, pos: rl.Vector2) bool {
return rl.checkCollisionPointLine(pos, self.nodes[0].*.pos, self.nodes[1].*.pos, c.ROAD_SIZE);
pub fn collides(self: *const Road, pos: rl.Vector2) bool {
return rl.checkCollisionPointLine(pos, self.nodes[0].pos, self.nodes[1].pos, c.ROAD_SIZE);
}
/// Updates node reference old_node => new node; returns error if old_node does not exist
pub fn updateNodeReference(self: *Road, old_node: *Node, new_node: *Node) !void {
for (0..self.nodes.len) |i| {
if (self.nodes[i] != old_node) continue;
self.nodes[i] = new_node;
// As nodes change, road's length must be recalculated
self.length = ut.calculate_length(self.nodes[0].pos, self.nodes[1].pos);
return;
}
return e.Entity.NotFound;
}
};
@@ -67,28 +100,8 @@ const std = @import("std");
const expect = std.testing.expect;
test "valid road nodes" {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const start: Node = .init(34, .{.x = 500, .y = 500});
const start_ptr = try allocator.create(Node);
defer {
start_ptr.*.deinit(allocator);
allocator.destroy(start_ptr);
// TODO rewrite
}
start_ptr.* = start;
const end: Node = .init(227, .{.x = 600, .y = 500});
const end_ptr = try allocator.create(Node);
defer {
end_ptr.*.deinit(allocator);
allocator.destroy(end_ptr);
}
end_ptr.* = end;
const road: Road = .init(11, start_ptr, end_ptr);
try expect(road.nodes[0].id == 34);
try expect(road.nodes[1].id == 227);
}
// TODO tests
// test every case error for every function that can return an error

View File

@@ -1,19 +1,20 @@
const std = @import("std");
const rl = @import("raylib");
const e = @import("../errors.zig");
const e = @import("../common/errors.zig");
const st = @import("../common/structures.zig");
const ut = @import("../common/utils.zig");
const Road = @import("road.zig").Road;
const Node = @import("node.zig").Node;
pub const RoadManager = struct {
next_id: usize,
roads: std.ArrayList(*Road),
highlighted_road: ?*Road,
pub fn init() RoadManager {
return .{
.next_id = 0,
.roads = .empty,
.highlighted_road = null,
};
}
@@ -26,19 +27,18 @@ pub const RoadManager = struct {
}
/// Draws all the roads in the list, sends the information ahead whether the road drawn should be highlighted
pub fn draw(self: *const RoadManager, delete_mode: bool) void {
pub fn draw(self: *const RoadManager, highlighted_road: ?*Road, display_info: bool) void {
for (self.roads.items) |road| {
const is_highlighted = delete_mode and self.highlighted_road != null and self.highlighted_road.? == road;
road.draw(is_highlighted);
const is_highlighted = if (highlighted_road) |h_road| road == h_road else false;
road.draw(is_highlighted, display_info);
}
}
/// Function which creates the road object, its pointer, adds it to the list
/// and then also references that same road to the bounding nodes
pub fn addRoad(self: *RoadManager, allocator: std.mem.Allocator, start: *Node, end: *Node) !void {
const road: Road = .init(self.getNextID(), start, end);
const road_ptr = try allocator.create(Road);
road_ptr.* = road;
road_ptr.* = Road.init(self.getNextID(), start, end);
try self.roads.append(allocator, road_ptr);
const ref = self.roads.items[self.roads.items.len - 1];
@@ -48,10 +48,8 @@ pub const RoadManager = struct {
/// Returns the id, and increases it by one; used for generating ID's for new entities
fn getNextID(self: *RoadManager) usize {
const id = self.next_id;
self.next_id += 1;
return id;
defer self.next_id += 1;
return self.next_id;
}
/// Deinits all the roads, clears them but not deiniting the list itself; also resets the next ID var
@@ -85,16 +83,13 @@ pub const RoadManager = struct {
return e.Entity.NotFound;
}
/// Sets the pointer to the road that is intersection with pos coordinate
pub fn update_highlighted_road(self: *RoadManager, pos: Vector2) void {
/// Returns if pos is pointing at a road, or null if it isn't at any
pub fn getHighlightedRoad(self: *const RoadManager, pos: Vector2) ?*Road {
for (self.roads.items) |road| {
if (!road.isHighlighted(pos)) continue;
self.highlighted_road = road;
return;
if (road.collides(pos)) return road;
}
self.highlighted_road = null;
return null;
}
};
@@ -102,36 +97,7 @@ const Vector2 = @import("raylib").Vector2;
const expect = std.testing.expect;
test "id tracking" {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var road_man: RoadManager = .init();
defer road_man.deinit(allocator);
const n = 5;
const start: Node = .init(0, .{.x = 0, .y = 0});
const start_ptr = try allocator.create(Node);
start_ptr.* = start;
const end: Node = .init(1, .{.x = 100, .y = 100});
const end_ptr = try allocator.create(Node);
end_ptr.* = end;
defer {
start_ptr.deinit(allocator);
end_ptr.deinit(allocator);
allocator.destroy(start_ptr);
allocator.destroy(end_ptr);
}
for (0..n) |_| {
try road_man.addRoad(allocator, start_ptr, end_ptr);
}
try expect(road_man.next_id == n);
try expect(road_man.roads.items.len == n);
// TODO rewrite
}
// TODO tests

View File

@@ -1,7 +1,7 @@
const std = @import("std");
const rl = @import("raylib");
const c = @import("constants.zig");
const c = @import("common/constants.zig");
const Simulator = @import("simulator.zig").Simulator;
pub fn main(init: std.process.Init) !void {
@@ -11,14 +11,16 @@ pub fn main(init: std.process.Init) !void {
.msaa_4x_hint = true,
.window_highdpi = true,
});
rl.initWindow(c.WIDTH, c.HEIGHT, "Base Road Network");
rl.initWindow(c.WIDTH, c.HEIGHT, "Traffic Simulator");
defer rl.closeWindow();
const monitor = 0;
rl.setWindowMonitor(monitor);
rl.setTargetFPS(rl.getMonitorRefreshRate(monitor));
var sim: Simulator = .init(allocator);
const rand_impl: std.Random.IoSource = .{ .io = init.io };
var sim: Simulator = .init(allocator, &rand_impl);
defer sim.deinit() catch |err| {
std.debug.panic("Failed to deinitialise the sim: {}\n", .{err});
};
@@ -34,3 +36,14 @@ pub fn main(init: std.process.Init) !void {
sim.draw(pos);
}
}
test "test rng" {
const io = std.testing.io;
const rng_impl: std.Random.IoSource = .{ .io = io };
const rng = rng_impl.interface();
const n_max = 1000;
const n_rng = rng.uintLessThan(usize, n_max);
std.debug.print("{d}\n", .{n_rng});
}

View File

@@ -1,9 +1,15 @@
const std = @import("std");
const rl = @import("raylib");
const c = @import("constants.zig");
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
@@ -12,26 +18,47 @@ pub const Simulator = struct {
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) Simulator {
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);
}
@@ -40,13 +67,51 @@ pub const Simulator = struct {
pub fn draw(self: *const Simulator, pos: rl.Vector2) void {
rl.clearBackground(c.BACKGROUND_COLOR);
self.road_man.draw(self.delete_mode);
self.node_man.draw(pos);
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.road_man.update_highlighted_road(pos);
self.updateHighlightedEntity(pos);
}
/// Exposed input handling function exposed to raylib
@@ -59,7 +124,10 @@ pub const Simulator = struct {
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});
};
@@ -67,22 +135,28 @@ pub const Simulator = struct {
/// Sub input handling function for mouse input only
fn handleMouseInput(self: *Simulator, pos: rl.Vector2) void {
if (rl.isMouseButtonReleased(.left)) self.leftClickEvent(pos);
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) {
self.delete_road() catch |err| {
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.new_road(pos);
self.createRoad(pos);
}
/// User initiated road building functionality
fn new_road(self: *Simulator, pos: rl.Vector2) void {
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
@@ -90,10 +164,14 @@ pub const Simulator = struct {
};
if (self.node_man.temp_node) |temp| {
if (temp.*.id == cur_node.*.id) return;
self.road_man.addRoad(self.allocator, temp, cur_node) catch |err| {
std.debug.panic("Failed to add a new road or assigning its nodes: {}\n", .{err});
// 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;
@@ -103,28 +181,241 @@ pub const Simulator = struct {
}
/// User initiated road destroying functionality
fn delete_road(self: *Simulator) !void {
if (self.road_man.highlighted_road == null) return;
const h_road = self.road_man.highlighted_road.?;
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];
const start_node = h_road.nodes[0];
const end_node = h_road.nodes[1];
self.road_man.deleteRoad(self.allocator, h_road) catch |err| {
std.debug.panic("Road deletion failed: {}\n", .{err});
};
self.road_man.highlighted_road = null;
try self.road_man.deleteRoad(self.allocator, h_road);
if (start_node.roads.items.len == 0)
try self.node_man.deleteNode(self.allocator, start_node);
if (start_node.roads.items.len == 0) {
const cars = try self.car_man.getCarsOnInf(self.allocator, .{ .node = start_node });
defer self.allocator.free(cars);
if (end_node.roads.items.len == 0)
try self.node_man.deleteNode(self.allocator, end_node);
// 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});
};
}
};

View File

@@ -3,4 +3,5 @@ test {
_ = @import("infrastructure/road.zig");
_ = @import("infrastructure/node_manager.zig");
_ = @import("infrastructure/road_manager.zig");
_ = @import("main.zig");
}

55
src/vehicles/car.zig Normal file
View File

@@ -0,0 +1,55 @@
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 Node = @import("../infrastructure/node.zig").Node;
pub const Car = struct {
/// Car ID, for easier debugging and identification
id: usize,
/// When car progresses along the road its location is determined via entity id and progress
progress: f32,
/// Tracks which infrastructure (pointer) the car is currently located at
inf: st.Infrastructure,
pub fn init(new_id: usize, spawn_node: *Node) Car {
return .{
.id = new_id,
.progress = 0,
.inf = .{ .node = spawn_node },
};
}
pub fn deinit(self: *Car, allocator: std.mem.Allocator) void {
allocator.destroy(self);
}
pub fn draw(self: *const Car, display_info: bool) void {
var pos: rl.Vector2 = undefined;
switch (self.inf) {
.node => |node| pos = node.pos,
.road => |road| {
const road_vector = ut.getVectorP1P2(road.nodes[0].pos, road.nodes[1].pos);
pos = .{
.x = road_vector.x / 2,
.y = road_vector.y / 2,
};
}
}
rl.drawEllipseV(pos, 20, 15, .red);
if (!display_info) return;
var buf: [100]u8 = undefined;
const entity_info = std.fmt.bufPrintZ(&buf, "{d}", .{ self.id }) catch |err| {
std.debug.panic("Failed to allocate space for ID???: {}\n", .{ err });
};
rl.drawText(entity_info, @trunc(pos.x), @trunc(pos.y), c.ENTITY_DATA_TEXT_SIZE, c.ENTITY_DATA_TEXT_COLOUR);
}
};

View File

@@ -0,0 +1,95 @@
const std = @import("std");
const Vector2 = @import("raylib").Vector2;
const e = @import("../common/errors.zig");
const ut = @import("../common/structures.zig");
const Node = @import("../infrastructure/node.zig").Node;
const Car = @import("car.zig").Car;
pub const CarManager = struct {
next_id: usize,
cars: std.ArrayList(*Car),
pub fn init() CarManager {
return .{
.next_id = 0,
.cars = .empty,
};
}
pub fn deinit(self: *CarManager, allocator: std.mem.Allocator) void {
for (self.cars.items) |car| {
car.deinit(allocator);
}
self.cars.deinit(allocator);
}
pub fn draw(self: *const CarManager, display_info: bool) void {
for (self.cars.items) |car| {
car.draw(display_info);
}
}
pub fn getNextID(self: *CarManager) usize {
defer self.next_id += 1;
return self.next_id;
}
pub fn addCar(self: *CarManager, allocator: std.mem.Allocator, node_ref: *Node) !void {
const car_ptr = try allocator.create(Car);
car_ptr.* = .init(self.getNextID(), node_ref);
try self.cars.append(allocator, car_ptr);
}
pub fn clear(self: *CarManager, allocator: std.mem.Allocator) void {
for (self.cars.items) |car| {
car.deinit(allocator);
}
self.cars.clearRetainingCapacity();
self.next_id = 0;
}
/// This function returns array of cars which are located on the node/road specified in the `inf` parameter
pub fn getCarsOnInf(self: *const CarManager, allocator: std.mem.Allocator, inf: ut.Infrastructure) ![]*Car {
var cars: std.ArrayList(*Car) = .empty;
const active_inf = std.meta.activeTag(inf);
for (self.cars.items) |car| {
if (std.meta.activeTag(car.inf) != active_inf) continue;
switch (car.inf) {
inline else => |a, tag| {
const b = @field(inf, @tagName(tag));
if (a == b) try cars.append(allocator, car);
}
}
}
return cars.toOwnedSlice(allocator);
}
/// Attempts to deinit and remove the (passed) car;
/// returns an error if car doesn't exist in the list
pub fn removeCar(self: *CarManager, allocator: std.mem.Allocator, car_to_delete: *Car) !void {
for (self.cars.items, 0..) |car, index| {
if (car != car_to_delete) continue;
car.deinit(allocator);
_ = self.cars.swapRemove(index);
return;
}
return e.Entity.NotFound;
}
/// TODO
pub fn removeMultipleCars(self: *CarManager, allocator: std.mem.Allocator, cars_to_delete: []*Car) !void {
_ = cars_to_delete; // autofix
_ = allocator; // autofix
_ = self; // autofix
}
};