# graphics3d/toon/toonscreenoutline (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/graphics3d/toon/toonscreenoutline/

Toon screen-space outline. (ToonScreenOutline of vanilla.js graphics3d/toon/toonscreenoutline.js)
- It draws normals, line ids and depth into the line buffer, finds lines at the boundaries between direct neighbors, then blends: thin lines look at the surrounding cells directly, thick lines are widened by jump flooding and the coverage is worked out from the distance.
- Line buffer: draws the create_mesh result of ToonRenderer once more with the same matrices and writes the normal (octahedron folded), the line id (14 bits), the shape (whether contour and crease lines are on) and the depth.
- Finding: looks once at every boundary between a pixel and its four direct neighbors. A line stands on the boundary between pixels, not on a pixel. (the same boundary is never drawn twice)
  A contour line is a silhouette touching empty space, a place touching another id, or, even with the same id, a place where the occluding pixel is farther than the depth threshold and error margin from the tangent plane of the occluded pixel (an occluded silhouette).
  A crease line is a place inside the same id where two neighboring normals differ by more than the crease angle. Only the normals one pixel apart are looked at, so no band stands around the silhouette of a round surface or on a slanted surface.
  Depth is compared as a tangent plane distance, so no false lines stand on a floor seen at a slant. The measured error (normal 8-bit angle error x distance between the two positions, one pixel of the crease x sine, one step of 24-bit depth) x the margin is added so far things mean the same, and low parallel steps are caught even when lower than one pixel.
- Thin line (up to a width of about 3.24 pixels): picks the first boundary side per pixel (R8UI, one byte) in the same order as the seed pick, and the blend reads the seeds of the 3 x 3 pixels around in the same order as the last jump flooding step to measure the distance to the nearest one.
  The full-screen passes are one side buffer and one blend. (on mobile tile GPUs the pass count and buffer bandwidth are a fraction of the thick line path)
- Widening (thick line): spreads the distance to the boundary segment by jump flooding. The step count is log2 whatever the width, and contour and crease lines are spread separately so they get separate widths.
- Blend: for each pixel of the drawing area it covers clamp(width / 2 - distance + 0.5, 0, 1) from the distance to the nearest boundary. (soft edges, and shrinking the line buffer does not turn widened lines into dotted lines)
- Per model: if has_screen_outline of ToonLineDrawOptions is false the model draws no line and only hides lines behind it. If has_crease_line is false only the crease line is off.
- Color per id: set_line_color gives each id a line color. (Unreal Custom Stencil style, a touching line takes the color of the front id, ids not in the table and an empty table keep the color of set_color)
- Width: the width of set_width and set_crease is the width of one line. (half on each side of the boundary) The unit is ToonOutlineWidthUnit, never below one pixel.
- Depth: the projection matrix tells orthographic from perspective, and depth is unpacked to view space positions for comparing. (projections that shift clip x, y like a screen rectangle also work)
- Scale: set_resolution_scale shrinks every buffer before the blend (line buffer, mask, seed, widening buffers). (the default 1 is the drawing area as it is, and below 1 a thin line works out one coverage buffer at the line buffer resolution and reads it bilinearly once to blend)
- Use: every frame begin_line_ids(gl, view, projection) → draw_mesh / draw_mesh_instanced → end_line_ids(gl) (works out the seeds and widening) → toon body drawing → draw_outline(gl).
  begin_line_ids notes the viewport of that moment as the drawing area and builds the line buffer to that size. end_line_ids and draw_outline restore the framebuffer, viewport and state.
  Handing it to ToonDrawQueue::set_screen_outline lets the draw queue do this order by itself. (when inserting between engine 2D drawing, flush the Graphic batch before and call restore_render_state after)
- The id per instance is line_id of ToonInstance. (lineId of the original instance object, None means the common id)

Example: Draw the toon screen-space outline in one frame

```rust
use vanilla::{create_box_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonLineDrawOptions, ToonOutlineWidthUnit, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};

fn draw_outlined_box(gl: &vanilla::GlContext) -> Result<(), String> {
	let mut renderer = ToonRenderer::new(gl)?;
	let mut outline = ToonScreenOutline::new(gl)?;
	outline.set_width(2.0, ToonOutlineWidthUnit::Pixel);
	outline.set_crease(50.0, 1.0, 0.8);
	let mut builder = MeshBuilder::new();
	builder.add_part(&create_box_geometry(1.0, 1.0, 1.0), &Matrix4::create_identity(), "#e0c8a8", ToonPartOptions { has_outline: false, ..ToonPartOptions::default() });
	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
	let view_matrix = Matrix4::create_look_at(Vector3::create(2.0, 2.0, 3.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
	let projection_matrix = Matrix4::create_perspective(std::f64::consts::FRAC_PI_4, 1.0, 0.1, 100.0);
	let model_matrix = Matrix4::create_identity();
	if outline.begin_line_ids(gl, &view_matrix, &projection_matrix) {
		outline.draw_mesh(gl, &mesh, &model_matrix, 1, ToonLineDrawOptions::default());
		outline.end_line_ids(gl);
	}
	renderer.begin_frame_with_matrices(gl, &view_matrix, &projection_matrix);
	renderer.draw_mesh(gl, &mesh, &model_matrix, ToonDrawOptions::default());
	renderer.end_frame(gl);
	outline.draw_outline(gl);
	Ok(())
}
```

## ToonLineDrawOptions (struct) (Clone, Copy, Debug, Default)

Options for drawing IDs. (the original drawMesh options)

Example: The floor only hides without lines, the crystals without crease lines

```rust
use vanilla::{create_box_geometry, create_octahedron_geometry, Matrix4, MeshBuilder, ToonLineDrawOptions, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};

fn draw_floor_and_crystal(gl: &vanilla::GlContext, renderer: &ToonRenderer, outline: &mut ToonScreenOutline) -> Option<()> {
	let part_options = ToonPartOptions { has_outline: false, ..ToonPartOptions::default() };
	let mut floor_builder = MeshBuilder::new();
	floor_builder.add_part(&create_box_geometry(6.0, 0.2, 6.0), &Matrix4::create_translation(0.0, -0.1, 0.0), "#506070", part_options);
	let floor_mesh = renderer.create_mesh(gl, &floor_builder.read_arrays())?;
	let mut crystal_builder = MeshBuilder::new();
	crystal_builder.add_part(&create_octahedron_geometry(0.5), &Matrix4::create_translation(0.0, 0.5, 0.0), "#90d0ff", part_options);
	let crystal_mesh = renderer.create_mesh(gl, &crystal_builder.read_arrays())?;
	let view_matrix = Matrix4::create_look_at(Vector3::create(3.0, 3.0, 4.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
	let projection_matrix = Matrix4::create_perspective(std::f64::consts::FRAC_PI_4, 1.0, 0.1, 100.0);
	if outline.begin_line_ids(gl, &view_matrix, &projection_matrix) {
		outline.draw_mesh(gl, &floor_mesh, &Matrix4::create_identity(), 1, ToonLineDrawOptions { has_screen_outline: false, ..ToonLineDrawOptions::default() });
		outline.draw_mesh(gl, &crystal_mesh, &Matrix4::create_identity(), 2, ToonLineDrawOptions { has_crease_line: false, ..ToonLineDrawOptions::default() });
		outline.end_line_ids(gl);
	}
	Some(())
}
```

- `pub joint_matrices: Option<&'a [f32]>` (field, since 0.4.0): Joint matrices of a skinned model. (16 numbers per joint, up to TOON_MAXIMUM_JOINTS, give the same pose as ToonRenderer::draw_mesh, None draws without a pose)
  - returns Option<&'a [f32]>
- `pub is_culled: bool` (field, since 0.4.0): Whether to skip when off screen. (not drawn if the bounding sphere is outside the frustum, default true)
  - returns bool
- `pub index_start: usize` (field, since 0.4.0): Only part of the body index buffer. (for giving a part a different ID, start index and count, to the end if the count is None)
  - returns usize
- `pub index_count: Option<usize>` (field, since 0.4.0): Number of body indices to draw. (None means from index_start to the end)
  - returns Option<usize>
- `pub is_mirrored: Option<bool>` (field, since 0.4.0): Whether to draw with the winding flipped. (when None, flipped if the model matrix determinant is negative, for instances None means not flipped)
  - returns Option<bool>
- `pub has_screen_outline: bool` (field, since 0.4.0): Whether to output outer lines. (when false, no line is output and only the lines behind are hidden)
  - returns bool
- `pub has_crease_line: bool` (field, since 0.4.0): Whether to output crease lines.
  - returns bool

## ToonLineTarget (struct)

Line buffer. (normal and id RGBA8 at the line buffer resolution, depth 24, the thin line side buffer R8UI, the seed RGBA16UI and two widening buffers RGBA16UI built when a thick line is drawn, jump_flood_index is the side where widening ended)

Example: Read the sizes of the line target and the widening target

```rust
use vanilla::ToonScreenOutline;

fn print_line_target(outline: &ToonScreenOutline) {
	if let Some(line_target) = outline.get_line_target() {
		println!("line {} x {}, jump flood {} x {}", line_target.width, line_target.height, line_target.jump_flood_width, line_target.jump_flood_height);
	}
}
```

- `pub framebuffer: GlFramebuffer` (field, since 0.4.0): Line target framebuffer. (normal and ID texture, depth texture)
  - returns GlFramebuffer
- `pub line_texture: GlTexture` (field, since 0.4.0): Normal and ID texture. (RGBA8, the normal octahedrally encoded in rg, the ID and flags in ba)
  - returns GlTexture
- `pub depth_texture: GlTexture` (field, since 0.4.0): Depth texture. (depth 24)
  - returns GlTexture
- `pub edge_mask_framebuffer: GlFramebuffer` (field, since 0.4.0): Framebuffer of the thin line side buffer.
  - returns GlFramebuffer
- `pub edge_mask_texture: GlTexture` (field, since 0.4.0): Thin line side buffer. (R8UI, the low 3 bits are the contour line and the high 3 bits the crease line first boundary side: 0 none, 1 right, 2 left, 3 up, 4 down)
  - returns GlTexture
- `pub seed_framebuffer: Option<GlFramebuffer>` (field, since 0.4.0): Seed buffer framebuffer. (built the first time a thick line is drawn, None before)
  - returns Option<GlFramebuffer>
- `pub seed_texture: Option<GlTexture>` (field, since 0.4.0): Seed texture. (RGBA16UI, rg is the contour line and ba the crease line, None before a thick line is drawn)
  - returns Option<GlTexture>
- `pub jump_flood_framebuffers: Vec<GlFramebuffer>` (field, since 0.4.0): Two widening buffer framebuffers. (used alternately, empty before a thick line is drawn)
  - returns Vec<GlFramebuffer>
- `pub jump_flood_textures: Vec<GlTexture>` (field, since 0.4.0): Two widening buffer textures. (RGBA16UI, empty before a thick line is drawn)
  - returns Vec<GlTexture>
- `pub jump_flood_index: Option<usize>` (field, since 0.4.0): Side where widening ended. (index into jump_flood_textures, 0 or 1, None when nothing was widened, -1 in the original)
  - returns Option<usize>
- `pub coverage_framebuffer: Option<GlFramebuffer>` (field, since 0.4.0): Framebuffer of the thin line coverage buffer of the reduced line buffer. (built the first time a reduced thin line is drawn, None before)
  - returns Option<GlFramebuffer>
- `pub coverage_texture: Option<GlTexture>` (field, since 0.4.0): Thin line coverage buffer of the reduced line buffer. (RGBA8 premultiplied color, bilinear, None before a reduced thin line is drawn)
  - returns Option<GlTexture>
- `pub outline_path: ToonOutlinePath` (field, since 0.4.0): Path of this frame. (set by end_line_ids)
  - returns ToonOutlinePath
- `pub width: i32` (field, since 0.4.0): Line buffer width. (drawing area x the fraction of set_resolution_scale, in pixels)
  - returns i32
- `pub height: i32` (field, since 0.4.0): Line buffer height. (drawing area x the fraction of set_resolution_scale, in pixels)
  - returns i32
- `pub jump_flood_width: i32` (field, since 0.4.0): Widening buffer width. (same as the line buffer, in pixels)
  - returns i32
- `pub jump_flood_height: i32` (field, since 0.4.0): Widening buffer height. (same as the line buffer, in pixels)
  - returns i32

## ToonScreenOutline (struct)

Toon screen-space outline. (see the header comment)

Example: Only a thick silhouette without crease lines

```rust
use vanilla::{ToonOutlineWidthUnit, ToonScreenOutline};

fn create_silhouette_outline(gl: &vanilla::GlContext) -> Result<ToonScreenOutline, String> {
	let mut outline = ToonScreenOutline::new(gl)?;
	outline.set_color([0.1, 0.08, 0.12, 1.0]);
	outline.set_width(3.0, ToonOutlineWidthUnit::Pixel);
	outline.set_crease(180.0, 1.0, 1.0);
	outline.set_resolution_scale(0.5);
	Ok(outline)
}
```

- `pub fn read_program_sources(color_space: ColorSpace) -> [(String, String); 9]` (static, since 0.4.0): Shader sources. (nine (vertex, fragment) pairs: id, seed, gather, widening, blend, thin line side buffer, thin line blend, coverage of a reduced buffer thin line, coverage buffer blend)
  - `color_space` ColorSpace: Color space. (original default is the engine's color space; with Linear the composite shader gets #define VANILLA_COLOR_SPACE_LINEAR 1)
  - returns [(String, String); 9]: Nine (vertex shader, fragment shader). (id, seed, gather, widening, blend, thin line side buffer, thin line blend, coverage of a reduced buffer thin line, coverage buffer blend, the attribute locations of the id shader are TOON_ATTRIBUTE_LOCATIONS)
- `pub fn new(gl: &GlContext) -> Result<ToonScreenOutline, String>` (constructor, since 0.4.0): Creation. (builds nine programs and an empty vertex array, the line buffer is built at the first begin_line_ids, the color space is the engine's)
  - `gl` &GlContext: The same context as the toon renderer.
  - returns Result<ToonScreenOutline, String>: New screen-space outline. Err(error message) if a shader cannot be built or the vertex array cannot be created.
- `pub fn new_with_options(gl: &GlContext, options: ToonScreenOutlineOptions) -> Result<ToonScreenOutline, String>` (static, since 0.4.0): Creation with options. (original new ToonScreenOutline(gl, options))
  - `gl` &GlContext: The same context as the toon renderer.
  - `options` ToonScreenOutlineOptions: Color space. (ToonScreenOutlineOptions, the curve that converts the line color to linear for HDR output)
  - returns Result<ToonScreenOutline, String>: New screen-space outline. Err(error message) if a shader cannot be built or the vertex array cannot be created.
- `pub fn get_color_space(&self) -> ColorSpace` (method, since 0.4.0): Returns the color space. (original getColorSpace, fixed at creation, the curve that converts the line color to linear for HDR output, pow 2.2 for Gamma and the standard sRGB curve for Linear)
  - returns ColorSpace: ColorSpace::Gamma or ColorSpace::Linear.
- `pub fn set_color(&mut self, color: [f64; 4])` (method, since 0.4.0): Sets the line color. (sRGB 0 ~ 1 and alpha, shared by outer lines and crease lines)
  - `color` [f64; 4]: sRGB [r, g, b, a].
- `pub fn set_line_color(&mut self, line_id: u32, color: [f64; 4])` (method, since 0.4.0): Set a line color per ID. (the contour and crease lines of the model with that ID in front take this color, IDs not in the table keep the set_color color)
  - Like the post-process outline of Unreal Custom Stencil, the color is picked by the ID already in the line target. For highlighting chosen models or coloring each team differently.
  - The table is a 128 x 128 lookup texture covering every line ID (1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID). There is no limit on how many IDs are set, and it is read once per pixel.
  - A line where two IDs touch takes the color of the nearer ID (closer to the camera). The color is stored as 8-bit sRGB, and alpha 0 is stored as 1/255. (to tell it apart from not being in the table; it is equally invisible)
  - `line_id` u32: 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID. (the ID given to draw_mesh and draw_mesh_instanced, does nothing when out of range)
  - `color` [f64; 4]: sRGB [r, g, b, a] in 0 ~ 1.

  Example: Make only the lines of the picked rock yellow

  ```rust
  use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonInstance, ToonLineDrawOptions, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};
  
  fn draw_picked_rock(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut outline = ToonScreenOutline::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#a89880", ToonPartOptions { has_outline: false, ..ToonPartOptions::default() });
  	let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
  	let instance_list: Vec<ToonInstance> = (0..3).map(|index| ToonInstance { model_matrix: Matrix4::create_translation(index as f64 * 0.7, 0.0, 0.0), line_id: Some(10 + index), ..ToonInstance::default() }).collect();
  	outline.set_line_color(11, [1.0, 0.85, 0.2, 1.0]);
  	let view_matrix = Matrix4::create_look_at(Vector3::create(0.7, 2.0, 3.0), Vector3::create(0.7, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  	let projection_matrix = Matrix4::create_perspective(std::f64::consts::FRAC_PI_4, 1.0, 0.1, 100.0);
  	if outline.begin_line_ids(gl, &view_matrix, &projection_matrix) {
  		outline.draw_mesh_instanced(gl, &rock_mesh, &instance_list, 10, ToonLineDrawOptions::default());
  		outline.end_line_ids(gl);
  	}
  	renderer.begin_frame_with_matrices(gl, &view_matrix, &projection_matrix);
  	renderer.draw_mesh_instanced(gl, &rock_mesh, &instance_list, ToonDrawOptions::default());
  	renderer.end_frame(gl);
  	outline.draw_outline(gl);
  	Ok(())
  }
  ```

- `pub fn remove_line_color(&mut self, line_id: u32)` (method, since 0.4.0): Remove one ID from the color table. (the lines of that ID go back to the set_color color)
  - `line_id` u32: The ID given to set_line_color.
- `pub fn clear_line_colors(&mut self)` (method, since 0.4.0): Clear the color table. (all lines go back to the set_color color)

  Example: Set the IDs to highlight again every frame

  ```rust
  use vanilla::ToonScreenOutline;
  
  fn mark_lines(outline: &mut ToonScreenOutline) -> u32 {
  	outline.clear_line_colors();
  	outline.set_line_color(3, [1.0, 1.0, 1.0, 1.0]);
  	outline.set_line_color(7, [1.0, 0.3, 0.2, 1.0]);
  	outline.get_line_color_count()
  }
  ```

- `pub fn get_line_color_count(&self) -> u32` (method, since 0.4.0): Return the number of IDs in the color table.
  - returns u32: The number of IDs set with set_line_color and not removed.
- `pub fn set_width(&mut self, width: f64, unit: ToonOutlineWidthUnit)` (method, since 0.4.0): Sets the outer line width. (lines at silhouettes and where different IDs meet, the width of one line rather than a radius, not drawn at 0, the crease line width is also counted in this unit)
  - `width` f64: Thickness of one line. (Half on each side of the boundary)
  - `unit` ToonOutlineWidthUnit: Unit of the thickness. (default Pixel in the original)
- `pub fn set_crease(&mut self, angle_degrees: f64, width: f64, opacity: f64)` (method, since 0.4.0): Sets crease lines. (a line where adjacent faces within the same ID bend more than this angle (degrees), the width is in the unit of set_width, strength 0 ~ 1, not drawn at 180 degrees or width 0)
  - `angle_degrees` f64: Crease angle. (180 draws no crease lines)
  - `width` f64: Thickness of one crease line. (default 1 in the original, 0 draws none)
  - `opacity` f64: Opacity of the crease line. (default 1 in the original, multiplied into the alpha of the line color)
- `pub fn set_focus_distance(&mut self, focus_distance: f64)` (method, since 0.4.0): Sets the focal distance. (Distance at which world width is converted to pixels for a perspective camera, usually from the camera to the look-at point, 0 uses the average distance of the drawn models)
  - `focus_distance` f64: Distance from the camera. (World length)
- `pub fn set_depth_threshold(&mut self, depth_threshold: f64)` (method, since 0.4.0): Set the depth threshold. (Among neighboring pixels with the same ID, if the occluding one is farther than this from the tangent plane of the occluded one, an occluded silhouette is drawn; world length)
  - `depth_threshold` is the distance perpendicular to the face, and a pixel margin is added to it. (the scale of set_depth_margin x the measured error; the error follows the pixel size and the slope of the face)
  - Fit it to the scale of the scene. (0.02 ~ 0.1 for a human-sized scene; with 0 only the error margin decides)
  - `depth_threshold` f64: Tangent plane distance threshold. (world length, perpendicular to the face, 0 or more)

  Example: Draw even low ledges as silhouettes

  ```rust
  use vanilla::{GlContext, ToonScreenOutline};
  
  fn make_outline(gl: &GlContext) -> Result<ToonScreenOutline, String> {
  	let mut outline = ToonScreenOutline::new(gl)?;
  	outline.set_depth_threshold(0.01);
  	assert_eq!(outline.depth_threshold(), 0.01);
  	Ok(outline)
  }
  ```

- `pub fn depth_threshold(&self) -> f64` (method, since 0.4.0): Read the depth threshold. (world length, perpendicular to the face)
  - returns f64: Tangent plane distance threshold. (default 0.05)
- `pub fn set_depth_margin(&mut self, depth_margin: f64)` (method, since 0.4.0): Set the depth margin scale. (How many times the measured error is added to the depth threshold as a pixel margin, default 2)
  - The error of the tangent plane distance that arises even on a continuous face is measured per pixel: the angle error of the 8-bit octahedral normal (0.0165 rad) x the distance between the two pixel positions (longer the more slanted the face), one pixel x the sine of the angle between the two normals for two pixels on either side of a crease, and one 24-bit depth step.
  - A low ledge whose two faces are parallel has a crease share of 0, so it is caught even when it is lower than one pixel. If you lower the depth threshold a lot on a model built from coarse polygons whose interpolated normals stray far from the face, stray lines appear; raise the scale then.
  - With 0 only the depth threshold decides.
  - `depth_margin` f64: Scale to multiply the measured error by. (0 or more, below 0 becomes 0)

  Example: Reduce the margin to catch low ledges better

  ```rust
  use vanilla::{GlContext, ToonScreenOutline};
  
  fn make_outline(gl: &GlContext) -> Result<ToonScreenOutline, String> {
  	let mut outline = ToonScreenOutline::new(gl)?;
  	outline.set_depth_threshold(0.02);
  	outline.set_depth_margin(1.0);
  	assert_eq!(outline.depth_margin(), 1.0);
  	Ok(outline)
  }
  ```

- `pub fn depth_margin(&self) -> f64` (method, since 0.4.0): Read the depth margin scale.
  - returns f64: Scale to multiply the measured error by. (default 2)
- `pub fn set_resolution_scale(&mut self, resolution_scale: f64)` (method, since 0.4.0): Sets the line buffer resolution fraction. (fraction of the drawing area 0.25 to 1, default 1, phones and tablets lower it for a light path)
  - As the name says, every buffer before the blend (line buffer = normal, id and depth, mask, seed, widening buffers) is sized to the drawing area x the fraction. The line buffer is drawn once more at the smaller resolution, so the cost drops with the square of the fraction.
    The default 1 is the same size as the drawing area, so the picture is byte for byte the same.
  - Below 1, a thin line (width x fraction at most about 3.24 line buffer pixels) works out the coverage (RGBA8 multiplied by intensity and id color) once at the line buffer resolution, and the last blend reads it bilinearly once. (9 reads become 1)
    A thick line runs the jump flooding at the line buffer resolution and measures the distance in drawing area pixels when blending. On either path the line width is in drawing area pixels (set_width) and the smaller the fraction, the softer the edges.
  - The line_texture and depth_texture resolution of get_line_target() is the drawing area x the fraction. (with width 0 drawing only the line buffer is unchanged, only the resolution can differ from the drawing area)
  - To match 1.5 pixels per CSS pixel, give fraction = 1.5 / (drawing buffer pixels / CSS pixels).
  - `resolution_scale` f64: 0.25 to 1. (1 is the drawing area resolution as it is)
- `pub fn set_hdr_output(&mut self, is_hdr_output: bool)` (method, since 0.4.0): Sets HDR output. (true converts the line color to linear before blending, match with ToonRenderer::set_hdr_output)
  - `is_hdr_output` bool: If true, the line color is converted to linear before blending.
- `pub fn get_line_widths(&self) -> [f64; 2]` (method, since 0.4.0): This frame's line widths. (drawing area pixels for [outer line, crease line], determined after end_line_ids, 0 if not drawn)
  - returns [f64; 2]: [silhouette line thickness, crease line thickness]. (0 if not drawn)
- `pub fn get_line_target(&self) -> Option<&ToonLineTarget>` (method, since 0.4.0): Returns the line buffer. (None when absent, the id, depth and mask textures, the size)
  - returns Option<&ToonLineTarget>: Line buffer. (normal and id texture, depth texture, thin line side buffer, the seed and two widening buffers with the finished side when a thick line was drawn, the coverage buffer when a reduced thin line was drawn, the path of this frame, the size, None when not built yet or building failed)
- `pub fn read_line_widths(&self) -> [f64; 2]` (method, since 0.4.0): Computes the line widths. (drawing area pixels for [outer line, crease line], the current value if there is no frame drawing IDs)
  - returns [f64; 2]: [silhouette line thickness, crease line thickness].
- `pub fn begin_line_ids(&mut self, gl: &GlContext, view_matrix: &Matrix4, projection_matrix: &Matrix4) -> bool` (method, since 0.4.0): Begins drawing IDs. (records the current viewport as the drawing area, binds and clears the line target, false if the target cannot be built)
  - `gl` &GlContext: GL context.
  - `view_matrix` &Matrix4: View matrix.
  - `projection_matrix` &Matrix4: Projection matrix. (Perspective or orthographic)
  - returns bool: false if the line target could not be built. (draw_mesh then does nothing)
- `pub fn draw_mesh(&mut self, gl: &GlContext, mesh: &ToonMesh, model_matrix: &Matrix4, line_id: u32, options: ToonLineDrawOptions)` (method, since 0.4.0): Draws IDs for one model. (same matrices and pose as ToonRenderer::draw_mesh, IDs 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID, no line where the same IDs meet, skipped if off-screen)
  - `gl` &GlContext: GL context.
  - `mesh` &ToonMesh: Result of ToonRenderer::create_mesh.
  - `model_matrix` &Matrix4: Model matrix.
  - `line_id` u32: 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID. (0 is empty space and not used, no line where the same IDs touch)
  - `options` ToonLineDrawOptions: Draw options. (joint matrices, culling, part of the body index buffer, flipped winding, whether to produce silhouette and crease lines)
- `pub fn draw_mesh_instanced(&mut self, gl: &GlContext, mesh: &ToonMesh, instance_list: &[ToonInstance], line_id: u32, options: ToonLineDrawOptions)` (method, since 0.4.0): Draws IDs for multiple instances of the same model at once. (uses the instance's line_id if present, otherwise the common ID, the options are the same for all instances)
  - `gl` &GlContext: GL context.
  - `mesh` &ToonMesh: Result of ToonRenderer::create_mesh.
  - `instance_list` &[ToonInstance]: Instance list. (model matrix and ID, the shared ID if the ID is None)
  - `line_id` u32: Common ID.
  - `options` ToonLineDrawOptions: Same as draw_mesh. (the options are the same for every instance, None for is_mirrored does not flip)
- `pub fn draw_mesh_instance_buffer(&mut self, gl: &GlContext, mesh: &ToonMesh, instance_buffer: &ToonInstanceBuffer, instance_count: usize, line_id: u32, options: ToonLineDrawOptions)` (method, since 0.4.0): Draw ids with a persistent instance buffer. (uses the same GPU buffer as the body and does not upload again, culls the whole buffer by its bounds; the original drawMeshInstanceBuffer)
  - The id of each instance is the instanceLineId slot of the layout, otherwise the common id. When the layout has no matrix the position is unknown and nothing is drawn. (vertex chunks do not run in the line board)
  - `gl` &GlContext: GL context.
  - `mesh` &ToonMesh: Result of ToonRenderer::create_mesh.
  - `instance_buffer` &ToonInstanceBuffer: The result of ToonRenderer::create_instance_buffer. (shares the mesh and the vertex arrays of the buffer with the body)
  - `instance_count` usize: Number of instances to draw. (Clamped if more than the buffer holds)
  - `line_id` u32: Common id. (when the layout has no instanceLineId)
  - `options` ToonLineDrawOptions: Same as draw_mesh. (the options are the same for every instance, None for is_mirrored does not flip)

  Example: Draw the body and the line board with one rock buffer

  ```rust
  use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonBufferUsage, ToonDrawOptions, ToonLineDrawOptions, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};
  
  fn draw_rocks(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut outline = ToonScreenOutline::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#a89880", ToonPartOptions { has_outline: false, ..ToonPartOptions::default() });
  	let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
  	let instance_layout = renderer.create_instance_layout(&[("instanceMatrix", 16), ("instanceTint", 4), ("instanceLineId", 1)])?;
  	let mut data: Vec<f32> = Vec::new();
  	for index in 0..3 {
  		data.extend_from_slice(Matrix4::create_translation(index as f64 * 0.5, 0.0, 0.0).get_elements());
  		data.extend_from_slice(&[1.0, 1.0, 1.0, 1.0, 10.0 + index as f32]);
  	}
  	let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Static)?;
  	let view_matrix = Matrix4::create_look_at(Vector3::create(0.5, 2.0, 3.0), Vector3::create(0.5, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  	let projection_matrix = Matrix4::create_perspective(std::f64::consts::PI / 4.0, 1.0, 0.1, 100.0);
  	if outline.begin_line_ids(gl, &view_matrix, &projection_matrix) {
  		outline.draw_mesh_instance_buffer(gl, &rock_mesh, &instance_buffer, 3, 10, ToonLineDrawOptions::default());
  		outline.end_line_ids(gl);
  	}
  	renderer.begin_frame_with_matrices(gl, &view_matrix, &projection_matrix);
  	renderer.draw_mesh_instance_buffer(gl, &rock_mesh, &instance_buffer, 3, ToonDrawOptions::default());
  	renderer.end_frame(gl);
  	outline.draw_outline(gl);
  	Ok(())
  }
  ```

- `pub fn end_line_ids(&mut self, gl: &GlContext)` (method, since 0.4.0): Ends id drawing. (a thin line picks one side buffer, a thick line picks the seeds and widens them by jump flooding, then the framebuffer, viewport and state are restored)
  - Thin line (width at most about 3.24 line buffer pixels): the full-screen pass is one side buffer. The blend looks at the seeds of the 3 x 3 pixels around. (no seed, gather or widening)
  - Thick line: one pass per seed, gather and widening step. (the seed buffer and widening buffers are built the first time a thick line is drawn)
  - A pass that overwrites a whole buffer first clears the buffer (clear_buffer_u32_slice, clear_buffer_f32_slice) so the old contents are not loaded. (removes the buffer load of tile GPUs, at the same place as the original)
  - `gl` &GlContext: GL context.
- `pub fn draw_outline(&mut self, gl: &GlContext)` (method, since 0.4.0): Draws the outline. (a thin line blends from the side buffer and a thick line from the widened seed buffer into the drawing area of begin_line_ids, depth is neither read nor written, stencil is left as it is)
  - `gl` &GlContext: GL context.
- `pub fn destroy(&mut self, gl: &GlContext)` (method, since 0.4.0): Deletes after use. (the line buffer, vertex array, nine programs)
  - `gl` &GlContext: GL context.

## ToonScreenOutlineOptions (struct) (Clone, Copy, Debug, PartialEq, Eq, Default)

Options for building a screen-space outline. (original constructor options)

Example: Build with the linear color space

```rust
use vanilla::{ColorSpace, ToonScreenOutline, ToonScreenOutlineOptions};

fn create_linear_outline(gl: &vanilla::GlContext) -> Result<ToonScreenOutline, String> {
	ToonScreenOutline::new_with_options(gl, ToonScreenOutlineOptions { color_space: ColorSpace::Linear })
}
```

- `pub color_space: ColorSpace` (field, since 0.4.0): Color space. (original colorSpace, default is the engine's color space, the same value as the ToonRenderer)
  - returns ColorSpace

## Functions and constants

- `pub const TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID: u32 = 16383` (field, since 0.4.0): Upper limit of line IDs. (written to the line target with 14 bits, 0 is empty)
  - returns u32
- `pub fn read_jump_flood_steps(reach: f64) -> Vec<i32>` (method, since 0.4.0): Jump flooding step list. (the steps needed to expand seeds out to reach pixels, halving from the largest down to 1)
  - Steps k, k/2, ..., 1 move seeds up to 2k - 1 pixels. (Rong, Tan 2006)
  - `reach` f64: Distance to carry the seeds. (Line target pixels)
  - returns Vec<i32>: Steps from the largest down to 1.

  Example: Steps to widen up to 4 pixels

  ```rust
  use vanilla::read_jump_flood_steps;
  
  assert_eq!(read_jump_flood_steps(4.0), vec![4, 2, 1]);
  ```

## ToonOutlineWidthUnit (enum) (Clone, Copy, Debug, PartialEq, Eq)

Width unit.

- `World`: World length. (orthographic uses the projection's vertical scale, perspective converts to screen pixels at the focal distance, so it gets thinner farther away)
- `Pixel`: Drawing area pixels. (the same width regardless of distance)

## ToonOutlinePath (enum) (Clone, Copy, Debug, PartialEq, Eq)

Outline path of this frame. ("none", "thin", "thinScaled", "jumpFlood" of outlinePath in the original)

Example: Reading whether the thin line path was taken

```rust
use vanilla::{ToonOutlinePath, ToonScreenOutline};

fn is_thin_path(outline: &ToonScreenOutline) -> bool {
	match outline.get_line_target() {
		Some(line_target) => matches!(line_target.outline_path, ToonOutlinePath::Thin | ToonOutlinePath::ThinScaled),
		None => false,
	}
}
```

- `None`: Not drawn. (both widths are 0 so only the line buffer is kept, or before end_line_ids)
- `Thin`: Thin line. (one side buffer and one blend, width at most about 3.24 line buffer pixels)
- `ThinScaled`: Thin line of a reduced line buffer. (works out one coverage buffer at the line buffer resolution and blends it with one bilinear read)
- `JumpFlood`: Thick line. (seed, gather, widening steps, blend)
