mod.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi::system::CondVar;
  19. use darkfi_serial::{async_trait, Decodable, Encodable, SerialDecodable, SerialEncodable};
  20. use futures::AsyncWriteExt;
  21. use log::debug;
  22. use miniquad::{
  23. conf, window, Backend, Bindings, BlendFactor, BlendState, BlendValue, BufferLayout,
  24. BufferSource, BufferType, BufferUsage, Equation, EventHandler, KeyCode, KeyMods, MouseButton,
  25. PassAction, Pipeline, PipelineParams, RenderingBackend, ShaderMeta, ShaderSource, TouchPhase,
  26. UniformDesc, UniformType, VertexAttribute, VertexFormat,
  27. };
  28. use std::{
  29. collections::HashMap,
  30. fs::File,
  31. path::PathBuf,
  32. sync::{
  33. atomic::{AtomicU32, Ordering},
  34. mpsc, Arc, Mutex as SyncMutex,
  35. },
  36. time::{Duration, Instant},
  37. };
  38. mod favico;
  39. mod linalg;
  40. pub use linalg::{Dimension, Point, Rectangle};
  41. mod shader;
  42. use crate::{
  43. app::{AppPtr, AsyncRuntime},
  44. error::{Error, Result},
  45. pubsub::{Publisher, PublisherPtr, Subscription, SubscriptionId},
  46. util::ansi_texture,
  47. };
  48. // This is very noisy so suppress output by default
  49. const DEBUG_RENDER: bool = false;
  50. const DEBUG_GFXAPI: bool = false;
  51. #[cfg(target_os = "android")]
  52. pub fn get_window_size_filename() -> PathBuf {
  53. crate::android::get_appdata_path().join("window_size")
  54. }
  55. #[cfg(not(target_os = "android"))]
  56. pub fn get_window_size_filename() -> PathBuf {
  57. dirs::cache_dir().unwrap().join("darkfi/app/window_size")
  58. }
  59. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  60. #[repr(C)]
  61. pub struct Vertex {
  62. pub pos: [f32; 2],
  63. pub color: [f32; 4],
  64. pub uv: [f32; 2],
  65. }
  66. impl Vertex {
  67. pub fn pos(&self) -> Point {
  68. self.pos.into()
  69. }
  70. pub fn set_pos(&mut self, pos: &Point) {
  71. self.pos = pos.as_arr();
  72. }
  73. }
  74. pub type GfxTextureId = u32;
  75. pub type GfxBufferId = u32;
  76. static NEXT_BUFFER_ID: AtomicU32 = AtomicU32::new(0);
  77. static NEXT_TEXTURE_ID: AtomicU32 = AtomicU32::new(0);
  78. pub type ManagedTexturePtr = Arc<ManagedTexture>;
  79. /// Auto-deletes texture on drop
  80. #[derive(Clone)]
  81. pub struct ManagedTexture {
  82. id: GfxTextureId,
  83. render_api: RenderApi,
  84. }
  85. impl Drop for ManagedTexture {
  86. fn drop(&mut self) {
  87. self.render_api.delete_unmanaged_texture(self.id);
  88. }
  89. }
  90. impl std::fmt::Debug for ManagedTexture {
  91. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  92. f.debug_struct("ManagedTexture").field("id", &self.id).finish()
  93. }
  94. }
  95. pub type ManagedBufferPtr = Arc<ManagedBuffer>;
  96. /// Auto-deletes buffer on drop
  97. #[derive(Clone)]
  98. pub struct ManagedBuffer {
  99. id: GfxBufferId,
  100. render_api: RenderApi,
  101. }
  102. impl Drop for ManagedBuffer {
  103. fn drop(&mut self) {
  104. self.render_api.delete_unmanaged_buffer(self.id);
  105. }
  106. }
  107. impl std::fmt::Debug for ManagedBuffer {
  108. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  109. f.debug_struct("ManagedBuffer").field("id", &self.id).finish()
  110. }
  111. }
  112. #[derive(Clone)]
  113. pub struct RenderApi {
  114. method_req: mpsc::Sender<GraphicsMethod>,
  115. }
  116. impl RenderApi {
  117. pub fn new(method_req: mpsc::Sender<GraphicsMethod>) -> Self {
  118. Self { method_req }
  119. }
  120. fn new_unmanaged_texture(&self, width: u16, height: u16, data: Vec<u8>) -> GfxTextureId {
  121. let gfx_texture_id = NEXT_TEXTURE_ID.fetch_add(1, Ordering::SeqCst);
  122. let method = GraphicsMethod::NewTexture((width, height, data, gfx_texture_id));
  123. let _ = self.method_req.send(method);
  124. gfx_texture_id
  125. }
  126. pub fn new_texture(&self, width: u16, height: u16, data: Vec<u8>) -> ManagedTexturePtr {
  127. Arc::new(ManagedTexture {
  128. id: self.new_unmanaged_texture(width, height, data),
  129. render_api: self.clone(),
  130. })
  131. }
  132. fn delete_unmanaged_texture(&self, texture: GfxTextureId) {
  133. let method = GraphicsMethod::DeleteTexture(texture);
  134. let _ = self.method_req.send(method);
  135. }
  136. fn new_unmanaged_vertex_buffer(&self, verts: Vec<Vertex>) -> GfxBufferId {
  137. let gfx_buffer_id = NEXT_BUFFER_ID.fetch_add(1, Ordering::SeqCst);
  138. let method = GraphicsMethod::NewVertexBuffer((verts, gfx_buffer_id));
  139. let _ = self.method_req.send(method);
  140. gfx_buffer_id
  141. }
  142. fn new_unmanaged_index_buffer(&self, indices: Vec<u16>) -> GfxBufferId {
  143. let gfx_buffer_id = NEXT_BUFFER_ID.fetch_add(1, Ordering::SeqCst);
  144. let method = GraphicsMethod::NewIndexBuffer((indices, gfx_buffer_id));
  145. let _ = self.method_req.send(method);
  146. gfx_buffer_id
  147. }
  148. pub fn new_vertex_buffer(&self, verts: Vec<Vertex>) -> ManagedBufferPtr {
  149. Arc::new(ManagedBuffer {
  150. id: self.new_unmanaged_vertex_buffer(verts),
  151. render_api: self.clone(),
  152. })
  153. }
  154. pub fn new_index_buffer(&self, indices: Vec<u16>) -> ManagedBufferPtr {
  155. Arc::new(ManagedBuffer {
  156. id: self.new_unmanaged_index_buffer(indices),
  157. render_api: self.clone(),
  158. })
  159. }
  160. fn delete_unmanaged_buffer(&self, buffer: GfxBufferId) {
  161. let method = GraphicsMethod::DeleteBuffer(buffer);
  162. let _ = self.method_req.send(method);
  163. }
  164. pub fn replace_draw_calls(&self, timest: u64, dcs: Vec<(u64, GfxDrawCall)>) {
  165. let method = GraphicsMethod::ReplaceDrawCalls { timest, dcs };
  166. let _ = self.method_req.send(method);
  167. }
  168. }
  169. #[derive(Clone, Debug)]
  170. pub struct GfxDrawMesh {
  171. pub vertex_buffer: ManagedBufferPtr,
  172. pub index_buffer: ManagedBufferPtr,
  173. pub texture: Option<ManagedTexturePtr>,
  174. pub num_elements: i32,
  175. }
  176. impl GfxDrawMesh {
  177. fn compile(
  178. self,
  179. textures: &HashMap<GfxTextureId, miniquad::TextureId>,
  180. buffers: &HashMap<GfxBufferId, miniquad::BufferId>,
  181. ) -> Option<DrawMesh> {
  182. let vertex_buffer_id = self.vertex_buffer.id;
  183. let index_buffer_id = self.index_buffer.id;
  184. let buffers_keep_alive = [self.vertex_buffer, self.index_buffer];
  185. let texture = match self.texture {
  186. Some(gfx_texture) => Self::try_get_texture(textures, gfx_texture),
  187. None => None,
  188. };
  189. Some(DrawMesh {
  190. vertex_buffer: Self::try_get_buffer(buffers, vertex_buffer_id)?,
  191. index_buffer: Self::try_get_buffer(buffers, index_buffer_id)?,
  192. buffers_keep_alive,
  193. texture,
  194. num_elements: self.num_elements,
  195. })
  196. }
  197. fn try_get_texture(
  198. textures: &HashMap<GfxTextureId, miniquad::TextureId>,
  199. gfx_texture: ManagedTexturePtr,
  200. ) -> Option<(ManagedTexturePtr, miniquad::TextureId)> {
  201. let gfx_texture_id = gfx_texture.id;
  202. let Some(mq_texture_id) = textures.get(&gfx_texture_id) else {
  203. error!(target: "gfx", "Serious error: missing texture ID={gfx_texture_id}");
  204. error!(target: "gfx", "Dumping textures:");
  205. for (gfx_texture_id, texture_id) in textures {
  206. error!(target: "gfx", "{gfx_texture_id} => {texture_id:?}");
  207. }
  208. panic!("Missing texture ID={gfx_texture_id}");
  209. return None
  210. };
  211. Some((gfx_texture, textures[&gfx_texture_id]))
  212. }
  213. fn try_get_buffer(
  214. buffers: &HashMap<GfxBufferId, miniquad::BufferId>,
  215. gfx_buffer_id: GfxBufferId,
  216. ) -> Option<miniquad::BufferId> {
  217. let Some(mq_buffer_id) = buffers.get(&gfx_buffer_id) else {
  218. error!(target: "gfx", "Serious error: missing buffer ID={gfx_buffer_id}");
  219. error!(target: "gfx", "Dumping buffers:");
  220. for (gfx_buffer_id, buffer_id) in buffers {
  221. error!(target: "gfx", "{gfx_buffer_id} => {buffer_id:?}");
  222. }
  223. panic!("Missing buffer ID={gfx_buffer_id}");
  224. return None
  225. };
  226. Some(*mq_buffer_id)
  227. }
  228. }
  229. #[derive(Debug, Clone)]
  230. pub enum GfxDrawInstruction {
  231. SetScale(f32),
  232. Move(Point),
  233. ApplyView(Rectangle),
  234. Draw(GfxDrawMesh),
  235. }
  236. impl GfxDrawInstruction {
  237. fn compile(
  238. self,
  239. textures: &HashMap<GfxTextureId, miniquad::TextureId>,
  240. buffers: &HashMap<GfxBufferId, miniquad::BufferId>,
  241. ) -> Option<DrawInstruction> {
  242. let instr = match self {
  243. Self::SetScale(scale) => DrawInstruction::SetScale(scale),
  244. Self::Move(off) => DrawInstruction::Move(off),
  245. Self::ApplyView(view) => DrawInstruction::ApplyView(view),
  246. Self::Draw(mesh) => DrawInstruction::Draw(mesh.compile(textures, buffers)?),
  247. };
  248. Some(instr)
  249. }
  250. }
  251. #[derive(Clone, Debug, Default)]
  252. pub struct GfxDrawCall {
  253. pub instrs: Vec<GfxDrawInstruction>,
  254. pub dcs: Vec<u64>,
  255. pub z_index: u32,
  256. }
  257. impl GfxDrawCall {
  258. fn compile(
  259. self,
  260. textures: &HashMap<GfxTextureId, miniquad::TextureId>,
  261. buffers: &HashMap<GfxBufferId, miniquad::BufferId>,
  262. timest: u64,
  263. ) -> Option<DrawCall> {
  264. Some(DrawCall {
  265. instrs: self
  266. .instrs
  267. .into_iter()
  268. .map(|i| i.compile(textures, buffers))
  269. .collect::<Option<Vec<_>>>()?,
  270. dcs: self.dcs,
  271. z_index: self.z_index,
  272. timest,
  273. })
  274. }
  275. }
  276. #[derive(Clone, Debug)]
  277. struct DrawMesh {
  278. vertex_buffer: miniquad::BufferId,
  279. index_buffer: miniquad::BufferId,
  280. /// Keeps the buffers alive for the duration of this draw call
  281. buffers_keep_alive: [ManagedBufferPtr; 2],
  282. texture: Option<(ManagedTexturePtr, miniquad::TextureId)>,
  283. num_elements: i32,
  284. }
  285. #[derive(Debug, Clone)]
  286. enum DrawInstruction {
  287. SetScale(f32),
  288. Move(Point),
  289. ApplyView(Rectangle),
  290. Draw(DrawMesh),
  291. }
  292. #[derive(Debug)]
  293. struct DrawCall {
  294. instrs: Vec<DrawInstruction>,
  295. dcs: Vec<u64>,
  296. z_index: u32,
  297. timest: u64,
  298. }
  299. struct RenderContext<'a> {
  300. ctx: &'a mut Box<dyn RenderingBackend>,
  301. draw_calls: &'a HashMap<u64, DrawCall>,
  302. uniforms_data: [u8; 128],
  303. white_texture: miniquad::TextureId,
  304. scale: f32,
  305. view: Rectangle,
  306. cursor: Point,
  307. }
  308. impl<'a> RenderContext<'a> {
  309. fn draw(&mut self) {
  310. if DEBUG_RENDER {
  311. debug!(target: "gfx", "RenderContext::draw()");
  312. }
  313. let curr_pos = Point::zero();
  314. self.draw_call(&self.draw_calls[&0], 0);
  315. if DEBUG_RENDER {
  316. debug!(target: "gfx", "RenderContext::draw() [DONE]");
  317. }
  318. }
  319. fn apply_view(&mut self) {
  320. let view = self.view * self.scale;
  321. let (_, screen_height) = window::screen_size();
  322. let view_x = view.x.round() as i32;
  323. let view_y = screen_height - (view.y + view.h);
  324. let view_y = view_y.round() as i32;
  325. let view_w = view.w.round() as i32;
  326. let view_h = view.h.round() as i32;
  327. // OpenGL does not like negative values here
  328. if view_w <= 0 || view_h <= 0 {
  329. return
  330. }
  331. if DEBUG_RENDER {
  332. debug!(target: "gfx", "=> viewport {view_x} {view_y} {view_w} {view_h}");
  333. }
  334. self.ctx.apply_viewport(view_x, view_y, view_w, view_h);
  335. self.ctx.apply_scissor_rect(view_x, view_y, view_w, view_h);
  336. }
  337. fn apply_model(&mut self) {
  338. let off_x = self.cursor.x / self.view.w;
  339. let off_y = self.cursor.y / self.view.h;
  340. let scale_w = 1. / self.view.w;
  341. let scale_h = 1. / self.view.h;
  342. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  343. glam::Mat4::from_scale(glam::Vec3::new(scale_w, scale_h, 1.));
  344. let data: [u8; 64] = unsafe { std::mem::transmute_copy(&model) };
  345. self.uniforms_data[64..].copy_from_slice(&data);
  346. self.ctx.apply_uniforms_from_bytes(self.uniforms_data.as_ptr(), self.uniforms_data.len());
  347. }
  348. fn draw_call(&mut self, draw_call: &DrawCall, indent: u32) {
  349. let ws = if DEBUG_RENDER { " ".repeat(indent as usize * 4) } else { String::new() };
  350. let old_view = self.view;
  351. let old_cursor = self.cursor;
  352. for instr in &draw_call.instrs {
  353. match instr {
  354. DrawInstruction::SetScale(scale) => {
  355. self.scale = *scale;
  356. if DEBUG_RENDER {
  357. debug!(target: "gfx", "{ws}set_scale({scale})");
  358. }
  359. }
  360. DrawInstruction::Move(off) => {
  361. self.cursor = old_cursor + *off;
  362. if DEBUG_RENDER {
  363. debug!(target: "gfx",
  364. "{ws}move({off:?}) cursor={:?}, scale={}, view={:?}",
  365. self.cursor, self.scale, self.view
  366. );
  367. }
  368. self.apply_model();
  369. }
  370. DrawInstruction::ApplyView(view) => {
  371. self.view = *view;
  372. if DEBUG_RENDER {
  373. debug!(target: "gfx",
  374. "{ws}apply_view({view:?}) scale={}, view={:?}",
  375. self.scale, self.view
  376. );
  377. }
  378. self.apply_view();
  379. }
  380. DrawInstruction::Draw(mesh) => {
  381. if DEBUG_RENDER {
  382. debug!(target: "gfx", "{ws}draw({mesh:?})");
  383. }
  384. let texture = match mesh.texture {
  385. Some((_, texture)) => texture,
  386. None => self.white_texture,
  387. };
  388. let bindings = Bindings {
  389. vertex_buffers: vec![mesh.vertex_buffer],
  390. index_buffer: mesh.index_buffer,
  391. images: vec![texture],
  392. };
  393. self.ctx.apply_bindings(&bindings);
  394. self.ctx.draw(0, mesh.num_elements, 1);
  395. }
  396. }
  397. }
  398. let mut draw_calls: Vec<_> =
  399. draw_call.dcs.iter().map(|key| (key, &self.draw_calls[key])).collect();
  400. draw_calls.sort_unstable_by_key(|(_, dc)| dc.z_index);
  401. for (dc_key, dc) in draw_calls {
  402. if DEBUG_RENDER {
  403. debug!(target: "gfx", "{ws}drawcall {dc_key}");
  404. }
  405. self.draw_call(dc, indent + 1);
  406. }
  407. self.cursor = old_cursor;
  408. self.apply_model();
  409. self.view = old_view;
  410. self.apply_view();
  411. }
  412. }
  413. #[derive(Clone, Debug)]
  414. pub enum GraphicsMethod {
  415. NewTexture((u16, u16, Vec<u8>, GfxTextureId)),
  416. DeleteTexture(GfxTextureId),
  417. NewVertexBuffer((Vec<Vertex>, GfxBufferId)),
  418. NewIndexBuffer((Vec<u16>, GfxBufferId)),
  419. DeleteBuffer(GfxBufferId),
  420. ReplaceDrawCalls { timest: u64, dcs: Vec<(u64, GfxDrawCall)> },
  421. }
  422. pub type GraphicsEventPublisherPtr = Arc<GraphicsEventPublisher>;
  423. pub struct GraphicsEventPublisher {
  424. resize: PublisherPtr<Dimension>,
  425. key_down: PublisherPtr<(KeyCode, KeyMods, bool)>,
  426. key_up: PublisherPtr<(KeyCode, KeyMods)>,
  427. chr: PublisherPtr<(char, KeyMods, bool)>,
  428. mouse_btn_down: PublisherPtr<(MouseButton, Point)>,
  429. mouse_btn_up: PublisherPtr<(MouseButton, Point)>,
  430. mouse_move: PublisherPtr<Point>,
  431. mouse_wheel: PublisherPtr<Point>,
  432. touch: PublisherPtr<(TouchPhase, u64, Point)>,
  433. }
  434. impl GraphicsEventPublisher {
  435. pub fn new() -> Arc<Self> {
  436. Arc::new(Self {
  437. resize: Publisher::new(),
  438. key_down: Publisher::new(),
  439. key_up: Publisher::new(),
  440. chr: Publisher::new(),
  441. mouse_btn_down: Publisher::new(),
  442. mouse_btn_up: Publisher::new(),
  443. mouse_move: Publisher::new(),
  444. mouse_wheel: Publisher::new(),
  445. touch: Publisher::new(),
  446. })
  447. }
  448. fn notify_resize(&self, screen_size: Dimension) {
  449. self.resize.notify(screen_size);
  450. }
  451. fn notify_key_down(&self, key: KeyCode, mods: KeyMods, repeat: bool) {
  452. let ev = (key, mods, repeat);
  453. self.key_down.notify(ev);
  454. }
  455. fn notify_key_up(&self, key: KeyCode, mods: KeyMods) {
  456. let ev = (key, mods);
  457. self.key_up.notify(ev);
  458. }
  459. fn notify_char(&self, chr: char, mods: KeyMods, repeat: bool) {
  460. let ev = (chr, mods, repeat);
  461. self.chr.notify(ev);
  462. }
  463. fn notify_mouse_btn_down(&self, button: MouseButton, mouse_pos: Point) {
  464. let ev = (button, mouse_pos);
  465. self.mouse_btn_down.notify(ev);
  466. }
  467. fn notify_mouse_btn_up(&self, button: MouseButton, mouse_pos: Point) {
  468. let ev = (button, mouse_pos);
  469. self.mouse_btn_up.notify(ev);
  470. }
  471. fn notify_mouse_move(&self, mouse_pos: Point) {
  472. self.mouse_move.notify(mouse_pos);
  473. }
  474. fn notify_mouse_wheel(&self, wheel_pos: Point) {
  475. self.mouse_wheel.notify(wheel_pos);
  476. }
  477. fn notify_touch(&self, phase: TouchPhase, id: u64, touch_pos: Point) {
  478. let ev = (phase, id, touch_pos);
  479. self.touch.notify(ev);
  480. }
  481. pub fn subscribe_resize(&self) -> Subscription<Dimension> {
  482. self.resize.clone().subscribe()
  483. }
  484. pub fn subscribe_key_down(&self) -> Subscription<(KeyCode, KeyMods, bool)> {
  485. self.key_down.clone().subscribe()
  486. }
  487. pub fn subscribe_key_up(&self) -> Subscription<(KeyCode, KeyMods)> {
  488. self.key_up.clone().subscribe()
  489. }
  490. pub fn subscribe_char(&self) -> Subscription<(char, KeyMods, bool)> {
  491. self.chr.clone().subscribe()
  492. }
  493. pub fn subscribe_mouse_btn_down(&self) -> Subscription<(MouseButton, Point)> {
  494. self.mouse_btn_down.clone().subscribe()
  495. }
  496. pub fn subscribe_mouse_btn_up(&self) -> Subscription<(MouseButton, Point)> {
  497. self.mouse_btn_up.clone().subscribe()
  498. }
  499. pub fn subscribe_mouse_move(&self) -> Subscription<Point> {
  500. self.mouse_move.clone().subscribe()
  501. }
  502. pub fn subscribe_mouse_wheel(&self) -> Subscription<Point> {
  503. self.mouse_wheel.clone().subscribe()
  504. }
  505. pub fn subscribe_touch(&self) -> Subscription<(TouchPhase, u64, Point)> {
  506. self.touch.clone().subscribe()
  507. }
  508. }
  509. struct Stage {
  510. #[allow(dead_code)]
  511. app: AppPtr,
  512. #[allow(dead_code)]
  513. async_runtime: AsyncRuntime,
  514. ctx: Box<dyn RenderingBackend>,
  515. pipeline: Pipeline,
  516. white_texture: miniquad::TextureId,
  517. draw_calls: HashMap<u64, DrawCall>,
  518. textures: HashMap<GfxTextureId, miniquad::TextureId>,
  519. buffers: HashMap<GfxBufferId, miniquad::BufferId>,
  520. method_rep: mpsc::Receiver<GraphicsMethod>,
  521. event_pub: GraphicsEventPublisherPtr,
  522. }
  523. impl Stage {
  524. pub fn new(
  525. app: AppPtr,
  526. async_runtime: AsyncRuntime,
  527. method_rep: mpsc::Receiver<GraphicsMethod>,
  528. event_pub: GraphicsEventPublisherPtr,
  529. cv_started: Arc<CondVar>,
  530. ) -> Self {
  531. let mut ctx: Box<dyn RenderingBackend> = window::new_rendering_backend();
  532. // This will start the app to start. Needed since we cannot get window size for init
  533. // until window is created.
  534. cv_started.notify();
  535. let white_texture = ctx.new_texture_from_rgba8(1, 1, &[255, 255, 255, 255]);
  536. let mut shader_meta: ShaderMeta = shader::meta();
  537. shader_meta.uniforms.uniforms.push(UniformDesc::new("Projection", UniformType::Mat4));
  538. shader_meta.uniforms.uniforms.push(UniformDesc::new("Model", UniformType::Mat4));
  539. let shader = ctx
  540. .new_shader(
  541. match ctx.info().backend {
  542. Backend::OpenGl => ShaderSource::Glsl {
  543. vertex: shader::GL_VERTEX,
  544. fragment: shader::GL_FRAGMENT,
  545. },
  546. Backend::Metal => ShaderSource::Msl { program: shader::METAL },
  547. },
  548. shader_meta,
  549. )
  550. .unwrap();
  551. let params = PipelineParams {
  552. color_blend: Some(BlendState::new(
  553. Equation::Add,
  554. BlendFactor::Value(BlendValue::SourceAlpha),
  555. BlendFactor::OneMinusValue(BlendValue::SourceAlpha),
  556. )),
  557. ..Default::default()
  558. };
  559. let pipeline = ctx.new_pipeline(
  560. &[BufferLayout::default()],
  561. &[
  562. VertexAttribute::new("in_pos", VertexFormat::Float2),
  563. VertexAttribute::new("in_color", VertexFormat::Float4),
  564. VertexAttribute::new("in_uv", VertexFormat::Float2),
  565. ],
  566. shader,
  567. params,
  568. );
  569. Stage {
  570. app,
  571. async_runtime,
  572. ctx,
  573. pipeline,
  574. white_texture,
  575. draw_calls: HashMap::from([(
  576. 0,
  577. DrawCall { instrs: vec![], dcs: vec![], z_index: 0, timest: 0 },
  578. )]),
  579. textures: HashMap::new(),
  580. buffers: HashMap::new(),
  581. method_rep,
  582. event_pub,
  583. }
  584. }
  585. fn process_method(&mut self, method: GraphicsMethod) {
  586. //debug!(target: "gfx", "Received method: {:?}", method);
  587. match method {
  588. GraphicsMethod::NewTexture((width, height, data, gfx_texture_id)) => {
  589. self.method_new_texture(width, height, data, gfx_texture_id)
  590. }
  591. GraphicsMethod::DeleteTexture(texture) => self.method_delete_texture(texture),
  592. GraphicsMethod::NewVertexBuffer((verts, sendr)) => {
  593. self.method_new_vertex_buffer(verts, sendr)
  594. }
  595. GraphicsMethod::NewIndexBuffer((indices, sendr)) => {
  596. self.method_new_index_buffer(indices, sendr)
  597. }
  598. GraphicsMethod::DeleteBuffer(buffer) => self.method_delete_buffer(buffer),
  599. GraphicsMethod::ReplaceDrawCalls { timest, dcs } => {
  600. self.method_replace_draw_calls(timest, dcs)
  601. }
  602. };
  603. }
  604. fn method_new_texture(
  605. &mut self,
  606. width: u16,
  607. height: u16,
  608. data: Vec<u8>,
  609. gfx_texture_id: GfxTextureId,
  610. ) {
  611. let texture = self.ctx.new_texture_from_rgba8(width, height, &data);
  612. if DEBUG_GFXAPI {
  613. debug!(target: "gfx", "Invoked method: new_texture({}, {}, ..., {}) -> {:?}",
  614. width, height, gfx_texture_id, texture);
  615. //debug!(target: "gfx", "Invoked method: new_texture({}, {}, ..., {}) -> {:?}\n{}",
  616. // width, height, gfx_texture_id, texture,
  617. // ansi_texture(width as usize, height as usize, &data));
  618. }
  619. if let Some(_) = self.textures.insert(gfx_texture_id, texture) {
  620. panic!("Duplicate texture ID={gfx_texture_id} detected!");
  621. }
  622. }
  623. fn method_delete_texture(&mut self, gfx_texture_id: GfxTextureId) {
  624. let texture = self.textures.remove(&gfx_texture_id).expect("couldn't find gfx_texture_id");
  625. if DEBUG_GFXAPI {
  626. debug!(target: "gfx", "Invoked method: delete_texture({} => {:?})",
  627. gfx_texture_id, texture);
  628. }
  629. self.ctx.delete_texture(texture);
  630. }
  631. fn method_new_vertex_buffer(&mut self, verts: Vec<Vertex>, gfx_buffer_id: GfxBufferId) {
  632. let buffer = self.ctx.new_buffer(
  633. BufferType::VertexBuffer,
  634. BufferUsage::Immutable,
  635. BufferSource::slice(&verts),
  636. );
  637. if DEBUG_GFXAPI {
  638. debug!(target: "gfx", "Invoked method: new_vertex_buffer(..., {}) -> {:?}",
  639. gfx_buffer_id, buffer);
  640. //debug!(target: "gfx", "Invoked method: new_vertex_buffer({:?}, {}) -> {:?}",
  641. // verts, gfx_buffer_id, buffer);
  642. }
  643. if let Some(_) = self.buffers.insert(gfx_buffer_id, buffer) {
  644. panic!("Duplicate vertex buffer ID={gfx_buffer_id} detected!");
  645. }
  646. }
  647. fn method_new_index_buffer(&mut self, indices: Vec<u16>, gfx_buffer_id: GfxBufferId) {
  648. let buffer = self.ctx.new_buffer(
  649. BufferType::IndexBuffer,
  650. BufferUsage::Immutable,
  651. BufferSource::slice(&indices),
  652. );
  653. if DEBUG_GFXAPI {
  654. debug!(target: "gfx", "Invoked method: new_index_buffer({}) -> {:?}",
  655. gfx_buffer_id, buffer);
  656. //debug!(target: "gfx", "Invoked method: new_index_buffer({:?}, {}) -> {:?}",
  657. // indices, gfx_buffer_id, buffer);
  658. }
  659. if let Some(_) = self.buffers.insert(gfx_buffer_id, buffer) {
  660. panic!("Duplicate index buffer ID={gfx_buffer_id} detected!");
  661. }
  662. }
  663. fn method_delete_buffer(&mut self, gfx_buffer_id: GfxBufferId) {
  664. let buffer = self.buffers.remove(&gfx_buffer_id).expect("couldn't find gfx_buffer_id");
  665. if DEBUG_GFXAPI {
  666. debug!(target: "gfx", "Invoked method: delete_buffer({} => {:?})",
  667. gfx_buffer_id, buffer);
  668. }
  669. self.ctx.delete_buffer(buffer);
  670. }
  671. fn method_replace_draw_calls(&mut self, timest: u64, dcs: Vec<(u64, GfxDrawCall)>) {
  672. if DEBUG_GFXAPI {
  673. debug!(target: "gfx", "Invoked method: replace_draw_calls({:?})", dcs);
  674. }
  675. for (key, val) in dcs {
  676. let Some(val) = val.compile(&self.textures, &self.buffers, timest) else {
  677. error!(target: "gfx", "fatal: replace_draw_calls({timest}, ...) failed with item ID={key}");
  678. continue
  679. };
  680. //self.draw_calls.insert(key, val);
  681. match self.draw_calls.get_mut(&key) {
  682. Some(old_val) => {
  683. // Only replace the draw call if it is more recent
  684. if old_val.timest < timest {
  685. *old_val = val;
  686. } else {
  687. trace!(target: "gfx", "Rejected stale draw_call {key}: {val:?}");
  688. }
  689. }
  690. None => {
  691. self.draw_calls.insert(key, val);
  692. }
  693. }
  694. }
  695. }
  696. }
  697. impl EventHandler for Stage {
  698. fn update(&mut self) {
  699. // Process as many methods as we can
  700. while let Ok(method) = self.method_rep.try_recv() {
  701. self.process_method(method);
  702. }
  703. }
  704. fn draw(&mut self) {
  705. self.ctx.begin_default_pass(PassAction::clear_color(0., 0., 0., 1.));
  706. self.ctx.apply_pipeline(&self.pipeline);
  707. // This will make the top left (0, 0) and the bottom right (1, 1)
  708. // Default is (-1, 1) -> (1, -1)
  709. let proj = glam::Mat4::from_translation(glam::Vec3::new(-1., 1., 0.)) *
  710. glam::Mat4::from_scale(glam::Vec3::new(2., -2., 1.));
  711. let mut uniforms_data = [0u8; 128];
  712. let data: [u8; 64] = unsafe { std::mem::transmute_copy(&proj) };
  713. uniforms_data[0..64].copy_from_slice(&data);
  714. //let data: [u8; 64] = unsafe { std::mem::transmute_copy(&model) };
  715. //uniforms_data[64..].copy_from_slice(&data);
  716. assert_eq!(128, 2 * UniformType::Mat4.size());
  717. let (screen_w, screen_h) = miniquad::window::screen_size();
  718. let mut render_ctx = RenderContext {
  719. ctx: &mut self.ctx,
  720. draw_calls: &self.draw_calls,
  721. uniforms_data,
  722. white_texture: self.white_texture,
  723. scale: 1.,
  724. view: Rectangle::from([0., 0., screen_w, screen_h]),
  725. cursor: Point::from([0., 0.]),
  726. };
  727. render_ctx.draw();
  728. self.ctx.commit_frame();
  729. }
  730. fn resize_event(&mut self, width: f32, height: f32) {
  731. let filename = get_window_size_filename();
  732. if let Some(parent) = filename.parent() {
  733. let _ = std::fs::create_dir_all(parent);
  734. }
  735. if let Ok(mut file) = File::create(filename) {
  736. (width as i32).encode(&mut file).unwrap();
  737. (height as i32).encode(&mut file).unwrap();
  738. }
  739. self.event_pub.notify_resize(Dimension::from([width, height]));
  740. }
  741. fn key_down_event(&mut self, keycode: KeyCode, mods: KeyMods, repeat: bool) {
  742. self.event_pub.notify_key_down(keycode, mods, repeat);
  743. }
  744. fn key_up_event(&mut self, keycode: KeyCode, mods: KeyMods) {
  745. self.event_pub.notify_key_up(keycode, mods);
  746. }
  747. fn char_event(&mut self, chr: char, mods: KeyMods, repeat: bool) {
  748. self.event_pub.notify_char(chr, mods, repeat);
  749. }
  750. fn mouse_button_down_event(&mut self, button: MouseButton, x: f32, y: f32) {
  751. let pos = Point::from([x, y]);
  752. self.event_pub.notify_mouse_btn_down(button, pos);
  753. }
  754. fn mouse_button_up_event(&mut self, button: MouseButton, x: f32, y: f32) {
  755. let pos = Point::from([x, y]);
  756. self.event_pub.notify_mouse_btn_up(button, pos);
  757. }
  758. fn mouse_motion_event(&mut self, x: f32, y: f32) {
  759. let pos = Point::from([x, y]);
  760. self.event_pub.notify_mouse_move(pos);
  761. }
  762. fn mouse_wheel_event(&mut self, x: f32, y: f32) {
  763. let pos = Point::from([x, y]);
  764. self.event_pub.notify_mouse_wheel(pos);
  765. }
  766. /// The id corresponds to multi-touch. Multiple touch events have different ids.
  767. fn touch_event(&mut self, phase: TouchPhase, id: u64, x: f32, y: f32) {
  768. let pos = Point::from([x, y]);
  769. self.event_pub.notify_touch(phase, id, pos);
  770. }
  771. fn quit_requested_event(&mut self) {
  772. debug!(target: "gfx", "quit requested");
  773. // Doesn't work
  774. //miniquad::window::cancel_quit();
  775. //self.app.stop();
  776. //self.async_runtime.stop();
  777. }
  778. }
  779. pub fn run_gui(
  780. app: AppPtr,
  781. async_runtime: AsyncRuntime,
  782. method_rep: mpsc::Receiver<GraphicsMethod>,
  783. event_pub: GraphicsEventPublisherPtr,
  784. cv_started: Arc<CondVar>,
  785. ) {
  786. let mut window_width = 1024;
  787. let mut window_height = 768;
  788. if let Ok(mut file) = File::open(get_window_size_filename()) {
  789. window_width = Decodable::decode(&mut file).unwrap();
  790. window_height = Decodable::decode(&mut file).unwrap();
  791. }
  792. debug!(target: "gfx", "Window size {window_width} x {window_height}");
  793. let mut conf = miniquad::conf::Conf {
  794. window_title: "DarkFi".to_string(),
  795. window_width,
  796. window_height,
  797. high_dpi: true,
  798. window_resizable: true,
  799. platform: miniquad::conf::Platform {
  800. linux_backend: miniquad::conf::LinuxBackend::WaylandWithX11Fallback,
  801. wayland_use_fallback_decorations: false,
  802. //blocking_event_loop: true,
  803. ..Default::default()
  804. },
  805. icon: Some(miniquad::conf::Icon {
  806. small: favico::SMALL,
  807. medium: favico::MEDIUM,
  808. big: favico::BIG,
  809. }),
  810. ..Default::default()
  811. };
  812. let metal = std::env::args().nth(1).as_deref() == Some("metal");
  813. conf.platform.apple_gfx_api =
  814. if metal { conf::AppleGfxApi::Metal } else { conf::AppleGfxApi::OpenGl };
  815. miniquad::start(conf, || {
  816. Box::new(Stage::new(app, async_runtime, method_rep, event_pub, cv_started))
  817. });
  818. }