OpenGL point sprites rotation in fragment shader

前端 未结 3 1555
感动是毒
感动是毒 2021-02-04 20:17

I\'m following this tutorial to learn something more about OpenGL and in particular point sprites. But I\'m stuck on one of the exercises at the end of the page:

3条回答
  •  终归单人心
    2021-02-04 20:56

    The traditional method is to pass a matrix to the shader, whether vertex or fragment. If you don't know how to fill in a rotation matrix, Google and Wikipedia can help.

    The main thing is that you're going to run into is the simple fact that a 2D rotation is not enough. gl_PointCoord goes from [0, 1]. A pure rotation matrix rotates around the origin, which is the bottom-left in point-coord space. So you need more than a pure rotation matrix.

    You need a 3x3 matrix, which has part rotation and part translation. This matrix should be generated as follows (using GLM for math stuff):

    glm::mat4 currMat(1.0f);
    currMat = glm::translate(currMat, glm::vec3(0.5f, 0.5f, 0.0f));
    currMat = glm::rotate(currMat, angle, glm::vec3(0.0f, 0.0f, 1.0f));
    currMat = glm::translate(currMat, glm::vec3(-0.5f, -0.5f, 0.0f));
    

    You then pass currMat to the shader as a 4x4 matrix. Your shader does this:

    vec2 texCoord = (rotMatrix * vec4(gl_PointCoord, 0, 1)).xy
    gl_FragColor = texture2D(texture, texCoord) * f_color;
    

    I'll leave it as an exercise for you as to how to move the translation from the fourth column into the third, and how to pass it as a 3x3 matrix. Of course, in that case, you'll do vec3(gl_PointCoord, 1) for the matrix multiply.

提交回复
热议问题