|
1 | 1 | module sapp
|
2 | 2 |
|
3 | 3 | import os
|
| 4 | +import stbi |
4 | 5 |
|
5 | 6 | // v_sapp_gl_read_rgba_pixels reads pixles from the OpenGL buffer into `pixels`.
|
6 | 7 | fn C.v_sapp_gl_read_rgba_pixels(x int, y int, width int, height int, pixels charptr)
|
7 | 8 |
|
8 | 9 | // screenshot takes a screenshot of the current window.
|
9 |
| -[inline] |
10 | 10 | pub fn screenshot(path string) ? {
|
11 | 11 | if !path.ends_with('.ppm') {
|
12 | 12 | return error(@MOD + '.' + @FN + ' currently only supports .ppm files.')
|
13 | 13 | }
|
| 14 | + return screenshot_ppm(path) |
| 15 | +} |
14 | 16 |
|
15 |
| - w := width() |
16 |
| - h := height() |
17 |
| - |
18 |
| - size := w * h * 4 // |
19 |
| - mut pixels := []byte{len: size, init: 0} |
20 |
| - |
21 |
| - C.v_sapp_gl_read_rgba_pixels(0, 0, w, h, pixels.data) |
22 |
| - |
23 |
| - // TODO use separate thread for writing the data |
24 |
| - // TODO use stbi to support more formats |
25 |
| - // stbi.write_png(path, w, h, components, pixels.data, 3 * w) |
26 |
| - // stbi.write_tga(path, w, h, components, pixels.data) |
27 |
| - write_rgba_to_ppm(path, w, h, 4, pixels) ? |
| 17 | +// screenshot_ppm takes a screenshot of the current window as a .ppm file |
| 18 | +[manualfree] |
| 19 | +pub fn screenshot_ppm(path string) ? { |
| 20 | + ss := screenshot_window() |
| 21 | + write_rgba_to_ppm(path, ss.width, ss.height, 4, ss.pixels) ? |
| 22 | + unsafe { ss.destroy() } |
| 23 | +} |
28 | 24 |
|
29 |
| - unsafe { |
30 |
| - pixels.free() |
31 |
| - } |
| 25 | +// screenshot_png takes a screenshot of the current window as a .png file |
| 26 | +[manualfree] |
| 27 | +pub fn screenshot_png(path string) ? { |
| 28 | + ss := screenshot_window() |
| 29 | + stbi.set_flip_vertically_on_write(true) |
| 30 | + stbi.stbi_write_png(path, ss.width, ss.height, 4, ss.pixels, ss.width * 4) ? |
| 31 | + unsafe { ss.destroy() } |
32 | 32 | }
|
33 | 33 |
|
34 | 34 | // write_rgba_to_ppm writes `pixels` data in RGBA format to PPM3 format.
|
35 |
| -fn write_rgba_to_ppm(path string, w int, h int, components int, pixels []byte) ? { |
| 35 | +fn write_rgba_to_ppm(path string, w int, h int, components int, pixels &byte) ? { |
36 | 36 | mut f_out := os.create(path) ?
|
| 37 | + defer { |
| 38 | + f_out.close() |
| 39 | + } |
37 | 40 | f_out.writeln('P3') ?
|
38 | 41 | f_out.writeln('$w $h') ?
|
39 | 42 | f_out.writeln('255') ?
|
40 | 43 | for i := h - 1; i >= 0; i-- {
|
41 | 44 | for j := 0; j < w; j++ {
|
42 | 45 | idx := i * w * components + j * components
|
43 |
| - r := int(pixels[idx]) |
44 |
| - g := int(pixels[idx + 1]) |
45 |
| - b := int(pixels[idx + 2]) |
46 |
| - f_out.write_string('$r $g $b ') ? |
| 46 | + unsafe { |
| 47 | + r := int(pixels[idx]) |
| 48 | + g := int(pixels[idx + 1]) |
| 49 | + b := int(pixels[idx + 2]) |
| 50 | + f_out.write_string('$r $g $b ') ? |
| 51 | + } |
47 | 52 | }
|
48 | 53 | }
|
49 |
| - f_out.close() |
50 | 54 | }
|
0 commit comments