Get accurate integer modulo in WebGL shader

喜夏-厌秋 提交于 2019-12-04 08:17:12

You're not modding 7 by 7 you're modding 7/15ths by 7/15ths

Try

gl_FragColor = vec4(mod(
  floor(v_texCoord[0] * 15.),
  floor(v_texCoord[1] * 15.)
) / 15., 0, 0, 1);

You can see the 2 versions running here

function render(num) {
  var gl = document.getElementById("c" + num).getContext("webgl");
  var programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);

  var arrays = {
    position: [-1, -1, 0, 1, -1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, 1, 0],
  };
  var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);

  var uniforms = {
    resolution: [gl.canvas.width, gl.canvas.height],
    intMod: num == 1,
  };

  gl.useProgram(programInfo.program);
  twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
  twgl.setUniforms(programInfo, uniforms);
  twgl.drawBufferInfo(gl, bufferInfo);
}

render(0)
render(1);
canvas { margin: 1em; height: 100px; width: 150px; }
div { display: inline-block; }
pre { text-align: center; }
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>
  <script id="vs" type="notjs">
attribute vec4 position;

void main() {
  gl_Position = position;
}
  </script>
  <script id="fs" type="notjs">
precision mediump float;

uniform vec2 resolution;
uniform bool intMod;

void main() {
  vec2 v_texCoord = gl_FragCoord.xy / resolution.xy;

  if (!intMod) {
  
    gl_FragColor = vec4(mod(
      float(int(v_texCoord[0]*15.))/15.,
      float(int(v_texCoord[1]*15.))/15.
    ), 0, 0, 1);

  } else {

    gl_FragColor = vec4(mod(
      floor(v_texCoord[0]*15.),
      floor(v_texCoord[1]*15.)
    )/15., 0, 0, 1);
    
  }
  
}
  </script>
<div><canvas id="c0"></canvas><pre>mod with fractions</pre></div>
<div><canvas id="c1"></canvas><pre>mod with ints</pre></div>

You should also note that mod by 0 is undefined meaning you'll get different results on different GPUs

Here is a GLSL function that calculates MOD accurately with (float) parameters that should be integers:

/**
 * Returns accurate MOD when arguments are approximate integers.
 */
float modI(float a,float b) {
    float m=a-floor((a+0.5)/b)*b;
    return floor(m+0.5);
}

Please note, if a<0 and b>0 then the return value will be >=0, unlike other languages' % operator.

Note that since webGL2, we now have int operations so this problem is now trivially solve by x % y .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!