OpenGlContent.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Numerics;
  6. using System.Runtime.InteropServices;
  7. using Avalonia;
  8. using Avalonia.OpenGL;
  9. using static Avalonia.OpenGL.GlConsts;
  10. // ReSharper disable StringLiteralTypo
  11. namespace ControlCatalog.Pages.OpenGl;
  12. internal class OpenGlContent
  13. {
  14. private int _vertexShader;
  15. private int _fragmentShader;
  16. private int _shaderProgram;
  17. private int _vertexBufferObject;
  18. private int _indexBufferObject;
  19. private int _vertexArrayObject;
  20. private GlVersion GlVersion;
  21. private string GetShader(bool fragment, string shader)
  22. {
  23. var version = (GlVersion.Type == GlProfileType.OpenGL
  24. ? RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 150 : 120
  25. : 100);
  26. var data = "#version " + version + "\n";
  27. if (GlVersion.Type == GlProfileType.OpenGLES)
  28. data += "precision mediump float;\n";
  29. if (version >= 150)
  30. {
  31. shader = shader.Replace("attribute", "in");
  32. if (fragment)
  33. shader = shader
  34. .Replace("varying", "in")
  35. .Replace("//DECLAREGLFRAG", "out vec4 outFragColor;")
  36. .Replace("gl_FragColor", "outFragColor");
  37. else
  38. shader = shader.Replace("varying", "out");
  39. }
  40. data += shader;
  41. return data;
  42. }
  43. private string VertexShaderSource => GetShader(false, @"
  44. attribute vec3 aPos;
  45. attribute vec3 aNormal;
  46. uniform mat4 uModel;
  47. uniform mat4 uProjection;
  48. uniform mat4 uView;
  49. varying vec3 FragPos;
  50. varying vec3 VecPos;
  51. varying vec3 Normal;
  52. uniform float uTime;
  53. uniform float uDisco;
  54. void main()
  55. {
  56. float discoScale = sin(uTime * 10.0) / 10.0;
  57. float distortionX = 1.0 + uDisco * cos(uTime * 20.0) / 10.0;
  58. float scale = 1.0 + uDisco * discoScale;
  59. vec3 scaledPos = aPos;
  60. scaledPos.x = scaledPos.x * distortionX;
  61. scaledPos *= scale;
  62. gl_Position = uProjection * uView * uModel * vec4(scaledPos, 1.0);
  63. FragPos = vec3(uModel * vec4(aPos, 1.0));
  64. VecPos = aPos;
  65. Normal = normalize(vec3(uModel * vec4(aNormal, 1.0)));
  66. }
  67. ");
  68. private string FragmentShaderSource => GetShader(true, @"
  69. varying vec3 FragPos;
  70. varying vec3 VecPos;
  71. varying vec3 Normal;
  72. uniform float uMaxY;
  73. uniform float uMinY;
  74. uniform float uTime;
  75. uniform float uDisco;
  76. //DECLAREGLFRAG
  77. void main()
  78. {
  79. float y = (VecPos.y - uMinY) / (uMaxY - uMinY);
  80. float c = cos(atan(VecPos.x, VecPos.z) * 20.0 + uTime * 40.0 + y * 50.0);
  81. float s = sin(-atan(VecPos.z, VecPos.x) * 20.0 - uTime * 20.0 - y * 30.0);
  82. vec3 discoColor = vec3(
  83. 0.5 + abs(0.5 - y) * cos(uTime * 10.0),
  84. 0.25 + (smoothstep(0.3, 0.8, y) * (0.5 - c / 4.0)),
  85. 0.25 + abs((smoothstep(0.1, 0.4, y) * (0.5 - s / 4.0))));
  86. vec3 objectColor = vec3((1.0 - y), 0.40 + y / 4.0, y * 0.75 + 0.25);
  87. objectColor = objectColor * (1.0 - uDisco) + discoColor * uDisco;
  88. float ambientStrength = 0.3;
  89. vec3 lightColor = vec3(1.0, 1.0, 1.0);
  90. vec3 lightPos = vec3(uMaxY * 2.0, uMaxY * 2.0, uMaxY * 2.0);
  91. vec3 ambient = ambientStrength * lightColor;
  92. vec3 norm = normalize(Normal);
  93. vec3 lightDir = normalize(lightPos - FragPos);
  94. float diff = max(dot(norm, lightDir), 0.0);
  95. vec3 diffuse = diff * lightColor;
  96. vec3 result = (ambient + diffuse) * objectColor;
  97. gl_FragColor = vec4(result, 1.0);
  98. }
  99. ");
  100. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  101. private struct Vertex
  102. {
  103. public Vector3 Position;
  104. public Vector3 Normal;
  105. }
  106. private readonly Vertex[] _points;
  107. private readonly ushort[] _indices;
  108. private readonly float _minY;
  109. private readonly float _maxY;
  110. public OpenGlContent()
  111. {
  112. var name = typeof(OpenGlPage).Assembly.GetManifestResourceNames().First(x => x.Contains("teapot.bin"));
  113. using (var sr = new BinaryReader(typeof(OpenGlPage).Assembly.GetManifestResourceStream(name)!))
  114. {
  115. var buf = new byte[sr.ReadInt32()];
  116. sr.Read(buf, 0, buf.Length);
  117. var points = new float[buf.Length / 4];
  118. Buffer.BlockCopy(buf, 0, points, 0, buf.Length);
  119. buf = new byte[sr.ReadInt32()];
  120. sr.Read(buf, 0, buf.Length);
  121. _indices = new ushort[buf.Length / 2];
  122. Buffer.BlockCopy(buf, 0, _indices, 0, buf.Length);
  123. _points = new Vertex[points.Length / 3];
  124. for (var primitive = 0; primitive < points.Length / 3; primitive++)
  125. {
  126. var srci = primitive * 3;
  127. _points[primitive] = new Vertex
  128. {
  129. Position = new Vector3(points[srci], points[srci + 1], points[srci + 2])
  130. };
  131. }
  132. for (int i = 0; i < _indices.Length; i += 3)
  133. {
  134. Vector3 a = _points[_indices[i]].Position;
  135. Vector3 b = _points[_indices[i + 1]].Position;
  136. Vector3 c = _points[_indices[i + 2]].Position;
  137. var normal = Vector3.Normalize(Vector3.Cross(c - b, a - b));
  138. _points[_indices[i]].Normal += normal;
  139. _points[_indices[i + 1]].Normal += normal;
  140. _points[_indices[i + 2]].Normal += normal;
  141. }
  142. for (int i = 0; i < _points.Length; i++)
  143. {
  144. _points[i].Normal = Vector3.Normalize(_points[i].Normal);
  145. _maxY = Math.Max(_maxY, _points[i].Position.Y);
  146. _minY = Math.Min(_minY, _points[i].Position.Y);
  147. }
  148. }
  149. }
  150. private static void CheckError(GlInterface gl)
  151. {
  152. int err;
  153. while ((err = gl.GetError()) != GL_NO_ERROR)
  154. Console.WriteLine(err);
  155. }
  156. public string Info { get; private set; } = string.Empty;
  157. public unsafe void Init(GlInterface GL, GlVersion version)
  158. {
  159. GlVersion = version;
  160. CheckError(GL);
  161. Info = $"Renderer: {GL.GetString(GL_RENDERER)} Version: {GL.GetString(GL_VERSION)}";
  162. // Load the source of the vertex shader and compile it.
  163. _vertexShader = GL.CreateShader(GL_VERTEX_SHADER);
  164. Console.WriteLine(GL.CompileShaderAndGetError(_vertexShader, VertexShaderSource));
  165. // Load the source of the fragment shader and compile it.
  166. _fragmentShader = GL.CreateShader(GL_FRAGMENT_SHADER);
  167. Console.WriteLine(GL.CompileShaderAndGetError(_fragmentShader, FragmentShaderSource));
  168. // Create the shader program, attach the vertex and fragment shaders and link the program.
  169. _shaderProgram = GL.CreateProgram();
  170. GL.AttachShader(_shaderProgram, _vertexShader);
  171. GL.AttachShader(_shaderProgram, _fragmentShader);
  172. const int positionLocation = 0;
  173. const int normalLocation = 1;
  174. GL.BindAttribLocationString(_shaderProgram, positionLocation, "aPos");
  175. GL.BindAttribLocationString(_shaderProgram, normalLocation, "aNormal");
  176. Console.WriteLine(GL.LinkProgramAndGetError(_shaderProgram));
  177. CheckError(GL);
  178. // Create the vertex buffer object (VBO) for the vertex data.
  179. _vertexBufferObject = GL.GenBuffer();
  180. // Bind the VBO and copy the vertex data into it.
  181. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  182. CheckError(GL);
  183. var vertexSize = Marshal.SizeOf<Vertex>();
  184. fixed (void* pdata = _points)
  185. GL.BufferData(GL_ARRAY_BUFFER, new IntPtr(_points.Length * vertexSize),
  186. new IntPtr(pdata), GL_STATIC_DRAW);
  187. _indexBufferObject = GL.GenBuffer();
  188. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  189. CheckError(GL);
  190. fixed (void* pdata = _indices)
  191. GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, new IntPtr(_indices.Length * sizeof(ushort)), new IntPtr(pdata),
  192. GL_STATIC_DRAW);
  193. CheckError(GL);
  194. _vertexArrayObject = GL.GenVertexArray();
  195. GL.BindVertexArray(_vertexArrayObject);
  196. CheckError(GL);
  197. GL.VertexAttribPointer(positionLocation, 3, GL_FLOAT,
  198. 0, vertexSize, IntPtr.Zero);
  199. GL.VertexAttribPointer(normalLocation, 3, GL_FLOAT,
  200. 0, vertexSize, new IntPtr(12));
  201. GL.EnableVertexAttribArray(positionLocation);
  202. GL.EnableVertexAttribArray(normalLocation);
  203. CheckError(GL);
  204. }
  205. public void Deinit(GlInterface GL)
  206. {
  207. // Unbind everything
  208. GL.BindBuffer(GL_ARRAY_BUFFER, 0);
  209. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  210. GL.BindVertexArray(0);
  211. GL.UseProgram(0);
  212. // Delete all resources.
  213. GL.DeleteBuffer(_vertexBufferObject);
  214. GL.DeleteBuffer(_indexBufferObject);
  215. GL.DeleteVertexArray(_vertexArrayObject);
  216. GL.DeleteProgram(_shaderProgram);
  217. GL.DeleteShader(_fragmentShader);
  218. GL.DeleteShader(_vertexShader);
  219. }
  220. static Stopwatch St = Stopwatch.StartNew();
  221. public unsafe void OnOpenGlRender(GlInterface gl, int fb, PixelSize size,
  222. float yaw, float pitch, float roll, float disco)
  223. {
  224. gl.Viewport(0, 0, size.Width, size.Height);
  225. gl.ClearDepth(1);
  226. gl.Disable(GL_CULL_FACE);
  227. gl.Disable(GL_SCISSOR_TEST);
  228. gl.DepthFunc(GL_LESS);
  229. gl.DepthMask(1);
  230. gl.ClearColor(0, 0, 0, 0);
  231. gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  232. gl.Enable(GL_DEPTH_TEST);
  233. var GL = gl;
  234. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  235. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  236. GL.BindVertexArray(_vertexArrayObject);
  237. GL.UseProgram(_shaderProgram);
  238. CheckError(GL);
  239. var projection =
  240. Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.PI / 4), (float)(size.Width / size.Height),
  241. 0.01f, 1000);
  242. var view = Matrix4x4.CreateLookAt(new Vector3(25, 25, 25), new Vector3(), new Vector3(0, 1, 0));
  243. var model = Matrix4x4.CreateFromYawPitchRoll(yaw, pitch, roll);
  244. var modelLoc = GL.GetUniformLocationString(_shaderProgram, "uModel");
  245. var viewLoc = GL.GetUniformLocationString(_shaderProgram, "uView");
  246. var projectionLoc = GL.GetUniformLocationString(_shaderProgram, "uProjection");
  247. var maxYLoc = GL.GetUniformLocationString(_shaderProgram, "uMaxY");
  248. var minYLoc = GL.GetUniformLocationString(_shaderProgram, "uMinY");
  249. var timeLoc = GL.GetUniformLocationString(_shaderProgram, "uTime");
  250. var discoLoc = GL.GetUniformLocationString(_shaderProgram, "uDisco");
  251. GL.UniformMatrix4fv(modelLoc, 1, false, &model);
  252. GL.UniformMatrix4fv(viewLoc, 1, false, &view);
  253. GL.UniformMatrix4fv(projectionLoc, 1, false, &projection);
  254. GL.Uniform1f(maxYLoc, _maxY);
  255. GL.Uniform1f(minYLoc, _minY);
  256. GL.Uniform1f(timeLoc, (float)St.Elapsed.TotalSeconds);
  257. GL.Uniform1f(discoLoc, disco);
  258. CheckError(GL);
  259. GL.DrawElements(GL_TRIANGLES, _indices.Length, GL_UNSIGNED_SHORT, IntPtr.Zero);
  260. CheckError(GL);
  261. }
  262. }