image.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 async_trait::async_trait;
  19. use image::ImageReader;
  20. use rand::{rngs::OsRng, Rng};
  21. use std::{
  22. io::Cursor,
  23. sync::{Arc, Mutex as SyncMutex, OnceLock, Weak},
  24. };
  25. use crate::{
  26. gfx::{
  27. GfxDrawCall, GfxDrawInstruction, GfxDrawMesh, GfxTextureId, ManagedTexturePtr, Rectangle,
  28. RenderApi,
  29. },
  30. mesh::{MeshBuilder, MeshInfo, COLOR_WHITE},
  31. prop::{PropertyAtomicGuard, PropertyPtr, PropertyRect, PropertyStr, PropertyUint32, Role},
  32. scene::{Pimpl, SceneNodePtr, SceneNodeWeak},
  33. util::unixtime,
  34. ExecutorPtr,
  35. };
  36. use super::{DrawUpdate, OnModify, UIObject};
  37. macro_rules! d { ($($arg:tt)*) => { debug!(target: "ui::image", $($arg)*); } }
  38. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::image", $($arg)*); } }
  39. pub type ImagePtr = Arc<Image>;
  40. pub struct Image {
  41. node: SceneNodeWeak,
  42. render_api: RenderApi,
  43. tasks: OnceLock<Vec<smol::Task<()>>>,
  44. texture: SyncMutex<Option<ManagedTexturePtr>>,
  45. dc_key: u64,
  46. rect: PropertyRect,
  47. uv: PropertyRect,
  48. z_index: PropertyUint32,
  49. priority: PropertyUint32,
  50. path: PropertyStr,
  51. parent_rect: SyncMutex<Option<Rectangle>>,
  52. }
  53. impl Image {
  54. pub async fn new(node: SceneNodeWeak, render_api: RenderApi, ex: ExecutorPtr) -> Pimpl {
  55. t!("Image::new()");
  56. let node_ref = &node.upgrade().unwrap();
  57. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  58. let uv = PropertyRect::wrap(node_ref, Role::Internal, "uv").unwrap();
  59. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  60. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  61. let path = PropertyStr::wrap(node_ref, Role::Internal, "path", 0).unwrap();
  62. let node_name = node_ref.name.clone();
  63. let node_id = node_ref.id;
  64. let self_ = Arc::new(Self {
  65. node,
  66. render_api,
  67. tasks: OnceLock::new(),
  68. texture: SyncMutex::new(None),
  69. dc_key: OsRng.gen(),
  70. rect,
  71. uv,
  72. z_index,
  73. priority,
  74. path,
  75. parent_rect: SyncMutex::new(None),
  76. });
  77. *self_.texture.lock().unwrap() = Some(self_.load_texture());
  78. Pimpl::Image(self_)
  79. }
  80. async fn reload(self: Arc<Self>) {
  81. let texture = self.load_texture();
  82. let old_texture = std::mem::replace(&mut *self.texture.lock().unwrap(), Some(texture));
  83. self.clone().redraw().await;
  84. }
  85. fn load_texture(&self) -> ManagedTexturePtr {
  86. let path = self.path.get();
  87. // TODO we should NOT use panic here
  88. let data = Arc::new(SyncMutex::new(vec![]));
  89. let data2 = data.clone();
  90. miniquad::fs::load_file(&path.clone(), move |res| match res {
  91. Ok(res) => *data2.lock().unwrap() = res,
  92. Err(e) => {
  93. error!(target: "ui::image", "Unable to open image: {path}");
  94. panic!("Resource not found!");
  95. }
  96. });
  97. let data = std::mem::take(&mut *data.lock().unwrap());
  98. let img =
  99. ImageReader::new(Cursor::new(data)).with_guessed_format().unwrap().decode().unwrap();
  100. let img = img.to_rgba8();
  101. //let img = image::ImageReader::open(path).unwrap().decode().unwrap().to_rgba8();
  102. let width = img.width() as u16;
  103. let height = img.height() as u16;
  104. let bmp = img.into_raw();
  105. self.render_api.new_texture(width, height, bmp)
  106. }
  107. async fn redraw(self: Arc<Self>) {
  108. let trace_id = rand::random();
  109. let timest = unixtime();
  110. t!("redraw({:?}) [trace_id={trace_id}]", self.node.upgrade().unwrap());
  111. let Some(parent_rect) = self.parent_rect.lock().unwrap().clone() else { return };
  112. let Some(draw_update) = self.get_draw_calls(parent_rect, trace_id).await else {
  113. error!(target: "ui::image", "Image failed to draw");
  114. return
  115. };
  116. self.render_api.replace_draw_calls(timest, draw_update.draw_calls);
  117. t!("redraw() DONE [trace_id={trace_id}]");
  118. }
  119. /// Called whenever any property changes.
  120. fn regen_mesh(&self) -> MeshInfo {
  121. let rect = self.rect.get();
  122. let uv = self.uv.get();
  123. let mesh_rect = Rectangle::from([0., 0., rect.w, rect.h]);
  124. let mut mesh = MeshBuilder::new();
  125. mesh.draw_box(&mesh_rect, COLOR_WHITE, &uv);
  126. mesh.alloc(&self.render_api)
  127. }
  128. async fn get_draw_calls(&self, parent_rect: Rectangle, _: u32) -> Option<DrawUpdate> {
  129. self.rect.eval(&parent_rect).ok()?;
  130. let rect = self.rect.get();
  131. self.uv.eval(&rect).ok()?;
  132. let mesh = self.regen_mesh();
  133. let texture = self.texture.lock().unwrap().clone().expect("Node missing texture_id!");
  134. let mesh = GfxDrawMesh {
  135. vertex_buffer: mesh.vertex_buffer,
  136. index_buffer: mesh.index_buffer,
  137. texture: Some(texture),
  138. num_elements: mesh.num_elements,
  139. };
  140. Some(DrawUpdate {
  141. key: self.dc_key,
  142. draw_calls: vec![(
  143. self.dc_key,
  144. GfxDrawCall {
  145. instrs: vec![
  146. GfxDrawInstruction::Move(rect.pos()),
  147. GfxDrawInstruction::Draw(mesh),
  148. ],
  149. dcs: vec![],
  150. z_index: self.z_index.get(),
  151. },
  152. )],
  153. })
  154. }
  155. }
  156. #[async_trait]
  157. impl UIObject for Image {
  158. fn priority(&self) -> u32 {
  159. self.priority.get()
  160. }
  161. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  162. let me = Arc::downgrade(&self);
  163. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  164. on_modify.when_change(self.rect.prop(), Self::redraw);
  165. on_modify.when_change(self.uv.prop(), Self::redraw);
  166. on_modify.when_change(self.z_index.prop(), Self::redraw);
  167. on_modify.when_change(self.path.prop(), Self::reload);
  168. self.tasks.set(on_modify.tasks);
  169. }
  170. async fn draw(
  171. &self,
  172. parent_rect: Rectangle,
  173. trace_id: u32,
  174. atom: &mut PropertyAtomicGuard,
  175. ) -> Option<DrawUpdate> {
  176. t!("Image::draw() [trace_id={trace_id}]");
  177. *self.parent_rect.lock().unwrap() = Some(parent_rect);
  178. self.get_draw_calls(parent_rect, trace_id).await
  179. }
  180. }
  181. impl Drop for Image {
  182. fn drop(&mut self) {
  183. self.render_api.replace_draw_calls(unixtime(), vec![(self.dc_key, Default::default())]);
  184. }
  185. }