image.rs 7.1 KB

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