问题
I'm working on implementing a fragment shader in WebGL, and came across the limitation of being able to only use constant expressions in for loops. Does anyone have any suitable workarounds for this?
In my specific case, I'm implementing a bilateral filter, and currently have a window size specified as a const in my fragment shader, but would like to be able to change this from JavaScript. Uniforms aren't considered constants and thus can't be used in a for loop, so I'm looking for some other way of implementing this.
The only thing I can think of is to read the shader source from JavaScript, parse it and replace the value of the const with the desired window size, then recompile the shader. This would work for my purpose, but I'd like to know if there's an easier way.
回答1:
If you want/need the ability to dynamically change your loop length you may use a for
loop counting to a very large number / infinity and break
once your limit is reached:
uniform int loopLimit;
for (int i = 0; i < 10000; i++) {
if (i == loopLimit) break;
// Do your stuff
}
来源:https://stackoverflow.com/questions/32529183/workaround-to-use-uniforms-or-similar-in-webgl-for-loops