billboarding vertices in the vertex shader

前端 未结 2 1577
别那么骄傲
别那么骄傲 2021-01-03 00:57

Code demonstrating issue (comment/uncomment out the gl_Position lines in the vertex shader)

2条回答
  •  长情又很酷
    2021-01-03 01:50

    It is also worth looking at how it is done in Three.js and their SpriteMaterial: sprite_vert.glsl

    Here is an annotated snippet:

    // optional: pass 2D rotation angle as an uniform
    uniform float rotation;
    // optional: pass 2D center point as an uniform
    uniform vec2 center;
    
    // optional: use this define to scale the model according to distance from the camera
    #define USE_SIZEATTENUATION
    
    // [skipped includes]
    
    void main() {
        // discard rotation and scale
        vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );
    
        // extract model's scale
        vec2 scale;
        scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );
        scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );
    
        // if not defined, keep model the same size regardless of distance from the camera
        #ifndef USE_SIZEATTENUATION
            bool isPerspective = isPerspectiveMatrix( projectionMatrix );
            if ( isPerspective ) scale *= - mvPosition.z;
        #endif
    
        // if center is not passed as uniform, create vec2 center = vec2(0.0);
    
        // aligned with the camera [and scaled]
        vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
    
        // if rotation is not passed as uniform, skip the next block
    
        // rotate 2D
        vec2 rotatedPosition;
        rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
        rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
    
        // billboard
        mvPosition.xy += rotatedPosition;
    
        gl_Position = projectionMatrix * mvPosition;
    
        // [skipped includes]
    }
    

提交回复
热议问题