Debian Codegraph @

devel-docs/render_tree.rst

raw
1 Render tree
2 ===========
3
4 For historical reasons, librsvg's code flow during rendering is as
5 follows. The rendering code traverses the SVG tree of elements, and
6 for each one, its ``::draw()`` method is called; its signature looks
7 like this (some arguments omitted):
8
9 .. code-block:: rust
10
11 pub fn draw(
12 &self,
13 ...
14 draw_ctx: &mut DrawingCtx,
15 ) -> Result<BoundingBox, RenderingError> { ... }
16
17 The draw() methods perform the actual rendering as side effects on the
18 ``draw_ctx``, and return a ``BoundingBox``. That is, the bounding box of
19 an element is computed at the same time that it is rendered. This is
20 suboptimal for several reasons:
21
22 - Many things that happen during rendering depend on knowing the
23 bounding box. For example, gradients, patterns, and filters with
24 units set to ``objectBoundingBox`` need to know the bounds. The
25 rendering code in drawing_ctx.rs is cluttered because it must
26 resolve bounding boxes very late.
27
28 - This is especially problematic for filters, since a Cairo surface
29 needs to be created *before* rendering, and that surface should have
30 a size relative to the bounding box of the element being filtered!
31 :issue:`Bug #1 <1>` is precisely about this: librsvg instead creates
32 a temporary surface as big as the document's toplevel viewport and filters
33 it, but this doesn't work well for filters like Gaussian blur that should
34 actually reference pixels outside of the document's area (think of a
35 shape that extends past the document's area, which then gets
36 blurred).
37
38 - The way for an element to signal that it is not drawable
39 (e.g. ``<defs>`` is by returning an empty bounding box and not
40 rendering anything. This is awkward.
41
42 - When rendering to a temporary surface for filtering or masking,
43 there is a set of affine transformations that needs to be maintained
44 carefully: an affine for the clipping path outside the temporary
45 surface, an affine for drawing inside the surface, an affine to
46 composite the surface into the final result. This is hard to
47 understand and hard to test.
48
49 These problems can be solved by having a **render tree**.
50
51 What is a render tree?
52 ----------------------
53
54 As of 2022/Oct/06, librsvg does not compute a render tree data
55 structure prior to rendering. Instead, in a very 2000s fashion, it
56 walks the tree of elements and calls a ``.draw()`` method for each
57 one. Each element then calls whatever methods it needs from
58 ``DrawingCtx`` to draw itself. Elements which don't produce graphical
59 output (e.g. ``<defs>`` or ``<marker>``) simply have an empty
60 ``draw()`` method.
61
62 Over time we have been refactoring that in the direction of actually
63 being able to produce a render tree. What would that look like?
64 Consider an SVG document like this:
65
66 .. code-block:: xml
67
68 <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
69 <defs>
70 <rect id="TheRect" x="10" y="10" width="20" height="20" fill="blue"/>
71 </defs>
72
73 <g>
74 <use href="#TheRect" stroke="red" stroke-width="2"/>
75
76 <circle cx="50" cy="50" r="20" fill="yellow"/>
77 </g>
78 </svg>
79
80 A render tree would be a list of nested instructions like this:
81
82 ::
83
84 group { # refers to the toplevel SVG
85 width: 100
86 height: 100
87 establishes_viewport: true # because it is an <svg> element
88
89 children {
90 group { # refers to the <g>
91 establishes_viewport: false # because it is a simple <g>
92
93 children {
94 shape {
95 path="the <rect> above but resolved to path commands"
96
97 # note how the following is the cascaded style and the <use> semantics
98 fill: blue
99 stroke: red
100 stroke-width: 2
101 }
102
103 shape {
104 path="the <circle> above but resolved to path commands"
105
106 fill: yellow
107 }
108 }
109 }
110 }
111 }
112
113 That is, we take the high-level SVG instructions and "lower" them to a
114 few possible drawing primitives like path-based shapes that can be
115 grouped. All the primitives have everything that is needed to draw
116 them, like their set of computed values for styles, and their
117 coordinates resolved to their user-space coordinate system.
118
119 Browser engines produce render trees more or less similar to the above
120 (they don't always call them that), and get various benefits:
121
122 - The various recursively-nested subtrees can be rendered concurrently.
123
124 - Having low-level primitives makes it easier to switch to another
125 rendering engine in the future.
126
127 - The tree can be re-rendered without recomputation, or subtrees can
128 be recomputed efficiently if e.g. an animated element changes a few
129 of its properties.
130
131 Why did librsvg not do that since the beginning?
132 ------------------------------------------------
133
134 Librsvg was originally written in the early 2000s, when several things
135 were happening at the same time:
136
137 - libxml2 (one of the early widely-available parsers for XML) had
138 recently gotten a SAX API for parsing XML. This lets an application
139 stream in the parsed XML elements and process them one by one,
140 without having to build a tree of elements+attributes first. In
141 those days, memory was at a premium and "not producing a tree" was
142 seen as beneficial.
143
144 - The SVG spec itself was being written, and it did not have all of
145 the features we know now. In particular, maybe at some point it
146 didn't have elements that worked by referencing others, like
147 ``<use>`` or ``<filter>``. The CSS cascade could be done on the fly
148 for the XML elements being streamed in, and one could emit rendering
149 commands for each element to produce the final result.
150
151 That is, at that time, it was indeed feasible to do this: stream in
152 parsed XML elements one by one as produced by libxml2, and for each
153 element, compute its CSS cascade and render it.
154
155 This scheme probably stopped working at some point when SVG got
156 features that allowed referencing elements that have not been declared
157 yet (think of ``<use href="#foo"/>`` but with the ``<defs> <path
158 id="foo" .../> </defs>`` declared until later in the document). Or
159 elements that referenced others, like ``<rect filter="url(#blah)">``.
160 In both cases, one needs to actually build an in-memory tree of parsed
161 elements, and *then* resolve the references between them.
162
163 That is where much of the complexity of librsvg's code flow comes from:
164
165 - ``AcquiredNodes`` is the thing that resolves references when needed.
166 It also detects reference cycles, which are an error.
167
168 - ``ComputedValues`` often get resolved until pretty late, by passing
169 the ``CascadedValues`` state down to children as they are drawn.
170
171 - ``DrawingCtx`` was originally a giant ball of mutable state, but we
172 have been whittling it down and moving part of that state elsewhere.
173
174
175 Summary of the SVG rendering model
176 ----------------------------------
177
178 In the SVG2 spec, this has been offloaded to the "`Order of graphical
179 operations
180 <https://www.w3.org/TR/compositing/#compositingandblendingorder>`_"
181 section of the Compositing and Blending Level 1 spec. Once the render
182 tree is resolved, each node is painted like this, conceptually to a
183 transparent, temporary surface:
184
185 - Paint the shape/text/etc.
186 - Filters.
187 - Clip paths.
188 - Masks.
189 - Blend/composite the temporary surface onto the result.
190
191 The most critical function in librsvg is probably
192 :internals:struct-method:`rsvg::drawing_ctx::DrawingCtx::with_discrete_layer`;
193 it implements this drawing model.
194
195 Current state (2023/03/30)
196 --------------------------
197
198 ``layout.rs`` has the beginnings of the render tree. It's probably mis-named? It contains this:
199
200 - A ``LayerKind`` with primitives for path-based shapes, text, and images.
201
202 - A `stacking context
203 <https://www.w3.org/TR/SVG2/render.html#EstablishingStackingContex>`_,
204 which indicates each layer's opacity/clip/mask/filters.
205
206 - A ``Layer`` which composes the previous two. The ``StackingContext``
207 provides the compositing/masking/filtering parameters, while the
208 ``LayerKind`` determines the primitive contents of the layer.
209
210 - Various ancillary structures that try to have only user-space
211 coordinates (e.g. a number of CSS pixels instead of ``5cm``) and no
212 references to other things.
213
214 The last point is not yet fully realized. For example,
215 ``StackingContext.clip_in_user_space`` has a reference to an element,
216 which will be used as the clip path — that one needs to be normalized
217 to user-space coordinates in the end. Also,
218 ``StackingContext.filter`` is a filter list as parsed from the SVG,
219 not a ``FilterSpec`` that has been resolved to user space.
220
221 It would be good to resolve everything as early as possible to allow
222 lowering concepts to their final renderable form. Whenever we have
223 done this via refactoring, it has simplified the code closer to the
224 actual rendering via Cairo.
225
226 Major subprojects
227 -----------------
228
229 Path based shapes (``layout::Shape``) and text primitives
230 (``layout::Text``) are almost done. The only missing thing for shapes
231 would be to "explode" their markers into the actual primitives that
232 would be rendered for them. However...
233
234 There is no primitive for groups yet. Every SVG element that allows
235 renderable children must produce a group primitive of some sort:
236 ``svg``, ``g``, ``use``, ``marker``, etc. Among those, ``use`` and
237 ``marker`` are especially interesting since they must explode their
238 referenced subtree into a shadow DOM, which librsvg doesn't support
239 yet for CSS cascading purposes (the reference subtree gets rendered
240 properly, but the full semantics of shadow DOM are not implemented
241 yet).
242
243 Elements that establish a viewport (``svg``, ``symbol``, ``image``,
244 ``marker``, ``pattern``) need to carry information about this
245 viewport, which is a ``viewBox`` plus ``preserveAspectRatio`` and
246 ``overflow``. See :issue:`298` for a somewhat obsolete description
247 of the refactoring work needed to unify this logic.
248
249 The ``layout::StackingContext`` struct should contain another field,
250 probably called ``layer``, with something like this:
251
252 .. code-block:: rust
253
254 struct StackingContext {
255 // ... all its current fields
256
257 layer: Layer
258 }
259
260 enum Layer {
261 Shape(Box<Shape>),
262 Text(Box<Text>),
263 StackingContext(Box<StackingContext>)
264 }
265
266 That is, every stacking context should contain the thing that it will
267 draw, and that thing may be a shape/text or another stacking context!
268
269 Bounding boxes
270 --------------
271
272 SVG depends on the ``objectBoundingBox`` of an element in many places:
273 to resolve a gradient's or pattern's units, to determine the size of
274 masks and clips, to determine the size of the filter region.
275
276 The current big bug to solve is :issue:`778`, which requires
277 knowing the ``objectBoundingBox`` of an element **before** rendering
278 it, so that a temporary surface of the appropriate size can be created
279 for rendering the element if it has isolated opacity or masks/filters.
280 Currently librsvg creates a temporary surface with the size and
281 position of the toplevel viewport, and this is wrong for shapes that
282 fall outside the viewport.
283
284 The problem is that librsvg computes bounding boxes at the time of
285 rendering, not before that. However, now ``layout::Shape`` and
286 ``layout::Text`` already know their bounding box beforehand. Work
287 needs to be done to do the same for a ``layout::Group`` or whatever
288 that primitive ends up being called (by taking the union of its
289 children's bounding boxes, so e.g. that a group with a filter can
290 create a temporary surface to be able to render all of its children
291 and then filter the surface).
292
293 Being able to compute the ``objectBoundingBox`` of an element before
294 rendering it would open the door to fixing bug :issue:`1` (yeah, really):
295 currently, the temporary surface used for filtering has the size of
296 the toplevel viewport, but this doesn't work well when one tries to
297 Gaussian-blur an element that lies partially outside that viewport.
298 The filter should apply to the element's extents plus the filter
299 region, which takes into account the extra space needed for a Gaussian
300 blur to work around a shape. Since librsvg cannot render the full
301 shape if it lies partially outside of the toplevel viewport, the
302 blurred result shows up with a halo near the image's edge, since
303 transparent pixels get "blurred in" with the shape's pixels.
304
305 Status
306 ------
307
308 * 2023/Mar/30 - the "current viewport" is no longer part of
309 ``DrawingCtx``'s mutable state. Instead, a ``Viewport`` struct is
310 passed down the call chain via a function argument. This is not
311 complete yet, since the code modifies the current ``cr``'s transform
312 apart from the current viewport's transform. The goal is to have
313 the current viewport actually have the full transform to be applied
314 to the object being rendered. This should simplify gnarly code
315 paths like the one for rendering ``<pattern>``.
316
317 * 2025/Apr/09 - The current ``Viewport`` is passed as an argument to
318 functions that need it, and it holds the current transform
319 correctly. Evidence of this is that the code does not call
320 ``cr.transform()`` anymore; only
321 ``cr.set_matrix(viewport.transform)`` in the innermost code, right
322 before drawing operations on the ``cr``.
323
324 Elements that "establish a new viewport", per the SVG spec, use a
325 ``LayoutViewport`` and pass it to
326 ``DrawingCtx::with_discrete_layer()``. This composes the
327 appropriate transform into the current ``Viewport`` and passes it on
328 to the drawing functions. Only the markers code remains to be
329 cleaned up for this, see :issue:`1162`.
330
331 Next steps: :issue:`1162`, :issue:`1163`.
332
333 We can actually start defining ``layout::Group`` now, or rather, the
334 implementation for ``DrawingCtx::draw_group()``.