A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

shaders.cc 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "shaders.h"
  2. namespace Cygnet::Shaders {
  3. const char *spriteVx = R"glsl(
  4. #define TILE_SIZE 32.0
  5. uniform mat3 camera;
  6. uniform mat3 transform;
  7. uniform vec3 frameInfo; // frame height, frame count, frame index
  8. attribute vec2 vertex;
  9. varying vec2 v_texCoord;
  10. void main() {
  11. // Here, I'm basically treating 1/(TILE_SIZE*16) as half the size of a "pixel".
  12. // It's just an arbitrary small number, but it works as an offset to make sure
  13. // neighbouring parts of the atlas don't bleed into the frame we actually
  14. // want to draw due to (nearest neighbour) interpolation.
  15. float pixoffset = (1.0 - vertex.y * 2.0) / (frameInfo.x * TILE_SIZE * 16.0);
  16. v_texCoord = vec2(
  17. vertex.x,
  18. (frameInfo.x * frameInfo.z + (frameInfo.x * vertex.y)) /
  19. (frameInfo.x * frameInfo.y) + pixoffset);
  20. vec3 pos = camera * transform * vec3(vertex, 1);
  21. gl_Position = vec4(pos.xy, 0, 1);
  22. }
  23. )glsl";
  24. const char *spriteFr = R"glsl(
  25. precision mediump float;
  26. varying vec2 v_texCoord;
  27. uniform sampler2D tex;
  28. void main() {
  29. gl_FragColor = texture2D(tex, v_texCoord);
  30. }
  31. )glsl";
  32. const char *chunkVx = R"glsl(
  33. uniform mat3 camera;
  34. uniform vec2 pos;
  35. attribute vec2 vertex;
  36. varying vec2 v_tileCoord;
  37. void main() {
  38. vec3 pos = camera * vec3(pos + vertex, 1);
  39. gl_Position = vec4(pos.xy, 0, 1);
  40. v_tileCoord = vec2(vertex.x, vertex.y);
  41. }
  42. )glsl";
  43. const char *chunkFr = R"glsl(
  44. precision mediump float;
  45. #define TILE_SIZE 32.0
  46. #define CHUNK_WIDTH 64
  47. #define CHUNK_HEIGHT 64
  48. varying vec2 v_tileCoord;
  49. uniform sampler2D tileAtlas;
  50. uniform vec2 tileAtlasSize;
  51. uniform sampler2D tiles;
  52. void main() {
  53. vec2 tilePos = floor(vec2(v_tileCoord.x, v_tileCoord.y));
  54. vec4 tileColor = texture2D(tiles, tilePos / vec2(CHUNK_WIDTH, CHUNK_HEIGHT));
  55. float tileID = floor((tileColor.r * 256.0 + tileColor.a) * 256.0);
  56. // 1/(TILE_SIZE*16) plays the same role here as in the sprite vertex shader.
  57. vec2 offset = v_tileCoord - tilePos;
  58. vec2 pixoffset = (1.0 - offset * 2.0) / (TILE_SIZE * 16.0);
  59. vec2 atlasPos = vec2(
  60. pixoffset.x + tileID + offset.x,
  61. pixoffset.y + floor(tileID / tileAtlasSize.x) + offset.y);
  62. gl_FragColor = texture2D(tileAtlas, atlasPos / tileAtlasSize);
  63. }
  64. )glsl";
  65. }