| 1 |
# Skia CPU Backend Architecture |
| 2 |
|
| 3 |
This document outlines the major pieces of Skia's CPU backend. The CPU backend is responsible for |
| 4 |
rendering graphics on the CPU, without the use of a GPU. |
| 5 |
|
| 6 |
## Background and Definitions |
| 7 |
|
| 8 |
* **Bitmap**: A grid of pixels representing an image, where each pixel has a color. This is the |
| 9 |
digital canvas Skia's CPU backend paints on. Common image file formats like PNG and JPEG store |
| 10 |
bitmap data. |
| 11 |
* **Blend Mode**: A rule that defines how a source color (the one being drawn) is mathematically |
| 12 |
combined with a destination color (the one already on the canvas). |
| 13 |
* **Blitter**: A component that writes the final pixel colors from the rendering pipeline into the |
| 14 |
destination bitmap. It's the "hand" that actually puts the colored pixels onto the canvas. |
| 15 |
* **Clip**: A region that restricts drawing. Anything drawn outside the clip is not visible. |
| 16 |
* **Coverage Mask**: An array of values (typically 8-bit alpha) that represents how much a |
| 17 |
geometric shape covers each pixel. A value of 255 means fully covered, 0 means not covered, |
| 18 |
and intermediate values represent partial coverage for anti-aliasing. |
| 19 |
* **Hairline**: The thinnest visual line, typically one device pixel wide. A stroke width of 0 |
| 20 |
in a paint is interpreted as a hairline. Hairlines do not scale with the CTM. |
| 21 |
* **Matrix**: A mathematical tool used to transform (translate, scale, rotate, skew) what is |
| 22 |
being drawn. |
| 23 |
* **Paint**: An object holding stylistic information for drawing, like color, stroke width, and |
| 24 |
effects. |
| 25 |
* **Path**: A sequence of lines and curves that describe a shape. Skia uses quadratic, cubic, and |
| 26 |
conic Bézier curves to create smooth, scalable curves. A quadratic curve has one control point, |
| 27 |
while a cubic curve has two for more complex shapes. A conic curve represents perfect |
| 28 |
circles etc using one control point and one weight. |
| 29 |
* **Rasterization**: Converting vector graphics (math-based shapes) into a grid of pixels (a |
| 30 |
raster image) for display. |
| 31 |
* **Scanline**: A single horizontal row of pixels. Complex shapes are often rendered one scanline |
| 32 |
at a time. |
| 33 |
* **Shader**: A program that calculates the color of a pixel. Shaders can produce solid colors, |
| 34 |
gradients, textures, or procedural patterns. |
| 35 |
* **Tiling**: An optimization strategy where a large drawing operation is broken into a series of |
| 36 |
smaller, tile-sized operations to keep memory usage (e.g., for intermediate buffers) bounded. |
| 37 |
* **Winding Number**: An algorithm used to determine if a point is inside a complex or |
| 38 |
self-intersecting path. Imagine drawing a ray from the point in any fixed direction to |
| 39 |
infinity. The winding number is the count of how many times the path crosses the ray in one |
| 40 |
direction (e.g., clockwise) minus the number of times it crosses in the other direction |
| 41 |
(counter-clockwise). For a non-zero winding rule, any point with a non-zero winding number is |
| 42 |
considered "inside" the path. This correctly handles shapes with holes and overlapping |
| 43 |
sections. |
| 44 |
|
| 45 |
## Data Flow Walkthrough |
| 46 |
|
| 47 |
The following sections describe the journey of a single drawing command (e.g., |
| 48 |
`canvas.drawPath(...)`) through the CPU backend, from the public API call to modifying raw pixel |
| 49 |
memory. |
| 50 |
|
| 51 |
See [CPU.dot](./CPU.dot) for a supplementary diagram. |
| 52 |
|
| 53 |
### 1. The API Layer |
| 54 |
|
| 55 |
The journey begins with the user-facing drawing API. |
| 56 |
|
| 57 |
- **`SkSurface`**: Represents the drawing destination. A CPU-backed surface, created via |
| 58 |
**`SkSurfaces::Raster(...)`**, allocates and owns pixel memory via an `SkPixelRef`. The |
| 59 |
`SkSurface` manages an `SkBitmap` using this memory and provides an `SkCanvas` for drawing. |
| 60 |
- **`SkImage`**: Represents an immutable snapshot of pixel data. It can be created from an |
| 61 |
`SkSurface` (via `surface->makeImageSnapshot()`), from an `SkBitmap`, or from encoded data |
| 62 |
(e.g., a PNG file). On the CPU backend, this is implemented by **`SkImage_Raster`**, which holds |
| 63 |
an `SkBitmap` that in turn points to the underlying pixels via an `SkPixelRef`. Because it is |
| 64 |
immutable, it can be cached and shared safely across threads. It can be drawn to a canvas via |
| 65 |
`canvas->drawImage(...)`. |
| 66 |
- **`SkCanvas`**: The primary drawing interface with methods like `drawPath`, `drawImage`, etc. The |
| 67 |
user provides geometry (e.g., `SkPath`), images (`SkImage`), styling (`SkPaint`), and font |
| 68 |
information (`SkFont`) to the canvas. The `SkCanvas` holds the current transformation matrix |
| 69 |
and clip. When a draw call is made, the `SkCanvas` forwards all the information to an internal |
| 70 |
`SkDevice` for rendering. |
| 71 |
- **`SkPath`**: A high-level object representing vector geometry (lines, curves). It is a |
| 72 |
lightweight, copy-on-write object that holds a shared pointer (`sk_sp`) to an `SkPathRef`. |
| 73 |
- **`SkPathRef`**: The reference-counted object that actually stores the raw path data: arrays of |
| 74 |
points, verbs (move, line, quad, conic, cubic, close), and conic weights. `SkPathRef` objects are |
| 75 |
always **heap-allocated** and managed by `sk_sp`. Internally, `SkPathRef` uses |
| 76 |
`skia_private::STArray` for its geometry data storage. This `STArray` is a small-object optimized |
| 77 |
array, meaning that for small paths, the geometry data is stored directly within the `STArray`'s |
| 78 |
internal buffer (part of the heap-allocated `SkPathRef` object). For larger paths, the `STArray` |
| 79 |
dynamically allocates additional memory on the heap to store the geometry data. |
| 80 |
|
| 81 |
#### Text Rendering |
| 82 |
|
| 83 |
Drawing text is a specialized, but common, case. The process involves three key classes: |
| 84 |
- **`SkFontMgr`**: A top-level object that discovers and manages the fonts installed on the system. |
| 85 |
It is used to create an `SkTypeface` by matching a font family name (e.g., "Roboto") or by |
| 86 |
loading font data directly from a file or stream. It also handles "fallback", which allows a user |
| 87 |
to find the data to draw a glyph from a collection of fonts and ordering heuristics (e.g. use this |
| 88 |
font for Latin characters and this font for emoji). |
| 89 |
- **`SkTypeface`**: An immutable object representing the raw data of a single font face (e.g., |
| 90 |
"Roboto Bold"). It typically contains the vector paths for each glyph, but also supports bitmap |
| 91 |
glyphs. Vector glyphs are rasterized and stored in a glyph cache (`SkStrikeCache`). |
| 92 |
- **`SkFont`**: A lightweight object that holds a reference to an `SkTypeface` plus styling |
| 93 |
attributes like text size, scale, and skew. |
| 94 |
|
| 95 |
When a user calls a method like `canvas.drawSimpleText(...)`, they provide the text and an `SkFont` |
| 96 |
to the `SkCanvas`. The backend then uses the `SkFont` to look up the individual glyphs from the |
| 97 |
`SkTypeface`. Each glyph is subsequently treated as a standard `SkPath` to be rendered. |
| 98 |
|
| 99 |
**Note on Text Layout:** Core Skia handles rendering individual glyphs, but it does not perform |
| 100 |
complex text layout (e.g., line breaking, justification, or bidirectional text). For rich text |
| 101 |
layout, Skia provides the **`SkParagraph`** module, which is a higher-level library built on top |
| 102 |
of Skia's core components. |
| 103 |
|
| 104 |
#### Paint Configuration |
| 105 |
|
| 106 |
The **`SkPaint`** object holds a suite of optional components that control the styling and |
| 107 |
pixel-processing pipeline. |
| 108 |
- **`SkShader`**: Generates the source color for the geometry. If no shader is present, the paint's |
| 109 |
color is used. Shaders can produce gradients, bitmap patterns, or procedural colors. |
| 110 |
- **`SkColorFilter`**: Modifies the source color produced by the shader or paint. Common uses |
| 111 |
include tinting or applying a color matrix for color correction. |
| 112 |
- **`SkMaskFilter`**: Operates on the shape's coverage mask, not its color. Its most common use is |
| 113 |
blurring the shape's edges, such as with a Gaussian blur from `SkMaskFilter::MakeBlur`. |
| 114 |
- **`SkPathEffect`**: Modifies the geometry of a shape before it is drawn. For example, |
| 115 |
`SkPathEffect::MakeDash` creates an effect that turns solid lines into dashed lines. This |
| 116 |
happens before rasterization. |
| 117 |
- **`SkBlender`**: Controls how the source color (from the shader) is blended with the destination |
| 118 |
color (already on the canvas). It is a more powerful, programmable version of the traditional |
| 119 |
`SkBlendMode` enum. The blending logic is executed as a stage in the `SkRasterPipeline`. |
| 120 |
- **`SkImageFilter`**: Applies a complex, multi-pass effect to the output of a drawing operation. |
| 121 |
Unlike other effects, an image filter can operate on the entire result of a draw as a texture. |
| 122 |
This often requires allocating a temporary, offscreen layer. For example, a drop shadow filter |
| 123 |
might draw the shape into a layer, blur it, offset it, and then draw the original shape again |
| 124 |
on top of the blurred shadow. |
| 125 |
|
| 126 |
### 2. The Device Layer: `SkBitmapDevice` |
| 127 |
|
| 128 |
For the CPU backend, the `SkCanvas` forwards draw calls to an **`SkBitmapDevice`**. This object is |
| 129 |
the concrete target for all CPU-based drawing. It manages the destination **`SkBitmap`** and |
| 130 |
initiates rendering by creating and dispatching to an `SkDraw` object. |
| 131 |
|
| 132 |
**A Note on Clipping:** The device manages an `SkRasterClipStack` corresponding to the canvas's |
| 133 |
`save()`/`restore()` calls. For each draw, it resolves this stack into a single `SkRasterClip` |
| 134 |
and passes it to `SkDraw`, which is stateless regarding the clip. |
| 135 |
|
| 136 |
**A Note on Tiling:** For large or complex draws, the device may use tiling. It breaks the |
| 137 |
operation into smaller, tile-sized chunks, adjusting the clip for each. This bounds the memory |
| 138 |
required for intermediate buffers by invoking the draw process once per tile. |
| 139 |
|
| 140 |
### 3. The Orchestrator: `SkDraw` |
| 141 |
|
| 142 |
The `SkBitmapDevice` creates an **`SkDraw`** object for each primitive. `SkDraw` orchestrates a |
| 143 |
single draw, bundling the geometry (`SkPath`), styling (`SkPaint`), transform, clip, and |
| 144 |
destination `SkPixmap`. It uses `SkScan` to convert the vector shape into raster operations. |
| 145 |
|
| 146 |
### 4. The Rasterizer: `SkScan` |
| 147 |
|
| 148 |
`SkDraw` passes the `SkPath` to **`SkScan`**, the core rasterizer. `SkScan` converts the vector |
| 149 |
path into horizontal scanlines, calculating a coverage mask (alpha values) for each. It is |
| 150 |
unaware of color or effects. `SkDraw` provides `SkScan` with a `SkBlitter`, which `SkScan` |
| 151 |
invokes for each scanline to render the coverage data. |
| 152 |
|
| 153 |
**A Note on Scan Converters:** The `isAntiAlias()` flag on the `SkPaint` selects the scan |
| 154 |
converter: |
| 155 |
- **Aliased (`SkScan_Path.cpp`):** When anti-aliasing (AA) is off, it produces a binary (0% or |
| 156 |
100%) coverage mask based on whether pixel centers are inside the path, resulting in hard |
| 157 |
edges. For each horizontal run of covered pixels, it calls `blitter->blitH(x, y, width)`. |
| 158 |
- **Analytic Anti-Aliased (`SkScan_AAAPath.cpp`):** When AA is on, it analytically calculates the |
| 159 |
exact geometric area of intersection with each pixel, producing fractional coverage values for |
| 160 |
smooth edges. For each horizontal run of partially-covered pixels, it calls |
| 161 |
`blitter->blitAntiH(x, y, alphas, runs)`. |
| 162 |
|
| 163 |
### 5. The Pixel Writer: `SkRasterPipelineBlitter` |
| 164 |
|
| 165 |
The **`SkRasterPipelineBlitter`** is the primary `SkBlitter` in the CPU backend. It implements the |
| 166 |
`SkBlitter` interface, but instead of writing pixels directly, it translates calls like `blitH` |
| 167 |
or `blitRect` from `SkScan` into an execution of its internal `SkRasterPipeline`. It configures |
| 168 |
the pipeline with the correct coverage information from the blitter call and then runs the |
| 169 |
pipeline to compute and write the final pixel colors to those lines. |
| 170 |
|
| 171 |
### 6. The Workhorse: `SkRasterPipeline` |
| 172 |
|
| 173 |
The **`SkRasterPipeline`** calculates final pixel colors by chaining together single-purpose |
| 174 |
**stages**. For example, a draw might use stages for loading coverage (`load_a8`), setting a |
| 175 |
source color (`uniform_color`), loading the destination, blending (`srcover`), and storing the |
| 176 |
result (`store_8888`). This stage-based design avoids a combinatorial explosion of functions. |
| 177 |
|
| 178 |
The pipeline is assembled into a sequence of pre-compiled "stages", which are executed in a loop |
| 179 |
over the covered area. These functions use **SIMD (e.g., SSE, NEON)** to process multiple pixels |
| 180 |
at once for high performance. The pipeline gets memory layout information from an `SkPixmap` to |
| 181 |
load and store pixels. |
| 182 |
|
| 183 |
### 7. The Pixel Memory View: `SkPixmap`, `SkBitmap`, and `SkPixelRef` |
| 184 |
|
| 185 |
This is the final stop where pixels are modified. |
| 186 |
- **`SkPixmap`**: A lightweight object with a pointer to pixel memory and its metadata |
| 187 |
(dimensions, color type). It provides the `SkRasterPipeline` with the exact memory addresses |
| 188 |
for reading and writing. |
| 189 |
- **`SkBitmap`**: Held by `SkBitmapDevice`, it pairs an `SkImageInfo` with the pixel storage. |
| 190 |
- **`SkPixelRef`**: A smart pointer that owns the heap-allocated pixel memory, originally created |
| 191 |
by the `SkSurface`. |
| 192 |
|
| 193 |
The `SkRasterPipeline`'s final stage uses the address from the `SkPixmap` to write the new color |
| 194 |
into the memory owned by the `SkPixelRef`, completing the draw. |