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

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

Toon renderer. (ToonRenderer of vanilla.js graphics3d/toon/toonrenderer.js)
- Draws models from MeshBuilder arrays or read_glb_arrays with single-color material and outline.
- Light: holds one ToonLightSet as the default. Sun (direction and color, shadow), ambient light of sky color and ground color, fill light, point lights and spotlights (up to TOON_MAXIMUM_POINT_LIGHTS), rim light, highlight, light model (÷π).
  Cel shading is a shade ramp. (Base, 1st shade, 2nd shade with Step and Feather of the Unity Toon Shader, shadows enter as the shade color, boundaries without stairs by fwidth, a ramp texture also works)
  The sun receives the whole ramp color, while the fill light, point lights and spotlights receive the ramp's brightness level. Highlight and rim range from the hard toon form to the soft form. The math is in the toonlightset.rs header.
  set_light, set_sun_direction, set_fill_light, set_shade, set_shade_ramp, clear_shade_ramp, set_band_count, set_band_ramp, set_ramp_texture, set_rim_light, set_specular, set_point_lights,
  set_point_light_limit, set_light_model modify the default set. A different set (create_light_set) can be given per draw via the light_set of ToonDrawOptions.
- Normals: transformed by the transpose of the inverse of the upper left 3x3 of the model matrix and the joint matrix. (Light stays correct on stretched and squashed models, the same goes for matrices changed by the vertex chunk)
- Material: vertex color (sRGB), glow (multiplied by the base color and added), unlit. If vertex UVs (arrays.uv_data, 2 each) exist, textures are sampled.
- Draw options (ToonDrawOptions, defaults give the same image as before):
  tint_color [r, g, b, a] sRGB and alpha. If tint_amount is given (0 ~ 1), the tint is mixed in sRGB instead of multiplied. (hit flash, malfunction red)
  glow_scale multiplier of vertex glow (default 1), color_scale multiplier of the final linear color (default 1, darkens a mirrored image), emissive_color [r, g, b] sRGB and emissive_intensity (linear multiplier, default 1, color default black).
  base_color_texture (multiplied into base color, alpha into opacity), emissive_texture (multiplied into glow color), uv_transform [u offset, v offset, u scale, v scale] (offset, scale of KHR_texture_transform).
  decal_texture overlays the base color by alpha (color = texture x decal_color). Glows in that color by decal_emission. decal_uv_transform is for picking one cell of an atlas.
  alpha_cutoff discards pixels whose opacity is below it. (0 disables, glTF MASK)
  blend_mode: ToonBlendMode::Alpha (default, straight alpha), Premultiplied (premultiplied alpha), Additive (additive). Anything other than Alpha is drawn as transparent.
  soft_edge multiplies opacity by pow(|dot(N, V)|, soft_edge) to fade the edges. (0 disables, Fresnel style)
  is_mirrored draws with the winding flipped. If None, it flips by itself when the determinant of the model matrix is negative. If the view matrix is mirrored, that flip is added too.
  index_start, index_count draw only that span of the body vertex indices. (0 means to the end, GLB material ranges, hidden parts) outline_index_start, outline_index_count are for the outline shell.
  material (ToonMaterial), textures ([(uniform name, texture)]), on_before_draw(program, gl, ToonProgramKind) are extension points. (toonmaterial.rs header)
  light_set (ToonLightSet) is the light set of that draw. group, is_depth_prepassed are read only by ToonDrawQueue.
  If receives_shadow (default true) is false, the sun's shadow is not looked up. shade_offset is added to the received light amount to move the shade boundary. (Vertex color threshold of Guilty Gear Xrd, Shading Grade Map form of the Unity Toon Shader)
  specular_scale, rim_scale (default 1) are the highlight and rim multipliers of that draw. (0 means none, strength per material)
  matcap_texture is a matcap read with the view-space normal. matcap_strength (default 1), matcap_blend (ToonMatcapBlend::Multiply default, Add)
  outline_color [r, g, b, a] sRGB is the shell outline color of that draw (set_outline_color if None), outline_width_scale (default 1) is the multiplier of the built thickness.
  outline_offset_z (default 0) is the world length the shell is pushed away from the camera. (So it does not show in front of the body, Offset Z of the Unity Toon Shader)
  angel_ring_texture is the angel ring texture. u is the x of the view-space normal, v is the y of the second UV mixed with the y of the view normal by angel_ring_offset_v (default 0.3). (Angel Ring of the Unity Toon Shader)
  angel_ring_color [r, g, b] (linear multiplier, default white), angel_ring_offset_u (0 ~ 0.5, default 0), is_angel_ring_alpha (default false adds, true covers with the texture alpha)
  The angel ring UV is rotated back by the camera roll. (read_camera_roll, Camera Rolling Stabilizer of the Unity Toon Shader, the ring stays on the head even when the camera is tilted)
  line_id, has_screen_outline, has_crease_line are values ToonDrawQueue passes to the screen-space outline. (The renderer does not read them)
- Outline shell (inverted hull): uploads the base position and push direction (built thickness, the averaged normal of the same position) of the shell MeshBuilder built, and the shader pushes it by outline_width_scale and draws only back faces.
  If set_outline_distance_scale(reference distance, minimum scale, maximum scale) is given, distance to the camera / reference distance is multiplied into the thickness to keep the screen thickness. (Perspective only)
  If set_outline_fade_distance(near distance, far distance) is given, the thickness goes to 0 as the distance from the model position to the camera approaches the far distance. (smoothstep, Nearest and Farthest Distance of the Unity Toon Shader)
  The shell color is multiplied by the sun color when the outline light color usage of the light set is on (default). (Divided by its intensity when the intensity is 1 or more, same as the Unity Toon Shader outline)
- Skeleton: the joint matrices computed by write_skin_pose are passed to draw_mesh. (Up to TOON_MAXIMUM_JOINTS, 96 like the engine's SkinnedModelRenderer)
- GPU instancing: draw_mesh_instanced draws many copies of the same model at once with a matrix and tint per instance. (both body and outline, culled and uploaded on every draw)
  For long-lived instances, build a persistent buffer with create_instance_layout and create_instance_buffer and draw with draw_mesh_instance_buffer. (culls the whole buffer by its bounds, the material vertex snippet reads user attributes)
  When changing, use update_instance_buffer (whole) or update_instance_buffer_range (part, bufferSubData). The body, the outline shell, the shadow and the screen-space outline board share the same GPU buffer.
- Off-screen culling: tests the model's bounding sphere against the view-projection frustum and skips drawing if outside. (instances are culled one by one and only the rest are uploaded)
- Shadows: cast into the engine ShadowMap with begin_shadow_pass and draw_mesh, received with set_shadow. (3x3 PCF, the bias is the texel-unit value of ShadowMap::set_bias multiplied by the texel size and slope)
  Point light and spotlight shadows are cast into a ShadowAtlas with begin_shadow_atlas_pass and, per tile, set_shadow_atlas_tile and draw_mesh, and received with set_local_shadows. (A point light uses six cube tiles, a spotlight one perspective tile)
  The shadow is multiplied into that light's received amount and goes into the shade ramp. (Same form as the sun) Only point lights with casts_shadow true get tiles. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS)
  Even when shadows are not received, a 1x1 comparison depth texture is bound to both shadow units. (Without a depth texture on a sampler2DShadow unit the Mac driver reports it, and if a color texture is bound WebGL refuses to draw)
- HDR: set_hdr_output(true) outputs linear color without gamma. Draw into a float render target (ToonPostProcess) and finish with bloom and tone mapping.
- Usage: create_mesh(gl, arrays) → every frame begin_frame(gl, view and projection) → draw_mesh / draw_mesh_instanced → end_frame(gl) → delete_mesh when done.
  begin_frame records the previous draw state (blending, depth, face culling, program, vertex array) and enables depth testing and face culling, and end_frame restores the recorded state.
  (When inserting between engine 2D draws, flush the Graphic batch before it)
  begin_frame_with_matrices(gl, view, projection) starts with two matrices. (orthographic or raw matrix camera) The camera position and view rotation (highlight, rim, soft edge, matcap) are read from the view and projection.
- Per program, frame values (view and projection, camera, shadow, HDR) and the light set are uploaded only when they change. Only per-draw values (model matrix, tint, textures) are uploaded every time.
- read_program_sources gives the default sources to hand to ShaderWarmer, and read_material_program_sources(material, instance layout, ambient occlusion, color space) gives the sources of that program. (the original has one function with optional arguments)
- Drawing inside a node rectangle: given set_screen_rect(x, y, width, height), begin_frame moves the view-projection clip space into that rectangle and scissors out the rest.
  The rectangle is in pixels within the viewport at begin_frame time (usually the whole drawing buffer), with the origin at the top left. Off-screen culling uses the frustum before the move. end_frame releases the scissor.
- begin_frame_with_camera(Camera3D) calls begin_frame with the camera's view and projection. It uses the same camera as the 2D display (Camera3D::project_to_view).
- draw_mesh_outline draws only the outline shell. (when ToonDrawQueue draws all outlines together after drawing every opaque body, draws are not counted)
- casts_shadow of ToonDrawOptions is read only by ToonDrawQueue::draw_shadows. If is_body_drawn is false, only the outline is drawn. (The original attaches them by name to the options object)
- Textures: built with create_texture(gl, width, height, RGBA bytes, ToonTextureOptions). UV (0, 0) is the top left of the image. (Same as glTF)
- Color space: set by ToonRendererOptions::color_space of new_with_options (default is the engine's EngineConfiguration::color_space, Gamma without an engine) and does not change. (get_color_space)
  Gamma (default): passed colors and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB and then converted to linear with pow(color, 2.2) to compute light. pow(1 / 2.2) is applied for the screen.
  Linear: color textures are uploaded in an sRGB format so the GPU decodes them to linear, and passed colors are converted to linear with the standard sRGB curve before they are multiplied and mixed. The same curve converts back to sRGB for the screen.
  Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (ToonPostProcess and ToonScreenOutline are built with the same value too)
- Texture units: point light shadow atlas 0, ramp 1, matcap 2, sun shadow 3, base color 4, emission 5, decal 6, angel ring 7, material 8 ~ 15, ambient occlusion 16. begin_frame records the binding of unit 0 and end_frame restores it.
  A texture already bound to a unit is not bound again, and the chosen unit is not set back to 0 after every draw. (end_frame restores the chosen unit; stage callbacks and on_before_draw are called with unit 0 chosen)
- Ambient occlusion: while set_ambient_occlusion_texture(the result of ToonPostProcess::draw_ambient_occlusion, direct lighting strength) is set, bodies are drawn with the body program that defines TOON_AMBIENT_OCCLUSION.
  (The origin and the direct lighting strength go in the ambientOcclusionOrigin and ambientOcclusionDirectLightingStrength slots of the ToonFrame frame block, same as the original)
- Second UV: if the arrays have uv1_data, vertexUv is four values (UV, second UV). Shader chunks read it as ToonSurface.uv1. ((0, 1) if none)
- Light color usage (set_light_color_usage), shade-side rim (set_shade_rim_light) and light intensity limit (set_light_intensity_limited) live in the light set (ToonLightSet).

## ToonProgramSources (struct) (Clone, Debug)

Sources and attribute locations of the three programs. (result of compose_toon_program_sources)

Example: Building sources with material chunks and user instance attributes

```rust
use vanilla::{compose_toon_program_sources, ColorSpace, ToonInstanceLayout, ToonMaterial, ToonMaterialChunks};

let material = ToonMaterial::new(ToonMaterialChunks {
	name: String::from("pulse"),
	uniform_chunk: String::from("uniform float pulse;\n"),
	surface_chunk: String::from("void applySurface(inout ToonSurface surface) {\n\tsurface.emission += vec3(pulse);\n}\n"),
	..ToonMaterialChunks::default()
});
let instance_layout = ToonInstanceLayout::new(&[("instanceOffset", 3)]).unwrap();
let sources = compose_toon_program_sources(Some(&material), Some(&instance_layout), false, ColorSpace::Gamma, &[]);
assert!(sources.solid_fragment_shader.contains("uniform float pulse;"));
let linear_sources = compose_toon_program_sources(Some(&material), Some(&instance_layout), true, ColorSpace::Linear, &[]);
assert!(linear_sources.solid_fragment_shader.starts_with("#version 300 es\n#define VANILLA_COLOR_SPACE_LINEAR 1\n#define TOON_AMBIENT_OCCLUSION\n"));
assert!(sources.solid_vertex_shader.contains("in vec3 instanceOffset;"));
assert!(sources.attribute_locations.iter().any(|(name, _)| name == "instanceOffset"));
```

- `pub solid_vertex_shader: String` (field, since 0.4.0): Body vertex shader.
  - returns String
- `pub solid_fragment_shader: String` (field, since 0.4.0): Body fragment shader.
  - returns String
- `pub outline_vertex_shader: String` (field, since 0.4.0): Outline shell vertex shader.
  - returns String
- `pub outline_fragment_shader: String` (field, since 0.4.0): Outline shell fragment shader.
  - returns String
- `pub depth_vertex_shader: String` (field, since 0.4.0): Shadow depth vertex shader.
  - returns String
- `pub depth_fragment_shader: String` (field, since 0.4.0): Shadow depth fragment shader.
  - returns String
- `pub attribute_locations: Vec<(String, u32)>` (field, since 0.4.0): Attribute names and locations. (TOON_ATTRIBUTE_LOCATIONS plus the user attributes of the instance layout)
  - returns Vec<(String, u32)>

## ToonMesh (struct)

A model uploaded to the GPU.

Example: Upload two parts as one model and delete it when done

```rust
use vanilla::{create_box_geometry, create_sphere_geometry, Matrix4, MeshBuilder, ToonPartOptions, ToonRenderer};

fn upload_mesh(gl: &vanilla::GlContext, renderer: &ToonRenderer) {
	let mut builder = MeshBuilder::new();
	builder.add_part(&create_box_geometry(1.0, 1.0, 1.0), &Matrix4::create_identity(), "#d06060", ToonPartOptions::default());
	builder.add_part(&create_sphere_geometry(0.4, 16, 12, std::f64::consts::PI), &Matrix4::create_translation(0.0, 0.9, 0.0), "#f0c8a0", ToonPartOptions::default());
	if let Some(mesh) = renderer.create_mesh(gl, &builder.read_arrays()) {
		let (center, radius) = mesh.get_bounding_sphere();
		let (body_index_count, outline_index_count) = mesh.get_index_counts();
		println!("{:?} {} {} {} {}", center, radius, body_index_count, outline_index_count, mesh.has_outline());
		renderer.delete_mesh(gl, mesh);
	}
}
```

- `pub fn is_skinned(&self) -> bool` (method, since 0.4.0): Whether the model is moved by a skeleton.
  - returns bool: true if there is a skeleton (skin_data).
- `pub fn has_uv(&self) -> bool` (method, since 0.4.0): Whether it has texture coordinates.
  - returns bool: true if every vertex has a UV.
- `pub fn get_bounding_sphere(&self) -> ([f64; 3], f64)` (method, since 0.4.0): Bounding sphere. (center and radius in model coordinates, 1.5 times the rest pose for skeletal models)
  - returns ([f64; 3], f64): (center [x, y, z] in model coordinates, radius)
- `pub fn get_index_counts(&self) -> (usize, usize)` (method, since 0.4.0): Vertex index counts of the body and outline shell.
  - returns (usize, usize): (body vertex index count, outline shell vertex index count)
- `pub fn has_outline(&self) -> bool` (method, since 0.4.0): Whether it has an outline shell.
  - returns bool: true if there is an outline shell.

## ToonInstanceBuffer (struct)

Persistent instance buffer. (result of create_instance_buffer, a vertex array bound together with each model is built on the first draw)

Example: Upload the matrices and tints of nine trees once

```rust
use vanilla::{Matrix4, ToonBufferUsage, ToonDrawOptions, ToonMesh, ToonRenderer};

fn draw_trees(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, mesh: &ToonMesh, view_projection_matrix: &Matrix4) -> Result<(), String> {
	let instance_layout = renderer.create_instance_layout(&[("instanceMatrix", 16), ("instanceTint", 4)])?;
	let mut data: Vec<f32> = Vec::new();
	for index in 0..9 {
		let model_matrix = Matrix4::create_translation((index % 3) as f64 - 1.0, 0.0, (index / 3) as f64 - 1.0);
		data.extend_from_slice(model_matrix.get_elements());
		data.extend_from_slice(&[1.0, 1.0 - index as f32 * 0.05, 1.0, 1.0]);
	}
	let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Static)?;
	renderer.begin_frame(gl, view_projection_matrix);
	renderer.draw_mesh_instance_buffer(gl, mesh, &instance_buffer, instance_buffer.get_instance_count(), ToonDrawOptions::default());
	renderer.end_frame(gl);
	renderer.delete_instance_buffer(gl, instance_buffer);
	Ok(())
}
```

- `pub fn get_layout(&self) -> &ToonInstanceLayout` (method, since 0.4.0): Returns the instance layout.
  - returns &ToonInstanceLayout: Instance layout of the buffer.
- `pub fn get_float_count(&self) -> usize` (method, since 0.4.0): Number of values held.
  - returns usize: Number of values held.
- `pub fn get_instance_count(&self) -> usize` (method, since 0.4.0): Number of instances held. (the value count divided by the layout's value count)
  - returns usize: Number of stored instances.
- `pub fn get_id(&self) -> u64` (method, since 0.4.0): Buffer id. (different for every buffer, the shadow cache recognizes the buffer by it)
  - returns u64: Buffer id.
- `pub fn get_generation(&self) -> u64` (method, since 0.4.0): Number of changes. (+1 on every update_instance_buffer and update_instance_buffer_range, the shadow cache notices buffer changes through it)
  - returns u64: Number of changes.
- `pub fn get_bounds(&self) -> Option<ToonInstanceBounds>` (method, since 0.4.0): Bounds of the whole buffer. (only when the layout has a matrix)
  - returns Option<ToonInstanceBounds>: The bounds. None when there is no matrix or no instance.
- `pub fn get_data(&self) -> Option<std::cell::Ref<'_, [f32]>>` (method, since 0.4.0): The copy used to recompute the bounds. (only when the layout has a matrix, do not modify it)
  - returns Option<std::cell::Ref<'_, [f32]>>: The copy of the numbers. None when there is no matrix.

## ToonInstanceBounds (struct) (Clone, Copy, Debug, PartialEq)

Bounds of a whole instance buffer. (only when the layout has a matrix: the center of the position box, the distance to the farthest position and the largest scale; the original bounds)
- The mesh bounding sphere is added when drawing, so the bounds serve any mesh. (read_instance_buffer_sphere)

Example: Creating a bounds value

```rust
use vanilla::ToonInstanceBounds;

let bounds = ToonInstanceBounds { center: [0.0, 1.0, 0.0], radius: 5.0, scale: 2.0 };
assert_eq!(bounds.radius, 5.0);
```

- `pub center: [f64; 3]` (field, since 0.4.0): Center of the box of positions.
  - returns [f64; 3]
- `pub radius: f64` (field, since 0.4.0): Distance from the center to the farthest position.
  - returns f64
- `pub scale: f64` (field, since 0.4.0): Largest scale of the instance matrices.
  - returns f64

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

Options for building a texture. (mipmaps, repeat, smooth filtering)

Example: Building a 2x2 matcap without mipmaps and with edge clamping

```rust
use vanilla::core::graphic::GlTexture;
use vanilla::{ToonRenderer, ToonTextureOptions};

fn create_matcap_texture(gl: &vanilla::GlContext, renderer: &ToonRenderer) -> Result<GlTexture, String> {
	let pixels = [60, 60, 70, 255, 255, 255, 255, 255, 60, 60, 70, 255, 160, 160, 180, 255];
	renderer.create_texture(gl, 2, 2, &pixels, ToonTextureOptions { is_mipmapped: false, is_repeated: false, ..ToonTextureOptions::default() })
}
```

- `pub is_mipmapped: bool` (field, since 0.4.0): Whether to build mipmaps. (default true)
  - returns bool
- `pub is_repeated: bool` (field, since 0.4.0): Whether to repeat. (default true, false clamps to the edge)
  - returns bool
- `pub is_filtered: bool` (field, since 0.4.0): Whether to filter smoothly. (default true, false uses the nearest pixel)
  - returns bool
- `pub is_color_data: bool` (field, since 0.4.0): Whether it is a color. (default true means color, false means data such as normals or masks, only distinguished in the linear color space: colors are SRGB8_ALPHA8, data RGBA8, and the gamma color space always uses RGBA)
  - returns bool

## ToonBeforeDrawCallback (type)

Callback called before drawing. (program, GL, program kind, for setting the material's uniforms)

```rust
pub type ToonBeforeDrawCallback<'a> = &'a dyn Fn(&ShaderProgram, &GlContext, ToonProgramKind)
```

## ToonDrawOptions (struct) (Clone, Copy, Default, std::fmt::Debug)

Options for drawing one model.

Example: Change tint, outline color and thickness, and translucency per draw

```rust
use vanilla::{ToonBlendMode, ToonDrawOptions};

let options = ToonDrawOptions {
	tint_color: [1.0, 0.6, 0.6, 1.0],
	alpha: 0.5,
	outline_color: Some([0.1, 0.06, 0.08, 1.0]),
	outline_width_scale: 1.5,
	..ToonDrawOptions::default()
};
assert!(options.has_outline && options.is_culled);
assert_eq!(options.blend_mode, ToonBlendMode::Alpha);
```

- `pub tint_color: [f64; 4]` (field, since 0.4.0): Tint color. ([r, g, b, a] sRGB, default white, multiplied into the base color when tint_amount is not given, alpha is multiplied into opacity)
  - returns [f64; 4]
- `pub alpha: f64` (field, since 0.4.0): Opacity. (default 1, drawn as transparent when below 1)
  - returns f64
- `pub joint_matrices: Option<&'a [f32]>` (field, since 0.4.0): Joint matrix values. (computed by write_skin_pose, 16 per joint, None means no skeletal motion)
  - returns Option<&'a [f32]>
- `pub has_outline: bool` (field, since 0.4.0): Whether to draw the outline shell. (default true)
  - returns bool
- `pub is_culled: bool` (field, since 0.4.0): Whether to cull when off screen. (default true)
  - returns bool
- `pub casts_shadow: bool` (field, since 0.4.0): Whether to cast shadows. (default true, read only by ToonDrawQueue::draw_shadows)
  - returns bool
- `pub is_body_drawn: bool` (field, since 0.4.0): Whether to draw the body. (default true, false draws only the outline)
  - returns bool
- `pub tint_amount: Option<f64>` (field, since 0.4.0): Tint mix amount. (0 ~ 1, if given the tint is mixed in sRGB instead of multiplied, hit flash, malfunction red)
  - returns Option<f64>
- `pub glow_scale: f64` (field, since 0.4.0): Vertex glow multiplier. (default 1)
  - returns f64
- `pub color_scale: f64` (field, since 0.4.0): Multiplier of the final linear color. (default 1, darkens a mirrored image)
  - returns f64
- `pub emissive_color: [f64; 3]` (field, since 0.4.0): Glow color. ([r, g, b] sRGB, default black)
  - returns [f64; 3]
- `pub emissive_intensity: f64` (field, since 0.4.0): Glow color intensity. (linear multiplier, default 1)
  - returns f64
- `pub base_color_texture: Option<GlTexture>` (field, since 0.4.0): Base color texture. (multiplied into the base color, alpha into opacity, None means none)
  - returns Option<GlTexture>
- `pub emissive_texture: Option<GlTexture>` (field, since 0.4.0): Glow texture. (multiplied into the glow color, None means none)
  - returns Option<GlTexture>
- `pub uv_transform: [f64; 4]` (field, since 0.4.0): UV offset and scale. ([u offset, v offset, u scale, v scale], offset, scale of KHR_texture_transform)
  - returns [f64; 4]
- `pub decal_texture: Option<GlTexture>` (field, since 0.4.0): Decal texture. (overlays the base color by alpha, color = texture x decal_color, None means none)
  - returns Option<GlTexture>
- `pub decal_color: [f64; 3]` (field, since 0.4.0): Decal color. (multiplied into the texture, default white)
  - returns [f64; 3]
- `pub decal_emission: f64` (field, since 0.4.0): Amount the decal glows in its color. (default 0)
  - returns f64
- `pub decal_uv_transform: [f64; 4]` (field, since 0.4.0): Decal UV offset and scale. ([u offset, v offset, u scale, v scale], for picking one cell of an atlas)
  - returns [f64; 4]
- `pub alpha_cutoff: f64` (field, since 0.4.0): Discards pixels whose opacity is below it. (0 disables, glTF MASK)
  - returns f64
- `pub blend_mode: ToonBlendMode` (field, since 0.4.0): Blend mode. (default ToonBlendMode::Alpha, anything other than Alpha is drawn as transparent)
  - returns ToonBlendMode
- `pub soft_edge: f64` (field, since 0.4.0): Exponent that fades the edges. (opacity is multiplied by pow(|dot(N, V)|, soft_edge), 0 disables, Fresnel style)
  - returns f64
- `pub is_mirrored: Option<bool>` (field, since 0.4.0): Whether to draw with the winding flipped. (None flips by itself when the determinant of the model matrix is negative, if the view matrix is mirrored that flip is added too)
  - returns Option<bool>
- `pub index_start: usize` (field, since 0.4.0): First position to draw among the body vertex indices. (GLB material range, hidden parts)
  - returns usize
- `pub index_count: usize` (field, since 0.4.0): Number to draw among the body vertex indices. (0 means to the end)
  - returns usize
- `pub outline_index_start: usize` (field, since 0.4.0): First position to draw among the outline shell vertex indices.
  - returns usize
- `pub outline_index_count: usize` (field, since 0.4.0): Number to draw among the outline shell vertex indices. (0 means to the end)
  - returns usize
- `pub material: Option<&'a ToonMaterial>` (field, since 0.4.0): Material whose shader chunks are inserted. (None means the default program, toonmaterial.rs header)
  - returns Option<&'a ToonMaterial>
- `pub textures: &'a [(&'a str, GlTexture)]` (field, since 0.4.0): Material textures. ([(uniform name, texture)], from unit 8, up to TOON_MAXIMUM_MATERIAL_TEXTURES)
  - returns &'a [(&'a str, GlTexture)]
- `pub on_before_draw: Option<ToonBeforeDrawCallback<'a>>` (field, since 0.4.0): Callback called before drawing. (program, GL, program kind, for setting the material's uniforms)
  - returns Option<ToonBeforeDrawCallback<'a>>
- `pub light_set: Option<&'a ToonLightSet>` (field, since 0.4.0): Light set of that draw. (None means the renderer's default set)
  - returns Option<&'a ToonLightSet>
- `pub group: Option<u32>` (field, since 0.4.0): Group number of transparent draws. (the same number is sorted as one lump, read only by ToonDrawQueue)
  - returns Option<u32>
- `pub is_depth_prepassed: bool` (field, since 0.4.0): Whether to draw only the depth of the group first. (read only by ToonDrawQueue)
  - returns bool
- `pub receives_shadow: bool` (field, since 0.4.0): Whether to receive shadows. (if false, the sun's shadows are ignored)
  - returns bool
- `pub shade_offset: f64` (field, since 0.4.0): Value added to the light-receiving amount x. (shifts the shade boundary, the vertex color threshold of Guilty Gear Xrd, the Shading Grade Map style of Unity Toon Shader, the surface snippet can adjust it further with surface.shadeOffset)
  - returns f64
- `pub specular_scale: f64` (field, since 0.4.0): Specular highlight multiplier. (0 means no specular highlight for this draw, per-material strength)
  - returns f64
- `pub rim_scale: f64` (field, since 0.4.0): Rim light multiplier. (0 means no rim light for this draw)
  - returns f64
- `pub matcap_texture: Option<GlTexture>` (field, since 0.4.0): Matcap texture. (a sphere image read with view-space normals, None for none)
  - returns Option<GlTexture>
- `pub matcap_strength: f64` (field, since 0.4.0): Matcap strength.
  - returns f64
- `pub matcap_blend: ToonMatcapBlend` (field, since 0.4.0): Matcap blend. (multiply or add)
  - returns ToonMatcapBlend
- `pub outline_color: Option<[f64; 4]>` (field, since 0.4.0): Shell outline color. (sRGB and alpha, None for the renderer's set_outline_color)
  - returns Option<[f64; 4]>
- `pub outline_width_scale: f64` (field, since 0.4.0): Shell outline width multiplier. (multiplied by the built width)
  - returns f64
- `pub outline_offset_z: f64` (field, since 0.4.0): Distance to push the shell outline away from the camera. (World length, so it does not show through in front of the body, the form of Offset Z of the Unity Toon Shader)
  - returns f64
- `pub angel_ring_texture: Option<GlTexture>` (field, since 0.4.0): Angel ring texture. (A hair reflection band read with the x of the view-space normal and the y of the second UV, none if None, Angel Ring of the Unity Toon Shader)
  - returns Option<GlTexture>
- `pub angel_ring_color: [f64; 3]` (field, since 0.4.0): Angel ring color. (Linear multiplier)
  - returns [f64; 3]
- `pub angel_ring_offset_u: f64` (field, since 0.4.0): Amount that pulls the angel ring u toward the screen center. (0 ~ 0.5, AR_OffsetU)
  - returns f64
- `pub angel_ring_offset_v: f64` (field, since 0.4.0): Amount that shifts the angel ring v from the second UV toward the view normal. (0 ~ 1, AR_OffsetV, default 0.3)
  - returns f64
- `pub is_angel_ring_alpha: bool` (field, since 0.4.0): Whether the angel ring covers by texture alpha. (Adds if false, ARSampler_AlphaOn)
  - returns bool
- `pub line_id: Option<u32>` (field, since 0.4.0): Line ID for the screen-space outline. (when ToonDrawQueue draws into the line target, None uses the queue order + 1)
  - returns Option<u32>
- `pub has_screen_outline: bool` (field, since 0.4.0): Whether to output the screen-space outline. (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 screen-space crease lines.
  - returns bool

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

One instance. (model matrix and tint, the tint alpha also multiplies the outline)
- emissive_color is the emission sRGB added to that instance (None for none, added on top of the shading and pattern so only that instance brightens), and emissive_intensity is the linear multiplier of the emission (original default 1).
  The model matrix is read as affine. (see TOON_INSTANCE_FLOAT_COUNT, the emission goes into the bottom row of the matrix)
- line_id is this instance's line ID read by ToonScreenOutline::draw_mesh_instanced. (the original lineId, None uses the common ID, ToonRenderer does not read it)

Example: Twenty identical rocks with a different tint per instance

```rust
use vanilla::{Matrix4, ToonDrawOptions, ToonInstance, ToonMesh, ToonRenderer};

fn draw_rocks(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, mesh: &ToonMesh, view_projection_matrix: &Matrix4) {
	let instance_list: Vec<ToonInstance> = (0..20).map(|index| {
		let shade = 0.6 + (index % 5) as f64 * 0.1;
		ToonInstance {
			model_matrix: Matrix4::create_translation((index % 5) as f64 * 1.5, 0.0, (index / 5) as f64 * 1.5),
			tint_color: [shade, shade, shade, 1.0],
			..ToonInstance::default()
		}
	}).collect();
	renderer.begin_frame(gl, view_projection_matrix);
	renderer.draw_mesh_instanced(gl, mesh, &instance_list, ToonDrawOptions::default());
	renderer.end_frame(gl);
}
```

- `pub model_matrix: Matrix4` (field, since 0.4.0): Model matrix.
  - returns Matrix4
- `pub tint_color: [f64; 4]` (field, since 0.4.0): Tint color. ([r, g, b, a] sRGB, alpha is also multiplied into the outline)
  - returns [f64; 4]
- `pub line_id: Option<u32>` (field, since 0.4.0): Line number for the screen-space outline. (None means the shared number, ToonRenderer does not read it)
  - returns Option<u32>
- `pub emissive_color: Option<[f64; 3]>` (field, since 0.4.0): Added emission color. ([r, g, b] sRGB, None for no emission)
  - returns Option<[f64; 3]>
- `pub emissive_intensity: f64` (field, since 0.4.0): Linear multiplier of the emission. (original default 1, not read when emissive_color is None)
  - returns f64

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

Drawn and culled counts. (one frame, cleared by begin_frame)

Example: Printing draw calls and culled count after drawing a frame

```rust
use vanilla::{ToonFrameStatistics, ToonRenderer};

fn print_statistics(renderer: &ToonRenderer) {
	let statistics: ToonFrameStatistics = renderer.get_frame_statistics();
	println!("draw calls {}, drawn {}, culled {}", statistics.draw_call_count, statistics.drawn_object_count, statistics.culled_object_count);
}
```

- `pub draw_call_count: u32` (field, since 0.4.0): Draw call count.
  - returns u32
- `pub drawn_object_count: u32` (field, since 0.4.0): Number of drawn models. (instances are counted one by one)
  - returns u32
- `pub culled_object_count: u32` (field, since 0.4.0): Number of models culled as off screen. (instances are counted one by one)
  - returns u32

## ToonFrameCamera (struct) (Clone, Copy, Debug, PartialEq)

Camera read from the view and projection. (position is [x, y, z, 1] for perspective, [0, 0, 0, 0] for orthographic, forward is the view direction, is_mirrored is whether the view matrix is mirrored)

Example: Read the eye position and view direction from the view and projection matrices

```rust
use vanilla::{read_frame_camera, Matrix4, Vector3};

let mut view_projection_matrix = Matrix4::create_perspective(0.8, 16.0 / 9.0, 0.1, 100.0);
view_projection_matrix.multiply(&Matrix4::create_look_at(Vector3::create(0.0, 2.0, 5.0), Vector3::create(0.0, 2.0, 0.0), Vector3::create(0.0, 1.0, 0.0)));
let frame_camera = read_frame_camera(&view_projection_matrix);
assert_eq!(frame_camera.position[3], 1.0);
assert!((frame_camera.position[2] - 5.0).abs() < 0.001);
assert!(frame_camera.forward[2] < -0.999);
assert!(!frame_camera.is_mirrored);
```

- `pub position: [f64; 4]` (field, since 0.4.0): Eye position. ([x, y, z, 1] perspective, [0, 0, 0, 0] orthographic)
  - returns [f64; 4]
- `pub forward: [f64; 3]` (field, since 0.4.0): View direction. ([x, y, z], unit)
  - returns [f64; 3]
- `pub is_mirrored: bool` (field, since 0.4.0): Whether the view matrix is mirrored.
  - returns bool

## ToonProgramPrewarmOptions (struct) (Clone, Copy, Default)

List of combinations to add to the prewarm. (The options of the original prewarmDrawQueue; the default adds nothing)

Example

```rust
use vanilla::ToonProgramPrewarmOptions;

let options = ToonProgramPrewarmOptions::default();
assert!(options.light_feature_list.is_empty());
```

- `pub queue_list: &'a [&'a ToonDrawQueue<'q>]` (field, since 0.4.0): Draw queues to read more from. (Queues holding materials or instance layouts that appear later; the original queueList)
  - returns &'a [&'a ToonDrawQueue<'q>]
- `pub light_set_list: &'a [&'a ToonLightSet]` (field, since 0.4.0): Light sets to additionally match against every draw in the draw queue. (Uses the feature bits of their current values; the original lightSetList)
  - returns &'a [&'a ToonLightSet]
- `pub light_feature_list: &'a [&'a [&'a str]]` (field, since 0.4.0): Light set side feature combinations to additionally match. (Per combination, the names among "rampTexture", "shadeStops", "rim", "shadeRim" and "intensityLimit" that will additionally turn on; the original lightFeatureList)
  - returns &'a [&'a [&'a str]]

## ToonProgramPrewarm (struct)

Progress of prewarming program variants. (The result of ToonRenderer::prewarm_draw_queue, the original ToonProgramPrewarm)
- Without the parallel compile extension it is already finished when created. With it, the handed-off compiles are finished a few per frame by step.

Example: Finishing one step per frame while loading and starting once done

```rust
use vanilla::{ToonDrawQueue, ToonRenderer};

fn update_loading(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, queue: &ToonDrawQueue) -> bool {
	let mut prewarm = renderer.prewarm_draw_queue(gl, queue);
	while !prewarm.step(gl, renderer) {
		// Call again each frame.
	}
	prewarm.is_ready()
}
```

- `pub fn step(&mut self, gl: &crate::GlContext, renderer: &mut ToonRenderer) -> bool` (method, since 0.4.0): One step. (Finishes compiled programs and puts them in the program slots, only a few per step, call it every frame)
  - `gl` &crate::GlContext: GL context that built the renderer.
  - `renderer` &mut ToonRenderer: The renderer that prewarm_draw_queue was called on.
  - returns bool: True if everything is finished.
- `pub fn is_ready(&self) -> bool` (method, since 0.4.0): Whether everything is built. (Drawing is allowed anyway; anything not built is built on the spot)
  - returns bool: True if everything is built.
- `pub fn wait(&mut self, gl: &crate::GlContext, renderer: &mut ToonRenderer)` (method, since 0.4.0): Waits until everything is built. (Finishes all the remaining compiles inside this call)
  - `gl` &crate::GlContext: GL context that built the renderer.
  - `renderer` &mut ToonRenderer: The renderer that prewarm_draw_queue was called on.

## ToonRenderer (struct)

Toon renderer. (see the header comment)

Example: Draw after setting the sun and outline color, then read statistics and clean up

```rust
use vanilla::{create_capsule_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonPartOptions, ToonRenderer, Vector3};

fn draw_once(gl: &vanilla::GlContext) -> Result<(), String> {
	let mut renderer = ToonRenderer::new(gl)?;
	renderer.set_light([-0.4, -1.0, -0.3], [1.0, 0.96, 0.9], [0.45, 0.5, 0.6], [0.25, 0.22, 0.2]);
	renderer.set_outline_color([0.1, 0.06, 0.08, 1.0]);
	let mut builder = MeshBuilder::new();
	builder.add_part(&create_capsule_geometry(0.3, 0.6, 8, 16), &Matrix4::create_identity(), "#a0d0a0", ToonPartOptions { outline_width: 0.02, ..ToonPartOptions::default() });
	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
	let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 1.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(0.8, 1.0, 0.1, 20.0);
	renderer.begin_frame_with_matrices(gl, &view_matrix, &projection_matrix);
	renderer.draw_mesh(gl, &mesh, &Matrix4::create_identity(), ToonDrawOptions::default());
	renderer.draw_mesh(gl, &mesh, &Matrix4::create_translation(0.0, 0.0, 50.0), ToonDrawOptions::default());
	renderer.end_frame(gl);
	let statistics = renderer.get_frame_statistics();
	assert_eq!((statistics.drawn_object_count, statistics.culled_object_count), (1, 1));
	renderer.delete_mesh(gl, mesh);
	renderer.destroy(gl);
	Ok(())
}
```

- `pub fn read_program_sources() -> [(String, String); 3]` (static, since 0.4.0): Shader sources. (three (vertex, fragment) pairs: body, outline, shadow depth, for the default programs)
  - returns [(String, String); 3]: Three sets of (vertex, fragment) sources. (body, outline, shadow depth)
- `pub fn read_material_program_sources(material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, is_ambient_occlusion: bool, color_space: ColorSpace) -> [(String, String); 3]` (static, since 0.4.0): Shader sources for a material and instance layout. (three (vertex, fragment) pairs, the attribute locations are attribute_locations of compose_toon_program_sources)
  - `material` Option<&ToonMaterial>: Material whose shader chunks are inserted. (None means empty chunks)
  - `instance_layout` Option<&ToonInstanceLayout>: Instance layout. (None means none)
  - `is_ambient_occlusion` bool: Whether it is the body program of a frame with ambient occlusion on. (original default false; frames with a texture set by set_ambient_occlusion_texture use this body program)
  - `color_space` ColorSpace: Color space. (original default is the engine's color space; pass the same value the renderer builds with)
  - returns [(String, String); 3]: Three sets of (vertex, fragment) sources. (body, outline, shadow depth)
- `pub fn new(gl: &crate::GlContext) -> Result<ToonRenderer, String>` (constructor, since 0.4.0): Creation. (builds the three default programs, the color space is the engine's)
  - `gl` &crate::GlContext: GL context to draw with.
  - returns Result<ToonRenderer, String>: New renderer. Err(error text) if the default programs or textures cannot be built.
- `pub fn new_with_options(gl: &crate::GlContext, options: ToonRendererOptions) -> Result<ToonRenderer, String>` (static, since 0.4.0): Creation with options. (original new ToonRenderer(gl, options), builds the three default programs)
  - The color space is fixed at creation and does not change. (get_color_space)
    Gamma (default): passed colors (vertex color, tint, emissive color, decal color, outline color) and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB and then converted to linear with pow(color, 2.2) to compute light.
      pow(1 / 2.2) is applied for the screen. (linear as is for HDR output)
    Linear: color textures are uploaded in an sRGB format so the GPU decodes them to linear, and passed colors are converted to linear with the standard sRGB curve (IEC 61966-2-1) before they are multiplied and mixed. The same curve converts back to sRGB for the screen.
      Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (ToonPostProcess and ToonScreenOutline are built with the same value too)
  - `gl` &crate::GlContext: GL context to draw with.
  - `options` ToonRendererOptions: Color space. (ToonRendererOptions)
  - returns Result<ToonRenderer, String>: New renderer. Err(error text) if the default programs or textures cannot be built.
- `pub fn create_material(&self, chunks: ToonMaterialChunks) -> ToonMaterial` (method, since 0.4.0): Creates a material. (shader snippets, toonmaterial.rs header comment)
  - `chunks` ToonMaterialChunks: Shader chunks. (name, uniform_chunk, surface_chunk, light_chunk, vertex_chunk, an empty text means the engine's empty function)
  - returns ToonMaterial: The built material.
- `pub fn set_async_program_build(&mut self, is_async: bool)` (method, since 0.4.0): Sets whether to hand off a body variant first seen and draw with the default body meanwhile. (The original setAsyncProgramBuild; default true; without the parallel compile extension it is built on the spot regardless of this value)
  - `is_async` bool: If true, a body variant first seen mid-scene is not built on the spot; it is drawn with the default body with every feature on (same picture) until it finishes building. If false, it is built on the spot and waited for.

  Example

  ```rust
  use vanilla::ToonRenderer;
  
  fn configure(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	renderer.set_async_program_build(false);
  	assert!(!renderer.is_async_program_build());
  	Ok(())
  }
  ```

- `pub fn is_async_program_build(&self) -> bool` (method, since 0.4.0): Reads whether a body variant first seen is handed off and the default body is drawn meanwhile. (The original isAsyncProgramBuild)
  - returns bool: True if handed off and drawn with the default body. (Default true)

  Example

  ```rust
  use vanilla::ToonRenderer;
  
  fn read(gl: &vanilla::GlContext) -> Result<(), String> {
  	let renderer = ToonRenderer::new(gl)?;
  	assert!(renderer.is_async_program_build());
  	Ok(())
  }
  ```

- `pub fn prepare_material(&mut self, gl: &crate::GlContext, material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>) -> bool` (method, since 0.4.0): Prebuilds a material's programs. (to avoid a stall on first draw, false on failure)
  - `gl` &crate::GlContext: GL context.
  - `material` Option<&ToonMaterial>: Material to build in advance. (None means the default program)
  - `instance_layout` Option<&ToonInstanceLayout>: Instance layout to use with it. (None means none)
  - returns bool: false if it could not be built.
- `pub fn prewarm_draw_queue(&mut self, gl: &crate::GlContext, queue: &ToonDrawQueue) -> ToonProgramPrewarm` (method, since 0.4.0): Prewarms, without drawing, the program variants that the items in a draw queue will use. (The original prewarmDrawQueue; same idea as Unity ShaderVariantCollection.WarmUp and Unreal PSO caches)
  - Builds the material, body feature bits (decided by the light set and draw options), ambient occlusion body, outline and shadow depth programs with the same keys the draw queue uses when drawing.
  - Moves the one-frame hitch of building a program for a combination first seen in the first draw into loading time. Call it once after adding the scene and before the first frame.
  - With GL_KHR_parallel_shader_compile (the web uses the same extension) it only hands off compiling and finishes the compiled ones each frame with ToonProgramPrewarm::step. Without it, programs are built inside this call.
  - Drawing before the prewarm finishes is fine. A variant not built yet is built on the spot. (Same behavior)
  - Once the draw queue gets instance layouts, their variants are built with the same keys. (instance_layout of ToonProgramRequest)
  - `gl` &crate::GlContext: GL context that built the renderer.
  - `queue` &ToonDrawQueue: Draw queue to read the variants from. (Only reads what was added; does not draw)
  - returns ToonProgramPrewarm: Progress of the prewarm. (is_ready, step, wait)

  Example: Prewarming variants after adding the scene and before the first frame

  ```rust
  use vanilla::{create_sphere_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonRenderer};
  
  fn prewarm(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_sphere_geometry(0.5, 16, 10, std::f64::consts::PI), &Matrix4::create_identity(), "#f0e8e0", ToonPartOptions::default());
  	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
  	let mut queue = ToonDrawQueue::new();
  	queue.add_mesh(&mesh, &Matrix4::create_identity(), ToonDrawOptions { casts_shadow: false, ..ToonDrawOptions::default() });
  	let mut prewarm = renderer.prewarm_draw_queue(gl, &queue);
  	prewarm.wait(gl, &mut renderer);
  	assert!(prewarm.is_ready());
  	Ok(())
  }
  ```

- `pub fn prewarm_draw_queue_with_options<'x, 'a: 'x, 'q: 'x>(&mut self, gl: &crate::GlContext, queue: &ToonDrawQueue<'a>, options: &ToonProgramPrewarmOptions<'_, 'q>) -> Result<ToonProgramPrewarm, String>` (method, since 0.4.0): Prewarms what a draw queue holds plus the combinations the game will use mid-scene. (The original prewarmDrawQueue(queue, options); like Unity ShaderVariantCollection, you give a list of combinations)
  - To the variants the queue holds it adds the light feature combinations of options, the light sets and the variants read from other queues, and builds even what is not in the queue now with the same keys. Everything else is the same as prewarm_draw_queue.
  - If a light feature name is not rampTexture, shadeStops, rim, shadeRim or intensityLimit, nothing is built and Err is returned. (The original throws)
  - `gl` &crate::GlContext: GL context that built the renderer.
  - `queue` &ToonDrawQueue<'a>: Draw queue to read the variants from.
  - `options` &ToonProgramPrewarmOptions<'_, 'q>: List of combinations to build in addition. (ToonProgramPrewarmOptions::default() is the same as prewarm_draw_queue)
  - returns Result<ToonProgramPrewarm, String>: Progress of the prewarm. Err if a light feature name is wrong.

  Example: Prewarming up to the rim light combinations that turn on mid-scene

  ```rust
  use vanilla::{create_sphere_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonProgramPrewarmOptions, ToonRenderer};
  
  fn prewarm(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_sphere_geometry(0.5, 16, 10, std::f64::consts::PI), &Matrix4::create_identity(), "#f0e8e0", ToonPartOptions::default());
  	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
  	let mut queue = ToonDrawQueue::new();
  	queue.add_mesh(&mesh, &Matrix4::create_identity(), ToonDrawOptions { casts_shadow: false, ..ToonDrawOptions::default() });
  	let rim: &[&str] = &["rim"];
  	let rim_and_shade_rim: &[&str] = &["rim", "shadeRim"];
  	let options = ToonProgramPrewarmOptions { light_feature_list: &[rim, rim_and_shade_rim], ..ToonProgramPrewarmOptions::default() };
  	let mut prewarm = renderer.prewarm_draw_queue_with_options(gl, &queue, &options)?;
  	prewarm.wait(gl, &mut renderer);
  	assert!(prewarm.is_ready());
  	Ok(())
  }
  ```

- `pub fn delete_material(&mut self, gl: &crate::GlContext, material: &ToonMaterial)` (method, since 0.4.0): Deletes a material's programs. (for all instance layouts, rebuilt when drawn again)
  - `gl` &crate::GlContext: GL context that built the programs.
  - `material` &ToonMaterial: Material whose programs to delete.
- `pub fn create_light_set(&self) -> ToonLightSet` (method, since 0.4.0): Creates a light set. (to pass per draw through light_set of ToonDrawOptions, starts with the same values as the default lighting)
  - returns ToonLightSet: A new light set starting with the same values as the default light.
- `pub fn get_light_set(&self) -> &ToonLightSet` (method, since 0.4.0): Returns the default light set.
  - returns &ToonLightSet: The default light set.
- `pub fn get_light_set_mut(&mut self) -> &mut ToonLightSet` (method, since 0.4.0): Returns the default light set. (for modifying it)
  - returns &mut ToonLightSet: The default light set. (a mutable reference)
- `pub fn create_instance_layout(&self, attributes: &[(&str, usize)]) -> Result<ToonInstanceLayout, String>` (method, since 0.4.0): Creates an instance layout. ((name, size) list, ToonInstanceLayout in toonmaterial.rs)
  - `attributes` &[(&str, usize)]: List of (name, size).
  - returns Result<ToonInstanceLayout, String>: Built instance layout. Err(error text) if a name is not a shader name or is duplicated, a size does not fit, or there are too many user attributes.
- `pub fn create_instance_buffer(&self, gl: &crate::GlContext, instance_layout: &ToonInstanceLayout, data: &[f32], usage: ToonBufferUsage) -> Result<ToonInstanceBuffer, String>` (method, since 0.4.0): Creates a persistent instance buffer. (data holding the layout's value count per instance, with ToonBufferUsage::Static it is uploaded once and drawn for a long time)
  - `gl` &crate::GlContext: GL context to build the buffer with.
  - `instance_layout` &ToonInstanceLayout: Layout of one instance.
  - `data` &[f32]: Numbers of instances stored one after another, layout float count each.
  - `usage` ToonBufferUsage: A ToonBufferUsage value. (Static uploads once and draws for a long time)
  - returns Result<ToonInstanceBuffer, String>: Instance buffer. Err(the GL error text) if the buffer cannot be built.
- `pub fn update_instance_buffer(&self, gl: &crate::GlContext, instance_buffer: &ToonInstanceBuffer, data: &[f32])` (method, since 0.4.0): Updates an instance buffer. (re-uploads the whole thing)
  - `gl` &crate::GlContext: GL context that built the buffer.
  - `instance_buffer` &ToonInstanceBuffer: Result of create_instance_buffer.
  - `data` &[f32]: New numbers. (The instance count may change)
- `pub fn update_instance_buffer_range(&self, gl: &crate::GlContext, instance_buffer: &ToonInstanceBuffer, first_instance: usize, data: &[f32]) -> Result<(), String>` (method, since 0.4.0): Update part of an instance buffer. (uploads only as many instances as data holds, from instance first_instance, bufferSubData)
  - `gl` &crate::GlContext: GL context that built the buffer.
  - `instance_buffer` &ToonInstanceBuffer: Result of create_instance_buffer.
  - `first_instance` usize: Number of the first instance to update. (from 0)
  - `data` &[f32]: The numbers of the instances to update, laid out one layout float count after another. (Err beyond the instances in the buffer; use update_instance_buffer to grow it)
  - returns Result<(), String>: Ok when updated. Err(reason text) when the range does not fit.

  Example: Move one rock and draw without uploading again

  ```rust
  use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonBufferUsage, ToonDrawOptions, ToonPartOptions, ToonRenderer, Vector3};
  
  fn move_one_rock(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#909098", ToonPartOptions { has_outline: true, ..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)])?;
  	let mut data: Vec<f32> = Vec::new();
  	for index in 0..3 {
  		data.extend_from_slice(Matrix4::create_translation(index as f64 - 1.0, 0.0, 0.0).get_elements());
  		data.extend_from_slice(&[1.0, 1.0, 1.0, 1.0]);
  	}
  	let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Dynamic)?;
  	let mut moved: Vec<f32> = Vec::new();
  	moved.extend_from_slice(Matrix4::create_translation(0.0, 0.5, 0.0).get_elements());
  	moved.extend_from_slice(&[1.0, 0.6, 0.6, 1.0]);
  	renderer.update_instance_buffer_range(gl, &instance_buffer, 1, &moved)?;
  	let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 2.0, 4.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  	renderer.begin_frame_with_matrices(gl, &view_matrix, &Matrix4::create_perspective(0.8, 1.0, 0.1, 30.0));
  	renderer.draw_mesh_instance_buffer(gl, &rock_mesh, &instance_buffer, 3, ToonDrawOptions::default());
  	renderer.end_frame(gl);
  	assert_eq!(instance_buffer.get_generation(), 1);
  	Ok(())
  }
  ```

- `pub fn delete_instance_buffer(&self, gl: &crate::GlContext, instance_buffer: ToonInstanceBuffer)` (method, since 0.4.0): Deletes an instance buffer. (also the vertex arrays built with it, delete before the model)
  - `gl` &crate::GlContext: GL context that built the buffer.
  - `instance_buffer` ToonInstanceBuffer: Result of create_instance_buffer.
- `pub fn create_texture(&self, gl: &crate::GlContext, width: u32, height: u32, pixels: &[u8], options: ToonTextureOptions) -> Result<GlTexture, String>` (method, since 0.4.0): Creates a texture. (RGBA bytes width x height x 4, decode images with decode_glb_image or the image crate)
  - In the linear color space (ColorSpace::Linear), color textures (base color, emission, decal, matcap, angel ring, ramp) are uploaded in an sRGB format (SRGB8_ALPHA8).
    The GPU decodes them to linear when reading, so filtering and mipmaps happen in linear space, and the shader uses the values as linear colors as they are. (the same as sRGB textures in Unity and Unreal)
    Data textures such as normals, masks and ids are uploaded to RGBA8 as they are with is_color_data: false. (data read by material chunks)
  - The gamma color space (default) uploads RGBA regardless of is_color_data, and the shader converts color textures to linear with pow 2.2. (the same as before)
  - `gl` &crate::GlContext: GL context to build the texture with.
  - `width` u32: Width. (pixels)
  - `height` u32: Height. (pixels)
  - `pixels` &[u8]: RGBA bytes. (width x height x 4 or more)
  - `options` ToonTextureOptions: Mipmaps, repeat, filtering, whether it is a color. (ToonTextureOptions)
  - returns Result<GlTexture, String>: Built RGBA texture. Err(error text) if the width or height is 0, the bytes are short, or the texture cannot be built.
- `pub fn delete_texture(&self, gl: &crate::GlContext, texture: GlTexture)` (method, since 0.4.0): Deletes a texture.
  - `gl` &crate::GlContext: GL context that built the texture.
  - `texture` GlTexture: Texture to delete.
- `pub fn destroy(&self, gl: &crate::GlContext)` (method, since 0.4.0): Deletes the renderer. (all programs and the empty texture, models, instance buffers and textures are deleted separately)
  - `gl` &crate::GlContext: GL context that built the renderer.
- `pub fn create_mesh(&self, gl: &crate::GlContext, arrays: &ToonMeshArrays) -> Option<ToonMesh>` (method, since 0.4.0): Uploads a mesh. (None if the body is empty)
  - If building a GL buffer or vertex array fails, deletes what was built so far and returns None.
  - `gl` &crate::GlContext: GL context to upload the model with.
  - `arrays` &ToonMeshArrays: Result of MeshBuilder::read_arrays or read_glb_arrays.
  - returns Option<ToonMesh>: Model uploaded to the GPU. (None if the body vertex indices are empty or GL buffers cannot be built)
- `pub fn delete_mesh(&self, gl: &crate::GlContext, mesh: ToonMesh)` (method, since 0.4.0): Deletes a model.
  - `gl` &crate::GlContext: GL context that uploaded the model.
  - `mesh` ToonMesh: Result of create_mesh.
- `pub fn apply_frame_state(&self, gl: &crate::GlContext)` (method, since 0.4.0): Applies the frame's draw state. (blending off, depth test LEQUAL and depth write, back-face culling, front face CCW, ToonDrawQueue reapplies it after stage callbacks)
  - `gl` &crate::GlContext: GL context.
- `pub fn begin_frame(&mut self, gl: &crate::GlContext, view_projection_matrix: &Matrix4)` (method, since 0.4.0): Begins a frame. (sets view, projection and frustum, records the previous state, then enables depth testing and face culling, the caller decides whether to clear depth)
  - `gl` &crate::GlContext: GL context.
  - `view_projection_matrix` &Matrix4: View and projection matrix. (Projection x view)
- `pub fn end_frame(&mut self, gl: &crate::GlContext)` (method, since 0.4.0): Ends a frame. (restores the recorded state)
  - `gl` &crate::GlContext: GL context.
- `pub fn begin_frame_with_camera(&mut self, gl: &crate::GlContext, camera: &Camera3D)` (method, since 0.4.0): Begins a frame with a camera. (begin_frame with the Camera3D's view and projection)
  - `gl` &crate::GlContext: GL context.
  - `camera` &Camera3D: Camera3D. (Reads view and projection)
- `pub fn begin_frame_with_matrices(&mut self, gl: &crate::GlContext, view_matrix: &Matrix4, projection_matrix: &Matrix4)` (method, since 0.4.0): Begins a frame with view and projection matrices. (without Camera3D, begin_frame with projection x view)
  - `gl` &crate::GlContext: GL context.
  - `view_matrix` &Matrix4: View matrix.
  - `projection_matrix` &Matrix4: Projection matrix.
- `pub fn get_frame_camera(&self) -> ToonFrameCamera` (method, since 0.4.0): Returns this frame's camera. (read from view and projection)
  - returns ToonFrameCamera: Camera of this frame. (position [x, y, z, w(1 perspective, 0 orthographic)], forward, is_mirrored)
- `pub fn set_screen_rect(&mut self, x: f64, y: f64, width: f64, height: f64)` (method, since 0.4.0): Sets the screen rectangle to draw into. (viewport pixels, top-left origin, from the next begin_frame)
  - `x` f64: Left edge. (Viewport pixels)
  - `y` f64: Top edge. (Viewport pixels, top is 0)
  - `width` f64: Width. (pixels)
  - `height` f64: Height. (pixels)
- `pub fn clear_screen_rect(&mut self)` (method, since 0.4.0): Clears the screen rectangle to draw into. (draws to the whole viewport)
- `pub fn get_screen_rect(&self) -> Option<Rect>` (method, since 0.4.0): Returns the screen rectangle to draw into. (None if none)
  - returns Option<Rect>: Screen rectangle to draw in. (None if none)
- `pub fn begin_shadow_pass(&mut self, gl: &crate::GlContext, shadow_map: &ShadowMap)` (method, since 0.4.0): Begins the shadow depth pass. (into the ShadowMap's framebuffer with the light's view and projection, end_shadow_pass restores the previous framebuffer and viewport)
  - `gl` &crate::GlContext: GL context.
  - `shadow_map` &ShadowMap: ShadowMap. (where depth is drawn, set the light matrix with update_light_matrix beforehand)
- `pub fn begin_shadow_atlas_pass(&mut self, gl: &crate::GlContext, shadow_atlas: &ShadowAtlas)` (method, since 0.4.0): Begins the shadow atlas depth pass. (Binds and clears the atlas and notes the previous state, per tile draw_mesh draws only depth after set_shadow_atlas_tile, end with end_shadow_pass)
  - `gl` &crate::GlContext: GL context.
  - `shadow_atlas` &ShadowAtlas: ShadowAtlas.
- `pub fn set_shadow_atlas_tile(&mut self, gl: &crate::GlContext, shadow_atlas: &ShadowAtlas, tile_index: usize)` (method, since 0.4.0): Selects a tile of the shadow atlas. (Sets that tile's view, projection, frustum and viewport, between begin_shadow_atlas_pass and end_shadow_pass)
  - `gl` &crate::GlContext: GL context.
  - `shadow_atlas` &ShadowAtlas: ShadowAtlas.
  - `tile_index` usize: Cell index.
- `pub fn end_shadow_pass(&mut self, gl: &crate::GlContext)` (method, since 0.4.0): Ends the shadow depth pass. (restores the framebuffer, viewport and state)
  - `gl` &crate::GlContext: GL context.
- `pub fn is_visible(&self, mesh: &ToonMesh, model_matrix: &Matrix4) -> bool` (method, since 0.4.0): Whether the bounding sphere is inside the frustum. (center transformed by the model matrix, radius multiplied by the largest scale)
  - `mesh` &ToonMesh: Result of create_mesh.
  - `model_matrix` &Matrix4: Model matrix.
  - returns bool: true if inside the frustum.
- `pub fn draw_mesh(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, model_matrix: &Matrix4, options: ToonDrawOptions)` (method, since 0.4.0): Draws one model. (depth only in the shadow pass, skipped if off-screen)
  - `gl` &crate::GlContext: GL context.
  - `mesh` &ToonMesh: Result of create_mesh.
  - `model_matrix` &Matrix4: Model matrix.
  - `options` ToonDrawOptions: Draw options. (ToonDrawOptions, header comment)
- `pub fn draw_mesh_instanced(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, instance_list: &[ToonInstance], options: ToonDrawOptions)` (method, since 0.4.0): Draws many copies of the same model at once. (GPU instancing, off-screen instances are culled and only the rest are uploaded)
  - For skeletal models, all instances share the same pose. (joint_matrices of options)
  - The winding is decided by the first instance's matrix. (or by is_mirrored if given)
  - `gl` &crate::GlContext: GL context.
  - `mesh` &ToonMesh: Result of create_mesh.
  - `instance_list` &[ToonInstance]: Model matrix, tint and emission per instance. (the tint is a multiplied sRGB and alpha, the emission is an added sRGB and linear multiplier, the model matrix is read as affine)
  - `options` ToonDrawOptions: Same as draw_mesh. (applied the same to every instance)

  Example: Brighten only one instance by adding emission

  ```rust
  use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonInstance, ToonPartOptions, ToonRenderer, Vector3};
  
  fn draw_glowing_rock(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#909098", ToonPartOptions { has_outline: true, ..ToonPartOptions::default() });
  	let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
  	let mut instance_list: Vec<ToonInstance> = (0..3).map(|index| ToonInstance { model_matrix: Matrix4::create_translation(index as f64 - 1.0, 0.0, 0.0), ..ToonInstance::default() }).collect();
  	instance_list[1].emissive_color = Some([1.0, 0.85, 0.3]);
  	instance_list[1].emissive_intensity = 0.35;
  	let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 2.0, 3.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  	renderer.begin_frame_with_matrices(gl, &view_matrix, &Matrix4::create_perspective(0.8, 1.0, 0.1, 30.0));
  	renderer.draw_mesh_instanced(gl, &rock_mesh, &instance_list, ToonDrawOptions::default());
  	renderer.end_frame(gl);
  	Ok(())
  }
  ```

- `pub fn draw_mesh_instance_buffer(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, instance_buffer: &ToonInstanceBuffer, instance_count: usize, options: ToonDrawOptions)` (method, since 0.4.0): Draw with a persistent instance buffer. (culls the whole buffer by its bounds, instance_count instances; when the layout has no matrix the vertex chunk decides the position and nothing is culled)
  - `gl` &crate::GlContext: GL context.
  - `mesh` &ToonMesh: Result of create_mesh.
  - `instance_buffer` &ToonInstanceBuffer: Result of create_instance_buffer.
  - `instance_count` usize: Number of instances to draw. (Clamped if more than the buffer holds)
  - `options` ToonDrawOptions: Same as draw_mesh. (the vertex chunk of the material reads the user attributes; with is_culled false nothing is culled)
- `pub fn draw_mesh_outline(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, model_matrix: &Matrix4, options: ToonDrawOptions)` (method, since 0.4.0): Draws only the outline of one model. (neither culled nor counted, not drawn if there is no shell, has_outline is false, or it is the shadow pass)
  - `gl` &crate::GlContext: GL context.
  - `mesh` &ToonMesh: Result of create_mesh.
  - `model_matrix` &Matrix4: Model matrix.
  - `options` ToonDrawOptions: Same as draw_mesh.
- `pub fn set_light(&mut self, sun_direction: [f64; 3], sun_color: [f64; 3], sky_color: [f64; 3], ground_color: [f64; 3])` (method, since 0.4.0): Sets the lighting. (sun direction, sun color, sky color, ground color, all linear colors 0 ~, may exceed 1 with HDR, default light set)
  - `sun_direction` [f64; 3]: Direction the sun shines. ([x, y, z], the way the light travels)
  - `sun_color` [f64; 3]: Linear color of the sun.
  - `sky_color` [f64; 3]: Linear color of the ambient light from above.
  - `ground_color` [f64; 3]: Linear color of the ambient light from below.
- `pub fn set_sun_direction(&mut self, sun_direction: [f64; 3])` (method, since 0.4.0): Sets the sun direction. (the direction light travels, toonlightset.rs header comment)
  - `sun_direction` [f64; 3]: Direction the light travels. ([x, y, z])
- `pub fn get_sun_direction(&self) -> [f64; 3]` (method, since 0.4.0): Returns the sun direction. (pass it as is to ShadowMap::update_light_matrix)
  - returns [f64; 3]: Direction the sun shines. ([x, y, z])
- `pub fn set_fill_light(&mut self, fill_direction: [f64; 3], fill_color: [f64; 3])` (method, since 0.4.0): Sets the fill light. (direction light travels and linear color)
  - `fill_direction` [f64; 3]: Direction the light travels. ([x, y, z])
  - `fill_color` [f64; 3]: Linear color. (0 means none)
- `pub fn set_rim_light(&mut self, rim_color: [f64; 3], rim_power: f64, rim_feather: f64, rim_light_mask: f64)` (method, since 0.4.0): Sets the rim light. (ToonLightSet::set_rim_light, linear color, power, softness 0 ~ 1, fraction kept only on the sunlit side 0 ~ 1)
  - `rim_color` [f64; 3]: Linear color to add.
  - `rim_power` f64: Power. (0 means none)
  - `rim_feather` f64: 0 hard rim ~ 1 soft rim.
  - `rim_light_mask` f64: 1 means only on the side that receives the sun.
- `pub fn set_specular(&mut self, specular_strength: f64, specular_exponent: f64, specular_feather: f64, specular_color: [f64; 3])` (method, since 0.4.0): Sets the specular highlight. (ToonLightSet::set_specular, strength, exponent, softness 0 ~ 1, linear color)
  - `specular_strength` f64: Strength. (0 means none)
  - `specular_exponent` f64: Blinn-Phong exponent.
  - `specular_feather` f64: 0 hard spot ~ 1 soft light.
  - `specular_color` [f64; 3]: Linear color.
- `pub fn set_point_lights(&mut self, point_light_list: &[ToonPointLight])` (method, since 0.4.0): Sets point lights and spotlights. (ToonLightSet::set_point_lights)
  - `point_light_list` &[ToonPointLight]: List of point lights and spotlights. (the form of ToonLightSet::set_point_lights)
- `pub fn set_point_light_limit(&mut self, point_light_limit: usize)` (method, since 0.4.0): Sets the limit on the number of point lights. (ToonLightSet::set_point_light_limit)
  - `point_light_limit` usize: Number of point lights to receive. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)
- `pub fn set_shade(&mut self, shade: ToonShade)` (method, since 0.4.0): Sets the three shades. (ToonLightSet::set_shade, base, 1st shade and 2nd shade of Unity Toon Shader)
  - `shade` ToonShade: Thresholds, softness and colors from the base to the 1st and 2nd shade. (ToonShade)
- `pub fn set_shade_ramp(&mut self, positions: &[f64], colors: &[[f64; 3]], feathers: &[f64], is_half_lambert: bool)` (method, since 0.4.0): Sets the shade ramp. (ToonLightSet::set_shade_ramp)
  - `positions` &[f64]: Position per cell.
  - `colors` &[[f64; 3]]: Linear multiplier per cell.
  - `feathers` &[f64]: Softness per cell.
  - `is_half_lambert` bool: Whether to count with half Lambert.
- `pub fn clear_shade_ramp(&mut self)` (method, since 0.4.0): Turns off the shade ramp. (smooth Lambert)
- `pub fn set_band_count(&mut self, band_count: u32)` (method, since 0.4.0): Sets uniform bands. (ToonLightSet::set_band_count, 0 for smooth)
  - `band_count` u32: Number of cells.
- `pub fn set_band_ramp(&mut self, thresholds: &[f64], values: &[f64], is_half_lambert: bool)` (method, since 0.4.0): Sets the gray band ramp. (ToonLightSet::set_band_ramp)
  - `thresholds` &[f64]: Ascending thresholds.
  - `values` &[f64]: Received amount per cell.
  - `is_half_lambert` bool: Whether to count with half Lambert.
- `pub fn set_ramp_texture(&mut self, ramp_texture: Option<GlTexture>, is_half_lambert: bool)` (method, since 0.4.0): Sets the ramp texture. (ToonLightSet::set_ramp_texture, None for bands)
  - `ramp_texture` Option<GlTexture>: Ramp texture built with create_texture, or None.
  - `is_half_lambert` bool: Whether to count with half Lambert.
- `pub fn set_light_model(&mut self, light_model: ToonLightModel)` (method, since 0.4.0): Sets the light model.
  - `light_model` ToonLightModel: Light model. (if is_energy_normalized is true, base color x light is divided by π)
- `pub fn set_outline_color(&mut self, outline_color: [f64; 4])` (method, since 0.4.0): Sets the outline color. (sRGB 0 ~ 1 and alpha)
  - `outline_color` [f64; 4]: [r, g, b, a] (sRGB 0 ~ 1 and alpha)
- `pub fn set_outline_distance_scale(&mut self, reference_distance: f64, minimum_scale: f64, maximum_scale: f64)` (method, since 0.4.0): Sets the distance multiplier of the shell outline. (the width is built at the reference distance and pushed thicker by that much when far to keep the screen width, the multiplier is between the smallest and largest, reference distance 0 turns it off)
  - Applied only with perspective cameras. The per-vertex distance to the camera / reference distance is multiplied into the width. (a similar screen width regardless of distance, like Guilty Gear Xrd)
  - `reference_distance` f64: Distance at which the built thickness is kept. (0 turns it off)
  - `minimum_scale` f64: Minimum scale.
  - `maximum_scale` f64: Maximum scale.
- `pub fn set_outline_fade_distance(&mut self, near_distance: f64, far_distance: f64)` (method, since 0.4.0): Sets the distance at which the shell outline fades when far. (Built width up to the near distance, 0 from the far distance, smoothstep in between, off if the far distance is not above the near distance, Nearest and Farthest Distance of the Unity Toon Shader)
  - `near_distance` f64: Distance at which the built thickness is kept.
  - `far_distance` f64: Distance at which the thickness becomes 0.
- `pub fn get_outline_fade_distance(&self) -> [f64; 2]` (method, since 0.4.0): Returns the distance at which the shell outline fades. ([near distance, far distance])
  - returns [f64; 2]: [near distance, far distance]
- `pub fn set_local_shadows(&mut self, shadow_atlas: Option<&ShadowAtlas>, strength: f64)` (method, since 0.4.0): Sets the point light and spotlight shadows to receive. (ShadowAtlas or None, strength 0 ~ 1, the atlas is the one built from the point light list of the default light set)
  - `shadow_atlas` Option<&ShadowAtlas>: ShadowAtlas or None.
  - `strength` f64: Shadow strength. (0 ~ 1)
- `pub fn set_light_color_usage(&mut self, light_color_usage: ToonLightColorUsage)` (method, since 0.4.0): Sets the light color usage. (ToonLightSet::set_light_color_usage)
  - `light_color_usage` ToonLightColorUsage: Whether each part uses the sun color. (ToonLightColorUsage)
- `pub fn set_light_intensity_limited(&mut self, is_limited: bool)` (method, since 0.4.0): Sets light intensity limiting. (ToonLightSet::set_light_intensity_limited, default true)
  - `is_limited` bool: If true, limits what each light gives to 1. (Default true)
- `pub fn set_shade_rim_light(&mut self, shade_rim_color: [f64; 3], shade_rim_power: f64)` (method, since 0.4.0): Sets the shade-side rim light. (ToonLightSet::set_shade_rim_light)
  - `shade_rim_color` [f64; 3]: Linear color to add.
  - `shade_rim_power` f64: Power. (0 means none)
- `pub fn get_outline_distance_scale(&self) -> [f64; 3]` (method, since 0.4.0): Returns the distance multiplier of the shell outline. ([reference distance, smallest multiplier, largest multiplier])
  - returns [f64; 3]: [reference distance, minimum scale, maximum scale]
- `pub fn set_hdr_output(&mut self, is_hdr_output: bool)` (method, since 0.4.0): Sets HDR output. (if true, outputs linear color without gamma, for drawing into the float render target of ToonPostProcess)
  - `is_hdr_output` bool: If true, outputs linear color without gamma.
- `pub fn set_shadow(&mut self, shadow_map: Option<&ShadowMap>, strength: f64)` (method, since 0.4.0): Sets the shadow to receive. (ShadowMap or None, strength 0 ~ 1, the original default strength is 0.6)
  - `shadow_map` Option<&ShadowMap>: ShadowMap to receive. (None means no shadows are received)
  - `strength` f64: Shadow strength 0 ~ 1.
- `pub fn get_frame_statistics(&self) -> ToonFrameStatistics` (method, since 0.4.0): This frame's drawn and culled counts.
  - returns ToonFrameStatistics: Counts of this frame. (draw_call_count, drawn_object_count, culled_object_count)
- `pub fn get_program(&self, material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, kind: ToonProgramKind) -> Option<&ShaderProgram>` (method, since 0.4.0): Returns the programs for a material and instance layout. (only built ones, the original getSolidProgram(material) family)
  - `material` Option<&ToonMaterial>: Material. (None means empty chunks)
  - `instance_layout` Option<&ToonInstanceLayout>: Instance layout. (None means none)
  - `kind` ToonProgramKind: Program kind. (body, outline, shadow depth)
  - returns Option<&ShaderProgram>: That program. (None if it has not been built yet or could not be built)
- `pub fn get_color_space(&self) -> ColorSpace` (method, since 0.4.0): Returns the color space. (original getColorSpace, fixed at creation, does not change)
  - returns ColorSpace: ColorSpace::Gamma or ColorSpace::Linear.

  Example: Build a linear color space renderer and a post process and screen outline with the same value

  ```rust
  use vanilla::{ColorSpace, ToonPostProcess, ToonPostProcessOptions, ToonRenderer, ToonRendererOptions, ToonScreenOutline, ToonScreenOutlineOptions};
  
  fn create_linear_set(gl: &vanilla::GlContext) -> Result<(), String> {
  	let renderer = ToonRenderer::new_with_options(gl, ToonRendererOptions { color_space: ColorSpace::Linear })?;
  	let post_process = ToonPostProcess::new_with_options(gl, 320, 180, ToonPostProcessOptions { color_space: renderer.get_color_space(), ..ToonPostProcessOptions::default() })?;
  	let screen_outline = ToonScreenOutline::new_with_options(gl, ToonScreenOutlineOptions { color_space: renderer.get_color_space() })?;
  	assert_eq!(post_process.get_color_space(), ColorSpace::Linear);
  	assert_eq!(screen_outline.get_color_space(), ColorSpace::Linear);
  	Ok(())
  }
  ```

- `pub fn set_ambient_occlusion_texture(&mut self, texture: Option<GlTexture>, direct_lighting_strength: f64)` (method, since 0.4.0): Sets the ambient occlusion texture. (original setAmbientOcclusionTexture, the result of ToonPostProcess::draw_ambient_occlusion or None, from the next begin_frame)
  - While the texture is set, bodies are drawn with the ambient occlusion body program (TOON_AMBIENT_OCCLUSION), which multiplies the visibility at the screen position into the ambient light (sky and ground light).
    By direct_lighting_strength it also multiplies the diffuse and specular of the sun, fill light and point lights by 1 - strength x (1 - visibility). (after the band is chosen, so band edges stay, Direct Lighting Strength of URP)
    Rim light, glow, matcap and angel ring stay as they are. Transparent things (alpha or tint alpha below 1) and surfaces whose depth differs from the texture (not in the line target) are not multiplied.
  - None goes back to the default body program, which does not read the texture. (a screen with it off is the same as one where it was never set)
  - Materials that use all 8 material textures are drawn without ambient occlusion on devices with 16 fragment shader units.
  - `texture` Option<GlTexture>: Ambient occlusion result texture. (r visibility with intensity applied, gba 24-bit depth, None turns it off)
  - `direct_lighting_strength` f64: Share applied to direct light. (clamped to 0 ~ 1, original default 0)
- `pub fn get_ambient_occlusion_texture(&self) -> Option<GlTexture>` (method, since 0.4.0): Returns the ambient occlusion texture. (original getAmbientOcclusionTexture)
  - returns Option<GlTexture>: The set texture. (None if not set)
- `pub fn get_ambient_occlusion_direct_lighting_strength(&self) -> f64` (method, since 0.4.0): Returns the share of ambient occlusion applied to direct light. (original getAmbientOcclusionDirectLightingStrength)
  - returns f64: The second argument of set_ambient_occlusion_texture. (0 ~ 1, 0 if not set)
- `pub fn get_solid_program(&self) -> &ShaderProgram` (method, since 0.4.0): Returns the body program. (default program)
  - returns &ShaderProgram: Body program.
- `pub fn get_outline_program(&self) -> &ShaderProgram` (method, since 0.4.0): Returns the outline program. (default program)
  - returns &ShaderProgram: Outline program.
- `pub fn get_depth_program(&self) -> &ShaderProgram` (method, since 0.4.0): Returns the shadow depth program. (default program)
  - returns &ShaderProgram: Shadow depth program.

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

Options for building a toon renderer. (original constructor options)

Example: Build a linear color space renderer

```rust
use vanilla::{ColorSpace, ToonRenderer, ToonRendererOptions};

fn create_linear_renderer(gl: &vanilla::GlContext) -> Result<ToonRenderer, String> {
	let renderer = ToonRenderer::new_with_options(gl, ToonRendererOptions { color_space: ColorSpace::Linear })?;
	assert_eq!(renderer.get_color_space(), ColorSpace::Linear);
	Ok(renderer)
}
```

- `pub color_space: ColorSpace` (field, since 0.4.0): Color space. (original colorSpace, default is the engine's color space EngineConfiguration::color_space, Gamma without an engine)
  - returns ColorSpace

## Functions and constants

- `pub const TOON_MAXIMUM_JOINTS: usize = crate::graphics3d::jointblock::JOINT_BLOCK_MAXIMUM` (field, since 0.4.0): Upper limit on the number of bones one model uses. (the size of the shader's uniform array)
  - returns usize
- `pub const TOON_INSTANCE_FLOAT_COUNT: usize = 20` (field, since 0.4.0): Number of values per instance. (matrix 16, tint 4)
  - The matrix is read as an affine 3x4. The four values of the bottom row (elements 3, 7, 11, 15) are the instance emission (sRGB r, g, b and linear intensity). (The 3x4 matrix form of Godot MultiMesh and Unity BatchRendererGroup)
    Storing Matrix4 elements as they are leaves the bottom row 0, 0, 0, 1, so there is no emission.
  - returns usize
- `pub const TOON_MAXIMUM_MATERIAL_TEXTURES: usize = 8` (field, since 0.4.0): Upper limit of textures a material can bind per draw. (Units 8 ~ 15)
  - returns usize
- `pub const TOON_ATTRIBUTE_LOCATIONS: [(&str, u32); 13]` (field, since 0.4.0): Attribute locations. (all programs use the same locations, instance layout user attributes start at 13)
  - returns [(&str, u32); 13]
- `pub fn compose_toon_program_sources(material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, is_ambient_occlusion: bool, color_space: ColorSpace, disabled_features: &[&str]) -> ToonProgramSources` (method, since 0.4.0): Builds the sources of the three programs from a material and instance layout. (the default program if both are None)
  
  # Panics
  Panics if disabled_features has an unknown name. (the original throws)
  - `material` Option<&ToonMaterial>: Material whose shader chunks are inserted. (None means empty chunks)
  - `instance_layout` Option<&ToonInstanceLayout>: Instance layout that declares the user attributes. (None means none)
  - `is_ambient_occlusion` bool: Whether to define TOON_AMBIENT_OCCLUSION in the body fragment shader and multiply the ambient occlusion texture into the ambient light. (original default false)
  - `color_space` ColorSpace: Color space. (original default is the engine's color space; with Linear every source gets #define VANILLA_COLOR_SPACE_LINEAR 1)
  - `disabled_features` &[&str]: Feature branches to remove from the body fragment shader at compile time. (any of baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit; none by default in the original; a removed branch is not drawn if a draw turns it on. The renderer finds the branches a draw does not use and passes them itself)
  - returns ToonProgramSources: Sources and attribute locations of the three programs. (ToonProgramSources)
- `pub fn read_instance_buffer_sphere(mesh: &ToonMesh, instance_buffer: &ToonInstanceBuffer) -> Option<[f64; 4]>` (method, since 0.4.0): World bounding sphere when a mesh is drawn with an instance buffer. (the buffer bounds plus the mesh bounding sphere at the largest scale, culling by it drops no pixels; the original readInstanceBufferSphere)
  - `mesh` &ToonMesh: Result of ToonRenderer::create_mesh.
  - `instance_buffer` &ToonInstanceBuffer: Result of create_instance_buffer.
  - returns Option<[f64; 4]>: [x, y, z, radius]. None when the layout has no matrix and the bounds are unknown.
- `pub fn is_sphere_in_frustum(frustum_planes: &[[f64; 4]; 6], sphere: &[f64; 4]) -> bool` (method, since 0.4.0): Whether a sphere is inside the frustum. (the six planes of extract_frustum_planes; the original isSphereInFrustum)
  - `frustum_planes` &[[f64; 4]; 6]: The result of extract_frustum_planes.
  - `sphere` &[f64; 4]: [x, y, z, radius].
  - returns bool: true when inside or touching the frustum.
- `pub fn extract_frustum_planes(matrix: &Matrix4) -> [[f64; 4]; 6]` (method, since 0.4.0): The six frustum planes from a view-projection matrix. (ax + by + cz + d >= 0 is inside, normalized)
  - `matrix` &Matrix4: View and projection matrix. (Projection x view)
  - returns [[f64; 4]; 6]: [a, b, c, d] of the six planes. (Left, right, bottom, top, near, far)
- `pub fn read_matrix_determinant(matrix: &Matrix4) -> f64` (method, since 0.4.0): Determinant of the model matrix's upper-left 3x3. (negative means a mirrored matrix, winding is flipped)
  - `matrix` &Matrix4: Model matrix.
  - returns f64: Determinant of the upper left 3x3. (Negative means a mirrored matrix)
- `pub fn read_frame_camera(matrix: &Matrix4) -> ToonFrameCamera` (method, since 0.4.0): Reads the camera from view and projection matrices. (eye position if perspective, view direction if orthographic, whether the matrix is mirrored)
  - Perspective: the eye is the point where clip x, y, w are all 0. (system of equations from rows 0, 1, 3)
  - Orthographic: xyz of row 3 is 0, so the eye is infinitely far. The view direction is the cross product of rows 0, 1, oriented toward increasing depth.
  - A normal projection (near plane < far plane) has a negative determinant in its upper-left 3x3. If positive, the view matrix is mirrored.
  - `matrix` &Matrix4: View and projection matrix.
  - returns ToonFrameCamera: Read camera. (position [x, y, z, w(1 perspective, 0 orthographic)], forward [x, y, z], is_mirrored)
- `pub fn read_view_rotation(view_projection_matrix: &Matrix4, forward: [f64; 3]) -> [f64; 9]` (method, since 0.4.0): Reads the 3x3 view rotation from the view-projection matrix. (column order, rows are right, up, back, for computing view-space normals for matcaps)
  - Right is row 0's xyz minus the view direction component. (for symmetric perspective, orthographic and projections moved to a screen rectangle alike)
  - `view_projection_matrix` &Matrix4: View and projection matrix.
  - `forward` [f64; 3]: View direction. (the forward of read_frame_camera)
  - returns [f64; 9]: The 9 numbers of a mat3. (Column order)
- `pub fn read_camera_roll(view_rotation: &[f32; 9], is_mirrored: bool) -> f64` (method, since 0.4.0): Reads the angle that undoes camera roll. (the same computation as the Unity Toon Shader angel ring Camera Rolling Stabilizer, original readCameraRoll)
  - roll is the angle between the camera right (row 0 of the view rotation) and the horizontal right axis, dir is -1 if the right's y is negative, and the returned angle is -(dir x roll).
  - Unity is left-handed so its horizontal right axis is cross(back, up), and the engine is right-handed so the same side is cross(forward, up). For a mirrored frame the axis is flipped. (the Unity Toon Shader mirrorFlag)
  - Looking straight up or down there is no horizontal axis, so it is 0.
  - `view_rotation` &[f32; 9]: The 9 values of a mat3. (result of read_view_rotation, column order)
  - `is_mirrored` bool: Whether the view matrix is mirrored. (the is_mirrored of read_frame_camera)
  - returns f64: Angle to rotate the angel ring UV around (0.5, 0.5). (Radians)
- `pub fn read_uv_data(uv_data: &[f32], uv1_data: Option<&[f32]>, vertex_count: usize) -> Vec<f32>` (method, since 0.4.0): Builds the UV vertex array. (UV 2 per point without a second UV, UV and second UV interleaved as 4 with one, vertexUv in the shader is a vec4, so if only 2 are uploaded zw is (0, 1))
  - `uv_data` &[f32]: UV. (2 per point)
  - `uv1_data` Option<&[f32]>: Second UV. (2 per point, None if none)
  - `vertex_count` usize: Number of points.
  - returns Vec<f32>: 2 or 4 per point.
- `pub fn read_outline_vertex_data(outline_vertex_data: &[f32], outline_base_data: &[f32]) -> Vec<f32>` (method, since 0.4.0): Builds the shell vertex array. (per point, base position 3 and push direction 3, the push direction is copy position - base position)
  - If there are no base positions or the length differs (a shell prebuilt in the GLB), the copy positions are used as the base and the push direction is 0. (the width multiplier is not applied)
  - `outline_vertex_data` &[f32]: Copy positions pushed by the built thickness. (3 each)
  - `outline_base_data` &[f32]: Base positions before pushing. (3 each, if the length differs the copied positions are used as the base)
  - returns Vec<f32>: 6 per point.
- `pub fn create_reflection_matrix(plane_point: [f64; 3], plane_normal: [f64; 3]) -> Matrix4` (method, since 0.4.0): Builds a reflection matrix across a plane. (a point on the plane and its normal, multiplied into the model or view matrix for a planar mirror)
  - Drawing with a reflected matrix flips the winding. ToonRenderer flips the front face itself if the model matrix determinant is negative. (can also be set with is_mirrored)
  - `plane_point` [f64; 3]: A point on the plane. ([x, y, z])
  - `plane_normal` [f64; 3]: Normal of the plane. ([x, y, z], length does not matter)
  - returns Matrix4: Matrix reflected across the plane.

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

Program kind of a draw. (third argument of on_before_draw)

- `Solid`: Body.
- `Outline`: Outline shell.
- `Depth`: Shadow depth.
