纹理类型

基础纹理

HLSL
Texture1D tex1D; // 一维纹理
Texture2D tex2D; // 二维纹理
Texture3D tex3D; // 三维纹理
TextureCube texCube; // 立方体纹理
点击展开查看更多

数组纹理

HLSL
Texture2DArray tex2DArray;
float3 texCoord = float3(u, v, 2.0); // 索引2对应第3个纹理
float4 color = tex2DArray.Sample(sampler, texCoord);
点击展开查看更多

其他特殊纹理

纹理采样

HLSL 的纹理对象提供了多种采样方法,最常用的是Sample,其基本语法为:

HLSL
float4 Sample(
	SamplerState sampler,
	floatN texCoord,
	[int mipLevel],
	[float bias]
);
点击展开查看更多

其他采样函数

采样器状态 SamplerState

采样器定义了纹理采样的规则(过滤方式、寻址模式、比较函数等),在 DirectX10 + 中通过SamplerState对象声明,与纹理资源分离。 核心属性包括

HLSL
SamplerState anisotropicSampler {
	Filter = ANISOTROPIC;
	AddressU = WRAP;
	AddressV = WRAP;
	MaxAnisotropy = 16;
};
点击展开查看更多

示例

2D 纹理采样

HLSL
// 纹理与采样器声明
Texture2D diffuseTex;
SamplerState linearWrapSampler {
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};

// 像素着色器
float4 PS(float2 texCoord : TEXCOORD0) : SV_Target {
    // 采样2D纹理
    float4 diffuseColor = diffuseTex.Sample(linearWrapSampler, texCoord);
    return diffuseColor;
}
点击展开查看更多

立方体纹理采样(环境反射)

HLSL
TextureCube envMap;
SamplerState cubeSampler {
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = WRAP; // 立方体纹理坐标为方向向量,寻址模式通常不影响
    AddressV = WRAP;
    AddressW = WRAP;
};

float4 PS(float3 worldNormal : NORMAL, float3 worldPos : POSITION) : SV_Target {
    // 计算反射方向(假设视角方向为viewDir)
    float3 viewDir = normalize(cameraPos - worldPos);
    float3 reflectDir = reflect(-viewDir, worldNormal);
    
    // 采样环境贴图
    float4 reflectionColor = envMap.Sample(cubeSampler, reflectDir);
    return reflectionColor;
}
点击展开查看更多

版权声明

作者: Chaim

链接: https://chaim.eu.org/posts/%E7%BA%B9%E7%90%86/

许可证: CC BY-NC-SA 4.0

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Please attribute the source, use non-commercially, and maintain the same license.

开始搜索

输入关键词搜索文章内容

↑↓
ESC
⌘K 快捷键