WebGPU 纹理
前言
这是 WebGPU 系列里讲“怎么给着色器喂数据”的第五篇,这次的主角是纹理(Texture)。纹理在 WebGPU 里不只是贴 2D 图,它靠硬件采样器(Sampler)做过滤和插值,这才是它真正好用的地方。下面从基础概念讲到采样、过滤模式、Mipmap 生成,再到纹理类型和格式,核心代码片段都留着,方便你上手。
纹理基础:为什么需要纹理?
纹理一般就是一张 2D 图,本质是个 2D 颜色数组。拿存储缓冲区(Storage Buffer)也能模拟,但纹理有个特别之处:它能被采样器(Sampler)这块专用硬件访问。采样器一次能读纹理里最多 16 个值,再按过滤设置混一混,缩放、平滑显示这类常见需求都很快。
纹理坐标
采样时纹理坐标(UV 坐标)是归一化的,范围 0.0 到 1.0,跟纹理实际尺寸无关。坐标 (0,0) 对应纹理数据的第一个纹素(texel),一般在左下角(看数据怎么排)。
简单示例:绘制带纹理的四边形
把之前的三角形例子改成四边形(两个三角形),在着色器里采样纹理:
struct OurVertexShaderOutput {
@builtin(position) position: vec4f,
@location(0) texcoord: vec2f,
};
@vertex fn vs(
@builtin(vertex_index) vertexIndex : u32
) -> OurVertexShaderOutput {
let pos = array(
// 第一个三角形
vec2f( 0.0, 0.0), // 中心
vec2f( 1.0, 0.0), // 右中
vec2f( 0.0, 1.0), // 中上
// 第二个三角形
vec2f( 0.0, 1.0), // 中上
vec2f( 1.0, 0.0), // 右中
vec2f( 1.0, 1.0), // 右上
);
var vsOutput: OurVertexShaderOutput;
let xy = pos[vertexIndex];
vsOutput.position = vec4f(xy, 0.0, 1.0);
vsOutput.texcoord = xy;
return vsOutput;
}
@group(0) @binding(0) var ourSampler: sampler;
@group(0) @binding(1) var ourTexture: `texture_2d<f32>`;
@fragment fn fs(fsInput: OurVertexShaderOutput) -> @location(0) vec4f {
return textureSample(ourTexture, ourSampler, fsInput.texcoord);
}
⚠️ 注意:这里图省事,直接把裁剪空间位置当纹理坐标用了。真做项目时,纹理坐标一般走顶点缓冲区传进来。
纹理数据与创建
创建一个 5x7 纹素的纹理
const kTextureWidth = 5;
const kTextureHeight = 7;
const _ = [255, 0, 0, 255]; // 红
const y = [255, 255, 0, 255]; // 黄
const b = [0, 0, 255, 255]; // 蓝
const textureData = new Uint8Array(
[
b,
_,
_,
_,
_,
_,
y,
y,
y,
_,
_,
y,
_,
_,
_,
_,
y,
y,
_,
_,
_,
y,
_,
_,
_,
_,
y,
_,
_,
_,
_,
_,
_,
_,
_,
].flat(),
);
创建 GPUTexture 对象
格式用 rgba8unorm,意思是每个通道 8 位无符号归一化整数,着色器里会自动转成 [0.0, 1.0] 的浮点值。
const texture = device.createTexture({
size: [kTextureWidth, kTextureHeight],
format: "rgba8unorm",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
device.queue.writeTexture(
{ texture },
textureData,
{ bytesPerRow: kTextureWidth * 4 },
{ width: kTextureWidth, height: kTextureHeight },
);
创建采样器并绑定
const sampler = device.createSampler();
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: sampler },
{ binding: 1, resource: texture },
],
});
过滤模式:magFilter 与 minFilter
采样器能配不同的过滤模式,纹理放大或缩小时算颜色的方式就不一样。
magFilter(放大过滤)
纹理被放大显示时,采样器默认用 nearest(最近邻),也能设成 linear(线性插值)。线性插值会取周围 4 个纹素,按纹理坐标的小数部分混一下,出来更平滑。
const sampler = device.createSampler({
magFilter: "linear",
addressModeU: "repeat",
addressModeV: "repeat",
});
minFilter(缩小过滤)
纹理被缩小时如果还用 linear,只取 4 个纹素混合,闪烁和颜色跳动会很厉害。解法是上 Mipmap。
Mipmap:解决缩小闪烁的关键
Mipmap(多级渐远纹理)是一串逐级缩小的纹理,每一级都是上一级的一半(向下取整),颜色提前混好。纹理缩小时,GPU 会按实际绘制尺寸挑合适的 Mip 级别,单次采样那种闪烁就没了。
生成 Mipmap 的示例代码
const lerp = (a, b, t) => a + (b - a) * t;
const mix = (a, b, t) => a.map((v, i) => lerp(v, b[i], t));
const bilinearFilter = (tl, tr, bl, br, t1, t2) => {
const t = mix(tl, tr, t1);
const b = mix(bl, br, t1);
return mix(t, b, t2);
};
const createNextMipLevelRgba8Unorm = ({
data: src,
width: srcWidth,
height: srcHeight,
}) => {
const dstWidth = Math.max(1, (srcWidth / 2) | 0);
const dstHeight = Math.max(1, (srcHeight / 2) | 0);
const dst = new Uint8Array(dstWidth * dstHeight * 4);
const getSrcPixel = (x, y) => {
const offset = (y * srcWidth + x) * 4;
return src.subarray(offset, offset + 4);
};
for (let y = 0; y < dstHeight; ++y) {
for (let x = 0; x < dstWidth; ++x) {
const u = (x + 0.5) / dstWidth;
const v = (y + 0.5) / dstHeight;
const au = u * srcWidth - 0.5;
const av = v * srcHeight - 0.5;
const tx = au | 0;
const ty = av | 0;
const t1 = au % 1;
const t2 = av % 1;
const tl = getSrcPixel(tx, ty);
const tr = getSrcPixel(tx + 1, ty);
const bl = getSrcPixel(tx, ty + 1);
const br = getSrcPixel(tx + 1, ty + 1);
const dstOffset = (y * dstWidth + x) * 4;
dst.set(bilinearFilter(tl, tr, bl, br, t1, t2), dstOffset);
}
}
return { data: dst, width: dstWidth, height: dstHeight };
};
const generateMips = (src, srcWidth) => {
const srcHeight = src.length / 4 / srcWidth;
let mip = { data: src, width: srcWidth, height: srcHeight };
const mips = [mip];
while (mip.width > 1 || mip.height > 1) {
mip = createNextMipLevelRgba8Unorm(mip);
mips.push(mip);
}
return mips;
};
创建带 Mipmap 的纹理
const mips = generateMips(textureData, kTextureWidth);
const texture = device.createTexture({
label: "yellow F on red",
size: [mips[0].width, mips[0].height],
mipLevelCount: mips.length,
format: "rgba8unorm",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
mips.forEach(({ data, width, height }, mipLevel) => {
device.queue.writeTexture(
{ texture, mipLevel },
data,
{ bytesPerRow: width * 4 },
{ width, height },
);
});
mipmapFilter:Mip 级别之间的过渡
除了 magFilter 和 minFilter,还有个 mipmapFilter,管的是 Mip 级别切换时怎么过渡。设成 linear,GPU 会从相邻两个 Mip 级别各采一次再混,过渡更顺,3D 场景里的远景平面特别吃这个。
示例:画 8 个不同过滤组合的平面,一眼就能看出差别。
const sampler = device.createSampler({
addressModeU: "repeat",
addressModeV: "repeat",
magFilter: i & 1 ? "linear" : "nearest",
minFilter: i & 2 ? "linear" : "nearest",
mipmapFilter: i & 4 ? "linear" : "nearest",
});
纹理类型与视图
WebGPU 有三种基础纹理类型:
| 类型 | 说明 |
|---|---|
"1d" | 一维纹理,高度和深度固定为 1 |
"2d" | 二维纹理,最常用 |
"3d" | 三维纹理,可看成多个 2D 纹理堆起来 |
纹理视图(Texture View)能玩的花样更多:
"2d"纹理可以有"2d-array"、"cube"、"cube-array"视图"1d"和"3d"纹理只能有同维度视图- 立方体纹理(Cube Map)常拿来当天空盒、环境映射
在 WGSL 中,纹理类型与视图维度对应:
| 视图维度 | WGSL 类型 |
|---|---|
"1d" | texture_1d 或 texture_storage_1d |
"2d" | texture_2d、texture_storage_2d、texture_multisampled_2d 等 |
"2d-array" | texture_2d_array、texture_storage_2d_array |
"3d" | texture_3d、texture_storage_3d |
"cube" | texture_cube、texture_depth_cube |
"cube-array" | texture_cube_array、texture_depth_cube_array |
纹理格式概览
WebGPU 的纹理格式挺多,命名规则像 rgba8unorm、rg16float、rg11b10ufloat 这样:字母是通道(r/g/b/a),数字是每通道位数,后缀是数据类型:
unorm:无符号归一化(0 → 1)snorm:有符号归一化(-1 → +1)uint:无符号整数sint:有符号整数float:浮点数
有些格式得靠特殊特性支持(比如 float32-filterable),WGSL 里的采样器类型也得跟格式对上(texture_2d<f32>、texture_2d<i32>、texture_2d<u32>)。
关键的三点
-
用 Mipmap 解决纹理缩小闪烁
纹理被缩小时,一定得生成 Mipmap,再设上minFilter: 'linear'(或者再配上mipmapFilter: 'linear'),不然颜色跳动和视觉噪点很扎眼。Mipmap 提前把各级颜色混好了,GPU 挑级别、做级别间过渡都方便。 -
过滤模式要按性能和画质权衡
全设linear最平滑,但采样一次要读 8 个纹素(2D 纹理),nearest只读 1 个。像素风游戏或者对性能敏感的场景,最好先用nearest;需要平滑缩放就上linear+ Mipmap。 -
纹理格式和采样器得看硬件能力挑
有些格式(比如rgba32float)默认不能过滤,除非开float32-filterable。移动端 32 位浮点纹理过滤经常没有,所以尽量用rgba16float、rgba8unorm这种通用格式。另外 WGSL 里纹理泛型参数(<f32>、<i32>、<u32>)必须跟格式对上。
术语对照
文中这些术语在 GLSL/WebGL 里都有对应概念,怕混淆的话对着看:
| WebGPU / WGSL 术语 | GLSL / WebGL 对应术语 | 说明 |
|---|---|---|
texture_2d<f32> | sampler2D | 二维纹理对象 |
sampler | sampler(在 GLSL 中通常与纹理绑定,但概念相同) | 采样器,定义过滤和寻址模式 |
textureSample() | texture() 或 texture2D() | 纹理采样函数 |
magFilter / minFilter | GL_TEXTURE_MAG_FILTER / GL_TEXTURE_MIN_FILTER | 放大/缩小过滤模式 |
nearest / linear | GL_NEAREST / GL_LINEAR | 最近邻 / 线性插值 |
mipmapFilter | GL_TEXTURE_MIN_FILTER 中的 GL_LINEAR_MIPMAP_LINEAR 等 | Mipmap 过滤 |
addressModeU/V (repeat, clamp-to-edge) | GL_REPEAT, GL_CLAMP_TO_EDGE | 纹理坐标包裹模式 |
rgba8unorm | GL_RGBA8 | 纹理内部格式 |
mipLevelCount | glGenerateMipmap() 后自动生成 | Mipmap 级别数量 |
GPUTextureUsage.RENDER_ATTACHMENT | gl.framebufferTexture2D() | 渲染到纹理 |
在 GLSL 里采样器通常直接跟纹理绑在一起,WebGPU/WGSL 里纹理和采样器是两个独立资源,走绑定组分开绑。这样采样器能复用,过滤行为也好精确控制。
总结
这篇把 WebGPU 纹理的基础概念和采样机制过了一遍,包括纹理数据创建、过滤模式、Mipmap 生成、纹理类型与视图、纹理格式。采样器和纹理格式配对好了,在 WebGPU 里做高质量渲染就不难。后面还会聊图像导入、视频纹理、立方体贴图这些进阶话题。
