Zh/Material proxies: Difference between revisions

From Valve Developer Community
< Zh
Jump to navigation Jump to search
No edit summary
m (Setting bug notice hidetested=1 param on page where the bug might not need tested in param specified)
 
(15 intermediate revisions by 8 users not shown)
Line 1: Line 1:
{{LanguageBar|title=材质代理}}
{{toc-right}}
{{toc-right}}
{{lang|Material_proxies}}
'''材质代理'''允许游戏的编译后C++代码在运行时操作{{L|material|材质}}的属性。它们可用于创建动态或动画纹理。


'''材质代理'''允许游戏编译C++代码来控制[[贴图]]。 许多代理执行特定的任务, 但是 [[List Of Material Proxies|这里也有一些通常的]],在VMT文件内提供一些基础向的脚本语言支持。
== 使用方法 ==
材质代理可以通过{{L|VMT}}文件添加到材质中,具体位于名为<code>Proxies</code>的{{L|KeyValues}}块内;其中的每个条目即为我们所称的'''代理'''。一个材质可以添加任意数量的代理,代理按出现顺序依次执行。游戏会以极快的速度不断重复执行材质代理列表。{{inline note|name=每帧执行?}}


可以添加任意数量的代理,它们会按照顺序执行。
代理的名称决定了其拥有的参数和执行的功能。
许多代理执行特定任务,但也有一些更通用的代理共同为VMT文件提供基础脚本支持。{{clarify}}
{{main|List of material proxies}}


{{bug|一些用户说工具模式下的游戏不会启用一些材质代理功能。}}
通常,每个代理都有一个输出值(例如{{L|float|浮点数}}),该值将被写入其<code>resultVar</code>,后者可以是着色器参数或变量(变量参见[[#Variables|下文]])。
{{todo|没测试过。}}
 
== 用途 ==
 
这是一个具有<code>Sine</code>(正弦)的材质代理,允许在8秒内对它进行[[$alpha|淡入淡出]]操作。


例如,以下材质使用{{material proxy|Sine}}代理生成浮点数并写入材质的{{ent|$alpha}}着色器参数,使纹理在8秒周期内渐隐渐现:
<source lang=php>
<source lang=php>
LightmappedGeneric
LightmappedGeneric
Line 18: Line 18:
$basetexture shadertest/LightmappedTexture
$basetexture shadertest/LightmappedTexture


Proxies // 代理的代码块
Proxies // 代理在此块内列出
{
{
Sine // 提供正弦波的代理
Sine // 生成正弦波值的代理
{
{
resultVar $alpha // 需要控制的参数部分
sineperiod 8      // 正弦周期长度(秒)
sineperiod 8
sinemin 0     // 最小值
sinemin 0
sinemax 1     // 最大值
sinemax 1
resultVar $alpha // 振荡输出值的写入位置
}
}
}
}
Line 31: Line 31:
</source>
</source>


=== Variables ===
=== 变量 ===


Materials can declare their own variables for internal use. Such variables must be declared outside the Proxies block, in the body of the material, and must have default values specified on the right-hand side.
材质可以声明自定义变量供内部使用。此类变量必须在<code>Proxies</code>块外的材质主体中声明,并需在右侧指定默认值。


These custom variables might be used to pass results between proxies or to submit hard-coded data to them. They are often employed to chain mathematic function proxies (i.e. <code>Add</code>, <code>Subtract</code>, etc) together into longer equations. For 2D/3D vectors (<code>"[0 0 0]"</code>), the variable name can have <code>[0]</code> suffixed to read/write a specific index. Writes to indexed variables should be encased in quotes.
这些自定义变量可用于在代理间传递结果或向其提交硬编码数据。它们常被用于将数学函数代理(如{{material proxy|Add}}、{{material proxy|Subtract}}等)链接成更长的方程式。对于2D/3D/4D向量(<code>$vec "[0 0 0]"</code>),变量名可附加<code>[0]</code><code>"$vec[0]"</code>)以读写特定索引。对索引变量的写入操作需用引号包裹。


This example extends the one above by staggering the starting position of the sine wave:
引擎使用8位有符号整数编码这些自定义变量,因此每个材质最多有128个独立自定义变量。


此示例扩展了前例,通过{{material proxy|EntityRandom}}代理生成的随机值错开正弦波的起始位置:
<source lang=php>
<source lang=php>
LightmappedGeneric
LightmappedGeneric
Line 44: Line 45:
$basetexture shadertest/LightmappedTexture
$basetexture shadertest/LightmappedTexture


$offset 0 // declare custom var
$offset 0 // 声明自定义变量($offset不是游戏已知的着色器参数)
Proxies
Proxies
{
{
EntityRandom
EntityRandom // 生成随机数
{
{
resultVar $offset // write to custom var
resultVar $offset // 写入自定义变量
}
}
Sine
Sine
{
{
resultVar $alpha
resultVar $alpha
timeoffset $offset // read from custom var
timeoffset $offset // 从自定义变量读取
sineperiod 8
sineperiod 8
sinemin 0
sinemin 0
Line 64: Line 65:
</source>
</source>


Now each entity this material is used on pulses to its own schedule.
现在使用此材质的每个实体都会按自身节奏脉动。
 
Other examples for writing to indexed variables:


以下是通过$color向量写入索引变量创建"随机"颜色脉动的示例:
<source lang=php>
<source lang=php>
$color "[0 0 0]"
$color "[0 0 0]" // 非自定义变量,游戏识别"$color"


proxies
proxies
Line 100: Line 100:
</source>
</source>


An example of using a color vector to create 'random' color pulses.


{{expand|noborder=1|title=动态纹理变换示例|
<source lang=php>
<source lang=php>
UnlitGeneric
UnlitGeneric
Line 165: Line 165:
}
}
</source>
</source>
}}


An example of a dynamic texture transform.
=== 拆分向量 ===
 
使用向量存在特殊性,因为<code>"$pos[0]"</code>等向量分量表达式并非总被游戏识别。
== Splitting a vector ==
{{important|当访问向量分量或定义向量时,必须使用引号}}
Using vectors is quirky. Not all proxies recognize vector components. If a vector's components need be processed separately, they need to be split into different variables first.
下列代理(且仅限于这些键值)可识别向量分量:
 
<tt>
The following proxies, and only these keyvalues, can recognize vector components:
* 所有代理的<code>resultVar</code>
<code>
* {{material proxy|Clamp}}:         min, max
* '''Clamp: '''        min, max
* {{material proxy|Sine}}:          offset, max, min, period
* '''Sine:'''         offset, max, min, period
* {{material proxy|LinearRamp}}:    rate, initial value
* '''LinearRamp:'''   rate, initial value
* {{material proxy|UniformNoise}}:  min, max
* '''UniformNoise:''' min, max
* {{material proxy|GaussianNoise}}: min, max, mean, halfwidth
* '''GaussianNoise:''' min, max, mean, halfwidth
* {{material proxy|WrapMinMax}}:    min, max
* '''WrapMinMax:'''   min, max
* {{material proxy|Exponential}}:  min, max, scale, offset
* '''Exponential:'''   min, max, scale, offset
</tt>
</code>
如需单独处理向量分量,需先将其拆分到不同变量中。
All of the above can be used to split a vector. However Clamp is the [[Cheap|cheapest]] to use:
上述所有方法都可用于拆分向量,但{{L|Clamp}}是{{L|Cheap|消耗最低}}的方式。
{{expand|noborder=1|title=示例|
<source lang="php">
<source lang="php">
         $pos "[0 0 0]"
         $pos "[0 0 0]"
         $posX .0        //must be float or Clamp will not save the value properly
         $posX .0        //必须是浮点数,否则Clamp无法正确保存值
         $posY .0        //must be float or Clamp will not save the value properly
         $posY .0        //必须是浮点数,否则Clamp无法正确保存值
         $posZ .0        //must be float or Clamp will not save the value properly
         $posZ .0        //必须是浮点数,否则Clamp无法正确保存值
          
          
         $zero 0
         $zero 0
          
          
         //Proxy that outputs a 3d vector
         //输出3D向量的代理
         PlayerPosition
         PlayerPosition
         {
         {
Line 197: Line 199:
         }
         }
          
          
         //Split the 3d vector for further use
         //拆分3D向量供后续使用
         Clamp
         Clamp
         {
         {
Line 222: Line 224:
         }
         }
</source>
</source>
}}


{{warning|Quotes are needed when addressing a vector's component, or when defining a vector.}}
== 编写新代理 ==


== Writing new proxies ==
创建新代理较为简单。它们仅存在于客户端,应继承自<code>IMaterialProxy</code>或其子类。


New proxies are easy to create. They exist on the client only and should inherit from <code>IMaterialProxy</code> or one of its descendants.
需要包含以下头文件:
 
You will need these #includes:


* <code>"materialsystem/IMaterialProxy.h"</code>
* <code>"materialsystem/IMaterialProxy.h"</code>
* <code>"materialsystem/IMaterialVar.h"</code>
* <code>"materialsystem/IMaterialVar.h"</code>


These functions are included in the interface:
接口包含以下函数:


; <code>[[bool]] Init( [[IMaterial]]* pMaterial, [[KeyValues]]* pKeyValues )</code>
; <code>{{L|bool}} Init( {{L|IMaterial}}* pMaterial, {{L|KeyValues}}* pKeyValues )</code>
: Called when the material is first [[precache]]d. Use this function to initialise variables and grab references to the material vars you will be using. Return true on success and false on failure (in which case the proxy will not be run).
: 材质首次{{L|precache|预缓存}}时调用。用于初始化变量并获取材质变量引用。成功返回true,失败返回false(代理将不运行)。
: <code>pKeyValues</code> contains the proxy parameters from the VMT file.
: <code>pKeyValues</code>包含来自VMT文件的代理参数。
; <code>void OnBind( void* pC_BaseEntity )</code>
; <code>void OnBind( void* pC_BaseEntity )</code>
: Called when the material is about to be rendered on an entity. This is where the work is done.
: 材质即将在实体上渲染时调用。主要工作在此完成。
: When coding this function it is important to remember that all entities using a material share the same material object, and that if you change it on one entity it changes everywhere else too. Since <code>OnBind()</code> is called every time an entity comes up for rendering this is not a problem ''so long as you reassign the value you want every time''. Don't return early just because there has been no change, and don't store any input data in the proxy. {{note|<code>pC_BaseEntity</code> doesn't lead to a <code>[[C_BaseEntity]]</code> as its name suggests, but rather to the associated <code>[[IClientRenderable]]</code>. The easiest way to access the entity directly is to base your class on <code>CEntityMaterialProxy</code> (in <code>proxyentity.h</code>) and use the <code>OnBind(C_BaseEntity*)</code> overload it provides.}}
: 编码时需注意:所有使用该材质的实体共享同一材质对象,若修改某实体的材质参数将影响所有实体。由于<code>OnBind()</code>在每次实体渲染前调用,''只要每次重新赋值所需值就不会出现问题''。不要因无变化而提前返回,也不要在代理中存储输入数据。{{note|<code>pC_BaseEntity</code>并不指向{{L|C_BaseEntity}},而是关联的{{L|IClientRenderable}}。直接访问实体的最简单方法是继承自<code>CEntityMaterialProxy</code>(位于<code>proxyentity.h</code>),使用其提供的<code>OnBind(C_BaseEntity*)</code>重载。}}
; <code>void Release()</code>
; <code>void Release()</code>
: {{todo|Called when the proxy is removed, but when is that?}}
: {{todo|代理被移除时调用,但具体时机是?}}
; <code>[[IMaterial]]* GetMaterial()</code>
; <code>{{L|IMaterial}}* GetMaterial()</code>
: The material the proxy is attached to. {{tip|If you have a material var stored, you can return <code>IMaterialVar::GetOwningMaterial()</code> here instead of creating a new <code>IMaterial</code> pointer.}}
: 代理所属的材质。{{tip|若已存储材质变量,可返回<code>IMaterialVar::GetOwningMaterial()</code>而无需新建<code>IMaterial</code>指针}}


=== Interface ===
=== 接口 ===


The proxy must expose its interface to materials with the <code>EXPOSE_INTERFACE</code> macro:
代理必须通过<code>EXPOSE_INTERFACE</code>宏向材质暴露接口:


<source lang=cpp>
<source lang=cpp>
Line 255: Line 256:
</source>
</source>


The lack of a comma between the proxy name and interface version is intentional.
代理名称与接口版本间无逗号为刻意设计。


=== Tools recording ===
=== 工具录制 ===


This code was added to all proxies in the Orange Box:
橙盒版本中所有代理都添加了以下代码:


<source lang=cpp>
<source lang=cpp>
Line 273: Line 274:
</source>
</source>


It's probably related to the [[Source Filmmaker]]. It's a good idea to add it to your proxy too in case the Filmmaker is ever released!
这可能与{{L|Source Filmmaker}}相关。建议在代理中添加此代码以兼容未来可能发布的电影制作工具!
 
{{tip|<code>CEntityMaterialProxy</code>会自动执行此调用}}
 
== 已知问题 ==


{{tip|<code>CEntityMaterialProxy</code> makes the call by itself.}}
{{bug|hidetested=1|材质的首个参数无法被代理写入。简单解决方案是在VMT顶部添加虚拟变量}}
{{bug|hidetested=1|有用户报告工具模式无法在游戏中运行某些功能代理。问题范围未经验证}}
{{bug|hidetested=1|在粒子或{{L|prop_static}}上使用访问实体状态的代理(如<code>EntityRandom</code>)可能导致游戏崩溃}}


== See also ==
== 另见 ==
* [[List Of Material Proxies]]
* {{L|List Of Material Proxies|材质代理列表}}
* [[Material Creation]]
* {{L|Material proxies programming|材质代理编程}}
* {{L|Material Creation|材质创建}}
* Steam指南,详解各类代理:[https://steamcommunity.com/sharedfiles/filedetails/?id=594255575 基础], [https://steamcommunity.com/sharedfiles/filedetails/?id=668958242 随机数], [https://steamcommunity.com/sharedfiles/filedetails/?id=749130424 "编程"]


== External links ==
== 外部链接 ==
* [http://web.archive.org/web/20140719034333/http://www.nodraw.net/2010/01/dynamic-materials-with-proxies/ Dynamic Materials With Proxies] - An article covering practical uses of materials with proxies by [http://www.nodraw.net NoDraw.net]
* [https://nodraw.net/2010/01/dynamic-materials-with-proxies/ 使用代理的动态材质] - [http://www.nodraw.net NoDraw.net]关于材质代理实际应用的文章


[[Category:Material System]]
{{ACategory|Source}}
[[Category:Programming]]
{{ACategory|Material System}}
{{ACategory|C++}}

Latest revision as of 07:18, 20 May 2025

English (en)Português do Brasil (pt-br)中文 (zh)Translate (Translate)
Info content.png
This page is Machine translated
It is not recommended to use machine translation without any corrections.
If the article is not corrected in the long term, it will be removed.
Also, please make sure the article complies with the alternate languages guide.(en)
This notice is put here by LanguageBar template and if you want to remove it after updating the translation you can do so on this page.


材质代理允许游戏的编译后C++代码在运行时操作材质(en)的属性。它们可用于创建动态或动画纹理。

使用方法

材质代理可以通过VMT(en)文件添加到材质中,具体位于名为ProxiesKeyValues(en)块内;其中的每个条目即为我们所称的代理。一个材质可以添加任意数量的代理,代理按出现顺序依次执行。游戏会以极快的速度不断重复执行材质代理列表。[每帧执行?]

代理的名称决定了其拥有的参数和执行的功能。 许多代理执行特定任务,但也有一些更通用的代理共同为VMT文件提供基础脚本支持。[澄清]

通常,每个代理都有一个输出值(例如浮点数(en)),该值将被写入其resultVar,后者可以是着色器参数或变量(变量参见下文)。

例如,以下材质使用Sine代理生成浮点数并写入材质的$alpha着色器参数,使纹理在8秒周期内渐隐渐现:

LightmappedGeneric
{
	$basetexture shadertest/LightmappedTexture

	Proxies // 代理在此块内列出
	{
		Sine // 生成正弦波值的代理
		{
			sineperiod	8      // 正弦周期长度(秒)
			sinemin		0      // 最小值
			sinemax		1      // 最大值
			resultVar	$alpha // 振荡输出值的写入位置
		}
	}
}

变量

材质可以声明自定义变量供内部使用。此类变量必须在Proxies块外的材质主体中声明,并需在右侧指定默认值。

这些自定义变量可用于在代理间传递结果或向其提交硬编码数据。它们常被用于将数学函数代理(如AddSubtract等)链接成更长的方程式。对于2D/3D/4D向量($vec "[0 0 0]"),变量名可附加[0]"$vec[0]")以读写特定索引。对索引变量的写入操作需用引号包裹。

引擎使用8位有符号整数编码这些自定义变量,因此每个材质最多有128个独立自定义变量。

此示例扩展了前例,通过EntityRandom代理生成的随机值错开正弦波的起始位置:

LightmappedGeneric
{
	$basetexture shadertest/LightmappedTexture

	$offset 0 // 声明自定义变量($offset不是游戏已知的着色器参数)
	
	Proxies
	{
		EntityRandom // 生成随机数
		{
			resultVar $offset // 写入自定义变量
		}
		Sine
		{
			resultVar	$alpha
			timeoffset	$offset // 从自定义变量读取
			sineperiod	8
			sinemin		0
			sinemax		1
		}
	}
}

现在使用此材质的每个实体都会按自身节奏脉动。

以下是通过$color向量写入索引变量创建"随机"颜色脉动的示例:

	$color "[0 0 0]" // 非自定义变量,游戏识别"$color"

	proxies
	{
		sine
		{
			sineperiod	1.3
			sinemin		0
			sinemax		1
			timeoffset	0
			resultvar	"$color[0]"
		}
		sine
		{
			sineperiod	1.7
			sinemin		0
			sinemax		1
			timeoffset	0
			resultvar	"$color[1]"
		}
		sine
		{
			sineperiod	2.3
			sinemin		0
			sinemax		1
			timeoffset	0
			resultvar	"$color[2]"
		}
	}


动态纹理变换示例
UnlitGeneric
{
	$basetexture "dev\gradient_dif"
	$color "[1 .8 .6]"

	$detail "dev\noise_512x32"
	$detailscale 1
	$detailblendmode 0
	$detailblendfactor 4.0

	$additive 1
	$nocull 1

	$cvar "[.5 .5]"
	$svar "[1 .25]"
	$rvar 0
	$tvar "[0 0]"

	$sine1 0
	$sine2 0

	proxies
	{
		linearramp
		{
			rate .3
			initialvalue 0
			resultvar "$tvar[1]"
		}
		sine
		{
			sineperiod 1.3
			sinemin -.004
			sinemax .002
			timeoffset 0
			resultvar $sine1
		}
		sine
		{
			sineperiod 1.7
			sinemin -.003
			sinemax .007
			timeoffset .2
			resultvar $sine2
		}
		add
		{
			srcvar1 $sine1
			srcvar2 $sine2
			resultvar "$tvar[0]"
		}
		texturetransform
		{
			centervar $cvar
			scalevar $svar
			rotatevar $rvar
			translatevar $tvar
			resultvar $detailtexturetransform
		}
	}
}

拆分向量

使用向量存在特殊性,因为"$pos[0]"等向量分量表达式并非总被游戏识别。

Icon-Important.png重要:当访问向量分量或定义向量时,必须使用引号

下列代理(且仅限于这些键值)可识别向量分量:

如需单独处理向量分量,需先将其拆分到不同变量中。 上述所有方法都可用于拆分向量,但Clamp(en)消耗最低(en)的方式。

示例
        $pos "[0 0 0]"
        $posX .0        //必须是浮点数,否则Clamp无法正确保存值
        $posY .0        //必须是浮点数,否则Clamp无法正确保存值
        $posZ .0        //必须是浮点数,否则Clamp无法正确保存值
        
        $zero 0
        
        //输出3D向量的代理
        PlayerPosition
        {
                scale                    1
                resultVar               "$pos"
        }
        
        //拆分3D向量供后续使用
        Clamp
        {
            srcVar1                      $zero
            min                         "$pos[0]"
            max                         "$pos[0]"
            resultVar                    $posX
        }
        
        Clamp
        {
            srcVar1                      $zero
            min                         "$pos[1]"
            max                         "$pos[1]"
            resultVar                    $posY
        }
        
        Clamp
        {
            srcVar1                      $zero
            min                         "$pos[2]"
            max                         "$pos[2]"
            resultVar                    $posZ
        }

编写新代理

创建新代理较为简单。它们仅存在于客户端,应继承自IMaterialProxy或其子类。

需要包含以下头文件:

  • "materialsystem/IMaterialProxy.h"
  • "materialsystem/IMaterialVar.h"

接口包含以下函数:

bool(en) Init( IMaterial(en)* pMaterial, KeyValues(en)* pKeyValues )
材质首次预缓存(en)时调用。用于初始化变量并获取材质变量引用。成功返回true,失败返回false(代理将不运行)。
pKeyValues包含来自VMT文件的代理参数。
void OnBind( void* pC_BaseEntity )
材质即将在实体上渲染时调用。主要工作在此完成。
编码时需注意:所有使用该材质的实体共享同一材质对象,若修改某实体的材质参数将影响所有实体。由于OnBind()在每次实体渲染前调用,只要每次重新赋值所需值就不会出现问题。不要因无变化而提前返回,也不要在代理中存储输入数据。
Note.png注意:pC_BaseEntity并不指向C_BaseEntity(en),而是关联的IClientRenderable(en)。直接访问实体的最简单方法是继承自CEntityMaterialProxy(位于proxyentity.h),使用其提供的OnBind(C_BaseEntity*)重载。
void Release()
待完善: 代理被移除时调用,但具体时机是?
IMaterial(en)* GetMaterial()
代理所属的材质。
Tip.png提示:若已存储材质变量,可返回IMaterialVar::GetOwningMaterial()而无需新建IMaterial指针

接口

代理必须通过EXPOSE_INTERFACE宏向材质暴露接口:

EXPOSE_INTERFACE( <className>, <interfaceName>, "<proxyName>" IMATERIAL_PROXY_INTERFACE_VERSION );

代理名称与接口版本间无逗号为刻意设计。

工具录制

橙盒版本中所有代理都添加了以下代码:

#include "toolframework_client.h"

void OnBind(...)
{
	//...

	if ( ToolsEnabled() )
		ToolFramework_RecordMaterialParams( GetMaterial() );
}

这可能与Source Filmmaker(en)相关。建议在代理中添加此代码以兼容未来可能发布的电影制作工具!

Tip.png提示:CEntityMaterialProxy会自动执行此调用

已知问题

Icon-Bug.png错误:材质的首个参数无法被代理写入。简单解决方案是在VMT顶部添加虚拟变量
Icon-Bug.png错误:有用户报告工具模式无法在游戏中运行某些功能代理。问题范围未经验证
Icon-Bug.png错误:在粒子或prop_static(en)上使用访问实体状态的代理(如EntityRandom)可能导致游戏崩溃

另见

外部链接