mod.rs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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_serial::{
  19. async_trait, AsyncEncodable, AsyncWrite, Decodable, Encodable, FutAsyncWriteExt,
  20. SerialDecodable, SerialEncodable, VarInt,
  21. };
  22. #[cfg(target_os = "android")]
  23. use miniquad::native::egl;
  24. use miniquad::{
  25. conf, window, Bindings, BufferSource, BufferType, BufferUsage, EventHandler, KeyCode, KeyMods,
  26. MouseButton, PassAction, Pipeline, RenderingBackend, TextureFormat, TextureKind, TextureParams,
  27. TextureWrap, TouchPhase, UniformType,
  28. };
  29. use std::{
  30. collections::{HashMap, HashSet},
  31. fs::File,
  32. io::Write,
  33. path::PathBuf,
  34. sync::{
  35. atomic::{AtomicU32, Ordering},
  36. Arc,
  37. },
  38. };
  39. pub mod anim;
  40. use anim::{Frame as AnimFrame, GfxSeqAnim};
  41. mod api;
  42. pub use api::{
  43. EpochIndex, GraphicsMethod, ManagedBuffer, ManagedBufferPtr, ManagedSeqAnim, ManagedSeqAnimPtr,
  44. ManagedTexture, ManagedTexturePtr, RenderApi,
  45. };
  46. mod ev;
  47. pub use ev::{
  48. GraphicsEventCharSub, GraphicsEventKeyDownSub, GraphicsEventKeyUpSub,
  49. GraphicsEventMouseButtonDownSub, GraphicsEventMouseButtonUpSub, GraphicsEventMouseMoveSub,
  50. GraphicsEventMouseWheelSub, GraphicsEventPublisher, GraphicsEventPublisherPtr,
  51. GraphicsEventResizeSub, GraphicsEventTouchSub,
  52. };
  53. mod favico;
  54. mod prune;
  55. use prune::PruneMethodHeap;
  56. mod linalg;
  57. pub use linalg::{Dimension, Point, Rectangle};
  58. mod shader;
  59. mod trax;
  60. use trax::get_trax;
  61. use crate::{
  62. prop::{BatchGuardId, PropertyAtomicGuard},
  63. scene::{Pimpl, SceneNodePtr},
  64. util::unixtime,
  65. GOD,
  66. };
  67. // This is very noisy so suppress output by default
  68. const DEBUG_RENDER: bool = false;
  69. const DEBUG_GFXAPI: bool = false;
  70. const DEBUG_TRAX: bool = false;
  71. #[macro_export]
  72. macro_rules! gfxtag {
  73. ($s:expr) => {{
  74. Some($s)
  75. }};
  76. }
  77. pub use crate::gfxtag;
  78. pub type DebugTag = Option<&'static str>;
  79. macro_rules! d { ($($arg:tt)*) => { debug!(target: "gfx", $($arg)*); } }
  80. macro_rules! t { ($($arg:tt)*) => { trace!(target: "gfx", $($arg)*); } }
  81. #[cfg(target_os = "android")]
  82. pub fn get_window_size_filename() -> PathBuf {
  83. crate::android::get_appdata_path().join("window_size")
  84. }
  85. #[cfg(not(target_os = "android"))]
  86. pub fn get_window_size_filename() -> PathBuf {
  87. dirs::cache_dir().unwrap().join("darkfi/app/window_size")
  88. }
  89. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  90. #[repr(C)]
  91. pub struct Vertex {
  92. pub pos: [f32; 2],
  93. pub color: [f32; 4],
  94. pub uv: [f32; 2],
  95. }
  96. impl Vertex {
  97. pub fn pos(&self) -> Point {
  98. self.pos.into()
  99. }
  100. pub fn set_pos(&mut self, pos: &Point) {
  101. self.pos = pos.as_arr();
  102. }
  103. }
  104. pub type TextureId = u32;
  105. pub type BufferId = u32;
  106. pub type AnimId = u32;
  107. static NEXT_BUFFER_ID: AtomicU32 = AtomicU32::new(0);
  108. static NEXT_TEXTURE_ID: AtomicU32 = AtomicU32::new(0);
  109. static NEXT_ANIM_ID: AtomicU32 = AtomicU32::new(0);
  110. #[derive(Clone, Debug)]
  111. pub struct DrawMesh {
  112. pub vertex_buffer: ManagedBufferPtr,
  113. pub index_buffer: ManagedBufferPtr,
  114. pub textures: Option<Vec<ManagedTexturePtr>>,
  115. pub num_elements: i32,
  116. }
  117. impl DrawMesh {
  118. fn compile(
  119. self,
  120. textures: &HashMap<TextureId, miniquad::TextureId>,
  121. buffers: &HashMap<BufferId, miniquad::BufferId>,
  122. debug_str: &'static str,
  123. ) -> GfxDrawMesh {
  124. let vertex_buffer_id = self.vertex_buffer.id;
  125. let index_buffer_id = self.index_buffer.id;
  126. let _buffers_keep_alive = [self.vertex_buffer, self.index_buffer];
  127. let textures = match self.textures {
  128. Some(gfx_textures) => {
  129. let mut compiled = Vec::with_capacity(gfx_textures.len());
  130. for gfx_texture in gfx_textures {
  131. compiled.push(Self::get_texture(textures, gfx_texture, debug_str));
  132. }
  133. Some(compiled)
  134. }
  135. None => None,
  136. };
  137. GfxDrawMesh {
  138. vertex_buffer: Self::get_buffer(buffers, vertex_buffer_id, debug_str),
  139. index_buffer: Self::get_buffer(buffers, index_buffer_id, debug_str),
  140. _buffers_keep_alive,
  141. textures,
  142. num_elements: self.num_elements,
  143. }
  144. }
  145. fn get_texture(
  146. textures: &HashMap<TextureId, miniquad::TextureId>,
  147. gfx_texture: ManagedTexturePtr,
  148. debug_str: &'static str,
  149. ) -> (ManagedTexturePtr, miniquad::TextureId) {
  150. let gfx_texture_id = gfx_texture.id;
  151. let Some(_mq_texture_id) = textures.get(&gfx_texture_id) else {
  152. panic!("Missing texture ID={gfx_texture_id} debug={debug_str}")
  153. };
  154. (gfx_texture, textures[&gfx_texture_id])
  155. }
  156. fn get_buffer(
  157. buffers: &HashMap<BufferId, miniquad::BufferId>,
  158. gfx_buffer_id: BufferId,
  159. debug_str: &'static str,
  160. ) -> miniquad::BufferId {
  161. let Some(mq_buffer_id) = buffers.get(&gfx_buffer_id) else {
  162. panic!("Missing buffer ID={gfx_buffer_id} debug={debug_str}")
  163. };
  164. *mq_buffer_id
  165. }
  166. }
  167. impl Encodable for DrawMesh {
  168. fn encode<S: Write>(&self, s: &mut S) -> std::result::Result<usize, std::io::Error> {
  169. let mut len = 0;
  170. len += self.vertex_buffer.id.encode(s)?;
  171. len += self.vertex_buffer.epoch.encode(s)?;
  172. len += self.vertex_buffer.tag.encode(s)?;
  173. len += self.vertex_buffer.buftype.encode(s)?;
  174. len += self.index_buffer.id.encode(s)?;
  175. len += self.index_buffer.epoch.encode(s)?;
  176. len += self.index_buffer.tag.encode(s)?;
  177. len += self.index_buffer.buftype.encode(s)?;
  178. match &self.textures {
  179. Some(texs) => {
  180. len += 1u8.encode(s)?;
  181. len += VarInt(texs.len() as u64).encode(s)?;
  182. for t in texs {
  183. len += t.id.encode(s)?;
  184. len += t.epoch.encode(s)?;
  185. len += t.tag.encode(s)?;
  186. }
  187. }
  188. None => {
  189. len += 0u8.encode(s)?;
  190. }
  191. }
  192. len += self.num_elements.encode(s)?;
  193. Ok(len)
  194. }
  195. }
  196. #[derive(Clone, Copy, Debug, SerialEncodable)]
  197. pub enum GraphicPipeline {
  198. RGB,
  199. YUV,
  200. }
  201. #[async_trait]
  202. impl AsyncEncodable for DrawMesh {
  203. async fn encode_async<W: AsyncWrite + Unpin + Send>(
  204. &self,
  205. _: &mut W,
  206. ) -> std::io::Result<usize> {
  207. Ok(0)
  208. }
  209. }
  210. #[derive(Debug, Clone)]
  211. pub enum DrawInstruction {
  212. SetScale(f32),
  213. Move(Point),
  214. SetPos(Point),
  215. ApplyView(Rectangle),
  216. Draw(DrawMesh),
  217. Animation(ManagedSeqAnimPtr),
  218. EnableDebug,
  219. SetPipeline(GraphicPipeline),
  220. Overlay(Vec<DrawInstruction>),
  221. }
  222. impl DrawInstruction {
  223. fn compile(
  224. self,
  225. textures: &HashMap<TextureId, miniquad::TextureId>,
  226. buffers: &HashMap<BufferId, miniquad::BufferId>,
  227. debug_str: &'static str,
  228. ) -> GfxDrawInstruction {
  229. match self {
  230. Self::SetScale(scale) => GfxDrawInstruction::SetScale(scale),
  231. Self::Move(off) => GfxDrawInstruction::Move(off),
  232. Self::SetPos(pos) => GfxDrawInstruction::SetPos(pos),
  233. Self::ApplyView(view) => GfxDrawInstruction::ApplyView(view),
  234. Self::Draw(mesh) => {
  235. GfxDrawInstruction::Draw(mesh.compile(textures, buffers, debug_str))
  236. }
  237. Self::Animation(anim) => GfxDrawInstruction::Animation(anim),
  238. Self::EnableDebug => GfxDrawInstruction::EnableDebug,
  239. Self::SetPipeline(pipeline) => GfxDrawInstruction::SetPipeline(pipeline),
  240. Self::Overlay(instrs) => {
  241. let compiled =
  242. instrs.into_iter().map(|i| i.compile(textures, buffers, debug_str)).collect();
  243. GfxDrawInstruction::Overlay(compiled)
  244. }
  245. }
  246. }
  247. }
  248. #[derive(Clone, Debug, Default)]
  249. pub struct DrawCall {
  250. pub instrs: Vec<DrawInstruction>,
  251. pub dcs: Vec<DcId>,
  252. pub z_index: u32,
  253. pub debug_str: &'static str,
  254. }
  255. impl DrawCall {
  256. pub fn new(
  257. instrs: Vec<DrawInstruction>,
  258. dcs: Vec<DcId>,
  259. z_index: u32,
  260. debug_str: &'static str,
  261. ) -> Self {
  262. Self { instrs, dcs, z_index, debug_str }
  263. }
  264. fn compile(
  265. self,
  266. textures: &HashMap<TextureId, miniquad::TextureId>,
  267. buffers: &HashMap<BufferId, miniquad::BufferId>,
  268. timest: Timestamp,
  269. ) -> GfxDrawCall {
  270. GfxDrawCall {
  271. instrs: self
  272. .instrs
  273. .into_iter()
  274. .map(|i| i.compile(textures, buffers, self.debug_str))
  275. .collect(),
  276. dcs: self.dcs,
  277. z_index: self.z_index,
  278. timest,
  279. }
  280. }
  281. }
  282. #[derive(Clone, Debug)]
  283. struct GfxDrawMesh {
  284. vertex_buffer: miniquad::BufferId,
  285. index_buffer: miniquad::BufferId,
  286. /// Keeps the buffers alive for the duration of this draw call
  287. _buffers_keep_alive: [ManagedBufferPtr; 2],
  288. textures: Option<Vec<(ManagedTexturePtr, miniquad::TextureId)>>,
  289. num_elements: i32,
  290. }
  291. #[derive(Debug, Clone)]
  292. enum GfxDrawInstruction {
  293. SetScale(f32),
  294. Move(Point),
  295. SetPos(Point),
  296. ApplyView(Rectangle),
  297. Draw(GfxDrawMesh),
  298. Animation(ManagedSeqAnimPtr),
  299. EnableDebug,
  300. SetPipeline(GraphicPipeline),
  301. Overlay(Vec<GfxDrawInstruction>),
  302. }
  303. #[derive(Clone, Debug)]
  304. struct GfxDrawCall {
  305. instrs: Vec<GfxDrawInstruction>,
  306. dcs: Vec<DcId>,
  307. z_index: u32,
  308. timest: Timestamp,
  309. }
  310. struct OverlayDefer {
  311. scale: f32,
  312. pos: Point,
  313. instrs: Vec<GfxDrawInstruction>,
  314. }
  315. struct RenderContext<'a> {
  316. ctx: &'a mut Box<dyn RenderingBackend>,
  317. draw_calls: &'a HashMap<DcId, GfxDrawCall>,
  318. uniforms_data: [u8; 128],
  319. white_texture: miniquad::TextureId,
  320. loaded_pipelines: &'a [Pipeline; 2],
  321. scale: f32,
  322. view: Rectangle,
  323. cursor: Point,
  324. gfx_pipeline: GraphicPipeline,
  325. anims: &'a mut HashMap<AnimId, GfxSeqAnim>,
  326. overlays: Vec<OverlayDefer>,
  327. }
  328. impl<'a> RenderContext<'a> {
  329. fn draw(&mut self) {
  330. if DEBUG_RENDER {
  331. let screen_size = miniquad::window::screen_size();
  332. d!("RenderContext::draw() [screen_size={screen_size:?}]");
  333. }
  334. if DEBUG_TRAX {
  335. get_trax().lock().set_curr(0);
  336. }
  337. self.draw_call(&self.draw_calls[&0], 0, DEBUG_RENDER);
  338. if DEBUG_RENDER {
  339. d!("RenderContext::draw() [DONE]");
  340. }
  341. // View should be reset now so draw overlays
  342. self.draw_overlays();
  343. }
  344. fn draw_overlays(&mut self) {
  345. let (screen_w, screen_h) = miniquad::window::screen_size();
  346. let overlays = std::mem::take(&mut self.overlays);
  347. for overlay in overlays {
  348. self.view = Rectangle::new(0., 0., screen_w, screen_h);
  349. self.scale = overlay.scale;
  350. self.view.w /= self.scale;
  351. self.view.h /= self.scale;
  352. self.apply_view();
  353. self.cursor = overlay.pos;
  354. self.apply_model();
  355. for instr in overlay.instrs {
  356. match instr {
  357. GfxDrawInstruction::Move(off) => {
  358. self.cursor += off;
  359. self.apply_model();
  360. }
  361. GfxDrawInstruction::Draw(mesh) => {
  362. if DEBUG_RENDER {
  363. d!(" draw_overlay({mesh:?})");
  364. }
  365. let images = match &mesh.textures {
  366. Some(texs) => texs.iter().map(|(_, tex_id)| *tex_id).collect(),
  367. None => vec![self.white_texture],
  368. };
  369. let bindings = Bindings {
  370. vertex_buffers: vec![mesh.vertex_buffer],
  371. index_buffer: mesh.index_buffer,
  372. images,
  373. };
  374. self.ctx.apply_bindings(&bindings);
  375. self.ctx.draw(0, mesh.num_elements, 1);
  376. }
  377. _ => unimplemented!(),
  378. }
  379. }
  380. }
  381. }
  382. fn apply_view(&mut self) {
  383. // Actual physical view
  384. let view = self.view * self.scale;
  385. let (_, screen_height) = window::screen_size();
  386. let view_x = view.x.round() as i32;
  387. let view_y = screen_height - (view.y + view.h);
  388. let view_y = view_y.round() as i32;
  389. let view_w = view.w.round() as i32;
  390. let view_h = view.h.round() as i32;
  391. // OpenGL does not like negative values here
  392. if view_w <= 0 || view_h <= 0 {
  393. return
  394. }
  395. if DEBUG_RENDER {
  396. d!("=> viewport {view_x} {view_y} {view_w} {view_h}");
  397. }
  398. self.ctx.apply_viewport(view_x, view_y, view_w, view_h);
  399. self.ctx.apply_scissor_rect(view_x, view_y, view_w, view_h);
  400. }
  401. fn apply_model(&mut self) {
  402. let off_x = self.cursor.x / self.view.w;
  403. let off_y = self.cursor.y / self.view.h;
  404. let scale_w = 1. / self.view.w;
  405. let scale_h = 1. / self.view.h;
  406. let model = glam::Mat4::from_translation(glam::Vec3::new(off_x, off_y, 0.)) *
  407. glam::Mat4::from_scale(glam::Vec3::new(scale_w, scale_h, 1.));
  408. let data: [u8; 64] = unsafe { std::mem::transmute_copy(&model) };
  409. self.uniforms_data[64..].copy_from_slice(&data);
  410. self.ctx.apply_uniforms_from_bytes(self.uniforms_data.as_ptr(), self.uniforms_data.len());
  411. }
  412. fn draw_call(&mut self, draw_call: &GfxDrawCall, mut indent: u32, mut is_debug: bool) {
  413. let ws = if is_debug { " ".repeat(indent as usize * 4) } else { String::new() };
  414. let old_scale = self.scale;
  415. let old_view = self.view;
  416. let old_cursor = self.cursor;
  417. let old_pipeline = self.gfx_pipeline;
  418. for (idx, instr) in draw_call.instrs.iter().enumerate() {
  419. if DEBUG_TRAX {
  420. get_trax().lock().set_instr(idx);
  421. }
  422. match instr {
  423. GfxDrawInstruction::SetScale(scale) => {
  424. self.scale = *scale;
  425. self.view.w /= self.scale;
  426. self.view.h /= self.scale;
  427. if is_debug {
  428. d!("{ws}set_scale({scale})");
  429. }
  430. }
  431. GfxDrawInstruction::Move(off) => {
  432. self.cursor += *off;
  433. if is_debug {
  434. d!(
  435. "{ws}move({off:?}) cursor={:?}, scale={}, view={:?}",
  436. self.cursor,
  437. self.scale,
  438. self.view
  439. );
  440. }
  441. self.apply_model();
  442. }
  443. GfxDrawInstruction::SetPos(pos) => {
  444. self.cursor = old_cursor + *pos;
  445. if is_debug {
  446. d!(
  447. "{ws}set_pos({pos:?}) cursor={:?}, scale={}, view={:?}",
  448. self.cursor,
  449. self.scale,
  450. self.view
  451. );
  452. }
  453. self.apply_model();
  454. }
  455. GfxDrawInstruction::ApplyView(view) => {
  456. // Adjust view relative to cursor
  457. self.view = *view + self.cursor + old_view.pos();
  458. // We could just skip drawing when clipping rect isn't visible
  459. // using an is_visible flag.
  460. match self.view.clip(&old_view) {
  461. Some(clipped) => self.view = clipped,
  462. None => self.view = Rectangle::zero(),
  463. }
  464. // Cursor resets within the view
  465. self.cursor = Point::zero();
  466. if is_debug {
  467. d!("{ws}apply_view({view:?}) scale={}, view={:?}", self.scale, self.view);
  468. }
  469. self.apply_view();
  470. self.apply_model();
  471. }
  472. GfxDrawInstruction::Draw(mesh) => {
  473. if is_debug {
  474. d!("{ws}draw({mesh:?})");
  475. }
  476. let images = match &mesh.textures {
  477. Some(texs) => texs.iter().map(|(_, tex_id)| *tex_id).collect(),
  478. None => vec![self.white_texture],
  479. };
  480. let bindings = Bindings {
  481. vertex_buffers: vec![mesh.vertex_buffer],
  482. index_buffer: mesh.index_buffer,
  483. images,
  484. };
  485. self.ctx.apply_bindings(&bindings);
  486. self.ctx.draw(0, mesh.num_elements, 1);
  487. }
  488. GfxDrawInstruction::Animation(anim) => {
  489. let gfx_anim = self.anims.get_mut(&anim.id).unwrap();
  490. gfx_anim.is_visible = true;
  491. if let Some(dc) = gfx_anim.tick() {
  492. self.draw_call(&dc, indent + 1, is_debug);
  493. }
  494. }
  495. GfxDrawInstruction::EnableDebug => {
  496. if !is_debug {
  497. indent = 0;
  498. }
  499. is_debug = true;
  500. d!("Frame start");
  501. }
  502. GfxDrawInstruction::SetPipeline(pipeline) => {
  503. self.gfx_pipeline = *pipeline;
  504. let pipeline_idx = *pipeline as usize;
  505. assert!(pipeline_idx < self.loaded_pipelines.len());
  506. self.ctx.apply_pipeline(&self.loaded_pipelines[pipeline_idx]);
  507. if is_debug {
  508. d!("{ws}set_pipeline({pipeline:?})");
  509. }
  510. }
  511. GfxDrawInstruction::Overlay(instrs) => {
  512. let pos = self.view.pos() / self.scale + self.cursor;
  513. self.overlays.push(OverlayDefer {
  514. scale: self.scale,
  515. pos,
  516. instrs: instrs.clone(),
  517. });
  518. }
  519. }
  520. }
  521. let mut draw_calls: Vec<_> =
  522. draw_call.dcs.iter().map(|key| (key, &self.draw_calls[key])).collect();
  523. draw_calls.sort_unstable_by_key(|(_, dc)| dc.z_index);
  524. for (dc_key, dc) in draw_calls {
  525. if DEBUG_TRAX {
  526. get_trax().lock().set_curr(*dc_key);
  527. }
  528. if is_debug {
  529. d!("{ws}drawcall {dc_key}");
  530. }
  531. self.draw_call(dc, indent + 1, is_debug);
  532. }
  533. self.scale = old_scale;
  534. if is_debug {
  535. d!("{ws}Frame close: cursor={old_cursor:?}, view={old_view:?}");
  536. }
  537. self.view = old_view;
  538. self.apply_view();
  539. self.cursor = old_cursor;
  540. self.gfx_pipeline = old_pipeline;
  541. let pipeline_idx = self.gfx_pipeline as usize;
  542. assert!(pipeline_idx < self.loaded_pipelines.len());
  543. self.ctx.apply_pipeline(&self.loaded_pipelines[pipeline_idx]);
  544. self.apply_model();
  545. }
  546. }
  547. type Timestamp = u64;
  548. type DcId = u64;
  549. struct Stage {
  550. ctx: Box<dyn RenderingBackend>,
  551. #[cfg(target_os = "android")]
  552. libegl: egl::LibEgl,
  553. loaded_pipelines: [Pipeline; 2],
  554. white_texture: miniquad::TextureId,
  555. draw_calls: HashMap<DcId, GfxDrawCall>,
  556. pending_batches: HashMap<BatchGuardId, Vec<GraphicsMethod>>,
  557. /// When dropping batches, we add to this set so that we keep track
  558. /// of the internal state's correctness.
  559. dropped_batches: Box<HashSet<BatchGuardId>>,
  560. textures: Box<HashMap<TextureId, miniquad::TextureId>>,
  561. buffers: Box<HashMap<BufferId, miniquad::BufferId>>,
  562. anims: Box<HashMap<AnimId, GfxSeqAnim>>,
  563. epoch: EpochIndex,
  564. method_recv: async_channel::Receiver<(EpochIndex, GraphicsMethod)>,
  565. event_pub: GraphicsEventPublisherPtr,
  566. pruner: PruneMethodHeap,
  567. screen_state: ScreenState,
  568. /// Cached window node, looked up lazily on first touch event
  569. window_node: Option<SceneNodePtr>,
  570. }
  571. impl Stage {
  572. pub fn new() -> Self {
  573. if DEBUG_TRAX {
  574. get_trax().lock().clear();
  575. }
  576. let mut ctx: Box<dyn RenderingBackend> = window::new_rendering_backend();
  577. let god = GOD.get().unwrap();
  578. // Start a new epoch. This is a brand new UI run.
  579. let epoch = god.render_api.next_epoch();
  580. // This will start the app to start. Needed since we cannot get window size for init
  581. // until window is created.
  582. god.start_app(epoch);
  583. let method_recv = god.method_recv.clone();
  584. let event_pub = god.event_pub.clone();
  585. let white_texture = ctx.new_texture_from_rgba8(1, 1, &[255, 255, 255, 255]);
  586. let anims: HashMap<AnimId, GfxSeqAnim> = HashMap::new();
  587. let rgb_pipeline = shader::create_rgb_pipeline(&mut ctx);
  588. let yuv_pipeline = shader::create_yuv_pipeline(&mut ctx);
  589. #[cfg(target_os = "android")]
  590. let libegl = egl::LibEgl::try_load().expect("Cant load LibEGL");
  591. let mut self_ = Stage {
  592. ctx,
  593. #[cfg(target_os = "android")]
  594. libegl,
  595. loaded_pipelines: [rgb_pipeline, yuv_pipeline],
  596. white_texture,
  597. draw_calls: HashMap::from([(
  598. 0,
  599. GfxDrawCall { instrs: vec![], dcs: vec![], z_index: 0, timest: 0 },
  600. )]),
  601. pending_batches: HashMap::new(),
  602. dropped_batches: Box::new(HashSet::new()),
  603. textures: Box::new(HashMap::new()),
  604. buffers: Box::new(HashMap::new()),
  605. anims: Box::new(anims),
  606. epoch,
  607. method_recv,
  608. event_pub,
  609. pruner: PruneMethodHeap::new(epoch),
  610. screen_state: ScreenState::On,
  611. window_node: None,
  612. };
  613. self_.pruner.textures = &*self_.textures as *const _;
  614. self_.pruner.buffers = &*self_.buffers as *const _;
  615. self_.pruner.anims = &*self_.anims as *const _;
  616. self_.pruner.dropped_batches = &mut *self_.dropped_batches as *mut _;
  617. self_
  618. }
  619. fn process_method(&mut self, mut method: GraphicsMethod) {
  620. //d!("Received method: {method:?}");
  621. match &mut method {
  622. GraphicsMethod::NewTexture((width, height, data, fmt, gtex_id, _)) => {
  623. self.method_new_texture(*width, *height, data, *fmt, *gtex_id)
  624. }
  625. GraphicsMethod::DeleteTexture((gtex_id, _)) => self.method_delete_texture(*gtex_id),
  626. GraphicsMethod::NewVertexBuffer((verts, gbuff_id, _)) => {
  627. self.method_new_vertex_buffer(verts, *gbuff_id)
  628. }
  629. GraphicsMethod::NewIndexBuffer((indices, gbuff_id, _)) => {
  630. self.method_new_index_buffer(indices, *gbuff_id)
  631. }
  632. GraphicsMethod::DeleteBuffer((gbuff_id, _, _)) => self.method_delete_buffer(*gbuff_id),
  633. GraphicsMethod::NewSeqAnim { id, frames_len, oneshot, tag: _ } => {
  634. self.method_new_anim(*id, *frames_len, *oneshot)
  635. }
  636. GraphicsMethod::UpdateSeqAnim { id, frame_idx, frame, tag: _ } => {
  637. self.method_update_anim(*id, *frame_idx, frame.clone())
  638. }
  639. GraphicsMethod::DeleteSeqAnim((ganim_id, _)) => self.method_delete_anim(*ganim_id),
  640. GraphicsMethod::ReplaceGfxDrawCalls { batch_id, .. } => {
  641. //let debug_strs: Vec<_> = dcs.iter().map(|(_, dc)| dc.debug_str).collect();
  642. //t!("Commit dc to {batch_id}: {debug_strs:?}");
  643. if self.dropped_batches.contains(batch_id) {
  644. t!("Discarding ReplaceGfxDrawCalls from dropped {batch_id}");
  645. return
  646. }
  647. let Some(batch) = self.pending_batches.get_mut(batch_id) else {
  648. panic!("unknown batch {batch_id}")
  649. };
  650. let method = std::mem::take(&mut method);
  651. batch.push(method);
  652. if DEBUG_TRAX {
  653. get_trax().lock().put_stat(0);
  654. }
  655. }
  656. GraphicsMethod::StartBatch { batch_id, tag } => {
  657. if DEBUG_GFXAPI {
  658. t!("Start batch {batch_id}: {tag:?}");
  659. }
  660. if !self.pending_batches.insert(*batch_id, vec![]).is_none() {
  661. panic!("batch {batch_id} already open!")
  662. }
  663. if DEBUG_TRAX {
  664. get_trax().lock().put_stat(0);
  665. }
  666. }
  667. GraphicsMethod::EndBatch { batch_id, timest } => {
  668. if self.dropped_batches.remove(batch_id) {
  669. if DEBUG_GFXAPI {
  670. t!("End batch {batch_id} was dropped");
  671. }
  672. return
  673. }
  674. if DEBUG_GFXAPI {
  675. t!("End batch {batch_id}");
  676. }
  677. let Some(batch) = self.pending_batches.remove(batch_id) else {
  678. panic!("unknown batch {batch_id}")
  679. };
  680. for mut method in batch {
  681. match &mut method {
  682. GraphicsMethod::ReplaceGfxDrawCalls { batch_id: _, dcs } => {
  683. let dcs = std::mem::take(dcs);
  684. self.method_replace_draw_calls(*timest, dcs)
  685. }
  686. _ => panic!("unexpected method in batch!"),
  687. }
  688. }
  689. }
  690. GraphicsMethod::Noop => panic!("noop"),
  691. }
  692. }
  693. fn method_new_texture(
  694. &mut self,
  695. width: u16,
  696. height: u16,
  697. data: &Vec<u8>,
  698. format: TextureFormat,
  699. gfx_texture_id: TextureId,
  700. ) {
  701. let fmt_size = format.size(width as u32, height as u32) as usize;
  702. assert_eq!(
  703. fmt_size,
  704. data.len(),
  705. "Texture data size mismatch for ID={gfx_texture_id}: \
  706. expected {fmt_size}, got {} for {width}x{height} {:?}",
  707. data.len(),
  708. format
  709. );
  710. let texture = self.ctx.new_texture_from_data_and_format(
  711. data,
  712. TextureParams {
  713. kind: TextureKind::Texture2D,
  714. format,
  715. width: width as _,
  716. height: height as _,
  717. wrap: TextureWrap::Clamp,
  718. min_filter: miniquad::FilterMode::Linear,
  719. mag_filter: miniquad::FilterMode::Linear,
  720. mipmap_filter: miniquad::MipmapFilterMode::None,
  721. allocate_mipmaps: false,
  722. sample_count: 1,
  723. },
  724. );
  725. if DEBUG_GFXAPI {
  726. d!("Invoked method: new_texture({width}, {height}, ..., {gfx_texture_id}) -> {texture:?}");
  727. //d!("Invoked method: new_texture({}, {}, ..., {}) -> {:?}\n{}",
  728. // width, height, gfx_texture_id, texture,
  729. // ansi_texture(width as usize, height as usize, &data));
  730. }
  731. if let Some(_) = self.textures.insert(gfx_texture_id, texture) {
  732. if DEBUG_TRAX {
  733. get_trax().lock().put_stat(2);
  734. }
  735. panic!("Duplicate texture ID={gfx_texture_id} detected!");
  736. }
  737. if DEBUG_TRAX {
  738. get_trax().lock().put_stat(0);
  739. }
  740. }
  741. fn method_delete_texture(&mut self, gfx_texture_id: TextureId) {
  742. let Some(texture) = self.textures.remove(&gfx_texture_id) else {
  743. if DEBUG_TRAX {
  744. get_trax().lock().put_stat(2);
  745. }
  746. panic!("unknown texture {gfx_texture_id}")
  747. };
  748. if DEBUG_GFXAPI {
  749. d!("Invoked method: delete_texture({gfx_texture_id} => {texture:?})");
  750. }
  751. self.ctx.delete_texture(texture);
  752. if DEBUG_TRAX {
  753. get_trax().lock().put_stat(0);
  754. }
  755. }
  756. fn method_new_vertex_buffer(&mut self, verts: &[Vertex], gfx_buffer_id: BufferId) {
  757. let buffer = self.ctx.new_buffer(
  758. BufferType::VertexBuffer,
  759. BufferUsage::Immutable,
  760. BufferSource::slice(verts),
  761. );
  762. if DEBUG_GFXAPI {
  763. d!("Invoked method: new_vertex_buffer(..., {gfx_buffer_id}) -> {buffer:?}");
  764. //debug!(target: "gfx", "Invoked method: new_vertex_buffer({:?}, {}) -> {:?}",
  765. // verts, gfx_buffer_id, buffer);
  766. }
  767. if let Some(_) = self.buffers.insert(gfx_buffer_id, buffer) {
  768. if DEBUG_TRAX {
  769. get_trax().lock().put_stat(2);
  770. }
  771. panic!("Duplicate vertex buffer ID={gfx_buffer_id} detected!")
  772. }
  773. if DEBUG_TRAX {
  774. get_trax().lock().put_stat(0);
  775. }
  776. }
  777. fn method_new_index_buffer(&mut self, indices: &[u16], gfx_buffer_id: BufferId) {
  778. let buffer = self.ctx.new_buffer(
  779. BufferType::IndexBuffer,
  780. BufferUsage::Immutable,
  781. BufferSource::slice(&indices),
  782. );
  783. if DEBUG_GFXAPI {
  784. d!("Invoked method: new_index_buffer({gfx_buffer_id}) -> {buffer:?}");
  785. //debug!(target: "gfx", "Invoked method: new_index_buffer({:?}, {}) -> {:?}",
  786. // indices, gfx_buffer_id, buffer);
  787. }
  788. if let Some(_) = self.buffers.insert(gfx_buffer_id, buffer) {
  789. if DEBUG_TRAX {
  790. get_trax().lock().put_stat(2);
  791. }
  792. panic!("Duplicate index buffer ID={gfx_buffer_id} detected!")
  793. }
  794. if DEBUG_TRAX {
  795. get_trax().lock().put_stat(0);
  796. }
  797. }
  798. fn method_delete_buffer(&mut self, gfx_buffer_id: BufferId) {
  799. let Some(buffer) = self.buffers.remove(&gfx_buffer_id) else {
  800. if DEBUG_TRAX {
  801. get_trax().lock().put_stat(2);
  802. }
  803. panic!("unknown buffer {gfx_buffer_id}");
  804. };
  805. if DEBUG_GFXAPI {
  806. d!("Invoked method: delete_buffer({gfx_buffer_id} => {buffer:?})");
  807. }
  808. self.ctx.delete_buffer(buffer);
  809. if DEBUG_TRAX {
  810. get_trax().lock().put_stat(0);
  811. }
  812. }
  813. fn method_new_anim(&mut self, gfx_anim_id: AnimId, frames_len: usize, oneshot: bool) {
  814. if DEBUG_GFXAPI {
  815. d!("Invoked method: new_anim({gfx_anim_id}, {frames_len}, {oneshot})");
  816. }
  817. if let Some(_) = self.anims.insert(gfx_anim_id, GfxSeqAnim::new(frames_len, oneshot)) {
  818. panic!("Duplicate anim ID={gfx_anim_id} detected!");
  819. }
  820. }
  821. fn method_update_anim(&mut self, gfx_anim_id: AnimId, frame_idx: usize, frame: AnimFrame) {
  822. let Some(anim) = self.anims.get_mut(&gfx_anim_id) else {
  823. panic!("couldn't find anim {gfx_anim_id}");
  824. };
  825. if DEBUG_GFXAPI {
  826. d!("Invoked method: update_anim({gfx_anim_id}[{frame_idx}] => {frame:?})");
  827. }
  828. anim.set(frame_idx, frame, &self.textures, &self.buffers);
  829. }
  830. fn method_delete_anim(&mut self, gfx_anim_id: AnimId) {
  831. let Some(anim) = self.anims.remove(&gfx_anim_id) else {
  832. panic!("couldn't find anim {gfx_anim_id}");
  833. };
  834. if DEBUG_GFXAPI {
  835. d!("Invoked method: delete_anim({} => {:?})", gfx_anim_id, anim);
  836. }
  837. }
  838. fn method_replace_draw_calls(&mut self, batch_timest: Timestamp, dcs: Vec<(DcId, DrawCall)>) {
  839. if DEBUG_GFXAPI {
  840. d!("Invoked method: replace_draw_calls({:?})", dcs);
  841. }
  842. // Phase 1: Check for conflicts with newer batches
  843. // If any draw call in this batch belongs to an older batch than the existing one,
  844. // reject the entire batch to maintain atomicity
  845. for (key, _) in &dcs {
  846. if let Some(old_val) = self.draw_calls.get(key) {
  847. if old_val.timest > batch_timest {
  848. // Entire batch is stale, reject all
  849. t!("Rejected stale batch {batch_timest}: conflict with newer batch {} on {key}", old_val.timest);
  850. if DEBUG_TRAX {
  851. get_trax().lock().put_stat(3); // New stat: rejected batch
  852. }
  853. return;
  854. }
  855. }
  856. }
  857. // Phase 2: Apply entire batch atomically
  858. for (key, val) in dcs {
  859. let val = val.compile(&self.textures, &self.buffers, batch_timest);
  860. // Insert/replace draw call
  861. self.draw_calls.insert(key, val);
  862. if DEBUG_TRAX {
  863. get_trax().lock().put_stat(1); // Success
  864. }
  865. }
  866. }
  867. fn trax_method(&self, epoch: EpochIndex, method: &GraphicsMethod) {
  868. let mut trax = get_trax().lock();
  869. match method {
  870. GraphicsMethod::NewTexture((_, _, _, _, gtex_id, tag)) => {
  871. trax.put_tex(epoch, *gtex_id, *tag);
  872. }
  873. GraphicsMethod::DeleteTexture((gtex_id, tag)) => {
  874. trax.del_tex(epoch, *gtex_id, *tag);
  875. }
  876. GraphicsMethod::NewVertexBuffer((verts, gbuff_id, tag)) => {
  877. trax.put_verts(epoch, verts.clone(), *gbuff_id, *tag, 0);
  878. }
  879. GraphicsMethod::NewIndexBuffer((idxs, gbuff_id, tag)) => {
  880. trax.put_idxs(epoch, idxs.clone(), *gbuff_id, *tag, 1);
  881. }
  882. GraphicsMethod::DeleteBuffer((gbuff_id, tag, buftype)) => {
  883. trax.del_buf(epoch, *gbuff_id, *tag, *buftype);
  884. }
  885. GraphicsMethod::NewSeqAnim { .. } => {
  886. //trax.put_idxs(epoch, idxs.clone(), *gbuff_id, *tag, 1);
  887. }
  888. GraphicsMethod::UpdateSeqAnim { .. } => {
  889. //trax.put_idxs(epoch, idxs.clone(), *gbuff_id, *tag, 1);
  890. }
  891. GraphicsMethod::DeleteSeqAnim(..) => {
  892. //trax.del_buf(epoch, *gbuff_id, *tag, *buftype);
  893. }
  894. GraphicsMethod::ReplaceGfxDrawCalls { batch_id, dcs } => {
  895. trax.put_dcs(epoch, *batch_id, dcs);
  896. }
  897. GraphicsMethod::StartBatch { batch_id, tag } => {
  898. trax.put_start_batch(epoch, *batch_id, *tag);
  899. }
  900. GraphicsMethod::EndBatch { batch_id, timest: _ } => {
  901. trax.put_end_batch(epoch, *batch_id);
  902. }
  903. GraphicsMethod::Noop => panic!("noop"),
  904. };
  905. }
  906. fn egl_ctx_is_disabled(&self) -> bool {
  907. #[cfg(target_os = "android")]
  908. {
  909. let egl_ctx = unsafe { (self.libegl.eglGetCurrentContext)() };
  910. egl_ctx.is_null()
  911. }
  912. #[cfg(not(target_os = "android"))]
  913. false
  914. }
  915. #[instrument(skip_all, target = "gfx::process")]
  916. fn process_methods(&mut self) {
  917. // Process as many methods as we can
  918. while let Ok((epoch, method)) = self.method_recv.try_recv() {
  919. if DEBUG_TRAX {
  920. self.trax_method(epoch, &method);
  921. }
  922. if epoch < self.epoch {
  923. if DEBUG_TRAX {
  924. let mut trax = get_trax().lock();
  925. trax.put_stat(1);
  926. trax.flush();
  927. }
  928. // Discard old rubbish
  929. t!(
  930. "Discard method with old epoch: {epoch} curr: {} [method={method:?}]",
  931. self.epoch
  932. );
  933. continue
  934. }
  935. assert_eq!(epoch, self.epoch);
  936. self.process_method(method);
  937. if DEBUG_TRAX {
  938. get_trax().lock().flush();
  939. }
  940. }
  941. }
  942. #[instrument(skip_all, target = "gfx::pruner")]
  943. fn prime_screen(&mut self) {
  944. let methods = self.pruner.recv_all();
  945. assert!(self.pending_batches.is_empty());
  946. // Process all cached methods by the pruner from while the screen was off.
  947. for method in methods {
  948. // Stale methods will be dropped by pruner, so they will not be caught by trax
  949. // while the screen is off.
  950. if DEBUG_TRAX {
  951. self.trax_method(self.epoch, &method);
  952. }
  953. // We discard batches here but process_method uses them so implement this
  954. // workaround.
  955. match method {
  956. GraphicsMethod::NewTexture(_) |
  957. GraphicsMethod::DeleteTexture(_) |
  958. GraphicsMethod::NewVertexBuffer(_) |
  959. GraphicsMethod::NewIndexBuffer(_) |
  960. GraphicsMethod::DeleteBuffer(_) |
  961. GraphicsMethod::NewSeqAnim { .. } |
  962. GraphicsMethod::UpdateSeqAnim { .. } |
  963. GraphicsMethod::DeleteSeqAnim(_) => self.process_method(method),
  964. GraphicsMethod::ReplaceGfxDrawCalls { .. } |
  965. GraphicsMethod::StartBatch { .. } |
  966. GraphicsMethod::EndBatch { .. } => {
  967. panic!("unsupported pruned methods should be dropped!")
  968. }
  969. GraphicsMethod::Noop => panic!("noop"),
  970. }
  971. if DEBUG_TRAX {
  972. get_trax().lock().flush();
  973. }
  974. }
  975. // Trigger a full screen redraw by sending a resize event
  976. let (width, height) = miniquad::window::screen_size();
  977. self.event_pub.notify_resize(Dimension::from([width, height]));
  978. }
  979. fn close_pending_batches(&mut self) {
  980. // Immediately apply any pending batches when the screen is switched off
  981. let batch_ids: Vec<_> = self.pending_batches.keys().cloned().collect();
  982. if !batch_ids.is_empty() {
  983. t!("Force closing pending batches: {batch_ids:?}");
  984. }
  985. for batch_id in batch_ids {
  986. self.process_method(GraphicsMethod::EndBatch { batch_id, timest: unixtime() });
  987. if !self.dropped_batches.insert(batch_id) {
  988. panic!("dropped batch {batch_id} already exits!");
  989. }
  990. }
  991. assert!(self.pending_batches.is_empty());
  992. }
  993. }
  994. #[derive(Copy, Clone, Debug, PartialEq)]
  995. enum ScreenState {
  996. // Screen is on as normal
  997. On,
  998. // First update since screen has gone off
  999. SwitchOff,
  1000. // Subsequent updates after SwitchOff state
  1001. Off,
  1002. // First update when screen is on but before draw has been called
  1003. ReadyOn,
  1004. // First update and draw has been called
  1005. PrimedOn,
  1006. // Second update ready to process pruned buffered allocs
  1007. SwitchOn,
  1008. }
  1009. impl ScreenState {
  1010. fn update(&mut self, egl_is_disabled: bool) {
  1011. use ScreenState::*;
  1012. *self = if egl_is_disabled {
  1013. match self {
  1014. On | ReadyOn | PrimedOn | SwitchOn => SwitchOff,
  1015. SwitchOff => Off,
  1016. Off => Off,
  1017. }
  1018. } else {
  1019. match self {
  1020. SwitchOff | Off => ReadyOn,
  1021. ReadyOn => PrimedOn,
  1022. PrimedOn => SwitchOn,
  1023. SwitchOn => On,
  1024. On => On,
  1025. }
  1026. };
  1027. }
  1028. }
  1029. impl EventHandler for Stage {
  1030. fn update(&mut self) {
  1031. // todo: trax is all messed up in this func
  1032. let old_screen_state = self.screen_state;
  1033. self.screen_state.update(self.egl_ctx_is_disabled());
  1034. if self.screen_state != old_screen_state {
  1035. d!("Switching screen state {old_screen_state:?} => {:?}", self.screen_state);
  1036. }
  1037. match self.screen_state {
  1038. ScreenState::SwitchOff => {
  1039. self.close_pending_batches();
  1040. // Screen is off so collect all methods into the pruner
  1041. self.pruner.drain(&self.method_recv);
  1042. }
  1043. ScreenState::Off => {
  1044. assert!(self.pending_batches.is_empty());
  1045. // Screen is off so collect all methods into the pruner
  1046. self.pruner.drain(&self.method_recv);
  1047. }
  1048. ScreenState::ReadyOn => {
  1049. // We actually want to skip draining the prune queue the first time so
  1050. // miniquad draw() actually gets a chance to be called first.
  1051. // Otherwise we will see a black screen for a sec or so while update() is running.
  1052. }
  1053. ScreenState::PrimedOn => {
  1054. self.prime_screen();
  1055. }
  1056. ScreenState::SwitchOn => {
  1057. // This should have been cleared in previous PrimedOn state
  1058. let methods = self.pruner.recv_all();
  1059. assert!(methods.is_empty());
  1060. self.process_methods();
  1061. }
  1062. ScreenState::On => {
  1063. self.process_methods();
  1064. }
  1065. }
  1066. }
  1067. fn draw(&mut self) {
  1068. self.ctx.begin_default_pass(PassAction::clear_color(0., 0., 0., 1.));
  1069. // Apply default RGB pipeline
  1070. self.ctx.apply_pipeline(&self.loaded_pipelines[GraphicPipeline::RGB as usize]);
  1071. // This will make the top left (0, 0) and the bottom right (1, 1)
  1072. // Default is (-1, 1) -> (1, -1)
  1073. let proj = glam::Mat4::from_translation(glam::Vec3::new(-1., 1., 0.)) *
  1074. glam::Mat4::from_scale(glam::Vec3::new(2., -2., 1.));
  1075. let mut uniforms_data = [0u8; 128];
  1076. let data: [u8; 64] = unsafe { std::mem::transmute_copy(&proj) };
  1077. uniforms_data[0..64].copy_from_slice(&data);
  1078. //let data: [u8; 64] = unsafe { std::mem::transmute_copy(&model) };
  1079. //uniforms_data[64..].copy_from_slice(&data);
  1080. assert_eq!(128, 2 * UniformType::Mat4.size());
  1081. let (screen_w, screen_h) = miniquad::window::screen_size();
  1082. // Mark all anims as invisible
  1083. for (_, anim) in self.anims.iter_mut() {
  1084. anim.is_visible = false;
  1085. }
  1086. let mut render_ctx = RenderContext {
  1087. ctx: &mut self.ctx,
  1088. draw_calls: &self.draw_calls,
  1089. uniforms_data,
  1090. white_texture: self.white_texture,
  1091. loaded_pipelines: &self.loaded_pipelines,
  1092. scale: 1.,
  1093. view: Rectangle::from([0., 0., screen_w, screen_h]),
  1094. cursor: Point::zero(),
  1095. gfx_pipeline: GraphicPipeline::RGB,
  1096. anims: &mut self.anims,
  1097. overlays: vec![],
  1098. };
  1099. render_ctx.draw();
  1100. self.ctx.end_render_pass();
  1101. self.ctx.commit_frame();
  1102. }
  1103. fn resize_event(&mut self, width: f32, height: f32) {
  1104. t!("resize_event({width}, {height})");
  1105. let filename = get_window_size_filename();
  1106. if let Some(parent) = filename.parent() {
  1107. let _ = std::fs::create_dir_all(parent);
  1108. }
  1109. if let Ok(mut file) = File::create(filename) {
  1110. (width as i32).encode(&mut file).unwrap();
  1111. (height as i32).encode(&mut file).unwrap();
  1112. }
  1113. self.event_pub.notify_resize(Dimension::from([width, height]));
  1114. }
  1115. fn key_down_event(&mut self, keycode: KeyCode, mods: KeyMods, repeat: bool) {
  1116. self.event_pub.notify_key_down(keycode, mods, repeat);
  1117. }
  1118. fn key_up_event(&mut self, keycode: KeyCode, mods: KeyMods) {
  1119. self.event_pub.notify_key_up(keycode, mods);
  1120. }
  1121. fn char_event(&mut self, chr: char, mods: KeyMods, repeat: bool) {
  1122. self.event_pub.notify_char(chr, mods, repeat);
  1123. }
  1124. fn mouse_button_down_event(&mut self, button: MouseButton, x: f32, y: f32) {
  1125. let pos = Point::from([x, y]);
  1126. self.event_pub.notify_mouse_btn_down(button, pos);
  1127. }
  1128. fn mouse_button_up_event(&mut self, button: MouseButton, x: f32, y: f32) {
  1129. let pos = Point::from([x, y]);
  1130. self.event_pub.notify_mouse_btn_up(button, pos);
  1131. }
  1132. fn mouse_motion_event(&mut self, x: f32, y: f32) {
  1133. let pos = Point::from([x, y]);
  1134. self.event_pub.notify_mouse_move(pos);
  1135. }
  1136. fn mouse_wheel_event(&mut self, x: f32, y: f32) {
  1137. let pos = Point::from([x, y]);
  1138. self.event_pub.notify_mouse_wheel(pos);
  1139. }
  1140. /// The id corresponds to multi-touch. Multiple touch events have different ids.
  1141. fn touch_event(&mut self, phase: TouchPhase, id: u64, x: f32, y: f32) {
  1142. let pos = Point::from([x, y]);
  1143. // Lazy cache window on first touch event
  1144. if self.window_node.is_none() {
  1145. let god = GOD.get().unwrap();
  1146. self.window_node = god.app.sg_root.lookup_node("/window");
  1147. }
  1148. // Direct call to Window's handle_touch_event_sync
  1149. if let Some(window_node) = &self.window_node {
  1150. match window_node.pimpl() {
  1151. Pimpl::Window(win) => {
  1152. if win.handle_touch_sync(phase, id, pos) {
  1153. return
  1154. }
  1155. }
  1156. _ => panic!(),
  1157. }
  1158. }
  1159. self.event_pub.notify_touch(phase, id, pos);
  1160. }
  1161. fn quit_requested_event(&mut self) {
  1162. debug!(target: "gfx", "quit requested");
  1163. let god = GOD.get().unwrap();
  1164. god.stop_app();
  1165. }
  1166. }
  1167. pub fn run_gui(linux_backend: miniquad::conf::LinuxBackend) {
  1168. let mut window_width = 1024;
  1169. let mut window_height = 768;
  1170. if let Ok(mut file) = File::open(get_window_size_filename()) {
  1171. window_width = Decodable::decode(&mut file).unwrap();
  1172. window_height = Decodable::decode(&mut file).unwrap();
  1173. }
  1174. debug!(target: "gfx", "Window size {window_width} x {window_height}");
  1175. let mut conf = miniquad::conf::Conf {
  1176. window_title: "DarkFi".to_string(),
  1177. window_width,
  1178. window_height,
  1179. high_dpi: true,
  1180. window_resizable: true,
  1181. platform: miniquad::conf::Platform {
  1182. linux_backend,
  1183. #[cfg(target_os = "android")]
  1184. blocking_event_loop: true,
  1185. #[cfg(target_os = "android")]
  1186. sleep_interval_ms: Some(40),
  1187. android_panic_hook: false,
  1188. ..Default::default()
  1189. },
  1190. icon: Some(miniquad::conf::Icon {
  1191. small: favico::SMALL,
  1192. medium: favico::MEDIUM,
  1193. big: favico::BIG,
  1194. }),
  1195. ..Default::default()
  1196. };
  1197. let metal = std::env::args().nth(1).as_deref() == Some("metal");
  1198. conf.platform.apple_gfx_api =
  1199. if metal { conf::AppleGfxApi::Metal } else { conf::AppleGfxApi::OpenGl };
  1200. miniquad::start(conf, || Box::new(Stage::new()));
  1201. }