Avoid CPU side conversion with texImage2D in Firefox

前端 未结 1 1694
梦毁少年i
梦毁少年i 2021-01-13 00:44

Whenever I use textures in webgl Firefox (Firefox Developer Edition 50.0a2 for OSX, to be excact) outputs these warnings in the console:

Error: WebGL:

1条回答
  •  爱一瞬间的悲伤
    2021-01-13 01:39

    Your sample doesn't print warnings in firefox 48 on OSX so I can only guess but

    A 2D canvas uses premultiplied alpha. WebGL, by default, uses un-premultipled alpha for textures. That means in order to transfer the contents of the canvas texture it has to be converted to premultiplied alpha which depending on how that's implemented could be slow.

    If you don't need un-premultiplied alpha in your texture then you can tell WebGL you want premultiplied data when called texImage2D and texSubImage2D by calling gl.pixelStorei and tell it like this

    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
    

    In this case the browser can possibly just use the canvas data as is. This might make the warning go away. Note if you're just uploading once you probably shouldn't care. If you're uploading every frame then maybe you should.

    Be aware though that gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); effects ALL texture uploads including raw data. For example

    gl.texImage2D(
        gl.TEXTURE_2D, 0, gl.RGBA, 
        1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, 
        new Uint8Array([128, 192, 255, 128]));
    

    if UNPACK_PREMULTIPLY_ALPHA_WEBGL is true the browser will do the premultiplication before uploading the texture so [255, 255, 255, 128] will become [64, 96, 128, 128].

    UNPACK_FLIP_Y_WEBGL might also affect upload speeds depending on how it's implemented in the browser.

    0 讨论(0)
提交回复
热议问题