ImGui_SDL2_OpenGL3_Demo.dpr 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. {
  2. FreePascal / Delphi bindings for ImGui
  3. Copyright (C) 2023 Coldzer0 <Coldzer0 [at] protonmail.ch>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the MIT License.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. MIT License for more details.
  10. }
  11. Program ImGui_SDL2_OpenGL3_Demo;
  12. {$IFDEF FPC}
  13. {$mode Delphi}{$H+}{$J-}
  14. {$Optimization FASTMATH}
  15. {$ENDIF}
  16. {$IfDef LINUX}
  17. {$IfDef FPC}
  18. {$LinkLib m}
  19. {$EndIf}
  20. {$EndIf}
  21. {$IfOpt D-}
  22. {$IfDef MSWINDOWS}
  23. {$AppType GUI}
  24. {$EndIf}
  25. {$ELSE}
  26. {$IfDef MSWINDOWS}
  27. {$AppType console}
  28. {$EndIf}
  29. {$EndIf}
  30. Uses
  31. {$IFDEF FPC}
  32. cmem,
  33. {$ENDIF}
  34. Math,
  35. SysUtils, ctypes,
  36. sdl2,
  37. glad_gl,
  38. PasImGui,
  39. PasImGui.Utils,
  40. PasImGui.ImPlot,
  41. PasImGui.Backend.SDL2,
  42. PasImGui.Renderer.OpenGL3,
  43. TestWindow, CustomNodeGraph;
  44. { TODO: Test with LIBGL_ALWAYS_SOFTWARE - Time : 9/23/2024 4:34:43 PM }
  45. Var
  46. counter: Integer;
  47. ShowPascalDemoWindow: Boolean = False;
  48. ShowAnotherWindow: Boolean = False;
  49. ShowDemoWindow: Boolean = False;
  50. ShowNodeWindow: Boolean = False;
  51. ShowImPlotPascalDemo: Boolean = False;
  52. clearColor: ImVec4;
  53. Var
  54. ImGuiCtx: PImGuiContext;
  55. IO: PImGuiIO;
  56. style : PImGuiStyle;
  57. quit: Boolean;
  58. window: PSDL_Window;
  59. e: TSDL_Event;
  60. testwin: TTestWindow;
  61. backup_current_window: PSDL_Window;
  62. backup_current_context: TSDL_GLContext;
  63. current: TSDL_DisplayMode;
  64. flags: Longword;
  65. gl_context: TSDL_GLContext;
  66. w, h: Integer;
  67. glsl_version: PAnsiChar = '';
  68. // LinePlots
  69. var
  70. xs1, ys1 : Array [0..1000] of Single;
  71. xs2, ys2 : Array [0..19] of Double;
  72. procedure ImPlotPascalDemoWindow();
  73. var
  74. i: Integer;
  75. begin
  76. if not ImGui.Begin_('ImPlot Pascal Demo', nil, ImGuiWindowFlags_NoDocking) then
  77. begin
  78. ImGui.End_();
  79. exit;
  80. end;
  81. for i := 0 to Pred(1001) do
  82. begin
  83. xs1[i] := i * 0.001;
  84. ys1[i] := 0.5 + 0.5 * Sin(50 * (xs1[i] + ImGui.GetTime() / 10));
  85. end;
  86. for i := 0 to Pred(20) do
  87. begin
  88. xs2[i] := i * 1/19.0;
  89. ys2[i] := xs2[i] * xs2[i];
  90. end;
  91. if (ImPlot.BeginPlot('Line Plots')) then
  92. begin
  93. ImPlot.SetupAxes('x','y');
  94. ImPlot.PlotLine('f(x)', PSingle(@xs1), PSingle(@ys1), 1001);
  95. ImPlot.SetNextMarkerStyle(ImPlotMarker_Circle);
  96. ImPlot.PlotLine('g(x)', PDouble(@xs2), PDouble(@ys2), 20, ImPlotLineFlags_Segments);
  97. ImPlot.EndPlot();
  98. end;
  99. ImGui.End_();
  100. end;
  101. Procedure ShowGreetingWindows;
  102. Var
  103. draw_list: PImDrawList;
  104. pos: ImVec2;
  105. Const
  106. HelloPascal: PAnsiChar = ' Hello From FreePascal / Delphi ';
  107. Begin
  108. Begin
  109. //ImGui.SetWindowPos(ImVec2.New(100, 100), ImGuiCond_FirstUseEver);
  110. ImGui.SetNextWindowPosCenter(ImGuiCond_FirstUseEver);
  111. If Not ImGui.Begin_('Greeting') Then
  112. Begin
  113. // Early out if the window is collapsed, as an optimization.
  114. ImGui.End_;
  115. exit;
  116. End;
  117. ImGui.Text('Hello, world %d', [counter]);
  118. If ImGui.Button('Add') Then
  119. Begin
  120. //button was pressed, do something special!
  121. Inc(counter);
  122. End;
  123. If ImGui.IsItemHovered(ImGuiHoveredFlags_RectOnly) Then
  124. Begin
  125. ImGui.SameLine();
  126. ImGui.Text('button hovered');
  127. End;
  128. ImGui.SameLine();
  129. pos := ImGui.GetCursorScreenPos();
  130. draw_list := ImGui.GetWindowDrawList();
  131. draw_list^.AddRectFilled(pos, ImVec2.New(pos.x + 50, pos.y + 20), $88000055);
  132. pos := ImVec2.New(pos.x + 50 + 20, pos.y);
  133. ImGui.SetCursorScreenPos(pos);
  134. draw_list^.AddRectFilled(pos, ImVec2.New(pos.x +
  135. ImGui.CalcTextSize(HelloPascal).x, pos.y + Trunc(ImGui.GetFont()^.EllipsisWidth * 2)), $88005500);
  136. ImGui.Text(HelloPascal);
  137. If ImGui.IsWindowHovered() Then
  138. ImGui.Text('window hovered')
  139. Else If ImGui.IsWindowHovered(ImGuiHoveredFlags_AnyWindow) Then
  140. ImGui.Text('some window hovered');
  141. ImGui.End_;
  142. End;
  143. Pos := ImGui.GetCenterViewPort(ImGui.GetMainViewport());
  144. Pos.y := Pos.y + 100;
  145. ImGui.SetNextWindowPos(Pos, ImGuiCond_FirstUseEver, ImVec2.New(0.5, 0.5));
  146. Begin
  147. ImGui.Begin_('Another greeting', @showAnotherWindow);
  148. ImGui.Text('Hello, next world %d', [counter]);
  149. If ImGui.Button('Not OK!') Then
  150. Begin
  151. Dec(counter);
  152. End;
  153. ImGui.End_;
  154. End;
  155. End;
  156. var
  157. GlobalStyleInitalized : Boolean = False;
  158. color_for_text, color_for_head, color_for_area, color_for_body, color_for_pops: ImVec3;
  159. Procedure RenderPascalCode();
  160. Var
  161. Pos: ImVec2;
  162. begin
  163. if not GlobalStyleInitalized then
  164. begin
  165. color_for_text := ImVec3.New(236.0 / 255.0, 240.0 / 255.0, 241.0 / 255.0);
  166. color_for_head := ImVec3.New(41.0 / 255.0, 128.0 / 255.0, 185.0 / 255.0);
  167. color_for_area := ImVec3.New(57.0 / 255.0, 79.0 / 255.0, 105.0 / 255.0);
  168. color_for_body := ImVec3.New(44.0 / 255.0, 62.0 / 255.0, 80.0 / 255.0);
  169. color_for_pops := ImVec3.New(33.0 / 255.0, 46.0 / 255.0, 60.0 / 255.0);
  170. GlobalStyleInitalized := True;
  171. end;
  172. //draw your scene or simple windows
  173. Pos := ImGui.GetCenterViewPort(ImGui.GetMainViewport());
  174. Pos.y := Pos.y - 160;
  175. ImGui.SetNextWindowPos(Pos, ImGuiCond_FirstUseEver, ImVec2.New(0.5, 0.5));
  176. Begin
  177. ImGui.Begin_('Hello From FreePascal / Delphi', nil, ImGuiWindowFlags_None);
  178. ImGui.Text('This is some useful text');
  179. ImGui.Checkbox('ImGui Demo', @showDemoWindow); ImGui.SameLine();
  180. ImGui.Checkbox('ImPlot Pascal Demo', @ShowImPlotPascalDemo);
  181. ImGui.Checkbox('Pascal Node Window', @showNodeWindow);
  182. ImGui.Checkbox('Pascal Demo Window', @showPascalDemoWindow);
  183. ImGui.Checkbox('Another Pascal window', @showAnotherWindow);
  184. ImGui.Spacing();
  185. ImGui.Separator();
  186. ImGui.Text('Global Styling Test');
  187. ImGui.NewLine();
  188. ImGui.ColorEdit3('color_for_text', @color_for_text);
  189. ImGui.ColorEdit3('color_for_head', @color_for_head);
  190. ImGui.ColorEdit3('color_for_area', @color_for_area);
  191. ImGui.ColorEdit3('color_for_body', @color_for_body);
  192. ImGui.ColorEdit3('color_for_pops', @color_for_pops);
  193. //If (ImGui.Button('Apply')) Then
  194. begin
  195. imgui_easy_theming(color_for_text, color_for_head, color_for_area, color_for_body, color_for_pops);
  196. end;
  197. ImGui.NewLine();
  198. ImGui.Separator();
  199. ImGui.ColorEdit3('Background color', @clearColor);
  200. If (ImGui.Button('Add')) Then
  201. begin
  202. Inc(counter);
  203. end;
  204. ImGui.SameLine(0.0, -1.0);
  205. ImGui.Text('counter = %d', [counter]);
  206. ImGui.Text('Application average %.3f ms/frame (%.f FPS)',
  207. [1000.0 / IO^.Framerate, IO^.Framerate]);
  208. ImGui.End_();
  209. End;
  210. If showAnotherWindow Then
  211. Begin
  212. ShowGreetingWindows;
  213. End;
  214. If showDemoWindow Then
  215. Begin
  216. ImGui.ShowDemoWindow(@showDemoWindow);
  217. End;
  218. End;
  219. Function PasAllocMem(sz: NativeUInt; {%H-}user_data: Pointer): Pointer; Cdecl;
  220. Begin
  221. Result := {$IFDEF FPC}cmem.Malloc(sz);{$ELSE}AllocMem(sz);{$ENDIF}
  222. End;
  223. Procedure PasFreeMem(ptr: Pointer; {%H-}user_data: Pointer); Cdecl;
  224. Begin
  225. {$IFDEF FPC}cmem.Free(ptr);{$ELSE}FreeMem(ptr);{$ENDIF}
  226. End;
  227. {$R *.res}
  228. procedure DrawGUI();
  229. begin
  230. // start imgui frame
  231. ImGui_OpenGL3_NewFrame();
  232. ImGui_ImplSDL2_NewFrame_Pas();
  233. ImGui.NewFrame();
  234. // Main UI Code
  235. Begin
  236. RenderPascalCode();
  237. if showNodeWindow then
  238. ShowExampleAppCustomNodeGraph(@showNodeWindow);
  239. If showPascalDemoWindow Then
  240. testwin.Show(showPascalDemoWindow);
  241. if ShowImPlotPascalDemo then
  242. ImPlotPascalDemoWindow();
  243. End;
  244. // render
  245. ImGui.Render();
  246. SDL_GL_MakeCurrent(window, gl_context);
  247. glViewport(0, 0, Trunc(IO^.DisplaySize.x), Trunc(IO^.DisplaySize.y));
  248. glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  249. glClear(GL_COLOR_BUFFER_BIT);
  250. ImGui_OpenGL3_RenderDrawData(ImGui.GetDrawData());
  251. // IMGUI_DOCK
  252. If (IO^.ConfigFlags And ImGuiConfigFlags_ViewportsEnable) <> 0 Then
  253. Begin
  254. backup_current_window := SDL_GL_GetCurrentWindow();
  255. backup_current_context := SDL_GL_GetCurrentContext();
  256. ImGui.UpdatePlatformWindows();
  257. ImGui.RenderPlatformWindowsDefault(nil, nil);
  258. SDL_GL_MakeCurrent(backup_current_window, backup_current_context);
  259. End;
  260. //show frame on display
  261. SDL_GL_SwapWindow(window);
  262. end;
  263. function window_redraw_on_resize(userdata: Pointer; e : PSDL_Event): Int32; cdecl;
  264. begin
  265. if (e^.type_ = SDL_WINDOWEVENT) and (e^.window.event = SDL_WINDOWEVENT_RESIZED) then
  266. begin
  267. glViewport(0, 0, e^.window.data1, e^.window.data2);
  268. DrawGUI();
  269. end;
  270. Result := 1;
  271. end;
  272. var
  273. FrameRate : Single = 60.0; // Default to 60 FPS
  274. elapsedMS : Single;
  275. SleepTime : Integer;
  276. Starting_tick: Cuint64;
  277. Begin
  278. { TODO: This is here for testing - Remove this later :V }
  279. //DeleteFile('MyApp.ini');
  280. // Set the Default Alloc & Free to point to Pascal Allocators
  281. igSetAllocatorFunctions(@PasAllocMem, @PasFreeMem, nil);
  282. //prevent SDL from raising a debugger exception to name threads
  283. SDL_SetHint(SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, '1');
  284. //open new SDL window with OpenGL rendering support
  285. If SDL_Init(SDL_INIT_VIDEO or SDL_INIT_TIMER) < 0 Then
  286. Begin
  287. if IsConsole then
  288. Writeln(Format('failed to init: %s', [SDL_GetError()]));
  289. End;
  290. // Decide GL+GLSL versions
  291. {$IfDef DARWIN}
  292. // GL 3.2 Core + GLSL 150
  293. // Always required on Mac
  294. glsl_version = '#version 150';
  295. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
  296. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  297. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  298. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  299. {$ELSE}
  300. // GL 4.1 uses GLSL 4.10
  301. glsl_version := '#version 410';
  302. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  303. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  304. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  305. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  306. {$EndIf}
  307. // From 2.0.18: Enable native IME.
  308. SDL_SetHint(SDL_HINT_IME_SHOW_UI, '1');
  309. SDL_SetHint(SDL_HINT_RENDER_DRIVER, 'opengl');
  310. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  311. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  312. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  313. SDL_GetCurrentDisplayMode(0, @current);
  314. flags := SDL_WINDOW_OPENGL Or SDL_WINDOW_RESIZABLE Or SDL_WINDOW_ALLOW_HIGHDPI;
  315. //flags := flags or SDL_WINDOW_FULLSCREEN_DESKTOP;
  316. h := 720;
  317. w := 1280;
  318. window := SDL_CreateWindow('Hello From FreePascal / Delphi (SDL2+OpenGL3)', SDL_WINDOWPOS_CENTERED,
  319. SDL_WINDOWPOS_CENTERED, w, h, flags);
  320. If window = nil Then
  321. Begin
  322. raise Exception.Create(Format('Failed to create window: %s', [SDL_GetError()]));
  323. halt;
  324. End;
  325. gl_context := SDL_GL_CreateContext(window);
  326. SDL_GL_SetSwapInterval(1); //enable VSync
  327. // setup imgui
  328. ImGui.CreateContext(nil);
  329. // Setup ImPlot
  330. ImPlot.Initialize();
  331. //set docking
  332. IO := ImGui.GetIO();
  333. // Ini Config File name
  334. IO^.IniFilename := 'MyApp.ini';
  335. // Enable Logging
  336. ImGuiCtx := ImGui.GetCurrentContext();
  337. ImGuiCtx^.LogType := ImGuiLogType_TTY;
  338. ImGuiCtx^.LogEnabled := True;
  339. // Enable Keyboard Controls
  340. IO^.ConfigFlags := IO^.ConfigFlags Or ImGuiConfigFlags_NavEnableKeyboard;
  341. // Enable Docking
  342. IO^.ConfigFlags := IO^.ConfigFlags Or ImGuiConfigFlags_DockingEnable;
  343. // Enable Multi-Viewport / Platform Windows
  344. IO^.ConfigFlags := IO^.ConfigFlags Or ImGuiConfigFlags_ViewportsEnable;
  345. // Init ImGui SDL2 OpenGL using Pure Pascal
  346. ImGui_ImplSDL2_InitForOpenGL_Pas(window, gl_context);
  347. ImGui_OpenGL3_Init(glsl_version);
  348. { uncomment to set a different gui theme }
  349. SetupImGuiStyle2(); // Using imgui_easy_theming
  350. //Imgui.StyleColorsDark(nil);
  351. //Imgui.StyleColorsLight(ImGui.GetStyle());
  352. // When viewports are enabled we tweak WindowRounding/WindowBg
  353. // so platform windows can look identical to regular ones.
  354. If (IO^.ConfigFlags And ImGuiConfigFlags_ViewportsEnable) <> 0 Then
  355. begin
  356. style := ImGui.GetStyle();
  357. style^.WindowRounding := 0.0;
  358. style^.Colors[ImGuiCol_WindowBg].w := 1.0;
  359. end;
  360. // Load Fonts
  361. //IO^.Fonts^.AddFontDefault();
  362. IO^.Fonts^.AddFontFromFileTTF('fonts/DroidSans.ttf', 25.0);
  363. //IO^.Fonts^.AddFontFromFileTTF('fonts/JetBrainsMonoNerdFontPropo-Italic.ttf ', 28.0);
  364. // Background Color
  365. clearColor.x := 0.45;
  366. clearColor.y := 0.55;
  367. clearColor.z := 0.60;
  368. clearColor.w := 1.00;
  369. testwin := TTestWindow.Create;
  370. counter := 0;
  371. quit := False;
  372. SDL_SetEventFilter(@window_redraw_on_resize, nil);
  373. While Not quit Do
  374. Begin
  375. starting_tick := SDL_GetPerformanceCounter();
  376. //handle input
  377. While SDL_PollEvent(@e) <> 0 Do
  378. Begin
  379. ImGui_ImplSDL2_ProcessEvent_Pas(@e);
  380. If e.type_ = SDL_QUITEV Then
  381. quit := True;
  382. If (e.type_ = SDL_WINDOWEVENT) And (e.window.event = SDL_WINDOWEVENT_CLOSE) And
  383. (e.window.windowID = SDL_GetWindowID(window)) Then
  384. quit := True;
  385. End;
  386. DrawGUI();
  387. // Locaked Frame Rate
  388. if FrameRate > 0 then
  389. begin
  390. elapsedMS := Single(SDL_GetPerformanceCounter() - starting_tick) / Single(SDL_GetPerformanceFrequency()) * 1000.0;
  391. SleepTime := Floor((1000.0 / FrameRate) - elapsedMS);
  392. if SleepTime <= 0 then
  393. SleepTime := 0;
  394. SDL_Delay(SleepTime);
  395. end;
  396. End;
  397. testwin.Free;
  398. // clean up
  399. ImGui_OpenGL3_Shutdown();
  400. ImGui_ImplSDL2_Shutdown_Pas();
  401. ImGui.DestroyContext(nil);
  402. SDL_GL_DeleteContext(gl_context);
  403. If window <> nil Then
  404. Begin
  405. SDL_DestroyWindow(window);
  406. window := nil;
  407. End;
  408. SDL_Quit();
  409. End.