Game Development Reference
In-Depth Information
Loading textures
Let's first understand a few important WebGL API functions before diving into
the code.
The
gl.pixelStorei
function sets pixel storage modes for
readPixels
and unpacks
textures with
texImage2D
and
texSubImage2D
. The
gl.pixelStorei
function is
declared as follows:
void gl.pixelStorei(GLenum pname, GLint param)
Let's see what each parameter of this function does:
•
pname
: This parameter specifies the pixel storage type; it must be either
gl.PACK_ALIGNMENT
,
gl.UNPACK_ALIGNMENT
, or
gl.UNPACK_FLIP_Y_WEBGL
•
param
: This parameter specifies the Boolean value for the pack or
unpack alignment
The
gl.pixelStorei
function is not used for a particular texture but is a global
setting for all textures used in our current graphics context. We will use this function
to flip the texture in our game, as shown in the following function call:
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
Normally, the texture coordinates in images start from the top-left corner. The
y
value
increases as we move downwards, but WebGL starts from the bottom-left corner and
the
y
value increases as we move upwards. The
gl.pixelStorei
function instructs
WebGL to store the image with the
y
coordinate flipped.
Our gaming application must bind the texture object to be able to operate on it. Once
the texture objects are bound, subsequent operations such as
gl.texImage2D
and
gl.texParameteri
affect the bound texture object. The following function makes the
specified texture the current texture for further operations:
void gl.bindTexture(target, GLuint texture)
Let's see what each parameter of this function does:
•
target
: This parameter binds the texture object to the texture target,
gl.TEXTURE_2D
or
gl.TEXTURE_CUBE_MAP
•
texture
: This parameter is the handle to the texture object
The primary function that is used for loading textures is
gl.texImage2D
. This
function is very powerful for the purpose of gaming, and is declared as follows:
void gl.texImage2D(target, level, internalFormat, format, type,
const void* pixels)