mod.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 parking_lot::Mutex as SyncMutex;
  20. use rand::{rngs::OsRng, Rng};
  21. use std::sync::Arc;
  22. use crate::{
  23. gfx::{gfxtag, DrawCall, DrawInstruction, DrawMesh, Rectangle, RenderApi},
  24. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyBool, PropertyRect, PropertyUint32, Role},
  25. scene::{Pimpl, SceneNodeWeak},
  26. util::unixtime,
  27. ExecutorPtr,
  28. };
  29. use super::{DrawTrace, DrawUpdate, OnModify, UIObject};
  30. pub mod shape;
  31. use shape::VectorShape;
  32. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui::vector_art", $($arg)*); } }
  33. pub type VectorArtPtr = Arc<VectorArt>;
  34. pub struct VectorArt {
  35. node: SceneNodeWeak,
  36. render_api: RenderApi,
  37. tasks: SyncMutex<Vec<smol::Task<()>>>,
  38. shape: VectorShape,
  39. dc_key: u64,
  40. is_visible: PropertyBool,
  41. rect: PropertyRect,
  42. z_index: PropertyUint32,
  43. priority: PropertyUint32,
  44. parent_rect: SyncMutex<Option<Rectangle>>,
  45. }
  46. impl VectorArt {
  47. pub async fn new(node: SceneNodeWeak, shape: VectorShape, render_api: RenderApi) -> Pimpl {
  48. t!("VectorArt::new()");
  49. let node_ref = &node.upgrade().unwrap();
  50. let is_visible = PropertyBool::wrap(node_ref, Role::Internal, "is_visible", 0).unwrap();
  51. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").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 self_ = Arc::new(Self {
  55. node,
  56. render_api,
  57. tasks: SyncMutex::new(vec![]),
  58. shape,
  59. dc_key: OsRng.gen(),
  60. is_visible,
  61. rect,
  62. z_index,
  63. priority,
  64. parent_rect: SyncMutex::new(None),
  65. });
  66. Pimpl::VectorArt(self_)
  67. }
  68. fn node_path(&self) -> String {
  69. format!("{:?}", self.node.upgrade().unwrap())
  70. }
  71. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  72. let trace = rand::random();
  73. let timest = unixtime();
  74. trace!(target: "ui::vector_art", "VectorArt::redraw({}) [trace={trace}]", self.node_path());
  75. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  76. let atom = &mut batch.spawn();
  77. let Some(draw_update) = self.get_draw_calls(atom, parent_rect, trace).await else {
  78. error!(target: "ui::vector_art", "Mesh failed to draw [trace={trace}]");
  79. return
  80. };
  81. self.render_api.replace_draw_calls(batch.id, timest, draw_update.draw_calls);
  82. }
  83. fn get_draw_instrs(&self) -> Vec<DrawInstruction> {
  84. if !self.is_visible.get() {
  85. t!("Skipping draw for invisible {}", self.node_path());
  86. return vec![]
  87. }
  88. let rect = self.rect.get();
  89. let verts = self.shape.eval(rect.w, rect.h).expect("bad shape");
  90. let indices = self.shape.indices.clone();
  91. let num_elements = self.shape.indices.len() as i32;
  92. //debug!(target: "ui::vector_art", "vec_draw_instrs {verts:?} | {indices:?} | {num_elements}");
  93. let vertex_buffer = self.render_api.new_vertex_buffer(verts, gfxtag!("vectorart"));
  94. let index_buffer = self.render_api.new_index_buffer(indices, gfxtag!("vectorart"));
  95. let mesh = DrawMesh { vertex_buffer, index_buffer, texture: None, num_elements };
  96. vec![DrawInstruction::Move(rect.pos()), DrawInstruction::Draw(mesh)]
  97. }
  98. async fn get_draw_calls(
  99. &self,
  100. atom: &mut PropertyAtomicGuard,
  101. parent_rect: Rectangle,
  102. trace: DrawTrace,
  103. ) -> Option<DrawUpdate> {
  104. if let Err(e) = self.rect.eval(atom, &parent_rect) {
  105. warn!(target: "ui::vector_art", "Rect eval failure: {e} [trace={trace}]");
  106. return None
  107. }
  108. let instrs = self.get_draw_instrs();
  109. Some(DrawUpdate {
  110. key: self.dc_key,
  111. draw_calls: vec![(
  112. self.dc_key,
  113. DrawCall::new(instrs, vec![], self.z_index.get(), "vecart"),
  114. )],
  115. })
  116. }
  117. }
  118. #[async_trait]
  119. impl UIObject for VectorArt {
  120. fn priority(&self) -> u32 {
  121. self.priority.get()
  122. }
  123. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  124. let me = Arc::downgrade(&self);
  125. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  126. on_modify.when_change(self.is_visible.prop(), Self::redraw);
  127. on_modify.when_change(self.rect.prop(), Self::redraw);
  128. on_modify.when_change(self.z_index.prop(), Self::redraw);
  129. *self.tasks.lock() = on_modify.tasks;
  130. }
  131. fn stop(&self) {
  132. self.tasks.lock().clear();
  133. *self.parent_rect.lock() = None;
  134. }
  135. async fn draw(
  136. &self,
  137. parent_rect: Rectangle,
  138. trace: DrawTrace,
  139. atom: &mut PropertyAtomicGuard,
  140. ) -> Option<DrawUpdate> {
  141. t!("VectorArt::draw({}) [trace={trace}]", self.node_path());
  142. *self.parent_rect.lock() = Some(parent_rect);
  143. self.get_draw_calls(atom, parent_rect, trace).await
  144. }
  145. }
  146. impl Drop for VectorArt {
  147. fn drop(&mut self) {
  148. let atom = self.render_api.make_guard(gfxtag!("VectorArt::drop"));
  149. self.render_api.replace_draw_calls(
  150. atom.batch_id,
  151. unixtime(),
  152. vec![(self.dc_key, Default::default())],
  153. );
  154. }
  155. }