image.rs 7.3 KB

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