为webgl中的每个对象使用不同的顶点和片段着色器 [英] Using a different vertex and fragment shader for each object in webgl
问题描述
我在webgl中有一个包含多个对象的场景。对于每个对象,我想使用不同的顶点和片段着色器。我的第一个问题是,是否可以为每个对象设置着色器?我知道在opengl中是可能的。
I have a scene with multiple objects in webgl. For each object I want to use a different vertex and a fragment shader. My first question is, is it possible to have a shader for each object? I am aware it is possible in opengl.
这是我想到的类似伪代码。任何例子都将非常感激。
This is something similar pseudo code of what I had in mind. Any example would be much appreciated.
glenableshader
draw triangle
gldisableshader
glenableshader
draw square
gldisableshader
谢谢
推荐答案
您可以查找几乎任何WebGL示例并将其转换为多个着色器示例。
You can look up pretty much any WebGL example and turn it into a multiple shader example.
伪代码
// At init time
for each shader program
create and compile vertex shader
create and compile fragment shader
create program and attach shaders
link program
record locations of attributes and uniforms
for each model/set of geometry/points/data
create buffer(s) for model
copy data into buffer(s) for model
for each texture
create texture
usually asynchronously load textures
// at draw time
clear
for each model
useProgram(program for model)
setup attributes for model
setup textures for model
set uniforms for model
draw
这与使用1个着色器程序绘制1个模型没什么不同。只需进行相同的设置。
This is no different than drawing 1 model with 1 shader program. Just do the same setup.
多一点代码...
设置属性会看起来像什么喜欢
For setting up attributes would look something like
for each attribute used by model
gl.enableVertexAttribArray(attribLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, bufferWithDataForAttribute);
gl.vertexAttribPointer(attribLocation, ...);
设置纹理(可能)看起来有点谎言
Setting up textures (might) look something liek this
for each texture used by model
gl.activeTexture(gl.TEXTURE0 + ndx);
gl.bindTexture(gl.TEXTURE_2D, texture);
最后你要使用的程序
gl.useProgram(programForModel);
for each uniform
gl.uniform???(uniformLocation, uniformValue);
gl.drawArrays(...)
or
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferOfIndicesForModel);
gl.drawElements(...);
这篇关于为webgl中的每个对象使用不同的顶点和片段着色器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!