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

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

Toon HDR finishing. (ToonPostProcess of vanilla.js graphics3d/toon/toonpostprocess.js)
- Outputs linear color drawn to a float render target to the screen with bloom, exposure, tone mapping and gamma.
- Combines the engine's RenderTarget (half-float color, depth), BloomEffect (or MultiLevelBloomEffect) and FullscreenPass.
- Usage: after ToonRenderer::set_hdr_output(true)
  begin(gl, background linear color) → draw with ToonRenderer → end(gl, output framebuffer, viewport)
  end (resolves first if multisampled) computes bloom and draws the tone-mapped color into the output framebuffer (screen if None). To mix with 2D, call Graphic::restore_render_state after it.
- Constructor options: new_with_options(gl, width, height, ToonPostProcessOptions { sample_count, use_float_color, depth_bits, use_depth_texture }) (the options of the original constructor, new uses the default options, same as now: RGBA16F, depth 16, no multisampling)
  If sample_count is 2 or more, the scene is drawn to a multisampled (MSAA) renderbuffer and resolved to a texture before end. Reduced to a count the device supports. (get_sample_count, set_sample_count)
  depth_bits 24 means 24-bit depth. (scenes with a distant far plane) use_depth_texture keeps the scene depth as a texture. (used by set_lit_area)
- Color space: linear color is written to the scene render target. (ToonRenderer::set_hdr_output(true), ToonScreenOutline::set_hdr_output(true), ToonVfx colors are also treated as linear)
  Games that wrote gamma-encoded color g to the float target and converted back with g^2.2 in compositing should convert those values to linear beforehand. Colors become c^2.2, and a brightness multiplier k applied on the gamma side becomes linear k^2.2.
  (e.g. 1.37 is linear 2, 1.6 is 2.81, 2.08 is 5, brightness 1.6 with multiplier 1.6 gives (1.6 x 1.6)^2.2 = 7.9) Bloom threshold and knee are linear brightness.
- Devices that cannot use float targets: even with use_float_color (default true), if is_float_color_supported is false, RGBA8 targets are built. (get_use_float_color is false)
  That case and use_float_color: false take the LDR path. The scene is drawn in screen color (gamma-encoded color, ToonRenderer::set_hdr_output(false)), and compositing adds bloom without tone mapping and gamma and applies only color grading.
- Canvas antialias: because this post process draws into its own MSAA target (sample_count), a game that uses it builds with EngineConfiguration::antialias set to false.
  With true, the canvas itself is MSAA, so the pass that copies to the screen and the UI blend per sample and cost more. (Mac mini, 2560x1440 toon post process scene, GPU throughput 6.89 → 6.49 ms, with it off 6.81 → 5.22 ms, measured on the same scene in the original)
  Example: engine_configuration.antialias = false;
- Bloom: default is a half-resolution 9-tap Gaussian (BloomEffect, threshold 0.9 ~ 1.6, ping-pong targets RGBA8, RGBA16F with set_bloom_float_color).
  Giving set_bloom_levels(gl, level count, threshold, knee) a level count of 1 or more switches to MultiLevelBloomEffect (halves down then scales up with a tent filter while adding, targets at the same precision as the scene). 0 restores the default. Strength is applied to both by set_bloom.
- Tone mapping is the ACES approximation (Narkowicz). Exposure (set_exposure) is multiplied in before mapping, then sRGB gamma is applied.
- Color grading: after gamma, applies in order brightness (set_brightness, toward 1 inside the lit area set_lit_area), saturation, color tone (multiplies a color normalized to brightness 1), fog light (pulls dark areas toward that color), contrast, edge darkening. (set_color_grade, set_vignette)
  Defaults are brightness 1, saturation 1, contrast 1, color tone 0, fog light 0, edge 0, so there is no grading.
- Resolution scale: with set_resolution_scale(gl, scale), the scene target is built at output size x scale and scaled up to end's viewport (linear filtering) for output. (to render only 3D at a lower resolution while leaving UI at device pixels, default 1)
- Outputting inside a node rectangle: resize(rectangle width, height) → begin → draw (leave ToonRenderer's screen rectangle cleared) → end(None, [x, drawing buffer height - y - height, width, height]).
- Differences from the original: settings that rebuild GL objects (set_sample_count, set_resolution_scale, set_bloom_levels, set_bloom_float_color) take gl and return a Result.

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

Constructor options. (the original constructor options, the defaults are no multisampling / float target / depth 16 / no depth texture)

Example: Options with 4 samples and 24-bit depth

```rust
use vanilla::ToonPostProcessOptions;

let options = ToonPostProcessOptions { sample_count: 4, depth_bits: 24, ..ToonPostProcessOptions::default() };
assert!(options.use_float_color);
assert!(!options.use_depth_texture);
```

- `pub sample_count: i32` (field, since 0.4.0): Multisample count. (none below 2)
  - returns i32
- `pub use_float_color: bool` (field, since 0.4.0): Whether to use a float target. (built as false if the device cannot)
  - returns bool
- `pub depth_bits: i32` (field, since 0.4.0): Depth renderbuffer bit count. (16 or 24)
  - returns i32
- `pub use_depth_texture: bool` (field, since 0.4.0): Whether to keep the scene depth as a texture. (set_lit_area)
  - returns bool
- `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

## ToonPostProcess (struct)

Toon HDR post-processing. (see the header comment)

Example: Draw a toon scene into a float target and output it with bloom and tone mapping

```rust
use vanilla::{create_sphere_geometry, Camera3D, Matrix4, MeshBuilder, ToonDrawOptions, ToonPartOptions, ToonPostProcess, ToonPostProcessOptions, ToonRenderer, Vector3};

fn draw_glowing_ball(gl: &vanilla::GlContext, width: i32, height: i32) -> Result<(), String> {
	let mut post_process = ToonPostProcess::new_with_options(gl, width, height, ToonPostProcessOptions { sample_count: 4, ..ToonPostProcessOptions::default() })?;
	post_process.set_exposure(1.2);
	post_process.set_bloom(true, 0.8, 0.9, 1.6);
	let mut renderer = ToonRenderer::new(gl)?;
	renderer.set_hdr_output(post_process.get_use_float_color());
	let mut builder = MeshBuilder::new();
	builder.add_part(&create_sphere_geometry(0.5, 32, 20, std::f64::consts::PI), &Matrix4::create_identity(), "#ffd080", ToonPartOptions { glow: 2.0, ..ToonPartOptions::default() });
	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
	let mut camera = Camera3D::new();
	camera.set_perspective(0.8, 0.1, 100.0);
	camera.set_aspect_ratio(width as f64 / height as f64);
	camera.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));
	post_process.begin(gl, [0.02, 0.02, 0.04]);
	renderer.begin_frame_with_camera(gl, &camera);
	renderer.draw_mesh(gl, &mesh, &Matrix4::create_identity(), ToonDrawOptions::default());
	renderer.end_frame(gl);
	post_process.end(gl, None, [0, 0, width, height]);
	Ok(())
}
```

- `pub fn new(gl: &GlContext, width: i32, height: i32) -> Result<ToonPostProcess, String>` (constructor, since 0.4.0): Constructor. (screen pixel size, default options)
  - `gl` &GlContext: The same context as the toon renderer.
  - `width` i32: Output width. (Pixels)
  - `height` i32: Output height. (Pixels)
  - returns Result<ToonPostProcess, String>: New toon HDR finishing. Err(error message) if the scene render target, bloom or composite shader cannot be built.
- `pub fn new_with_options(gl: &GlContext, width: i32, height: i32, options: ToonPostProcessOptions) -> Result<ToonPostProcess, String>` (static, since 0.4.0): Creates with options. (the original new ToonPostProcess(gl, width, height, options))
  - `gl` &GlContext: The same context as the toon renderer.
  - `width` i32: Output width. (Pixels)
  - `height` i32: Output height. (Pixels)
  - `options` ToonPostProcessOptions: Creation options. (multisample count, float target, depth bits 16 or 24, depth texture, color space)
  - returns Result<ToonPostProcess, String>: New toon HDR finishing. Err(error message) if the scene render target, bloom or composite shader cannot be built.
- `pub fn is_float_color_supported(gl: &GlContext) -> bool` (static, since 0.4.0): Whether a float color buffer can be rendered to. (on the web EXT_color_buffer_float or EXT_color_buffer_half_float is required, and whether a framebuffer with a 1 x 1 RGBA16F attached is complete)
  - `gl` &GlContext: Context to check.
  - returns bool: true if it can draw into an RGBA16F target.
- `pub fn resize(&mut self, gl: &GlContext, width: i32, height: i32) -> Result<(), String>` (method, since 0.4.0): Resizes. (output size, the scene buffer is multiplied by the resolution scale, unchanged if the same)
  - `gl` &GlContext: GL context.
  - `width` i32: Output width. (Pixels)
  - `height` i32: Output height. (Pixels)
  - returns Result<(), String>: Ok if the buffers were fitted. Err(GL error text) if GL objects cannot be made while rebuilding.
- `pub fn set_resolution_scale(&mut self, gl: &GlContext, resolution_scale: f64) -> Result<(), String>` (method, since 0.4.0): Sets the resolution scale. (scene buffer = output size x scale, 0.05 ~ 4, default 1)
  - `gl` &GlContext: GL context.
  - `resolution_scale` f64: Scale of the scene target. (0.05 ~ 4)
  - returns Result<(), String>: Ok if the buffers were fitted. Err(GL error text) if GL objects cannot be made while rebuilding.
- `pub fn get_resolution_scale(&self) -> f64` (method, since 0.4.0): Returns the resolution scale.
  - returns f64: Scale of the scene target.
- `pub fn set_sample_count(&mut self, gl: &GlContext, sample_count: i32) -> Result<(), String>` (method, since 0.4.0): Sets the multisample sample count. (none if below 2, rebuilds the scene buffer when changed)
  - `gl` &GlContext: GL context.
  - `sample_count` i32: Multisample count. (no multisampling below 2)
  - returns Result<(), String>: Ok if the count is the same or the scene target was rebuilt. Err(GL error text, the previous target is kept) if the new target cannot be built.
- `pub fn get_sample_count(&self) -> i32` (method, since 0.4.0): Returns the multisample sample count actually in use. (0 means none)
  - returns i32: Sample count the scene target actually uses. (Reduced to what the device accepts, 0 means none)
- `pub fn get_use_float_color(&self) -> bool` (method, since 0.4.0): Returns whether the scene buffer is float. (false means the LDR path)
  - returns bool: true if the scene target is float. (passed straight to ToonRenderer::set_hdr_output)
- `pub fn begin(&self, gl: &GlContext, clear_color: [f64; 3])` (method, since 0.4.0): Begins drawing the scene. (binds the scene render target and clears it with the background color and depth, linear color on the HDR path, screen color on the LDR path)
  - `gl` &GlContext: GL context.
  - `clear_color` [f64; 3]: [r, g, b] background color. (Linear color on the HDR path, screen color on the LDR path)
- `pub fn end(&self, gl: &GlContext, output_framebuffer: Option<GlFramebuffer>, viewport: [i32; 4])` (method, since 0.4.0): Finishes. (resolve if multisampled → bloom → tone map into the output framebuffer, viewport is [x, y, width, height])
  - `gl` &GlContext: GL context.
  - `output_framebuffer` Option<GlFramebuffer>: Framebuffer to output to. (screen if None)
  - `viewport` [i32; 4]: [x, y, width, height] output area. (Drawing buffer pixels, bottom left is the origin)
- `pub fn set_exposure(&mut self, exposure: f64)` (method, since 0.4.0): Sets the exposure. (multiplied before tone mapping, 1 is the default)
  - `exposure` f64: Exposure multiplier. (0 or more, 1 is the default)
- `pub fn set_bloom(&mut self, is_bloom_enabled: bool, bloom_strength: f64, threshold_start: f64, threshold_end: f64)` (method, since 0.4.0): Sets the bloom. (enabled, intensity, start and end of the threshold that extracts bright areas, the threshold is used only by the default 9-tap bloom)
  - `is_bloom_enabled` bool: Whether to turn on bloom.
  - `bloom_strength` f64: Bloom strength. (Multiplier added to the scene color, default 0.6)
  - `threshold_start` f64: Linear brightness where bright areas start to be extracted. (Default 0.9)
  - `threshold_end` f64: Linear brightness where they are fully extracted. (Default 1.6)
- `pub fn set_bloom_levels(&mut self, gl: &GlContext, level_count: usize, threshold: f64, knee: f64) -> Result<(), String>` (method, since 0.4.0): Sets the number of bloom levels. (0 means the default 9-tap bloom, 1 or more means a multi-level bloom with that many levels, threshold and knee are the linear brightness of the multi-level bloom)
  - The multi-level bloom buffers have the same precision as the scene buffer. (RGBA16F on the HDR path)
  - `gl` &GlContext: GL context.
  - `level_count` usize: Number of levels. (0 returns to the default 9-tap bloom)
  - `threshold` f64: Threshold of the multi-level bloom. (Linear brightness)
  - `knee` f64: Width for passing the threshold softly. (Linear brightness)
  - returns Result<(), String>: Ok if changed. Err(error message) if the multi-level bloom shader or targets cannot be built.
- `pub fn get_bloom_level_count(&self) -> usize` (method, since 0.4.0): Returns the number of bloom levels. (0 means the default 9-tap bloom)
  - returns usize: Number of levels of the multi-level bloom. (0 means the default 9-tap bloom)
- `pub fn set_bloom_float_color(&mut self, gl: &GlContext, is_float_color: bool) -> Result<(), String>` (method, since 0.4.0): Makes the ping-pong buffers of the default 9-tap bloom float. (true means RGBA16F, the default false means RGBA8, ignored if the scene buffer is not float)
  - `gl` &GlContext: GL context.
  - `is_float_color` bool: RGBA16F if true, RGBA8 if false.
  - returns Result<(), String>: Ok if changed or already the same. Err(GL error text, the previous buffers are kept) if new buffers cannot be built.
- `pub fn set_brightness(&mut self, brightness: f64)` (method, since 0.4.0): Sets the brightness. (multiplied at the very start of color grading, 1 leaves it unchanged)
  - `brightness` f64: Brightness multiplier. (0 or more, 1 leaves it as is)
- `pub fn set_lit_area(&mut self, center: [f64; 3], inner_radius: f64, outer_radius: f64, inverse_view_projection_matrix: &Matrix4)` (method, since 0.4.0): Sets the lit spot. (within horizontal distance inner_radius of that spot the brightness is 1, beyond outer_radius it is the set_brightness brightness, smooth in between)
  - Reconstructs the world position of each pixel from the scene depth texture (option use_depth_texture) and the inverse of that frame's view and projection matrices. Ignored if there is no depth texture.
  - Give it again every frame when the camera moves. The background where nothing was drawn is computed as a position on the far plane.
  - `center` [f64; 3]: Position to light. ([x, y, z] world position, horizontal distance is measured with x and z)
  - `inner_radius` f64: Horizontal radius with brightness 1. (World length)
  - `outer_radius` f64: Horizontal radius outside which the brightness of set_brightness applies. (world length)
  - `inverse_view_projection_matrix` &Matrix4: Inverse of this frame's view and projection.
- `pub fn clear_lit_area(&mut self)` (method, since 0.4.0): Clears the lit spot.
- `pub fn set_color_grade(&mut self, saturation: f64, contrast: f64, tone_color: [f64; 3], tone_amount: f64, haze_color: [f64; 3], haze_amount: f64)` (method, since 0.4.0): Sets the color grading. (saturation and contrast leave it unchanged at 1, tint and fog color are sRGB [r, g, b] 0 ~ 1 with a mix amount 0 ~ 1)
  - The tint color is normalized to luminance (Rec. 709) 1 before multiplying, so brightness stays the same and only the hue is tinted.
  - The fog color lifts darker areas more toward that color. (amount x (1 - luminance))
  - `saturation` f64: Saturation. (1 leaves it as is, 0 is grayscale)
  - `contrast` f64: Contrast. (1 leaves it as is)
  - `tone_color` [f64; 3]: [r, g, b] tint color. (sRGB 0 ~ 1, multiplied after normalizing its brightness to 1)
  - `tone_amount` f64: Amount of tint to mix. (0 ~ 1)
  - `haze_color` [f64; 3]: [r, g, b] haze color. (sRGB 0 ~ 1)
  - `haze_amount` f64: Amount of haze to mix. (0 ~ 1, stronger in darker areas)
- `pub fn set_vignette(&mut self, vignette_strength: f64)` (method, since 0.4.0): Sets the vignette. (0 is none, 1 makes the corners black)
  - `vignette_strength` f64: Strength of darkening the edges. (0 is none, 1 makes the corners black)
- `pub fn get_scene_render_target(&self) -> &RenderTarget` (method, since 0.4.0): Scene render target. (for inserting other post-processing)
  - returns &RenderTarget: Render target the scene is drawn into. (May be rebuilt if the resolution scale or sample count changes)
- `pub fn destroy(&mut self, gl: &GlContext)` (method, since 0.4.0): Disposes.
  - `gl` &GlContext: GL context.
- `pub fn get_color_space(&self) -> ColorSpace` (method, since 0.4.0): Returns the color space. (original getColorSpace, fixed at creation, selects the curve that produces the screen color after tone mapping)
  - returns ColorSpace: ColorSpace::Gamma or ColorSpace::Linear.
- `pub fn set_ambient_occlusion(&mut self, is_enabled: bool, intensity: f64, radius: f64, resolution_scale: f64, direct_lighting_strength: f64)` (method, since 0.4.0): Sets ambient occlusion (screen-space AO). (original setAmbientOcclusion, off by default; when on, draw_ambient_occlusion computes it and the body shader multiplies it into the ambient light)
  - `is_enabled` bool: Whether to turn it on.
  - `intensity` f64: Intensity. (clamped to 0 ~ 1, original default 0.5)
  - `radius` f64: Radius to search for occluders. (world length, at least 0.0001, original default 0.5)
  - `resolution_scale` f64: Resolution scale of the computed target. (clamped to 0.25 ~ 1, original default 0.5)
  - `direct_lighting_strength` f64: Share applied to direct light (diffuse and specular of the sun, fill light and point lights). (clamped to 0 ~ 1, original default 0 means ambient light only)

  Example: Turn on ambient occlusion in a scene without outlines and hand it to the draw queue

  ```rust
  use vanilla::{Matrix4, ToonDrawOptions, ToonDrawQueue, ToonMesh, ToonPostProcess, ToonRenderer};
  
  fn draw_room(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, post_process: &mut ToonPostProcess, room_mesh: &ToonMesh, view_matrix: &Matrix4, projection_matrix: &Matrix4) {
  	post_process.set_ambient_occlusion(true, 0.5, 0.5, 0.5, 0.5);
  	assert_eq!(post_process.get_ambient_occlusion_direct_lighting_strength(), 0.5);
  	post_process.begin(gl, [0.1, 0.1, 0.12]);
  	{
  		let mut queue = ToonDrawQueue::new();
  		queue.set_post_process(Some(&mut *post_process));
  		queue.add_mesh(room_mesh, &Matrix4::create_identity(), ToonDrawOptions::default());
  		queue.draw_with_matrices(gl, renderer, view_matrix, projection_matrix);
  	}
  	post_process.end(gl, None, [0, 0, 640, 360]);
  }
  ```

- `pub fn get_ambient_occlusion(&self) -> ToonAmbientOcclusion` (method, since 0.4.0): Returns the ambient occlusion settings. (original getAmbientOcclusion)
  - returns ToonAmbientOcclusion: Settings. (ToonAmbientOcclusion, a copy)
- `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, the fifth argument of set_ambient_occlusion, the draw queue sets it on the renderer)
  - returns f64: 0 ~ 1.
- `pub fn is_ambient_occlusion_enabled(&self) -> bool` (method, since 0.4.0): Whether ambient occlusion is on. (original isAmbientOcclusionEnabled)
  - returns bool: true if turned on with set_ambient_occlusion.
- `pub fn get_ambient_occlusion_prepass(&mut self, gl: &GlContext) -> Result<&mut ToonScreenOutline, String>` (method, since 0.4.0): Returns the prepass for scenes without outlines. (original getAmbientOcclusionPrepass, a screen outline with line width 0, built on the first call)
  - `gl` &GlContext: The same context as the toon renderer.
  - returns Result<&mut ToonScreenOutline, String>: A screen outline that draws only the line target. (draw with begin_line_ids, draw_mesh, end_line_ids and pass get_line_target to draw_ambient_occlusion) Err (error text) if it cannot be built.
- `pub fn draw_ambient_occlusion_with_prepass(&mut self, gl: &GlContext, view_matrix: &Matrix4, projection_matrix: &Matrix4) -> Option<GlTexture>` (method, since 0.4.0): Computes ambient occlusion with the prepass line target. (the same as passing the line target of get_ambient_occlusion_prepass to draw_ambient_occlusion, None if there is no prepass or it is off)
  - `gl` &GlContext: GL context.
  - `view_matrix` &Matrix4: View matrix the line target was drawn with.
  - `projection_matrix` &Matrix4: Projection matrix the line target was drawn with.
  - returns Option<GlTexture>: Result texture. (same as draw_ambient_occlusion)
- `pub fn draw_ambient_occlusion(&mut self, gl: &GlContext, line_target: &ToonLineTarget, view_matrix: &Matrix4, projection_matrix: &Matrix4) -> Option<GlTexture>` (method, since 0.4.0): Computes ambient occlusion. (original drawAmbientOcclusion, half-resolution GTAO → horizontal blur → vertical blur with upsampling from the normals and depth of the line target, None when off)
  - The result texture is RGBA8 at the size of the line target. (r is the visibility with intensity applied, gba the 24-bit depth) Pass it to ToonRenderer::set_ambient_occlusion_texture.
  - Restores the framebuffer, viewport, program, vertex array, active texture unit, depth test, blending, scissor and face culling.
  - `gl` &GlContext: GL context.
  - `line_target` &ToonLineTarget: This frame's line target. (ToonScreenOutline::get_line_target)
  - `view_matrix` &Matrix4: View matrix the line target was drawn with.
  - `projection_matrix` &Matrix4: Projection matrix the line target was drawn with.
  - returns Option<GlTexture>: Result texture. None when off or when the targets or shaders cannot be built.
- `pub fn get_ambient_occlusion_texture(&self) -> Option<GlTexture>` (method, since 0.4.0): Returns the ambient occlusion result texture. (original getAmbientOcclusionTexture, None if not computed yet or off)
  - returns Option<GlTexture>: Result texture. (RGBA8, r visibility, gba depth)

## ToonAmbientOcclusion (struct) (Clone, Copy, Debug, PartialEq, Default)

Ambient occlusion settings. (the { isEnabled, intensity, radius, resolutionScale, directLightingStrength } of the original getAmbientOcclusion)

Example: Read the defaults

```rust
use vanilla::ToonAmbientOcclusion;

let ambient_occlusion = ToonAmbientOcclusion::default();
assert!(!ambient_occlusion.is_enabled);
assert_eq!((ambient_occlusion.intensity, ambient_occlusion.radius, ambient_occlusion.resolution_scale, ambient_occlusion.direct_lighting_strength), (0.5, 0.5, 0.5, 0.0));
```

- `pub is_enabled: bool` (field, since 0.4.0): Whether it is on.
  - returns bool
- `pub intensity: f64` (field, since 0.4.0): Intensity. (0 ~ 1, 0 does not darken)
  - returns f64
- `pub radius: f64` (field, since 0.4.0): Radius to search for occluders. (world length)
  - returns f64
- `pub resolution_scale: f64` (field, since 0.4.0): Resolution scale of the computed target. (0.25 ~ 1, multiplied by the line target size)
  - returns f64
- `pub direct_lighting_strength: f64` (field, since 0.4.0): Share applied to direct light. (0 ~ 1, Direct Lighting Strength of URP)
  - returns f64
