main.lua 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. -- Grid shader from https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
  2. -- Compared to the simpler Grid example, this example:
  3. -- * Supports custom line widths
  4. -- * Has world-space lines instead of lines that are always the same thickness
  5. -- * Has better antialiasing, especially at the horizon
  6. function lovr.load()
  7. shader = lovr.graphics.newShader([[
  8. out vec2 scale;
  9. vec4 lovrmain() {
  10. scale = vec2(length(Transform[0]), length(Transform[1]));
  11. return DefaultPosition;
  12. }
  13. ]], [[
  14. uniform float lineWidth;
  15. uniform vec3 background;
  16. uniform vec3 foreground;
  17. in vec2 scale;
  18. vec4 lovrmain() {
  19. vec2 uv = (UV - 1.) * scale;
  20. vec4 uvDDXY = vec4(dFdx(uv), dFdy(uv));
  21. vec2 uvDeriv = vec2(length(uvDDXY.xz), length(uvDDXY.yw));
  22. vec2 drawWidth = clamp(vec2(lineWidth), uvDeriv, vec2(.5));
  23. vec2 lineAA = uvDeriv * 1.5;
  24. vec2 gridUV = 1.0 - abs(fract(uv) * 2. - 1.);
  25. vec2 grid2 = smoothstep(lineWidth + lineAA, lineWidth - lineAA, gridUV);
  26. grid2 *= clamp(lineWidth / drawWidth, 0., 1.);
  27. grid2 = mix(grid2, vec2(lineWidth), clamp(uvDeriv * 2. - 1., 0., 1.));
  28. float grid = mix(grid2.x, 1., grid2.y);
  29. vec3 rgb = mix(gammaToLinear(background), gammaToLinear(foreground), grid);
  30. return vec4(rgb, 1.);
  31. }
  32. ]])
  33. end
  34. function lovr.draw(pass)
  35. pass:setShader(shader)
  36. pass:send('lineWidth', .005)
  37. pass:send('background', { .05, .05, .05 })
  38. pass:send('foreground', { .5, .5, .5 })
  39. pass:plane(0, 0, 0, 200, 200, -math.pi / 2, 1, 0, 0)
  40. end