Fork of https://github.com/yatazet/cube-zig.
at main 89 lines 2.8 kB view raw
1const std = @import("std"); 2 3const screen_width = 160; 4const screen_height = 44; 5const buffer_size = screen_width * screen_height; 6 7var A: f32 = 0; 8var B: f32 = 0; 9var C: f32 = 0; 10 11var zBuffer: [buffer_size]f32 = undefined; 12var buffer: [buffer_size]u8 = undefined; 13 14const distance_from_cam = 100.0; 15const K1: f32 = 40.0; 16const cube_width: f32 = 20.0; 17const increment_speed: f32 = 0.4; 18 19fn calculateX(i: f32, j: f32, k: f32) f32 { 20 return j * @sin(A) * @sin(B) * @cos(C) - k * @cos(A) * @sin(B) * @cos(C) + j * @cos(A) * @sin(C) + k * @sin(A) * @sin(C) + i * @cos(B) * @cos(C); 21} 22 23fn calculateY(i: f32, j: f32, k: f32) f32 { 24 return j * @cos(A) * @cos(C) + k * @sin(A) * @cos(C) - j * @sin(A) * @sin(B) * @sin(C) + k * @cos(A) * @sin(B) * @sin(C) - i * @cos(B) * @sin(C); 25} 26 27fn calculateZ(i: f32, j: f32, k: f32) f32 { 28 return k * @cos(A) * @cos(B) - j * @sin(A) * @cos(B) + i * @sin(B); 29} 30 31fn plot(i: f32, j: f32, k: f32, ch: u8) void { 32 const x = calculateX(i, j, k); 33 const y = calculateY(i, j, k); 34 const z = calculateZ(i, j, k) + distance_from_cam; 35 36 const ooz = 1 / z; 37 38 const xp: usize = @intFromFloat(@floor(screen_width / 2 + K1 * ooz * x * 2)); 39 const yp: usize = @intFromFloat(@floor(screen_height / 2 + K1 * ooz * y)); 40 41 const idx = xp + yp * screen_width; 42 43 if (xp < screen_width and yp < screen_height and idx < buffer_size) { 44 if (ooz > zBuffer[idx]) { 45 zBuffer[idx] = ooz; 46 buffer[idx] = ch; 47 } 48 } 49} 50 51pub fn main(init: std.process.Init) !void { 52 const io = init.io; 53 var write_buf: [4096]u8 = undefined; 54 var file_writer = std.Io.File.stdout().writerStreaming(io, &write_buf); 55 const stdout = &file_writer.interface; 56 57 try stdout.writeAll("\x1b[J"); 58 try stdout.writeAll("\x1b[?25l"); 59 try stdout.flush(); 60 while (true) { 61 for (&buffer) |*b| b.* = ' '; 62 for (&zBuffer) |*z| z.* = 0; 63 var cubeX: f32 = -cube_width; 64 while (cubeX < cube_width) : (cubeX += increment_speed) { 65 var cubeY: f32 = -cube_width; 66 while (cubeY < cube_width) : (cubeY += increment_speed) { 67 plot(cubeX, cubeY, -cube_width, '@'); 68 plot(cube_width, cubeY, cubeX, '$'); 69 plot(-cube_width, cubeY, -cubeX, '~'); 70 plot(-cubeX, cubeY, cube_width, '#'); 71 plot(cubeX, -cube_width, -cubeY, ';'); 72 plot(cubeX, cube_width, cubeY, '+'); 73 } 74 } 75 76 try stdout.writeAll("\x1b[H"); 77 for (buffer, 0..) |ch, i| { 78 if (i % screen_width == 0 and i != 0) 79 try stdout.writeByte('\n'); 80 try stdout.writeByte(ch); 81 } 82 try stdout.flush(); 83 84 A += 0.04; 85 B += 0.02; 86 C += 0.01; 87 try io.sleep(.fromNanoseconds(16_000_000), .real); 88 } 89}