From 8d0420e47894dacb85d5bf66a34fb5baca4c5968 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Tue, 6 Aug 2024 07:40:20 +0200 Subject: [PATCH] Vec3 sample implementation --- src/main.zig | 6 ++++++ src/vector.zig | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/vector.zig diff --git a/src/main.zig b/src/main.zig index a347913..7804179 100644 --- a/src/main.zig +++ b/src/main.zig @@ -2,8 +2,14 @@ //! you are building an executable. If you are making a library, the convention //! is to delete this file and start with root.zig instead. const std = @import("std"); +const Vec3 = @import("vector.zig").Vec3; pub fn main() !void { + const a = Vec3.new(1.0, 2.0, 3.0); + const b = Vec3.new(4.0, 5.0, 6.0); + const c = a.dot(b); + std.debug.print("a dot b = {d}\n", .{c}); + // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); diff --git a/src/vector.zig b/src/vector.zig new file mode 100644 index 0000000..7993532 --- /dev/null +++ b/src/vector.zig @@ -0,0 +1,44 @@ +const expect = @import("std").testing.expect; + +/// A 3D vector. +pub const Vec3 = struct { + x: f32, + y: f32, + z: f32, + + /// Creates a new vector with the given components. + pub fn new(x: f32, y: f32, z: f32) Vec3 { + return Vec3{ .x = x, .y = y, .z = z }; + } + + /// Returns the dot product of this vector and another. + pub fn dot(self: Vec3, other: Vec3) f32 { + return self.x * other.x + self.y * other.y + self.z * other.z; + } + + /// Returns the cross product of this vector and another. + pub fn cross(self: Vec3, other: Vec3) Vec3 { + return Vec3{ + .x = self.y * other.z - self.z * other.y, + .y = self.z * other.x - self.x * other.z, + .z = self.x * other.y - self.y * other.x, + }; + } + + // Returns true if this vector is equal to another. + pub fn equals(self: *const Vec3, other: *const Vec3) bool { + return self.x == other.x and self.y == other.y and self.z == other.z; + } +}; + +test "Dot product" { + const a = Vec3{ .x = 1, .y = 2, .z = 3 }; + const b = Vec3{ .x = 4, .y = 5, .z = 6 }; + try expect(a.dot(b) == 32); +} + +test "Cross product" { + const a = Vec3{ .x = 1, .y = 2, .z = 3 }; + const b = Vec3{ .x = 4, .y = 5, .z = 6 }; + try expect(a.cross(b).equals(&Vec3{ .x = -3, .y = 6, .z = -3 })); +}