Search code examples
c++qtopengltexturestexture-mapping

Looping a texture on a surface


I want to know how to loop a texture on the surface of an object.

For a practical example, I'm trying to handle rendering world geometry, so that when I resize a world object twice the size of its texture, the texture will then appear twice - not double in size.

Is there any proper way to handle this? The only thing I can think of would be to physically create a brand new texture which is of the right size and manually copied X amount of times, but that sounds like it would eat up a lot of memory really quickly.

Here's a picture showing what I'm looking for, when resizing a plane on the XAxis:

example

Along with many other variables, I pass an object's UVMap to my shader as the "texture coordinate", and then I perform the following for rendering an object's texture prior to the draw arrays call:

QImage image;
image = worldObject->getQImage(i); //Within a for loop, grabs the right texture if the object has differing textures per face of object

glBindTexture(GL_TEXTURE_2D, spot);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.bits());

Solution

  • This is very easy to do. Where you currently use texture coordinates in the range [0.0, 1.0], you simply use a bigger range. For example, to repeat the texture twice, as shown in your example, you specify texture coordinates in the range [0.0, 2.0].

    This works in combination with using GL_REPEAT for the texture wrap mode:

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    

    These values are actually the default, so there's no need to set them if you did not set them to a different value earlier.

    This specifies that the texture should be repeated for texture coordinates outside the [0.0, 1.0] range. For example, texture coordinates between 1.0 and 2.0 will be equivalent to the coordinates between 0.0 and 1.0, repeating the whole texture.