gfxfundamentals / webgl2-fundamentals

WebGL 2 lessons starting from the basics
https://webgl2fundamentals.org
BSD 3-Clause "New" or "Revised" License
1.74k stars 220 forks source link

vao usage in examples #44

Open kswope opened 5 years ago

kswope commented 5 years ago

I've already come across two examples where I can completely comment out the lines with vao and not change the running of the program at all.

https://webgl2fundamentals.org/webgl/lessons/webgl-fundamentals.html https://webgl2fundamentals.org/webgl/lessons/webgl-2d-translation.html

I'm just beginning with webgl, so I'm not sure whats going on, either VAOs aren't being used correctly, the newest browsers are filling in some missing parts, or the tutorial examples are written in a way that is completely uninstructive as to the use of vaos.

greggman commented 5 years ago

The reason you can take the lines out is because there is only one VAO in those samples. As soon as you have 2 VAOs you'd have to put the lines back. The samples are the way they are to show the normal case (more than 1 VAO) not the exceptional case (just 1 VAO)

The normal case is explained here

https://webgl2fundamentals.org/webgl/lessons/webgl-drawing-multiple-things.html

This is no different than a 2D sample. Let's say you wanted to draw a moving box in red. You could do this

 ctx.fillStyle = "red";
 render(time) {
     ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
     ctx.fillRect(150 * Math.sin(time * .001) + 150, 75);
     requestAnimationFrame(render);
}
requestAnimationFrame(render);

But setting the fillStyle outside the loop is not normal. So the sample would show something like

 render(time) {
     ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
     ctx.fillStyle = "red";
     ctx.fillRect(150 * Math.sin(time * .001) + 150, 75);
     requestAnimationFrame(render);
}
requestAnimationFrame(render);

Even though for such a small sample fillStyle only needs to be set once.

It's the same with VAOs. Because there happens to be just one you could only bind once. But that's not the normal case. Just like drawing just one thing in one color is not the normal case

 render(time) {
     ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
     ctx.fillStyle = "red";
     ctx.fillRect(150 * Math.sin(time * .001) + 150, 75);
     ctx.fillStyle = "blue";
     ctx.fillRect(150 * Math.sin(time * -.001) + 150, 75);
     requestAnimationFrame(render);
}
requestAnimationFrame(render);