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

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

Toon screen-space outline. (Draws normals, line IDs and depth into the line target, picks lines at the boundaries between direct neighbors, looks at the surrounding cells directly for thin lines and widens thick lines with jump flooding, then computes coverage from distance and blends)

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

```js
import { ToonRenderer, ToonScreenOutline, ToonOutlineWidthUnit, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const outline = new ToonScreenOutline(webGL2RenderingContext);
outline.setWidth(2, ToonOutlineWidthUnit.pixel);
outline.setCrease(50, 1, 0.8);
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#e0c8a8", { hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
const viewMatrix = Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0));
const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
const modelMatrix = Matrix4.createIdentity();
if (outline.beginLineIds(viewMatrix, projectionMatrix)) {
	outline.drawMesh(mesh, modelMatrix, 1);
	outline.endLineIds();
}
renderer.beginFrameWithMatrices(viewMatrix, projectionMatrix);
renderer.drawMesh(mesh, modelMatrix);
renderer.endFrame();
outline.drawOutline();
```

## ToonScreenOutline

Toon screen-space outline. (Draws normals, line IDs and depth into the line target, picks lines at the boundaries between direct neighbors, looks at the surrounding cells directly for thin lines and widens thick lines with jump flooding, then computes coverage from distance and blends)
- Line target: draws the result of ToonRenderer's createMesh once more with the same matrices and writes the normal (octahedral encoding), line ID (14 bits), flags (whether the silhouette line and crease line are on) and depth.
- Picking: each boundary between a pixel and its four direct neighbors is looked at once. A line stands not on a pixel but in the middle of the boundary between pixels. (The same boundary is not drawn twice)
  A silhouette line is where it touches empty space (the silhouette), where it touches a different ID, or where, even with the same ID, the occluding pixel is farther than the depth threshold plus the error margin from the occluded pixel's tangent plane (occluded silhouette).
  A crease line is where two neighboring normals within the same ID open wider than the crease angle. Since only normals one pixel apart are compared, no band appears around the silhouette of round surfaces or on slanted surfaces.
  Depth is compared as tangent plane distance, so no false lines appear on a floor seen at a grazing angle. The measured error (8-bit normal angular error x the distance between the two positions, one pixel x the sine at a crease, one 24-bit depth step) x the factor is added to the threshold, so distant things mean the same, and a low parallel step is caught even when it is lower than one pixel.
- Thin lines (up to a width of about 3.24 pixels): in the same order as the seed pick, picks each pixel's first boundary side (one R8UI byte), and the blend looks at the seeds of the 3 x 3 surrounding pixels in the same order as the last jump flooding step to measure the distance to the nearest one.
  The full-screen passes are one side target and one blend. (A fraction of the passes and target bandwidth of the thick-line path on mobile tile GPUs)
- Widening (thick lines): the distance to the boundary segments is spread with jump flooding. The step count is log2 regardless of thickness, and silhouette and crease lines are spread separately to give separate thicknesses.
- Blending: each pixel of the drawing area is covered by clamp(thickness / 2 - distance + 0.5, 0, 1) from the distance to the nearest boundary. (Soft edges, and no stairs or dotted lines)
- Per model: if hasScreenOutline of drawMesh is false, that model produces no line and only hides lines behind it. If hasCreaseLine is false, only crease lines are turned off.
- Per-ID color: setLineColor gives a line color per ID. (The Unreal Custom Stencil form; a line where two IDs touch takes the color of the nearer ID, and IDs not in the table, or an empty table, keep the setColor color)
- Thickness: the thickness of setWidth and setCrease is the thickness of one line. (Half on each side of the boundary) The unit is ToonOutlineWidthUnit, and it does not go below one pixel.
- Depth: orthographic and perspective are told apart by the projection matrix, and depth is unpacked into view-space position for comparison. (Projections whose clip x and y were moved, like a screen rectangle, also work)
- Value: setResolutionScale shrinks every target before the blend (the line target, the mask, the seeds, the widening targets). (At the default 1 it is the drawing area as is; below 1 a thin line computes one coverage target at the line-target resolution and blends it with one bilinear read)
- Instances: drawMeshInstanced culls the instance array and uploads it then. drawMeshInstanceBuffer shares the ToonRenderer.createInstanceBuffer buffer with the body and does not upload it again.
  The ID of each instance in the buffer is read from the layout's instanceLineId slot. (The common ID if there is none)
- Use: every frame beginLineIds(view, projection) → drawMesh / drawMeshInstanced / drawMeshInstanceBuffer → endLineIds() (computes seeds and widening) → draw the toon bodies → drawOutline().
  beginLineIds notes the current viewport as the drawing area and builds the line target to fit its size. endLineIds and drawOutline restore the framebuffer, viewport and state.
  If handed over with ToonDrawQueue.setScreenOutline, the draw queue does this sequence by itself. (When inserted between engine 2D drawing, call Graphic.flushBatch before it)

Example: Only a thick silhouette without crease lines

```js
import { ToonScreenOutline, ToonOutlineWidthUnit } from "./vanilla.js";
const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
outline.setColor([0.1, 0.08, 0.12, 1]);
outline.setWidth(3, ToonOutlineWidthUnit.pixel);
outline.setCrease(180);
outline.setResolutionScale(0.5);
```

- `constructor(webGL2RenderingContext, options = null)` (constructor, since 0.4.0): Constructor. (Builds the nine programs and an empty vertex array; the line target is built at the first beginLineIds)
  - `webGL2RenderingContext` WebGL2RenderingContext: The same context as the toon renderer.
  - `options` object | null: { colorSpace (ColorSpace, default is the engine's color space, the same value as ToonRenderer) }
- `static readProgramSources(colorSpace = readEngineColorSpace())` (static, since 0.4.0): Returns the shader sources. (For prelinking with ShaderWarmer)
  - `colorSpace` string: Color space. (ColorSpace, default is the engine's color space, give the same value the ToonScreenOutline is built with)
  - returns Array<object>: Nine { vertexShader, fragmentShader, attributeLocationTable }. (ID, seed, gather, widening, blending, thin-line seed side target, thin-line blending, thin-line coverage on a reduced target, coverage target blending)

  Example: Add the shaders to the list to link in advance

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const sources = ToonScreenOutline.readProgramSources();
  const vertexShaders = sources.map((source) => source.vertexShader);
  ```

- `setColor(color)` (method, since 0.4.0): Set the line color. (sRGB 0 ~ 1 and alpha, shared by silhouette and crease lines)
  - `color` Array<number>: sRGB of [r, g, b, a]. (1 if a is omitted)
- `setLineColor(lineId, color)` (method, since 0.4.0): Set the line color per ID. (Silhouette and crease lines where a model with that ID is in front get this color; IDs not in the table keep the setColor color)
  - Like Unreal's Custom Stencil post-process outline, the color is picked by the ID already in the line target. For highlighting a chosen model or giving each team a different color.
  - The table is a 128 x 128 lookup texture covering every line ID (1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID). There is no limit on how many IDs are set, and it is read once per pixel.
  - A line where two IDs touch takes the color of the front ID (closer to the camera). Colors are stored as 8-bit sRGB, and alpha 0 is stored as 1/255. (To tell it apart from not being in the table; it is just as invisible)
  - `lineId` number: 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID. (The ID given to drawMesh and drawMeshInstanced; does nothing when out of range)
  - `color` Array<number>: [r, g, b, a] in sRGB 0 ~ 1. (1 if a is omitted)

  Example: Make only the line of the pointed rock yellow

  ```js
  import { ToonRenderer, ToonScreenOutline, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const outline = new ToonScreenOutline(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#a89880", { hasOutline: false });
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instances = [0, 1, 2].map((index) => ({ modelMatrix: Matrix4.createTranslation(index * 0.7, 0, 0), lineId: 10 + index }));
  outline.setLineColor(11, [1, 0.85, 0.2, 1]);
  const viewMatrix = Matrix4.createLookAt(Vector3.create(0.7, 2, 3), Vector3.create(0.7, 0, 0), Vector3.create(0, 1, 0));
  const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
  if (outline.beginLineIds(viewMatrix, projectionMatrix)) {
  	outline.drawMeshInstanced(rockMesh, instances, 10);
  	outline.endLineIds();
  }
  renderer.beginFrameWithMatrices(viewMatrix, projectionMatrix);
  renderer.drawMeshInstanced(rockMesh, instances);
  renderer.endFrame();
  outline.drawOutline();
  ```

- `removeLineColor(lineId)` (method, since 0.4.0): Remove one ID from the color table. (Lines of that ID go back to the setColor color)
  - `lineId` number: The ID given to setLineColor.
- `clearLineColors()` (method, since 0.4.0): Clear the color table. (All lines go back to the setColor color)

  Example: Set the IDs to highlight again every frame

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  outline.clearLineColors();
  outline.setLineColor(3, [1, 1, 1, 1]);
  outline.setLineColor(7, [1, 0.3, 0.2, 1]);
  const count = outline.getLineColorCount();
  ```

- `getLineColorCount()` (method, since 0.4.0): Return the number of IDs in the color table.
  - returns number: The number of IDs set with setLineColor and not removed.
- `setWidth(width, unit = ToonOutlineWidthUnit.pixel)` (method, since 0.4.0): Set the silhouette line thickness. (Lines at the silhouette and where a different ID touches, the thickness of one line rather than a radius, 0 draws none)
  - The crease line thickness is counted in this unit too.
  - `width` number: Thickness of one line. (Half on each side of the boundary)
  - `unit` string: ToonOutlineWidthUnit. (Default pixel)
- `setCrease(angleDegrees, width = 1, opacity = 1)` (method, since 0.4.0): Set crease lines. (A line where neighboring faces within the same ID bend more than this angle (degrees), thickness in the unit of setWidth, opacity 0 ~ 1)
  - `angleDegrees` number: Crease angle. (180 draws no crease lines)
  - `width` number: Thickness of one crease line. (Default 1, 0 draws none)
  - `opacity` number: Opacity of crease lines. (Default 1, multiplied into the alpha of the line color)

  Example: Leave small faces and make only big edges faint

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  outline.setCrease(75, 1.5, 0.6);
  ```

- `setFocusDistance(focusDistance)` (method, since 0.4.0): Sets the focal distance. (Distance at which world width is converted to pixels for a perspective camera, usually from the camera to the look-at point, 0 uses the average distance of the drawn models)
  - `focusDistance` number: Distance from the camera. (World length)
- `setDepthThreshold(depthThreshold)` (method, since 0.4.0): Set the depth threshold. (If, of two neighboring pixels with the same ID, the occluding one is farther than this from the occluded one's tangent plane, an occluded silhouette is drawn, world length)
  - depthThreshold is a distance perpendicular to the face, and a pixel margin is added to it. (The setDepthMargin factor x the measured error, the error follows the pixel size and the slant of the face)
  - Match it to the scale of the scene. (0.02 ~ 0.1 for a human-sized scene, 0 separates by the error margin alone)
  - `depthThreshold` number: Tangent plane distance threshold. (World length, perpendicular to the face, 0 or more)

  Example: Drawing even low steps as silhouettes

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  outline.setDepthThreshold(0.01);
  console.log(outline.getDepthThreshold());
  ```

- `getDepthThreshold()` (method, since 0.4.0): Returns the depth threshold. (World length, perpendicular to the face)
  - returns number: Tangent plane distance threshold. (World length)

  Example: Reading the default depth threshold

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  console.log(outline.getDepthThreshold()); // 0.05
  ```

- `setDepthMargin(depthMargin)` (method, since 0.4.0): Set the depth margin factor. (How many times the measured error the pixel margin added to the depth threshold is, default 2)
  - The error of the tangent-plane distance that appears even on connected surfaces is measured per pixel: the angular error of the 8-bit octahedral normal (0.0165 rad) x the distance between the two pixel positions (longer the more slanted the face), one pixel x the sine of the angle between the two normals for two pixels on either side of a crease, and one step of the 24-bit depth.
  - A low step between two parallel faces has no crease term, so it is caught even when it is lower than one pixel. On models that build round surfaces from coarse polygons, where the interpolated normal strays far from the face, lowering the depth threshold a lot produces stray lines, so raise the factor then.
  - 0 separates by the depth threshold alone.
  - `depthMargin` number: Factor to multiply the measured error by. (0 or more)

  Example: Reducing the margin to catch more low steps

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  outline.setDepthThreshold(0.02);
  outline.setDepthMargin(1);
  console.log(outline.getDepthMargin()); // 1
  ```

- `getDepthMargin()` (method, since 0.4.0): Returns the depth margin factor.
  - returns number: Factor to multiply the measured error by.

  Example: Reading the default depth margin factor

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
  console.log(outline.getDepthMargin()); // 2
  ```

- `setResolutionScale(resolutionScale)` (method, since 0.4.0): Set the resolution fraction of the line target. (Fraction of the drawing area 0.25 ~ 1, default 1, lowered on the light path for phones and tablets)
  - As the name says, every target before the blend (the line target = normals, IDs and depth, the mask, the seeds, the widening targets) is built at drawing area x fraction. The line target is drawn once more at that smaller resolution, so the cost falls by the square of the fraction.
    The default 1 is the same size as the drawing area, so the screen is byte for byte the same.
  - Below 1, a thin line (width x fraction up to about 3.24 line-target pixels) computes its coverage (strength times the ID color, RGBA8) once at the line-target resolution, and the final blend reads it once with bilinear filtering. (Nine reads become one)
    A thick line floods at the line-target resolution and measures the distance in drawing area pixels when blending. At any scale the line width (setWidth) is in drawing area pixels, and the smaller the fraction the softer the edges.
  - The lineTexture and depthTexture of getLineTarget() are drawing area x fraction in size. (The lineTexture contract of the miner stays: RGBA8, the ID in b and the low 6 bits of a, flags in the top 2 bits of a, and width 0 draws only the line target; only the resolution may differ from the drawing area)
  - To match 1.5 pixels per CSS pixel, pass 1.5 / (buffer pixels per CSS pixel). Since the engine resolution setting may bundle the buffer and differ from devicePixelRatio, count it as the canvas width / clientWidth.
  - `resolutionScale` number: 0.25 ~ 1. (1 keeps the drawing area resolution)

  Example: Match 1.5 line-target pixels per CSS pixel

  ```js
  import { ToonScreenOutline } from "./vanilla.js";
  const canvas = document.createElement("canvas");
  canvas.width = 750;
  canvas.height = 990;
  canvas.style.width = "375px";
  const outline = new ToonScreenOutline(canvas.getContext("webgl2"));
  const bufferPixelPerCssPixel = canvas.width / 375;
  outline.setResolutionScale(1.5 / bufferPixelPerCssPixel);
  ```

- `setHdrOutput(isHdrOutput)` (method, since 0.4.0): Sets HDR output. (true converts the line color to linear before blending, match with ToonRenderer.setHdrOutput)
  - `isHdrOutput` boolean: If true, the line color is converted to linear before blending.
- `getColorSpace()` (method, since 0.4.0): Returns the color space. (Set at construction, the curve that converts line color to linear for HDR output, pow 2.2 for gamma, the sRGB standard curve for linear)
  - returns string: ColorSpace.gamma or ColorSpace.linear.

  Example: Screen outline built with the same color space as the renderer

  ```js
  import { ToonRenderer, ToonScreenOutline, ColorSpace } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const screenOutline = new ToonScreenOutline(webGL2RenderingContext, { colorSpace: renderer.getColorSpace() });
  if (screenOutline.getColorSpace() !== ColorSpace.gamma) {
  	throw new Error("default color space is not gamma");
  }
  ```

- `getLineWidths()` (method, since 0.4.0): Return this frame's line thickness. (Drawing area pixels of [silhouette line, crease line], decided after endLineIds)
  - returns Array<number>: [silhouette line thickness, crease line thickness]. (0 if not drawn)
- `getLineTarget()` (method, since 0.4.0): Return the line target. (null if none)
  - returns object | null: { lineTexture (normal and ID RGBA8), depthTexture (depth 24), edgeMaskTexture (thin-line seed side target R8UI, low 3 bits contour and next 3 bits crease first edge side, 0 none, 1 right, 2 left, 3 up, 4 down), seedTexture (seeds at the line-target resolution RGBA16UI, null until a thick line is drawn), jumpFloodTextures (two widening targets RGBA16UI, empty until a thick line is drawn), jumpFloodIndex (the side that finished widening, -1 when jump flooding did not run), coverageTexture (coverage of a thin line when the line target is reduced, RGBA8 premultiplied color, null until a reduced thin line is drawn), outlinePath (this frame's path "none", "thin", "thinScaled", "jumpFlood"), width, height (line-target resolution, drawing area x the fraction of setResolutionScale), jumpFloodWidth, jumpFloodHeight (same as the line target) }
- `beginLineIds(viewMatrix, projectionMatrix)` (method, since 0.4.0): Begins drawing IDs. (Records the current viewport as the drawing area, binds and clears the line target)
  - `viewMatrix` Matrix4: View matrix.
  - `projectionMatrix` Matrix4: Projection matrix. (Perspective or orthographic)
  - returns boolean: false if the line target could not be built. (drawMesh then does nothing)
- `drawMesh(mesh, modelMatrix, lineId, options = {})` (method, since 0.4.0): Draws IDs for one model. (Same matrices and pose as ToonRenderer.drawMesh, skipped if off-screen)
  - `mesh` object | null: Result of ToonRenderer.createMesh.
  - `modelMatrix` Matrix4: Model matrix.
  - `lineId` number: 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID. (0 is empty space and not used, no line where the same IDs touch)
  - `options` object: { jointMatrices Float32Array, isCulled (default true), indexStart, indexCount (only part of the body index buffer), isMirrored (from the determinant if not given), hasScreenOutline (default true, false only hides without producing lines), hasCreaseLine (default true) }

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

  ```js
  import { ToonRenderer, ToonScreenOutline, MeshBuilder, createBoxGeometry, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const outline = new ToonScreenOutline(webGL2RenderingContext);
  const floorBuilder = new MeshBuilder();
  floorBuilder.addPart(createBoxGeometry(6, 0.2, 6), Matrix4.createTranslation(0, -0.1, 0), "#506070", { hasOutline: false });
  const floorMesh = renderer.createMesh(floorBuilder.readArrays());
  const crystalBuilder = new MeshBuilder();
  crystalBuilder.addPart(createOctahedronGeometry(0.5), Matrix4.createTranslation(0, 0.5, 0), "#90d0ff", { hasOutline: false });
  const crystalMesh = renderer.createMesh(crystalBuilder.readArrays());
  const viewMatrix = Matrix4.createLookAt(Vector3.create(3, 3, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0));
  const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
  if (outline.beginLineIds(viewMatrix, projectionMatrix)) {
  	outline.drawMesh(floorMesh, Matrix4.createIdentity(), 1, { hasScreenOutline: false });
  	outline.drawMesh(crystalMesh, Matrix4.createIdentity(), 2, { hasCreaseLine: false });
  	outline.endLineIds();
  }
  ```

- `drawMeshInstanced(mesh, instances, lineId, options = {})` (method, since 0.4.0): Draws IDs for multiple instances of the same model at once. (Uses the instance's lineId if present, otherwise the common ID)
  - `mesh` object | null: Result of ToonRenderer.createMesh.
  - `instances` Array<object>: Array of { modelMatrix: Matrix4, lineId: number (optional) }.
  - `lineId` number: Common ID.
  - `options` object: Same as drawMesh. (The options are the same for all instances)

  Example: A different ID per stone so lines appear where they touch too

  ```js
  import { ToonRenderer, ToonScreenOutline, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const outline = new ToonScreenOutline(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#a89880", { hasOutline: false });
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instances = [0, 1, 2].map((index) => ({ modelMatrix: Matrix4.createTranslation(index * 0.5, 0, 0), lineId: 10 + index }));
  const viewMatrix = Matrix4.createLookAt(Vector3.create(0.5, 2, 3), Vector3.create(0.5, 0, 0), Vector3.create(0, 1, 0));
  const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
  if (outline.beginLineIds(viewMatrix, projectionMatrix)) {
  	outline.drawMeshInstanced(rockMesh, instances, 10);
  	outline.endLineIds();
  }
  ```

- `drawMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, lineId, options = {})` (method, since 0.4.0): Draws IDs with a persistent instance buffer. (Uses the same GPU buffer as the body and does not upload it again, culled as a whole by the bounds of the entire buffer)
  - The ID of each instance is the layout's instanceLineId slot, otherwise the common ID. If the layout has no matrix the position is unknown and it is not drawn. (Vertex chunks do not run in the line target)
  - `mesh` object | null: Result of ToonRenderer.createMesh.
  - `instanceBuffer` object: The result of ToonRenderer.createInstanceBuffer. (Shares the vertex arrays of the renderer that built it)
  - `instanceCount` number: Number of instances to draw. (Clamped if more than the buffer holds)
  - `lineId` number: Common ID. (When the layout has no instanceLineId)
  - `options` object: Same as drawMesh. (The options are the same for all instances)

  Example: Draw the body and line target together with one rock buffer

  ```js
  import { ToonRenderer, ToonScreenOutline, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const outline = new ToonScreenOutline(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#a89880", { hasOutline: false });
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }, { name: "instanceLineId", size: 1 }]);
  const data = new Float32Array(21 * 3);
  for (let index = 0; index < 3; ++index) {
  	data.set(Matrix4.createTranslation(index * 0.5, 0, 0).getElements(), index * 21);
  	data.set([1, 1, 1, 1, 10 + index], index * 21 + 16);
  }
  const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);
  const viewMatrix = Matrix4.createLookAt(Vector3.create(0.5, 2, 3), Vector3.create(0.5, 0, 0), Vector3.create(0, 1, 0));
  const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
  if (outline.beginLineIds(viewMatrix, projectionMatrix)) {
  	outline.drawMeshInstanceBuffer(rockMesh, instanceBuffer, 3, 10);
  	outline.endLineIds();
  }
  renderer.beginFrameWithMatrices(viewMatrix, projectionMatrix);
  renderer.drawMeshInstanceBuffer(rockMesh, instanceBuffer, 3);
  renderer.endFrame();
  outline.drawOutline();
  ```

- `drawWithCount(mesh, modelElements, instanceCount, lineId, lineIdSource, isMirrored, options, vertexArray)` (method, since 0.4.0): Core of ID drawing.
  - `mesh` object: Result of ToonRenderer.createMesh.
  - `modelElements` Float32Array: The 16 numbers of the model matrix.
  - `instanceCount` number: 0 means normal drawing.
  - `lineId` number: Common ID.
  - `lineIdSource` number: Where to read the ID. (0 common ID, 1 the x of the tint slot, 2 the instance buffer's instanceLineId)
  - `isMirrored` boolean: Whether to draw with the winding flipped.
  - `options` object: Options of drawMesh.
  - `vertexArray` WebGLVertexArrayObject: Vertex array to draw. (The model's body, or the model bound with an instance buffer)
- `endLineIds()` (method, since 0.4.0): End ID drawing. (Thin lines pick one seed side target, thick lines pick seeds and widen them with jump flooding, then restores the framebuffer, viewport and state)
  - Thin lines (width at most THIN_LINE_MAXIMUM_WIDTH, about 3.24 pixels): one full-screen pass for the seed side target. The composite looks at the seeds of the surrounding 3 x 3 pixels. (No seed, gather or widening)
  - Thick lines: one pass each for seed, gather and every widening step. (The seed and widening targets are built the first time a thick line is drawn)
  - Passes that overwrite a whole target clear it first (clearBufferuiv, clearBufferfv) so the old contents are not loaded. (Removes target loads on tile GPUs; invalidateFramebuffer is not used because it added about 10 to 25 ms per frame in iPad and iPhone Safari)
- `drawOutline()` (method, since 0.4.0): Draw the outline. (Blends into the drawing area of beginLineIds with the seed side target for thin lines and the widened seed target for thick lines, neither reads nor writes depth, stencil untouched)
- `readLineWidths()` (method, since 0.4.0): Compute this frame's line thickness. (Drawing area pixels of [silhouette line, crease line], not below one pixel unless 0)
  - returns Array<number>: [silhouette line thickness, crease line thickness].
- `addDrawnDistance(mesh, modelElements)` (method, since 0.4.0): Adds a drawn model's distance. (Used in perspective when no focal distance is given, forward distance in view space)
  - `mesh` object: Result of ToonRenderer.createMesh.
  - `modelElements` Float32Array: The 16 numbers of the model matrix.
- `isVisible(mesh, modelElements)` (method, since 0.4.0): Whether the bounding sphere is inside this frame's frustum.
  - `mesh` object: Result of ToonRenderer.createMesh.
  - `modelElements` Float32Array: The 16 numbers of the model matrix.
  - returns boolean: true if inside the frustum.
- `readLineTarget(width, height, jumpFloodWidth, jumpFloodHeight)` (method, since 0.4.0): Read the line target. (Rebuilt if the size changes, normal and ID RGBA8 at drawing area resolution, depth 24, seeds RGBA16UI and two widening targets RGBA16UI, null if it could not be built)
  - `width` number: Width of the line target. (Drawing area pixels)
  - `height` number: Height of the line target.
  - `jumpFloodWidth` number: Width of the widening target.
  - `jumpFloodHeight` number: Height of the widening target.
  - returns object | null: The line target. (null if it could not be built)
- `deleteLineTarget()` (method, since 0.4.0): Deletes the line target.
- `saveState()` (method, since 0.4.0): Records the draw state.
- `restoreState()` (method, since 0.4.0): Restores the recorded state.
- `destroy()` (method, since 0.4.0): Delete after use. (Line target, vertex array, seven programs)

## Functions and constants

- `TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID = 16383` (field, since 0.4.0): Upper limit of line IDs. (Written into the line target in 14 bits, 0 is empty space)
  - returns number
- `readJumpFloodSteps(reach)` (method, since 0.4.0): Step list of jump flooding. (Steps needed to widen seeds up to reach pixels, halving from the largest down to 1)
  - Steps k, k/2, ..., 1 carry a seed up to 2k - 1 pixels. (Rong, Tan 2006)
  - `reach` number: Distance to carry the seeds. (Line target pixels)
  - returns Array<number>: Steps from the largest down to 1.

  Example: Steps to widen up to 4 pixels

  ```js
  import { readJumpFloodSteps } from "./vanilla.js";
  const steps = readJumpFloodSteps(4);
  ```

## ToonOutlineWidthUnit (enum)

Unit of thickness.
- world: world length. (Orthographic uses the vertical scale of the projection, perspective converts to screen pixels at the focal distance so it gets thinner farther away)
- pixel: pixels of the drawing area. (Same thickness regardless of distance)

Example: Give the thickness in world length

```js
import { ToonScreenOutline, ToonOutlineWidthUnit } from "./vanilla.js";
const outline = new ToonScreenOutline(document.createElement("canvas").getContext("webgl2"));
outline.setWidth(0.02, ToonOutlineWidthUnit.world);
outline.setFocusDistance(6);
```

- `world` = `world`: World length. (Thinner farther away)
- `pixel` = `pixel`: Pixels of the drawing area. (Same thickness regardless of distance)
