> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md).

# 材质

了解如何向具有基础形状的实体添加材质和纹理。

## 材质

可以通过添加一个 `Material` 组件，为使用基本形状（立方体、球体、平面等）的实体应用材质。该组件包含多个字段，可用于配置材质属性、添加纹理等。

*glTF* 模型包含自身的材质，这些材质会随模型一起隐式导入场景。若要修改或覆盖这些材质，请使用 `GltfNodeModifiers` 组件。详情请参阅 [修改 glTF 材质](#modify-gltf-materials) 。

导入包含自身材质的 3D 模型时，请注意，Decentraland 引擎并不支持所有着色器。它仅支持标准材质和 PBR（基于物理的渲染）材质。详情请参阅 [外部 3D 模型注意事项](https://github.com/decentraland/docs/blob/main/creator/3d-modeling/materials.md) 。

支持的材质类型包括：

* PBR（基于物理的渲染）：Decentraland 中最常见的材质类型。它支持纯色或纹理，以及金属度、自发光、透明度等多种属性。了解更多关于 [PBR](https://en.wikipedia.org/wiki/Physically_based_rendering).
* 基本材质：不会响应光照和阴影，因此非常适合显示广告牌图像。

## 在 Creator Hub 中使用场景编辑器

为实体设置材质的最简单方法是使用场景编辑器。你可以为实体添加 **材质** 组件，然后在场景编辑器界面中配置所有可用字段。请参阅 [添加组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/gou-jian/components.md#add-components).

## 添加材质

以下示例创建一个 PBR 材质，并设置其中的部分字段，使其呈红色并具有金属属性。该材质会添加到一个同时包含盒体形状的实体上，因此盒体将使用此材质着色。

```ts
//创建实体并指定形状
const meshEntity = engine.addEntity()
Transform.create(meshEntity, {
	position: Vector3.create(4, 1, 4),
})
MeshRenderer.setBox(meshEntity)

//创建材质并配置其字段
Material.setPbrMaterial(meshEntity, {
	albedoColor: Color4.Red(),
	metallic: 0.8,
	roughness: 0.1,
})
```

若要更改已包含 `Material` 组件的实体的材质，请运行 `Material.setPbrMaterial()` 或其他任一辅助函数，它会覆盖原有材质。无需移除原有材质 `Material` ，也无需使用高级语法。

```ts
//创建实体并指定形状
const meshEntity = engine.addEntity()
Transform.create(meshEntity, {
	position: Vector3.create(4, 1, 4),
})
MeshRenderer.setBox(meshEntity)

//创建材质并配置其字段
Material.setPbrMaterial(meshEntity, {
	albedoColor: Color4.Red(),
})

//使用新的材质组件覆盖
Material.setPbrMaterial(meshEntity, {
	albedoColor: Color4.Blue(),
})
```

{% hint style="warning" %}
**📔 注意**： `Material` 组件必须通过以下方式导入：

> `import { Material } from "@dcl/sdk/ecs"`

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

## 材质颜色

为材质设置纯色。在 PBR 材质中，需要设置 `albedoColor` 字段。反照率颜色会响应光照，并可呈现明暗层次。

颜色值的类型为 `Color4`，由以下部分组成： *r*, *g* 和 *b* 个值（红、绿、蓝）。每个值的取值范围为 0 到 1。通过设置这些值，你可以组合出任何可见颜色。要设置黑色，请将三者都设为 0；要设置白色，则将它们都设为 1。

{% hint style="warning" %}
**📔 注意**：如果将 `albedoColor` 中的任意颜色设为大于 *1*的值，它就会呈现为 *自发光*效果，数值越高，强度越大。例如， `{r: 15, g: 0, b: 0}` 会产生非常明亮的红色光芒。
{% endhint %}

如需详细了解如何设置颜色，请参阅 [颜色类型](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/color-types.md) 。

你还可以编辑 PBR 材质中的以下字段，微调其颜色的呈现效果：

* *emissiveColor*：材质发出的颜色。
* *reflectivityColor*：也称为 *高光颜色* ，在其他术语体系中也有此称呼。

如果要创建不受环境光照和阴影影响的纯色材质，请创建基本材质，而不是 PBR 材质。

```ts
Material.setBasicMaterial(myEntity, {
	diffuseColor: Color4.Black(),
})
```

## 使用纹理

设置 `texture` 参数，即可将图像文件设为材质的纹理。

```ts
//创建实体并指定形状
const meshEntity = engine.addEntity()
Transform.create(meshEntity, {
	position: Vector3.create(4, 1, 4),
})
MeshRenderer.setBox(meshEntity)

//创建材质并配置其字段
Material.setPbrMaterial(meshEntity, {
	texture: Material.Texture.Common({
		src: 'assets/materials/wood.png',
	}),
})
```

在上面的示例中，材质的图像位于 `assets/materials` 文件夹中，该文件夹位于场景项目文件夹的根目录下。

{% hint style="info" %}
**💡 提示**：建议将纹理图像文件放在场景内的 `/assets` 文件夹中。
{% endhint %}

创建纹理时，还可以传入其他参数：

* `filterMode`：确定渲染时纹理像素的拉伸或压缩方式。该参数接受 `TextureFilterMode` 枚举中的值。请参阅 [纹理缩放](#texture-scaling).
* `wrapMode`：确定纹理如何平铺到对象上。该参数接受 `TextureWrapMode` 枚举。参见 [纹理环绕](#texture-wrapping).

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'assets/materials/wood.png',
		filterMode: TextureFilterMode.TFM_BILINEAR,
		wrapMode: TextureWrapMode.TWM_CLAMP,
	}),
})
```

若要创建不受环境光照和阴影影响的纹理，请创建基本材质，而不是 PBR 材质。

```ts
Material.setBasicMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'assets/materials/wood.png',
	}),
})
```

### 来自外部 URL 的纹理

你可以将材质的纹理指向外部 URL，而不是场景项目中的内部路径。

```ts
Material.setBasicMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'https://wearable-api.decentraland.org/v2/collections/community_contest/wearables/cw_tuxedo_tshirt_upper_body/thumbnail',
	}),
})
```

URL 必须以 `https`, `http` 不支持 URL。

### 纹理环绕

你可以设置纹理与表面的对齐方式。默认情况下，纹理会拉伸以覆盖整个表面一次，但你也可以缩放和偏移纹理。

所有纹理都支持以下字段：

* `offset`：移动纹理以更改其对齐方式。该值为 Vector2，两个轴的取值范围均为 0 到 1，其中 1 表示纹理的完整宽度或高度。
* `tiling`：缩放纹理。默认值为 Vector 2 `[1, 1]`，此值会使图像重复一次并覆盖整个表面。
* `TextureWrapMode`：确定图像平铺未覆盖整个表面时的处理方式。此属性的值取自 `TextureWrapMode` 枚举，可使用以下值：
  * `TextureWrapMode.TWM_CLAMP`：纹理仅按指定尺寸显示一次。网格的其余表面保持透明。 `tiling` 的值会被忽略。
  * `TextureWrapMode.TWM_REPEAT`：纹理按指定尺寸重复，直到填满网格。
  * `TextureWrapMode.TWM_MIRROR`：与重复环绕模式一样，纹理会重复直到填满网格，但每次重复的方向都会镜像翻转。

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'assets/materials/wood.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
		offset: Vector2.create(0, 0.2),
		tiling: Vector2.create(1, 1),
	}),
})
```

{% hint style="warning" %}
**📔 注意**： `offset` 和 `tiling` 属性仅在 DCL 2.0 桌面客户端中受支持。
{% endhint %}

使用此功能可通过平铺图案覆盖大面积表面。例如，重复显示以下图像：

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-9fc3c9552e1da78b7ab43f388bab8c2d91b010fd%2Ftiles.webp?alt=media)

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'assets/materials/wood.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
		tiling: Vector2.create(8, 8),
	}),
})
```

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-b432accf316018a223e2902f5dd392b6d5d54c2c%2Ftiles-in-scene.webp?alt=media)

在下面的示例中，纹理使用 *镜像* 环绕模式，并且每次重复的纹理仅占表面的 1/4。这意味着我们会看到 4 个图像副本，沿两个轴彼此镜像。

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/atlas.png',
		wrapMode: TextureWrapMode.TWM_MIRROR,
		tiling: Vector2.create(0.25, 0.25),
	}),
})
```

### 纹理补间

使用 `Tween` 组件，并配置为 `TextureMove` 模式。补间会以平滑且经过优化的方式，在一段时间内逐渐更改纹理的 `offset` 或 `tiling` 属性。

{% hint style="warning" %}
**📔 注意**：纹理补间仅受 DCL 2.0 桌面客户端支持。
{% endhint %}

使用 `Tween` 组件和 `setTextureMove` 函数，在两个位置之间移动纹理。

```ts
Tween.setTextureMove(myEntity, Vector2.create(0, 0), Vector2.create(1, 0), 2000)
```

纹理补间需要以下信息：

* `entity`: 要移动其纹理的实体
* `start`: 表示起始位置的 Vector2
* `end`：用于表示结束位置的 Vector2
* `duration`：在两个位置之间移动所需的毫秒数

此外，还可以使用以下可选参数：

* `movementType`：定义移动作用于 `offset` 字段还是 `tiling` 字段。默认使用 `offset`.
* `easingFunction`：随时间变化的速率曲线，默认值为 `EasingFunction.EF_LINEAR`。其他值可以让变化以不同的速率加速和/或减速。

```ts
const myEntity = engine.addEntity()

MeshRenderer.setPlane(myEntity)

Transform.create(myEntity, {
	position: Vector3.create(4, 1, 4),
})

Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/water.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
	}),
})

Tween.setTextureMove(myEntity, Vector2.create(0, 0), Vector2.create(0, 1), 1000)
```

上述示例执行一个持续 1 秒的补间，并且只移动纹理一次。若要实现连续移动（例如模拟瀑布下落），需要使用 `setTextureMoveContinuous`.

```ts
const myEntity = engine.addEntity()

MeshRenderer.setPlane(myEntity)

Transform.create(myEntity, {
	position: Vector3.create(4, 1, 4),
})

Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/water.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
	}),
})

Tween.setTextureMoveContinuous(myEntity, Vector2.create(0, 1), 1)
```

上述示例使用 `setTextureMoveContinuous`，方向为 `(0, 1)`，速度为每秒 1 个单位。

纹理持续补间需要以下信息：

* `entity`: 要移动其纹理的实体
* `direction`：用于表示移动方向的 Vector2
* `speed`：实体每秒移动的单位数

还可以使用以下可选参数：

* `movementType`：定义移动作用于偏移量还是平铺字段。默认使用偏移量。
* `duration`：移动持续的毫秒数。时间到后，移动将停止。

**复杂的补间序列**

你还可以让纹理按照包含任意多个步骤的复杂序列移动。使用 `sequence` 字段列出所需数量的补间；它们会在 `Tween` 组件中定义的第一个补间之后按顺序执行。

```ts
//(...)
Tween.setTextureMove(myEntity, Vector2.create(0, 0), Vector2.create(0, 1), 1000)

TweenSequence.create(myEntity, {
	sequence: [
		{
			mode: Tween.Mode.TextureMove({
				start: Vector2.create(0, 1),
				end: Vector2.create(1, 1),
			}),
			duration: 1000,
			easingFunction: EasingFunction.EF_LINEAR,
		},
		{
			mode: Tween.Mode.TextureMove({
				start: Vector2.create(1, 1),
				end: Vector2.create(1, 0),
			}),
			duration: 1000,
			easingFunction: EasingFunction.EF_LINEAR,
		},
		{
			mode: Tween.Mode.TextureMove({
				start: Vector2.create(1, 0),
				end: Vector2.create(0, 0),
			}),
			duration: 1000,
			easingFunction: EasingFunction.EF_LINEAR,
		},
	],
	loop: TweenLoop.TL_RESTART,
})
```

请注意，在 TweenSequence 中定义补间时，需要使用更详细的格式： `Tween.Mode.TextureMove` 来定义补间动画。

### 多层纹理

你可以使用多个图像文件作为图层，组合出更逼真的纹理，例如添加 `bumpTexture` 和 `emissiveTexture`.

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/wood.png',
	}),
	bumpTexture: Material.Texture.Common({
		src: 'materials/woodBump.png',
	}),
	emissiveTexture: Material.Texture.Common({
		src: 'materials/glow.png',
	}),
})
```

bumpTexture `bumpTexture` 可以通过改变每个像素处表面法线的表现方式，模拟表面的凸起和褶皱。

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-c10fa878ba8f8a81fa0d124ec6680cde048f20b1%2Fwood-bump.webp?alt=media)

emissiveTexture `emissiveTexture` 可以增强材质特定部分的发光效果，从而实现非常有趣的效果。

**设置 UV**

另一种调整纹理缩放或对齐方式的方法，是配置 *uv* 属性。该属性位于 [MeshRenderer 组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/shape-components.md).

你需要设置 *u* 和 *v* 坐标，将纹理二维图像上的坐标与形状的顶点对应起来。实体的顶点越多，就需要在纹理上定义越多的 *uv* 坐标。例如，一个平面需要定义 8 个 *uv* 点，每个面 4 个。

```ts
const meshEntity = engine.addEntity()
Transform.create(meshEntity, {
	position: Vector3.create(4, 1, 4),
})
MeshRenderer.setPlane(
	meshEntity,
	[
		0, 0.75,

		0.25, 0.75,

		0.25, 1,

		0, 1,

		0, 0.75,

		0.25, 0.75,

		0.25, 1,

		0, 1,
	]
)

Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/wood.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
	}),
})
```

以下示例包含一个用于简化 UV 设置的函数。此处定义的 `setUVs` 函数接收行数和列数作为参数，并设置 UV，使纹理图像按指定次数重复。

```ts
const meshEntity = engine.addEntity()
Transform.create(meshEntity, {
	position: Vector3.create(4, 1, 4),
})
MeshRenderer.setBox(meshEntity, setUVs(3, 3))

Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/atlas.png',
		wrapMode: TextureWrapMode.TWM_REPEAT,
	}),
})

function setUVs(rows: number, cols: number) {
	return [
		// 未旋转平面的北侧
		0, // 左下角
		0,

		cols, // 右下角
		0,

		cols, // 右上角
		rows,

		0, // 左上角
		rows,

		// 未旋转平面的南侧
		cols, // 右下角
		0,

		0, // 左下角
		0,

		0, // 左上角
		rows,

		cols, // 右上角
		rows,
	]
}
```

要为以下对象设置 UV `box` 网格形状也遵循相同的结构。立方体的 6 个面各需要 4 对坐标，分别对应每个角。这 48 个值都列在同一个数组中。

{% hint style="warning" %}
**📔 注意**：Uv 属性目前仅适用于 `plane` 和 `box` 形状。另外， *uv* 值会同等影响所有纹理层，因为它们是在 *形状*.
{% endhint %}

### 纹理缩放

当纹理被拉伸或缩小到与原始纹理图像不同的尺寸时，有时会产生瑕疵。在 3D 环境中，透视效果自然会造成这种情况。为以不同方式弥补这一问题，存在多种 [纹理过滤](https://en.wikipedia.org/wiki/Texture_filtering) 算法。

Material `对象默认使用` 双线性 *算法，但你可以通过设置纹理的* 属性，将其配置为改用 *最近邻* 或 *三线性* 算法。此属性的值来自 `filterMode` 纹理的属性。其值取自 `TextureFilterMode` 枚举：

* `TextureFilterMode.TFM_POINT`：使用“最近邻”算法。此设置非常适合像素艺术风格的图形，因为纹理在屏幕上放大显示时，轮廓仍会保持清晰，而不会变模糊。
* `TextureFilterMode.TFM_BILINEAR`：使用双线性算法估算每个像素的颜色。
* `TextureFilterMode.TFM_TRILINEAR`：使用三线性算法估算每个像素的颜色。

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Common({
		src: 'materials/atlas.png',
		filterMode: TextureFilterMode.TFM_BILINEAR,
	}),
})
```

## 无光照材质

大多数情况下，你会希望场景中的材质受光照条件影响，包括阴影，以及随着一天中不同时段的色调变化而改变颜色。但在其他情况下，你可能希望显示颜色的纯粹状态。这在播放视频时很有用，也适用于需要醒目突出、用于向玩家传达提示的抽象标记。

若要创建无光照材质，请使用 `Material.setBasicMaterial`。基础材质并不具备 PBR 材质的所有属性，只包含必要属性：

* `diffuseColor`：颜色的 Color4
* `texture`：纹理
* `alphaTexture`：用于透明度图层的独立纹理
* `alphaTest`：根据纹理颜色实现透明效果的阈值
* `castShadows`：若为 false，则不会向场景中的其他实体投射阴影。

```ts
Material.setBasicMaterial(screen, {
	diffuseColor: Color4.Red(),
})
```

## 头像

若要显示任意玩家的缩略头像，请在设置材质纹理时使用 `Material.Texture.Avatar` ，并传入现有玩家的地址。这会根据该玩家的 256x256 图像创建纹理，显示头部和肩部。玩家会穿着当前服务器最近一次记录的可穿戴物品。

```ts
Material.setPbrMaterial(myEntity, {
	texture: Material.Texture.Avatar({
		userId: '0x517....',
	}),
})
```

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-7d9533dc2cdb50a2250e230346b85e1b458c6cc3%2FavatarTexture.webp?alt=media)

你可以获取任意 Decentraland 玩家的头像，即使他们当前未连接，也即使他们没有已认领的 Decentraland 名称。

传入的对象支持以下属性：

* `userId`：要显示其个人资料的用户 ID
* `filterMode`：确定渲染时纹理像素的拉伸或压缩方式。该参数接受 `TextureFilterMode` 枚举中的值。请参阅 [纹理缩放](#texture-scaling).
* `wrapMode`：确定纹理如何平铺到对象上。该参数接受 `TextureWrapMode` 枚举。参见 [纹理环绕](#texture-wrapping).

## 透明材质

若要创建纯色透明材质，只需将颜色定义为 `Color4`，并将第 4 个值设为介于 *0* 和 *1*之间的数值。越接近 *1*，不透明度越高。

```typescript
let transparentRed = Color4.create(1, 0, 0, 0.5)

Material.setPbrMaterial(meshEntity, {
	albedoColor: transparentRed,
})
```

如果材质使用包含透明信息的 .png 纹理，默认情况下它会是不透明的；但你可以将 `transparencyMode` 设为 `MaterialTransparencyMode.MTM_ALPHA_BLEND`.

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-4cfaaf2d24f923ceb5187b0b2d5039ec049085bf%2Ftransparent-image.webp?alt=media)

```typescript
Material.setPbrMaterial(floor, {
	texture: Material.Texture.Common({
		src: 'assets/scene/transparent-image.png',
	}),
	transparencyMode: MaterialTransparencyMode.MTM_ALPHA_BLEND,
})
```

transparencyMode `transparencyMode` 可以设为以下值：

* `MaterialTransparencyMode.MTM_OPAQUE`：完全不透明
* `MaterialTransparencyMode.MTM_ALPHA_TEST`：根据阈值，每个像素要么完全不透明，要么完全透明。
* `MaterialTransparencyMode.MTM_ALPHA_BLEND`：根据每个像素的值，可以呈现中间透明度。
* `MaterialTransparencyMode.MTM_ALPHA_TEST_AND_ALPHA_BLEND`：结合使用这两种方法。
* `MaterialTransparencyMode.MTM_AUTO`：根据提供的纹理确定使用的方法。

{% hint style="warning" %}
**📔 注意**：如果希望显示纹理自身的 alpha 通道，请务必自行设置 `transparencyMode` 。在桌面客户端中，默认的 `MTM_AUTO` 模式会忽略纹理的 alpha 值，并且只在 `albedoColor` 的 alpha 小于 1 时进行混合，因此透明的 `.png` 最终会完全不透明。使用 `MTM_ALPHA_BLEND` 或 `MTM_ALPHA_TEST`，透明度为纹理的 alpha 值乘以 `albedoColor` alpha 值。
{% endhint %}

如果将 `transparencyMode` 设为 `MaterialTransparencyMode.MTM_ALPHA_TEST`，就可以微调用于判断每个像素是否透明的阈值。将 `alphaTest` 属性设为介于 *0* 和 *1*之间的值。默认值为 *0.5*.

```ts
// 使用 alpha 测试
Material.setPbrMaterial(meshEntity1, {
	texture: Material.Texture.Common({
		src: 'images/myTexture.png',
	}),
	transparencyMode: MaterialTransparencyMode.MTM_ALPHA_TEST,
	alphaTest: 1,
})
```

使用 [无光照材质](#unlit-materials)时，可以添加 `alphaTexture` ，根据纹理使材质的特定区域透明。

{% hint style="warning" %}
**📔 注意**：应将遮罩中材质需要显示的区域涂成白色，将需要隐藏的区域涂成黑色。客户端读取的是遮罩颜色通道的亮度，而非 alpha 通道，因此任意一个通道值满格都会被视为不透明：纯红色遮罩也会被视为不透明。不要将颜色纹理重复用作自身的遮罩，否则其中每个暗色像素都会变透明，导致轮廓和阴影消失。
{% endhint %}

![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-901568ee2ece2fed1734c93716d4c7069869c47c%2Fcircular-video-screen.webp?alt=media)

```ts
// 使用遮罩图像将屏幕裁剪成圆形
Material.setBasicMaterial(meshEntity1, {
	texture: Material.Texture.Common({
		src: 'images/myTexture.png',
	}),
	alphaTexture: Material.Texture.Common({
		src: 'assets/scene/circle_mask.png',
		wrapMode: TextureWrapMode.TWM_MIRROR,
	}),
})
```

关于桌面客户端中的 `alphaTexture` ，还有两点需要了解：

* **它仅适用于无光照材质。** `Material.setPbrMaterial` 接受 `alphaTexture` ，但不会使用它。对于 PBR 材质，请将透明度设在颜色纹理自身的 alpha 通道中，并改为设置 `transparencyMode` 。
* **不带 `alphaTexture` 的无光照材质完全不透明**，而且 `alphaTest` 对其不起作用。仅使用 `texture` 加上 `alphaTest` 时，透明像素会显示其颜色，通常为黑色。

这与视频配合使用时，可以实现非常有趣的效果。请参阅 [视频播放](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/video-playing.md).

## 播放视频

若要将 URL 中的视频流式传输到材质中，或播放场景中存储的文件里的视频，请参阅 [视频播放](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/video-playing.md).

视频会用作材质的纹理。你可以设置材质的其他任意属性，来调整视频画面的外观。

## 高级语法

创建 `Materials` 组件的完整语法（不使用任何简化语法的辅助函数）如下：

```ts
Material.create(myEntity, {
	material: {
		$case: 'pbr',
		pbr: {
			texture: {
				tex: {
					$case: 'texture',
					texture: {
						src: 'images/scene-thumbnail.png',
					},
				},
			},
		},
	},
})

Material.create(myEntity, {
	material: {
		$case: 'pbr',
		pbr: {
			texture: {
				tex: {
					$case: 'avatarTexture',
					avatarTexture: {
						userId: '0x517....',
					},
				},
			},
		},
	},
})
```

基础协议对 Materials 组件的解释方式如下。辅助函数对这些细节进行了封装，并提供更易用的语法，但在底层，它们输出的仍是这种语法。

这些 `$case` 字段用于指定一种允许的类型。每种类型支持不同的一组参数。此处有两个层级的 `$case` ：

* material `字段支持` 以下值： `pbr` 和 `unlit`，用于定义材质类型。
* 纹理中的 `tex` 字段支持以下值，用于定义纹理类型：
  * `texture`
  * `avatarTexture`
  * `videoTexture`

根据 `$case`的值，可以定义对应类型的对象，并传入相关属性。

若要向可能已包含该组件实例的实体添加 `Material` 组件，请使用 `Material.createOrReplace()`。像 `Material.setPbrMaterial()` 这样的辅助函数会处理覆盖已有组件实例的情况，但如果实体已经包含该组件，再运行 `Material.create()` 则会返回错误。

## 修改 glTF 材质

使用 `GltfNodeModifiers` 组件来修改以下对象的材质 *glTF* 模型。此组件允许你使用自己的材质覆盖 *glTF* 模型的材质。你可以使用 `Material` 组件的任何属性，包括纹理、视频纹理、无光照材质等。

使用 `GltfNodeModifiers` 组件有两种方式：

* 将 `path` 属性留空，以修改整个模型的材质。
* 将 `path` 属性设为节点路径，以修改模型中特定节点（或多个节点）的材质。

### 修改整个模型的材质

以下示例展示如何修改 *glTF* 模型的材质。在此示例中，整个模型的材质被改为红色。

```ts
import { GltfNodeModifiers, GltfContainer, Transform } from '@dcl/sdk/ecs'

const myEntity = engine.addEntity()

GltfContainer.create(myEntity, {
	src: 'models/myModel.glb',
})

Transform.create(myEntity, {
	position: Vector3.create(4, 0, 4),
})

GltfNodeModifiers.create(myEntity, {
	modifiers: [
		{
			path: '',
			material: {
				material: {
					$case: 'pbr',
					pbr: {
						albedoColor: Color4.Red(),
					},
				},
			},
		},
	],
})
```

GltfNodeModifiers `GltfNodeModifiers` 组件具有以下属性：

* `modifiers`：修饰器数组。每个修饰器具有以下属性：
  * `path`：模型中要修改的节点路径。
  * `material`：要使用的材质。

path `path` 属性是一个字符串，表示 *glTF* 模型中要修改的节点路径。若要修改整个模型的材质，可以使用空字符串。若要修改特定节点的材质，可以使用该节点的路径。此路径必须指向网格节点，而不是顶点节点。

{% hint style="info" %}
**💡 提示**：你可以使用 [Babylon Sandbox 应用](https://sandbox.babylonjs.com/) 检查 *glTF* 模型，并找到要修改节点的路径。

不过，在某些模型中，Babylon Sandbox 可能会列出属于顶点而非网格的路径，这些路径无法使用。如果尝试使用无效路径，场景控制台会显示一条错误消息，其中包含该模型所有有效路径的完整列表。
{% endhint %}

material `material` 属性是一个表示要使用材质的对象。它需要采用 [高级语法](#advanced-syntax) 来编写，如上例所示。诸如……之类的辅助函数 `Material.setPbrMaterial()` 不能在此处使用。

### 修改模型中特定节点的材质

以下示例展示了如何修改 *glTF* 模型中特定节点的材质。在此示例中，将头部的材质修改为使用备用纹理。

```ts
import { GltfNodeModifiers, GltfContainer, Transform } from '@dcl/sdk/ecs'

const myEntity = engine.addEntity()

GltfContainer.create(myEntity, {
	src: 'models/myModel.glb',
})

Transform.create(myEntity, {
	position: Vector3.create(4, 0, 4),
})

GltfNodeModifiers.create(myEntity, {
	modifiers: [
		{
			path: 'M_Head_BaseMesh',
			material: {
				material: {
					$case: 'pbr',
					pbr: {
						texture: Material.Texture.Common({
							src: 'assets/scene/images/blinking-head.png',
						}),
					},
				},
			},
		},
	],
})
```

A `GltfNodeModifiers` 可以包含多个修改器，每个修改器都用于修改模型中的不同节点。以下示例展示了如何修改 *glTF* 模型中头部和身体的材质。

```ts
import { GltfNodeModifiers, GltfContainer, Transform } from '@dcl/sdk/ecs'

const myEntity = engine.addEntity()

GltfContainer.create(myEntity, {
	src: 'models/myModel.glb',
})

Transform.create(myEntity, {
	position: Vector3.create(4, 0, 4),
})

GltfNodeModifiers.create(myEntity, {
	modifiers: [
		{
			path: 'M_Head_BaseMesh',
			material: {
				material: {
					$case: 'pbr',
					pbr: {
						albedoColor: Color4.Red(),
					},
				},
			},
		},
		{
			path: 'M_Body_BaseMesh',
			material: {
				material: {
					$case: 'pbr',
					pbr: {
						albedoColor: Color4.Blue(),
					},
				},
			},
		},
	],
})
```

### 修改现有材质的字段

Material 组件提供了一个简化接口，用于访问和修改 Material 组件属性。它无需深入遍历嵌套的联合结构（`PBR` 与 `Unlit`, `texture` 与 `avatarTexture` 与 `videoTexture`），让材质操作更加直观，也更不容易出错。

以下方法可轻松操作 `Material` 组件：

* `Material.getFlat(entity: Entity): ReadonlyFlatMaterial`：返回一个 **只读的** `FlatMaterial` 访问器对象，可直接读取材质属性。如果实体没有 `Material` 组件，则会返回错误。为避免这种情况，可以改用以下方法。

```ts
const src = Material.getFlat(entity).texture.src
```

* `Material.getFlatOrNull(entity: Entity): ReadonlyFlatMaterial | null`：返回一个 **只读对象或 null**，具体取决于实体是否具有 `Material` 组件。

```ts
const src = Material.getFlatOrNull(entity)?.texture.src
```

* `Material.getFlatMutable(entity: Entity): FlatMaterial`：返回一个 **可读写的** `FlatMaterial`对象，可用于修改其属性。如果调用该方法的实体没有 `Material` 组件，则会抛出错误。

```ts
const src = Material.getFlatMutable(entity).texture.src
```

* `Material.getFlatMutableOrNull(entity: Entity): FlatMaterial | null`：它会返回一个 **可读写对象或 null** `FlatMaterial` 对象，可用于修改其属性。如果实体没有 `Material component`，则会返回 `null`.

```ts
const flatMaterial = Material.getFlatMutableOrNull(entity)
if (flatMaterial) {
	flatMaterial.texture.src = myNewTextureFile
}
```

### 移除 glTF 模型的阴影

若要移除 *glTF* 模型的阴影，可以将 `castShadows` 属性设为 `false` ，在 `GltfNodeModifiers` 对象中进行设置。这样会保留模型的原始材质，但阻止其投射阴影。这适用于不应投射阴影的模型，例如光束。

```ts
import { GltfNodeModifiers } from '@dcl/sdk/ecs'

GltfNodeModifiers.create(myEntity, {
	modifiers: [
		{
			path: '',
			castShadows: false,
		},
	],
})
```

{% hint style="info" %}
**💡 提示**：材质中使用的纹理也可以应用于粒子效果。有关在粒子中使用自定义纹理和精灵图集的详情，请参阅 [粒子系统](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/particle-system.md) 。
{% endhint %}

{% hint style="info" %}
**💡 提示**：材质示例请参阅 [`52,-52-testing-gallery`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/52,-52-testing-gallery) 测试场景，它并排展示 PBR 金属度/粗糙度/自发光/法线贴图组合的扫掠效果； [`74,-8-gltfnodemodifier`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/74,-8-gltfnodemodifier)，它会覆盖各个 GLTF 节点上的 PBR 和非光照材质；以及 [`0,3-texture-movement`](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/0,3-texture-movement)，它会为纹理偏移和重复平铺添加动画。
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/materials.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
