SceneBuilder.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. using System;
  2. using System.Collections.Generic;
  3. using Avalonia.Media;
  4. using Avalonia.Platform;
  5. using Avalonia.Threading;
  6. using Avalonia.VisualTree;
  7. namespace Avalonia.Rendering.SceneGraph
  8. {
  9. /// <summary>
  10. /// Builds a scene graph from a visual tree.
  11. /// </summary>
  12. public class SceneBuilder : ISceneBuilder
  13. {
  14. /// <inheritdoc/>
  15. public void UpdateAll(Scene scene)
  16. {
  17. _ = scene ?? throw new ArgumentNullException(nameof(scene));
  18. Dispatcher.UIThread.VerifyAccess();
  19. UpdateSize(scene);
  20. scene.Layers.GetOrAdd(scene.Root.Visual);
  21. using (var impl = new DeferredDrawingContextImpl(this, scene.Layers))
  22. using (var context = new DrawingContext(impl))
  23. {
  24. var clip = new Rect(scene.Root.Visual.Bounds.Size);
  25. Update(context, scene, (VisualNode)scene.Root, clip, true);
  26. }
  27. }
  28. /// <inheritdoc/>
  29. public bool Update(Scene scene, Visual visual)
  30. {
  31. _ = scene ?? throw new ArgumentNullException(nameof(scene));
  32. _ = visual ?? throw new ArgumentNullException(nameof(visual));
  33. Dispatcher.UIThread.VerifyAccess();
  34. if (!scene.Root.Visual.IsVisible)
  35. {
  36. throw new AvaloniaInternalException("Cannot update the scene for an invisible root visual.");
  37. }
  38. var node = (VisualNode?)scene.FindNode(visual);
  39. if (visual == scene.Root.Visual)
  40. {
  41. UpdateSize(scene);
  42. }
  43. if (visual.VisualRoot == scene.Root.Visual)
  44. {
  45. if (node?.Parent != null &&
  46. visual.VisualParent != null &&
  47. node.Parent.Visual != visual.VisualParent)
  48. {
  49. // The control has changed parents. Remove the node and recurse into the new parent node.
  50. ((VisualNode)node.Parent).RemoveChild(node);
  51. Deindex(scene, node);
  52. node = (VisualNode?)scene.FindNode(visual.VisualParent);
  53. }
  54. if (visual.IsVisible)
  55. {
  56. // If the node isn't yet part of the scene, find the nearest ancestor that is.
  57. node = node ?? FindExistingAncestor(scene, visual);
  58. // We don't need to do anything if this part of the tree has already been fully
  59. // updated.
  60. if (node != null && !node.SubTreeUpdated)
  61. {
  62. // If the control we've been asked to update isn't part of the scene then
  63. // we're carrying out an add operation, so recurse and add all the
  64. // descendents too.
  65. var recurse = node.Visual != visual;
  66. using (var impl = new DeferredDrawingContextImpl(this, scene.Layers))
  67. using (var context = new DrawingContext(impl))
  68. {
  69. var clip = new Rect(scene.Root.Visual.Bounds.Size);
  70. if (node.Parent != null)
  71. {
  72. context.PushPostTransform(node.Parent.Transform);
  73. clip = node.Parent.ClipBounds;
  74. }
  75. using (context.PushTransformContainer())
  76. {
  77. Update(context, scene, node, clip, recurse);
  78. }
  79. }
  80. return true;
  81. }
  82. }
  83. else
  84. {
  85. if (node != null)
  86. {
  87. // The control has been hidden so remove it from its parent and deindex the
  88. // node and its descendents.
  89. ((VisualNode?)node.Parent)?.RemoveChild(node);
  90. Deindex(scene, node);
  91. return true;
  92. }
  93. }
  94. }
  95. else if (node != null)
  96. {
  97. // The control has been removed so remove it from its parent and deindex the
  98. // node and its descendents.
  99. var trim = FindFirstDeadAncestor(scene, node);
  100. ((VisualNode)trim.Parent!).RemoveChild(trim);
  101. Deindex(scene, trim);
  102. return true;
  103. }
  104. return false;
  105. }
  106. private static VisualNode? FindExistingAncestor(Scene scene, Visual visual)
  107. {
  108. var node = scene.FindNode(visual);
  109. while (node == null && visual.IsVisible)
  110. {
  111. var parent = visual.VisualParent;
  112. if (parent is null)
  113. return null;
  114. visual = parent;
  115. node = scene.FindNode(visual);
  116. }
  117. return visual.IsVisible ? (VisualNode?)node : null;
  118. }
  119. private static VisualNode FindFirstDeadAncestor(Scene scene, IVisualNode node)
  120. {
  121. var parent = node.Parent;
  122. while (parent!.Visual.VisualRoot == null)
  123. {
  124. node = parent;
  125. parent = node.Parent;
  126. }
  127. return (VisualNode)node;
  128. }
  129. private static object GetOrCreateChildNode(Scene scene, Visual child, VisualNode parent)
  130. {
  131. var result = (VisualNode?)scene.FindNode(child);
  132. if (result != null && result.Parent != parent)
  133. {
  134. Deindex(scene, result);
  135. ((VisualNode?)result.Parent)?.RemoveChild(result);
  136. result = null;
  137. }
  138. return result ?? CreateNode(scene, child, parent);
  139. }
  140. private static void Update(DrawingContext context, Scene scene, VisualNode node, Rect clip, bool forceRecurse)
  141. {
  142. var visual = node.Visual;
  143. var opacity = visual.Opacity;
  144. var clipToBounds = visual.ClipToBounds;
  145. #pragma warning disable CS0618 // Type or member is obsolete
  146. var clipToBoundsRadius = visual is IVisualWithRoundRectClip roundRectClip ?
  147. roundRectClip.ClipToBoundsRadius :
  148. default;
  149. #pragma warning restore CS0618 // Type or member is obsolete
  150. var bounds = new Rect(visual.Bounds.Size);
  151. var contextImpl = (DeferredDrawingContextImpl)context.PlatformImpl;
  152. contextImpl.Layers.Find(node.LayerRoot!)?.Dirty.Add(node.Bounds);
  153. if (visual.IsVisible)
  154. {
  155. var m = node != scene.Root ?
  156. Matrix.CreateTranslation(visual.Bounds.Position) :
  157. Matrix.Identity;
  158. var renderTransform = Matrix.Identity;
  159. // this should be calculated BEFORE renderTransform
  160. if (visual.HasMirrorTransform)
  161. {
  162. var mirrorMatrix = new Matrix(-1.0, 0.0, 0.0, 1.0, visual.Bounds.Width, 0);
  163. renderTransform *= mirrorMatrix;
  164. }
  165. if (visual.RenderTransform != null)
  166. {
  167. var origin = visual.RenderTransformOrigin.ToPixels(new Size(visual.Bounds.Width, visual.Bounds.Height));
  168. var offset = Matrix.CreateTranslation(origin);
  169. var finalTransform = (-offset) * visual.RenderTransform.Value * (offset);
  170. renderTransform *= finalTransform;
  171. }
  172. m = renderTransform * m;
  173. using (contextImpl.BeginUpdate(node))
  174. using (context.PushPostTransform(m))
  175. using (context.PushTransformContainer())
  176. {
  177. var globalBounds = bounds.TransformToAABB(contextImpl.Transform);
  178. var clipBounds = clipToBounds ?
  179. globalBounds.Intersect(clip) :
  180. clip;
  181. forceRecurse = forceRecurse ||
  182. node.ClipBounds != clipBounds ||
  183. node.Opacity != opacity ||
  184. node.Transform != contextImpl.Transform;
  185. node.Transform = contextImpl.Transform;
  186. node.ClipBounds = clipBounds;
  187. node.ClipToBounds = clipToBounds;
  188. node.LayoutBounds = globalBounds;
  189. node.ClipToBoundsRadius = clipToBoundsRadius;
  190. node.GeometryClip = visual.Clip?.PlatformImpl;
  191. node.Opacity = opacity;
  192. // TODO: Check equality between node.OpacityMask and visual.OpacityMask before assigning.
  193. node.OpacityMask = visual.OpacityMask?.ToImmutable();
  194. if (ShouldStartLayer(visual))
  195. {
  196. if (node.LayerRoot != visual)
  197. {
  198. MakeLayer(scene, node);
  199. }
  200. else
  201. {
  202. UpdateLayer(node, scene.Layers[node.LayerRoot]);
  203. }
  204. }
  205. else if (node.LayerRoot == node.Visual && node.Parent != null)
  206. {
  207. ClearLayer(scene, node);
  208. }
  209. if (node.ClipToBounds)
  210. {
  211. clip = clip.Intersect(node.ClipBounds);
  212. }
  213. try
  214. {
  215. visual.Render(context);
  216. }
  217. catch { }
  218. var transformed = new TransformedBounds(new Rect(visual.Bounds.Size), clip, node.Transform);
  219. visual.SetTransformedBounds(transformed);
  220. if (forceRecurse)
  221. {
  222. var visualChildren = (IList<Visual>) visual.VisualChildren;
  223. node.TryPreallocateChildren(visualChildren.Count);
  224. if (visualChildren.Count == 1)
  225. {
  226. var childNode = GetOrCreateChildNode(scene, visualChildren[0], node);
  227. Update(context, scene, (VisualNode)childNode, clip, forceRecurse);
  228. }
  229. else if (visualChildren.Count > 1)
  230. {
  231. var count = visualChildren.Count;
  232. if (visual.HasNonUniformZIndexChildren)
  233. {
  234. var sortedChildren = new (Visual visual, int index)[count];
  235. for (var i = 0; i < count; i++)
  236. {
  237. sortedChildren[i] = (visualChildren[i], i);
  238. }
  239. // Regular Array.Sort is unstable, we need to provide indices as well to avoid reshuffling elements.
  240. Array.Sort(sortedChildren, (lhs, rhs) =>
  241. {
  242. var result = ZIndexComparer.Instance.Compare(lhs.visual, rhs.visual);
  243. return result == 0 ? lhs.index.CompareTo(rhs.index) : result;
  244. });
  245. foreach (var child in sortedChildren)
  246. {
  247. var childNode = GetOrCreateChildNode(scene, child.Item1, node);
  248. Update(context, scene, (VisualNode)childNode, clip, forceRecurse);
  249. }
  250. }
  251. else
  252. foreach (var child in visualChildren)
  253. {
  254. var childNode = GetOrCreateChildNode(scene, child, node);
  255. Update(context, scene, (VisualNode)childNode, clip, forceRecurse);
  256. }
  257. }
  258. node.SubTreeUpdated = true;
  259. contextImpl.TrimChildren();
  260. }
  261. }
  262. }
  263. else
  264. {
  265. contextImpl.BeginUpdate(node).Dispose();
  266. }
  267. }
  268. private static void UpdateSize(Scene scene)
  269. {
  270. var renderRoot = scene.Root.Visual as IRenderRoot;
  271. var newSize = renderRoot?.ClientSize ?? scene.Root.Visual.Bounds.Size;
  272. scene.Scaling = renderRoot?.RenderScaling ?? 1;
  273. if (scene.Size != newSize)
  274. {
  275. var oldSize = scene.Size;
  276. scene.Size = newSize;
  277. Rect horizontalDirtyRect = default;
  278. Rect verticalDirtyRect = default;
  279. if (newSize.Width > oldSize.Width)
  280. {
  281. horizontalDirtyRect = new Rect(oldSize.Width, 0, newSize.Width - oldSize.Width, oldSize.Height);
  282. }
  283. if (newSize.Height > oldSize.Height)
  284. {
  285. verticalDirtyRect = new Rect(0, oldSize.Height, newSize.Width, newSize.Height - oldSize.Height);
  286. }
  287. foreach (var layer in scene.Layers)
  288. {
  289. layer.Dirty.Add(horizontalDirtyRect);
  290. layer.Dirty.Add(verticalDirtyRect);
  291. }
  292. }
  293. }
  294. private static VisualNode CreateNode(Scene scene, Visual visual, VisualNode parent)
  295. {
  296. var node = new VisualNode(visual, parent);
  297. node.LayerRoot = parent.LayerRoot;
  298. scene.Add(node);
  299. return node;
  300. }
  301. private static void Deindex(Scene scene, VisualNode node)
  302. {
  303. var nodeChildren = node.Children;
  304. var nodeChildrenCount = nodeChildren.Count;
  305. for (var i = 0; i < nodeChildrenCount; i++)
  306. {
  307. if (nodeChildren[i] is VisualNode visual)
  308. {
  309. Deindex(scene, visual);
  310. }
  311. }
  312. scene.Remove(node);
  313. node.SubTreeUpdated = true;
  314. scene.Layers[node.LayerRoot!].Dirty.Add(node.Bounds);
  315. node.Visual.SetTransformedBounds(null);
  316. if (node.LayerRoot == node.Visual && node.Visual != scene.Root.Visual)
  317. {
  318. scene.Layers.Remove(node.LayerRoot);
  319. }
  320. }
  321. private static void ClearLayer(Scene scene, VisualNode node)
  322. {
  323. var parent = (VisualNode)node.Parent!;
  324. var oldLayerRoot = node.LayerRoot;
  325. var newLayerRoot = parent.LayerRoot!;
  326. var existingDirtyRects = scene.Layers[node.LayerRoot!].Dirty;
  327. var newDirtyRects = scene.Layers[newLayerRoot].Dirty;
  328. existingDirtyRects.Coalesce();
  329. foreach (var r in existingDirtyRects)
  330. {
  331. newDirtyRects.Add(r);
  332. }
  333. var oldLayer = scene.Layers[oldLayerRoot!];
  334. PropagateLayer(node, scene.Layers[newLayerRoot], oldLayer);
  335. scene.Layers.Remove(oldLayer);
  336. }
  337. private static void MakeLayer(Scene scene, VisualNode node)
  338. {
  339. var oldLayerRoot = node.LayerRoot!;
  340. var layer = scene.Layers.Add(node.Visual);
  341. var oldLayer = scene.Layers[oldLayerRoot!];
  342. UpdateLayer(node, layer);
  343. PropagateLayer(node, layer, scene.Layers[oldLayerRoot]);
  344. }
  345. private static void UpdateLayer(VisualNode node, SceneLayer layer)
  346. {
  347. layer.Opacity = node.Visual.Opacity;
  348. if (node.Visual.OpacityMask != null)
  349. {
  350. layer.OpacityMask = node.Visual.OpacityMask?.ToImmutable();
  351. layer.OpacityMaskRect = node.ClipBounds;
  352. }
  353. else
  354. {
  355. layer.OpacityMask = null;
  356. layer.OpacityMaskRect = default;
  357. }
  358. layer.GeometryClip = node.HasAncestorGeometryClip ?
  359. CreateLayerGeometryClip(node) :
  360. null;
  361. }
  362. private static void PropagateLayer(VisualNode node, SceneLayer layer, SceneLayer oldLayer)
  363. {
  364. node.LayerRoot = layer.LayerRoot;
  365. layer.Dirty.Add(node.Bounds);
  366. oldLayer.Dirty.Add(node.Bounds);
  367. foreach (VisualNode child in node.Children)
  368. {
  369. // If the child is not the start of a new layer, recurse.
  370. if (child.LayerRoot != child.Visual)
  371. {
  372. PropagateLayer(child, layer, oldLayer);
  373. }
  374. }
  375. }
  376. // HACK: Disabled layers because they're broken in current renderer. See #2244.
  377. private static bool ShouldStartLayer(Visual visual) => false;
  378. private static IGeometryImpl? CreateLayerGeometryClip(VisualNode node)
  379. {
  380. IGeometryImpl? result = null;
  381. VisualNode? n = node;
  382. for (;;)
  383. {
  384. n = (VisualNode?)n!.Parent;
  385. if (n == null || (n.GeometryClip == null && !n.HasAncestorGeometryClip))
  386. {
  387. break;
  388. }
  389. if (n?.GeometryClip != null)
  390. {
  391. var transformed = n.GeometryClip.WithTransform(n.Transform);
  392. result = result == null ? transformed : result.Intersect(transformed);
  393. }
  394. }
  395. return result;
  396. }
  397. }
  398. }