OpenGlPage.xaml.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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.Controls;
  9. using Avalonia.OpenGL;
  10. using Avalonia.Platform.Interop;
  11. using Avalonia.Threading;
  12. using static Avalonia.OpenGL.GlConsts;
  13. // ReSharper disable StringLiteralTypo
  14. namespace ControlCatalog.Pages
  15. {
  16. public class OpenGlPage : UserControl
  17. {
  18. }
  19. public class OpenGlPageControl : OpenGlControlBase
  20. {
  21. private float _yaw;
  22. public static readonly DirectProperty<OpenGlPageControl, float> YawProperty =
  23. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Yaw", o => o.Yaw, (o, v) => o.Yaw = v);
  24. public float Yaw
  25. {
  26. get => _yaw;
  27. set => SetAndRaise(YawProperty, ref _yaw, value);
  28. }
  29. private float _pitch;
  30. public static readonly DirectProperty<OpenGlPageControl, float> PitchProperty =
  31. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Pitch", o => o.Pitch, (o, v) => o.Pitch = v);
  32. public float Pitch
  33. {
  34. get => _pitch;
  35. set => SetAndRaise(PitchProperty, ref _pitch, value);
  36. }
  37. private float _roll;
  38. public static readonly DirectProperty<OpenGlPageControl, float> RollProperty =
  39. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Roll", o => o.Roll, (o, v) => o.Roll = v);
  40. public float Roll
  41. {
  42. get => _roll;
  43. set => SetAndRaise(RollProperty, ref _roll, value);
  44. }
  45. private float _disco;
  46. public static readonly DirectProperty<OpenGlPageControl, float> DiscoProperty =
  47. AvaloniaProperty.RegisterDirect<OpenGlPageControl, float>("Disco", o => o.Disco, (o, v) => o.Disco = v);
  48. public float Disco
  49. {
  50. get => _disco;
  51. set => SetAndRaise(DiscoProperty, ref _disco, value);
  52. }
  53. private string _info;
  54. public static readonly DirectProperty<OpenGlPageControl, string> InfoProperty =
  55. AvaloniaProperty.RegisterDirect<OpenGlPageControl, string>("Info", o => o.Info, (o, v) => o.Info = v);
  56. public string Info
  57. {
  58. get => _info;
  59. private set => SetAndRaise(InfoProperty, ref _info, value);
  60. }
  61. static OpenGlPageControl()
  62. {
  63. AffectsRender<OpenGlPageControl>(YawProperty, PitchProperty, RollProperty, DiscoProperty);
  64. }
  65. private int _vertexShader;
  66. private int _fragmentShader;
  67. private int _shaderProgram;
  68. private int _vertexBufferObject;
  69. private int _indexBufferObject;
  70. private int _vertexArrayObject;
  71. private GlExtrasInterface _glExt;
  72. private string GetShader(bool fragment, string shader)
  73. {
  74. var version = (GlVersion.Type == GlProfileType.OpenGL ?
  75. RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 150 : 120 :
  76. 100);
  77. var data = "#version " + version + "\n";
  78. if (GlVersion.Type == GlProfileType.OpenGLES)
  79. data += "precision mediump float;\n";
  80. if (version >= 150)
  81. {
  82. shader = shader.Replace("attribute", "in");
  83. if (fragment)
  84. shader = shader
  85. .Replace("varying", "in")
  86. .Replace("//DECLAREGLFRAG", "out vec4 outFragColor;")
  87. .Replace("gl_FragColor", "outFragColor");
  88. else
  89. shader = shader.Replace("varying", "out");
  90. }
  91. data += shader;
  92. return data;
  93. }
  94. private string VertexShaderSource => GetShader(false, @"
  95. attribute vec3 aPos;
  96. attribute vec3 aNormal;
  97. uniform mat4 uModel;
  98. uniform mat4 uProjection;
  99. uniform mat4 uView;
  100. varying vec3 FragPos;
  101. varying vec3 VecPos;
  102. varying vec3 Normal;
  103. uniform float uTime;
  104. uniform float uDisco;
  105. void main()
  106. {
  107. float discoScale = sin(uTime * 10.0) / 10.0;
  108. float distortionX = 1.0 + uDisco * cos(uTime * 20.0) / 10.0;
  109. float scale = 1.0 + uDisco * discoScale;
  110. vec3 scaledPos = aPos;
  111. scaledPos.x = scaledPos.x * distortionX;
  112. scaledPos *= scale;
  113. gl_Position = uProjection * uView * uModel * vec4(scaledPos, 1.0);
  114. FragPos = vec3(uModel * vec4(aPos, 1.0));
  115. VecPos = aPos;
  116. Normal = normalize(vec3(uModel * vec4(aNormal, 1.0)));
  117. }
  118. ");
  119. private string FragmentShaderSource => GetShader(true, @"
  120. varying vec3 FragPos;
  121. varying vec3 VecPos;
  122. varying vec3 Normal;
  123. uniform float uMaxY;
  124. uniform float uMinY;
  125. uniform float uTime;
  126. uniform float uDisco;
  127. //DECLAREGLFRAG
  128. void main()
  129. {
  130. float y = (VecPos.y - uMinY) / (uMaxY - uMinY);
  131. float c = cos(atan(VecPos.x, VecPos.z) * 20.0 + uTime * 40.0 + y * 50.0);
  132. float s = sin(-atan(VecPos.z, VecPos.x) * 20.0 - uTime * 20.0 - y * 30.0);
  133. vec3 discoColor = vec3(
  134. 0.5 + abs(0.5 - y) * cos(uTime * 10.0),
  135. 0.25 + (smoothstep(0.3, 0.8, y) * (0.5 - c / 4.0)),
  136. 0.25 + abs((smoothstep(0.1, 0.4, y) * (0.5 - s / 4.0))));
  137. vec3 objectColor = vec3((1.0 - y), 0.40 + y / 4.0, y * 0.75 + 0.25);
  138. objectColor = objectColor * (1.0 - uDisco) + discoColor * uDisco;
  139. float ambientStrength = 0.3;
  140. vec3 lightColor = vec3(1.0, 1.0, 1.0);
  141. vec3 lightPos = vec3(uMaxY * 2.0, uMaxY * 2.0, uMaxY * 2.0);
  142. vec3 ambient = ambientStrength * lightColor;
  143. vec3 norm = normalize(Normal);
  144. vec3 lightDir = normalize(lightPos - FragPos);
  145. float diff = max(dot(norm, lightDir), 0.0);
  146. vec3 diffuse = diff * lightColor;
  147. vec3 result = (ambient + diffuse) * objectColor;
  148. gl_FragColor = vec4(result, 1.0);
  149. }
  150. ");
  151. [StructLayout(LayoutKind.Sequential, Pack = 4)]
  152. private struct Vertex
  153. {
  154. public Vector3 Position;
  155. public Vector3 Normal;
  156. }
  157. private readonly Vertex[] _points;
  158. private readonly ushort[] _indices;
  159. private readonly float _minY;
  160. private readonly float _maxY;
  161. public OpenGlPageControl()
  162. {
  163. var name = typeof(OpenGlPage).Assembly.GetManifestResourceNames().First(x => x.Contains("teapot.bin"));
  164. using (var sr = new BinaryReader(typeof(OpenGlPage).Assembly.GetManifestResourceStream(name)))
  165. {
  166. var buf = new byte[sr.ReadInt32()];
  167. sr.Read(buf, 0, buf.Length);
  168. var points = new float[buf.Length / 4];
  169. Buffer.BlockCopy(buf, 0, points, 0, buf.Length);
  170. buf = new byte[sr.ReadInt32()];
  171. sr.Read(buf, 0, buf.Length);
  172. _indices = new ushort[buf.Length / 2];
  173. Buffer.BlockCopy(buf, 0, _indices, 0, buf.Length);
  174. _points = new Vertex[points.Length / 3];
  175. for (var primitive = 0; primitive < points.Length / 3; primitive++)
  176. {
  177. var srci = primitive * 3;
  178. _points[primitive] = new Vertex
  179. {
  180. Position = new Vector3(points[srci], points[srci + 1], points[srci + 2])
  181. };
  182. }
  183. for (int i = 0; i < _indices.Length; i += 3)
  184. {
  185. Vector3 a = _points[_indices[i]].Position;
  186. Vector3 b = _points[_indices[i + 1]].Position;
  187. Vector3 c = _points[_indices[i + 2]].Position;
  188. var normal = Vector3.Normalize(Vector3.Cross(c - b, a - b));
  189. _points[_indices[i]].Normal += normal;
  190. _points[_indices[i + 1]].Normal += normal;
  191. _points[_indices[i + 2]].Normal += normal;
  192. }
  193. for (int i = 0; i < _points.Length; i++)
  194. {
  195. _points[i].Normal = Vector3.Normalize(_points[i].Normal);
  196. _maxY = Math.Max(_maxY, _points[i].Position.Y);
  197. _minY = Math.Min(_minY, _points[i].Position.Y);
  198. }
  199. }
  200. }
  201. private void CheckError(GlInterface gl)
  202. {
  203. int err;
  204. while ((err = gl.GetError()) != GL_NO_ERROR)
  205. Console.WriteLine(err);
  206. }
  207. protected unsafe override void OnOpenGlInit(GlInterface GL, int fb)
  208. {
  209. CheckError(GL);
  210. _glExt = new GlExtrasInterface(GL);
  211. Info = $"Renderer: {GL.GetString(GL_RENDERER)} Version: {GL.GetString(GL_VERSION)}";
  212. // Load the source of the vertex shader and compile it.
  213. _vertexShader = GL.CreateShader(GL_VERTEX_SHADER);
  214. Console.WriteLine(GL.CompileShaderAndGetError(_vertexShader, VertexShaderSource));
  215. // Load the source of the fragment shader and compile it.
  216. _fragmentShader = GL.CreateShader(GL_FRAGMENT_SHADER);
  217. Console.WriteLine(GL.CompileShaderAndGetError(_fragmentShader, FragmentShaderSource));
  218. // Create the shader program, attach the vertex and fragment shaders and link the program.
  219. _shaderProgram = GL.CreateProgram();
  220. GL.AttachShader(_shaderProgram, _vertexShader);
  221. GL.AttachShader(_shaderProgram, _fragmentShader);
  222. const int positionLocation = 0;
  223. const int normalLocation = 1;
  224. GL.BindAttribLocationString(_shaderProgram, positionLocation, "aPos");
  225. GL.BindAttribLocationString(_shaderProgram, normalLocation, "aNormal");
  226. Console.WriteLine(GL.LinkProgramAndGetError(_shaderProgram));
  227. CheckError(GL);
  228. // Create the vertex buffer object (VBO) for the vertex data.
  229. _vertexBufferObject = GL.GenBuffer();
  230. // Bind the VBO and copy the vertex data into it.
  231. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  232. CheckError(GL);
  233. var vertexSize = Marshal.SizeOf<Vertex>();
  234. fixed (void* pdata = _points)
  235. GL.BufferData(GL_ARRAY_BUFFER, new IntPtr(_points.Length * vertexSize),
  236. new IntPtr(pdata), GL_STATIC_DRAW);
  237. _indexBufferObject = GL.GenBuffer();
  238. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  239. CheckError(GL);
  240. fixed (void* pdata = _indices)
  241. GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, new IntPtr(_indices.Length * sizeof(ushort)), new IntPtr(pdata),
  242. GL_STATIC_DRAW);
  243. CheckError(GL);
  244. _vertexArrayObject = _glExt.GenVertexArray();
  245. _glExt.BindVertexArray(_vertexArrayObject);
  246. CheckError(GL);
  247. GL.VertexAttribPointer(positionLocation, 3, GL_FLOAT,
  248. 0, vertexSize, IntPtr.Zero);
  249. GL.VertexAttribPointer(normalLocation, 3, GL_FLOAT,
  250. 0, vertexSize, new IntPtr(12));
  251. GL.EnableVertexAttribArray(positionLocation);
  252. GL.EnableVertexAttribArray(normalLocation);
  253. CheckError(GL);
  254. }
  255. protected override void OnOpenGlDeinit(GlInterface GL, int fb)
  256. {
  257. // Unbind everything
  258. GL.BindBuffer(GL_ARRAY_BUFFER, 0);
  259. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  260. _glExt.BindVertexArray(0);
  261. GL.UseProgram(0);
  262. // Delete all resources.
  263. GL.DeleteBuffers(2, new[] { _vertexBufferObject, _indexBufferObject });
  264. _glExt.DeleteVertexArrays(1, new[] { _vertexArrayObject });
  265. GL.DeleteProgram(_shaderProgram);
  266. GL.DeleteShader(_fragmentShader);
  267. GL.DeleteShader(_vertexShader);
  268. }
  269. static Stopwatch St = Stopwatch.StartNew();
  270. protected override unsafe void OnOpenGlRender(GlInterface gl, int fb)
  271. {
  272. gl.ClearColor(0, 0, 0, 0);
  273. gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  274. gl.Enable(GL_DEPTH_TEST);
  275. gl.Viewport(0, 0, (int)Bounds.Width, (int)Bounds.Height);
  276. var GL = gl;
  277. GL.BindBuffer(GL_ARRAY_BUFFER, _vertexBufferObject);
  278. GL.BindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBufferObject);
  279. _glExt.BindVertexArray(_vertexArrayObject);
  280. GL.UseProgram(_shaderProgram);
  281. CheckError(GL);
  282. var projection =
  283. Matrix4x4.CreatePerspectiveFieldOfView((float)(Math.PI / 4), (float)(Bounds.Width / Bounds.Height),
  284. 0.01f, 1000);
  285. var view = Matrix4x4.CreateLookAt(new Vector3(25, 25, 25), new Vector3(), new Vector3(0, -1, 0));
  286. var model = Matrix4x4.CreateFromYawPitchRoll(_yaw, _pitch, _roll);
  287. var modelLoc = GL.GetUniformLocationString(_shaderProgram, "uModel");
  288. var viewLoc = GL.GetUniformLocationString(_shaderProgram, "uView");
  289. var projectionLoc = GL.GetUniformLocationString(_shaderProgram, "uProjection");
  290. var maxYLoc = GL.GetUniformLocationString(_shaderProgram, "uMaxY");
  291. var minYLoc = GL.GetUniformLocationString(_shaderProgram, "uMinY");
  292. var timeLoc = GL.GetUniformLocationString(_shaderProgram, "uTime");
  293. var discoLoc = GL.GetUniformLocationString(_shaderProgram, "uDisco");
  294. GL.UniformMatrix4fv(modelLoc, 1, false, &model);
  295. GL.UniformMatrix4fv(viewLoc, 1, false, &view);
  296. GL.UniformMatrix4fv(projectionLoc, 1, false, &projection);
  297. GL.Uniform1f(maxYLoc, _maxY);
  298. GL.Uniform1f(minYLoc, _minY);
  299. GL.Uniform1f(timeLoc, (float)St.Elapsed.TotalSeconds);
  300. GL.Uniform1f(discoLoc, _disco);
  301. CheckError(GL);
  302. GL.DrawElements(GL_TRIANGLES, _indices.Length, GL_UNSIGNED_SHORT, IntPtr.Zero);
  303. CheckError(GL);
  304. if (_disco > 0.01)
  305. Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
  306. }
  307. class GlExtrasInterface : GlInterfaceBase<GlInterface.GlContextInfo>
  308. {
  309. public GlExtrasInterface(GlInterface gl) : base(gl.GetProcAddress, gl.ContextInfo)
  310. {
  311. }
  312. public delegate void GlDeleteVertexArrays(int count, int[] buffers);
  313. [GlMinVersionEntryPoint("glDeleteVertexArrays", 3,0)]
  314. [GlExtensionEntryPoint("glDeleteVertexArraysOES", "GL_OES_vertex_array_object")]
  315. public GlDeleteVertexArrays DeleteVertexArrays { get; }
  316. public delegate void GlBindVertexArray(int array);
  317. [GlMinVersionEntryPoint("glBindVertexArray", 3,0)]
  318. [GlExtensionEntryPoint("glBindVertexArrayOES", "GL_OES_vertex_array_object")]
  319. public GlBindVertexArray BindVertexArray { get; }
  320. public delegate void GlGenVertexArrays(int n, int[] rv);
  321. [GlMinVersionEntryPoint("glGenVertexArrays",3,0)]
  322. [GlExtensionEntryPoint("glGenVertexArraysOES", "GL_OES_vertex_array_object")]
  323. public GlGenVertexArrays GenVertexArrays { get; }
  324. public int GenVertexArray()
  325. {
  326. var rv = new int[1];
  327. GenVertexArrays(1, rv);
  328. return rv[0];
  329. }
  330. }
  331. }
  332. }