this repo has no description
at main 1.9 kB view raw
1const std = @import("std"); 2const zm = @import("zmath"); 3 4pub const Texture = union(enum) { 5 solid_color: SolidColor, 6 checker_texture: CheckerTexture, 7 8 pub fn init(alloc: std.mem.Allocator, data: anytype) !*Texture { 9 const tex = try alloc.create(Texture); 10 11 switch (@TypeOf(data)) { 12 SolidColor => tex.* = .{ .solid_color = data }, 13 CheckerTexture => tex.* = .{ .checker_texture = data }, 14 15 else => @panic("Cannot infer Texture type of: " ++ @typeName(@TypeOf(data))), 16 } 17 18 return tex; 19 } 20 21 pub fn value(self: *Texture, u: f32, v: f32, p: zm.Vec) zm.Vec { 22 switch (self.*) { 23 inline else => |*n| return n.value(u, v, p), 24 } 25 } 26}; 27 28pub const SolidColor = struct { 29 albedo: zm.Vec, 30 31 pub fn init(albedo: zm.Vec) SolidColor { 32 return SolidColor{ .albedo = albedo }; 33 } 34 35 pub fn rgb(r: f32, g: f32, b: f32) SolidColor { 36 return init(zm.f32x4(r, g, b, 1.0)); 37 } 38 39 pub fn value(self: *SolidColor, _: f32, _: f32, _: zm.Vec) zm.Vec { 40 return self.albedo; 41 } 42}; 43 44pub const CheckerTexture = struct { 45 inv_scale: f32, 46 even: *Texture, 47 odd: *Texture, 48 49 pub fn init(scale: f32, even: *Texture, odd: *Texture) CheckerTexture { 50 return CheckerTexture{ .inv_scale = 1 / scale, .even = even, .odd = odd }; 51 } 52 53 pub fn value(self: *CheckerTexture, u: f32, v: f32, p: zm.Vec) zm.Vec { 54 const x = @as(i32, @intFromFloat(@floor(self.inv_scale * p[0]))); 55 const y = @as(i32, @intFromFloat(@floor(self.inv_scale * p[1]))); 56 const z = @as(i32, @intFromFloat(@floor(self.inv_scale * p[2]))); 57 58 const is_even = @rem(x + y + z, 2) == 0; 59 60 if (is_even) { 61 return self.even.value(u, v, p); 62 } else { 63 return self.odd.value(u, v, p); 64 } 65 } 66};