v / vlib / sokol / sapp / sapp_v.c.v
69 lines · 62 sloc · 1.79 KB · 227dbc7d4a3943fe8f1541f595b6ef9851bef552
Raw
1module sapp
2
3import os
4import 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`.
9fn 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`.
16pub 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]
33pub 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]
42pub 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.
50fn 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