From d302628e8665572bc515c254a8d52909cc6db2ae Mon Sep 17 00:00:00 2001 From: ubq323 Date: Fri, 22 Mar 2024 19:38:29 +0000 Subject: refactor --- drawing.ha | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.ha | 71 +++++++++++++++++--------------------------------------------- 2 files changed, 84 insertions(+), 52 deletions(-) create mode 100644 drawing.ha diff --git a/drawing.ha b/drawing.ha new file mode 100644 index 0000000..ff2aa71 --- /dev/null +++ b/drawing.ha @@ -0,0 +1,65 @@ +use sdl2; + + +// 2d position, x and y +type pos = (int, int); + +type drawing_state = struct { + // is the mouse button held down? + drawing: bool, + pos: pos, + picture: picture, +}; + +type picture = struct { + d: *[*]u32, + w: size, + h: size, +}; +// Returns array index of the pixel at position pos. +// Bounds check happens in here instead of using a slice type, so +// that it's easier to remove later. +fn pidx(pic: *picture, pos: pos) size = { + const (x,y) = pos; + const (xs,ys) = (x:size, y:size); + assert(0 <= x, "x position must not be less than 0"); + assert(0 <= y, "y position must not be less than 0"); + assert(xs < pic.w, "x position must be less than picture width"); + assert(ys < pic.h, "y position must be less than picture height"); + + return xs + pic.w*ys; +}; +fn pic_set(pic: *picture, pos: pos, val: u32) void = pic.d[pidx(pic,pos)] = val; +fn picture_from_surface(surf: *sdl2::SDL_Surface) picture = picture { + w = surf.w: size, + h = surf.h: size, + d = (surf.pixels as *opaque: *[*]u32), +}; + +fn min(a: int, b: int) int = if (a - const d = ev.button; - mousex = d.x; - mousey = d.y; - if (d.button == 1) - drawing = (d.state == 1); + const edata = ev.button; + dstate.pos = (edata.x, edata.y); + if (edata.button == 1) + dstate.drawing = (edata.state == 1); case sdl2::SDL_EventType::MOUSEMOTION => - const d = ev.motion; - mousex = d.x; - mousey = d.y; + const edata = ev.motion; + dstate.pos = (edata.x, edata.y); case => void; }; + do_drawing(&dstate); - if (drawing) circle(pic, mousex, mousey, 25, 0x00ffff); + + // if (drawing) { + // circle(pic, mousex, mousey, 5, 0x00ffff); + // }; // circle(pic, 100, 100, n:int, 0xff0000); @@ -70,43 +76,4 @@ export fn main() void = { }; }; -def WHITE = 0x556602; -def BLACK = 0x0; - -type picture = struct { - d: []u32, - w: size, - h: size, -}; -fn pidx(pic: picture, x: size, y: size) size = (pic.w*y)+x; -fn pic_set(pic: picture, x: size, y: size, val: u32) void = pic.d[pidx(pic,x,y)] = val; -fn picture_from_surface(surf: *sdl2::SDL_Surface) picture = picture { - w = surf.w: size, - h = surf.h: size, - d = (surf.pixels as *opaque: *[*]u32)[..surf.w*surf.h], -}; - -fn min(a: int, b: int) int = if (a