tri_engine.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import
  2. algorithm,
  3. tri_engine/config,
  4. tri_engine/gfx/gl/gl,
  5. tri_engine/gfx/gl/primitive,
  6. tri_engine/gfx/gl/shader,
  7. tri_engine/gfx/color
  8. const primitiveVs = """
  9. #version 330 core
  10. layout(location = 0) in vec2 pos;
  11. layout(location = 1) in vec2 texCoord;
  12. out vec2 uv;
  13. void main()
  14. {
  15. gl_Position = vec4(pos, 0, 1);
  16. uv = texCoord;
  17. }
  18. """
  19. const primitiveFs = """
  20. #version 330 core
  21. in vec2 uv;
  22. out vec4 color;
  23. uniform sampler2D tex;
  24. uniform vec4 inColor;
  25. void main()
  26. {
  27. color = texture(tex, uv) * inColor;
  28. }
  29. """
  30. var gW, gH: Natural = 0
  31. proc w*(): int =
  32. gW
  33. proc h*(): int =
  34. gH
  35. type
  36. PRenderer = ref object
  37. primitiveProgram: TProgram
  38. primitives: seq[PPrimitive]
  39. proc setupGL() =
  40. ?glEnable(GLblend)
  41. ?glBlendFunc(GLsrcAlpha, GLoneMinusSrcAlpha)
  42. ?glClearColor(0.0, 0.0, 0.0, 1.0)
  43. ?glPolygonMode(GLfrontAndBack, GLfill)
  44. proc newRenderer*(w, h: Positive): PRenderer =
  45. gW = w
  46. gH = h
  47. new(result)
  48. newSeq(result.primitives, 0)
  49. loadExtensions()
  50. setupGL()
  51. result.primitiveProgram = newProgram(@[
  52. newShaderFromSrc(primitiveVs, TShaderType.vert),
  53. newShaderFromSrc(primitiveFs, TShaderType.frag)])
  54. proc draw(o: PRenderer, p: PPrimitive) =
  55. let loc = proc(x: string): Glint =
  56. result = glGetUniformLocation(o.primitiveProgram.id, x)
  57. if result == -1:
  58. raise newException(E_GL, "Shader error: " & x & " does not correspond to a uniform variable")
  59. setUniformV4(loc("inColor"), p.color)
  60. ?glActiveTexture(GLtexture0)
  61. ?glBindTexture(GLtexture2D, p.tex.id.GLuint)
  62. ?glUniform1i(loc("tex"), 0)
  63. p.bindBufs()
  64. setVertAttribPointers()
  65. ?glDrawElements(p.vertMode.GLenum, p.indices.len.GLsizei, cGLunsignedShort, nil)
  66. proc draw*(o: PRenderer) =
  67. ?glClear(GLcolorBufferBit)
  68. o.primitiveProgram.use()
  69. enableVertAttribArrs()
  70. var zSortedPrimitives = o.primitives
  71. zSortedPrimitives.sort(proc(x, y: PPrimitive): int =
  72. if x.z < y.z:
  73. -1
  74. elif x.z > y.z:
  75. 1
  76. else:
  77. 0)
  78. for x in zSortedPrimitives:
  79. o.draw(x)
  80. disableVertAttribArrs()
  81. proc addPrimitive*(o: PRenderer, p: PPrimitive) =
  82. o.primitives.add(p)