# graphics3d/toon/toonview3d (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/toon/toonview3d/

Component that draws toon 3D inside the node rectangle. (Inserts a 3D pass between the 2D node tree)

Example: Draw a toon 3D scene inside a node rectangle

```js
import { WorldNode, ToonView3D, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4, Vector3 } from "./vanilla.js";
const node = new WorldNode();
node.setContentSizeXY(320, 240);
const view = node.addComponent(ToonView3D);
view.getCamera().setPerspective(0.8, 0.1, 100);
view.getCamera().lookAt(Vector3.create(0, 1.5, 3), Vector3.create(0, 0.5, 0), Vector3.create(0, 1, 0));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 24, 16), Matrix4.createTranslation(0, 0.5, 0), "#f0b080");
const arrays = builder.readArrays();
const queue = new ToonDrawQueue();
let mesh = null;
view.setDrawCallback((renderer, camera) => {
	if (mesh === null) {
		mesh = renderer.createMesh(arrays);
	}
	queue.clear();
	queue.addMesh(mesh, Matrix4.createIdentity());
	queue.draw(renderer, camera);
});
```

## ToonView3D extends Component

Component that draws toon 3D inside the node rectangle. (Inserts a 3D pass between the 2D node tree)
- In draw: maps the node's content area (0, 0, content size) with the current transform to a rectangle in drawing buffer pixels (the bounding rectangle if rotated),
  draws the preceding 2D batch with Graphic.runExternalPass and clears depth, then sets the renderer's screen rectangle (setScreenRect) and calls the draw function.
  When done, releases the screen rectangle and restores the 2D state with restoreRenderState.
- A game may use WebGL directly through the same context before draw (a shadow map and the like). If it bound its own framebuffer it puts back the one it found, and it does not change the stencil. (Graphic.runExternalPass header)
- The renderer is built on the first draw. On devices that cannot build the shaders, it is not rebuilt and 2D is drawn with the fallback draw function (setFallbackDrawCallback).
  To share one renderer across multiple nodes, pass it in with setRenderer.
- The aspect ratio of the camera (getCamera) is matched to the rectangle's ratio on every draw. 2D markers over 3D points are computed with the same camera's projectToView.
- Depth clearing: inside a parent Mask's clip there is the Adreno 660 pitfall (Graphic.clearDepthBuffer header). The side that applies the clip
  calls clearDepthBuffer before beginClipRect, and this component is set with setDepthCleared(false).
- Draw function: (renderer, camera, screenRect, webGL2RenderingContext, output) => void. screenRect is the rectangle to draw in the current framebuffer (Rect, pixels, top-left origin).
  output is { outputFramebuffer, outputViewport }: the framebuffer bound now (null for the canvas) and the GL viewport inside it ([x, y, width, height], integers, bottom-left origin).
  Usually queue into ToonDrawQueue and call queue.draw(renderer, camera), or draw between renderer.beginFrameWithCamera and endFrame.
  When using ToonPostProcess, call renderer.clearScreenRect(), draw into a float render target, then give end the framebuffer and viewport of output.
  (so it lands in the right place regardless of render scale and opacity layers)

Example: Compute where to float a 2D marker above a 3D point

```js
import { WorldNode, ToonView3D, Rect, Vector3 } from "./vanilla.js";
const node = new WorldNode();
node.setContentSizeXY(400, 300);
const view = node.addComponent(ToonView3D);
const camera = view.getCamera();
camera.setPerspective(0.8, 0.1, 100);
camera.setAspectRatio(400 / 300);
camera.lookAt(Vector3.create(0, 2, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0));
const labelPosition = camera.projectToView(0, 1, 0, Rect.create(0, 0, 400, 300));
const isLabelShown = labelPosition.isInFront && labelPosition.x >= 0 && labelPosition.x <= 400;
```

- `constructor()` (constructor, since 0.4.0): Constructor.
- `setRenderScale(renderScale)` (method, since 0.4.0): Set the render scale. (only the 3D is drawn into a target at this scale and stretched on with linear filtering, the UI stays at device pixels. Same meaning as Unity URP renderScale and Unreal screen percentage)
  - At 1 (default) it draws straight to the screen as before. Otherwise it clears a target (the on-screen size of the content area x scale, with depth, multisampled with 4 samples when the canvas is anti-aliased)
    to transparent, draws into it and puts it on with source-over through the 2D drawing path. (it follows 2D clipping, and the 2D below shows where the 3D does not cover)
  - The target has its own depth, so reusing earlier 3D depth with setDepthCleared(false) only works at scale 1.
  - The draw function must output to the framebuffer and viewport of the output it receives to land in the right place at any scale. (ToonPostProcess.end and so on)
  - `renderScale` number: Scale. (0.05 to 4, 1 draws straight to the screen, 1 when not a number)

  Example: Draw only the 3D at half resolution

  ```js
  import { WorldNode, ToonView3D } from "./vanilla.js";
  const node = new WorldNode();
  node.setContentSizeXY(320, 240);
  const view = node.addComponent(ToonView3D);
  view.setRenderScale(0.5);
  const renderScale = view.getRenderScale();
  ```

- `getRenderScale()` (method, since 0.4.0): Return the render scale.
  - returns number: Scale. (1 draws straight to the screen)
- `setDrawCallback(drawCallback)` (method, since 0.4.0): Set the draw function. ((renderer, camera, screenRect, webGL2RenderingContext, output) => void, null draws nothing)
  - screenRect is the rect to draw in the current framebuffer (Rect, pixels, top-left origin, the same object rewritten on every draw).
  - output is { outputFramebuffer, outputViewport }. outputFramebuffer is the framebuffer bound now (null for the canvas),
    and outputViewport is the GL viewport inside it ([x, y, width, height], integers, bottom-left origin). (output_framebuffer and output_viewport of Rust ToonViewOutput)
    Anything output separately, such as ToonPostProcess.end, must use these two to land in the right place regardless of render scale and opacity layers.
  - `drawCallback` Function | null: (renderer, camera, screenRect, webGL2RenderingContext, output) => void. (does not draw if null)

  Example: Draw inside a node rectangle with HDR finishing

  ```js
  import { WorldNode, ToonView3D, ToonPostProcess } from "./vanilla.js";
  const node = new WorldNode();
  node.setContentSizeXY(320, 240);
  const view = node.addComponent(ToonView3D);
  let postProcess = null;
  view.setDrawCallback((renderer, camera, screenRect, webGL2RenderingContext, output) => {
  	if (postProcess === null) {
  		postProcess = new ToonPostProcess(webGL2RenderingContext, screenRect.size.x, screenRect.size.y);
  		renderer.setHdrOutput(postProcess.getUseFloatColor());
  	}
  	renderer.clearScreenRect();
  	postProcess.resize(screenRect.size.x, screenRect.size.y);
  	postProcess.begin([0.05, 0.05, 0.08]);
  	renderer.beginFrameWithCamera(camera);
  	renderer.endFrame();
  	postProcess.end(output.outputFramebuffer, output.outputViewport);
  });
  ```

- `setFallbackDrawCallback(fallbackDrawCallback)` (method, since 0.4.0): Sets the fallback draw function. (2D on devices where the renderer could not be built, (graphic, contentSize) => void)
  - `fallbackDrawCallback` Function | null: (graphic, contentSize) => void. Called on devices where the renderer could not be built. (Draws nothing if null)

  Example: Paint only the background on devices that cannot build the toon renderer

  ```js
  import { WorldNode, ToonView3D, Rect } from "./vanilla.js";
  const node = new WorldNode();
  node.setContentSizeXY(320, 240);
  const view = node.addComponent(ToonView3D);
  view.setFallbackDrawCallback((graphic, contentSize) => {
  	graphic.setFillColor("#203040");
  	graphic.drawRect(Rect.create(0, 0, contentSize.x, contentSize.y));
  });
  ```

- `setDepthCleared(isDepthCleared)` (method, since 0.4.0): Sets whether to clear depth before drawing. (default true)
  - `isDepthCleared` boolean: Whether to clear depth before drawing. (Inside a parent Mask clip, leave it false and let the clipping side clear)

  Example: Leave depth clearing to the clip

  ```js
  import { WorldNode, ToonView3D } from "./vanilla.js";
  const node = new WorldNode();
  node.setContentSizeXY(200, 200);
  const view = node.addComponent(ToonView3D);
  view.setDepthCleared(false);
  ```

- `isDepthCleared()` (method, since 0.4.0): Returns whether depth is cleared before drawing.
  - returns boolean: true if depth is cleared before drawing.
- `setRenderer(renderer)` (method, since 0.4.0): Sets the renderer. (When multiple nodes share one, if null it is built on the first draw)
  - `renderer` ToonRenderer | null: Renderer to share. (Built on the first draw if null)

  Example: Two nodes share one renderer

  ```js
  import { WorldNode, ToonView3D } from "./vanilla.js";
  const leftNode = new WorldNode();
  leftNode.setContentSizeXY(200, 200);
  const rightNode = new WorldNode();
  rightNode.setContentSizeXY(200, 200);
  const leftView = leftNode.addComponent(ToonView3D);
  const rightView = rightNode.addComponent(ToonView3D);
  leftView.setDrawCallback((renderer) => {
  	if (rightView.getRenderer() === null) {
  		rightView.setRenderer(renderer);
  	}
  });
  ```

- `getRenderer()` (method, since 0.4.0): Returns the renderer. (null if not yet built or could not be built)
  - returns ToonRenderer | null: Renderer. (null if not built yet or could not be built)
- `isRendererFailed()` (method, since 0.4.0): Whether the renderer could not be built.
  - returns boolean: true if the renderer could not be built. (Then the fallback draw function draws)
- `getCamera()` (method, since 0.4.0): Returns the camera.
  - returns Camera3D: The camera of this component. (Its aspect ratio is matched to the rectangle on every draw)
- `getScreenRect()` (method, since 0.4.0): Returns the screen rectangle of the last draw. (drawing buffer pixels)
  - returns Rect: Rectangle in drawing buffer pixels. (top-left origin, an empty rectangle before the first draw, a copy)
- `readRenderer(graphic)` (method, since 0.4.0): Reads the renderer. (Builds it the first time, null if it cannot be built, and it is not rebuilt)
  - `graphic` object: Graphic
  - returns ToonRenderer | null: Renderer. (null if it could not be built)
- `refreshScreenRect(graphic, contentSize)` (method, since 0.4.0): Content area to a rectangle in drawing buffer pixels. (Bounding rectangle of the four corners mapped with the current transform)
  - `graphic` object: Graphic. (Reads the current transform)
  - `contentSize` object: Vector2
- `draw(graphic)` (method, since 0.4.0): Draw.
  - `graphic` object: Graphic
- `detach(node)` (method, since 0.4.0): Detached from the node. (deletes the scale target, which is built again on first use after reattaching)
  - `node` object: The node detached from.
- `isDrawnInsideContent()` (method, since 0.4.0): Returns whether drawing is limited to the content area. (Clipped with scissor)
  - returns boolean: Always true.
