fyrox_material/shader/
mod.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Shader is a script for graphics card, it defines how to draw an object. It also defines a set
22//! of external resources needed for the rendering.
23//!
24//! # Structure
25//!
26//! Shader has rigid structure that could be described in this code snipped:
27//!
28//! ```ron
29//! (
30//!     name: "MyShader",
31//!
32//!     // A set of resources, the maximum amount of resources is limited by your GPU. The engine
33//!     // guarantees, that there could at least 16 textures and 16 resource groups per shader.
34//!     resources: [
35//!         (
36//!             // Each resource binding must have a name.
37//!             name: "diffuseTexture",
38//!
39//!             // Value has limited set of possible variants.
40//!             kind: Texture(kind: Sampler2D, fallback: White),
41//!
42//!             binding: 0
43//!         ),
44//!         (
45//!             name: "properties",
46//!             kind: PropertyGroup([
47//!                 (
48//!                     name: "diffuseColor",
49//!                     kind: Color(r: 255, g: 255, b: 255, a: 255),
50//!                 ),
51//!             ]),
52//!             binding: 0
53//!         ),
54//!         // There are number of built-in property groups which provides useful data for each shader.
55//!         // See the full list of built-in property groups below.
56//!         (
57//!             name: "fyrox_instanceData",
58//!             kind: PropertyGroup([
59//!                 // Autogenerated
60//!             ]),
61//!             binding: 1
62//!         ),
63//!     ],
64//!
65//!     // A set of passes that are intentionally missing in the shader.
66//!     disabled_passes: ["GBuffer", "DirectionalShadow", "PointShadow", "SpotShadow"],
67//!
68//!     // A set of render passes (see a section `Render pass` for more info)
69//!     passes: [
70//!         (
71//!             // Name must match with the name of either standard render pass (see below) or
72//!             // one of your passes.
73//!             name: "Forward",
74//!
75//!             // A set of parameters that regulate renderer pipeline state.
76//!             // This is mandatory field of each render pass.
77//!             draw_parameters: DrawParameters(
78//!                 // A face to cull. Either Front or Back.
79//!                 cull_face: Some(Back),
80//!
81//!                 // Color mask. Defines which colors should be written to render target.
82//!                 color_write: ColorMask(
83//!                     red: true,
84//!                     green: true,
85//!                     blue: true,
86//!                     alpha: true,
87//!                 ),
88//!
89//!                 // Whether to modify depth buffer or not.
90//!                 depth_write: true,
91//!
92//!                 // Whether to use stencil test or not.
93//!                 stencil_test: None,
94//!
95//!                 // Whether to perform depth test when drawing.
96//!                 depth_test: Some(Less),
97//!
98//!                 // Blending options.
99//!                 blend: Some(BlendParameters(
100//!                     func: BlendFunc(
101//!                         sfactor: SrcAlpha,
102//!                         dfactor: OneMinusSrcAlpha,
103//!                         alpha_sfactor: SrcAlpha,
104//!                         alpha_dfactor: OneMinusSrcAlpha,
105//!                     ),
106//!                     equation: BlendEquation(
107//!                         rgb: Add,
108//!                         alpha: Add
109//!                     )
110//!                 )),
111//!
112//!                 // Stencil options.
113//!                 stencil_op: StencilOp(
114//!                     fail: Keep,
115//!                     zfail: Keep,
116//!                     zpass: Keep,
117//!                     write_mask: 0xFFFF_FFFF,
118//!                 ),
119//!
120//!                 // Scissor box. Could be something like this:
121//!                 //
122//!                 // scissor_box: Some(ScissorBox(
123//!                 //    x: 10,
124//!                 //    y: 20,
125//!                 //    width: 100,
126//!                 //    height: 30
127//!                 // ))
128//!                 scissor_box: None
129//!             ),
130//!
131//!             // Vertex shader code.
132//!             vertex_shader:
133//!                 r#"
134//!                 layout(location = 0) in vec3 vertexPosition;
135//!                 layout(location = 1) in vec2 vertexTexCoord;
136//!
137//!                 out vec2 texCoord;
138//!
139//!                 void main()
140//!                 {
141//!                     texCoord = vertexTexCoord;
142//!                     gl_Position = fyrox_instanceData.worldViewProjection * vec4(vertexPosition, 1.0);
143//!                 }
144//!                 "#,
145//!
146//!             // Fragment shader code.
147//!             fragment_shader:
148//!                 r#"
149//!                 out vec4 FragColor;
150//!
151//!                 in vec2 texCoord;
152//!
153//!                 void main()
154//!                 {
155//!                     FragColor = properties.diffuseColor * texture(diffuseTexture, texCoord);
156//!                 }
157//!                 "#,
158//!         )
159//!     ],
160//! )
161//! ```
162//!
163//! Shader should contain at least one render pass to actually do some job. A shader could not
164//! have properties at all. Currently only vertex and fragment programs are supported. Each
165//! program mush be written in GLSL. Comprehensive GLSL documentation can be found
166//! [here](https://www.khronos.org/opengl/wiki/Core_Language_(GLSL))
167//!
168//! # Render pass
169//!
170//! Modern rendering is a very complex thing that requires drawing an object multiple times
171//! with different "scripts". For example to draw an object with shadows you need to draw an
172//! object twice: one directly in a render target, and one in a shadow map. Such stages called
173//! render passes.
174//!
175//! Binding of shaders to render passes is done via names, each render pass has unique name.
176//!
177//! ## Predefined passes
178//!
179//! There are number of predefined render passes:
180//!
181//! - `GBuffer` - A pass that fills a set of textures (render targets) with various data about each
182//!   rendered object (depth, normal, albedo, etc.). These textures then are used for physically-based
183//!   lighting. Use this pass when you want the standard lighting to work with your objects.
184//!
185//! - `Forward` - A pass that draws an object directly in a render target. It could be used to render
186//!   translucent objects.
187//!
188//! - `SpotShadow` - A pass that emits depth values for an object, later this depth map will be
189//!   used to render shadows.
190//!
191//! - `PointShadow` - A pass that emits distance from a fragment to a point light, later this depth
192//!   map will be used to render shadows.
193//!
194//! - `DirectionalShadow` - A pass that emits depth values for an object, later this depth map will be
195//!   used to render shadows for directional cascaded shadows.
196//!
197//! ## Disables passes
198//!
199//! A render pass can be marked as "disabled" to prevent the renderer emitting errors when it tries
200//! to use such render pass. This mechanism of explicit marking the pass disabled is here to ensure
201//! correctness of shaders. To explicitly disable a pass, add its name to `disabled_passes` array:
202//!
203//! ```ron
204//! disabled_passes: ["GBuffer", "DirectionalShadow", "PointShadow", "SpotShadow"],
205//! ```
206//!
207//! # Resources
208//!
209//! Each shader requires a specific set of external resources that will be used during the rendering.
210//! This set is defined in `resources` section of the shader and could contain the following resources:
211//!
212//! - `Texture` - a texture of arbitrary type
213//! - `PropertyGroup` - a group of numeric properties.
214//!
215//! ## Binding points
216//!
217//! Shader resource must define a unique (over its type) binding index. The engine will use these
218//! points to prepare appropriate resource descriptor sets for GPU. Keep in mind, that binding point
219//! indices are **unique** per each type of resource. This means that a set of texture resource could
220//! use the same indices as property groups. The binding points must be unique in its group. If
221//! there are more than one resource of a certain type, that shares the same binding point, the
222//! engine will refuse to use such shader.
223//!
224//! ## Built-in resources
225//!
226//! There are number of built-in resources, that Fyrox will try to assign automatically if they're
227//! defined in your shader, something like this:
228//!
229//! ```ron
230//! (
231//!     name: "fyrox_instanceData",
232//!     kind: PropertyGroup([
233//!         // Autogenerated
234//!     ]),
235//!     binding: 1
236//! ),
237//! ```
238//!
239//! The full list of built-in resources is defined below.
240//!
241//! ### `fyrox_instanceData`
242//!
243//! Property group. Provided for each rendered surface instance.
244//!
245//! | Name                 | Type       | Description                                 |
246//! |----------------------|------------|---------------------------------------------|
247//! | worldMatrix          | `mat4`     | Local-to-world transformation.              |
248//! | worldViewProjection  | `mat4`     | Local-to-clip-space transform.              |
249//! | blendShapesCount     | `int`      | Total amount of blend shapes.               |
250//! | useSkeletalAnimation | `bool`     | Whether skinned meshes is rendering or not. |
251//! | blendShapesWeights   | `vec4[32]` | Blend shape weights.                        |
252//!
253//! ### `fyrox_boneMatrices`
254//!
255//! Property group. Provided for each rendered surface, that has skeletal animation.
256//!
257//! | Name     | Type        | Description   |
258//! |----------|-------------|---------------|
259//! | matrices | `mat4[256]` | Bone matrices |
260//!
261//!
262//! ### `fyrox_cameraData`
263//!
264//! Property group. Contains camera properties. It contains info not only about scene camera,
265//! but also observer info when rendering shadow maps. In other words - it is generic observer
266//! properties.
267//!
268//! | Name                 | Type       | Description                                      |
269//! |----------------------|------------|--------------------------------------------------|
270//! | viewProjectionMatrix | `mat4`     | World-to-clip-space transformation.              |
271//! | position             | `vec3`     | World-space position of the camera.              |
272//! | upVector             | `vec3`     | World-space up-vector of the camera.             |
273//! | sideVector           | `vec3`     | World-space side-vector of the camera.           |
274//! | zNear                | `float`    | Near clipping plane location.                    |
275//! | zFar                 | `float`    | Far clipping plane location.                     |
276//! | zRange               | `float`    | `zFar - zNear`                                   |
277//!
278//! ### `fyrox_lightData`
279//!
280//! Property group. Available only in shadow passes.
281//!
282//! | Name              | Type   | Description                                                |
283//! |-------------------|--------|------------------------------------------------------------|
284//! | lightPosition     | `vec3` | World-space light source position. Only for shadow passes. |
285//! | ambientLightColor | `vec4` | Ambient lighting color of the scene.                       |
286//!
287//! ### `fyrox_lightsBlock`
288//!
289//! Property group. Information about visible light sources
290//!
291//! | Name              | Type       | Description                                             |
292//! |------------------ |------------|---------------------------------------------------------|
293//! | lightCount        | `int`      | Total amount of light sources visible on screen.        |
294//! | lightsColorRadius | `vec4[16]` | Color (xyz) and radius (w) of light source              |
295//! | lightsParameters  | `vec2[16]` | Hot-spot cone angle cos (x) and half cone angle cos (y) |
296//! | lightsPosition    | `vec3[16]` | World-space light position.                             |
297//! | lightsDirection   | `vec3[16]` | World-space light direction                             |
298//!
299//! ### `fyrox_graphicsSettings`
300//!
301//! Property group. Contains graphics options of the renderer.
302//!
303//! | Name   | Type       | Description                                       |
304//! |--------|------------|---------------------------------------------------|
305//! | usePom | `bool`     | Whether to use parallax occlusion mapping or not. |
306//!
307//! ### `fyrox_sceneDepth`
308//!
309//! Texture. Contains depth values of scene. Available **only** after opaque geometry is
310//! rendered (read - G-Buffer is filled). Typical usage is something like this:
311//!
312//! ```ron
313//! (
314//!     name: "fyrox_sceneDepth",
315//!     kind: Texture(kind: Sampler2D, fallback: White),
316//!     binding: 1
317//! ),
318//! ```
319//!
320//! ### `fyrox_widgetData`
321//!
322//! Property group. Contains UI widget-specific data, that can be used in UI shaders.
323//!
324//! | Name                | Type        | Description                                                |
325//! |---------------------|-------------|------------------------------------------------------------|
326//! | worldViewProjection | `mat4`      | World-to-clip-space transformation matrix.                 |
327//! | solidColor          | `vec4`      | RGBA color.                                                |
328//! | gradientColors      | `vec4[16]`  | A set of gradient colors.                                  |
329//! | gradientStops       | `float[16]` | A set of normalized (0.0-1.0) stops along the axis.        |
330//! | gradientOrigin      | `vec2`      | Origin position of the gradient (local coordinates).       |
331//! | gradientEnd         | `vec2`      | End position of the gradient (local coordinates).          |
332//! | gradientPointCount  | `int`       | Total number of gradient points.                           |
333//! | resolution          | `vec2`      | Frame buffer size to which the widget is drawn to.         |
334//! | boundsMin           | `vec2`      | Top-left point of the screen space bounding rectangle.     |
335//! | boundsMax           | `vec2`      | Right-bottom point of the screen space bounding rectangle. |
336//! | isFont              | `bool`      | `true` if the widget is a text, `false` - otherwise.       |
337//! | opacity             | `float`     | Opacity (0.0-1.0 range).                                   |
338//! | brushType           | `int`       | Brush type (0 solid, 1-linear gradient, 2-radial gradient  |
339//!
340//! # Code generation
341//!
342//! Fyrox automatically generates code for resource bindings. This is made specifically to prevent
343//! subtle mistakes. For example when you define this set of resources:
344//!
345//! ```ron
346//! (
347//!     name: "MyShader",
348//!
349//!     resources: [
350//!         (
351//!             name: "diffuseTexture",
352//!             kind: Texture(kind: Sampler2D, fallback: White),
353//!             binding: 0
354//!         ),
355//!         (
356//!             name: "normalTexture",
357//!             kind: Texture(kind: Sampler2D, fallback: Normal),
358//!             binding: 1
359//!         ),
360//!         (
361//!             name: "properties",
362//!             kind: PropertyGroup([
363//!                 (
364//!                     name: "texCoordScale",
365//!                     kind: Vector2(value: (1.0, 1.0)),
366//!                 ),
367//!                 (
368//!                     name: "diffuseColor",
369//!                     kind: Color(r: 255, g: 255, b: 255, a: 255),
370//!                 ),
371//!             ]),
372//!             binding: 0
373//!         ),
374//!     ]
375//! )
376//! ```
377//!
378//! The engine generates the following code and adds it to source code of every shader of every pass
379//! automatically:
380//!
381//! ```glsl
382//! uniform sampler2D diffuseTexture;
383//! uniform sampler2D normalTexture;
384//! struct Tproperties {
385//!     vec2 texCoordScale;
386//!     vec4 diffuseColor;
387//! };
388//! layout(std140) uniform Uproperties { Tproperties properties; }
389//! ```
390//!
391//! The most important thing is that the engine keeps properties in the `struct Tproperties` in
392//! correct order and forces `std140` layout on the generated uniform block. Since the engine knows
393//! the layout of the properties from their definition section, it could easily form a memory block
394//! with all required alignments and paddings that could be uploaded to GPU. The next important thing
395//! is that the engine batches all the data needed into a large chunks of data and uploads them
396//! all at once, which is much faster.
397//!
398//! # Drawing parameters
399//!
400//! Drawing parameters defines which GPU functions to use and at which state. For example, to render
401//! transparent objects you need to enable blending with specific blending rules. Or you need to disable
402//! culling to draw objects from both sides. This is when draw parameters comes in handy.
403//!
404//! There are relatively large list of drawing parameters, and it could confuse a person who didn't get
405//! used to work with graphics. The following list should help you to use drawing parameters correctly.
406//!
407//! - cull_face
408//!     - Defines which side of polygon should be culled.
409//!     - **Possible values:** `None`, [Some(CullFace::XXX)](fyrox_graphics::CullFace)
410//!
411//! - color_write:
412//!     - Defines which components of color should be written to a render target
413//!     - **Possible values:** [ColorMask](fyrox_graphics::ColorMask)(...)
414//!
415//!  - depth_write:
416//!     - Whether to modify depth buffer or not.
417//!     - **Possible values:** `true/false`
418//!
419//!  - stencil_test:
420//!     - Whether to use stencil test or not.
421//!     - **Possible values:**
422//!         - `None`
423//!         - Some([StencilFunc](fyrox_graphics::StencilFunc))
424//!
425//!  - depth_test:
426//!      - Whether to perform depth test when drawing.
427//!      - **Possible values:** `true/false`
428//!
429//!   - blend:
430//!      - Blending options.
431//!      - **Possible values:**
432//!         - `None`
433//!         - Some([BlendFunc](fyrox_graphics::BlendFunc))
434//!
435//!   - stencil_op:
436//!      - Stencil options.
437//!      - **Possible values:** [StencilOp](fyrox_graphics::StencilOp)
438//!
439//!    - `scissor_box`:
440//!       - A rectangle that is used for clipping (screen-space). This value can be redefined when
441//!         issuing a drawing command.
442//!       - `None`
443//!       - `Some(ScissorBox(x: 10, y: 20, width: 100, height: 30))`
444//!
445//! # Standard shader
446//!
447//! By default, Fyrox uses standard material for rendering, it covers 95% of uses cases and it is very
448//! flexible. To get standard shader instance, use [`ShaderResource::standard`]
449//!
450//! ```no_run
451//! # use fyrox_material::shader::{ShaderResource, ShaderResourceExtension};
452//!
453//! let standard_shader = ShaderResource::standard();
454//! ```
455//!
456//! Usually you don't need to get this shader manually, using of [Material::standard](super::Material::standard)
457//! is enough.
458
459use fyrox_core::some_or_continue;
460use fyrox_core::{
461    io::FileError, reflect::prelude::*, sparse::AtomicIndex, uuid::Uuid, visitor::prelude::*,
462    TypeUuidProvider,
463};
464pub use fyrox_graphics::gpu_program::{
465    SamplerFallback, ShaderResourceDefinition, ShaderResourceKind,
466};
467use fyrox_graphics::{gpu_program::ShaderProperty, DrawParameters};
468use fyrox_resource::{
469    embedded_data_source, io::ResourceIo, manager::BuiltInResource, untyped::ResourceKind,
470    Resource, ResourceData, SHADER_RESOURCE_UUID,
471};
472use lazy_static::lazy_static;
473use ron::ser::PrettyConfig;
474use serde::{Deserialize, Serialize};
475use std::{
476    error::Error,
477    fmt::{Display, Formatter},
478    fs::File,
479    io::Write,
480    path::Path,
481    sync::Arc,
482};
483use uuid::uuid;
484
485pub mod loader;
486
487/// A name of the standard shader.
488pub const STANDARD_SHADER_NAME: &str = "Standard";
489
490/// A name of the standard 2D shader.
491pub const STANDARD_2D_SHADER_NAME: &str = "Standard2D";
492
493/// A name of the standard particle system shader.
494pub const STANDARD_PARTICLE_SYSTEM_SHADER_NAME: &str = "StandardParticleSystem";
495
496/// A name of the standard two-sides shader.
497pub const STANDARD_TWOSIDES_SHADER_NAME: &str = "StandardTwoSides";
498
499/// A name of the standard terrain shader.
500pub const STANDARD_TERRAIN_SHADER_NAME: &str = "StandardTerrain";
501
502/// A name of the standard tile shader.
503pub const STANDARD_TILE_SHADER_NAME: &str = "StandardTile";
504
505/// A name of the standard sprite shader.
506pub const STANDARD_SPRITE_SHADER_NAME: &str = "StandardSprite";
507
508/// A name of the standard widget shader.
509pub const STANDARD_WIDGET_SHADER_NAME: &str = "StandardWidget";
510
511/// Internal state of the shader.
512///
513/// # Notes
514///
515/// Usually you don't need to access internals of the shader, but there sometimes could be a need to
516/// read shader definition, to get supported passes and properties.
517#[derive(Default, Debug, Clone, Reflect, Visit)]
518pub struct Shader {
519    /// Shader definition contains description of properties and render passes.
520    #[visit(optional)]
521    pub definition: ShaderDefinition,
522
523    /// An id that can be used to create associated GPU resources.
524    #[reflect(hidden)]
525    #[visit(skip)]
526    pub cache_index: Arc<AtomicIndex>,
527}
528
529impl TypeUuidProvider for Shader {
530    fn type_uuid() -> Uuid {
531        SHADER_RESOURCE_UUID
532    }
533}
534
535/// A render pass definition. See [`ShaderResource`] docs for more info about render passes.
536#[derive(Default, Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Reflect, Visit)]
537pub struct RenderPassDefinition {
538    /// A name of render pass.
539    pub name: String,
540    /// A set of parameters that will be used in a render pass.
541    #[serde(default)]
542    pub draw_parameters: DrawParameters,
543    /// A source code of vertex shader.
544    pub vertex_shader: String,
545    /// Vertex shader line number.
546    #[serde(default)]
547    pub vertex_shader_line: isize,
548    /// A source code of fragment shader.
549    pub fragment_shader: String,
550    /// Fragment shader line number.
551    #[serde(default)]
552    pub fragment_shader_line: isize,
553}
554
555/// A definition of the shader.
556#[derive(Default, Clone, Serialize, Deserialize, Debug, PartialEq, Reflect, Visit)]
557pub struct ShaderDefinition {
558    /// A name of the shader.
559    pub name: String,
560    /// A set of render passes.
561    pub passes: Vec<RenderPassDefinition>,
562    /// A set of resource definitions.
563    pub resources: Vec<ShaderResourceDefinition>,
564    /// A list of names of disabled render passes. It is used to strictly indicate that certain
565    /// passes are intentionally disabled in the rendering process.
566    #[serde(default)]
567    pub disabled_passes: Vec<String>,
568}
569
570impl ShaderDefinition {
571    /// Maximum number of simultaneous light sources that can be passed into a standard lights data
572    /// block.
573    pub const MAX_LIGHTS: usize = 16;
574
575    /// Maximum number of bone matrices per shader.
576    pub const MAX_BONE_MATRICES: usize = 255;
577
578    /// Maximum number of blend shape weight groups (packed weights of blend shapes into vec4).
579    pub const MAX_BLEND_SHAPE_WEIGHT_GROUPS: usize = 32;
580
581    /// Maximum number of gradient values per widget.
582    pub const MAX_GRADIENT_VALUE_COUNT: usize = 16;
583
584    fn find_shader_line_locations(&mut self, str: &str) {
585        let mut line_ends = Vec::new();
586        for (i, ch) in str.bytes().enumerate() {
587            if ch == b'\n' {
588                line_ends.push(i);
589            }
590        }
591        if str.bytes().last().is_some_and(|ch| ch != b'\n') {
592            line_ends.push(str.len());
593        }
594
595        fn find_line(line_ends: &[usize], byte_pos: usize) -> isize {
596            line_ends
597                .windows(2)
598                .enumerate()
599                .find_map(|(line_num, ends)| {
600                    if (ends[0]..ends[1]).contains(&byte_pos) {
601                        Some(line_num)
602                    } else {
603                        None
604                    }
605                })
606                .unwrap_or(0) as isize
607                + 1
608        }
609
610        let vertex_shader_regex = regex::Regex::new(r#"vertex_shader\s*:\s*r?#*""#).unwrap();
611        let fragment_shader_regex = regex::Regex::new(r#"fragment_shader\s*:\s*r?#*""#).unwrap();
612
613        let mut substr = str;
614        for pass in self.passes.iter_mut() {
615            let name_location = some_or_continue!(substr.find(&format!("\"{}\"", pass.name)));
616            let vertex_shader_location = some_or_continue!(vertex_shader_regex.find(substr));
617            let fragment_shader_location = some_or_continue!(fragment_shader_regex.find(substr));
618            let offset = str.len() - substr.len();
619            pass.vertex_shader_line = find_line(&line_ends, offset + vertex_shader_location.end());
620            pass.fragment_shader_line =
621                find_line(&line_ends, offset + fragment_shader_location.end());
622            let max = name_location
623                .max(vertex_shader_location.end())
624                .max(fragment_shader_location.end());
625            substr = &substr[(max + 1)..];
626        }
627    }
628
629    fn from_str(str: &str) -> Result<Self, ShaderError> {
630        let mut definition: ShaderDefinition = ron::de::from_str(str)?;
631        definition.generate_built_in_resources();
632        definition.find_shader_line_locations(str);
633        Ok(definition)
634    }
635
636    fn generate_built_in_resources(&mut self) {
637        for resource in self.resources.iter_mut() {
638            let ShaderResourceKind::PropertyGroup(ref mut properties) = resource.kind else {
639                continue;
640            };
641
642            match resource.name.as_str() {
643                "fyrox_widgetData" => {
644                    properties.clear();
645                    properties.extend([
646                        ShaderProperty::new_matrix4("worldViewProjection"),
647                        ShaderProperty::new_color("solidColor"),
648                        ShaderProperty::new_vec4_f32_array(
649                            "gradientColors",
650                            Self::MAX_GRADIENT_VALUE_COUNT,
651                        ),
652                        ShaderProperty::new_f32_array(
653                            "gradientStops",
654                            Self::MAX_GRADIENT_VALUE_COUNT,
655                        ),
656                        ShaderProperty::new_vector2("gradientOrigin"),
657                        ShaderProperty::new_vector2("gradientEnd"),
658                        ShaderProperty::new_vector2("resolution"),
659                        ShaderProperty::new_vector2("boundsMin"),
660                        ShaderProperty::new_vector2("boundsMax"),
661                        ShaderProperty::new_bool("isFont"),
662                        ShaderProperty::new_float("opacity"),
663                        ShaderProperty::new_int("brushType"),
664                        ShaderProperty::new_int("gradientPointCount"),
665                    ]);
666                }
667                "fyrox_cameraData" => {
668                    properties.clear();
669                    properties.extend([
670                        ShaderProperty::new_matrix4("viewProjectionMatrix"),
671                        ShaderProperty::new_vector3("position"),
672                        ShaderProperty::new_vector3("upVector"),
673                        ShaderProperty::new_vector3("sideVector"),
674                        ShaderProperty::new_float("zNear"),
675                        ShaderProperty::new_float("zFar"),
676                        ShaderProperty::new_float("zRange"),
677                    ]);
678                }
679                "fyrox_lightData" => {
680                    properties.clear();
681                    properties.extend([
682                        ShaderProperty::new_vector3("lightPosition"),
683                        ShaderProperty::new_vector4("ambientLightColor"),
684                    ]);
685                }
686                "fyrox_graphicsSettings" => {
687                    properties.clear();
688                    properties.extend([ShaderProperty::new_bool("usePOM")]);
689                }
690                "fyrox_lightsBlock" => {
691                    properties.clear();
692                    properties.extend([
693                        ShaderProperty::new_int("lightCount"),
694                        ShaderProperty::new_vec4_f32_array("lightsColorRadius", Self::MAX_LIGHTS),
695                        ShaderProperty::new_vec2_f32_array("lightsParameters", Self::MAX_LIGHTS),
696                        ShaderProperty::new_vec3_f32_array("lightsPosition", Self::MAX_LIGHTS),
697                        ShaderProperty::new_vec3_f32_array("lightsDirection", Self::MAX_LIGHTS),
698                    ])
699                }
700                "fyrox_instanceData" => {
701                    properties.clear();
702                    properties.extend([
703                        ShaderProperty::new_matrix4("worldMatrix"),
704                        ShaderProperty::new_matrix4("worldViewProjection"),
705                        ShaderProperty::new_int("blendShapesCount"),
706                        ShaderProperty::new_bool("useSkeletalAnimation"),
707                        ShaderProperty::new_vec4_f32_array(
708                            "blendShapesWeights",
709                            Self::MAX_BLEND_SHAPE_WEIGHT_GROUPS,
710                        ),
711                    ]);
712                }
713                "fyrox_boneMatrices" => {
714                    properties.clear();
715                    properties.extend([ShaderProperty::new_mat4_f32_array(
716                        "matrices",
717                        Self::MAX_BONE_MATRICES,
718                    )])
719                }
720                _ => (),
721            }
722        }
723    }
724}
725
726impl Shader {
727    /// Creates a shader from file.
728    pub async fn from_file<P: AsRef<Path>>(
729        path: P,
730        io: &dyn ResourceIo,
731    ) -> Result<Self, ShaderError> {
732        let bytes = io.load_file(path.as_ref()).await?;
733        let content = String::from_utf8_lossy(&bytes);
734        Ok(Self {
735            definition: ShaderDefinition::from_str(&content)?,
736            cache_index: Default::default(),
737        })
738    }
739
740    /// Creates a shader from string.
741    pub fn from_string(str: &str) -> Result<Self, ShaderError> {
742        Ok(Self {
743            definition: ShaderDefinition::from_str(str)?,
744            cache_index: Default::default(),
745        })
746    }
747
748    /// Creates a shader from string represented as raw bytes. This function will fail if the `bytes`
749    /// does not contain Utf8-encoded string.
750    pub fn from_string_bytes(bytes: &[u8]) -> Result<Self, ShaderError> {
751        Ok(Self {
752            definition: ShaderDefinition::from_str(
753                std::str::from_utf8(bytes).map_err(|_| ShaderError::NotUtf8Source)?,
754            )?,
755            cache_index: Default::default(),
756        })
757    }
758}
759
760impl ResourceData for Shader {
761    fn type_uuid(&self) -> Uuid {
762        <Self as TypeUuidProvider>::type_uuid()
763    }
764
765    fn save(&mut self, path: &Path) -> Result<(), Box<dyn Error>> {
766        let mut file = File::create(path)?;
767        file.write_all(
768            ron::ser::to_string_pretty(&self.definition, PrettyConfig::default())?.as_bytes(),
769        )?;
770        Ok(())
771    }
772
773    fn can_be_saved(&self) -> bool {
774        true
775    }
776
777    fn try_clone_box(&self) -> Option<Box<dyn ResourceData>> {
778        Some(Box::new(self.clone()))
779    }
780}
781
782/// A set of possible error variants that can occur during shader loading.
783#[derive(Debug)]
784pub enum ShaderError {
785    /// An i/o error has occurred.
786    Io(FileError),
787
788    /// A parsing error has occurred.
789    ParseError(ron::error::SpannedError),
790
791    /// Bytes does not represent Utf8-encoded string.
792    NotUtf8Source,
793}
794
795impl Display for ShaderError {
796    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
797        match self {
798            ShaderError::Io(v) => {
799                write!(f, "A file load error has occurred {v:?}")
800            }
801            ShaderError::ParseError(v) => {
802                write!(f, "A parsing error has occurred {v:?}")
803            }
804            ShaderError::NotUtf8Source => {
805                write!(f, "Bytes does not represent Utf8-encoded string.")
806            }
807        }
808    }
809}
810
811impl From<ron::error::SpannedError> for ShaderError {
812    fn from(e: ron::error::SpannedError) -> Self {
813        Self::ParseError(e)
814    }
815}
816
817impl From<FileError> for ShaderError {
818    fn from(e: FileError) -> Self {
819        Self::Io(e)
820    }
821}
822
823/// Type alias for shader resources.
824pub type ShaderResource = Resource<Shader>;
825
826/// Extension trait for shader resources.
827pub trait ShaderResourceExtension: Sized {
828    /// Creates new shader from given string. Input string must have the format defined in
829    /// examples for [`ShaderResource`].
830    fn from_str(id: Uuid, str: &str, kind: ResourceKind) -> Result<Self, ShaderError>;
831
832    /// Returns an instance of standard shader.
833    fn standard() -> Self;
834
835    /// Returns an instance of standard 2D shader.
836    fn standard_2d() -> Self;
837
838    /// Returns an instance of standard particle system shader.
839    fn standard_particle_system() -> Self;
840
841    /// Returns an instance of standard sprite shader.
842    fn standard_sprite() -> Self;
843
844    /// Returns an instance of standard terrain shader.
845    fn standard_terrain() -> Self;
846
847    /// Returns an instance of standard tile shader.
848    fn standard_tile() -> Self;
849
850    /// Returns an instance of standard two-sides terrain shader.
851    fn standard_twosides() -> Self;
852
853    /// Returns an instance of standard widget shader.
854    fn standard_widget() -> Self;
855
856    /// Returns a list of standard shader.
857    fn standard_shaders() -> [&'static BuiltInResource<Shader>; 8];
858}
859
860impl ShaderResourceExtension for ShaderResource {
861    fn from_str(id: Uuid, str: &str, kind: ResourceKind) -> Result<Self, ShaderError> {
862        Ok(Resource::new_ok(id, kind, Shader::from_string(str)?))
863    }
864
865    fn standard() -> Self {
866        STANDARD.resource()
867    }
868
869    fn standard_2d() -> Self {
870        STANDARD_2D.resource()
871    }
872
873    fn standard_particle_system() -> Self {
874        STANDARD_PARTICLE_SYSTEM.resource()
875    }
876
877    fn standard_sprite() -> Self {
878        STANDARD_SPRITE.resource()
879    }
880
881    fn standard_terrain() -> Self {
882        STANDARD_TERRAIN.resource()
883    }
884
885    fn standard_tile() -> Self {
886        STANDARD_TILE.resource()
887    }
888
889    fn standard_twosides() -> Self {
890        STANDARD_TWOSIDES.resource()
891    }
892
893    fn standard_widget() -> Self {
894        STANDARD_WIDGET.resource()
895    }
896
897    fn standard_shaders() -> [&'static BuiltInResource<Shader>; 8] {
898        [
899            &STANDARD,
900            &STANDARD_2D,
901            &STANDARD_PARTICLE_SYSTEM,
902            &STANDARD_SPRITE,
903            &STANDARD_TERRAIN,
904            &STANDARD_TWOSIDES,
905            &STANDARD_TILE,
906            &STANDARD_WIDGET,
907        ]
908    }
909}
910
911lazy_static! {
912    /// Standard shader.
913    pub static ref STANDARD: BuiltInResource<Shader> = BuiltInResource::new(
914        STANDARD_SHADER_NAME,
915        embedded_data_source!("standard/standard.shader"),
916        |data| {
917            ShaderResource::new_ok(
918                uuid!("87195f6e-cba4-4c27-9f89-d0bf726db965"),
919                ResourceKind::External,
920                Shader::from_string_bytes(data).unwrap(),
921            )
922        }
923    );
924    /// Standard 2D shader.
925    pub static ref STANDARD_2D: BuiltInResource<Shader> = BuiltInResource::new(
926        STANDARD_2D_SHADER_NAME,
927        embedded_data_source!("standard/standard2d.shader"),
928        |data| ShaderResource::new_ok(
929            uuid!("55fa05b0-3c25-4e46-bae7-65f093185b75"),
930            ResourceKind::External,
931            Shader::from_string_bytes(data).unwrap(),
932        )
933    );
934    /// Standard particle system shader.
935    pub static ref STANDARD_PARTICLE_SYSTEM: BuiltInResource<Shader> = BuiltInResource::new(
936        STANDARD_PARTICLE_SYSTEM_SHADER_NAME,
937        embedded_data_source!("standard/standard_particle_system.shader"),
938        |data| ShaderResource::new_ok(
939            uuid!("eb474445-6a25-4481-bca9-f919699c300f"),
940            ResourceKind::External,
941            Shader::from_string_bytes(data).unwrap(),
942        )
943    );
944    /// Standard sprite shader.
945    pub static ref STANDARD_SPRITE: BuiltInResource<Shader> = BuiltInResource::new(
946        STANDARD_SPRITE_SHADER_NAME,
947        embedded_data_source!("standard/standard_sprite.shader"),
948        |data| ShaderResource::new_ok(
949            uuid!("a135826a-4c1b-46d5-ba1f-0c9a226aa52c"),
950            ResourceKind::External,
951            Shader::from_string_bytes(data).unwrap(),
952        )
953    );
954    /// Standard terrain shader.
955    pub static ref STANDARD_TERRAIN: BuiltInResource<Shader> = BuiltInResource::new(
956        STANDARD_TERRAIN_SHADER_NAME,
957        embedded_data_source!("standard/terrain.shader"),
958        |data| {
959            ShaderResource::new_ok(
960                uuid!("4911aafe-9bb1-4115-a958-25b57b87b51e"),
961                ResourceKind::External,
962                Shader::from_string_bytes(data).unwrap(),
963            )
964        }
965    );
966    /// Standard tile shader.
967    pub static ref STANDARD_TILE: BuiltInResource<Shader> = BuiltInResource::new(
968        STANDARD_TILE_SHADER_NAME,
969        embedded_data_source!("standard/tile.shader"),
970        |data| {
971            ShaderResource::new_ok(
972                uuid!("5f29dd3a-ea99-480c-bb02-d2c6420843b1"),
973                ResourceKind::External,
974                Shader::from_string_bytes(data).unwrap(),
975            )
976        }
977    );
978    /// Standard two-sides shader.
979    pub static ref STANDARD_TWOSIDES: BuiltInResource<Shader> = BuiltInResource::new(
980        STANDARD_TWOSIDES_SHADER_NAME,
981        embedded_data_source!("standard/standard-two-sides.shader"),
982        |data| ShaderResource::new_ok(
983            uuid!("f7979409-5185-4e1c-a644-d53cea64af8f"),
984            ResourceKind::External,
985            Shader::from_string_bytes(data).unwrap(),
986        )
987    );
988    /// Standard widget shader.
989    pub static ref STANDARD_WIDGET: BuiltInResource<Shader> = BuiltInResource::new(
990        STANDARD_WIDGET_SHADER_NAME,
991        embedded_data_source!("standard/widget.shader"),
992        |data| ShaderResource::new_ok(
993            uuid!("f5908aa4-e187-42a8-95d2-dc6577f6def4"),
994            ResourceKind::External,
995            Shader::from_string_bytes(data).unwrap(),
996        )
997    );
998}
999
1000#[cfg(test)]
1001mod test {
1002    use crate::shader::{
1003        RenderPassDefinition, SamplerFallback, ShaderDefinition, ShaderResource,
1004        ShaderResourceDefinition, ShaderResourceExtension, ShaderResourceKind,
1005    };
1006    use fyrox_graphics::gpu_program::SamplerKind;
1007    use fyrox_resource::untyped::ResourceKind;
1008    use uuid::Uuid;
1009
1010    #[test]
1011    fn test_shader_load() {
1012        let code = r#"
1013            (
1014                name: "TestShader",
1015
1016                resources: [
1017                    (
1018                        name: "diffuseTexture",
1019                        kind: Texture(kind: Sampler2D, fallback: White),
1020                        binding: 0
1021                    ),
1022                ],
1023
1024                passes: [
1025                    (
1026                        name: "GBuffer",
1027                        draw_parameters: DrawParameters(
1028                            cull_face: Some(Back),
1029                            color_write: ColorMask(
1030                                red: true,
1031                                green: true,
1032                                blue: true,
1033                                alpha: true,
1034                            ),
1035                            depth_write: true,
1036                            stencil_test: None,
1037                            depth_test: Some(Less),
1038                            blend: None,
1039                            stencil_op: StencilOp(
1040                                fail: Keep,
1041                                zfail: Keep,
1042                                zpass: Keep,
1043                                write_mask: 0xFFFF_FFFF,
1044                            ),
1045                            scissor_box: None
1046                        ),
1047                        vertex_shader: "<CODE>",
1048                        fragment_shader: "<CODE>",
1049                    ),
1050                ],
1051            )
1052            "#;
1053
1054        let shader =
1055            ShaderResource::from_str(Uuid::new_v4(), code, ResourceKind::External).unwrap();
1056        let data = shader.data_ref();
1057
1058        let reference_definition = ShaderDefinition {
1059            name: "TestShader".to_owned(),
1060            resources: vec![ShaderResourceDefinition {
1061                name: "diffuseTexture".into(),
1062                kind: ShaderResourceKind::Texture {
1063                    kind: SamplerKind::Sampler2D,
1064                    fallback: SamplerFallback::White,
1065                },
1066                binding: 0,
1067            }],
1068            passes: vec![RenderPassDefinition {
1069                name: "GBuffer".to_string(),
1070                draw_parameters: Default::default(),
1071                vertex_shader: "<CODE>".to_string(),
1072                vertex_shader_line: 35,
1073                fragment_shader: "<CODE>".to_string(),
1074                fragment_shader_line: 36,
1075            }],
1076            disabled_passes: vec![],
1077        };
1078
1079        assert_eq!(data.definition, reference_definition);
1080    }
1081}