forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
390 lines (325 loc) · 14.5 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
#include "scene.h"
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <chrono>
#include <cassert>
#include <concepts>
#include <GLES3/gl3.h>
#include <GLES3/gl3platform.h>
static GLint compile_shader(GLuint program, GLuint shader_type, const GLchar *const *source)
{
auto shader_id = glCreateShader(shader_type);
glShaderSource(shader_id, 1, source, nullptr);
glCompileShader(shader_id);
GLint compiled = 0;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
GLint infoLen = 0;
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char *infoLog = reinterpret_cast<char *>(malloc(sizeof(char) * infoLen));
glGetShaderInfoLog(shader_id, infoLen, NULL, infoLog);
fprintf(stderr, "Error compiling %s shader:\n%s\n",
shader_type == GL_FRAGMENT_SHADER ? "fragment shader" : "vertex shader",
infoLog);
free(infoLog);
}
glDeleteShader(shader_id);
exit(1);
}
glAttachShader(program, shader_id);
return shader_id;
}
#define DEFINE_SCOPED_BINDING(StructName, ParamName, BindingFn, TargetName) \
struct StructName \
{ \
GLuint saved_value = {}; \
StructName() = delete; \
StructName(const StructName &) = delete; \
StructName &operator=(const StructName &) = delete; \
StructName(GLuint new_value) \
{ \
glGetIntegerv(ParamName, (GLint *)&saved_value); \
BindingFn(TargetName, new_value); \
} \
~StructName() { BindingFn(TargetName, saved_value); } \
}
DEFINE_SCOPED_BINDING(ScopedTextureBinding, GL_TEXTURE_BINDING_2D, glBindTexture, GL_TEXTURE_2D);
DEFINE_SCOPED_BINDING(ScopedFrameBufferBinding, GL_DRAW_FRAMEBUFFER_BINDING, glBindFramebuffer,
GL_DRAW_FRAMEBUFFER);
DEFINE_SCOPED_BINDING(ScopedVBOBinding, GL_ARRAY_BUFFER_BINDING, glBindBuffer, GL_ARRAY_BUFFER);
struct ScopedVAOBinding
{
GLuint saved_value = {};
ScopedVAOBinding() = delete;
ScopedVAOBinding(const ScopedVAOBinding &) = delete;
ScopedVAOBinding &operator=(const ScopedVAOBinding &) = delete;
ScopedVAOBinding(GLuint new_value)
{
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint *)&saved_value);
glBindVertexArray(new_value);
}
~ScopedVAOBinding() { glBindVertexArray(saved_value); }
};
struct DemoTexture
{
GLuint texture;
int width;
int height;
GLuint fbo;
DemoTexture(int width, int height) : width(width), height(height)
{
glGenFramebuffers(1, &fbo);
glGenTextures(1, &texture);
ScopedTextureBinding activeTexture(texture);
GLint old_unpack_alignment;
glGetIntegerv(GL_UNPACK_ALIGNMENT, &old_unpack_alignment);
GLint old_unpack_row_length;
glGetIntegerv(GL_UNPACK_ROW_LENGTH, &old_unpack_row_length);
GLint old_unpack_skip_pixels;
glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &old_unpack_skip_pixels);
GLint old_unpack_skip_rows;
glGetIntegerv(GL_UNPACK_SKIP_ROWS, &old_unpack_skip_rows);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
nullptr);
ScopedFrameBufferBinding activeFBO(fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
glPixelStorei(GL_UNPACK_ALIGNMENT, old_unpack_alignment);
glPixelStorei(GL_UNPACK_ROW_LENGTH, old_unpack_row_length);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, old_unpack_skip_pixels);
glPixelStorei(GL_UNPACK_SKIP_ROWS, old_unpack_skip_rows);
}
DemoTexture(const DemoTexture &) = delete;
DemoTexture &operator=(const DemoTexture &) = delete;
~DemoTexture()
{
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &texture);
}
template<std::invocable<> Callback>
void with_active_fbo(Callback callback)
{
ScopedFrameBufferBinding activeFBO(fbo);
callback();
}
};
class DemoRenderer
{
public:
DemoRenderer(slint::ComponentWeakHandle<App> app) : app_weak(app) { }
void operator()(slint::RenderingState state, slint::GraphicsAPI)
{
switch (state) {
case slint::RenderingState::RenderingSetup:
setup();
break;
case slint::RenderingState::BeforeRendering:
if (auto app = app_weak.lock()) {
auto red = (*app)->get_selected_red();
auto green = (*app)->get_selected_green();
auto blue = (*app)->get_selected_blue();
auto width = (*app)->get_requested_texture_width();
auto height = (*app)->get_requested_texture_height();
auto texture = render(red, green, blue, width, height);
(*app)->set_texture(texture);
(*app)->window().request_redraw();
}
break;
case slint::RenderingState::AfterRendering:
break;
case slint::RenderingState::RenderingTeardown:
teardown();
break;
}
}
private:
void setup()
{
program = glCreateProgram();
const GLchar *const fragment_shader =
R"(#version 100
precision mediump float;
varying vec2 frag_position;
uniform vec3 selected_light_color;
uniform float iTime;
float sdRoundBox(vec3 p, vec3 b, float r)
{
vec3 q = abs(p) - b;
return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0) - r;
}
vec3 rotateY(vec3 r, float angle)
{
mat3 rotation_matrix = mat3(cos(angle), 0, sin(angle), 0, 1, 0, -sin(angle), 0, cos(angle));
return rotation_matrix * r;
}
vec3 rotateZ(vec3 r, float angle) {
mat3 rotation_matrix = mat3(cos(angle), -sin(angle), 0, sin(angle), cos(angle), 0, 0, 0, 1);
return rotation_matrix * r;
}
// Distance from the scene
float scene(vec3 r)
{
vec3 pos = rotateZ(rotateY(r + vec3(-1.0, -1.0, 4.0), iTime), iTime);
vec3 cube = vec3(0.5, 0.5, 0.5);
float edge = 0.1;
return sdRoundBox(pos, cube, edge);
}
// https://iquilezles.org/articles/normalsSDF
vec3 normal( in vec3 pos )
{
vec2 e = vec2(1.0,-1.0)*0.5773;
const float eps = 0.0005;
return normalize( e.xyy*scene( pos + e.xyy*eps ) +
e.yyx*scene( pos + e.yyx*eps ) +
e.yxy*scene( pos + e.yxy*eps ) +
e.xxx*scene( pos + e.xxx*eps ) );
}
#define ITERATIONS 90
#define EPS 0.0001
vec4 render(vec2 fragCoord, vec3 light_color)
{
vec4 color = vec4(0, 0, 0, 1);
vec3 camera = vec3(1.0, 2.0, 1.0);
vec3 p = vec3(fragCoord.x, fragCoord.y + 1.0, -1.0);
vec3 dir = normalize(p - camera);
for(int i=0; i < ITERATIONS; i++)
{
float dist = scene(p);
if(dist < EPS) {
break;
}
p = p + dir * dist;
}
vec3 surf_normal = normal(p);
vec3 light_position = vec3(2.0, 4.0, -0.5);
float light = 7.0 + 2.0 * dot(surf_normal, light_position);
light /= 0.2 * pow(length(light_position - p), 3.5);
return vec4(light * light_color.x, light * light_color.y, light * light_color.z, 1.0) * 2.0;
}
/*
void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
vec2 r = fragCoord.xy / iResolution.xy;
r.x *= (iResolution.x / iResolution.y);
fragColor = render(r, vec3(0.2, 0.5, 0.9));
}
*/
void main() {
vec2 r = vec2(0.5 * frag_position.x + 1.0, 0.5 - 0.5 * frag_position.y);
gl_FragColor = render(r, selected_light_color);
})";
const GLchar *const vertex_shader = "#version 100\n"
"attribute vec2 position;\n"
"varying vec2 frag_position;\n"
"void main() {\n"
" frag_position = position;\n"
" gl_Position = vec4(position, 0.0, 1.0);\n"
"}\n";
auto fragment_shader_id = compile_shader(program, GL_FRAGMENT_SHADER, &fragment_shader);
auto vertex_shader_id = compile_shader(program, GL_VERTEX_SHADER, &vertex_shader);
GLint linked = 0;
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
GLint infoLen = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);
if (infoLen > 1) {
char *infoLog = reinterpret_cast<char *>(malloc(sizeof(char) * infoLen));
glGetProgramInfoLog(program, infoLen, NULL, infoLog);
fprintf(stderr, "Error linking shader:\n%s\n", infoLog);
free(infoLog);
}
glDeleteProgram(program);
exit(1);
}
glDetachShader(program, fragment_shader_id);
glDetachShader(program, vertex_shader_id);
GLuint position_location = glGetAttribLocation(program, "position");
effect_time_location = glGetUniformLocation(program, "iTime");
selected_light_color_position = glGetUniformLocation(program, "selected_light_color");
displayed_texture = std::make_unique<DemoTexture>(320, 200);
next_texture = std::make_unique<DemoTexture>(320, 200);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
ScopedVBOBinding savedVBO(vbo);
ScopedVAOBinding savedVAO(vao);
const float vertices[] = { -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0 };
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) * sizeof(vertices[0]), &vertices,
GL_STATIC_DRAW);
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 2, GL_FLOAT, false, 8, 0);
}
slint::Image render(float red, float green, float blue, int width, int height)
{
ScopedVBOBinding savedVBO(vbo);
ScopedVAOBinding savedVAO(vao);
glUseProgram(program);
if (next_texture->width != width || next_texture->height != height) {
auto new_texture = std::make_unique<DemoTexture>(width, height);
std::swap(next_texture, new_texture);
}
next_texture->with_active_fbo([&]() {
GLint saved_viewport[4];
glGetIntegerv(GL_VIEWPORT, &saved_viewport[0]);
glViewport(0, 0, next_texture->width, next_texture->height);
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_time)
/ 500.;
glUniform1f(effect_time_location, elapsed.count());
glUniform3f(selected_light_color_position, red, green, blue);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glViewport(saved_viewport[0], saved_viewport[1], saved_viewport[2], saved_viewport[3]);
});
glUseProgram(0);
auto resultTexture = slint::Image::create_from_borrowed_gl_2d_rgba_texture(
next_texture->texture,
{ static_cast<uint32_t>(next_texture->width),
static_cast<uint32_t>(next_texture->height) });
std::swap(next_texture, displayed_texture);
return resultTexture;
}
void teardown()
{
glDeleteProgram(program);
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
slint::ComponentWeakHandle<App> app_weak;
GLuint vbo;
GLuint vao;
GLuint program = 0;
GLuint effect_time_location = 0;
GLuint selected_light_color_position = 0;
std::chrono::time_point<std::chrono::steady_clock> start_time =
std::chrono::steady_clock::now();
std::unique_ptr<DemoTexture> displayed_texture;
std::unique_ptr<DemoTexture> next_texture;
};
int main()
{
auto app = App::create();
if (auto error = app->window().set_rendering_notifier(DemoRenderer(app))) {
if (*error == slint::SetRenderingNotifierError::Unsupported) {
fprintf(stderr,
"This example requires the use of a GL renderer. Please run with the "
"environment variable SLINT_BACKEND=winit set.\n");
} else {
fprintf(stderr, "Unknown error calling set_rendering_notifier\n");
}
exit(EXIT_FAILURE);
}
app->run();
}