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

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

Toon material. (shader chunks inserted into ToonRenderer's body shader, the per-game extension point)

Example: Put stripes in with a surface chunk and pass a texture and uniforms per draw

```js
import { ToonRenderer, ToonMaterial, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const material = new ToonMaterial({
	name: "stripe",
	uniformChunk: "uniform sampler2D stripeTexture;\nuniform float stripeShift;\n",
	surfaceChunk: `void applySurface(inout ToonSurface surface) {
		float stripe = texture(stripeTexture, vec2(surface.localPosition.y * 4.0 + stripeShift, 0.5)).r;
		surface.baseColor *= mix(0.5, 1.0, stripe);
	}`,
});
const stripeTexture = renderer.createTexture({ width: 2, height: 1, data: new Uint8Array([255, 255, 255, 255, 0, 0, 0, 255]) }, { isMipmapped: false, isColorData: false });
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#80c0e0", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createIdentity(), {
	material: material,
	textures: { stripeTexture: stripeTexture },
	onBeforeDraw: (program, context) => context.uniform1f(program.getUniformLocation("stripeShift"), 0.25),
});
renderer.endFrame();
```

## ToonMaterial

Toon material. (Shader chunks inserted into ToonRenderer's body shader, the per-game extension point)
- Only patterns and effects that the engine's standard features (textures, light, tint, blending) cannot do go into chunks. Slots without a chunk get the engine's empty functions.
- uniformChunk: goes into the top slot of the fragment shader. Write uniforms, constants, functions and the ins exported by the vertex chunk.
- surfaceChunk: defines void applySurface(inout ToonSurface surface). The engine calls it after computing the vertex color, textures and decal, before tint and light.
  ToonSurface { vec3 baseColor (sRGB in the gamma color space, linear in the linear color space, convert sRGB colors with toSurfaceColor before mixing them in), float alpha, vec3 emission (linear), vec3 normal (world, unit), float glow (vertex glow), bool isUnlit,
                vec4 detail (vertex pattern number and pattern color), vec2 uv, vec2 uv1 (second UV, (0, 1) if none), vec3 localPosition (model coordinates), vec3 worldPosition, vec3 viewDirection (from the surface toward the camera, unit),
                float shadeOffset (value added to the received light amount, moves the shade boundary), float specularMask (highlight multiplier), float rimMask (rim light multiplier) }
- lightChunk: defines void applyLight(ToonSurface surface, inout ToonLighting lighting). The engine calls it after gathering the sun, ambient light, fill, point lights and spotlights, highlight and rim, before combining.
  ToonLighting { vec3 irradiance (light multiplied into the base color, after the shade ramp), vec3 specular (highlight to add), vec3 rim (rim light to add), float shadow (0 ~ 1), float sunLevel (brightness level of the received sun 0 ~ 1) }
  Combining is base color x irradiance + specular x specularMask + rim x rimMask + glow.
- vertexChunk: goes into the top slot of the vertex shaders (all three: body, outline, shadow depth) and defines void applyVertex(inout ToonVertex vertex). Called before moving into world space.
  ToonVertex { vec3 localPosition, vec3 localNormal, vec3 color, vec2 material, vec4 detail, vec2 uv, vec2 uv1, vec4 tint, vec4 emissive, mat4 modelMatrix }
  User attributes of the instance layout (ToonInstanceLayout) are read as ins of that name. Since it goes into all three, do not use outs that exist only in the body. (Use the fields of vertex instead of vertex attribute names)
  Normals are moved by mat3(modelMatrix). If the scale is not uniform, divide localNormal by the square of that scale beforehand.
- The shader has the engine's toLinear(vec3) (sRGB to linear, pow 2.2 in the gamma color space, the sRGB standard curve in the linear color space), toSurfaceColor(vec3) (sRGB to the space of baseColor) and RECIPROCAL_PI.
  In the linear color space (ColorSpace.linear) the source has #define VANILLA_COLOR_SPACE_LINEAR 1, and the GPU decodes the color textures the engine binds to linear. (isColorData of ToonRenderer.createTexture)
- Textures are passed with the draw's options.textures ({ uniform name: texture }). The engine binds them in order to units it does not use (from 8, up to TOON_MAXIMUM_MATERIAL_TEXTURES) and puts the unit into the sampler2D uniform of that name.
- Uniforms that differ per draw are written in options.onBeforeDraw(program, webGL2RenderingContext). The engine rewrites its own uniforms, so write only the material's.

Example: Grow the rim with a light chunk and tilt with a vertex chunk

```js
import { ToonRenderer, ToonMaterial } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const material = new ToonMaterial({
	name: "leanRim",
	lightChunk: "void applyLight(ToonSurface surface, inout ToonLighting lighting) { lighting.rim *= 2.0; }",
	vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.localPosition.x += vertex.localPosition.y * 0.2; }",
});
if (!renderer.prepareMaterial(material)) {
	throw new Error("shader failed: " + material.getName());
}
```

- `constructor(chunks = {})` (constructor, since 0.4.0): Constructor.
  - `chunks` object: { name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (missing slots are empty strings)
- `getId()` (method, since 0.4.0): Returns the ID. (different per material)
  - returns number: Material number.
- `getName()` (method, since 0.4.0): Returns the name. (used in notification messages)
  - returns string: Name. (Empty text if not given)
- `getUniformChunk()` (method, since 0.4.0): Returns the uniform chunk.
  - returns string: Uniform chunk. (Empty text if none)
- `getSurfaceChunk()` (method, since 0.4.0): Returns the surface chunk.
  - returns string: Surface chunk. (Empty text if none)
- `getLightChunk()` (method, since 0.4.0): Returns the light chunk.
  - returns string: Light chunk. (Empty text if none)
- `getVertexChunk()` (method, since 0.4.0): Returns the vertex chunk.
  - returns string: Vertex chunk. (Empty text if none)

## ToonInstanceLayout

Instance layout. (the attribute order of one instance, used by ToonRenderer.createInstanceBuffer and drawMeshInstanceBuffer)
- { name, size } per attribute. If the name is instanceMatrix (16) the engine reads it as the model matrix, and if instanceTint (4) as the multiplying color.
  instanceMatrix is read as an affine 3x4, and the four values of the bottom row (elements 3, 7, 11, 15) are that instance's emission (sRGB r, g, b and a linear intensity, vertex.emissive). Storing Matrix4 elements as they are gives no emission.
- instanceLineId (1) is the per-instance line ID of the screen-space outline. (ToonScreenOutline.drawMeshInstanceBuffer, ToonDrawQueue.addMeshInstanceBuffer)
  It uses the last user attribute location (TOON_INSTANCE_LINE_ID_LOCATION), so with it one fewer user attribute fits. The vertex chunk can read it by that name too.
- Other names are user attributes. Up to TOON_MAXIMUM_INSTANCE_ATTRIBUTES, size 1 ~ 4. The vertex chunk reads them as ins of that name. (from location 13)
- Without instanceMatrix, the model matrix is the identity matrix. The vertex chunk builds and fills in vertex.modelMatrix. (when position, rotation and scale are stored in only a few numbers)
- Without instanceTint, the tint is 1.

Example: A layout holding only position and size without a matrix

```js
import { ToonRenderer, ToonInstanceLayout, ToonMaterial } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const instanceLayout = new ToonInstanceLayout([{ name: "instanceOffset", size: 3 }, { name: "instanceScale", size: 1 }, { name: "instanceTint", size: 4 }]);
const material = new ToonMaterial({
	name: "scatter",
	vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.localPosition = vertex.localPosition * instanceScale + instanceOffset; }",
});
renderer.prepareMaterial(material, instanceLayout);
const data = new Float32Array(instanceLayout.getFloatCount() * 2);
data.set([0, 0, 0, 1, 1, 1, 1, 1, 2, 0, 0, 0.5, 1, 0.6, 0.6, 1]);
const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);
```

- `constructor(attributes)` (constructor, since 0.4.0): Constructor. (throws if names overlap, sizes do not fit, or there are too many user attributes)
  - `attributes` Array<object>: Array of { name, size }.
- `getId()` (method, since 0.4.0): Returns the ID. (different per layout)
  - returns number: Layout number.
- `getAttributes()` (method, since 0.4.0): Returns the attribute list.
  - returns Array<object>: Array of { name, size, offset, location }. (offset in floats, location only for user attributes and instanceLineId, otherwise -1)
- `getFloatCount()` (method, since 0.4.0): Number of values per instance.
  - returns number: Number of values per instance.
- `hasMatrix()` (method, since 0.4.0): Whether it has a model matrix.
  - returns boolean: true if there is an instanceMatrix.
- `hasTint()` (method, since 0.4.0): Whether it has a tint.
  - returns boolean: true if there is an instanceTint.
- `hasLineId()` (method, since 0.4.0): Whether there is a per-instance line ID.
  - returns boolean: true if there is instanceLineId.

  Example: Layout holding matrix, tint and line ID

  ```js
  import { ToonInstanceLayout } from "./vanilla.js";
  const instanceLayout = new ToonInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }, { name: "instanceLineId", size: 1 }]);
  if (!instanceLayout.hasLineId() || instanceLayout.getFloatCount() !== 21) {
  	throw new Error("line id layout failed");
  }
  ```

- `readDeclarationSource()` (method, since 0.4.0): Shader declarations of the user attributes. (in float / vec2 / vec3 / vec4 name;)
  - returns string: in declarations, one line per user attribute. (Empty text if none)

## Functions and constants

- `TOON_MAXIMUM_INSTANCE_ATTRIBUTES = 3` (field, since 0.4.0): Upper limit on the number of user attributes in an instance layout. (attribute locations 13, 14, 15)
  - returns number
- `TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION = 13` (field, since 0.4.0): First location of the user instance attributes.
  - returns number
- `TOON_INSTANCE_MATRIX_NAME = "instanceMatrix"` (field, since 0.4.0): Name the engine reads as the model matrix in an instance layout. (16 floats)
  - returns string
- `TOON_INSTANCE_TINT_NAME = "instanceTint"` (field, since 0.4.0): Name the engine reads as the multiplied color in an instance layout. (4 floats)
  - returns string
- `TOON_INSTANCE_LINE_ID_NAME = "instanceLineId"` (field, since 0.4.0): The name the screen-space outline reads from an instance layout as the per-instance line ID. (1 value, 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID)
  - returns string
- `TOON_INSTANCE_LINE_ID_LOCATION` (field, since 0.4.0): Location of the line ID attribute. (The last user attribute location, the line target shader reads from this location)

## ToonBlendMode (enum)

Blend mode. (alpha is straight alpha SRC_ALPHA, premultiplied is premultiplied alpha ONE, additive is additive ONE, ONE)

Example: Blend a glowing ring additively

```js
import { ToonRenderer, ToonBlendMode, MeshBuilder, createTorusGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createTorusGeometry(0.5, 0.05, 8, 32), Matrix4.createIdentity(), "#40c0ff", { glow: 1, isUnlit: true, hasOutline: false });
const ringMesh = renderer.createMesh(builder.readArrays());
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(ringMesh, Matrix4.createIdentity(), { blendMode: ToonBlendMode.additive, alpha: 0.8 });
renderer.endFrame();
```

- `alpha` = `alpha`: Straight alpha. (SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
- `premultiplied` = `premultiplied`: Premultiplied alpha. (ONE, ONE_MINUS_SRC_ALPHA)
- `additive` = `additive`: Additive. (ONE, ONE)

## ToonMatcapBlend (enum)

How the matcap is blended. (multiply multiplies into the color, add adds to the color, same as the MatCap blending of the Unity Toon Shader)

Example: Add a matcap for a metallic shine

```js
import { ToonRenderer, ToonMatcapBlend, MeshBuilder, createSphereGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const matcapTexture = renderer.createTexture({ width: 2, height: 2, data: new Uint8Array([40, 40, 48, 255, 255, 255, 255, 255, 40, 40, 48, 255, 120, 120, 140, 255]) }, { isMipmapped: false, isRepeated: false });
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 24, 16), Matrix4.createIdentity(), "#c0a060", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 0, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createIdentity(), { matcapTexture: matcapTexture, matcapStrength: 0.6, matcapBlend: ToonMatcapBlend.add });
renderer.endFrame();
```

- `multiply` = `multiply`: Multiplies into the color.
- `add` = `add`: Adds to the color.

## ToonBufferUsage (enum)

Usage of the instance buffer. (static is uploaded once and drawn for a long time, dynamic is modified often)

Example: Build an instance buffer to update every frame

```js
import { ToonRenderer, ToonBufferUsage, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }]);
const data = new Float32Array(16 * 2);
data.set(Matrix4.createTranslation(-1, 0, 0).getElements(), 0);
data.set(Matrix4.createTranslation(1, 0, 0).getElements(), 16);
const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data, ToonBufferUsage.dynamic);
data.set(Matrix4.createTranslation(1, 0.5, 0).getElements(), 16);
renderer.updateInstanceBuffer(instanceBuffer, data);
```

- `static` = `static`: Uploaded once and used for a long time. (STATIC_DRAW)
- `dynamic` = `dynamic`: Changed often. (DYNAMIC_DRAW)
