| 1 | module sapp |
| 2 | |
| 3 | import os |
| 4 | import stbi |
| 5 | |
| 6 | #define SOKOL_VALIDATE_NON_FATAL 1 |
| 7 | |
| 8 | // v_sapp_gl_read_rgba_pixels reads pixles from the OpenGL buffer into `pixels`. |
| 9 | fn C.v_sapp_gl_read_rgba_pixels(x int, y int, width int, height int, pixels charptr) |
| 10 | |
| 11 | // screenshot takes a screenshot of the current window and |
| 12 | // saves it to `path`. The format is inferred from the extension |
| 13 | // of the file name in `path`. |
| 14 | // |
| 15 | // Supported formats are: `.png`, `.ppm`. |
| 16 | pub fn screenshot(path string) ! { |
| 17 | match os.file_ext(path) { |
| 18 | '.png' { |
| 19 | return screenshot_png(path) |
| 20 | } |
| 21 | '.ppm' { |
| 22 | return screenshot_ppm(path) |
| 23 | } |
| 24 | else { |
| 25 | return error(@MOD + '.' + @FN + ' currently only supports .png and .ppm files.') |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // screenshot_ppm takes a screenshot of the current window and |
| 31 | // saves it to `path` as a .ppm file. |
| 32 | @[manualfree] |
| 33 | pub fn screenshot_ppm(path string) ! { |
| 34 | ss := screenshot_window() |
| 35 | write_rgba_to_ppm(path, ss.width, ss.height, 4, ss.pixels)! |
| 36 | unsafe { ss.destroy() } |
| 37 | } |
| 38 | |
| 39 | // screenshot_png takes a screenshot of the current window and |
| 40 | // saves it to `path` as a .png file. |
| 41 | @[manualfree] |
| 42 | pub fn screenshot_png(path string) ! { |
| 43 | ss := screenshot_window() |
| 44 | stbi.set_flip_vertically_on_write(true) |
| 45 | stbi.stbi_write_png(path, ss.width, ss.height, 4, ss.pixels, ss.width * 4)! |
| 46 | unsafe { ss.destroy() } |
| 47 | } |
| 48 | |
| 49 | // write_rgba_to_ppm writes `pixels` data in RGBA format to PPM3 format. |
| 50 | fn write_rgba_to_ppm(path string, w int, h int, components int, pixels &u8) ! { |
| 51 | mut f_out := os.create(path)! |
| 52 | defer { |
| 53 | f_out.close() |
| 54 | } |
| 55 | f_out.writeln('P3')! |
| 56 | f_out.writeln('${w} ${h}')! |
| 57 | f_out.writeln('255')! |
| 58 | for i := h - 1; i >= 0; i-- { |
| 59 | for j := 0; j < w; j++ { |
| 60 | idx := i * w * components + j * components |
| 61 | unsafe { |
| 62 | r := int(pixels[idx]) |
| 63 | g := int(pixels[idx + 1]) |
| 64 | b := int(pixels[idx + 2]) |
| 65 | f_out.write_string('${r} ${g} ${b} ')! |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |