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

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

Toon light set. (Holds as one bundle the lights ToonRenderer uses to shade bodies and the toon light response)

Example: A light set with two shade color levels, hard highlight, rim and spotlight

```js
import { ToonLightSet } from "./vanilla.js";
const lightSet = new ToonLightSet();
lightSet.setLight([-0.4, -1, -0.3], [0.85, 0.82, 0.78], [0.3, 0.33, 0.42], [0.16, 0.15, 0.14]);
lightSet.setShade({ step: 0.5, feather: 0.02, color: [0.55, 0.52, 0.7], secondStep: 0.25, secondFeather: 0.02, secondColor: [0.36, 0.33, 0.52] });
lightSet.setSpecular(0.6, 64, 0);
lightSet.setRimLight([0.5, 0.55, 0.7], 3, 0.2, 1);
lightSet.setPointLights([{ position: [0, 3, 0], color: [1, 0.8, 0.6], intensity: 3, range: 6, direction: [0, -1, 0], innerConeAngle: 0.3, outerConeAngle: 0.6 }]);
```

## ToonLightSet

Toon light set. (Holds as one bundle the lights ToonRenderer uses to shade bodies and the toon light response)
- The renderer holds one default set, and the renderer's light settings such as setLight change that set. Another set can be given per draw with options.lightSet. (When the shade color differs per material)
- Sun (key light): the direction (sunDirection) is the way the light travels. It is the opposite of the direction from the surface toward the sun. ([0, -1, 0] when shining down from above) It receives shadows.
- Ambient: mixes the sky color and ground color by the normal's up and down (N.y x 0.5 + 0.5). (hemisphere light)
- Shade ramp (cel shading): the received light amount x is laid against the ramp to pick the color. x is dot(N, L) x 0.5 + 0.5 for half Lambert, otherwise max(dot(N, L), 0),
  and after adding the draw's shadeOffset, for the sun it is multiplied by the shadow (received amount 0 ~ 1). (Shadows enter as the shade color rather than black, System Shadows of the Unity Toon Shader)
  The ramp has a position, color (linear multiplier) and softness per cell (stop). The color of cell i transitions from the previous cell's color as x rises from (position - softness) to the position. (Step and Feather of the Unity Toon Shader)
  If the softness is smaller than one pixel width (fwidth), it is held at that width so the boundary does not stair-step.
  setShade builds the ramp from three, base, 1st shade and 2nd shade (Base, 1st Shade, 2nd Shade of the Unity Toon Shader), setShadeRamp from cells directly, setBandCount from even cells, setBandRamp from gray cells.
  If setRampTexture is given, the horizontal of that texture (x as u, v is 0.5) is read instead of cells. (The warp of Team Fortress 2, the ramp textures of Genshin and Honkai)
  Without cells (clearShadeRamp, setBandCount(0)) it is smooth Lambert.
- Per light: the sun receives the whole ramp color so the shade also takes on the sun's color. The fill light, point lights and spotlights receive the ramp's brightness level (bottom cell 0, top cell 1) and do not light faces turned away.
- Fill light (fill): a second directional light that does not receive shadows. Its direction means the same as the sun's. With the default color 0 it is absent.
- Highlight (specular): Blinn-Phong pow(max(dot(N, H), 0), exponent), from a hard spot cut at 0.5 (softness 0) to the plain soft light (softness 1). Color x strength x light color x received light level.
  It appears for the sun, point lights and spotlights alike. With the default strength 0 there is none.
- Rim light (rim): pow(1 - max(dot(N, V), 0), power), from a hard rim cut at 0.5 (softness 0) to a soft rim (1). If lightMask is 1, only on the side receiving the sun. Added regardless of the base color.
  The shade-side rim (setShadeRimLight) adds the same rim on the side facing away from the sun by (rim - (dot(N, L) x 0.5 + 0.5)). (Antipodean (Ap) Rim Light of the Unity Toon Shader)
- Light color usage (setLightColorUsage): chooses per color whether the light color is multiplied. When off, that color receives only the light's intensity (0.299 R + 0.587 G + 0.114 B), and the rim, matcap, angel ring and outline receive no light. (Is_LightColor_* of the Unity Toon Shader, all on by default)
- Light intensity limit (setLightIntensityLimited): limits what each light gives to 1. The sun and fill light are clamped to 1 per channel, and point lights and spotlights are divided by the intensity of their color with attenuation applied when it exceeds 1.
  (Limit Light Intensity of the Unity Toon Shader, on by default) Turn it off to use strong lights for HDR bloom.
  When porting an old game shader (one that did not limit light intensity), or when using point lights above intensity 1 or HDR bloom, use setLightIntensityLimited(false).
- Point lights and spotlights: up to TOON_MAXIMUM_POINT_LIGHTS. { position, color (linear), intensity, range, decay, rangeExponent, wrap, direction, innerConeAngle, outerConeAngle, castsShadow, shadowNear }
  Lights with castsShadow true get shadow tiles from ShadowAtlas.updateLights. (Six cube faces for a point light, one perspective tile for a spotlight, the far distance is range, the near distance is shadowNear default 0.05)
  Attenuation is window x distance attenuation. The window is (1 - (distance / range)^rangeExponent) clamped to 0 ~ 1 and squared if range is greater than 0, and 1 if it is 0. Distance attenuation is 1 / max(distance^decay, 0.01) if decay is greater than 0, and 1 if it is 0.
  The default (decay 2, rangeExponent 4) is the point light form of three.js, Unreal and Godot 4.
  Giving direction (the way the light travels) makes a spotlight. Angular attenuation is the square of clamp(cos angle x scale + offset, 0, 1) in the glTF KHR_lights_punctual form. (innerConeAngle default 0, outerConeAngle default π/4, radians)
  The received amount is the wrap (dot(N, L) + wrap) / (1 + wrap). (0 is Lambert, the wrap lighting of GPU Gems 1)
- Light model: if setLightModel({ isEnergyNormalized }) is true, base color x light is divided by π and the highlight is multiplied by (exponent + 8) / 8π. (The convention of giving physical light intensity as illuminance)
- All colors are linear colors. (They may exceed 1 for HDR) Ramp textures are treated as sRGB and read converted to linear. (By the shader with pow 2.2 in the gamma color space, by the GPU as an sRGB texture in the linear color space)
- Modifying it raises the version number (getVersion). The renderer does not re-upload if the set and version number are the same.

Example: Give a different shade color per material with light sets

```js
import { ToonRenderer, MeshBuilder, createSphereGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const skinLightSet = renderer.createLightSet();
skinLightSet.setShade({ step: 0.55, feather: 0.04, color: [0.86, 0.6, 0.6] });
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 32, 20), Matrix4.createIdentity(), "#f0d0c0", { hasOutline: false });
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, 10));
renderer.drawMesh(mesh, Matrix4.createIdentity(), { lightSet: skinLightSet });
renderer.endFrame();
```

- `constructor()` (constructor, since 0.4.0): Constructor. (The default is a two-level shade split at half Lambert 0.5, with a cool purple shade color)
- `markChanged()` (method, since 0.4.0): Raises the version after a modification.
- `getId()` (method, since 0.4.0): Returns the ID. (different per set)
  - returns number: Set number.
- `getVersion()` (method, since 0.4.0): Returns the version number. (raised on every modification)
  - returns number: Version number.
- `setLight(sunDirection, sunColor, skyColor, groundColor)` (method, since 0.4.0): Set the sun and ambient light. (Direction the sun shines, sun color, sky color, ground color, all linear)
  - `sunDirection` Array<number>: The way the light travels. [x, y, z]
  - `sunColor` Array<number>: Linear color and intensity of the sun. [r, g, b]
  - `skyColor` Array<number>: Ambient light of faces looking up. [r, g, b]
  - `groundColor` Array<number>: Ambient light of faces looking down. [r, g, b]
- `setSunDirection(sunDirection)` (method, since 0.4.0): Sets the sun direction. (the way the light travels, flip the sign if you have the direction from the surface toward the sun)
  - `sunDirection` Array<number>: [x, y, z]
- `getSunDirection()` (method, since 0.4.0): Returns the sun direction. (pass it as is to ShadowMap.updateLightMatrix)
  - returns Array<number>: [x, y, z]
- `getSunColor()` (method, since 0.4.0): Returns the sun color.
  - returns Array<number>: Linear [r, g, b].
- `getSkyColor()` (method, since 0.4.0): Returns the sky color.
  - returns Array<number>: Linear [r, g, b].
- `getGroundColor()` (method, since 0.4.0): Returns the ground color.
  - returns Array<number>: Linear [r, g, b].
- `setFillLight(fillDirection, fillColor)` (method, since 0.4.0): Set the fill light. (Direction the light travels and linear color, none if the color is 0, receives no shadow)
  - `fillDirection` Array<number>: The way the light travels. [x, y, z]
  - `fillColor` Array<number>: Linear [r, g, b].
- `getFillLight()` (method, since 0.4.0): Returns the fill light.
  - returns object: { direction, color }
- `setRimLight(rimColor, rimPower, rimFeather = 1, rimLightMask = 0)` (method, since 0.4.0): Set the rim light. (Linear color, power, softness 0 ~ 1, share kept only on the side receiving the sun 0 ~ 1, none if the power is 0 or less)
  - `rimColor` Array<number>: Linear color to add. [r, g, b]
  - `rimPower` number: Power. (The larger, the thinner the rim, 0 means none)
  - `rimFeather` number: 0 is a hard rim, 1 is a soft rim. (Default 1)
  - `rimLightMask` number: 1 puts the rim only on the side receiving the sun. (Default 0)

  Example: A hard rim that stands only on the sun side

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setRimLight([0.6, 0.65, 0.8], 2.5, 0, 1);
  ```

- `getRimLight()` (method, since 0.4.0): Returns the rim light.
  - returns object: { color, power, feather, lightMask }
- `setShadeRimLight(shadeRimColor, shadeRimPower)` (method, since 0.4.0): Set the shade-side rim light. (Rim on the side facing away from the sun, linear color, power, softness is shared with setRimLight, none if the power is 0 or less)
  - `shadeRimColor` Array<number>: Linear color to add. [r, g, b]
  - `shadeRimPower` number: Power. (0 means none)

  Example: A blue rim on the shade side

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setRimLight([0.8, 0.75, 0.6], 3, 0.1, 1);
  lightSet.setShadeRimLight([0.2, 0.3, 0.6], 2.5);
  ```

- `getShadeRimLight()` (method, since 0.4.0): Return the shade-side rim light.
  - returns object: { color, power }
- `setLightColorUsage(lightColorUsage)` (method, since 0.4.0): Set the light color usage. (Whether to multiply the light color per color, ones not given stay as they are)
  - base base, shade shade, highlight highlight, rim rim, shadeRim shade-side rim, matcap matcap, angelRing angel ring, outline shell outline.
  - Base, shade and highlight receive the light's luminance (gray) when off, and the rest receive no light when off. (lightIntensity and 1 in the Unity Toon Shader source)
  - `lightColorUsage` object: true or false for { base, shade, highlight, rim, shadeRim, matcap, angelRing, outline }.

  Example: Keep the shade and outline from taking on the light color

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setLightColorUsage({ shade: false, outline: false });
  ```

- `getLightColorUsage()` (method, since 0.4.0): Return the light color usage.
  - returns object: { base, shade, highlight, rim, shadeRim, matcap, angelRing, outline }
- `setLightIntensityLimited(isLimited)` (method, since 0.4.0): Set the light intensity limit. (If true, limits what each light gives to 1 so it does not wash out to white, default true, Limit Light Intensity of the Unity Toon Shader)
  - The sun and fill light are clamped to 1 per color channel. (saturate of the main light)
  - Point lights and spotlights are divided by the intensity (0.299 R + 0.587 G + 0.114 B) of their color with attenuation applied when it exceeds 1. (min(color, color / intensity) of additional lights)
  - If the light model is isEnergyNormalized, the share after dividing by π is limited to 1.
  - When porting an old game shader (one that did not limit light intensity), or when using point lights above intensity 1 or HDR bloom, use setLightIntensityLimited(false).
  - `isLimited` boolean: If true, limits.

  Example: Turn off the limit to get HDR bloom from a strong sun

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setLight([-0.4, -1, -0.3], [4, 3.8, 3.5], [0.4, 0.45, 0.55], [0.2, 0.18, 0.16]);
  lightSet.setLightIntensityLimited(false);
  if (lightSet.isLightIntensityLimited()) {
  	throw new Error("unexpected limit");
  }
  ```

- `isLightIntensityLimited()` (method, since 0.4.0): Return whether the light intensity is limited.
  - returns boolean: true if limited.
- `setSpecular(specularStrength, specularExponent = 48, specularFeather = 0, specularColor = [1, 1, 1])` (method, since 0.4.0): Set the highlight (specular). (None if the strength is 0, the larger the exponent the smaller the spot, softness 0 is a hard toon spot, 1 is soft Blinn-Phong)
  - `specularStrength` number: Strength. (0 means none)
  - `specularExponent` number: Blinn-Phong exponent. (Default 48)
  - `specularFeather` number: 0 ~ 1. (Default 0, hard spot)
  - `specularColor` Array<number>: Linear [r, g, b]. (Default white)

  Example: Soft highlight

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setSpecular(0.4, 32, 1, [1, 0.95, 0.9]);
  ```

- `getSpecular()` (method, since 0.4.0): Return the highlight.
  - returns object: { strength, exponent, feather, color }
- `setPointLights(pointLights)` (method, since 0.4.0): Set point lights and spotlights. (Ones beyond TOON_MAXIMUM_POINT_LIGHTS are dropped, giving direction makes a spotlight)
  - `pointLights` Array<object>: Array of { position [x, y, z], color [r, g, b] linear, intensity (default 1), range (default 0 = endless), decay (default 2), rangeExponent (default 4), wrap (default 0),
  direction [x, y, z] (the way the light travels, spotlight if given), innerConeAngle (default 0), outerConeAngle (default π/4), castsShadow (default false), shadowNear (default 0.05) }.

  Example: One spotlight shining down

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setPointLights([{ position: [0, 4, 0], color: [1, 0.9, 0.7], intensity: 4, range: 8, direction: [0, -1, 0], innerConeAngle: 0.25, outerConeAngle: 0.5 }]);
  ```

- `getPointLights()` (method, since 0.4.0): Returns the point lights. (as set, before clipping to the limit)
  - returns Array<object>: Array in the form filled by setPointLights.
- `setPointLightLimit(pointLightLimit)` (method, since 0.4.0): Sets the limit on the number of point lights put into the shader. (0 ~ TOON_MAXIMUM_POINT_LIGHTS, lowered on lightweight paths)
  - `pointLightLimit` number: Limit.
- `getPointLightCount()` (method, since 0.4.0): Number of point lights put into the shader. (the smaller of the set count and the limit)
  - returns number: Number of point lights put into the shader.
- `setShade(shade)` (method, since 0.4.0): Set the three shades. (Base, 1st shade, 2nd shade of the Unity Toon Shader and Step and Feather of their boundaries)
  - step is the boundary between base and 1st shade, secondStep the boundary between 1st and 2nd shade. (A position of the received light amount x, with half Lambert 0.5 is the face perpendicular to the sun)
  - Colors are linear multipliers on the base color and light. The base is white [1, 1, 1].
  - If secondStep is 0 or less, there is no 2nd shade. (Default 0)
  - `shade` object: { step (default 0.5), feather (default 0.02), color (default [0.5, 0.48, 0.66]), secondStep (default 0), secondFeather (default 0.02), secondColor (default [0.32, 0.3, 0.48]), isHalfLambert (default true) }

  Example: A warm 1st shade and a deep 2nd shade

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setShade({ step: 0.5, feather: 0.03, color: [0.8, 0.62, 0.6], secondStep: 0.2, secondFeather: 0.03, secondColor: [0.5, 0.36, 0.42] });
  ```

- `setShadeRamp(positions, colors, feathers, isHalfLambert)` (method, since 0.4.0): Set the shade ramp. (Position, linear color and softness per cell, 2 ~ TOON_MAXIMUM_BAND_STEPS cells, smooth Lambert if emptied)
  - Cells are in ascending order of position. The position and softness of the first cell are not used. (The first cell's color if x is below the second cell)
  - `positions` Array<number>: Position per cell. (Received light amount x)
  - `colors` Array<Array<number>>: Linear [r, g, b] multiplier per cell.
  - `feathers` Array<number>: Softness per cell. (Width of the transition into that cell)
  - `isHalfLambert` boolean: Whether to count x as dot x 0.5 + 0.5. (Otherwise max(dot, 0))

  Example: Give a three-cell ramp directly

  ```js
  import { ToonLightSet } from "./vanilla.js";
  const lightSet = new ToonLightSet();
  lightSet.setShadeRamp([0, 0.4, 0.62], [[0.3, 0.3, 0.45], [0.62, 0.6, 0.75], [1, 1, 1]], [0, 0.05, 0.02], true);
  ```

- `clearShadeRamp()` (method, since 0.4.0): Turn off the shade ramp. (Smooth Lambert)
- `getShadeRamp()` (method, since 0.4.0): Return the shade ramp. (Smooth Lambert if the cells are empty)
  - returns object: { positions, colors, feathers, isHalfLambert }
- `setBandCount(bandCount)` (method, since 0.4.0): Set even cells. (Gray cells rounding max(dot(N, L), 0) to the cell count, 1 ~ TOON_MAXIMUM_BAND_STEPS - 1, 0 means smooth Lambert)
  - `bandCount` number: Number of cells. (0 means smooth)
- `setBandRamp(thresholds, values, isHalfLambert)` (method, since 0.4.0): Set a gray cell ramp. (Thresholds are one fewer than values, values up to TOON_MAXIMUM_BAND_STEPS, below the first threshold is the first value, above the last threshold the last value)
  - `thresholds` Array<number>: Ascending thresholds.
  - `values` Array<number>: Received amount per cell.
  - `isHalfLambert` boolean: Whether to compare dot x 0.5 + 0.5 to the thresholds.
- `setRampTexture(rampTexture, isHalfLambert = true)` (method, since 0.4.0): Set the ramp texture. (Reads the horizontal of the texture instead of cells, back to cells if null, one built with ToonRenderer.createTexture)
  - Reads x as u at v 0.5. Left is shade, right is light. Treated as sRGB and converted to linear. Build it with isRepeated: false so it does not wrap.
  - `rampTexture` WebGLTexture | null: Ramp texture or null.
  - `isHalfLambert` boolean: Whether to count x with half Lambert. (Default true)

  Example: A four-cell ramp texture drawn in code

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const data = new Uint8Array([70, 60, 120, 255, 120, 110, 170, 255, 200, 190, 220, 255, 255, 255, 255, 255]);
  const rampTexture = renderer.createTexture({ width: 4, height: 1, data: data }, { isMipmapped: false, isRepeated: false, isFiltered: false });
  renderer.getLightSet().setRampTexture(rampTexture);
  ```

- `getRampTexture()` (method, since 0.4.0): Return the ramp texture. (null if none)
  - returns WebGLTexture | null: Ramp texture. (null if none)
- `setLightModel(lightModel)` (method, since 0.4.0): Sets the light model. ({ isEnergyNormalized } whether to divide base color x light by π)
  - `lightModel` object: { isEnergyNormalized }
- `getLightModel()` (method, since 0.4.0): Returns the light model.
  - returns object: { isEnergyNormalized }

## Functions and constants

- `TOON_MAXIMUM_POINT_LIGHTS = 8` (field, since 0.4.0): Upper limit of point lights and spotlights received in one draw. (Size of the uniform arrays in the shader)
  - returns number
- `TOON_MAXIMUM_BAND_STEPS = 8` (field, since 0.4.0): Upper limit of shade ramp cells. (Size of the uniform arrays in the shader)
  - returns number
