检查英文版本文档 (#2696)

* fix: english check
This commit is contained in:
AZhan
2025-05-26 22:20:03 +08:00
committed by GitHub
parent 054f7daeeb
commit daeb250dd3
53 changed files with 1883 additions and 2061 deletions

View File

@@ -1,6 +1,7 @@
{
"material": { "title": " Material Overview" },
"composition": { "title": "Material Composition" },
"editor": { "title": "Using the Editor" },
"script": { "title": "Script Usage" }
"overview": { "title": "Material Overview" },
"examples": { "title": "Guidelines and Examples" },
"builtinShaders": { "title": "Built-in shaders" },
"shaderLab": { "title": "ShaderLab" },
"variables": "Built-in Variables"
}

View File

@@ -0,0 +1,6 @@
{
"pbr": "PBR",
"unlit": "Unlit",
"blinnPhong": "Blinn Phong",
"digitalHuman": "Digital Human"
}

View File

@@ -0,0 +1,26 @@
---
title: Blinn Phong
---
The [BlinnPhongMaterial](/apis/core/#BlinnPhongMaterial) is a classic material. Although not based on physically-based rendering (PBR), its efficient rendering algorithm and comprehensive optical properties make it still applicable in many scenarios today.
## Editor Usage
<img src="https://gw.alipayobjects.com/zos/OasisHub/eaa93827-29a4-46ad-b9d3-f179fa200c57/blinn.gif" alt="blinn" />
## Parameter Overview
| Parameter | Description |
| :-- | :-- |
| [baseColor](/apis/core/#BlinnPhongMaterial-baseColor) | Base color. **Base Color * Base Texture = Final Base Color** |
| [baseTexture](/apis/core/#BlinnPhongMaterial-baseTexture) | Base texture. Multiplied with base color. |
| [specularColor](/apis/core/#BlinnPhongMaterial-specularColor) | Specular color. **Specular Color * Specular Texture = Final Specular Color** |
| [specularTexture](/apis/core/#BlinnPhongMaterial-specularTexture) | Specular texture. Multiplied with specular color. |
| [normalTexture](/apis/core/#BlinnPhongMaterial-normalTexture) | Normal texture. Creates surface detail with a bump map, and controls depth via normal intensity. |
| [normalIntensity](/apis/core/#BlinnPhongMaterial-normalIntensity) | Normal intensity. Controls the strength of surface detail. |
| [emissiveColor](/apis/core/#BlinnPhongMaterial-emissiveColor) | Emissive color. **Emissive Color * Emissive Texture = Final Emissive Color** (renders color even without lighting). |
| [emissiveTexture](/apis/core/#BlinnPhongMaterial-emissiveTexture) | Emissive texture. Multiplied with emissive color. |
| [shininess](/apis/core/#BlinnPhongMaterial-shininess) | Shininess coefficient. Higher values produce more concentrated specular highlights. |
| [tilingOffset](/apis/core/#BlinnPhongMaterial-tilingOffset) | Texture tiling and offset. A Vector4 value controlling UV scale and offset (see [example](/embed/tiling-offset)). |
For script-based material usage, refer to the [material usage tutorial](/en/docs/graphics/material/examples/create/#4-script-based-method).

View File

@@ -0,0 +1,54 @@
---
title: Eyes
---
The eye shader provides realistic rendering for eye models, enhancing your creations with lifelike visual effects.
<img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*VVUtRL4JfE0AAAAAAAAAAAAADgDwAQ/original" />
<Callout type="info">
This shader is closely tied to model UV mapping. If you need to build eyes from scratch, this shader is not recommended. For users without shader coding experience, it's advised to use the official eye geometry model in the example, simply replacing necessary textures to meet your needs. To create custom eye shader variants, refer to the [Shader Lab development tutorial](/en/docs/graphics/shader/shaderLab/intro/) documentation.
</Callout>
## Importing Eye Examples
Galacean includes built-in eye material examples to help you get started. [Click here](https://galacean.antgroup.com/editor/projects) to view this example.
1. Navigate to the editor homepage in Galacean.
2. Select the **Templates** panel, browse the template interface, preview and download the eye example to your **Project**.
## Eye Anatomy Breakdown
Before rendering eyes, understand the biological structure of the eye to better utilize the shader.
| Parameter | Description |
| :-------------------- | :-------------------------------------------------------- |
| **Sclera** | The opaque outer layer of the eyeball, commonly known as "the white of the eye" |
| **Limbus** | Also called the corneoscleral junction, the boundary between the cornea and sclera |
| **Iris** | A ring of color surrounding the pupil, forming a hollow circle |
| **Pupil** | The black central part of the eyeball that allows light to enter and reach the retina |
| **Cornea** | The transparent front part of the eyeball |
## Eye Textures
| Texture | Parameter | Description |
| :---------------------------------------------------------------: | :------------------------: | :-------------------------------------------------------------------------- |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*74fgRYw9nS4AAAAAAAAAAAAADgDwAQ/original" /> | **Sclera Texture** | Controls the sclera (white of the eye) color and blood vessel color around the eye. Modify this texture to add bloodshot effects. |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*Nc_XTpVNlFAAAAAAAAAAAAAADgDwAQ/original" /> | **Iris Texture** | Controls the iris color |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*jkZ5QoeXyWUAAAAAAAAAAAAADgDwAQ/original" /> | **Iris Normal Texture** | Specifies a normal map for the iris surface to control light flow |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*B8McQpjhh98AAAAAAAAAAAAADgDwAQ/original" /> | **Cornea Normal Texture** | Specifies a normal map for the sclera to provide subtle texture variations on the white of the eye |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*c_zmQ5DwI1wAAAAAAAAAAAAADgDwAQ/original" /> | **Sclera Mask** | A mask texture controlling the size of sclera/iris/limbus/pupil. `R` channel controls the iris area, `G` channel controls the limbus area, `B` channel controls the pupil scaling area |
## Material Properties
| Parameter | Description |
| :------------------------ | :-------------------------------------: |
| **Sclera Color** | Sclera texture base color |
| **Sclera Size** | Sclera UV scale |
| **Sclera Specular** | Metalness of the sclera (white of eye) |
| **Sclera Roughness** | Roughness of the sclera (white of eye) |
| **Pupil Dilation** | Pupil size, adjustable in XY directions |
| **Limbal Ring Amount** | Intensity of the limbus ring |
| **Parallax Layer** | Parallax depth effect |
| **Iris Color** | Iris base color |
| **Eye Iris Size** | Iris scaling size |

View File

@@ -0,0 +1,30 @@
---
title: Hair
---
The hair shader is based on the Kajiya-Kay rendering model, approximately simulating dual-layer anisotropic highlights on hair strands, commonly known as "angel rings" in hair rendering.
<img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*k7t9RbgNMOIAAAAAAAAAAAAADgDwAQ/original" />
## Importing Examples
Galacean provides hair examples to help you get started. [Click here](https://galacean.antgroup.com/editor/projects) to find this example.
1. Navigate to the editor homepage in Galacean.
2. Select the **Templates** panel, browse the template interface, preview, and download the hair example to your **Project**.
## Dual-Layer Highlights
<img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*IZrjTY7JbfkAAAAAAAAAAAAADgDwAQ/original" />
## Material Properties
| Parameter | Description |
| :-----------------------: | :-------------------------------------------------------------: |
| **HairFirstWidth** | Adjust the width of the first-layer "angel ring" highlight on hair |
| **HairSecondWidth** | Adjust the width of the second-layer "angel ring" highlight on hair |
| **HairFirstStrength** | Strength of the first-layer highlight. Increase this value for stronger highlights |
| **HairSecondStrength** | Strength of the second-layer highlight. Increase this value for stronger highlights |
| **HairFirstOffset** | Adjust the position of the first-layer highlight by modifying this value |
| **HairSecondOffset** | Adjust the position of the second-layer highlight by modifying this value |
| **HairFirstColor** | Color of the first-layer highlight |
| **HairSecondColor** | Color of the second-layer highlight |

View File

@@ -0,0 +1,31 @@
---
title: Skin
---
The skin shader uses the **Spherical Gaussian model**, allowing flexible customization of different **Diffusion Profiles** to simulate human skin or standard subsurface scattering effects.
<img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*ynWiSp_2n90AAAAAAAAAAAAADgDwAQ/original" />
## Importing Examples
Galacean provides skin material examples to help you get started. [Click here](https://galacean.antgroup.com/editor/projects) to find this example.
1. Navigate to the editor homepage in Galacean.
2. Select the **Templates** panel, browse the template interface, preview, and download the skin example to your **Project**.
## Material Properties
| Parameter | Description |
| :--------------------: | :---------------------------------: |
| **SSS Color** | Adjust the skin scattering color |
| **Curvature Texture** | Curvature map controlling scattering areas |
| **Curvature Power** | Curvature intensity (best range between `0-1`) |
## Detail Comparison
The following demonstration compares PBR vs. skin material rendering effects:
<Comparison
leftSrc="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*NLyOR71_nj4AAAAAAAAAAAAADgDwAQ/original"
leftText="PBR"
rightSrc="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*xfl_Ra0oj0AAAAAAAAAAAAAADgDwAQ/original"
rightText="SSS"
/>

View File

@@ -0,0 +1,175 @@
---
title: PBR
---
**PBR** stands for **Physically Based Rendering**, or **Physically Based Rendering** in Chinese. Originally proposed by Disney in 2012, it has since been widely adopted in the gaming industry. Compared to traditional rendering methods like **Blinn-Phong**, PBR adheres to energy conservation and physical rules. Artists only need to adjust a few simple parameters to ensure accurate rendering results even in complex scenes. PBR follows energy conservation principles, is physically based, and incorporates [IBL](/en/docs/graphics-light-ambient) to simulate global illumination. It allows for easier adjustment of rendering effects through parameters like metallic and roughness.
## PBR Basic Parameters
| Parameter | Description |
| :-- | :-- |
| [metallic](/apis/core/#PBRMaterial-metallic) | **Metallic**. Simulates the metallic properties of a material. Higher values result in stronger specular reflections, reflecting more surrounding environment. |
| [roughness](/apis/core/#PBRMaterial-roughness) | **Roughness**. Simulates the roughness of a material. Higher roughness creates a less flat microsurface and blurrier specular reflections. |
| [roughnessMetallicTexture](/apis/core/#PBRMaterial-roughnessMetallicTexture) | **Roughness Metallic Texture**. Used with metallic and roughness, operates in a multiplicative relationship. |
| [baseColor](/apis/core/#PBRBaseMaterial-baseColor) | **Base Color**. **Base Color * Base Color Texture = Final Base Color**. The base color represents the albedo value of an object. Unlike traditional diffuse color, it contributes to both specular and diffuse components. We can control the contribution ratio using metallic and roughness. |
| [emissiveColor](/apis/core/#PBRBaseMaterial-emissiveColor) | **Emissive Color**. Renders color even without lighting. |
| [baseTexture](/apis/core/#PBRBaseMaterial-baseTexture) | **Base Color Texture**. Used with base color, operates in a multiplicative relationship. |
| [normalTexture](/apis/core/#PBRBaseMaterial-normalTexture) | **Normal Texture**. Creates surface detail with a bump map and controls depth via normal intensity. |
| [emissiveTexture](/apis/core/#PBRBaseMaterial-emissiveTexture) | **Emissive Texture**. Combine with emissive color ([emissiveFactor](/apis/core/#PBRBaseMaterial-emissiveTexture)) to achieve emissive effects, rendering color even without lighting. |
| [occlusionTexture](/apis/core/#PBRBaseMaterial-occlusionTexture) | **Occlusion Texture**. Enhances shadow details of objects. |
| [tilingOffset](/apis/core/#PBRBaseMaterial-tilingOffset) | **Tiling Offset**. A Vector4 value controlling UV scale and offset (see [example](/examples/tiling-offset)). |
| [clearCoat](/apis/core/#PBRBaseMaterial-clearCoat) | **Clear Coat Strength**. Default is 0 (disabled). See [example](/examples/pbr-clearcoat). |
| [clearCoatTexture](/apis/core/#PBRBaseMaterial-clearCoatTexture) | **Clear Coat Strength Texture**. Multiplied with clearCoat. |
| [clearCoatRoughness](/apis/core/#PBRBaseMaterial-clearCoatRoughness) | **Clear Coat Roughness**. |
| [clearCoatRoughnessTexture](/apis/core/#PBRBaseMaterial-clearCoatRoughnessTexture) | **Clear Coat Roughness Texture**. Multiplied with clearCoatRoughness. |
| [clearCoatNormalTexture](/apis/core/#PBRBaseMaterial-clearCoatNormalTexture) | **Clear Coat Normal Texture**. Shares the original materials normal if not set. |
By adjusting the metallic parameter, youll notice that higher metallic values make the surrounding environment clearer and transition from a white pure color to a colorful one. This occurs because dielectric materials (metallic = 1) reflect 100% of light at the surface, resulting in colorful environmental reflections:
<img src="https://gw.alipayobjects.com/zos/OasisHub/711f8b97-247c-465e-8cf2-4896b0c78534/metal.gif" />
<Callout type="warning">
In addition to the above general parameters, PBR provides two workflows: **Metal-Roughness** and **Specular-Glossiness**, corresponding to [PBRMaterial](/apis/core/#PBRMaterial) and [PBRSpecularMaterial](/apis/core/#PBRSpecularMaterial).
</Callout>
## PBRMaterial
#### Anisotropy
<Callout type="info">
Refers to the directional variation of light reflection on a surface, often manifesting as distinct gloss or reflection effects. This phenomenon is common in real-world materials, especially metals, fabrics, and hair.
</Callout>
| Parameter | Description |
| :-- | :-- |
| [anisotropy](/apis/core/#PBRMaterial-anisotropy) | **Anisotropy Strength**. Default is 0 (disabled). See [example](/examples/pbr-anisotropy). |
| [anisotropyRotation](/apis/core/#PBRMaterial-anisotropyRotation) | **Anisotropy Rotation Angle**. Rotates along tangent and bitangent space. |
| [anisotropyTexture](/apis/core/#PBRMaterial-anisotropyTexture) | **Anisotropy Texture**. RG channels store anisotropy direction (multiplied with rotation); B channel stores strength (multiplied with anisotropy). |
Enabling Anisotropy
- Navigate to **Inspector**, enable [anisotropy](/apis/core/#PBRMaterial-anisotropy), and adjust parameters for desired effects:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*j0jGRZL3iBsAAAAAAAAAAAAADgDwAQ/original"
/>
#### Sheen
<Callout type="info">
Used to simulate subtle glossy effects on fabric surfaces. This gloss is visible at specific viewing angles, resembling light scattering on silk, velvet, or other fine fibers.
</Callout>
| Parameter | Description |
| :-- | :-- |
| [sheenColor](/apis/core/#PBRMaterial-sheenColor) | **Base Sheen Color**. Determines the color observed when light interacts with the surface. |
| [sheenColorTexture](/apis/core/#PBRMaterial-sheenColorTexture) | **Sheen Color Texture**. Provides complex color variations across the surface. |
| [sheenRoughness](/apis/core/#PBRMaterial-sheenRoughness) | **Sheen Roughness**. Lower values = smoother surfaces with concentrated gloss; higher values = rougher surfaces with softer, diffused gloss. |
| [sheenRoughnessTexture](/apis/core/#PBRMaterial-sheenRoughnessTexture) | **Sheen Roughness Texture**. Defines varying roughness across the surface. |
<Image
figcaption="Gloss variation on fabric at different angles"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*mQ5UT7TnFrEAAAAAAAAAAAAADgDwAQ/original"
/>
Enabling Sheen
- Select the material and adjust parameters:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*ID62RJf8sFYAAAAAAAAAAAAADgDwAQ/original"
/>
#### Thin Film Iridescence
<Callout type="info">
Occurs when surface colors change with viewing and lighting angles. Common in soap bubbles, insect wings, and pearls.
</Callout>
| Parameter | Description |
| :-- | :-- |
| [iridescence](/apis/core/#PBRMaterial-iridescence) | **Thin Film Interference Strength** (01). |
| [iridescenceTexture](/apis/core/#PBRMaterial-iridescenceTexture) | **Iridescence Strength Texture**. |
| [iridescenceIOR](/apis/core/#PBRMaterial-iridescenceIOR) | **Iridescence Refractive Index**. Controls light bending and resulting colors. |
| [iridescenceThicknessRange](/apis/core/#PBRMaterial-iridescenceThicknessRange) | **Iridescence Thickness Range**. Determines color variation. |
| [iridescenceThicknessTexture](/apis/core/#PBRMaterial-iridescenceThicknessTexture) | **Iridescence Thickness Texture**. Affects color and thickness. |
<Image
figcaption="Thin film interference effect"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*GEksSY3q1qUAAAAAAAAAAAAADgDwAQ/original"
/>
Enabling Iridescence
- Select the material, ensure [iridescence](/apis/core/#PBRMaterial-iridescence) > 0, and adjust [metallic](/apis/core/#PBRMaterial-metallic), [roughness](/apis/core/#PBRMaterial-roughness), [iridescenceIOR](/apis/core/#PBRMaterial-iridescenceIOR), etc.:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*GJU9Ra9ZWUIAAAAAAAAAAAAADgDwAQ/original"
/>
#### Transmission
<Callout type="info">
Describes light passing through a material rather than being reflected or absorbed. When light hits a transparent/semi-transparent object, some light transmits through it.
</Callout>
<Image
figcaption="Transmission from 0 to 1"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*P7XpSoWpRdQAAAAAAAAAAAAADgDwAQ/original"
/>
| Parameter | Description |
| :-- | :-- |
| [transmission](/apis/core/#PBRMaterial-transmission) | **Transmission Strength** (01). 0 = no transmission; 1 = fully transparent. |
| [transmissionTexture](/apis/core/#PBRMaterial-transmissionTexture) | **Transmission Texture**. Samples R channel, multiplied with transmission. |
Enabling Transmission
- Enable **Opaque Texture** in Camera and Scene:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*_tBbRYNaBPMAAAAAAAAAAAAADgDwAQ/original"
/>
- Adjust transmission parameters:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*tTT_TbnawQQAAAAAAAAAAAAADgDwAQ/original"
/>
<Callout type="warning">
According to physics, refraction relies on transmission. Refraction only occurs when transmission > 0.
</Callout>
#### Refraction
| Parameter | Description |
| :-- | :-- |
| [attenuationColor](/apis/core/#PBRMaterial-attenuationColor) | **Absorption Color**. Simulates optical absorption in colored glass, liquids, or gems. |
| [attenuationDistance](/apis/core/#PBRMaterial-attenuationDistance) | **Attenuation Distance**. Shorter distances = denser, more vivid colors; longer distances = softer color transitions. |
| [thickness](/apis/core/#PBRMaterial-thickness) | **Refraction Thickness**. Controls light bending. Larger values = more pronounced refraction. |
| [thicknessTexture](/apis/core/#PBRMaterial-thicknessTexture) | **Thickness Texture**. Samples G channel; white = thicker, black = thinner. Multiplied with thickness. |
<Image
figcaption="Color changes with increasing attenuationDistance"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*TSZlQ7HOaS4AAAAAAAAAAAAADgDwAQ/original"
/>
Enabling Refraction
- Ensure [transmission](/apis/core/#PBRMaterial-transmission) is enabled, set [thickness](/apis/core/#PBRMaterial-thickness) > 0, and adjust attenuation color/distance:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*yKNsQpiPQxoAAAAAAAAAAAAADgDwAQ/original"
/>
> For refraction calculations, we assume:
> - Use a simplified geometry shape to approximate surface properties.
> - Use [refractionMode](/apis/core/#PBRMaterial-refractionMode) to define the refraction mode.
| refractionMode | Description |
| :-- | :-- |
| [Sphere](/apis/core/#PBRMaterial-Sphere) | Uses spheres to approximate curved surface refraction. |
| [Planar](/apis/core/#PBRMaterial-Planar) | Uses planes for flat surface refraction. |
## PBRSpecularMaterial
| Parameter | Description |
| :-- | :-- |
| [specularColor](/apis/core/#PBRMaterial-specularColor) | **Specular Color**. Unlike metal-roughness workflows, this directly defines specular color (only active when metal-roughness workflow is disabled). |
| [glossiness](/apis/core/#PBRMaterial-glossiness) | **Glossiness**. Opposite of roughness (only active when metal-roughness workflow is disabled). |
| [specularGlossinessTexture](/apis/core/#PBRMaterial-specularGlossinessTexture) | **Specular Glossiness Texture**. Multiplied with specular and glossiness. |
> **Note**: PBR must enable [ambient lighting](/en/docs/graphics-light-ambient).
For script-based material usage, refer to the [material usage tutorial](/en/docs/graphics-material-script).

View File

@@ -0,0 +1,59 @@
---
title: Unlit
---
In simple scenarios where lighting calculations are unnecessary, the engine provides [UnlitMaterial](/apis/core/#UnlitMaterial), which uses minimal shader code. It only requires a color or texture to render. Unlit materials are ideal for rendering pre-baked models, as they need only a base texture or color to display high-quality offline rendering results. The downside is that they cannot display real-time light interaction effects, as Unlit rendering is entirely determined by textures and is unaffected by lighting.
## Editor Usage
<img src="https://gw.alipayobjects.com/zos/OasisHub/6be78a08-3075-4cd1-8cad-9757fc34f695/unlit.gif" alt="unlit" />
## Parameter Overview
| Parameter | Description |
| :-- | :-- |
| [baseColor](/apis/core/#UnlitMaterial-baseColor) | **Base Color**. **Base Color * Base Texture = Final Color**. |
| [baseTexture](/apis/core/#UnlitMaterial-baseTexture) | **Base Texture**. Multiplied with base color. |
| [tilingOffset](/apis/core/#UnlitMaterial-tilingOffset) | **Tiling Offset**. A Vector4 value controlling UV scaling and offset (see [example](/embed/tiling-offset)). |
For script-based material usage, refer to the [material usage tutorial](/en/docs/graphics/material/script).
## Exporting Unlit Material from Blender
As described in the [baking tutorial](/en/docs/art/bake-blender), if you've already prepared baked textures and want a **convenient material** whose color is solely determined by the baked texture—without needing to add lights, adjust normals, or tweak advanced properties like metallic/roughness—you can use Galacean's [UnlitMaterial](/apis/core/#UnlitMaterial). glTF includes a dedicated [KHR_materials_unlit](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) extension, which Galacean parses to generate Unlit materials.
<img src="https://gw.alipayobjects.com/zos/OasisHub/39965fc2-3fc2-44b9-a294-a04eb4441120/1623652741734-090284d5-9b1a-4db8-9231-dc3f4d188a38-20210614150743080.png" alt="image.png" style={{zoom:"50%"}} />
Test model: [TREX.zip](https://www.yuque.com/attachments/yuque/0/2021/zip/381718/1623651429048-7f6a3610-d5cb-4a73-97f5-0d37d0c63b2c.zip?_lake_card=%7B%22src%22%3A%22https%3A%2F%2Fwww.yuque.com%2Fattachments%2Fyuque%2F0%2F2021%2Fzip%2F381718%2F1623651429048-7f6a3610-d5cb-4a73-97f5-0d37d0c63b2c.zip%22%2C%22name%22%3A%22TREX.zip%22%2C%22size%22%3A499161%2C%22type%22%3A%22application%2Fx-zip-compressed%22%2C%22ext%22%3A%22zip%22%2C%22status%22%3A%22done%22%2C%22taskId%22%3A%22u458bcbec-d647-4328-8036-3d5eb12860f%22%2C%22taskType%22%3A%22upload%22%2C%22id%22%3A%22ua8a5baad%22%2C%22card%22%3A%22file%22%7D)
### Steps to Export glTF with Unlit Extension in Blender
1. **Import Model**
<img src="https://gw.alipayobjects.com/zos/OasisHub/e5dbfb61-5c0c-4ca5-8c7f-bde353d4c211/1623651809057-138f49cf-6fe7-4f54-8161-c7e157ec85fd-20210614150752343.png" />
2. **Modify Shader**
The default shader type is **BSDF**. Change the surface shader type in the material properties to **Background**.
<img src="https://gw.alipayobjects.com/zos/OasisHub/abf1e279-1f78-4d21-8c1f-d58d7f74992c/1623652169374-7f39e5f0-6639-4795-8565-b8f0b09420ed-20210614150804567.png" />
<img src="https://gw.alipayobjects.com/zos/OasisHub/c8c51e5f-c7c6-44a3-87e2-dc649e13fddb/1623652230768-69cd6f7e-175d-4f9f-9042-b3629d422b8e.png" />
3. **Add Baked Texture**
Connect the baked texture's **Color** output to the **Shader** input.
<img src="https://gw.alipayobjects.com/zos/OasisHub/50c69e7b-c099-4a2d-b546-8a55ff4f9309/1623652264008-7ae4c13c-6430-44b0-995e-2c23c9f117a7-20210614150846797.png" />
<img src="https://gw.alipayobjects.com/zos/OasisHub/6ed13e19-a9e5-4454-a0d5-ad27b3cabe14/1623652368637-6dda44be-4cde-4f65-a72f-d39b5d3f60ce.png" />
<img src="https://gw.alipayobjects.com/zos/OasisHub/e9a99c9c-f661-4666-86bc-d8e91030c0f7/1623652380351-501dd929-7f96-4578-b49a-11724a0782a7.png" />
4. **Export glTF**
If the preview looks correct, export the glTF file.
<img src="https://gw.alipayobjects.com/zos/OasisHub/4b6b5f8f-ebd2-46af-85c7-9a26b5f66a2e/1623652403568-450291a8-1a0b-4cf4-8e71-c183a05632b0-20210614150902221.png" />
<img src="https://gw.alipayobjects.com/zos/OasisHub/1fe38185-399e-4f56-bff4-c39ba4ae3a2a/1623652462007-85b065a3-69fa-4d80-9dfd-834ef66da12a.png" />
Drag the exported glTF file into the editor or [glTF Viewer](https://galacean.antgroup.com/engine/gltf-viewer). If the material type is **UnlitMaterial**, it means the [KHR_materials_unlit](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) extension has been correctly applied, and Galacean has parsed it into an Unlit material.
<img src="https://gw.alipayobjects.com/zos/OasisHub/fbb6ba43-f7d7-4757-a1d3-590083d30573/1623652636074-d8bb8437-f885-43fd-8957-8e14ae9fd8c0-20210614150914493.png" />

View File

@@ -1,48 +0,0 @@
---
title: Material Composition
---
The Galacean material consists of **[shaders](/en/docs/graphics-shader), render states, and [shader data](/en/docs/graphics-shader-shaderData)**. Shaders can write vertex and fragment code to determine the color of pixels output to the screen by the rendering pipeline; render states can provide additional configurations to the context of the rendering pipeline; shader data encapsulates some data sets passed from the CPU to the GPU, such as colors, matrices, textures, etc.
## Render States
Galacean encapsulates the configuration of the rendering pipeline in the [RenderState object](/apis/core/#RenderState), which can configure [blend states](/apis/core/#RenderState-BlendState), [depth states](/apis/core/#RenderState-DepthState), [stencil states](/apis/core/#RenderState-StencilState), and [raster states](/apis/core/#RenderState-RasterState) separately. Taking the standard rendering process of a transparent object as an example, we want to enable blending mode, set the blend factor, and because transparent objects are rendered in layers, we also need to disable depth writing;
```typescript
const renderState = material.renderState;
// 1. 设置颜色混合因子。
const blendState = renderState.blendState;
const target = blendState.targetBlendState;
// src 混合因子为AsAsAsAs
target.sourceColorBlendFactor = target.sourceAlphaBlendFactor = BlendFactor.SourceAlpha;
// dst 混合因子为1 - As1 - As1 - As1 - As
target.destinationColorBlendFactor = target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
// 操作方式为 src + dst */
target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
// 2. 开启颜色混合
target.enabled = true;
// 3. 关闭深度写入。
const depthState = renderState.depthState;
depthState.writeEnabled = false;
// 4. 设置透明渲染队列
renderState.renderQueueType = RenderQueueType.Transparent;
```
> For more options regarding render states, you can refer to the corresponding [API documentation](/apis/core/#RenderState).
The render queue can determine the rendering order of this material in the current scene. The engine will handle different ranges of render queues differently, such as [RenderQueueType.Transparent](/apis/core/#RenderQueueType-transparent) rendering from far to near, while [RenderQueueType.Opaque](/apis/core/#RenderQueueType-Opaque) rendering from near to far.
```typescript
material.renderQueueType = RenderQueueType.Opaque;
```
For the same render queue, we can also set the `priority` property of the [Renderer](/apis/core/#Renderer) to forcibly determine the rendering order, defaulting to 0, where a higher number means rendering later, for example:
```typescript
renderer.priority = -1; // Render with priority
```

View File

@@ -1,24 +0,0 @@
---
title: Using the Editor
---
## Using the Editor
### 1. Manually Create Material
<Image src="https://gw.alipayobjects.com/zos/OasisHub/b01b0ee2-317e-4acb-8c2f-e07736179d67/image-20240206163405147.png" alt="image-20240206163405147" style={{ zoom: "50%" }} />
### 2. Import Model
Refer to the [Import and Use Model](/en/docs/graphics/model/use/) tutorial. We can first import the model into the editor. Generally, the model is already automatically bound to the material, and the user does not need to do anything; if you want to modify the material, we need to click the `duplicate & remap` button to generate a copy of the material and then edit the material copy.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/1f5caa3a-bc01-419f-83c0-dd0ef12692bf/remap.gif" alt="remap" style={{ zoom: "100%" }} />
Switching shaders will not reset shader data. For example, if the base color is red, the base color will remain red even if the shader is switched.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/b3724c3e-e8d9-43af-91c8-c6a80cd027f9/image-20231009112713870.png" alt="image-20231009112713870" style={{ zoom: "50%" }} />
### 3. Adjust Material
For specific operations, see the [Shader Tutorial](/en/docs/graphics/shader/intro/).

View File

@@ -0,0 +1,6 @@
{
"create": { "title": "Creating Materials" },
"builtin": { "title": "Using Built-in Shaders" },
"custom": { "title": "Custom Shaders" },
"shaderData": { "title": "Using Shader Data" }
}

View File

@@ -0,0 +1,30 @@
---
title: Using Built-in Shaders
---
The Galacean engine provides several commonly used built-in shaders, including:
| Type | Description |
| :-- | :-- |
| [Unlit](/en/docs/graphics/material/builtinShaders/unlit) | The **Unlit Shader** is suitable for rendering pre-baked models. It only requires a base texture or color to display high-quality offline rendering results. However, it cannot simulate real-time light interaction because its rendering is entirely determined by textures and is unaffected by lighting. See the [baking tutorial](/en/docs/art/bake-blender) and [Unlit export tutorial](/en/docs/graphics/shader/builtins/unlit) for details. |
| [Blinn Phong](/en/docs/graphics/material/builtinShaders/blinnPhong/) | The **Blinn Phong Shader** is ideal for scenarios where photorealism is not critical. Though not physically based, its efficient rendering algorithm and comprehensive optical properties make it applicable in many cases. |
| [PBR](/en/docs/graphics/material/builtinShaders/pbr) | The **PBR Shader** is designed for applications requiring realistic rendering. Since PBR follows energy conservation and is physically based, developers can ensure physically accurate results by adjusting parameters like metallic, roughness, and lighting. |
| [Hair](/en/docs/graphics/material/builtinShaders/digitalHuman/hair) | The hair shader is based on the Kajiya-Kay model, approximating dual-layer anisotropic highlights on hair strands, commonly referred to as "angel rings" in hair rendering. |
| [Skin](/en/docs/graphics/material/builtinShaders/digitalHuman/skin) | Skin rendering uses the Spherical Gaussian model, allowing flexible customization of different diffusion profiles to simulate human skin or standard subsurface scattering effects. |
| [Eyes](/en/docs/graphics/material/builtinShaders/digitalHuman/eye) | The eye shader provides realistic rendering for eyeball models, enabling lifelike artistic results in your creations. |
You can directly debug the corresponding properties of built-in shaders in the editor to observe real-time rendering changes.
<img src="https://gw.alipayobjects.com/zos/OasisHub/cd87c11a-7a68-4cde-a19a-40cff943e878/2025-02-10%25252017.05.33.gif" />
Most built-in shaders share these common parameters:
| Parameter | Description |
| :-- | :-- |
| [isTransparent](/apis/core/#BaseMaterial-isTransparent) | **Transparency**. Enables/disables transparency. When enabled, use [BlendMode](/apis/core/#BaseMaterial-blendMode) to set the color blending mode. |
| [alphaCutoff](/apis/core/#BaseMaterial-alphaCutoff) | **Alpha Cutoff Value**. Sets a threshold; fragments with alpha values below this will be discarded in the shader. See [example](/embed/blend-mode). |
| [renderFace](/apis/core/#BaseMaterial-renderFace) | **Render Face**. Controls whether to render front-facing, back-facing, or both sides. |
| [blendMode](/apis/core/#BaseMaterial-blendMode) | **Color Blending Mode**. Specifies how colors blend when the material is transparent. See [example](/embed/blend-mode). |
| [tilingOffset](/apis/core/#BaseMaterial-tilingOffset) | **Tiling Offset**. A Vector4 value controlling UV scaling and offset. See [example](/embed/tiling-offset). |
Each shader offers unique rendering effects and use cases. For more details, refer to the [Built-in Shaders tutorial](/en/docs/graphics/material/builtinShaders/pbr/).

View File

@@ -0,0 +1,54 @@
---
title: Creating Materials
---
There are generally three ways to create materials:
## 1. Manual Creation
<img src="https://gw.alipayobjects.com/zos/OasisHub/b01b0ee2-317e-4acb-8c2f-e07736179d67/image-20240206163405147.png" />
## 2. Materials from Models
Refer to the [Model Import and Usage](/en/docs/graphics/model/use/) tutorial. First, import the model into the editor. In most cases, the model will automatically bind its material, requiring no user action.
### 2.1. Remap Material
To modify the model's material, click the **`duplicate and remap`** button to generate a copy of the material. Note that **Remap** will modify the model's preset, affecting all model instances (as shown below):
<img src="https://gw.alipayobjects.com/zos/OasisHub/4a41f66e-5523-43f0-a9b5-4028b9d14cbc/2025-01-24%25252015.30.31.gif" />
### 2.2. Incremental Modification
To modify only a specific model's material, use the incremental modification feature:
<img src="https://gw.alipayobjects.com/zos/OasisHub/5d2409f2-a7b2-4b5e-9e6a-9845c3358af3/2025-01-24%25252015.32.04.gif" />
## 3. Bind Material
Directly drag the material into the scene to bind it.
<img src="https://gw.alipayobjects.com/zos/OasisHub/62d6a8cb-fd70-4c37-beab-9dacc8ae4d5b/2025-05-23%25252017.13.59.gif" />
## 4. Script-Based Method
You can also create or modify materials via scripts. Below is a demo that replaces a material by attaching a script to a cube entity:
```ts showLineNumbers
export default class extends Script {
onStart() {
// Get all renderers
const renderers = [];
this.entity.getComponentsIncludeChildren(MeshRenderer, renderers);
const renderer = renderers[0];
// Modify material directly
const material = renderer.getMaterial();
material.baseColor.set(1, 0, 0, 1);
// Or replace the material
const pbrMaterial = new PBRMaterial(engine);
const material = renderer.setMaterial(material);
}
}
```

View File

@@ -0,0 +1,306 @@
---
title: Custom Shaders
---
Similar to functions, classes, and properties in TypeScript, shader code also has its own set of APIs and配套的 [UIScript](/en/docs/graphics/material/shaderLab/script). This article will guide you through customizing your shaders using these APIs and [ShaderLab](/en/docs/graphics/material/shaderLab/overview).
## Quick Start
We'll start with the `Unlit template` to introduce our shader API. Follow the steps below to create a Unlit shader:
<img
src="https://gw.alipayobjects.com/zos/OasisHub/9abd1026-4e4d-4994-b36a-f964375c38cb/image-20240731105324320.png"
style={{ zoom: "50%" }}
/>
The engine will automatically generate the shader file and [UIScript](/en/docs/graphics/material/shaderLab/script) file for you:
<img
src="https://gw.alipayobjects.com/zos/OasisHub/6351fa81-5159-4469-bd95-8f21a8f2f4ac/image-20250124162909194.png"
style={{ zoom: "50%" }}
/>
By default, the Unlit template includes skinning calculations and a Shadow Pass. As shown below, skeletal animations and shadows render correctly:
<Image src="https://gw.alipayobjects.com/zos/OasisHub/6e7f7d40-e54c-45bc-a915-dfbfb26c2c74/2024-08-01%25252017.01.06.gif" />
Key code includes using `UsePass "pbr/Default/ShadowCaster"` to enable shadow mapping and `getSkinMatrix` to animate the mesh:
```ts showLineNumbers {1,11-15} /getSkinMatrix/
UsePass "pbr/Default/ShadowCaster"
Pass "Example" {
#include "Skin.glsl"
Varyings vert(Attributes attr) {
Varyings v;
vec4 position = vec4(attr.POSITION, 1.0);
// Skin
#ifdef RENDERER_HAS_SKIN
mat4 skinMatrix = getSkinMatrix(attr);
position = skinMatrix * position;
#endif
gl_Position = renderer_MVPMat * position;
v.uv = attr.TEXCOORD_0;
return v;
}
}
```
Unlit shaders are unaffected by lighting by default. To make the output respond to lighting, use APIs from `Light.glsl`:
```ts showLineNumbers {1,4} /getDirectLight/
#include "Light.glsl"
// Demo: Calculate only the first directional light
DirectLight light = getDirectLight(0);
float dotNL = saturate(dot(v.normalWS, -light.direction));
baseColor.rgb *= dotNL * light.color;
```
<Image src="https://gw.alipayobjects.com/zos/OasisHub/a552c86f-6a59-4765-89ff-fac3b38aa9d2/2024-08-01%25252017.06.14.gif" />
While vertex color calculations, normal maps, and [ambient lighting](/en/docs/graphics/light/ambient) can also be implemented, we recommend using the `PBR template` instead of the `Unlit template`. The PBR template already includes these features and provides a more comprehensive lighting model (e.g., anisotropy, Clear Coat) with macro-based extensions.
## PBR Template
Create a `PBR Shader template` and bind it to your material. The material panel will now include settings for base properties, metallic/roughness, anisotropy, normals, emissive, occlusion, and Clear Coat, all responsive to direct and ambient lighting:
<img
src="https://gw.alipayobjects.com/zos/OasisHub/1bb43cac-ca21-4342-a6ea-a19324eaf12d/image-20240801174338560.png"
style={{ zoom: "50%" }}
/>
<Image src="https://gw.alipayobjects.com/zos/OasisHub/f8f09e89-e14d-481e-a328-eed491f41e79/image-20240801174216595.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/65a7f2ec-ffd5-45cf-9508-8d951b995e3d/2024-08-01%25252017.40.02.gif" />
### Overriding the Lighting Model
1. Create a `DemoPass.glsl` file and include it in your main shader:
```ts showLineNumbers {7-8}
// PBRShader.gs
SubShader "Default" {
Pass "Forward Pass" {
VertexShader = PBRVertex;
FragmentShader = PBRFragment;
// #include "ForwardPassPBR.glsl"
#include "./DemoPass.glsl"
}
}
```
2. Modify the lighting model in `DemoPass.glsl` (demo shows direct light changes):
```ts showLineNumbers {7-8}
// DemoPass.glsl
#include "Common.glsl"
#include "Fog.glsl"
#include "AttributesPBR.glsl"
#include "VaryingsPBR.glsl"
// #include "LightDirectPBR.glsl"
#include "DemoLight.glsl"
#include "LightIndirectPBR.glsl"
#include "VertexPBR.glsl"
#include "FragmentPBR.glsl"
```
3. Override the specular reflection model using `FUNCTION_SPECULAR_LOBE` (example uses thin-film interference):
```ts showLineNumbers {2,5,16} /specularLobe_iridescence/
// DemoLight.glsl
#define FUNCTION_SPECULAR_LOBE specularLobe_iridescence
#include "BRDF.glsl"
#include "./IridescenceFunction.glsl"
void specularLobe_iridescence(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 specularColor){
vec3 thin = DirectBDRFIridescence(surfaceData, incidentDirection, brdfData);
vec3 BRDF_Specular = BRDF_Specular_GGX( incidentDirection, surfaceData, surfaceData.normal, brdfData.specularColor, brdfData.roughness);
vec3 factor = mix(BRDF_Specular, thin, material_Iridescence);
specularColor += attenuationIrradiance * factor;
}
#include "LightDirectPBR.glsl"
```
<Image src="https://gw.alipayobjects.com/zos/OasisHub/ad18c98d-d1a5-47fd-b5c8-882908c249a2/2024-08-01%25252018.51.36.gif" />
## Common APIs
### Usage Example
```glsl
#include "Common.glsl"
float f2 = pow2(0.5);
```
### Common
Provides macros like `PI` and utility functions (`gammaToLinear`, `pow2`). See [source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/Common.glsl).
### Fog
Depth fog calculation:
```glsl
vec4 fog(vec4 color, vec3 positionVS);
```
### Transform
System variables for model/view/world space:
```glsl
mat4 renderer_LocalMat;
mat4 renderer_ModelMat;
mat4 camera_ViewMat;
mat4 camera_ProjMat;
mat4 renderer_MVMat;
mat4 renderer_MVPMat;
mat4 renderer_NormalMat;
vec3 camera_Position;
vec3 camera_Forward;
vec4 camera_ProjectionParams;
```
### Light
Access engine lighting data:
```glsl
DirectLight getDirectLight(int index);
PointLight getPointLight(int index);
SpotLight getSpotLight(int index);
EnvMapLight scene_EnvMapLight;
#ifdef SCENE_USE_SH
vec3 scene_EnvSH[9];
#endif
#ifdef SCENE_USE_SPECULAR_ENV
samplerCube scene_EnvSpecularSampler;
#endif
```
### Normal
Normal calculation utilities:
```glsl
vec3 getNormalByNormalTexture(mat3 tbn, sampler2D normalTexture, float normalIntensity, vec2 uv, bool isFrontFacing);
mat3 getTBNByDerivatives(vec2 uv, vec3 normal, vec3 position, bool isFrontFacing);
```
### Shadow
Shadow-related functions ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/Shadow.glsl)):
```glsl
int computeCascadeIndex(vec3 positionWS);
vec3 getShadowCoord(vec3 positionWS);
float sampleShadowMap(vec3 positionWS, vec3 shadowCoord);
```
### Skin
Skinning calculation:
```glsl
mat4 getSkinMatrix(Attributes attributes);
```
### BlendShape
Blend shape calculation:
```glsl
void calculateBlendShape(Attributes attributes, inout vec4 position, inout vec3 normal, inout vec4 tangent);
```
## PBR APIs
### AttributesPBR
All PBR attribute variables ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/AttributesPBR.glsl)).
### VaryingsPBR
All PBR varying variables ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/VaryingsPBR.glsl)).
### LightDirectPBR
Direct lighting calculations based on BRDF ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/LightDirectPBR.glsl)).
**Usage:**
```glsl
evaluateDirectRadiance(varyings, surfaceData, brdfData, shadowAttenuation, color.rgb);
```
**Override Macros:**
```glsl
#define FUNCTION_SURFACE_SHADING surfaceShading
#define FUNCTION_DIFFUSE_LOBE diffuseLobe
#define FUNCTION_SPECULAR_LOBE specularLobe
#define FUNCTION_CLEAR_COAT_LOBE clearCoatLobe
#define FUNCTION_SHEEN_LOBE sheenLobe
// Function signatures...
```
<Callout type="info">See PBR template extension example above.</Callout>
### LightIndirectPBR
Indirect lighting (IBL) calculations ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/LightIndirectPBR.glsl)).
**Usage:**
```glsl
evaluateIBL(varyings, surfaceData, brdfData, color.rgb);
```
**Override Macros:**
```glsl
#define FUNCTION_DIFFUSE_IBL evaluateDiffuseIBL
#define FUNCTION_SPECULAR_IBL evaluateSpecularIBL
#define FUNCTION_CLEAR_COAT_IBL evaluateClearCoatIBL
#define FUNCTION_SHEEN_IBL evaluateSheenIBL
// Function signatures...
```
### VertexPBR
Vertex shader utilities for UV/TBN/skinning ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/VertexPBR.glsl)):
```glsl showLineNumbers {2, 4}
Varyings varyings;
varyings.uv = getUV0(attributes);
VertexInputs vertexInputs = getVertexInputs(attributes);
// positionWS
varyings.positionWS = vertexInputs.positionWS;
// normalWS、tangentWS、bitangentWS
#ifdef RENDERER_HAS_NORMAL
varyings.normalWS = vertexInputs.normalWS;
#ifdef RENDERER_HAS_TANGENT
varyings.tangentWS = vertexInputs.tangentWS;
varyings.bitangentWS = vertexInputs.bitangentWS;
#endif
#endif
gl_Position = renderer_MVPMat * vertexInputs.positionOS;
```
### BRDF
Core PBR lighting calculations and data structures ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/BRDF.glsl)).
### BTDF
Transmission/refraction functions ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/BTDF.glsl)).
### FragmentPBR
Handles material properties and surface data initialization ([source](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/FragmentPBR.glsl)):
```glsl showLineNumbers
BRDFData brdfData;
SurfaceData surfaceData = getSurfaceData(varyings, aoUV, gl_FrontFacing);
initBRDFData(surfaceData, brdfData);
```
## Final Notes
For complete file organization examples, refer to the official [ForwardPassPBR](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/ForwardPassPBR.glsl) implementation.

View File

@@ -0,0 +1,104 @@
---
title: Using Shader Data
---
Like other programming languages, we use many variables when writing shaders. The engine provides many [built-in variables](/en/docs/graphics/material/variables), which are automatically available in shaders without manual setup. Below, we'll explore how to define and use custom data.
### Setting Data
We recommend using [ShaderLab](/en/docs/graphics/material/shaderLab/overview) to declare and manage shader data:
```glsl showLineNumbers {3,8,17,21}
Editor {
Properties {
material_BaseColor("Offset unit scale", Color) = (1,1,1,1);
...
Header("Emissive")
{
material_EmissiveColor("Emissive color", Color) = (1,1,1,1);
...
}
...
}
...
Macros {
[On] UV_OFFSET("UV Offset", Range(1,100)) = 10;
...
Header("Common") {
SOME_MACRO("label", Int) = 1;
}
}
...
// Specify the path to the UIScript editor file for this shader.
UIScript "./shaderScript.ts";
}
```
<Callout type="positive">
Refer to [ShaderLab Property Definition](/en/docs/graphics/material/shaderLab/property) for more data types.
</Callout>
You can also set shader data programmatically:
```ts showLineNumbers
// ShaderData can be stored in scene, camera, renderer, or material.
const shaderData = material.shaderData;
// Upload different types of shader data
shaderData.setFloat("u_float", 1.5);
shaderData.setInt("u_int", 1);
shaderData.setInt("u_bool", 1);
shaderData.setVector2("u_vec2", new Vector2(1, 1));
shaderData.setVector3("u_vec3", new Vector3(1, 1, 1));
shaderData.setVector4("u_vec4", new Vector4(1, 1, 1, 1));
shaderData.setMatrix("u_matrix", new Matrix());
shaderData.setIntArray("u_intArray", new Int32Array(10));
shaderData.setFloatArray("u_floatArray", new Float32Array(10));
shaderData.setTexture("u_sampler2D", texture2D);
shaderData.setTexture("u_samplerCube", textureCube);
shaderData.setTextureArray("u_samplerArray", [texture2D, textureCube]);
// Enable macro
shaderData.enableMacro("DISCARD");
// Disable macro
shaderData.disableMacro("DISCARD");
// Enable variable macro
shaderData.enableMacro("LIGHT_COUNT", "3");
// Switch variable macro (automatically disables previous "LIGHT_COUNT 3")
shaderData.enableMacro("LIGHT_COUNT", "2");
// Disable variable macro
shaderData.disableMacro("LIGHT_COUNT");
```
### Accessing Data
Once data is set, you can directly use it in your shader:
```glsl showLineNumbers filename="test.glsl"
float test = u_float;
int test = u_int;
bool test = u_bool;
vec2 test = u_vec2;
mat4 test = u_matrix;
sampler2D test = u_sampler2D;
...
```
You can also retrieve these values via code:
```ts showLineNumbers filename="test.ts"
const test = shaderData.getFloat("u_float");
const test = shaderData.getInt("u_int");
const test = shaderData.getVector2("u_vec2");
const test = shaderData.getMatrix("u_matrix");
const test = shaderData.getTexture("u_sampler2D");
```

View File

@@ -1,14 +0,0 @@
---
title: Material Overview
---
Materials refer to a collection of properties used to describe the appearance and surface characteristics of an object. Materials determine how a model interacts with light during rendering, thus affecting its visual presentation.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/a3f74864-241e-4cd8-9ad4-733c2a0b2cc2/image-20240206153815596.png" alt="image-20240206153815596" style={{ zoom: "50%" }} />
This section includes the following related information:
- [Material Composition](/en/docs/graphics/material/composition/)
- [Editor Usage](/en/docs/graphics/material/editor/)
- [Script Usage](/en/docs/graphics/material/script/)

View File

@@ -0,0 +1,51 @@
---
title: Material Overview
---
<Image src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*Iq8iRKWPAqgAAAAAAAAAAAAADgDwAQ/original" />
A material contains **Shader, ShaderData, and RenderStates**.
## Shader
A Shader is a program that runs on the GPU, typically consisting of a vertex shader and a fragment shader. You can conveniently write this code using [ShaderLab syntax](/en/docs/graphics/material/shaderLab/overview/).
## Shader Data
Like other programming languages, we use many variables when writing shaders. Refer to the [built-in variables documentation](/en/docs/graphics/material/variables/) to find the desired built-in variables. You can also manually upload shader data and macro switches via the [ShaderData tutorial](/en/docs/graphics/material/examples/shaderData):
## Render States
Galacean supports configuring [BlendState](/apis/core/#RenderState-BlendState), [DepthState](/apis/core/#RenderState-DepthState), [StencilState](/apis/core/#RenderState-StencilState), and [RasterState](/apis/core/#RenderState-RasterState).
Let's take a standard rendering process for a transparent object as an example. We enable transparent blending and disable depth writing since transparent objects are rendered additively. We also set it to the transparent render queue:
```ts
material.renderQueueType = RenderQueueType.Transparent;
material.renderState.depthState.writeEnabled = false;
material.renderState.blendState.enabled = true;
```
We recommend using ShaderLab for configuration:
```ts showLineNumbers {3,7-12,14}
Pass "Pass0" {
DepthState {
WriteEnabled = false;
}
BlendState {
Enabled = true;
SourceColorBlendFactor = BlendFactor.SourceAlpha;
DestinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
SourceAlphaBlendFactor = BlendFactor.One;
DestinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
}
RenderQueueType = Transparent;
}
```
<Callout type="info">
Render states can also be set as variables and controlled via ShaderData. For details, see [ShaderLab Render State Configuration](/en/docs/graphics/material/shaderLab/renderState).
</Callout>

View File

@@ -1,79 +0,0 @@
---
title: Script Usage
---
The material exported by the editor is only the base class [Material](/apis/core/#Material), while through code you can create the engine's pre-packaged [PBRMaterial](/apis/core/#PBRMaterial), [UnlitMaterial](/apis/core/#UnlitMaterial), and [BlinnPhongMaterial](/apis/core/#BlinnPhongMaterial).
## Getting Material
### 1. Get from an existing renderer
```typescript
// 获取想要修改的 renderer
const renderer = entity.getComponent(MeshRenderer);
// 或者获取所有 renderer
const renderers = [];
entity.getComponentsIncludeChildren(MeshRenderer, renderers);
// 通过 `getMaterial` 获取当前 renderer 的第 i 个材质, 默认第 0 个。
const material = renderer.getMaterial();
```
### 2. Replace the material in the renderer
We can also directly replace the material type, for example, reassigning a PBR material to the model:
```typescript
// 获取想要修改的 renderer
const renderer = entity.getComponent(MeshRenderer);
// 创建材质
const material = new PBRMaterial(engine);
// 通过 `setMaterial` 设置当前 renderer 的第 i 个材质, 默认第 0 个。
const material = renderer.setMaterial(material);
```
### 3. Create built-in materials
```typescript
const pbrMaterial = new PBRMaterial(engine);
const bpMaterial = new BlinnPhongMaterial(engine);
const unlitMaterial = new UnlitMaterial(engine);
```
### 4. Create custom materials
```typescript
// Refer to the shader tutorial for the specific steps of Shader.create
const customMaterial = new Material(engine, Shader.find("***"));
```
## Modifying Material
### 1. Modify built-in materials
```typescript
// 设置透明,引擎已经封装好对应渲染状态的设置
pbrMaterial.isTransparent = true;
// 设置透明度
pbrMaterial.baseColor.a = 0.5;
// 金属、粗糙度等其他配置
pbrMaterial.metallic = 1;
pbrMaterial.baseTexture = **;
```
### 2. Modify custom materials
```typescript
const shaderData = material.shaderData;
// 获取想要设置的着色器数据
const baseColor = shaderData.setFloat("material_BaseColor");
// 修改着色器数据
baseColor.a = 0.5;
shaderData.setTexture("material_BaseTexture", texture);
shaderData.enable("MATERIAL_HAS_BASETEXTURE");
// 更多的着色器操作,详见着色器文档
```

View File

@@ -0,0 +1,10 @@
{
"overview": "ShaderLab Overview",
"property": "Material Property Definition",
"script": "Using and Binding UIScript",
"global": "Global Variable Declaration",
"renderState": "Rendering State Setup",
"entry": "Vertex and Fragment Shader Programming",
"multi": "Multi-Pass Shader Writing",
"chunk": "Shader Code Segment Inclusion"
}

View File

@@ -0,0 +1,60 @@
---
title: Shader Code Segment Inclusion
---
To facilitate code reuse, ShaderLab allows including code segments using the `include` macro. These segments are automatically expanded during compilation.
```glsl showLineNumbers
#include "{includeKey}"
```
To make a code segment accessible via the `include` macro, there are two ways to declare it:
## 1. Create Shader / Shader Chunk in the Editor
The `includeKey` for created code segments corresponds to the file path in the project. For example, in the image below, if you want to include the `ShaderChunk` code segment in the `UnlitShader` shader asset, you can reference it using either absolute or relative paths:
```glsl showLineNumbers
// Relative path
#include "./ShaderChunk.glsl"
// Editor-resolved path
#include "/ShaderChunk.glsl" // Project asset root directory
```
<Image src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*3UDUS6OtbPUAAAAAAAAAAAAAeteEAQ/fmt.webp" />
## 2. Register Code Segments in Script
```ts showLineNumbers
import { ShaderFactory } from '@galacean/engine';
const commonSource = `// shader chunk`;
ShaderFactory.registerInclude('includeKey', commonSource);
```
Referencing in ShaderLab:
```glsl showLineNumbers
#include "includeKey"
```
<Callout>
In the current version, the engine provides built-in **PBR** ShaderLab code segments. Developers can use these to customize PBR shaders. Note that you must register these engine-provided ShaderLab code segments before use.
```ts showLineNumbers {4} filename="TypeScript"
import { registerIncludes } from "@galacean/engine-shader-shaderlab";
// Register built-in ShaderLab code segments
registerIncludes();
```
```glsl showLineNumbers filename="ShaderLab"
...
#include "Common.glsl"
#include "BRDF.glsl"
...
```
Official built-in PBR ShaderLab code segment source code: [Reference](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/PBR.gs)
</Callout>

View File

@@ -0,0 +1,110 @@
---
title: Vertex and Fragment Shader Programming
---
A `Pass` represents a single GPU rendering process, so each `Pass` must include both a vertex shader and a fragment shader. In ShaderLab, the `VertexShader` and `FragmentShader` keywords specify their entry functions.
```glsl showLineNumbers {4-5}
...
Pass "0" {
...
VertexShader = vert;
FragmentShader = frag;
v2f vert(a2v o) {
...
}
...
void frag(v2f i) {
...
}
...
}
```
## Attribute and Varying Variable Declarations
Like traditional GLSL shaders, ShaderLab uses **Attribute** and **Uniform** variables to receive rendering data from the CPU. **Varying variables** are used to pass data between vertex and fragment shaders. Unlike traditional GLSL, ShaderLab declares these variables using **structs** and **shader entry function signatures**.
```glsl showLineNumbers {13, 16, 21, 27-28}
struct Attributes {
vec3 POSITION;
vec4 COLOR_0;
...
}
struct Varyings {
vec2 uv;
vec3 position;
...
}
...
Varyings vert(Attributes attr) {
Varyings vary;
...
vary.position = attr.Position;
...
return vary;
}
void frag(Varyings vary) {
...
gl_FragColor = vary.COLOR_0;
}
...
VertexShader = vert;
FragmentShader = frag;
```
## MRT (Multiple Render Targets)
ShaderLab supports both **GLSL 100** and **GLSL 300** syntax, so you can use either approach to specify MRT:
### 1. Using `gl_FragData[i]`
```glsl showLineNumbers {2-3}
void main(v2f input) {
gl_FragData[0] = vec4(1.,0.,0.,1.); // render target 0
gl_FragData[1] = vec4(1.,0.,0.,1.); // render target 1
}
```
### 2. Using a Return Struct
```glsl showLineNumbers {1-4}
struct mrt {
layout(location = 0) vec4 fragColor0; // render target 0
layout(location = 1) vec4 fragColor1; // render target 1
}
mrt main(v2f input) {
mrt output;
output.fragColor0 = vec4(1.,0.,0.,1.);
output.fragColor1 = vec4(1.,0.,0.,1.);
return output;
}
```
## Macros
ShaderLab currently supports the following GLSL macro operations:
| Macro | Description |
| :-: | :- |
| `#define` | Same as GLSL |
| `#undef` | Same as GLSL |
| `#if` | Same as GLSL |
| `#ifdef` | Same as GLSL |
| `#ifndef` | Same as GLSL |
| `#else` | Same as GLSL |
| `#elif` | Same as GLSL |
| `#endif` | Same as GLSL |
| `defined` | Same as GLSL |
| `#include` | **ShaderLab-specific**: Used for code segment inclusion. See [documentation](./chunk) for details |
All macros except `#include` follow standard GLSL behavior. For detailed usage, refer to the [GLSL specification](https://registry.khronos.org/OpenGL/specs/es/3.0/GLSL_ES_Specification_3.00.pdf).
<Callout type="warning">
ShaderLab macros are expanded during the preprocessor phase and **cannot affect ShaderLab structure parsing**. This means keywords like `Shader`, `SubShader`, `Pass`, `EditorProperties`, and `EditorMacros` cannot appear inside conditional macros like `#ifdef`.
</Callout>

View File

@@ -0,0 +1,151 @@
---
title: Global Variable Declaration
---
In the [overview section](./overview/#syntax-introduction), we mentioned that the overall structure of `ShaderLab` consists of three nested modules: `Shader`, `SubShader`, and `Pass`. Each module has its own global variable scope. Within the global scope, you can declare four types of global variables: **RenderState**, **Structs**, **Functions**, and **Single Variables**.
| Variable Type | Description |
| :-- | :-- |
| **RenderState** | Corresponds to the engine's [RenderState](/apis/galacean/#RenderState) API and can be directly configured in ShaderLab. |
| **Structs** | Function similarly to GLSL structs and are also used for declaring **Varying** and **Attribute** variables. See [documentation](./entry/#attribute-and-varying-variable-declaration) for details. |
| **Functions** | Equivalent to global functions in GLSL. |
| **Single Variables** | Used to define **Uniform** variables in shaders. |
<Callout type="info">
### Global Variable Scope
Similar to other programming languages, global variables in `ShaderLab` follow scope rules and name overriding principles. Specifically:
- Global variables are only visible and valid within the module they are declared in (`Shader`, `SubShader`, or `Pass`).
- **Name Overriding Rule**: If a global variable with the same name exists in a `Pass` module as one in its parent `SubShader` module, the `Pass`-level variable will override the `SubShader`-level variable. The same logic applies between `SubShader` and its parent `Shader` module.
</Callout>
## RenderState
Includes **BlendState**, **DepthState**, **StencilState**, **RasterState**, and **renderQueueType**.
### BlendState
```glsl
BlendState state {
Enabled: bool;
ColorBlendOperation: BlendOperation.XXX;
AlphaBlendOperation: BlendOperation.XXX;
SourceColorBlendFactor: BlendFactor.XXX;
SourceAlphaBlendFactor: BlendFactor.XXX;
DestinationColorBlendFactor: BlendFactor.XXX;
DestinationAlphaBlendFactor: BlendFactor.XXX;
ColorWriteMask: float // 0xffffffff
BlendColor: vec4;
AlphaToCoverage: bool;
}
```
<Callout>
The [BlendOperation](/apis/galacean/#BlendOperation) and [BlendFactor](/apis/galacean/#BlendFactor) enums are identical to engine APIs.
</Callout>
### DepthState
```glsl
DepthState state {
Enabled: bool;
WriteEnabled: bool;
CompareFunction: CompareFunction.XXX;
}
```
<Callout>
The [CompareFunction](/apis/galacean/#CompareFunction) enum is identical to the engine API.
</Callout>
### StencilState
```glsl
StencilState state {
Enabled: bool;
ReferenceValue: int;
Mask: float; // 0xffffffff
WriteMask: float; // 0xffffffff
CompareFunctionFront: CompareFunction.XXX;
CompareFunctionBack: CompareFunction.XXX;
PassOperationFront: StencilOperation.XXX;
PassOperationBack: StencilOperation.XXX;
FailOperationFront: StencilOperation.XXX;
FailOperationBack: StencilOperation.XXX;
ZFailOperationFront: StencilOperation.XXX;
ZFailOperationBack: StencilOperation.XXX;
}
```
<Callout>
The [CompareFunction](/apis/galacean/#CompareFunction) and [StencilOperation](/apis/galacean/#StencilOperation) enums are identical to engine APIs.
</Callout>
### RasterState
```glsl
RasterState state {
CullMode: CullMode.XXX;
DepthBias: float;
SlopeScaledDepthBias: float;
}
```
<Callout>
The [CullMode](/apis/galacean/#CullMode) enum is identical to the engine API.
</Callout>
### renderQueueType
```glsl showLineNumbers
RenderQueueType = Transparent;
RenderQueueType = Opaque;
RenderQueueType = AlphaTest;
```
For detailed information about these render states, refer to the [documentation](./renderState).
## Structs and Functions
Equivalent to GLSL syntax. The code block below demonstrates functions and structs declared in `Shader`, `SubShader`, and `Pass` scopes:
```glsl showLineNumbers {5-9, 15-19, 25-29}
Shader "PlanarShadow" {
...
// Scope: Entire Shader module
mat4 getJointMatrix(sampler2D smp, float index) {
float base = index / renderer_JointCount;
...
return mat4(m0, m1, m2, m3);
}
...
SubShader "Default" {
...
// Scope: "Default" SubShader module
vec3 ShadowProjectPos(vec4 vertPos) {
vec3 shadowPos;
...
return shadowPos;
}
...
Pass "0" {
...
// a2v struct is only visible in Pass "0"
struct a2v {
vec4 POSITION;
vec4 JOINTS_0;
vec4 WEIGHTS_0;
};
...
}
}
...
}
```
## Single Variables
Equivalent to GLSL syntax. All **Uniform** variables in `ShaderLab` are declared using global single-variable syntax:
```glsl showLineNumbers
[lowp/mediump/highp] mat4 uMVPMatrix;
```

View File

@@ -0,0 +1,66 @@
---
title: Multi-Pass Shader Writing
---
Sometimes, to render a complex effect, we need to perform multiple rendering passes within a single rendering loop. We can organize these related passes under the same `SubShader` for unified management. A Shader containing multiple passes is commonly referred to as a **multi-pass shader**.
As shown below, declare multiple passes required for rendering within a `SubShader`. The engine will render these passes in the order they are declared:
```glsl showLineNumbers {6-8}
SubShader "SubShaderName" {
...
// Global variable area: variable declarations, struct declarations, render state declarations
...
Pass "Pass0" { ... }
Pass "Pass1" { ... }
Pass "Pass2" { ... }
...
}
```
## UsePass
Developers can reuse shader passes using the `UsePass` directive: `UsePass "{pass path}"`. The pass path format is `{ShaderName/SubShaderName/PassName}`. For example, if the following shader pass is declared:
```glsl showLineNumbers {1,3,5}
Shader "water" {
...
SubShader "Default" {
...
Pass "0" {
...
}
...
}
...
}
```
Developers can reuse it in other custom shaders via `UsePass "water/Default/0"`.
Additionally, the `UsePass` directive supports reusing built-in engine passes. Currently supported built-in passes include:
| Built-in Shader | Pass Path |
| :-------------: | :---------------------------: |
| PBR | pbr/Default/Forward |
| Unlit | unlit/Default/Forward |
| Skybox | skybox/Default/Forward |
| Particle-shader | particle-shader/Default/Forward |
| SpriteMask | SpriteMask/Default/Forward |
| Sprite | Sprite/Default/Forward |
<Callout>
The `SubShader` is not only used for organizing multiple passes but also supports setting `Tags`, which correspond to the engine's [setTag](/apis/galacean/#SubShader-setTag) API. For example, setting a `ReplaceTag`:
```glsl showLineNumbers
SubShader "SubShaderName" {
...
Tags {ReplaceTag = "opaque"}
Pass "PassName" {
...
}
}
</Callout>

View File

@@ -0,0 +1,144 @@
---
title: ShaderLab
---
`ShaderLab` is a shader wrapper language designed for the Galacean engine. It allows developers to write custom shaders using familiar `GLSL` syntax while providing additional high-level abstractions and management features to enhance development efficiency. With `ShaderLab`, developers can more easily define material properties, rendering configurations, and other effects. Although `ShaderLab` introduces convenience for shader development, it does not replace `GLSL` but remains compatible with it. Developers can write native `GLSL` code blocks within the `ShaderLab` framework to leverage the combined advantages of both.
## Syntax Overview
The basic structure of `ShaderLab` syntax is as follows:
```glsl
Shader "ShaderName" {
...
Editor {
...
}
...
SubShader "SubShaderName" {
...
Pass "PassName" {
...
}
...
}
...
}
```
### Main Syntax Modules in ShaderLab
| Syntax Module | Description |
| :- | :-- |
| [Shader](./shader) | Declares a shader object in `ShaderLab`. Developers can add material properties, bind [Shader UI scripts](./script), and [declare global variables](./global) within this module. |
| [Editor](./editor) | Customizes the material Inspector panel through the `Editor` module. |
| [SubShader](./subShader) | Specifies [Tags](/apis/galacean/#SubShader-setTag), adds shader passes, and uses the `UsePass` directive within `SubShader`. |
| [Pass](./pass) | Declares a [ShaderPass](/apis/galacean/#ShaderPass) object via the `Pass` module. |
## Unlit ShaderLab Example
```ts showLineNumbers {2,18,21}
Shader "ShaderName" {
Editor {
Properties {
material_BaseColor("Main Color", Color) = (0, 0, 0, 1);
material_BaseTexture("Texture", Texture2D);
material_AlphaCutoff("Alpha Cutoff", Range(0, 1, 0.01)) = 0;
Header("Common"){
isTransparent("Transparent", Boolean) = false;
renderFace("Render Face", Enum(Front:0, Back:1, Double:2)) = 0;
blendMode("Blend Mode", Enum(Normal:0, Additive:1)) = 0;
}
}
UIScript "${uiScriptPath}";
}
SubShader "Default" {
UsePass "pbr/Default/ShadowCaster"
Pass "Pass0" {
DepthState {
WriteEnabled = depthWriteEnabled;
}
BlendState {
Enabled = blendEnabled;
SourceColorBlendFactor = sourceColorBlendFactor;
DestinationColorBlendFactor = destinationColorBlendFactor;
SourceAlphaBlendFactor = sourceAlphaBlendFactor;
DestinationAlphaBlendFactor = destinationAlphaBlendFactor;
}
RasterState{
CullMode = rasterStateCullMode;
}
RenderQueueType = renderQueueType;
struct Attributes {
vec3 POSITION;
vec2 TEXCOORD_0;
vec4 JOINTS_0;
vec4 WEIGHTS_0;
};
struct Varyings {
vec2 uv;
};
#include "Common.glsl"
#include "Skin.glsl"
#include "Transform.glsl"
vec4 material_BaseColor;
float material_AlphaCutoff;
sampler2D material_BaseTexture;
VertexShader = vert;
FragmentShader = frag;
Varyings vert(Attributes attr) {
Varyings v;
vec4 position = vec4(attr.POSITION, 1.0);
// Skin
#ifdef RENDERER_HAS_SKIN
mat4 skinMatrix = getSkinMatrix(attr);
position = skinMatrix * position;
#endif
gl_Position = renderer_MVPMat * position;
v.uv = attr.TEXCOORD_0;
return v;
}
void frag(Varyings v) {
vec4 baseColor = material_BaseColor;
#ifdef MATERIAL_HAS_BASETEXTURE
vec4 textureColor = texture2D(material_BaseTexture, v.uv);
#ifndef ENGINE_IS_COLORSPACE_GAMMA
textureColor = gammaToLinear(textureColor);
#endif
baseColor *= textureColor;
#endif
#ifdef MATERIAL_IS_ALPHA_CUTOFF
if( baseColor.a < material_AlphaCutoff ) {
discard;
}
#endif
gl_FragColor = baseColor;
#ifndef ENGINE_IS_COLORSPACE_GAMMA
gl_FragColor = linearToGamma(gl_FragColor);
#endif
}
}
}
```

View File

@@ -0,0 +1,127 @@
---
title: Material Property Definition
---
Developers use the `Editor` module to customize material properties bound to this `Shader`. The `Galacean` editor automatically reflects these material properties to the Inspector panel of the material asset.
<div style={{display: "flex"}}>
<Image src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*mwAxRr45kE8AAAAAAAAAAAAAeteEAQ/fmt.webp" width="435px" />
<Image src= "https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*7MrxTIG5fpkAAAAAAAAAAAAAeteEAQ/fmt.webp" width="200px" />
</div>
## Editor Module Syntax Skeleton
```glsl showLineNumbers
Editor {
Properties {
material_BaseColor("Offset unit scale", Color) = (1,1,1,1);
...
Header("Emissive")
{
material_EmissiveColor("Emissive color", Color) = (1,1,1,1);
...
}
...
}
...
Macros {
[On] UV_OFFSET("UV Offset", Range(1,100)) = 10;
...
Header("") {
SOME_MACRO("label", Int) = 1;
}
}
...
// Specifies the path to the UIScript project in the editor.
UIScript "./shaderScript.ts";
}
```
### Material Property Definition
```glsl
/**
* @language zh
* Comments description
*/
/**
* @language en
* 注释描述
*/
propertyName("Description", EditType) = [DefaultValue];
```
<Callout type="info">
1. Use the `Header` directive to group related properties. The Inspector panel will reflect this hierarchy:
```
Header("Emissive") {
material_EmissiveColor("Emissive color", Color) = (1,1,1,1);
...
}
```
2. Use comments to specify hover tooltips in the Inspector. The `@language` directive supports multilingual annotations.
</Callout>
The supported `EditType` list is as follows:
| EditType | Example |
| :-: | :-- |
| Bool | propertyName("Property Description", Boolean) = true; |
| Int | propertyName("Property Description", Int) = 1; <br/>propertyName("Property Description", Range(0,8)) = 1 <br/> propertyName("Property Description", Enum(Item1: 1, Item2: 2, Item3: 3)) = 1 // Enum |
| Float | propertyName("Property Description", Float) = 0.5; <br/>propertyName("Property Description", Range(0.0, 1.0)) = 0.5; <br/> propertyName("Property Description", Enum(Item1: 1.0, Item2: 2.0, Item3: 3.0)) = 1.0; // Enum |
| Texture2D | propertyName("Property Description", Texture2D); |
| TextureCube | propertyName("Property Description", TextureCube); |
| Color | propertyName("Property Description", Color) = (0.25, 0.5, 0.5, 1); |
| Vector2 | propertyName("Property Description", Vector2) = (0.25, 0.5); |
| Vector3 | propertyName("Property Description", Vector3) = (0.25, 0.5, 0.5); |
| Vector4 | propertyName("Property Description", Vector4) = (0.25, 0.5, 0.5, 1.0); |
#### Enum Type
```glsl showLineNumbers
propertyName("Property Description", Enum(Item1: 1, Item2: 2, Item3: 3)) = 1;
```
<Callout type="warning">
Only Int and Float types support enums currently. Mixed type enums (e.g., combining Int and Float) are not supported. The following example will not be parsed correctly:
```glsl
propertyName("Property Description", Enum("Item1":1, "Item2":2.0, "Item3": 3)) = 2.0;
```
</Callout>
### Material Macro Property Definition
Used to reflect macros used in the Shader to the Inspector, enabling flexible adjustments to Shader-dependent macros in the editor.
```glsl showLineNumbers
// Enabled/Disabled
[On/Off]macroName("MacroLabel", EditType) = [DefaultValue];
```
The `[On/Off]` directive specifies the macro's default state. The editor currently supports the following macro types:
| Type | Example |
| :-----: | :-------------------------------------------------------------------------------------------------------- |
| No-Value Macro | macroName("Macro Description"); |
| Bool | macroName("Macro Description", Boolean) = true; |
| Int | macroName("Macro Description", Int) = 1; <br/> macroName("Macro Description", Range(0,8)) = 1; |
| Float | macroName("Macro Description", Float) = 0.5; <br/> macroName("Macro Description", Range(0.0, 1.0)) = 0.5; |
| Color | macroName("Macro Description", Color) = (0.25, 0.5, 0.5, 1); |
| Vector2 | macroName("Macro Description", Vector2) = (0.25, 0.5); |
| Vector3 | macroName("Macro Description", Vector3) = (0.25, 0.5, 0.5); |
| Vector4 | macroName("Macro Description", Vector4) = (0.25, 0.5, 0.5, 1.0);

View File

@@ -0,0 +1,86 @@
---
title: Rendering State Setup
---
In the Galacean engine, each Shader `Pass` represents a GPU rendering process, so we can set rendering states for each `Pass` individually. In ShaderLab, there are two ways to configure these states.
### 1. Explicit Assignment
```glsl showLineNumbers {4, 10}
...
Pass "0" {
...
BlendState blendState {
Enabled = true;
ColorBlendOperation = BlendOperation.Add;
...
}
BlendState = blendState;
...
}
...
```
As shown in the [global variables section](./global), you can declare rendering state variables in different scope levels and then assign them using `BlendState = blendState`.
### 2. Declaration within Global Variable Scope
```glsl showLineNumbers {4}
...
Pass "0" {
...
BlendState {
Enabled = true;
ColorBlendOperation = BlendOperation.Add;
...
}
...
}
...
```
<Callout type="info">
1. The configuration for `DepthState`, `StencilState`, and `RasterState` follows the same pattern.
2. The global variable scope can also be at the `SubShader` or `Shader` level. Its scope follows the same [rules](./global/#Global_Variable_Scope) as other global variables. For example, a rendering state defined at the `SubShader` level will apply to all `Pass`es under that `SubShader`.
</Callout>
## Rendering State Property Configuration
There are also two methods for configuring individual rendering state properties:
```glsl showLineNumbers {7,9}
Shader "Demo" {
...
BlendState customBlendState
{
Enabled = true;
// Constant assignment
SourceColorBlendFactor = BlendFactor.SourceColor;
// Variable assignment
DestinationColorBlendFactor = material_DstBlend;
}
...
Pass "0" {
...
BlendState = customBlendState;
...
}
}
```
The above example demonstrates two approaches for assigning `BlendState` properties: **constant assignment** and **variable assignment**.
### Constant Assignment
The right-hand side of the assignment statement uses specific engine enum values, e.g.: `BlendFactor.SourceColor`.
<Callout type="warning">
An exception exists for render queue configuration: `RenderQueueType = Transparent;`
</Callout>
### Variable Assignment
The right-hand side of the assignment uses a variable name. The actual value can be set at runtime by developers through the API `ShaderData.setInt("material_DstBlend", BlendFactor.SourceColor)`.

View File

@@ -0,0 +1,131 @@
---
title: Using and Binding UIScript
---
While developers can adjust custom material properties in the editor, they can also specify callback behaviors for data changes using the `UIScript` directive. By leveraging hook functions exposed by UIScript, developers can implement property interdependencies, reducing the number of declared properties and simplifying the Inspector panel.
### Binding `UIScript` in ShaderLab:
```glsl showLineNumbers
Editor {
...
UIScript "/path/to/script";
...
}
```
The bound `UIScript` script path supports both relative and absolute paths. Using the project root directory as an example, the absolute path is `/PBRScript1.ts` and the relative path is `./PBRScript1.ts`.
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*t4LFQ4KEL6kAAAAAAAAAAAAADteEAQ/fmt.webp"
width="70%"
/>
### UIScript Interface
The editor exposes relevant APIs through the built-in `ShaderUIScript` class. The type definition of `ShaderUIScript` is embedded in the Galacean Web editor, with the complete definition as follows:
```ts
import { Color, Material, Texture, Vector2, Vector3, Vector4 } from "@galacean/engine";
type ShaderPropertyValue = number | Vector2 | Vector3 | Vector4 | Color | Texture;
type ShaderMacroValue = number | Vector2 | Vector3 | Vector4 | Color;
/**
* Script for extending `Shader` UI logic.
*/
export abstract class ShaderUIScript {
/** @internal */
_propertyCallBacks: Map<string, (material: Material, value: ShaderPropertyValue) => void> = new Map();
/** @internal */
_macroCallBacks: Map<string, (material: Material, defined: boolean, value: ShaderMacroValue) => void> = new Map();
/**
* Called when the shader is switched.
* @param material - The material the shader is bound to
*/
onMaterialShaderSwitched(material: Material): void {}
/**
* Registers a property change callback.
* @param propertyName - Property name
* @param onChanged - Callback triggered when the property changes
*/
protected onPropertyChanged(
propertyName: string,
onChanged: (material: Material, value: ShaderPropertyValue) => void
): void {
this._propertyCallBacks.set(propertyName, onChanged);
}
/**
* Registers a macro change callback.
* @param macroName - Macro name
* @param onChanged - Callback triggered when the macro changes
*/
protected onMacroChanged(
macroName: string,
onChanged: (material: Material, defined: boolean, value: ShaderMacroValue) => void
): void {
this._macroCallBacks.set(macroName, onChanged);
}
}
```
### Writing UIScript
1. Create a UIScript in the editor.
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*Qh4UTZgaY7MAAAAAAAAAAAAADteEAQ/fmt.webp"
width="60%"
figcaption="Creating UIScript"
/>
2. Specify property change callbacks by extending the `ShaderUIScript` class.
```ts
import { Material, RenderQueueType, Vector3, BlendFactor, RenderFace, CullMode, BlendMode } from "@galacean/engine";
export default class extends ShaderUIScript {
constructor() {
super();
// Register property change listeners in the constructor
this.onPropertyChanged("material_NormalTexture", (material: Material, value) => {
const shaderData = material.shaderData;
if (value) {
shaderData.enableMacro("MATERIAL_HAS_NORMALTEXTURE");
} else {
shaderData.disableMacro("MATERIAL_HAS_NORMALTEXTURE");
}
});
}
// Override shader binding callback
override onMaterialShaderSwitched(material: Material) {
const shaderData = material.shaderData;
shaderData.disableMacro("MATERIAL_OMIT_NORMAL");
shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
// Set default values
const anisotropyInfo = shaderData.getVector3("material_AnisotropyInfo");
if (!anisotropyInfo) {
shaderData.setVector3("material_AnisotropyInfo", new Vector3(1, 0, 0));
} else {
shaderData.setFloat("anisotropy", anisotropyInfo.z);
const PI2 = Math.PI * 2;
const rotationRad = (Math.atan2(anisotropyInfo.y, anisotropyInfo.x) + PI2 ) % PI2;
shaderData.setFloat("anisotropyRotation", rotationRad * (180 / Math.PI))
}
}
}
```
<Callout info="warning">
Note: The current version of ShaderLab's material property module only defines the Inspector UI panel for materials bound to this shader in the editor. It does not automatically declare corresponding global variables in `ShaderPass`. If these variables are referenced in `ShaderPass` code, you must explicitly declare them in the [global variables](./shader/#Global_Variables) module.
</Callout>

View File

@@ -0,0 +1,60 @@
---
title: Built-in Variables
---
Built-in variables are frequently used in Shader code. There are two types: **per-vertex** `attribute` variables and **per-shader** `uniform` variables.
Below are the engine's built-in variables for reference when writing Shaders:
### Vertex Inputs
| Per-vertex Data | Attribute Name | Data Type |
| :-------------- | :------------- | :-------- |
| Vertex | POSITION | vec3 |
| Normal | NORMAL | vec3 |
| Tangent | TANGENT | vec4 |
| Vertex Color | COLOR_0 | vec4 |
| Bone Indices | JOINTS_0 | vec4 |
| Bone Weights | WEIGHTS_0 | vec4 |
| First UV Set | TEXCOORD_0 | vec2 |
| Second UV Set | TEXCOORD_1 | vec2 |
### Properties
#### Renderer
| Name | Type | Description |
| :---------------- | :--- | :--------------------------- |
| renderer_LocalMat | mat4 | Model local coordinate matrix |
| renderer_ModelMat | mat4 | Model world coordinate matrix |
| renderer_MVMat | mat4 | Model view matrix |
| renderer_MVPMat | mat4 | Model view projection matrix |
| renderer_NormalMat| mat4 | Normal matrix |
#### Camera
| Name | Type | Description |
| :-------------------------- | :-------- | :-------------------------------------------------------------------------- |
| camera_ViewMat | mat4 | View matrix |
| camera_ProjMat | mat4 | Projection matrix |
| camera_VPMat | mat4 | View projection matrix |
| camera_ViewInvMat | mat4 | Inverse view matrix |
| camera_Position | vec3 | Camera position |
| camera_DepthTexture | sampler2D | Depth information texture |
| camera_OpaqueTexture | sampler2D | Opaque texture |
| camera_DepthBufferParams | Vec4 | Camera depth buffer parameters: (x: 1.0 - far / near, y: far / near, z: 0, w: 0) |
| camera_ProjectionParams | Vec4 | Projection matrix parameters: (x: flipProjection ? -1 : 1, y: near, z: far, w: 0) |
#### Time
| Name | Type | Description |
| :---------------- | :--- | :-------------------------------------------------------------- |
| scene_ElapsedTime | vec4 | Total time since engine started: (x: t, y: sin(t), z: cos(t), w: 0) |
| scene_DeltaTime | vec4 | Time since last frame: (x: dt, y: 0, z: 0, w: 0) |
#### Fog
| Name | Type | Description |
| :----------------- | :--- | :---------- |
| scene_FogColor | vec4 | Fog color |
| scene_FogParams | vec4 | Fog parameters: (x: -1/(end-start), y: end/(end-start), z: density / ln(2), w: density / sqr(ln(2)) |

View File

@@ -1,9 +0,0 @@
{
"intro": { "title": "Shader Introduction" },
"class": { "title": "Shader Object" },
"builtins": { "title": "Built-in Shaders" },
"custom": { "title": "Custom Shaders" },
"assets": { "title": "Shader Assets" },
"shaderLab": { "title": "ShaderLab" },
"shaderAPI": { "title": "Shader API [Experimental]" }
}

View File

@@ -1,25 +0,0 @@
---
title: Shader Assets
---
Shader assets define Shader objects in the Galacean editor project and currently include two types:
- Shader Main File
With the `.gs` suffix, it is the entry file compiled by ShaderLab.
- Shader Chunk
With the `.glsl` suffix, it is a reusable ShaderLab code snippet introduced via the `#include` macro.
<Callout type="warning">
`EditorProperties` and `EditorMacros` can only be declared in the Shader main file and cannot be introduced via the `#include` macro.
</Callout>
## Shader Asset Creation
<Image src="https://mdn.alipayobjects.com/huamei_rmtxpm/afts/img/A*namMTLNnCPYAAAAAAAAAAAAADv-7AQ/original" />
The editor provides three Shader asset file templates: `Unlit Shader`, `PBR Shader`, and `Shader Chunk`. Similar to script components, selecting a Shader asset allows you to preview the Shader code in the Inspector interface. You can edit the Shader code in real-time by double-clicking or selecting it in the code editing page.
Go to [Shader API Tutorial](/en/docs/graphics/shader/shaderAPI/) to learn how to extend Shaders based on the templates.

View File

@@ -1,26 +0,0 @@
---
title: Blinn Phong
---
[BlinnPhongMaterial](/apis/core/#BlinnPhongMaterial) material is one of the classic materials. Although it is not based on physical rendering, its efficient rendering algorithm and comprehensive optical components make it still applicable to many scenarios today.
## Editor Usage
<Image src="https://gw.alipayobjects.com/zos/OasisHub/eaa93827-29a4-46ad-b9d3-f179fa200c57/blinn.gif" alt="blinn" style={{ zoom: "100%" }} />
## Parameter Introduction
| Parameter | Application |
| :-- | :-- |
| [baseColor](/apis/core/#BlinnPhongMaterial-baseColor) | Base color. **Base color \* Base texture = Final base color.** |
| [baseTexture](/apis/core/#BlinnPhongMaterial-baseTexture) | Base texture. Used in conjunction with the base color, it is a multiplicative relationship. |
| [specularColor](/apis/core/#BlinnPhongMaterial-specularColor) | Specular reflection color. **Specular reflection color \* Specular reflection texture = Final specular reflection color.** |
| [specularTexture](/apis/core/#BlinnPhongMaterial-specularTexture) | Specular reflection texture. Used in conjunction with the specular reflection color, it is a multiplicative relationship. |
| [normalTexture](/apis/core/#BlinnPhongMaterial-normalTexture) | Normal texture. You can set the normal texture to create a bump effect visually, and control the bump degree through normal intensity. |
| [normalIntensity](/apis/core/#BlinnPhongMaterial-normalIntensity) | Normal intensity. Used to control the bump degree. |
| [emissiveColor](/apis/core/#BlinnPhongMaterial-emissiveColor) | Emissive color. **Emissive color \* Emissive texture = Final emissive color. Even without lighting, it can render color.** |
| [emissiveTexture](/apis/core/#BlinnPhongMaterial-emissiveTexture) | Emissive texture. Used in conjunction with the emissive color, it is a multiplicative relationship. |
| [shininess](/apis/core/#BlinnPhongMaterial-shininess) | Specular reflection coefficient. The larger the value, the more concentrated the specular reflection effect. |
| [tilingOffset](/apis/core/#BlinnPhongMaterial-tilingOffset) | Scaling and offset of texture coordinates. It is a Vector4 data that controls the scaling and offset of texture coordinates in the uv direction. Refer to [example](/en/embed/tiling-offset) |
If you need to use the material through scripts, please refer to the [Material Usage Tutorial](/en/docs/graphics/material/script).

View File

@@ -1,54 +0,0 @@
---
title: Eyes
---
The eye shader provides realistic rendering for eyeball models, giving your creations a lifelike artistic effect.
<img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*VVUtRL4JfE0AAAAAAAAAAAAADgDwAQ/original" />
<Callout type="info">
This shader is strongly associated with the model UV. If you need to build eyes from scratch, it is not recommended to use this shader. For those without shader code development experience, it is recommended to use the eyeball geometry model from the official examples and simply replace the necessary textures to meet your needs. If you need to create your own eye shader variant, please refer to the [shader lab development tutorial](/en/docs/graphics-shader-lab) document.
</Callout>
## Import Eye Example
Galacean comes with an eyeball material example to further help you get started. To view this example, [click here](https://galacean.antgroup.com/editor/projects).
1. Navigate to the editor homepage in the Galacean editor.
2. Select the **Templates** panel, navigate to the template interface, preview, and download the eyeball example to **Project**.
## Eyeball Anatomy
Before starting to render eyes, familiarize yourself with the biological structure of the eyeball to better use the shader.
| Parameter | Description |
| :-------------------: | :-------------------------------------------------------: |
| Sclera (Sclera) | The sclera is the opaque membrane on the outer layer of the eyeball, commonly known as the "white of the eye" |
| Limbus (Limbus) | Also known as the corneoscleral junction, it is the boundary between the cornea and the sclera (white of the eye) |
| Iris (Iris) | The iris is a ring of color surrounding the pupil center, forming a hollow ring |
| Pupil (Pupil) | The pupil is the black part at the center of the eyeball, allowing light to enter the eye and reach the retina |
| Cornea (Cornea) | The cornea is the transparent part located at the front of the eyeball |
## Eye Textures
| Texture | Parameter | Description |
| :-------------------------------------------------------------: | :------------------------: | :------------------------------------------------------------------ |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*74fgRYw9nS4AAAAAAAAAAAAADgDwAQ/original" /> | Sclera Texture | Specifies the texture that controls the color of the sclera (white of the eye) and the color of the blood vessels around the eye. If you want the eyeball to be full of blood vessels, you need to modify this texture |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*Nc_XTpVNlFAAAAAAAAAAAAAADgDwAQ/original" /> | Iris Texture | Controls the color of the iris |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*jkZ5QoeXyWUAAAAAAAAAAAAADgDwAQ/original" /> | Iris Normal Texture | Specifies the texture to control the normals of the iris, determining the light flow on the surface of the iris |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*B8McQpjhh98AAAAAAAAAAAAADgDwAQ/original" /> | Cornea Normal Texture | Specifies the texture to control the normals of the sclera, providing subtle texture variations of the sclera (white of the eye) |
| <img src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*c_zmQ5DwI1wAAAAAAAAAAAAADgDwAQ/original" /> | Sclera Mask | Specifies a mask texture to control the size of the sclera/iris/limbus/pupil. The `R` channel controls the iris area, the `G` channel controls the limbus area, and the `B` channel controls the pupil scaling area |
## Material Properties
| Parameter | Description |
| :---------------------: | :-------------------------------------: |
| Sclera Color | Sclera texture color |
| Sclera Size | Sclera UV size |
| Sclera Specular | Sclera (white of the eye) metallicity |
| Sclera Roughness | Sclera (white of the eye) roughness |
| Pupil Dilation | Pupil size, adjustable in the xy direction |
| Limbal Ring Amount | Intensity of the limbal ring |
| Parallax Layer | Parallax depth |
| Iris Color | Iris color |
| Eye Iris Size | Iris size |

View File

@@ -1,30 +0,0 @@
---
title: Hair
---
Hair shading is based on the Kajiya-Kay shading model, which approximates the dual-layer anisotropic highlights on the hair surface, commonly known as "angel rings" in hair rendering.
<Image src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*k7t9RbgNMOIAAAAAAAAAAAAADgDwAQ/original" />
## Import Example
Galacean provides you with a hair example to further help you get started. To find this example, please [click](https://galacean.antgroup.com/editor/projects).
1. Navigate to the editor homepage in the Galacean Editor.
2. Select the **Templates** panel, navigate to the template interface, preview and download the hair example to **Project**.
## Dual-layer Highlights
<Image src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*IZrjTY7JbfkAAAAAAAAAAAAADgDwAQ/original" />
## Material Properties
| Parameter | Description |
| :----------------: | :----------------: |
| HairFirstWidth | Adjust the width of the first layer "angel ring highlight" of the hair |
| HairSecondWidth | Adjust the width of the second layer "angel ring highlight" of the hair |
| HairFirstStrength | The intensity of the first layer highlight of the hair. For example, if you need a stronger highlight effect, you can increase the value |
| HairSecondStrength | The intensity of the second layer highlight of the hair. For example, if you need a stronger highlight effect, you can increase the value |
| HairFirstOffest | The offset of the first layer highlight of the hair. If you want to adjust the position of the highlight, you can modify this value |
| HairSecondOffest | The offset of the second layer highlight of the hair. If you want to adjust the position of the highlight, you can modify this value |
| HairFirstColor | The color of the first layer highlight of the hair |
| HairSecondColor | The color of the second layer highlight of the hair |

View File

@@ -1,31 +0,0 @@
---
title: Skin
---
The skin uses the Spherical Gaussian model, allowing flexible customization of different Diffusion Profiles to simulate human skin or general subsurface scattering effects.
<Image src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*ynWiSp_2n90AAAAAAAAAAAAADgDwAQ/original" />
## Import Example
Galacean provides you with a skin example to further help you get started. To find this example, please [click](https://galacean.antgroup.com/editor/projects).
1. Navigate to the editor homepage in the Galacean editor.
2. Select the **Templates** panel, navigate to the template interface, preview, and download the skin example to **Project**.
## Material Properties
| Parameter | Description |
| :-------------------: | :-----------------------------: |
| SSSColor | Adjust the skin scattering color |
| CurvatureTexture | Curvature map, controls the scattering area |
| CurvaturePower | Intensity of curvature, the best range is between `0-1` |
## Detail Display
The following demonstration compares the differences between PBR and skin materials.
<Comparison
leftSrc="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*NLyOR71_nj4AAAAAAAAAAAAADgDwAQ/original"
leftText="PBR"
rightSrc="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*xfl_Ra0oj0AAAAAAAAAAAAAADgDwAQ/original"
rightText="SSS"
/>

View File

@@ -1,25 +0,0 @@
---
title: Introduction
---
Currently, the Galacean engine has many built-in shaders, such as
| Type | Description |
| :-- | :-- |
| [Unlit](/en/docs/graphics/shader/builtins/unlit) | The Unlit Shader is suitable for rendering baked models. It only requires setting a basic texture or color to display high-quality rendering results obtained from offline rendering. However, the downside is that it cannot display real-time light and shadow interactions because Unlit rendering is determined by the texture and is not affected by any lighting. Refer to [Baking Tutorial](/en/docs/art/bake-blender) and [Export Unlit Tutorial](/en/docs/graphics/shader/builtins/unlit) |
| [Blinn Phong](/en/docs/graphics/shader/builtins/blinnPhong) | The Blinn Phong Shader is suitable for scenes that do not require high realism. Although it does not follow physical principles, its efficient rendering algorithm and comprehensive optical components make it suitable for many scenes. |
| [PBR](/en/docs/graphics/shader/builtins/pbr) | The PBR Shader is suitable for applications that require realistic rendering. Since PBR is based on physical rendering and follows energy conservation, developers can ensure that the rendering effects are physically correct by adjusting parameters such as metallicity, roughness, and lighting. |
You can directly debug the corresponding properties of the built-in shaders in the editor to observe real-time rendering effect changes.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/94cf8176-569d-4605-bd73-967b03316c3d/image-20240206173751409.png" />
> Correspondingly, you can achieve the same effect by setting the APIs of PBRMaterial, BlinnPhongMaterial, and UnlitMaterial materials.
| Parameter | Application |
| :-- | :-- |
| [isTransparent](/apis/core/#BaseMaterial-isTransparent) | Transparency. You can set whether the material is transparent. If set to transparent, you can use [BlendMode](/apis/core/#BaseMaterial-blendMode) to set the color blending mode. |
| [alphaCutoff](/apis/core/#BaseMaterial-alphaCutoff) | Alpha cutoff value. You can set the cutoff value. In the shader, fragments with transparency less than this value will be culled. Refer to [Example](/en/embed/blend-mode) |
| [renderFace](/apis/core/#BaseMaterial-renderFace) | Render face. You can decide to render the front, back, or both sides. |
| [blendMode](/apis/core/#BaseMaterial-blendMode) | Color blending mode. When the material is set to transparent, you can set this enumeration to decide the color blending mode. Refer to [Example](/en/embed/blend-mode) |
| [tilingOffset](/apis/core/#BlinnPhongMaterial-tilingOffset) | Texture coordinate scaling and offset. It is a Vector4 data that controls the scaling and offset of texture coordinates in the uv direction. Refer to [Example](/en/embed/tiling-offset) |

View File

@@ -1,176 +0,0 @@
---
title: PBR
---
PBR, short for Physically Based Rendering, is a rendering method first introduced by Disney in 2012 and later widely adopted by the gaming industry. Compared to traditional rendering methods like Blinn-Phong, PBR adheres to energy conservation and follows physical principles. Artists only need to adjust a few simple parameters to achieve accurate rendering results, even in complex scenes. PBR incorporates energy conservation, is physically-based, and introduces IBL (Image-Based Lighting) to simulate global illumination. By using parameters such as metallic and roughness, it allows for more convenient adjustment of rendering effects.
## Introduction to Basic PBR Parameters
| Parameter | Application |
| :-- | :-- |
| [metallic](/apis/core/#PBRMaterial-metallic) | Metallic Level: Simulates the metallic nature of a material. The higher the metallic value, the stronger the specular reflection, allowing more surrounding environment to be reflected. |
| [roughness](/apis/core/#PBRMaterial-roughness) | Roughness: Simulates the material's roughness. The higher the roughness, the less smooth the micro-surface becomes, resulting in more diffuse specular reflections. |
| [roughnessMetallicTexture](/apis/core/#PBRMaterial-roughnessMetallicTexture) | Metallic-Roughness Texture: Works in conjunction with metallic and roughness values, using a multiplicative relationship. |
| [baseColor](/apis/core/#PBRBaseMaterial-baseColor) | Base Color: Base Color × Base Color Texture = Final Base Color. Base color represents the material's reflectance value. Unlike traditional diffuse colors, it contributes to both specular and diffuse reflections. You can adjust the metallic and roughness properties to control the ratio of these contributions.|
| [emissiveColor](/apis/core/#PBRBaseMaterial-emissiveColor) | Emissive Color: Allows materials to emit light, rendering colors even without illumination.|
| [baseTexture](/apis/core/#PBRBaseMaterial-baseTexture) | Base Color Texture: Works with base color in a multiplicative relationship. |
| [normalTexture](/apis/core/#PBRBaseMaterial-normalTexture) | Normal Map Texture: Simulates surface bumps visually using a normal map, with adjustable strength to control the intensity of the effect. |
| [emissiveTexture](/apis/core/#PBRBaseMaterial-emissiveTexture) | Emissive Texture: Used in conjunction with emissive color[emissiveFactor](/apis/core/#PBRBaseMaterial-emissiveTexture)to achieve self-emitting effects. |
| [occlusionTexture](/apis/core/#PBRBaseMaterial-occlusionTexture) | Occlusion Texture: Enhances shadow detail using an occlusion map. |
| [tilingOffset](/apis/core/#PBRBaseMaterial-tilingOffset) | Texture Tiling and Offset: A Vector4 controlling the tiling and offset of the texture in the UV directionsSee [example](/examples/tiling-offset) |
| [clearCoat](/apis/core/#PBRBaseMaterial-clearCoat) | Clear Coat Intensity: Default is 0, meaning the clear coat effect is disabled. See [example](/examples/pbr-clearcoat) 。 |
| [clearCoatTexture](/apis/core/#PBRBaseMaterial-clearCoatTexture) | Clear Coat Intensity Texture: Works multiplicatively with clearCoat. |
| [clearCoatRoughness](/apis/core/#PBRBaseMaterial-clearCoatRoughness) | Clear Coat Roughness: Determines the roughness of the clear coat layer. |
| [clearCoatRoughnessTexture](/apis/core/#PBRBaseMaterial-clearCoatRoughnessTexture) | Clear Coat Roughness Texture: Works multiplicatively with clearCoatRoughness. |
| [clearCoatNormalTexture](/apis/core/#PBRBaseMaterial-clearCoatNormalTexture) | Clear Coat Normal Texture: If not set, it defaults to using the base material's normal texture. |
Adjusting the metallic property reveals that higher metallic values make the environment reflection more vivid, transitioning from pure white to colored. This happens because fully metallic surfaces (metallic = 1) reflect 100% of the light, including the surrounding environment:
<img src="https://gw.alipayobjects.com/zos/OasisHub/711f8b97-247c-465e-8cf2-4896b0c78534/metal.gif" />
<Callout type="warning">
Beyond these general parameters, PBR supports two workflows: **Metallic-Roughness** and **Specular-Glossiness**, corresponding to [PBRMaterial](/apis/core/#PBRMaterial) and [PBRSpecularMaterial](/apis/core/#PBRSpecularMaterial)。
</Callout>
## PBRMaterial
#### Anisotropy
<Callout type="info"> Anisotropy refers to the material's property of reflecting light differently in various directions, often seen in materials like metals, fabrics, and hair. </Callout>
| Parameter | Application |
| :-- | :-- |
| [anisotropy](/apis/core/#PBRMaterial-anisotropy) | Anisotropy Strength: Default is 0, disabling anisotropic effects. See [example](/examples/pbr-anisotropy) 。 |
| [anisotropyRotation](/apis/core/#PBRMaterial-anisotropyRotation) | Anisotropy Rotation: Rotates the effect in tangent space. |
| [anisotropyTexture](/apis/core/#PBRMaterial-anisotropyTexture) | Anisotropy Texture: The RG channels store direction information (combined with anisotropyRotation), while the B channel stores anisotropy strength (multiplied by anisotropy). |
To enable anisotropy
- Navigate to the Inspector Enable [anisotropy](/apis/core/#PBRMaterial-anisotropy) and adjust its parameters:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*j0jGRZL3iBsAAAAAAAAAAAAADgDwAQ/original"
/>
#### Sheen
<Callout type="info">
Typically used to simulate the subtle glossy effect of surfaces like fabrics, this effect is usually visible at certain viewing angles. It mimics the light-scattering characteristics of materials like silk, velvet, or other finely textured surfaces.
</Callout>
| Parameter | Description |
| :-- | :-- |
| [sheenColor](/apis/core/#PBRMaterial-sheenColor) | Base sheen color of the surface. This property determines the observed glossy color when light interacts with the surface.|
| [sheenColorTexture](/apis/core/#PBRMaterial-sheenColorTexture) | Adds more complex and detailed variations to the sheen color. Using this texture allows different areas of the surface to exhibit distinct glossy colors. |
| [sheenRoughness](/apis/core/#PBRMaterial-sheenRoughness) | Defines the surface roughness. Lower values indicate smoother surfaces with more concentrated gloss, while higher values create rougher surfaces with softer, more diffused gloss. |
| [sheenRoughnessTexture](/apis/core/#PBRMaterial-sheenRoughnessTexture) | Allows variations in roughness across the surface using a texture, enabling detailed roughness patterns for more realistic effects. |
<Image
figcaption="Glossy variations on fabric surfaces at different angles"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*mQ5UT7TnFrEAAAAAAAAAAAAADgDwAQ/original"
/>
Enable sheen
- Select the material and adjust the corresponding parameters to achieve the desired effect:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*ID62RJf8sFYAAAAAAAAAAAAADgDwAQ/original"
/>
#### Thin Film Iridescence
<Callout type="info"> This effect causes surface colors to change based on the viewing and lighting angles. It's commonly seen in natural phenomena like soap bubbles, insect wings, pearls, and more. </Callout>
| Parameter | Description |
| :-- | :-- |
| [iridescence](/apis/core/#PBRMaterial-iridescence) | Intensity of the thin-film iridescence, ranging from 0 to 1. |
| [iridescenceTexture](/apis/core/#PBRMaterial-iridescenceTexture) | Texture controlling the intensity of the thin-film iridescence. |
| [iridescenceIOR](/apis/core/#PBRMaterial-iridescenceIOR) | Index of refraction for the thin-film effect, influencing the degree of light bending and resulting colors. |
| [iridescenceThicknessRange](/apis/core/#PBRMaterial-iridescenceThicknessRange) | Defines the thickness range of the thin film, determining the color variation caused by the iridescence effect. |
| [iridescenceThicknessTexture](/apis/core/#PBRMaterial-iridescenceThicknessTexture) | Texture defining the thickness variation of the thin film, influencing the final colors. |
<Image
figcaption="Thin film iridescence effect"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*GEksSY3q1qUAAAAAAAAAAAAADgDwAQ/original"
/>
Enable Iridescence
- Select the material, ensure [iridescence](/apis/core/#PBRMaterial-iridescence) is greater than 0, and enable the thin-film effect
- Adjust parameters like [metallic](/apis/core/#PBRMaterial-metallic) [roughness](/apis/core/#PBRMaterial-roughness) [iridescenceIOR](/apis/core/#PBRMaterial-iridescenceIOR) to achieve the desired result
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*GJU9Ra9ZWUIAAAAAAAAAAAAADgDwAQ/original"
/>
#### Transmission
<Callout type="info">Describes the portion of light passing through an object rather than being reflected or absorbed. This phenomenon occurs in transparent or translucent materials when part of the light passes through the surface.</Callout>
<Image
figcaption="Variation of transmission from 0 to 1"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*P7XpSoWpRdQAAAAAAAAAAAAADgDwAQ/original"
/>
| Parameter | Description |
| :-- | :-- |
| [transmission](/apis/core/#PBRMaterial-transmission) | Controls the intensity of light transmission through the material, ranging from 0 (opaque) to 1 (fully transparent). |
| [transmissionTexture](/apis/core/#PBRMaterial-transmissionTexture) | A texture that multiplies with the transmission value, sampled from the R channel, to control varying transmission intensities across the surface. |
Enable transmission
- First, enable the Opaque Texture option in both the Camera and Scene settings:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*_tBbRYNaBPMAAAAAAAAAAAAADgDwAQ/original"
/>
- Select the material and adjust the related transmission parameters:
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*tTT_TbnawQQAAAAAAAAAAAAADgDwAQ/original"
/>
<Callout type="warning">
`Refraction` occurs based on the physical principle that it requires `transmission`. This means `refraction` effects only apply when [transmission](/apis/core/#PBRMaterial-transmission) is greater than 0.
</Callout>
#### Refraction
| Parameter | Description |
| :-- | :-- |
| [attenuationColor](/apis/core/#PBRMaterial-attenuationColor) | Absorption color, determining the color change of light as it travels through the object. Useful for simulating colored glass, liquids, or gemstone effects. |
| [attenuationDistance](/apis/core/#PBRMaterial-attenuationDistance) | The distance over which light diminishes within the object. Shorter distances result in denser appearances with more pronounced color changes, while longer distances produce more gradual changes. A value of 0 means no attenuation. |
| [thickness](/apis/core/#PBRMaterial-thickness) | Refraction thickness, controlling the bending of light as it passes through the object. Higher values produce more pronounced refraction, while smaller values create straighter light paths. |
| [thicknessTexture](/apis/core/#PBRMaterial-thicknessTexture) | A texture sampled from the G channel to define thickness variations. White areas represent greater thickness, black areas represent less, and it multiplies with the [thickness](/apis/core/#PBRMaterial-thickness) value. |
<Image
figcaption="Changes in attenuationDistance and resulting color variations"
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*TSZlQ7HOaS4AAAAAAAAAAAAADgDwAQ/original"
/>
Enable Refraction
- After enabling [transmission](/apis/core/#PBRMaterial-transmission), set [thickness](/apis/core/#PBRMaterial-thickness) to a value greater than 0 to activate refraction.
- Adjust attenuation color, attenuation distance, and other parameters to fine-tune the effect.
<Image
src="https://mdn.alipayobjects.com/huamei_9ahbho/afts/img/A*yKNsQpiPQxoAAAAAAAAAAAAADgDwAQ/original"
/>
> Assumptions made for implementing the refraction algorithm:
>
> A simple geometric approximation is used to simulate the surface characteristics of the object. The material's refraction mode is determined using [refractionMode](/apis/core/#PBRMaterial-refractionMode).
| refractionMode | Description |
| :-- | :-- |
| [Sphere](/apis/core/#PBRMaterial-Sphere) | Uses a sphere as the geometric approximation for the surface, efficiently handling light refraction on curved surfaces. |
| [Planar](/apis/core/#PBRMaterial-Planar) | Uses a plane as the geometric approximation for the surface, suitable for simulating transmission and refraction on flat materials. |
## PBRSpecularMaterial
| Parameter | Application |
| :-- | :-- |
| [specularColor](/apis/core/#PBRMaterial-specularColor) | Specifies the specular highlight color directly instead of deriving it from metallic and base color values (only effective when the metallic-roughness workflow is disabled).|
| [glossiness](/apis/core/#PBRMaterial-glossiness) | Simulates surface smoothness, opposite to roughness (only effective when the metallic-roughness workflow is disabled). |
| [specularGlossinessTexture](/apis/core/#PBRMaterial-specularGlossinessTexture) | A texture for combining specular color and glossiness, with the values being multiplied together. |
> **Note**PBR require [ambient lighting](/en/docs/graphics-light-ambient) to be enabled.
For scripting materials,refer to the [Material Usage Guide](/en/docs/graphics-material-script).

View File

@@ -1,63 +0,0 @@
---
title: Unlit
---
In some simple scenes, you might not want to calculate lighting. The engine provides [UnlitMaterial](/apis/core/#UnlitMaterial), which uses the most streamlined shader code and only requires color or texture to render. Unlit material is suitable for rendering baked models. It only needs a basic texture or color to display the high-quality rendering results obtained from offline rendering. However, the downside is that it cannot display real-time light and shadow interactions because Unlit is determined by the texture and is not affected by any lighting.
## Editor Usage
<Image src="https://gw.alipayobjects.com/zos/OasisHub/6be78a08-3075-4cd1-8cad-9757fc34f695/unlit.gif" alt="unlit" style={{ zoom: "100%" }} />
## Parameter Introduction
| Parameter | Application |
| :-- | :-- |
| [baseColor](/apis/core/#UnlitMaterial-baseColor) | Base color. **Base color \* Base color texture = Final color.** |
| [baseTexture](/apis/core/#UnlitMaterial-baseTexture) | Base texture. Used in conjunction with the base color, it is a multiplicative relationship. |
| [tilingOffset](/apis/core/#UnlitMaterial-tilingOffset) | Scaling and offset of texture coordinates. It is a Vector4 data that controls the scaling and offset of texture coordinates in the uv direction. Refer to [example](/en/embed/tiling-offset) |
If you need to use the material through a script, you can go to the [material usage tutorial](/en/docs/graphics/material/script).
## Export Unlit Material from Blender
As introduced in the [baking tutorial](/en/docs/art/bake-blender), if we have already created the baked map and want a **convenient material** where the color is only influenced by the baked texture, without adding lights, debugging normals, or adjusting advanced properties like metallic roughness, then you can try Galacean's [UnlitMaterial](/apis/core/#UnlitMaterial). glTF has a dedicated [KHR_materials_unlit](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) plugin, which Galacean will parse to generate Unlit material.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/39965fc2-3fc2-44b9-a294-a04eb4441120/1623652741734-090284d5-9b1a-4db8-9231-dc3f4d188a38-20210614150743080.png" alt="image.png" style={{ zoom: "50%" }} />
Test model: [TREX.zip](https://www.yuque.com/attachments/yuque/0/2021/zip/381718/1623651429048-7f6a3610-d5cb-4a73-97f5-0d37d0c63b2c.zip?_lake_card=%7B%22src%22%3A%22https%3A%2F%2Fwww.yuque.com%2Fattachments%2Fyuque%2F0%2F2021%2Fzip%2F381718%2F1623651429048-7f6a3610-d5cb-4a73-97f5-0d37d0c63b2c.zip%22%2C%22name%22%3A%22TREX.zip%22%2C%22size%22%3A499161%2C%22type%22%3A%22application%2Fx-zip-compressed%22%2C%22ext%22%3A%22zip%22%2C%22status%22%3A%22done%22%2C%22taskId%22%3A%22u458bcbec-d647-4328-8036-3d5eb12860f%22%2C%22taskType%22%3A%22upload%22%2C%22id%22%3A%22ua8a5baad%22%2C%22card%22%3A%22file%22%7D)
Next, we will introduce how to export a glTF file with the unlit plugin using Blender software.
1. Import the model
<Image src="https://gw.alipayobjects.com/zos/OasisHub/e5dbfb61-5c0c-4ca5-8c7f-bde353d4c211/1623651809057-138f49cf-6fe7-4f54-8161-c7e157ec85fd-20210614150752343.png" />
2. Modify Shader
The default shader type is BSDF. We need to change the shader type in the surface material properties to **Background**.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/abf1e279-1f78-4d21-8c1f-d58d7f74992c/1623652169374-7f39e5f0-6639-4795-8565-b8f0b09420ed-20210614150804567.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/c8c51e5f-c7c6-44a3-87e2-dc649e13fddb/1623652230768-69cd6f7e-175d-4f9f-9042-b3629d422b8e.png" />
3. Add Baked Texture
Add the baked texture and connect Color and Shader together.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/50c69e7b-c099-4a2d-b546-8a55ff4f9309/1623652264008-7ae4c13c-6430-44b0-995e-2c23c9f117a7-20210614150846797.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/6ed13e19-a9e5-4454-a0d5-ad27b3cabe14/1623652368637-6dda44be-4cde-4f65-a72f-d39b5d3f60ce.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/e9a99c9c-f661-4666-86bc-d8e91030c0f7/1623652380351-501dd929-7f96-4578-b49a-11724a0782a7.png" />
4. Export glTF
If the preview is normal, export the glTF.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/4b6b5f8f-ebd2-46af-85c7-9a26b5f66a2e/1623652403568-450291a8-1a0b-4cf4-8e71-c183a05632b0-20210614150902221.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/1fe38185-399e-4f56-bff4-c39ba4ae3a2a/1623652462007-85b065a3-69fa-4d80-9dfd-834ef66da12a.png" />
Drag the exported glTF file into the editor or [glTF Viewer](https://galacean.antgroup.com/engine/gltf-viewer). If the material type is **UnlitMaterial**, it means that the [KHR_materials_unlit](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) extension has been exported, and Galacean has parsed it into an Unlit material.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/fbb6ba43-f7d7-4757-a1d3-590083d30573/1623652636074-d8bb8437-f885-43fd-8957-8e14ae9fd8c0-20210614150914493.png" />

View File

@@ -1,54 +0,0 @@
---
title: Shader
---
In the [Shader Introduction](/en/docs/graphics/shader/intro/), we learned the basic concepts of shaders. The Galacean engine encapsulates other rendering-related information based on shader programs to form a Shader object. The Shader object, together with the [material](/en/docs/graphics/material/material/), determines the final rendering result of the rendered object.
## Shader
The Shader object contains the following:
- name
The name of the Shader instance. Once created, the Shader object is cached by the engine and can be reused by finding it through `Shader.find()` using `Shader.name` as the index. Therefore, the engine requires that the name attribute of the Shader must be unique within a single engine instance.
- SubShader
A Shader object contains at least one SubShader object.
## SubShader
A shader program may run on different GPU hardware platforms and different rendering pipelines. Therefore, the Shader object specifies different rendering logic for different hardware platforms and rendering pipelines through key-value pairs of tags, which are the SubShader objects.
The SubShader contains the following:
- Tags
Tags are key-value pairs consumed by the rendering pipeline, usually used to specify information such as the hardware platforms and rendering pipelines compatible with the Shader. The current engine's built-in pipeline consumes the following Tags:
| Key | value |
| ------------- | ------------ |
| pipelineStage | Forward |
| pipelineStage | DepthOnly |
| pipelineStage | ShadowCaster |
| pipelineStage | DepthOnly |
Additionally, you can specify the `replacementTag` of the rendering pipeline through [Camera.setReplacementShader](/apis/galacean/#Camera-resetReplacementShader) to achieve the purpose of replacing the `SubShader` with the specified `Tag`.
Tags can be specified through [SubShader.setTag](/apis/galacean/#SubShader-setTag) and [ShaderPass.setTag](/apis/galacean/#ShaderPass-setTag). For details on specifying Tags in ShaderLab, see the [documentation](/en/docs/graphics/shader/shaderLab/syntax/subShader/#tags).
- Passes
A SubShader contains at least one ShaderPass object.
- RenderStates
[RenderState rendering states](/en/docs/graphics/material/composition/#渲染状态) shared by all ShaderPasses under the SubShader.
## ShaderPass
ShaderPass encapsulates the specific shader program and the [rendering state](/en/docs/graphics/material/composition/#渲染状态) when performing the final rendering.
<Callout type="info">
The ShaderPasses under the same SubShader are rendered sequentially according to the array order, with the rendering effects gradually superimposed to form the final rendering result of the Shader in the current frame.
</Callout>

View File

@@ -1,297 +0,0 @@
---
title: Custom Shaders
---
There may be some special rendering requirements in the business, such as water flow effects, which need to be implemented through **custom shaders** (Shader).
## Creating Shaders
The [Shader class](/apis/core/#Shader) encapsulates vertex shaders, fragment shaders, shader precompilation, platform precision, and platform differences. Its creation and use are very convenient, and users only need to focus on the shader algorithm itself without worrying about what precision to use or which version of GLSL to write. Here is a simple demo:
```javascript
import { Material, Shader, Color } from "@galacean/engine";
//-- Shader 代码
const vertexSource = `
uniform mat4 renderer_MVPMat;
attribute vec3 POSITION;
void main() {
gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);
}
`;
const fragmentSource = `
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
// 创建自定义 shader整个 runtime 只需要创建一次)
Shader.create("demo", vertexSource, fragmentSource);
// 创建材质
const material = new Material(engine, Shader.find("demo"));
```
`Shader.create()` is used to add the shader to the engine's cache pool, so it only needs to be created once during the entire runtime. After that, it can be repeatedly used through [Shader.find(name)](/apis/galacean/#Shader-find).
> Note: The engine has already pre-created blinn-phong, pbr, shadow-map, shadow, skybox, framebuffer-picker-color, and trail shaders. Users can directly use these built-in shaders and cannot create them with the same name.
In the above example, because we did not upload the `u_color` variable, the fragment output is still black (the default value of the uniform). Next, we will introduce the built-in shader variables of the engine and how to upload custom variables.
## Built-in Shader Variables
Above, we assigned a shader to the material, and the program can start rendering at this point.
> It should be noted that there are two types of variables in shader code: **per-vertex** `attribute` variables and **per-shader** `uniform` variables. (After GLSL300, they are unified as in variables)
The engine has automatically uploaded some commonly used variables, which users can directly use in the shader code, such as vertex data and MVP data. Below are the variables uploaded by default by the engine.
### Vertex Inputs
| Per-vertex Data | Attribute Name | Data Type |
| :--------------- | :------------- | :-------- |
| Vertex | POSITION | vec3 |
| Normal | NORMAL | vec3 |
| Tangent | TANGENT | vec4 |
| Vertex Color | COLOR_0 | vec4 |
| Bone Index | JOINTS_0 | vec4 |
| Bone Weight | WEIGHTS_0 | vec4 |
| First Texture Coord | TEXCOORD_0 | vec2 |
| Second Texture Coord | TEXCOORD_1 | vec2 |
### Properties
#### Renderer
| Name | Type | Description |
| :----------------- | :--- | ----------------------- |
| renderer_LocalMat | mat4 | Model local coordinate matrix |
| renderer_ModelMat | mat4 | Model world coordinate matrix |
| renderer_MVMat | mat4 | Model view matrix |
| renderer_MVPMat | mat4 | Model view projection matrix |
| renderer_NormalMat | mat4 | Normal matrix |
#### Camera
| Name | Type | Description |
| :----------------------- | :-------- | ---------------------------------------------------------------------- |
| camera_ViewMat | mat4 | View matrix |
| camera_ProjMat | mat4 | Projection matrix |
| camera_VPMat | mat4 | View projection matrix |
| camera_ViewInvMat | mat4 | Inverse view matrix |
| camera_Position | vec3 | Camera position |
| camera_DepthTexture | sampler2D | Depth information texture |
| camera_DepthBufferParams | Vec4 | Camera depth buffer parameters: (x: 1.0 - far / near, y: far / near, z: 0, w: 0) |
| camera_ProjectionParams | Vec4 | Projection matrix parameters: (x: flipProjection ? -1 : 1, y: near, z: far, w: 0) |
#### Time
| Name | Type | Description |
| :---------------- | :--- | :--------------------------------------------------------------- |
| scene_ElapsedTime | vec4 | Total time elapsed since the engine started: (x: t, y: sin(t), z: cos(t), w: 0) |
| scene_DeltaTime | vec4 | Time interval since the last frame: (x: dt, y: 0, z: 0, w: 0) |
#### Fog
| Name | Type | Description |
| :-- | :-- | :-- |
| scene_FogColor | vec4 | Color of the fog |
| scene_FogParams | vec4 | Fog parameters: (x: -1/(end-start), y: end/(end-start), z: density / ln(2), w: density / sqr(ln(2)) |
## Upload Shader Data
> For uploading per-vertex data, please refer to [Mesh Renderer](/en/docs/graphics/mesh/modelMesh), which will not be repeated here.
In addition to built-in variables, we can upload any custom-named variables in the shader. All we need to do is use the correct interface according to the shader data type. All upload interfaces are stored in [ShaderData](/apis/core/#ShaderData), and the shaderData instance objects are stored in the engine's four main classes: [Scene](/apis/core/#Scene), [Camera](/apis/core/#Camera), [Renderer](/apis/core/#Renderer), and [Material](/apis/core/#Material). We just need to call the interfaces on these shaderData to upload variables, and the engine will automatically assemble these data at the underlying level and perform optimizations such as redundancy checks.
<Image src="https://mdn.alipayobjects.com/huamei_jvf0dp/afts/img/A*ijQMQJM_Vy0AAAAAAAAAAAAADleLAQ/original" />
### Benefits of Separating Shader Data
Shader data is stored separately in the engine's four main classes: [Scene](/apis/core/#Scene), [Camera](/apis/core/#Camera), [Renderer](/apis/core/#Renderer), and [Material](/apis/core/#Material). One of the benefits of this approach is that the underlying layer can upload a specific block of uniform data based on the upload timing, improving performance. Additionally, separating material-independent shader data allows for shared materials. For example, two renderers sharing one material can both manipulate the same shader without affecting each other's rendering results because this part of the shader data upload comes from the shaderData of the two renderers.
Example:
```typescript
const renderer1ShaderData = renderer1.shaderData;
const renderer2ShaderData = renderer2.shaderData;
const materialShaderData = material.shaderData;
materialShaderData.setColor("material_color", new Color(1, 0, 0, 1));
renderer1ShaderData.setFloat("u_progross", 0.5);
renderer2ShaderData.setFloat("u_progross", 0.8);
```
### Calling Interfaces
The types of shader data and their respective API calls are as follows:
| Shader Type | ShaderData API |
| :-- | :-- |
| `bool`, `int` | setInt(value: number) |
| `float` | setFloat(value: number) |
| `bvec2`, `ivec2`, `vec2` | setVector2(value: Vector2) |
| `bvec3`, `ivec3`, `vec3` | setVector3(value: Vector3) |
| `bvec4`, `ivec4`, `vec4` | setVector4(value: Vector4) |
| `mat4` | setMatrix(value: Matrix) |
| `float[]`, `vec2[]`, `vec3[]`, `vec4[]`, `mat4[]` | setFloatArray(value: Float32Array) |
| `bool[]`, `int[]`, `bvec2[]`, `bvec3[]`, `bvec4[]`, `ivec2[]`, `ivec3[]`, `ivec4[]` | setIntArray(value: Int32Array) |
| `sampler2D`, `samplerCube` | setTexture(value: Texture) |
| `sampler2D[]`, `samplerCube[]` | setTextureArray(value: Texture[]) |
The code demonstration is as follows:
```glsl
// shader
uniform float u_float;
uniform int u_int;
uniform bool u_bool;
uniform vec2 u_vec2;
uniform vec3 u_vec3;
uniform vec4 u_vec4;
uniform mat4 u_matrix;
uniform int u_intArray[10];
uniform float u_floatArray[10];
uniform sampler2D u_sampler2D;
uniform samplerCube u_samplerCube;
uniform sampler2D u_samplerArray[2];
// GLSL 300:
// in float u_float;
// ...
```
```typescript
// shaderData 可以分别保存在 scene 、camera 、renderer、 material 中。
const shaderData = material.shaderData;
shaderData.setFloat("u_float", 1.5);
shaderData.setInt("u_int", 1);
shaderData.setInt("u_bool", 1);
shaderData.setVector2("u_vec2", new Vector2(1, 1));
shaderData.setVector3("u_vec3", new Vector3(1, 1, 1));
shaderData.setVector4("u_vec4", new Vector4(1, 1, 1, 1));
shaderData.setMatrix("u_matrix", new Matrix());
shaderData.setIntArray("u_intArray", new Int32Array(10));
shaderData.setFloatArray("u_floatArray", new Float32Array(10));
shaderData.setTexture("u_sampler2D", texture2D);
shaderData.setTexture("u_samplerCube", textureCube);
shaderData.setTextureArray("u_samplerArray", [texture2D, textureCube]);
```
> **Note**: For performance considerations, the engine does not currently support struct array uploads or individual element uploads of arrays.
### Macro Switches
In addition to uniform variables, the engine also treats [macro definitions](https://www.wikiwand.com/en/OpenGL_Shading_Language) in shaders as a type of variable. This is because enabling/disabling macro definitions will generate different shader variants, which will also affect the rendering results.
For example, if there are these macro-related operations in the shader:
```glsl
#ifdef DISCARD
discard;
#endif
#ifdef LIGHT_COUNT
uniform vec4 u_color[ LIGHT_COUNT ];
#endif
```
They are also controlled through [ShaderData](/apis/core/#Shader-enableMacro):
```typescript
// 开启宏开关
shaderData.enableMacro("DISCARD");
// 关闭宏开关
shaderData.disableMacro("DISCARD");
// 开启变量宏
shaderData.enableMacro("LIGHT_COUNT", "3");
// 切换变量宏。这里底层会自动 disable 上一个宏,即 “LIGHT_COUNT 3”
shaderData.enableMacro("LIGHT_COUNT", "2");
// 关闭变量宏
shaderData.disableMacro("LIGHT_COUNT");
```
## Encapsulating Custom Materials
This section combines all the content above to provide users with a simple encapsulation example. We hope it will be helpful to you:
```typescript
import { Material, Shader, Color, Texture2D, BlendFactor, RenderQueueType } from "@galacean/engine";
//-- Shader 代码
const vertexSource = `
uniform mat4 renderer_MVPMat;
attribute vec3 POSITION;
attribute vec2 TEXCOORD_0;
varying vec2 v_uv;
void main() {
gl_Position = renderer_MVPMat * vec4(POSITION, 1.0);
v_uv = TEXCOORD_0;
}
`;
const fragmentSource = `
uniform vec4 u_color;
varying vec2 v_uv;
#ifdef TEXTURE
uniform sampler2D u_texture;
#endif
void main() {
vec4 color = u_color;
#ifdef TEXTURE
color *= texture2D(u_texture, v_uv);
#endif
gl_FragColor = color;
}
`;
Shader.create("demo", vertexSource, fragmentSource);
export class CustomMaterial extends Material {
set texture(value: Texture2D) {
if (value) {
this.shaderData.enableMacro("TEXTURE");
this.shaderData.setTexture("u_texture", value);
} else {
this.shaderData.disableMacro("TEXTURE");
}
}
set color(val: Color) {
this.shaderData.setColor("u_color", val);
}
// make it transparent
set transparent() {
const target = this.renderState.blendState.targetBlendState;
const depthState = this.renderState.depthState;
target.enabled = true;
target.sourceColorBlendFactor = target.sourceAlphaBlendFactor = BlendFactor.SourceAlpha;
target.destinationColorBlendFactor = target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
depthState.writeEnabled = false;
this.renderQueueType = RenderQueueType.Transparent;
}
constructor(engine: Engine) {
super(engine, Shader.find("demo"));
}
}
```

View File

@@ -1,24 +0,0 @@
<Image src="https://gw.alipayobjects.com/zos/OasisHub/a3f74864-241e-4cd8-9ad4-733c2a0b2cc2/image-20240206153815596.png" />
## Introduction to Shaders
A shader is a program that runs on the GPU, typically consisting of two "entry functions" known as the Vertex Shader and the Fragment Shader, corresponding to two different stages of the rendering pipeline. Below is a simplified illustration of the engine's rendering process (rendering pipeline), focusing on the shader part.
```mermaid
flowchart LR
A[CPU应用层] -->|准备顶点和其他\n渲染计算相关的数据| B{Vertex Shader}
subgraph Shader / 着色器
B --> |计算顶点在三维空间的真实坐标\n以及其他后续渲染阶段需要的数据| C{Fragment Shader}
end
C -->|基于上一个渲染阶段的计算结果数据\n计算每个顶点的最终像素值| D[帧图像]
```
<figcaption style={{"text-align":"center", color: "#889096","font-size":"12px"}}>Simplified Rendering Pipeline</figcaption>
In this chapter, we will cover the following topics:
|Section|Content|
|:--:|:--:|
|[Shader Object](/en/docs/graphics/shader/class/)|Overview and basic usage of the Shader object in the engine|
|[Built-in Shaders](/en/docs/graphics/shader/builtins/intro/)|Common built-in shaders in the engine|
|[Shader Assets](/en/docs/graphics/shader/assets/)|How to create and modify Shader assets in the editor|
|[ShaderLab](/en/docs/graphics/shader/shaderLab/intro/)|A more convenient way to create Shaders|

View File

@@ -1,364 +0,0 @@
---
title: Shader API【Experimental】
---
<Callout type="warning">
This version is currently experimental and can only be used in the `editor`. If you want to use it in `Pro Code`, you
need to import the `@galacean/engine-shader-shaderlab` package. Please note that the API may change in the next
version, and we will notify you in time.
</Callout>
Similar to functions, classes, and properties in Typescript, Shader code also has its own set of APIs. This article can help you write your own Shader based on these APIs and `ShaderLab` syntax.
## Getting Started
Let's start with the `Unlit template` to briefly introduce our Shader API. First, create an Unlit Shader as shown in the figure below:
<img
src="https://gw.alipayobjects.com/zos/OasisHub/9abd1026-4e4d-4994-b36a-f964375c38cb/image-20240731105324320.png"
style={{ zoom: "50%" }}
/>
The default Unlit template already has built-in skinning calculations and Shadow Pass, so you can see that skeletal animation and shadows are rendered correctly:
<Image src="https://gw.alipayobjects.com/zos/OasisHub/6e7f7d40-e54c-45bc-a915-dfbfb26c2c74/2024-08-01%25252017.01.06.gif" />
The key code is as follows. By calling `UsePass "pbr/Default/ShadowCaster"`, the object can be rendered to the Shadowmap; by using the `getSkinMatrix` API, you can get the bone matrix to animate the object.
```ts showLineNumbers {1,11-15} /getSkinMatrix/
UsePass "pbr/Default/ShadowCaster"
Pass "Example" {
#include "Skin.glsl"
Varyings vert(Attributes attr) {
Varyings v;
vec4 position = vec4(attr.POSITION, 1.0);
// Skin
#ifdef RENDERER_HAS_SKIN
mat4 skinMatrix = getSkinMatrix(attr);
position = skinMatrix * position;
#endif
gl_Position = renderer_MVPMat * position;
v.uv = attr.TEXCOORD_0;
return v;
}
}
```
The Unlit Shader is not affected by lighting by default. We can call the API provided by `Light.glsl` to make the Shader's output affected by lighting:
```ts showLineNumbers {1,4} /getDirectLight/
#include "Light.glsl"
// Demo 演示,我们只简单计算第 1 盏方向光。
DirectLight light = getDirectLight(0);
// 衰减系数,光线越垂直照射的地方越亮
float dotNL = saturate( dot( v.normalWS, -light.direction ) );
baseColor.rgb *= dotNL * light.color;
```
<Image src="https://gw.alipayobjects.com/zos/OasisHub/a552c86f-6a59-4765-89ff-fac3b38aa9d2/2024-08-01%25252017.06.14.gif" />
Of course, in addition, you can also perform vertex color calculations, normal map calculations, [ambient light](/en/docs/graphics/light/ambient) calculations, and other operations, but we do not recommend doing these operations based on the `Unlit template`. The `PBR template` already has these calculations built-in and provides a more comprehensive lighting model, such as anisotropy, Clear Coat, etc., and provides function overload macros for quick expansion.
## PBR Template
We recreate a `PBR Shader template` and bind it to the material ball just now. You can see that the material panel already has built-in basic properties, metallic roughness, anisotropy, normal, emission, shadow occlusion, Clear Coat, and other configurations, and can be affected by direct light and ambient light:
<img
src="https://gw.alipayobjects.com/zos/OasisHub/1bb43cac-ca21-4342-a6ea-a19324eaf12d/image-20240801174338560.png"
style={{ zoom: "50%" }}
/>
<Image src="https://gw.alipayobjects.com/zos/OasisHub/f8f09e89-e14d-481e-a328-eed491f41e79/image-20240801174216595.png" />
<Image src="https://gw.alipayobjects.com/zos/OasisHub/65a7f2ec-ffd5-45cf-9508-8d951b995e3d/2024-08-01%25252017.40.02.gif" />
Next, we refer to the `thin film interference` algorithm to see how to overload the implementation of the lighting model:
1. First, create a `DemoPass.glsl` and import it into the main Shader file just now:
```ts showLineNumbers {7-8}
// PBRShader.gs
SubShader "Default" {
Pass "Forward Pass" {
VertexShader = PBRVertex;
FragmentShader = PBRFragment;
// #include "ForwardPassPBR.glsl"
#include "./DemoPass.glsl"
}
```
2. Modify the lighting model in `DemoPass.glsl`. As a demo, we only demonstrate modifying the direct light part:
```ts showLineNumbers {7-8}
// DemoPass.glsl
#include "Common.glsl"
#include "Fog.glsl"
#include "AttributesPBR.glsl"
#include "VaryingsPBR.glsl"
// #include "LightDirectPBR.glsl"
#include "DemoLight.glsl"
#include "LightIndirectPBR.glsl"
#include "VertexPBR.glsl"
#include "FragmentPBR.glsl"
```
3. Use the `FUNCTION_SPECULAR_LOBE` macro to overload the `direct light specular reflection lighting model`. The algorithm part here is copied from thin-film interference, so you don't need to worry too much about it. After overloading, `LightDirectPBR.glsl` can recognize this function and replace the lighting model implementation. Key functions for both direct and indirect light provide corresponding overload macros, which will be introduced in detail in the API documentation below:
```ts showLineNumbers {2,5,16} /specularLobe_iridescence/
// DemoLight.glsl
#define FUNCTION_SPECULAR_LOBE specularLobe_iridescence
#include "BRDF.glsl"
#include "./IridescenceFunction.glsl"
void specularLobe_iridescence(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 specularColor){
vec3 thin = DirectBDRFIridescence(surfaceData, incidentDirection, brdfData);
vec3 BRDF_Specular = BRDF_Specular_GGX( incidentDirection, surfaceData, surfaceData.normal, brdfData.specularColor, brdfData.roughness);
vec3 factor =mix(BRDF_Specular,thin,material_Iridescence);
specularColor += attenuationIrradiance * factor;
}
#include "LightDirectPBR.glsl"
```
<Image src="https://gw.alipayobjects.com/zos/OasisHub/ad18c98d-d1a5-47fd-b5c8-882908c249a2/2024-08-01%25252018.51.36.gif" />
## General API
The API call method is as follows:
```glsl
#include "Common.glsl"
float f2 = pow2(0.5);
```
### Common
Provides common macros like `PI`, and general methods like `gammaToLinear`, `pow2`, etc. See [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/Common.glsl) for details.
### Fog
Provides depth fogging methods:
```glsl
vec4 fog(vec4 color, vec3 positionVS);
```
### Transform
Provides system variables for model space, view space, world space, camera coordinates, etc. [system variables](/en/docs/graphics/shader/custom/#属性):
```glsl
mat4 renderer_LocalMat;
mat4 renderer_ModelMat;
mat4 camera_ViewMat;
mat4 camera_ProjMat;
mat4 renderer_MVMat;
mat4 renderer_MVPMat;
mat4 renderer_NormalMat;
vec3 camera_Position;
vec3 camera_Forward;
vec4 camera_ProjectionParams;
```
### Light
Provides methods to get [engine lighting](/en/docs/graphics/light/light), including direct light and indirect light:
```glsl
// 直接光
DirectLight getDirectLight(int index);
PointLight getPointLight(int index);
SpotLight getSpotLight(int index);
// 间接光
EnvMapLight scene_EnvMapLight;
#ifdef SCENE_USE_SH
vec3 scene_EnvSH[9];
#endif
#ifdef SCENE_USE_SPECULAR_ENV
samplerCube scene_EnvSpecularSampler;
#endif
```
### Normal
Provides some general methods for normal calculation:
```glsl
// 在切线空间进行法线贴图运算后的法线
vec3 getNormalByNormalTexture(mat3 tbn, sampler2D normalTexture, float normalIntensity, vec2 uv, bool isFrontFacing);
// 利用导数计算切线,针对本身没有切线的模型
mat3 getTBNByDerivatives(vec2 uv, vec3 normal, vec3 position, bool isFrontFacing);
```
### Shadow
Provides shadow-related functions. See [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/Shadow.glsl) for details.
```glsl
// 获取级联阴影所属层级比如级联数量设为4则返回 03
int computeCascadeIndex(vec3 positionWS);
// 获取 shadowmap 中的坐标
vec3 getShadowCoord(vec3 positionWS);
// 获取阴影强度,包含采样方式、阴影衰减
float sampleShadowMap(vec3 positionWS, vec3 shadowCoord);
```
### Skin
Provides bone calculation methods:
```glsl
mat4 getSkinMatrix(Attributes attributes);
```
### BlendShape
Provides BS calculation methods:
```glsl
void calculateBlendShape(Attributes attributes, inout vec4 position, inout vec3 normal, inout vec4 tangent);
```
## PBR API
In addition to the general API, PBR also encapsulates a series of APIs such as the BRDF lighting model. These are some core links of `ForwardPassPBR`. When users extend other materials, such as SSS, thin-film interference, etc., they may also need these functions and can try to `#include` reuse these APIs.
<Image src="https://gw.alipayobjects.com/zos/OasisHub/dd9af974-f4d2-4ef5-845a-732f39492bc0/yuque_diagram.jpg" />
### AttributesPBR
Encapsulates all the Attribute variables needed for PBR. See [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/AttributesPBR.glsl) for details.
### VaryingsPBR
Encapsulates all the Varyings variables needed for PBR. See [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/VaryingsPBR.glsl) for details.
### LightDirectPBR
````
Encapsulates direct light calculations based on the BRDF lighting model. For more details, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/LightDirectPBR.glsl).
Generally, you can call it directly:
```glsl
// Evaluate direct lighting
evaluateDirectRadiance(varyings, surfaceData, brdfData, shadowAttenuation, color.rgb);
````
The following function overload macros are provided to override key calculations of the lighting model:
```glsl
#define FUNCTION_SURFACE_SHADING surfaceShading
#define FUNCTION_DIFFUSE_LOBE diffuseLobe
#define FUNCTION_SPECULAR_LOBE specularLobe
#define FUNCTION_CLEAR_COAT_LOBE clearCoatLobe
#define FUNCTION_SHEEN_LOBE sheenLobe
void surfaceShading(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 lightColor, inout vec3 totalDiffuseColor, inout vec3 totalSpecularColor);
void diffuseLobe(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 attenuationIrradiance, inout vec3 diffuseColor);
void specularLobe(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 specularColor);
float clearCoatLobe(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 color, inout vec3 specularColor);
void sheenLobe(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, vec3 incidentDirection, vec3 attenuationIrradiance, inout vec3 diffuseColor, inout vec3 specularColor);
```
<Callout type="info">Refer to the PBR template extension above for the overload method.</Callout>
### LightInDirectPBR
Encapsulates [ambient light](/en/docs/graphics/light/ambient) calculations based on the BRDF lighting model. For more details, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/LightIndirectPBR.glsl).
Generally, you can call it directly:
```glsl
// IBL
evaluateIBL(varyings, surfaceData, brdfData, color.rgb);
```
The following function overload macros are provided to override key calculations of the lighting model:
```glsl
#define FUNCTION_DIFFUSE_IBL evaluateDiffuseIBL
#define FUNCTION_SPECULAR_IBL evaluateSpecularIBL
#define FUNCTION_CLEAR_COAT_IBL evaluateClearCoatIBL
#define FUNCTION_SHEEN_IBL evaluateSheenIBL
void evaluateDiffuseIBL(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, inout vec3 diffuseColor);
void evaluateSpecularIBL(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, float radianceAttenuation, inout vec3 specularColor);
float evaluateClearCoatIBL(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, inout vec3 specularColor);
void evaluateSheenIBL(Varyings varyings, SurfaceData surfaceData, BRDFData brdfData, float radianceAttenuation, inout vec3 diffuseColor, inout vec3 specularColor);
```
### VertexPBR
Some methods required by the PBR vertex shader, such as obtaining UV coordinates after TilingOffset, obtaining world coordinates, normals, tangents after skeletal and BS operations, etc. For more details, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/VertexPBR.glsl).
```glsl showLineNumbers {2, 4}
Varyings varyings;
varyings.uv = getUV0(attributes);
VertexInputs vertexInputs = getVertexInputs(attributes);
// positionWS
varyings.positionWS = vertexInputs.positionWS;
// normalWS、tangentWS、bitangentWS
#ifdef RENDERER_HAS_NORMAL
varyings.normalWS = vertexInputs.normalWS;
#ifdef RENDERER_HAS_TANGENT
varyings.tangentWS = vertexInputs.tangentWS;
varyings.bitangentWS = vertexInputs.bitangentWS;
#endif
#endif
gl_Position = renderer_MVPMat * vertexInputs.positionOS;
```
### BRDF
The key file of the PBR lighting model, encapsulating general calculation functions related to BRDF, as well as the `SurfaceData` structure and `BRDFData` structure used for subsequent lighting model calculations. For more details, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/BRDF.glsl).
### BTDF
Provides transmission and refraction related functions, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/BTDF.glsl)。
### FragmentPBR
Contains a large number of variables passed from the CPU, such as metallic, roughness, maps, etc., and initializes the `SurfaceData` structure through `getSurfaceData`. For more details, see [source code](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/FragmentPBR.glsl).
```glsl showLineNumbers
BRDFData brdfData;
// 初始化 SurfaceData 结构体
SurfaceData surfaceData = getSurfaceData(varyings, aoUV, gl_FrontFacing);
// 可以在这加工 SurfaceData 里面的数据
initBRDFData(surfaceData, brdfData);
```
### Finally
In addition to the functionality and calling methods of key APIs, you can refer to the [ForwardPassPBR](https://github.com/galacean/engine/blob/main/packages/shader-shaderlab/src/shaders/shadingPBR/ForwardPassPBR.glsl) on the official website for the organization of the entire file.

View File

@@ -1,6 +0,0 @@
{
"intro": "Introduction",
"create": "Create",
"syntax": "Syntax",
"usage": "Usage"
}

View File

@@ -1,35 +0,0 @@
---
title: Creation
---
## Create in the Editor
You can add 3 types of ShaderLab templates in the editor: `Unlit`, `PBR`, and Shader Fragments.
<Image
src="https://mdn.alipayobjects.com/huamei_rmtxpm/afts/img/A*namMTLNnCPYAAAAAAAAAAAAADv-7AQ/original"
style={{ width: "50%" }}
/>
Among them, **`Unlit`** and **`PBR`** are shader templates written using ShaderLab syntax, while **Shader Fragments** are for convenient code segment reuse. In ShaderLab, you can use the `include` macro to reference code segments, which will be automatically expanded and replaced during subsequent compilation. For usage details, see the syntax standard module.
## Create in Script
Currently, `ShaderLab` is not yet integrated into the engine core package. You need to pass in a newly created `ShaderLab` object during engine initialization; otherwise, the engine cannot parse and use shaders written in `ShaderLab` syntax.
1. `ShaderLab` Initialization
```ts
import { ShaderLab } from "@galacean/engine-shaderlab";
const shaderLab = new ShaderLab();
// 使用ShaderLab初始化Engine
const engine = await WebGLEngine.create({ canvas: "canvas", shaderLab });
```
2. Create Shader
```glsl
// Directly create Shader using ShaderLab
const shader = Shader.create(galaceanShaderCode);
```

View File

@@ -1,14 +0,0 @@
---
title: Introduction
---
> In the [Custom Shader](/en/docs/graphics/shader/custom/) section, we learned how to create custom Shaders using the native WebGL GLSL language. In this section, we will introduce another way to create Shaders --- ShaderLab.
`ShaderLab` is a Shader packaging language tailored for the Galacean engine. It allows developers to write custom Shaders using the familiar [GLSL](https://www.khronos.org/files/opengles_shading_language.pdf) syntax while providing additional high-level abstractions and management features to enhance development efficiency. In the [Material Composition](/en/docs/graphics/material/composition/) section, we mentioned that before the introduction of ShaderLab, setting various [render states](/en/docs/graphics/material/composition/#渲染状态) required developers to manually call APIs. With ShaderLab, developers can directly set and specify render states in the "Shader" file. Additionally, they can define material rendering parameters bound to the Shader, which are mapped to the Inspector panel in the editor, making it easier for developers to adjust rendering effects in real-time.
Although ShaderLab introduces convenience for writing shaders, it does not replace GLSL but is compatible with it. Developers can write native GLSL code blocks within the ShaderLab framework, enjoying the advantages of both. The ShaderLab usage process is as follows:
```mermaid
flowchart LR
A[Create Shader] --> B[Edit shaderlab] --> C[Debug shaderlab]
```

View File

@@ -1,8 +0,0 @@
{
"intro": "Introduction",
"shader": "Shader",
"editor": "Editor",
"subShader": "SubShader",
"pass": "Pass",
"macro": "Macro"
}

View File

@@ -1,256 +0,0 @@
import { Image } from "@/mdx";
---
# Editor
```glsl
Editor {
Properties {
material_BaseColor("Offset unit scale", Color) = (1,1,1,1);
...
Header("Emissive")
{
material_EmissiveColor("Emissive color", Color) = (1,1,1,1);
...
}
...
}
...
Macros {
[On] UV_OFFSET("UV Offset", Range(1,100)) = 10;
...
Header("") {
SOME_MACRO("label", Int) = 1;
}
}
...
// Specify the path of bound UIScript.
UIScript "./shaderScript.ts";
}
```
## Properties
It can be used to define properties bound to the Shader's custom material, allowing developers to adjust the defined properties through the custom material Inspector panel in the editor.
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*1mjVR5GXXOkAAAAAAAAAAAAADteEAQ/fmt.webp"
figcaption="Material Inspector"
width="200px"
/>
### Property Definition
```glsl
/**
* @language zh
* Comments description
*/
/**
* @language en
* 注释描述
*/
propertyName("Description", EditType) = [DefaultValue];
```
<Callout type="info">
1. You can use the `Header` directive to organize related properties, and the corresponding Inspector will have the appropriate hierarchical categorization.
```
Header("Emissive") {
material_EmissiveColor("Emissive color", Color) = (1,1,1,1);
...
}
```
2. Annotate Inspector Hover tooltip content through comments, supporting multilingual specification using the `@language` directive.
</Callout>
The currently supported list of EditTypes is as follows::
| EditType | Example |
| :-: | :-- |
| Bool | propertyName("Property Description", Boolean) = true; |
| Int | propertyName("Property Description", Int) = 1; <br/>propertyName("Property Description", Range(0,8)) = 1 <br/> propertyName("Property Description", Enum(Item1: 1, Item2: 2, Item3: 3)) = 1 // Enumeration |
| Float | propertyName("Property Description", FLoat) = 0.5; <br/>propertyName("Property Description", Range(0.0, 1.0)) = 0.5; <br/> propertyName("Property Description", Enum(Item1: 1.0, Item2: 2.0, Item3: 3.0)) = 1.0; // Enumeration |
| Texture2D | propertyName("Property Description", Texture2D); |
| TextureCube | propertyName("Property Description", TextureCube); |
| Color | propertyName("Property Description", Color) = (0.25, 0.5, 0.5, 1); |
| Vector2 | propertyName("Property Description", Vector2) = (0.25, 0.5); |
| Vector3 | propertyName("Property Description", Vector3) = (0.25, 0.5, 0.5); |
| Vector4 | propertyName("Property Description", Vector4) = (0.25, 0.5, 0.5, 1.0); |
#### Enumeration
```glsl
propertyName("Property Description", Enum(Item1: 1, Item2: 2, Item3: 3)) = 1;
```
<Callout typ="warning">
Currently, only Int and Float types support enumeration, and type mixing is not supported. For example, the following
enumeration mixes Float and Int, and will not be correctly parsed. ```glsl propertyName("Property Description",
Enum("Item1":1, "Item2":2.0, "Item3": 3)) = 2.0; ```
</Callout>
## Macros
It is used to reflect macros utilized in the Shader to the Inspector, allowing for flexible adjustments of the macros on which the Shader depends within the editor.
```
[On/Off]macroName("MacroLabel", EditType) = [DefaultValue];
```
Specify the default state of a macro using the [On/Off] directive. The types of macros currently supported by the editor are as follows:
| Type | Example |
| :-----: | :-------------------------------------------------------------------------------------------------------- |
| | macroName("Macro Description"); |
| Bool | macroName("Macro Description", Boolean) = true; |
| Int | macroName("Macro Description", Int) = 1; <br/> macroName("Macro Description", Range(0,8)) = 1; |
| Float | macroName("Macro Description", FLoat) = 0.5; <br/> macroName("Macro Description", Range(0.0, 1.0)) = 0.5; |
| Color | macroName("Macro Description", Color) = (0.25, 0.5, 0.5, 1); |
| Vector2 | macroName("Macro Description", Vector2) = (0.25, 0.5); |
| Vector3 | macroName("Macro Description", Vector3) = (0.25, 0.5, 0.5); |
| Vector4 | macroName("Macro Description", Vector4) = (0.25, 0.5, 0.5, 1.0); |
## UIScript
While developers adjust custom material properties using the editor, they can also specify data change callback behavior through `UIScript`.
- Bind `UIScript` in ShaderLab:
```
Editor {
...
UIScript "/path/to/script";
...
}
```
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*t4LFQ4KEL6kAAAAAAAAAAAAADteEAQ/fmt.webp"
width="70%"
/>
The bound UIScript script path supports both relative and absolute paths. Taking the project root directory in the above
image as an example, the absolute path is `/PBRScript1.ts`, and the relative path is `./PBRScript1.ts`.
### UIScript API
The editor exposes relevant APIs through the built-in `ShaderUIScript` class.
```ts
import { Color, Material, Texture, Vector2, Vector3, Vector4 } from "@galacean/engine";
type ShaderPropertyValue = number | Vector2 | Vector3 | Vector4 | Color | Texture;
type ShaderMacroValue = number | Vector2 | Vector3 | Vector4 | Color;
/**
* Script for extending `Shader` UI logic.
*/
export abstract class ShaderUIScript {
/** @internal */
_propertyCallBacks: Map<string, (material: Material, value: ShaderPropertyValue) => void> = new Map();
/** @internal */
_macroCallBacks: Map<string, (material: Material, defined: boolean, value: ShaderMacroValue) => void> = new Map();
/**
* The method is called when then shader is switched.
* @param material - The material which the shader is bound to
*/
onMaterialShaderSwitched(material: Material): void {}
/**
* Register property change callback.
* @parma propertyName - Property name
* @parma onChanged - Fired on property changed
*/
protected onPropertyChanged(
propertyName: string,
onChanged: (material: Material, value: ShaderPropertyValue) => void
): void {
this._propertyCallBacks.set(propertyName, onChanged);
}
/**
* Register macro change callback.
* @parma macroName - Macro name
* @parma onChanged - Fired on macro changed
*/
protected onMacroChanged(
macroName: string,
onChanged: (material: Material, defined: boolean, value: ShaderMacroValue) => void
): void {
this._macroCallBacks.set(macroName, onChanged);
}
}
```
### Edit UIScript
1. Create UIScript in Editor
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*Qh4UTZgaY7MAAAAAAAAAAAAADteEAQ/fmt.webp"
width="60%"
figcaption="create UIScript"
/>
2. Specify property change callbacks by inheriting from the `ShaderUIScript` class.
```ts
import { Material, RenderQueueType, Vector3, BlendFactor, RenderFace, CullMode, BlendMode } from "@galacean/engine";
export default class extends ShaderUIScript {
constructor() {
super();
......
// Register change callbacks in constructor.
this.onPropertyChanged("material_NormalTexture", (material: Material, value) => {
const shaderData = material.shaderData;
if (value) {
shaderData.enableMacro("MATERIAL_HAS_NORMALTEXTURE");
} else {
shaderData.disableMacro("MATERIAL_HAS_NORMALTEXTURE");
}
})
......
}
// Specify callback on shader switch.
override onMaterialShaderSwitched(material: Material) {
const shaderData = material.shaderData;
shaderData.disableMacro("MATERIAL_OMIT_NORMAL");
shaderData.enableMacro("MATERIAL_NEED_WORLD_POS");
shaderData.enableMacro("MATERIAL_NEED_TILING_OFFSET");
// default value
const anisotropyInfo = shaderData.getVector3("material_AnisotropyInfo");
if (!anisotropyInfo) {
shaderData.setVector3("material_AnisotropyInfo", new Vector3(1, 0, 0));
} else {
shaderData.setFloat("anisotropy", anisotropyInfo.z);
const PI2 = Math.PI * 2;
const rotationRad = (Math.atan2(anisotropyInfo.y, anisotropyInfo.x) + PI2 ) % PI2;
shaderData.setFloat("anisotropyRotation", rotationRad * (180 / Math.PI))
}
}
}
```
<Callout info="warning">
Note that the current version of the ShaderLab material properties module only defines the Inspector UI panel for the
material bound to the Shader in the editor. It does not declare the corresponding global variables in the ShaderPass
for you. If the ShaderPass code references this variable, you must explicitly declare it in the Global Variables
module.
</Callout>

View File

@@ -1,37 +0,0 @@
---
title: ShaderLab Syntax Standard
---
## Editing Shaders in the Editor
Double-click the shader asset we created in the previous step to jump to the code editing page.
> A future version will release the Galacean VSCode plugin, which will provide syntax checking, auto-completion, and code synchronization features for `ShaderLab`. Stay tuned.
<Image
src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*c4yyRboqBSwAAAAAAAAAAAAADteEAQ/fmt.webp"
style={{ zoom: "50%" }}
/>
## Syntax Standard
The `ShaderLab` syntax framework is as follows:
```glsl
Shader "ShaderName" {
...
Editor {
...
}
SubShader "SubShaderName" {
...
Pass "PassName" {
...
}
...
}
...
}
```
It mainly includes [Shader](/en/docs/graphics/shader/shaderLab/syntax/shader/), [SubShader](/en/docs/graphics/shader/shaderLab/syntax/subShader/), and [ShaderPass](/en/docs/graphics/shader/shaderLab/syntax/pass/) modules.

View File

@@ -1,45 +0,0 @@
---
title: Macros
---
ShaderLab supports some macros and macro operators from the standard GLSL syntax:
- `#define`
- `#undef`
- `#if`
- `#ifdef`
- `#ifndef`
- `#else`
- `#elif`
- `#endif`
- `defined`
and the additionally introduced `#include` macro.
<Callout type="warning">
ShaderLab macros are expanded during the preprocessor stage, so macros cannot affect ShaderLab structure parsing. Keywords such as `Shader`, `SubShader`, `Pass`, `EditorProperties`, and `EditorMacros` cannot be included within branch macros like `#ifdef`.
</Callout>
## include Macro
To facilitate code reuse, the `include` macro can be used in ShaderLab to reference code segments, which will be automatically expanded and replaced during subsequent compilation.
```glsl
#include "{includeKey}"
```
To enable code segments to be referenced via the `include` macro, we have two ways to declare code segments:
1. Create Shader / Shader Fragment in the editor
The `includeKey` for the created code segment is the file path of the file in the project, such as `/Root/Effect.glsl`.
2. Explicitly register code segments in the script
```ts
import { ShaderFactory } from '@galacean/engine';
const commonSource = `// shader chunk`;
ShaderFactory.registerInclude('includeKey', commonSource);
```
Shader file inclusion supports relative path references. All relative paths are converted based on the main Shader file path. For example, if the Shader file path is `/root/hair/shader.gs` and the included code segment path is `/root/hair/common.glsl`, the relative path for inclusion would be `#include "./common.glsl"`.

View File

@@ -1,129 +0,0 @@
---
title: Pass
---
```glsl
Pass "PassName" {
Tag {PipelineStage = "ShadowCaster"}
...
// Glbals
...
// Render pipeline and render state settings
// Specify the entry function of shader
VertexShader = vert;
// Specify render queue
RenderQueueType = Transparent;
}
```
`Pass` is the basic element of a `Shader` object. A simple shader object may contain only one `Pass`, but more complex shaders can contain multiple `Pass`es. It defines the operations performed at specific stages of the rendering pipeline, such as the shader programs running on the GPU, rendering states, and settings related to the rendering pipeline.
## Rendering State
It can be specified in the following two ways:
1. Explicit assignment
```
BlendState = blendState;
```
2. Declaration in the global variable domain of Pass
```
BlendState {
Rendering state property = Property value;
}
```
## Specifying uniform Variables
Directly declare them as global variables
```glsl
mediump vec4 u_color;
float material_AlphaCutoff;
mat4 renderer_ModelMat;
vec3 u_lightDir;
```
## Declaring varying Variables
Specify by defining the output [structure](/en/docs/graphics/shader/shaderLab/syntax/shader/#structs-functions) of the vertex shader and the input structure of the fragment shader
```glsl
struct v2f {
vec3 color;
};
v2f vert(a2v o) {
...
}
void frag(v2f i) {
...
}
```
## Specifying Vertex and Fragment Shaders
Explicitly specify the shader entry functions using `VertexShader` and `FragmentShader`
```
VertexShader = vert;
FragmentShader = frag;
```
## Setting the Render Queue
Specify using the `RenderQueueType` directive, which is equivalent to the engine API.
```
RenderQueueType = Transparent;
```
<Callout type="info">
In addition to setting the render state and render queue in ShaderLab, developers can also configure these settings through the material API, such as:
```ts
// Render queue setting
material.renderQueueType = RenderQueueType.Opaque;
// Render state setting const renderState = material.renderState.depthState; depthState.writeEnabled = false;
```
When render states and render queues are declared in ShaderLab, the corresponding settings in the material will be ignored."
</Callout>
```
## MRT(Multiple Render Targets)
ShaderLab is compatible with both GLSL 100 and GLSL 300 syntax, allowing you to specify MRT using either syntax.
1. Specify MRT using `gl_FragData[i]`.
```glsl
void main(v2f input) {
gl_FragData[0] = vec4(1.,0.,0.,1.); // render target 0
gl_FragData[1] = vec4(1.,0.,0.,1.); // render target 1
}
```
2. Specify by returning a struct from the entry function
```glsl
struct mrt {
layout(location = 0) vec4 fragColor0; // render target 0
layout(location = 1) vec4 fragColor1; // render target 1
}
mrt main(v2f input) {
mrt output;
output.fragColor0 = vec4(1.,0.,0.,1.);
output.fragColor1 = vec4(1.,0.,0.,1.);
return output;
}
```

View File

@@ -1,132 +0,0 @@
---
title: Shader
---
```glsl
Shader "ShaderName" {
...
// Global variables
...
SubShader "SubShaderName" {
...
}
...
}
```
In ShaderLab, `Shader` is a collection of shader programs and other engine rendering settings in the traditional rendering pipeline. It allows defining multiple shader programs within the same `Shader` object and instructs Galacean on how to choose and use them during rendering. The `Shader` object has a nested structure, corresponding to the engine's encapsulated [Shader](/apis/galacean/#Shader), [SubShader](/apis/galacean/#SubShader), and [ShaderPass](/apis/galacean/#ShaderPass) objects.
## Material Property Definition
In ShaderLab, developers can customize the Inspector property panel for custom materials using this Shader through the [`Editor`](./editor/) directive.
## Global Variables
You can declare 4 types of global variables in ShaderLab: RenderState, Structs, Functions, and Single Variables.
### RenderState
Includes BlendState, DepthState, StencilState, RasterState
- BlendState
```glsl
BlendState {
Enabled[n]: bool;
ColorBlendOperation[n]: BlendOperation;
AlphaBlendOperation[n]: BlendOperation;
SourceColorBlendFactor[n]: BlendFactor;
SourceAlphaBlendFactor[n]: BlendFactor;
DestinationColorBlendFactor[n]: BlendFactor;
DestinationAlphaBlendFactor[n]: BlendFactor;
ColorWriteMask[n]: float // 0xffffffff
BlendColor: vec4;
AlphaToCoverage: bool;
}
```
[n] can be omitted. When using MRT, [n] specifies a particular MRT render state. Omitting it sets all MRT states. BlendOperation and BlendFactor enums are the same as the engine API.
- DepthState
```glsl
DepthState {
Enabled: bool;
WriteEnabled: bool;
CompareFunction: CompareFunction;
}
```
CompareFunction enums are the same as the engine API.
- StencilState
```glsl
StencilState {
Enabled: bool;
ReferenceValue: int;
Mask: float; // 0xffffffff
WriteMask: float; // 0xffffffff
CompareFunctionFront: CompareFunction;
CompareFunctionBack: CompareFunction;
PassOperationFront: StencilOperation;
PassOperationBack: StencilOperation;
FailOperationFront: StencilOperation;
FailOperationBack: StencilOperation;
ZFailOperationFront: StencilOperation;
ZFailOperationBack: StencilOperation;
}
```
CompareFunction and StencilOperation enums are the same as the engine API.
- RasterState
```glsl
RasterState {
CullMode: CullMode;
DepthBias: float;
SlopeScaledDepthBias: float;
}
```
CullMode enums are the same as the engine API.
Example of setting `BlendState` in `ShaderLab`:
```glsl
Shader "Demo" {
...
BlendState customBlendState
{
Enabled = true;
// Constant variable assignment
SourceColorBlendFactor = BlendFactor.SourceColor;
// Variable assignment
DestinationColorBlendFactor = material_DstBlend;
}
...
Pass "0" {
...
BlendState = customBlendState;
...
}
}
```
The above example shows two ways of assigning values to BlendState properties: _constant assignment_ and _variable assignment_:
- Constant assignment means the right side of the assignment statement is a specified engine enum variable, e.g., BlendFactor.SourceColor.
- Variable assignment means the right side of the assignment statement is any variable name. The specific value of the variable is specified by the user at runtime through the ShaderData.setInt("material_DstBlend", BlendFactor.SourceColor) API.
### Structs, Functions
Same as the syntax in GLSL.
### Single Variables
```glsl
[lowp/mediump/highp] variableType variableName;
```
Similar to other programming languages, global variables in ShaderLab also have scope and name overriding principles. In simple terms, the scope of global variables in ShaderLab is limited to the SubShader or Pass module in which they are declared. The name overriding principle means that if there are global variables with the same name within a Pass, the global variables within the Pass will override the global variables with the same name in the SubShader.

View File

@@ -1,37 +0,0 @@
---
title: SubShader
---
```glsl
SubShader "SubShaderName" {
...
// 全局变量区:变量声明,结构体声明,渲染状态声明
...
Tags {ReplaceTag = "opaque"}
UsePass "ShaderName/SubShaderName/PassName"
Pass "PassName" {
...
}
}
```
## Tags
In the [Shader Object](/en/docs/graphics/shader/class/) section, we learned the basic concepts and uses of Tags. In ShaderLab, you can directly declare and specify them using the `Tags` directive, without needing to manually specify them using the `SubShader.setTag` API method.
## UsePass
If a `SubShader` contains multiple `Pass` objects, you can reuse other `Pass` objects using the `UsePass` directive, such as the engine's built-in PBR Pass: `UsePass "pbr/Default/Forward"`
| Built-in Shader | Pass Path |
| :-----------------: | :-----------------------------: |
| PBR | pbr/Default/Forward |
| Unlit | unlit/Default/Forward |
| Skybox | skybox/Default/Forward |
| Particle-shader | particle-shader/Default/Forward |
| SpriteMask | SpriteMask/Default/Forward |
| Sprite | Sprite/Default/Forward |

View File

@@ -1,14 +0,0 @@
---
title: "Usage"
---
With custom shader assets written using `ShaderLab`, we can implement user-defined materials by binding the shader to newly created materials.
<Image src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*tVDOTq0ms2gAAAAAAAAAAAAADteEAQ/original" style={{zoom: "50%"}} />
- `ShaderLab` Reflecting Material Properties
If we write the `material property definition` module in `ShaderLab`, the properties defined in the module will be exposed in the Inspector panel of the material asset bound to the Shader.
<Image src="https://mdn.alipayobjects.com/huamei_aftkdx/afts/img/A*38UISKqK2WUAAAAAAAAAAAAADteEAQ/original" style={{zoom: "50%"}} />

View File

@@ -23,4 +23,4 @@ title: Blinn Phong
| [shininess](/apis/core/#BlinnPhongMaterial-shininess) | 镜面反射系数。值越大镜面反射效果越聚拢。 |
| [tilingOffset](/apis/core/#BlinnPhongMaterial-tilingOffset) | 纹理坐标的缩放与偏移。是一个 Vector4 数据,分别控制纹理坐标在 uv 方向上的缩放和偏移,参考 [案例](/embed/tiling-offset) |
如果需要通过脚本使用材质,可以前往[材质的使用教程](/docs/graphics/material/examples/create/#3-脚本方式)。
如果需要通过脚本使用材质,可以前往[材质的使用教程](/docs/graphics/material/examples/create/#4-脚本方式)。