Skip to content

Instantly share code, notes, and snippets.

@mlfarrell
Last active November 13, 2019 23:39
Show Gist options
  • Save mlfarrell/1d7597303e3a62e4e99c4d15a5ea02b5 to your computer and use it in GitHub Desktop.
Save mlfarrell/1d7597303e3a62e4e99c4d15a5ea02b5 to your computer and use it in GitHub Desktop.
#version 450
#define VGL_VULKAN
#extension GL_ARB_separate_shader_objects : enable
#define SPRITE_SCALE 0.200000
struct PerInstance
{
//.xyz are xyz pos in 3D
//abs(.w) is texture atlas x-shift
//sign(.w) can be -1 for h-flip
vec4 position;
float alpha, scale;
};
//Bilboard shader
//draw sprites in 3D from any angle
layout(location = 0) in vec4 position;
layout(location = 4) in vec2 texcoord0;
layout(location = 0) out OutBlock
{
vec2 varTexcoord;
flat float varDistanceToCamera;
float varAlpha;
};
const int MAX_TRANSFORMS = 512;
#ifdef VGL_VULKAN
#define gl_InstanceID gl_InstanceIndex
layout (std140, set = 1, binding = 16) uniform InstancedTransforms
{
PerInstance instanceData[MAX_TRANSFORMS];
};
#else
layout (std140) uniform InstancedTransforms
{
PerInstance instanceData[MAX_TRANSFORMS];
};
#endif
layout(set = 1, binding = 0) uniform sampler2D texture0;
layout(std140, set = 0, binding = 0) uniform UBO
{
uniform vec3 spriteSize;
uniform vec3 cameraPosition;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
};
mat4 rotationX(float angle)
{
return mat4(1.0, 0.0, 0.0 ,0.0,
0.0, cos(angle), -sin(angle), 0.0,
0.0, sin(angle), cos(angle), 0.0,
0.0, 0.0, 0.0, 1.0);
}
void main()
{
vec4 instancePos = instanceData[gl_InstanceID].position;
vec2 size = vec2(1.0/spriteSize.z, 1.0);
float flipped = sign(instancePos.w);
vec2 texCoord = texcoord0 * size + flipped*vec2(abs(instancePos.w), 0.0);
if(flipped < 0)
{
texCoord.x = size.x-texCoord.x;
}
varTexcoord = texCoord;
varAlpha = instanceData[gl_InstanceID].alpha;
mat4 translate = mat4(1.0);
translate[3] = vec4(instancePos.xyz, 1.0);
mat4 localModelViewMatrix = modelViewMatrix * translate;
#ifndef NO_BILBOARDING
mat4 mvBilboard = mat4(mat3(SPRITE_SCALE*instanceData[gl_InstanceID].scale));
mvBilboard[3] = localModelViewMatrix[3];
#else
mat4 rot = rotationX(radians(90));
mat4 mvBilboard = localModelViewMatrix * mat4(mat3(SPRITE_SCALE*instanceData[gl_InstanceID].scale)) * rot;
#endif
vec4 mvPos = (mvBilboard * ((position) * vec4(spriteSize.xy, 1.0, 1.0)));
//somewhat hacking this (tired of dealing with it)
varDistanceToCamera = length(cameraPosition-mvPos.xyz);// / (spriteSize.y/16.0);
gl_Position = projectionMatrix * mvPos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment