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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::GLUniformType;
use crate::Renderer;
use glib::object::Cast;
use glib::object::IsA;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::fmt;
use std::ptr;

glib::wrapper! {
    /// A [`GLShader`][crate::GLShader] is a snippet of GLSL that is meant to run in the
    /// fragment shader of the rendering pipeline.
    ///
    /// A fragment shader gets the coordinates being rendered as input and
    /// produces the pixel values for that particular pixel. Additionally,
    /// the shader can declare a set of other input arguments, called
    /// uniforms (as they are uniform over all the calls to your shader in
    /// each instance of use). A shader can also receive up to 4
    /// textures that it can use as input when producing the pixel data.
    ///
    /// [`GLShader`][crate::GLShader] is usually used with gtk_snapshot_push_gl_shader()
    /// to produce a [`GLShaderNode`][crate::GLShaderNode] in the rendering hierarchy,
    /// and then its input textures are constructed by rendering the child
    /// nodes to textures before rendering the shader node itself. (You can
    /// pass texture nodes as children if you want to directly use a texture
    /// as input).
    ///
    /// The actual shader code is GLSL code that gets combined with
    /// some other code into the fragment shader. Since the exact
    /// capabilities of the GPU driver differs between different OpenGL
    /// drivers and hardware, GTK adds some defines that you can use
    /// to ensure your GLSL code runs on as many drivers as it can.
    ///
    /// If the OpenGL driver is GLES, then the shader language version
    /// is set to 100, and GSK_GLES will be defined in the shader.
    ///
    /// Otherwise, if the OpenGL driver does not support the 3.2 core profile,
    /// then the shader will run with language version 110 for GL2 and 130 for GL3,
    /// and GSK_LEGACY will be defined in the shader.
    ///
    /// If the OpenGL driver supports the 3.2 code profile, it will be used,
    /// the shader language version is set to 150, and GSK_GL3 will be defined
    /// in the shader.
    ///
    /// The main function the shader must implement is:
    ///
    /// **⚠️ The following code is in glsl ⚠️**
    ///
    /// ```glsl
    ///  void mainImage(out vec4 fragColor,
    ///                 in vec2 fragCoord,
    ///                 in vec2 resolution,
    ///                 in vec2 uv)
    /// ```
    ///
    /// Where the input @fragCoord is the coordinate of the pixel we're
    /// currently rendering, relative to the boundary rectangle that was
    /// specified in the [`GLShaderNode`][crate::GLShaderNode], and @resolution is the width and
    /// height of that rectangle. This is in the typical GTK coordinate
    /// system with the origin in the top left. @uv contains the u and v
    /// coordinates that can be used to index a texture at the
    /// corresponding point. These coordinates are in the [0..1]x[0..1]
    /// region, with 0, 0 being in the lower left corder (which is typical
    /// for OpenGL).
    ///
    /// The output @fragColor should be a RGBA color (with
    /// premultiplied alpha) that will be used as the output for the
    /// specified pixel location. Note that this output will be
    /// automatically clipped to the clip region of the glshader node.
    ///
    /// In addition to the function arguments the shader can define
    /// up to 4 uniforms for textures which must be called u_textureN
    /// (i.e. u_texture1 to u_texture4) as well as any custom uniforms
    /// you want of types int, uint, bool, float, vec2, vec3 or vec4.
    ///
    /// All textures sources contain premultiplied alpha colors, but if some
    /// there are outer sources of colors there is a gsk_premultiply() helper
    /// to compute premultiplication when needed.
    ///
    /// Note that GTK parses the uniform declarations, so each uniform has to
    /// be on a line by itself with no other code, like so:
    ///
    /// **⚠️ The following code is in glsl ⚠️**
    ///
    /// ```glsl
    /// uniform float u_time;
    /// uniform vec3 u_color;
    /// uniform sampler2D u_texture1;
    /// uniform sampler2D u_texture2;
    /// ```
    ///
    /// GTK uses the "gsk" namespace in the symbols it uses in the
    /// shader, so your code should not use any symbols with the prefix gsk
    /// or GSK. There are some helper functions declared that you can use:
    ///
    /// **⚠️ The following code is in glsl ⚠️**
    ///
    /// ```glsl
    /// vec4 GskTexture(sampler2D sampler, vec2 texCoords);
    /// ```
    ///
    /// This samples a texture (e.g. u_texture1) at the specified
    /// coordinates, and contains some helper ifdefs to ensure that
    /// it works on all OpenGL versions.
    ///
    /// You can compile the shader yourself using [`compile()`][Self::compile()],
    /// otherwise the GSK renderer will do it when it handling the glshader
    /// node. If errors occurs, the returned @error will include the glsl
    /// sources, so you can see what GSK was passing to the compiler. You
    /// can also set GSK_DEBUG=shaders in the environment to see the sources
    /// and other relevant information about all shaders that GSK is handling.
    ///
    /// # An example shader
    ///
    /// **⚠️ The following code is in glsl ⚠️**
    ///
    /// ```glsl
    /// uniform float position;
    /// uniform sampler2D u_texture1;
    /// uniform sampler2D u_texture2;
    ///
    /// void mainImage(out vec4 fragColor,
    ///                in vec2 fragCoord,
    ///                in vec2 resolution,
    ///                in vec2 uv) {
    ///   vec4 source1 = GskTexture(u_texture1, uv);
    ///   vec4 source2 = GskTexture(u_texture2, uv);
    ///
    ///   fragColor = position * source1 + (1.0 - position) * source2;
    /// }
    /// ```
    #[doc(alias = "GskGLShader")]
    pub struct GLShader(Object<ffi::GskGLShader, ffi::GskGLShaderClass>);

    match fn {
        type_ => || ffi::gsk_gl_shader_get_type(),
    }
}

impl GLShader {
    /// Creates a [`GLShader`][crate::GLShader] that will render pixels using the specified code.
    /// ## `sourcecode`
    /// GLSL sourcecode for the shader, as a `GBytes`
    ///
    /// # Returns
    ///
    /// A new [`GLShader`][crate::GLShader]
    #[doc(alias = "gsk_gl_shader_new_from_bytes")]
    #[doc(alias = "new_from_bytes")]
    pub fn from_bytes(sourcecode: &glib::Bytes) -> GLShader {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::gsk_gl_shader_new_from_bytes(
                sourcecode.to_glib_none().0,
            ))
        }
    }

    /// Creates a [`GLShader`][crate::GLShader] that will render pixels using the specified code.
    /// ## `resource_path`
    /// path to a resource that contains the GLSL sourcecode for
    ///     the shader
    ///
    /// # Returns
    ///
    /// A new [`GLShader`][crate::GLShader]
    #[doc(alias = "gsk_gl_shader_new_from_resource")]
    #[doc(alias = "new_from_resource")]
    pub fn from_resource(resource_path: &str) -> GLShader {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::gsk_gl_shader_new_from_resource(
                resource_path.to_glib_none().0,
            ))
        }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new builder-pattern struct instance to construct [`GLShader`] objects.
    ///
    /// This method returns an instance of [`GLShaderBuilder`](crate::builders::GLShaderBuilder) which can be used to create [`GLShader`] objects.
    pub fn builder() -> GLShaderBuilder {
        GLShaderBuilder::default()
    }

    /// Tries to compile the @self for the given @renderer.
    ///
    /// If there is a problem, this function returns [`false`] and reports
    /// an error. You should use this function before relying on the shader
    /// for rendering and use a fallback with a simpler shader or without
    /// shaders if it fails.
    ///
    /// Note that this will modify the rendering state (for example
    /// change the current GL context) and requires the renderer to be
    /// set up. This means that the widget has to be realized. Commonly you
    /// want to call this from the realize signal of a widget, or during
    /// widget snapshot.
    /// ## `renderer`
    /// a [`Renderer`][crate::Renderer]
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if an error occurred
    #[doc(alias = "gsk_gl_shader_compile")]
    pub fn compile(&self, renderer: &impl IsA<Renderer>) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::gsk_gl_shader_compile(
                self.to_glib_none().0,
                renderer.as_ref().to_glib_none().0,
                &mut error,
            );
            assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Looks for a uniform by the name @name, and returns the index
    /// of the uniform, or -1 if it was not found.
    /// ## `name`
    /// uniform name
    ///
    /// # Returns
    ///
    /// The index of the uniform, or -1
    #[doc(alias = "gsk_gl_shader_find_uniform_by_name")]
    pub fn find_uniform_by_name(&self, name: &str) -> i32 {
        unsafe {
            ffi::gsk_gl_shader_find_uniform_by_name(self.to_glib_none().0, name.to_glib_none().0)
        }
    }

    /// Gets the value of the uniform @idx in the @args block.
    ///
    /// The uniform must be of bool type.
    /// ## `args`
    /// uniform arguments
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The value
    #[doc(alias = "gsk_gl_shader_get_arg_bool")]
    #[doc(alias = "get_arg_bool")]
    pub fn arg_bool(&self, args: &glib::Bytes, idx: i32) -> bool {
        unsafe {
            from_glib(ffi::gsk_gl_shader_get_arg_bool(
                self.to_glib_none().0,
                args.to_glib_none().0,
                idx,
            ))
        }
    }

    /// Gets the value of the uniform @idx in the @args block.
    ///
    /// The uniform must be of float type.
    /// ## `args`
    /// uniform arguments
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The value
    #[doc(alias = "gsk_gl_shader_get_arg_float")]
    #[doc(alias = "get_arg_float")]
    pub fn arg_float(&self, args: &glib::Bytes, idx: i32) -> f32 {
        unsafe {
            ffi::gsk_gl_shader_get_arg_float(self.to_glib_none().0, args.to_glib_none().0, idx)
        }
    }

    /// Gets the value of the uniform @idx in the @args block.
    ///
    /// The uniform must be of int type.
    /// ## `args`
    /// uniform arguments
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The value
    #[doc(alias = "gsk_gl_shader_get_arg_int")]
    #[doc(alias = "get_arg_int")]
    pub fn arg_int(&self, args: &glib::Bytes, idx: i32) -> i32 {
        unsafe { ffi::gsk_gl_shader_get_arg_int(self.to_glib_none().0, args.to_glib_none().0, idx) }
    }

    /// Gets the value of the uniform @idx in the @args block.
    ///
    /// The uniform must be of uint type.
    /// ## `args`
    /// uniform arguments
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The value
    #[doc(alias = "gsk_gl_shader_get_arg_uint")]
    #[doc(alias = "get_arg_uint")]
    pub fn arg_uint(&self, args: &glib::Bytes, idx: i32) -> u32 {
        unsafe {
            ffi::gsk_gl_shader_get_arg_uint(self.to_glib_none().0, args.to_glib_none().0, idx)
        }
    }

    /// Get the size of the data block used to specify arguments for this shader.
    ///
    /// # Returns
    ///
    /// The size of the data block
    #[doc(alias = "gsk_gl_shader_get_args_size")]
    #[doc(alias = "get_args_size")]
    pub fn args_size(&self) -> usize {
        unsafe { ffi::gsk_gl_shader_get_args_size(self.to_glib_none().0) }
    }

    /// Returns the number of textures that the shader requires.
    ///
    /// This can be used to check that the a passed shader works
    /// in your usecase. It is determined by looking at the highest
    /// u_textureN value that the shader defines.
    ///
    /// # Returns
    ///
    /// The number of texture inputs required by @self
    #[doc(alias = "gsk_gl_shader_get_n_textures")]
    #[doc(alias = "get_n_textures")]
    pub fn n_textures(&self) -> i32 {
        unsafe { ffi::gsk_gl_shader_get_n_textures(self.to_glib_none().0) }
    }

    /// Get the number of declared uniforms for this shader.
    ///
    /// # Returns
    ///
    /// The number of declared uniforms
    #[doc(alias = "gsk_gl_shader_get_n_uniforms")]
    #[doc(alias = "get_n_uniforms")]
    pub fn n_uniforms(&self) -> i32 {
        unsafe { ffi::gsk_gl_shader_get_n_uniforms(self.to_glib_none().0) }
    }

    /// Gets the resource path for the GLSL sourcecode being used
    /// to render this shader.
    ///
    /// # Returns
    ///
    /// The resource path for the shader
    #[doc(alias = "gsk_gl_shader_get_resource")]
    #[doc(alias = "get_resource")]
    pub fn resource(&self) -> Option<glib::GString> {
        unsafe { from_glib_none(ffi::gsk_gl_shader_get_resource(self.to_glib_none().0)) }
    }

    /// Gets the GLSL sourcecode being used to render this shader.
    ///
    /// # Returns
    ///
    /// The source code for the shader
    #[doc(alias = "gsk_gl_shader_get_source")]
    #[doc(alias = "get_source")]
    pub fn source(&self) -> glib::Bytes {
        unsafe { from_glib_none(ffi::gsk_gl_shader_get_source(self.to_glib_none().0)) }
    }

    /// Get the name of the declared uniform for this shader at index @idx.
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The name of the declared uniform
    #[doc(alias = "gsk_gl_shader_get_uniform_name")]
    #[doc(alias = "get_uniform_name")]
    pub fn uniform_name(&self, idx: i32) -> glib::GString {
        unsafe {
            from_glib_none(ffi::gsk_gl_shader_get_uniform_name(
                self.to_glib_none().0,
                idx,
            ))
        }
    }

    /// Get the offset into the data block where data for this uniforms is stored.
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The data offset
    #[doc(alias = "gsk_gl_shader_get_uniform_offset")]
    #[doc(alias = "get_uniform_offset")]
    pub fn uniform_offset(&self, idx: i32) -> i32 {
        unsafe { ffi::gsk_gl_shader_get_uniform_offset(self.to_glib_none().0, idx) }
    }

    /// Get the type of the declared uniform for this shader at index @idx.
    /// ## `idx`
    /// index of the uniform
    ///
    /// # Returns
    ///
    /// The type of the declared uniform
    #[doc(alias = "gsk_gl_shader_get_uniform_type")]
    #[doc(alias = "get_uniform_type")]
    pub fn uniform_type(&self, idx: i32) -> GLUniformType {
        unsafe {
            from_glib(ffi::gsk_gl_shader_get_uniform_type(
                self.to_glib_none().0,
                idx,
            ))
        }
    }
}

#[derive(Clone, Default)]
// rustdoc-stripper-ignore-next
/// A [builder-pattern] type to construct [`GLShader`] objects.
///
/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
#[must_use = "The builder must be built to be used"]
pub struct GLShaderBuilder {
    resource: Option<String>,
    source: Option<glib::Bytes>,
}

impl GLShaderBuilder {
    // rustdoc-stripper-ignore-next
    /// Create a new [`GLShaderBuilder`].
    pub fn new() -> Self {
        Self::default()
    }

    // rustdoc-stripper-ignore-next
    /// Build the [`GLShader`].
    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
    pub fn build(self) -> GLShader {
        let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
        if let Some(ref resource) = self.resource {
            properties.push(("resource", resource));
        }
        if let Some(ref source) = self.source {
            properties.push(("source", source));
        }
        glib::Object::new::<GLShader>(&properties)
    }

    /// Resource containing the source code for the shader.
    ///
    /// If the shader source is not coming from a resource, this
    /// will be [`None`].
    pub fn resource(mut self, resource: &str) -> Self {
        self.resource = Some(resource.to_string());
        self
    }

    pub fn source(mut self, source: &glib::Bytes) -> Self {
        self.source = Some(source.clone());
        self
    }
}

impl fmt::Display for GLShader {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("GLShader")
    }
}