vanilladocs
vanillapunch.com
API / graphics3d/toon/toonmaterial

graphics3d/toon/toonmaterial

툰 머티리얼. (ToonRenderer 의 몸 셰이더에 끼울 셰이더 조각, 게임마다의 확장 자리)

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
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();
Put stripes in with a surface chunk and pass a texture and uniforms per draw

ToonMaterial

짝Counterpart: vanilla-engine ToonMaterial

툰 머티리얼. (ToonRenderer 의 몸 셰이더에 끼울 셰이더 조각, 게임마다의 확장 자리)

  • 엔진의 표준 기능(텍스처, 빛, 틴트, 섞기)으로 되지 않는 무늬나 연출만 조각으로 넣는다. 조각이 없는 칸은 엔진의 빈 함수가 들어간다.
  • uniformChunk: 조각 셰이더의 맨 위 칸에 들어간다. 유니폼, 상수, 함수, 정점 조각이 내보낸 in 을 적는다.
  • surfaceChunk: void applySurface(inout ToonSurface surface) 를 정의한다. 엔진이 꼭짓점 색, 텍스처, 데칼을 셈한 뒤, 틴트와 빛 전에 부른다. ToonSurface { vec3 baseColor (감마 색 공간은 sRGB, 선형 색 공간은 선형, sRGB 색을 섞을 때는 toSurfaceColor 로 바꿔 넣는다), float alpha, vec3 emission (선형), vec3 normal (월드, 단위), float glow (꼭짓점 빛남), bool isUnlit, vec4 detail (꼭짓점 무늬 번호와 무늬 색), vec2 uv, vec2 uv1 (2 번 UV, 없으면 (0, 1)), vec3 localPosition (모형 좌표), vec3 worldPosition, vec3 viewDirection (면에서 카메라 쪽, 단위), float shadeOffset (빛을 받는 몫에 더할 값, 그늘 경계를 옮김), float specularMask (하이라이트 배), float rimMask (림 빛 배) }
  • lightChunk: void applyLight(ToonSurface surface, inout ToonLighting lighting) 를 정의한다. 엔진이 해, 바탕빛, 채움, 점광과 스포트라이트, 하이라이트, 림을 모은 뒤 합치기 전에 부른다. ToonLighting { vec3 irradiance (바탕색에 곱할 빛, 그늘 램프를 거친 것), vec3 specular (더할 하이라이트), vec3 rim (더할 림 빛), float shadow (0 ~ 1), float sunLevel (해를 받는 밝기 단계 0 ~ 1) } 합치기는 바탕색 x irradiance + specular x specularMask + rim x rimMask + 빛남 이다.
  • vertexChunk: 정점 셰이더(몸, 바깥선, 그림자 깊이 셋 모두)의 맨 위 칸에 들어가고 void applyVertex(inout ToonVertex vertex) 를 정의한다. 월드로 옮기기 전에 부른다. ToonVertex { vec3 localPosition, vec3 localNormal, vec3 color, vec2 material, vec4 detail, vec2 uv, vec2 uv1, vec4 tint, vec4 emissive, mat4 modelMatrix } 인스턴스 꼴(ToonInstanceLayout)의 사용자 어트리뷰트는 그 이름의 in 으로 읽는다. 셋 모두에 들어가므로 몸에만 있는 out 은 쓰지 않는다. (꼭짓점 어트리뷰트 이름 대신 vertex 의 칸을 쓴다) 노멀은 mat3(modelMatrix) 로 옮긴다. 크기가 고르지 않으면 localNormal 을 그 크기의 제곱으로 나눠 둔다.
  • 셰이더에는 엔진의 toLinear(vec3) (sRGB 를 선형으로, 감마 색 공간은 pow 2.2, 선형 색 공간은 sRGB 표준 곡선), toSurfaceColor(vec3) (sRGB 를 baseColor 의 공간으로) 와 RECIPROCAL_PI 가 있다. 선형 색 공간(ColorSpace.linear)이면 소스에 #define VANILLA_COLOR_SPACE_LINEAR 1 이 있고 엔진이 묶는 색 텍스처는 GPU 가 선형으로 풀어 준다. (ToonRenderer.createTexture 의 isColorData)
  • 텍스처는 그리기의 options.textures({ 유니폼 이름: 텍스처 })로 넘긴다. 엔진이 쓰지 않는 유닛(8 부터, TOON_MAXIMUM_MATERIAL_TEXTURES 개까지)을 차례로 묶고 그 이름의 sampler2D 유니폼에 유닛을 넣는다.
  • 그리기마다 다른 유니폼은 options.onBeforeDraw(program, webGL2RenderingContext) 에서 쓴다. 엔진의 유니폼은 엔진이 다시 쓰므로 머티리얼의 것만 쓴다.

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
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());
}
생성자constructorconstructor(chunks = {})#0.4.0 부터since 0.4.0소스source

생성.

Constructor.

chunksobject
{ name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (없는 칸은 빈 글){ name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (missing slots are empty strings)

짝Counterpart: vanilla-engine ToonMaterial.new

메서드methodgetId()#0.4.0 부터since 0.4.0소스source

번호 반환. (머티리얼마다 다르다)

Returns the ID. (different per material)

반환Returnsnumber 머티리얼 번호.Material number.

짝Counterpart: vanilla-engine ToonMaterial.get_id

메서드methodgetName()#0.4.0 부터since 0.4.0소스source

이름 반환. (알림 글에 쓴다)

Returns the name. (used in notification messages)

반환Returnsstring 이름. (주지 않았으면 빈 글)Name. (Empty text if not given)

짝Counterpart: vanilla-engine ToonMaterial.get_name

메서드methodgetUniformChunk()#0.4.0 부터since 0.4.0소스source

유니폼 조각 반환.

Returns the uniform chunk.

반환Returnsstring 유니폼 조각. (없으면 빈 글)Uniform chunk. (Empty text if none)

짝Counterpart: vanilla-engine ToonMaterial.get_uniform_chunk

메서드methodgetSurfaceChunk()#0.4.0 부터since 0.4.0소스source

표면 조각 반환.

Returns the surface chunk.

반환Returnsstring 표면 조각. (없으면 빈 글)Surface chunk. (Empty text if none)

짝Counterpart: vanilla-engine ToonMaterial.get_surface_chunk

메서드methodgetLightChunk()#0.4.0 부터since 0.4.0소스source

빛 조각 반환.

Returns the light chunk.

반환Returnsstring 빛 조각. (없으면 빈 글)Light chunk. (Empty text if none)

짝Counterpart: vanilla-engine ToonMaterial.get_light_chunk

메서드methodgetVertexChunk()#0.4.0 부터since 0.4.0소스source

정점 조각 반환.

Returns the vertex chunk.

반환Returnsstring 정점 조각. (없으면 빈 글)Vertex chunk. (Empty text if none)

짝Counterpart: vanilla-engine ToonMaterial.get_vertex_chunk

ToonInstanceLayout

짝Counterpart: vanilla-engine ToonInstanceLayout

인스턴스 꼴. (인스턴스 하나의 어트리뷰트 차례, ToonRenderer.createInstanceBuffer 와 drawMeshInstanceBuffer 가 쓴다)

  • 어트리뷰트마다 { name, size }. 이름이 instanceMatrix(16) 면 모형 행렬, instanceTint(4) 면 곱하는 색으로 엔진이 읽는다. instanceMatrix 는 아핀 3x4 로 읽고 아래 줄 네 칸(원소 3, 7, 11, 15)은 그 인스턴스의 빛남(sRGB r, g, b 와 선형 세기, vertex.emissive)이다. Matrix4 원소를 그대로 담으면 빛남이 없다.
  • instanceLineId(1) 는 화면 공간 바깥선의 인스턴스마다 선 번호다. (ToonScreenOutline.drawMeshInstanceBuffer, ToonDrawQueue.addMeshInstanceBuffer) 사용자 어트리뷰트의 마지막 자리(TOON_INSTANCE_LINE_ID_LOCATION)를 쓰므로 이것이 있으면 사용자 어트리뷰트는 하나 적게 넣는다. 정점 조각도 그 이름으로 읽을 수 있다.
  • 그 밖의 이름은 사용자 어트리뷰트다. TOON_MAXIMUM_INSTANCE_ATTRIBUTES 개까지, 크기 1 ~ 4. 정점 조각이 그 이름의 in 으로 읽는다. (자리 13 부터)
  • instanceMatrix 가 없으면 모형 행렬은 단위 행렬이다. 정점 조각이 vertex.modelMatrix 를 지어 넣는다. (자리, 돌림, 크기를 몇 수로만 담을 때)
  • instanceTint 가 없으면 틴트는 1 이다.

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
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);
생성자constructorconstructor(attributes)#0.4.0 부터since 0.4.0소스source

생성. (이름이 겹치거나, 크기가 맞지 않거나, 사용자 어트리뷰트가 너무 많으면 던진다)

Constructor. (throws if names overlap, sizes do not fit, or there are too many user attributes)

attributesArray<object>
{ name, size } 의 배열.Array of { name, size }.

짝Counterpart: vanilla-engine ToonInstanceLayout.new

메서드methodgetId()#0.4.0 부터since 0.4.0소스source

번호 반환. (꼴마다 다르다)

Returns the ID. (different per layout)

반환Returnsnumber 꼴 번호.Layout number.

짝Counterpart: vanilla-engine ToonInstanceLayout.get_id

메서드methodgetAttributes()#0.4.0 부터since 0.4.0소스source

어트리뷰트 목록 반환.

Returns the attribute list.

반환ReturnsArray<object> { name, size, offset, location } 의 배열. (offset 은 수 단위, location 은 사용자 어트리뷰트와 instanceLineId 만, 아니면 -1)Array of { name, size, offset, location }. (offset in floats, location only for user attributes and instanceLineId, otherwise -1)

짝Counterpart: vanilla-engine ToonInstanceLayout.get_attributes

메서드methodgetFloatCount()#0.4.0 부터since 0.4.0소스source

인스턴스 하나의 수 개수.

Number of values per instance.

반환Returnsnumber 인스턴스 하나의 수 개수.Number of values per instance.

짝Counterpart: vanilla-engine ToonInstanceLayout.get_float_count

메서드methodhasMatrix()#0.4.0 부터since 0.4.0소스source

모형 행렬이 있는지.

Whether it has a model matrix.

반환Returnsboolean instanceMatrix 가 있으면 true.true if there is an instanceMatrix.

짝Counterpart: vanilla-engine ToonInstanceLayout.has_matrix

메서드methodhasTint()#0.4.0 부터since 0.4.0소스source

틴트가 있는지.

Whether it has a tint.

반환Returnsboolean instanceTint 가 있으면 true.true if there is an instanceTint.

짝Counterpart: vanilla-engine ToonInstanceLayout.has_tint

메서드methodhasLineId()#0.4.0 부터since 0.4.0소스source

인스턴스마다의 선 번호가 있는지.

Whether there is a per-instance line ID.

반환Returnsboolean instanceLineId 가 있으면 true.true if there is instanceLineId.

짝Counterpart: vanilla-engine ToonInstanceLayout.has_line_id

예제Example행렬, 틴트, 선 번호를 담는 꼴Layout holding matrix, tint and line ID
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");
}
메서드methodreadDeclarationSource()#0.4.0 부터since 0.4.0소스source

사용자 어트리뷰트의 셰이더 선언. (in float / vec2 / vec3 / vec4 이름;)

Shader declarations of the user attributes. (in float / vec2 / vec3 / vec4 name;)

반환Returnsstring 사용자 어트리뷰트마다 한 줄인 in 선언. (없으면 빈 글)in declarations, one line per user attribute. (Empty text if none)

짝Counterpart: vanilla-engine ToonInstanceLayout.read_declaration_source

상수Constants

상수constantTOON_MAXIMUM_INSTANCE_ATTRIBUTES = 3#0.4.0 부터since 0.4.0소스source

인스턴스 꼴에 넣을 수 있는 사용자 어트리뷰트 수의 상한. (어트리뷰트 자리 13, 14, 15)

Upper limit on the number of user attributes in an instance layout. (attribute locations 13, 14, 15)

반환Returnsnumber

짝Counterpart: vanilla-engine TOON_MAXIMUM_INSTANCE_ATTRIBUTES

상수constantTOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION = 13#0.4.0 부터since 0.4.0소스source

사용자 인스턴스 어트리뷰트의 첫 자리.

First location of the user instance attributes.

반환Returnsnumber

짝Counterpart: vanilla-engine TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION

상수constantTOON_INSTANCE_MATRIX_NAME = "instanceMatrix"#0.4.0 부터since 0.4.0소스source

인스턴스 꼴에서 엔진이 모형 행렬로 읽는 이름. (수 16)

Name the engine reads as the model matrix in an instance layout. (16 floats)

반환Returnsstring

짝Counterpart: vanilla-engine TOON_INSTANCE_MATRIX_NAME

상수constantTOON_INSTANCE_TINT_NAME = "instanceTint"#0.4.0 부터since 0.4.0소스source

인스턴스 꼴에서 엔진이 곱하는 색으로 읽는 이름. (수 4)

Name the engine reads as the multiplied color in an instance layout. (4 floats)

반환Returnsstring

짝Counterpart: vanilla-engine TOON_INSTANCE_TINT_NAME

상수constantTOON_INSTANCE_LINE_ID_NAME = "instanceLineId"#0.4.0 부터since 0.4.0소스source

인스턴스 꼴에서 화면 공간 바깥선이 인스턴스마다의 선 번호로 읽는 이름. (수 1, 1 ~ TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID)

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)

반환Returnsstring

짝Counterpart: vanilla-engine TOON_INSTANCE_LINE_ID_NAME

상수constantTOON_INSTANCE_LINE_ID_LOCATION#0.4.0 부터since 0.4.0소스source

선 번호 어트리뷰트의 자리. (사용자 어트리뷰트의 마지막 자리, 선의 판 셰이더가 이 자리에서 읽는다)

Location of the line ID attribute. (The last user attribute location, the line target shader reads from this location)

짝Counterpart: vanilla-engine TOON_INSTANCE_LINE_ID_LOCATION

ToonBlendModeenum

짝Counterpart: vanilla-engine ToonBlendMode

섞는 방식. (alpha 는 곧은 알파 SRC_ALPHA, premultiplied 는 미리 곱한 알파 ONE, additive 는 더하기 ONE, ONE)

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

예제Example빛나는 고리를 더하기로 섞기Blend a glowing ring additively
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();
이름Name값Value설명Description
alphaalpha곧은 알파. (SRC_ALPHA, ONE_MINUS_SRC_ALPHA)Straight alpha. (SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
premultipliedpremultiplied미리 곱한 알파. (ONE, ONE_MINUS_SRC_ALPHA)Premultiplied alpha. (ONE, ONE_MINUS_SRC_ALPHA)
additiveadditive더하기. (ONE, ONE)Additive. (ONE, ONE)

ToonMatcapBlendenum

짝Counterpart: vanilla-engine ToonMatcapBlend

매트캡을 섞는 방식. (multiply 는 색에 곱함, add 는 색에 더함, 유니티 툰 셰이더의 MatCap 섞기와 같다)

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
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();
이름Name값Value설명Description
multiplymultiply색에 곱한다.Multiplies into the color.
addadd색에 더한다.Adds to the color.

ToonBufferUsageenum

짝Counterpart: vanilla-engine ToonBufferUsage

인스턴스 버퍼의 쓰임. (static 은 한 번 올리고 오래 그림, dynamic 은 자주 고침)

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
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);
이름Name값Value설명Description
staticstatic한 번 올려 오래 쓴다. (STATIC_DRAW)Uploaded once and used for a long time. (STATIC_DRAW)
dynamicdynamic자주 고친다. (DYNAMIC_DRAW)Changed often. (DYNAMIC_DRAW)