This page has been translated automatically.
Видеоуроки
Interface
Essentials
Advanced
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Professional (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Landscape Tool
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World Nodes
Звуковые объекты
Объекты поиска пути
Players
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
Плагины
Форматы файлов
Materials and Shaders
Rebuilding the Engine Tools
GUI
Двойная точность координат
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Сэмплы материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Tutorials
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Создание пользовательского шейдера для постобработки

UNIGINE engine allows you to create your own post-effects by writing custom shaders. To write post-effect shaders, you should use the Scriptable Materials workflow: create the material, write the necessary shaders, and apply it globally or per-camera. Движок Unigine позволяет создавать собственные пост-эффекты, написав собственные шейдеры. Для написания шейдеров постэффектов следует использовать тот же рабочий процесс, что и для этапов отложенного и прямого рендеринга: создать материал, написать шейдеры вершин и фрагментов.

This tutorial explains how to create a post-effect grayscale material, write the shader for it, add a parameter to the material to be able to specify the value from the UnigineEditor. В этом руководстве объясняется, как создать материал постэффекта, написать для него шейдеры (как вершину, так и фрагмент), добавить параметр к материалу, чтобы можно было указать значение из UnigineEditor.

See AlsoСмотрите также#

Create a MaterialСоздаем материал#

As in all other shaders tutorials, you should create the material first. Let's add a new base material to your project.Write the Expression callback in UNIGINE Script which is called after the Post Materials stage (RENDER_CALLBACK_END_POST_MATERIALS) of the render sequence to perform the custom grayscale render pass. Как и во всех других уроках по шейдерам, вы должны сначала создать материал. Давайте добавим в ваш проект новый базовый материал .

To create post-effect material, you should specify the custom pass for shaders and textures. Чтобы создать материал постэффекта, вы должны указать проход пост-обработки для шейдеров и текстур.

The material will have the following structure: Материал будет иметь следующую структуру:

Source Code (ULON) greyscale.basemat
BaseMaterial <preview_hidden=true var_prefix=var texture_prefix=tex>
{
	
	Texture color <source=procedural>
	Texture dirt = "core/textures/water_global/foam_d.dds" <anisotropy=true>

	
	Slider grayscale_power = 0.5 <min=0.0 max=1.0 max_expand=true>
	Slider dirt_power = 0.5 <min=-1.0 max=1.0 max_expand=true>

	/* ... */
	// more code below
}

The key features of this post material are: Ключевые особенности этого пост-материала:

  • Added the shader and textures for post pass. Добавлены шейдеры и текстуры для прохода post.
  • Added the shared grayscale_power and dirt_power parameters. Добавлены общие параметры grayscale_power и dirt_power.

Save the new material as grayscale.basemat file to the data folder.Save the material file and let's proceed to UnigineEditor. Сохраните новый материал как файл custom_post.basemat в папку data.

Создаем вершинный шейдер#

  1. Напишите код шейдера в текстовом редакторе:
    Source Code (ULON) greyscale.basemat
    /* ... */
    
    // define the custom render pass
    Pass my_pass
    {
    	Fragment = 
    	#{
    		// Include the UUSL fragment shader header
    		#include <core/materials/shaders/api/common.h>
    		
    		MAIN_FRAG_BEGIN(FRAGMENT_IN)
    			
    			// Get the UV
    			float2 uv = IN_DATA(0);
    			
    			// Get the scene color
    			float4 scene_color = TEXTURE_BIAS_ZERO(tex_color, uv);
    			
    			// Get the dirt color
    			float4 dirt_color = TEXTURE_BIAS_ZERO(tex_dirt, uv);
    			
    			// Calculate the grayscale
    			float3 gray_scene_color = toFloat3(rgbToLuma(scene_color.rgb));
    			scene_color.rgb = lerp(scene_color.rgb, gray_scene_color, var_grayscale_power);
    			
    			// add some dirt and calculate the final color
    			OUT_COLOR = scene_color + dirt_color * var_dirt_power;
    			
    		MAIN_FRAG_END
    
    		// end
    	#}
    }
    
    /* ... */
    // more code below
    Внимание
    Вам следует добавить новую строку (нажмите Enter) после закрытия инструкции (после командыMAIN_END).
  2. Сохраните файл шейдера как post.vert в папке data/shaders/vertex.

Код вершинного шейдера прост, так как нам не нужно работать с геометрией.

Примечание
Используйте команду materials_reload для перезагрузки шейдеров во время работы движка.

Create Fragment ShaderСоздаем фрагментный шейдер#

This section contains the sample code for the fragment shader (also known as pixel shader). В этом разделе содержится инструкция по созданию фрагментного шейдера (также известного как пиксельный шейдер ).

To create the fragment shader for the custom pass, add the following ULON node to the material: Чтобы создать фрагментный шейдер для прохода постобработки, выполните следующие действия:

  1. Откройте простой текстовый редактор и напишите следующее:
    Source code (UUSL)
    // Include the UUSL fragment shader header
    #include <core/shaders/common/fragment.h>
    
    // Define the texture of the scene
    INIT_TEXTURE(0,TEX_SCENE)
    INIT_TEXTURE(1,TEX_DIRT)
    
    // Input values
    STRUCT(FRAGMENT_IN)
    	INIT_POSITION		// Projected position
    	INIT_IN(float2,0)	// Texcoords
    END
    
    // Define the grayscale_power parameter
    CBUFFER(parameters)
    	UNIFORM float grayscale_power;
    	UNIFORM float dirt_power;
    END
    
    MAIN_BEGIN(FRAGMENT_OUT,FRAGMENT_IN)
    	
    	// Get the UV
    	float2 uv = IN_DATA(0);
    	
    	// Get the scene color
    	float4 scene_color = TEXTURE_BIAS_ZERO(TEX_SCENE,uv);
    	
    	// Get the dirt color
    	float4 dirt_color = TEXTURE_BIAS_ZERO(TEX_DIRT,uv);
    	
    	// Calculate the grayscale
    	float3 gray_scene_color = dot(float3(0.3f, 0.59f, 0.11f), scene_color.rgb);
    	scene_color.rgb = lerp(scene_color.rgb,gray_scene_color,grayscale_power);
    
    	// add some dirt
    	OUT_COLOR = scene_color+dirt_color*dirt_power;
    	
    MAIN_END
    
    // end
    Внимание
    You should add a new line (press Enter) after closing the instruction (after MAIN_END command). Вам следует добавить новую строку (нажмите Enter) после закрытия инструкции (после командыMAIN_END).
  2. Сохраните файл шейдера как post.frag в папке data/shaders/fragment.

Well, let's clarify what is under the hood of this fragment shader: Что ж, давайте проясним, что скрывается за этим фрагментным шейдером:

  • We get the texture which was specified in the post-effect material. Мы получаем текстуру, которая была указана в материале пост-эффекта.
  • We convert the color of the scene to grayscale. Применяя стандартное уравнение градаций серого, мы меняем цвет сцены.
  • By using lerp function (which performs a linear interpolation), we add the custom grayscale_power parameter to adjust the grayscale power. Используя функцию lerp (которая выполняет линейную интерполяцию), мы добавляем настраиваемый параметр grayscale_power для регулировки мощности оттенков серого.
  • We also get the dirt texture and apply it to the final scene color to simulate dirt on camera lens (can also be used for vignette effect etc.) Мы также получаем текстуру грязи и применяем ее к окончательному цвету сцены, чтобы имитировать грязь на объективе камеры (также можно использовать для эффекта виньетки и т. д.)
  • A custom dirt_power parameter to adjust intensity of the dirt texture (its impact on the final image). Пользовательский параметр dirt_power для регулировки интенсивности текстуры грязи (ее влияния на окончательное изображение).
Примечание
Use the materials_reload console command to reload shaders whilst the engine is running. Используйте консольную команду materials_reload для перезагрузки шейдеров во время работы движка.

See AlsoСмотрите также#

Editing the MaterialРедактирование материала#

Material has been created, the shader has been written, it's time to use it in the project! Материал создан, шейдеры написаны, пора использовать в проекте!

  1. Open UnigineEditor and launch your project. Откройте UnigineEditor и запустите свой проект.
  2. Create a new material by inheriting from the recently created grayscale material in the Materials Hierarchy window. Создайте новый материал, унаследовав его от недавно созданного в окне Materials Hierarchy.
  3. Open the Settings window by choosing Windows -> Settings from the main menu
    Откройте окно Settings, выбрав Windows -> Settings в главном меню
  4. In the Settings window choose Runtime -> World -> Render -> Scriptable Materials and specify the name of the child grayscale material in the field.

    The grayscale post-effect will be applied.The grayscale post-effect will be applied.

    The grayscale post-effect will be applied.
    В окне Settings выберите Runtime -> World -> Render -> Screen Space Materials и укажите имя дочернего материала публикации в поле Post.

    The grayscale post-effect will be applied. Будет применен пост-эффект оттенков серого.

  5. Configure your post-effect by adjusting the Grayscale Power and Dirt Power parameters.

    The final scene.The final scene.
    The final scene.
    Выберите свой материал в окне Materials. Затем в окне Parameters выберите вкладку Parameters.

    Настройте пост-эффект, отрегулировав параметры Grayscale Power и Dirt Power.

    The final scene. Финальная сцена.
Последнее обновление: 10.03.2022
Build: ()