Jump to content

API access for parameters on the "Common" tab of the Material


photo

Recommended Posts

Добрый день, сотрудники компании Unigine.
Необходимо программно задавать настройки материала у объекта типа ObjectWaterMesh. Всего UnigineEditor для этого типа объекта имеются четыре вкладки настроек мате риала (Common, States, Textures, Parameters). Для получения и задания параметров на вкладках States, Textures и  Parameters имеются соответствующие методы:

  • getNumStates(...)/getStateName(...)/getStateType(...)/setState(...)
  • getNumTextures(...)/getTextureName(...)/getTextureType(...)/setTexture(...) и т.д.
  • getNumParameters(...)/getParameterName(...)/getParameterType(...)/setParameter(...) и т.д.

Для вкладки "Common" аналогичные методы отсутствуют и методов подходящих по смыслу из названий на вкладке "Common"  тоже нет.

Вопросы: 

  1. Как программно работать с параметрами на вкладке "Common"?
  2. Имена параметров во вкладках не документированы? Узнать имена параметров в соответствующих вкладках можно только посредством перебора в цикле и применения метода getStateName(...)/getTextureName(...)/getParameterName(...) соответственно?
  3. При обходе всех параметров на соответствующих вкладках обнаружил, что в редакторе отображается не полный набор параметров. Это сделано для того, чтобы не было возможности изменять некоторые параметры которые являются "условно" константными, инициализируются автоматически на момент создания материала и изменению не подлежат?
  4. При работе метода setParameter(...), если задать произвольное имя параметра (параметра с таким именем у материала не существует) этот параметр будет добавлен? Или метод setParameter(...) не найдёт параметра с таким именем и завершит выполнение? Т.е. вообщем вопрос - можно-ли расширять набор параметров (состояний/текстур/параметров/ на вкладке "Common") произвольными параметрами?
  5. Возможные значения типов получаемые методами getStateType(....)/getTextureType()/getParameterType(...) перечислены в таблице Variables в документации Unigine::Material Class?

 

Link to comment

Hi Nokolai,

Answers to first two questions..

1. Как программно работать с параметрами на вкладке "Common"? 
1. How to programmatically work with parameters on the "Common" tab?

If I want to programmatically program the common tab parameters of materials then they are accessed through 

https://developer.unigine.com/en/docs/2.11/api/library/rendering/class.material?rlang=cpp

All methods are there in above class. If you want to set DepthTest there is a method setDepthTest, for Overlap setOverlap.

Blending sets can be set using the same class and rendering passes of unigine will take  care of renderstates automatically before rendering the object.

if you manually need to do something with the mesh or object to render; get the Blend Functions and then use the RenderStates to set them using

https://developer.unigine.com/en/docs/2.11/api/library/rendering/class.renderstate?rlang=usc

Like 

RenderState::saveState();
RenderState::clearStates();
RenderState::flushStates();

RenderState::setBlendFunc(RenderState::BLEND_SRC_ALPHA, RenderState::BLEND_ONE_MINUS_SRC_ALPHA, RenderState::BLEND_OP_ADD);
RenderState::flushStates();

// Do rendering

RenderState::restoreState();

2. Имена параметров во вкладках не документированы? 

2. Parameter names in tabs not documented? 

You may find the documentation for the parameters here

https://developer.unigine.com/en/docs/2.11/content/materials/library/?rlang=cpp

I hope at least first two questions are answered.

Regards,

Rohit

 

Link to comment

Dear Nikolaj,

3. При обходе всех параметров на соответствующих вкладках обнаружил, что в редакторе отображается не полный набор параметров. Это сделано для того, чтобы не было возможности изменять некоторые параметры которые являются "условно" константными, инициализируются автоматически на момент создания материала и изменению не подлежат? 

3. When bypassing all the parameters on the corresponding tabs, I found that the editor does not display a complete set of parameters. This is done so that it is not possible to change some parameters that are "conditionally" constant, are initialized automatically at the time of creation of the material and are not subject to change?

Refer

https://developer.unigine.com/en/docs/2.11/code/formats/materials_formats/base_material_format?rlang=cpp#element_parameter

Check Base materials from your SDK. Few parameters, states are internal and hidden. Not exposed to Editor. They are for internal usage.

I have created some custom materials for my workflow and they are not shown at all in the editor. But my program chosses these materials when I want them. The materials are marked hidden="1"

You try to create your simple material and understand it in depth. For Example a custom dissolve material like this :

<base_material version="2.10.0.0" name="post_filter_transition_dissolve" hidden="1">

 <!-- Post-effect shaders -->
	< shader pass="post"  
	 vertex="core/shaders/arort/common_screen_space_plane.vert" 
	 fragment="core/shaders/arort/transition_dissolve.frag"/>   
   
   <texture name="program" pass="post" type="procedural" unit="0"/>
   <texture name="preview" pass="post" type="procedural" unit="1"/>
      
</base_material>

Look at hidden="1"

The material will not be shown in the Editor Material Hierarchy. But I can find it and use it as engine loads it on initialisation.

Rohit

Link to comment

4. При работе метода setParameter(...), если задать произвольное имя параметра (параметра с таким именем у материала не существует) этот параметр будет добавлен? Или метод setParameter(...) не найдёт параметра с таким именем и завершит выполнение? Т.е. вообщем вопрос - можно-ли расширять набор параметров (состояний/текстур/параметров/ на вкладке "Common") произвольными параметрами? 
4. When the setParameter (...) method works, if you specify an arbitrary parameter name (there is no parameter with the same name for the material) will this parameter be added? Or does the setParameter (...) method not find a parameter with that name and complete execution? Those. in general the question - is it possible to expand the set of parameters (states / textures / parameters / on the "Common" tab) with arbitrary parameters?

 

Technically, When you Write Material, the parameters are linked to attached shaders. If you give any arbitrary name to parameter; which parameter in shader it will linked too?

So complete this discussion I attach the Shader for above custom material to answer this question. Vertex Shader

// Include the UUSL header
#include <core/shaders/common/common.h>

// Input data struct
STRUCT(VERTEX_IN)
 INIT_ATTRIBUTE(float4,0,POSITION) // Vertex position
 INIT_ATTRIBUTE(float4,1,TEXCOORD0) // Vertex texcoords
 INIT_ATTRIBUTE(float4,2,COLOR0)  // Vertex color
END

// Output data struct
STRUCT(VERTEX_OUT)
 INIT_POSITION  // Output projected position
 INIT_OUT(float2,0) // Texcoords (x and y only)
END

MAIN_BEGIN(VERTEX_OUT,VERTEX_IN)
 
 // Set output position
 OUT_POSITION = getPosition(IN_ATTRIBUTE(0));
 OUT_DATA(0).xy = IN_ATTRIBUTE(1).xy;
 
MAIN_END

// end

and pixel Shader


// Include the UUSL fragment shader header
#include <core/shaders/common/fragment.h>

// Define the texture of the scene
INIT_TEXTURE(0,TEX_PGM)
INIT_TEXTURE(1,TEX_PRV)

// Input values
STRUCT(FRAGMENT_IN)
	INIT_POSITION  // Projected position
	INIT_IN(float2,0) // Texcoords
END

CBUFFER(parameters)
UNIFORM float InAmount;
END

MAIN_BEGIN(FRAGMENT_OUT,FRAGMENT_IN)

 float2 uv = IN_DATA(0);
 
 float4 Color1 = TEXTURE_BIAS_ZERO(TEX_PGM, uv);
 float4 Color2 = TEXTURE_BIAS_ZERO(TEX_PRV, uv);
 float4 Color = lerp(Color1, Color2, InAmount);
 OUT_COLOR = Color;	
 
MAIN_END

// end

Now You make this material hidden=0 and add Parameter Float for amount. Now you may change values from Editor and take those in your code to handle the material rendering by setting amount value to the shader parameter InAmount. This is the general flow.

So If you add any parameter name it will not add automatically but you need to create it in your materials. If you send parameter name which is not already there,  Unigine will ignore it. Try by coding it. Might be it will break? One need to write code to test it.

If you are asking this for base material, I guess this you cannot do. But you create custom material for it and then handle all passes correctly; then you may add your parameters to inherited custom material. Little Difficult.

Hope I understood your question and it is answered now.

Regards,

Rohit


 

Link to comment

5. Возможные значения типов получаемые методами getStateType(....)/getTextureType()/getParameterType(...) перечислены в таблице Variables в документации Unigine::Material Class?
5. The possible type values obtained by getStateType (....) / getTextureType () / getParameterType (...) methods are listed in the Variables table in the Unigine :: Material Class?

Yes.

 

Link to comment
  • 2 months later...

Thank you very much rohit.gonsalves for such detailed answer. But, in 2 question i meant the names of the paremeters used in group methods "setParameterXXX" (setParameterFloat, setParameterFloat2,...set ParameterInt, ... ) for example:

void setParameterFloat ( const char * name, float value )

in use:

...->getMaterial(0)->setParameterFloat("underwater_fog_transparency", -1.0f);

To use this method i need to know name of parameter (in this example it is "underwater_fog_transparency"). Where in the documentation can i find list with names all parameters?  

I had to use this code to output parameter names and search for the meaning i needed:

			Log::error("States (%d):\n", waterMesh->getMaterial(0)->getNumStates());
			for (int i = 0; i < waterMesh->getMaterial(0)->getNumStates(); i++) {
				Log::error("%s (%d)\n", waterMesh->getMaterial(0)->getStateName(i), waterMesh->getMaterial(0)->getStateType(i));
			}
			Log::error("Textures (%d):\n", waterMesh->getMaterial(0)->getNumTextures());
			for (int i = 0; i < waterMesh->getMaterial(0)->getNumTextures(); i++) {
				Log::error("%s (%d)\n", waterMesh->getMaterial(0)->getTextureName(i), waterMesh->getMaterial(0)->getTextureType(i));
			}
			Log::error("Parameters (%d):\n", waterMesh->getMaterial(0)->getNumParameters());
			for (int i = 0; i < waterMesh->getMaterial(0)->getNumParameters(); i++) {
				Log::error("%s (%d)\n", waterMesh->getMaterial(0)->getParameterName(i), waterMesh->getMaterial(0)->getParameterType(i));
			}

 

Link to comment
×
×
  • Create New...