From 0c97c2124e83b0bcf8719a62ce3704602ee66c38 Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Tue, 17 Dec 2024 20:56:01 +0100 Subject: ppm: simple example to generate a ppm image --- ppm/ppm.zig | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 ppm/ppm.zig (limited to 'ppm/ppm.zig') diff --git a/ppm/ppm.zig b/ppm/ppm.zig new file mode 100644 index 0000000..8b89456 --- /dev/null +++ b/ppm/ppm.zig @@ -0,0 +1,51 @@ +const std = @import("std"); +const assert = std.debug.assert; + +pub const Pixel = extern struct { + r: u8, + g: u8, + b: u8, +}; + +pub fn ppm(comptime xdim: u32, comptime ydim: u32) type { + return struct { + const Self = @This(); + + /// Pixel data of the ppm image. + px: [ydim][xdim]Pixel, + + /// Initial value of the `ppm` type. + pub const init: Self = .{ + .px = undefined, + }; + + /// Set pixel data at `(x, y)`. + pub fn set(self: *Self, x: u32, y: u32, px: Pixel) void { + assert(x < xdim and y < ydim); + self.px[x][y] = px; + } + + /// Get slice of pixels for row `y`. + pub fn row(self: *Self, y: u32) []Pixel { + assert(y < ydim); + return self.px[y][0..]; + } + + /// Write out image file with `name`. + pub fn dump(self: *const Self, name: []const u8) !void { + const f = try std.fs.cwd().createFile(name, .{ .truncate = true }); + defer f.close(); + + const w = f.writer(); + // Write ppm header (in ascii): + // MAGIC XDIM YDIM MAX_COLOR_VALUE + try w.print("P6 {} {} 255\n", .{ xdim, ydim }); + + for (self.px) |curr_row| { + for (curr_row) |px| { + try w.writeStruct(px); + } + } + } + }; +} -- cgit v1.2.3