graphics3d/toon/toonrenderer
툰 렌더러. (MeshBuilder 와 readGlbArrays 의 배열을 한 색 재질과 바깥선으로 그린다)
Toon renderer. (draws MeshBuilder and readGlbArrays arrays with single-color material and outline)
import { ToonRenderer, MeshBuilder, createSphereGeometry, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 32, 20), Matrix4.createTranslation(0, 0.5, 0), "#f0c8a0", { hasOutline: true });
builder.addPart(createBoxGeometry(3, 0.1, 3), Matrix4.createTranslation(0, -0.05, 0), "#708090", { hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
renderer.setShade({ step: 0.5, feather: 0.02, color: [0.6, 0.55, 0.75], secondStep: 0.2, secondFeather: 0.02, secondColor: [0.4, 0.36, 0.55], isHalfLambert: true });
renderer.setRimLight([0.5, 0.55, 0.7], 3, 0.2, 1);
renderer.setSpecular(0.6, 64, 0, [1, 1, 1]);
renderer.setPointLights([
{ position: [1.5, 1.5, 1], color: [1, 0.7, 0.4], intensity: 2, range: 5 },
{ position: [0, 3, 0], color: [0.6, 0.8, 1], intensity: 3, range: 6, direction: [0, -1, 0], innerConeAngle: 0.3, outerConeAngle: 0.6 },
]);
const matcapTexture = renderer.createTexture({ width: 2, height: 2, data: new Uint8Array([60, 60, 70, 255, 255, 255, 255, 255, 60, 60, 70, 255, 160, 160, 180, 255]) }, { isMipmapped: false, isRepeated: false });
const viewMatrix = Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0.4, 0), Vector3.create(0, 1, 0));
const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
renderer.beginFrameWithMatrices(viewMatrix, projectionMatrix);
renderer.drawMesh(mesh, Matrix4.createIdentity(), { receivesShadow: false, specularScale: 1.5, matcapTexture: matcapTexture, matcapStrength: 0.5 });
renderer.endFrame();ToonRenderer
툰 렌더러. (MeshBuilder 와 readGlbArrays 의 배열을 한 색 재질과 바깥선으로 그린다)
- 빛: ToonLightSet 하나를 기본으로 든다. 해(방향과 색, 그림자), 하늘색과 땅색의 바탕빛, 채움 빛, 점광과 스포트라이트(TOON_MAXIMUM_POINT_LIGHTS 까지), 림 빛, 하이라이트, 빛 꼴(÷π). 셀 셰이딩은 그늘 램프다. (유니티 툰 셰이더의 바탕, 1 차 그늘, 2 차 그늘과 Step, Feather, 그림자는 그늘 색으로 들어간다, 경계는 fwidth 로 계단 없이, 램프 텍스처도 된다) 해는 램프 색을 통째로, 채움 빛과 점광과 스포트라이트는 램프의 밝기 단계를 받는다. 하이라이트와 림은 단단한 툰 꼴에서 부드러운 꼴까지. 셈은 ToonLightSet 머리말에 있다. setLight, setSunDirection, setFillLight, setShade, setShadeRamp, clearShadeRamp, setBandCount, setBandRamp, setRampTexture, setRimLight, setSpecular, setPointLights, setPointLightLimit, setLightModel 은 기본 묶음을 고친다. 그리기마다 options.lightSet 으로 다른 묶음(createLightSet)을 줄 수 있다. (재질마다 그늘 색이 다를 때)
- 노멀: 모형 행렬과 본 행렬의 왼쪽 위 3x3 의 역행렬의 전치로 옮긴다. (늘이고 줄인 모형도 빛이 맞다, 정점 조각이 고친 행렬도 같다)
- 재질: 꼭짓점의 색(sRGB), 빛남(바탕색에 곱해 더함), 빛을 받지 않음. 꼭짓점 UV(arrays.uvData, 2 씩)가 있으면 텍스처를 읽는다.
- 그리기 꼴(options, 기본값이면 지금까지와 같은 화면): tintColor [r, g, b, a] sRGB 와 alpha. tintAmount 를 주면(0 ~ 1) 틴트를 곱하지 않고 sRGB 로 섞는다. (맞은 번쩍임, 고장 빨강, 선형 색 공간은 선형으로 섞는다) glowScale 꼭짓점 빛남의 배(기본 1), colorScale 마지막 선형 색의 배(기본 1, 거울에 비친 모습을 어둡게), emissiveColor [r, g, b] sRGB 와 emissiveIntensity(선형 배, 기본 1, 색 기본 검정). baseColorTexture(바탕색에 곱함, 알파는 불투명도에), emissiveTexture(빛남 색에 곱함), uvTransform [u 옮김, v 옮김, u 배, v 배] (KHR_texture_transform 의 offset, scale). decalTexture 는 바탕색 위에 알파로 덮는다(색 = 텍스처 x decalColor). decalEmission 만큼 그 색으로 빛난다. decalUvTransform 은 묶음 그림의 한 칸을 고를 때. alphaCutoff 는 불투명도가 그보다 작은 화소를 버린다. (0 이면 끔, glTF MASK) blendMode: ToonBlendMode.alpha(기본, 곧은 알파), premultiplied(미리 곱한 알파), additive(더하기). alpha 가 아니면 비치는 것으로 그린다. softEdge 는 pow(|dot(N, V)|, softEdge) 를 불투명도에 곱해 가장자리를 엷게 한다. (0 이면 끔, 프레넬 꼴) isMirrored 는 감기를 뒤집어 그린다. 주지 않으면 모형 행렬의 행렬식이 음수일 때 스스로 뒤집는다. 보기 행렬이 거울에 비쳤으면 그것도 더해 뒤집는다. indexStart, indexCount 는 몸의 꼭짓점 번호 가운데 그 자리만 그린다. (GLB 재질 범위, 숨긴 부분) outlineIndexStart, outlineIndexCount 는 바깥선 껍데기. material(ToonMaterial), textures({ 유니폼 이름: 텍스처 }), onBeforeDraw(program, webGL2RenderingContext, ToonProgramKind) 는 확장 자리다. (toonmaterial.js 머리말) lightSet(ToonLightSet) 은 그 그리기의 빛 묶음이다. receivesShadow (기본 true) 가 false 면 해의 그림자를 보지 않는다. shadeOffset 은 빛을 받는 몫에 더해 그늘 경계를 옮긴다. (길티기어 Xrd 의 꼭짓점 색 문턱, 유니티 툰 셰이더의 Shading Grade Map 꼴) specularScale, rimScale (기본 1) 은 그 그리기의 하이라이트와 림 배다. (0 이면 없음, 재질마다의 세기) matcapTexture 는 보기 공간 노멀로 읽는 매트캡이다. matcapStrength (기본 1), matcapBlend (ToonMatcapBlend.multiply 기본, add) outlineColor [r, g, b, a] sRGB 는 그 그리기의 껍데기 바깥선 색 (주지 않으면 setOutlineColor), outlineWidthScale (기본 1) 은 지은 굵기의 배다. outlineOffsetZ (기본 0) 는 껍데기를 카메라에서 먼 쪽으로 미는 월드 길이다. (몸 앞으로 비치지 않게, 유니티 툰 셰이더의 Offset Z) angelRingTexture 는 천사 고리 텍스처다. u 는 보기 공간 노멀의 x, v 는 2 번 UV 의 y 와 보기 노멀의 y 를 angelRingOffsetV (기본 0.3) 로 섞은 것이다. (유니티 툰 셰이더의 Angel Ring) angelRingColor [r, g, b] (선형 배, 기본 흰색), angelRingOffsetU (0 ~ 0.5, 기본 0), isAngelRingAlpha (기본 false 면 더하고 true 면 텍스처 알파로 덮는다) 천사 고리 UV 는 카메라 기울임만큼 되돌려 돌린다. (readCameraRoll, 유니티 툰 셰이더의 Camera Rolling Stabilizer, 카메라를 기울여도 고리는 머리에 붙어 있다) lineId, hasScreenOutline, hasCreaseLine 은 ToonDrawQueue 가 화면 공간 바깥선에 넘기는 값이다. (렌더러는 읽지 않는다)
- 바깥선 껍데기(inverted hull): MeshBuilder 가 지은 껍데기의 바탕 자리와 미는 쪽(지은 굵기, 같은 자리의 노멀을 평균한 쪽)을 올리고, 셰이더가 outlineWidthScale 만큼 밀어 뒷면만 그린다. setOutlineDistanceScale(기준 거리, 가장 작은 배, 가장 큰 배) 를 주면 카메라까지의 거리 / 기준 거리 를 굵기에 곱해 화면 굵기를 맞춘다. (원근만) setOutlineFadeDistance(가까운 거리, 먼 거리) 를 주면 모형의 자리에서 카메라까지가 먼 거리에 다가갈수록 굵기가 0 이 된다. (smoothstep, 유니티 툰 셰이더의 Nearest, Farthest Distance) 껍데기 색은 빛 묶음의 outline 빛 색 쓰기가 켜져 있으면(기본) 해의 색을 곱한다. (세기가 1 이상이면 세기로 나눈 색, 유니티 툰 셰이더 바깥선과 같다)
- 뼈대: writeSkinPose 가 셈한 본 행렬을 drawMesh 에 넘긴다. (TOON_MAXIMUM_JOINTS 까지)
- GPU 인스턴싱: drawMeshInstanced 로 같은 모형 여럿을 인스턴스마다 행렬과 틴트로 한 번에 그린다. (몸과 바깥선 모두, 그릴 때마다 걸러서 올림) 오래 두는 인스턴스는 createInstanceLayout 과 createInstanceBuffer 로 영구 버퍼를 짓고 drawMeshInstanceBuffer 로 그린다. (버퍼 전체의 경계로 통째 거름, 머티리얼 정점 조각이 사용자 어트리뷰트를 읽음) 고칠 때는 updateInstanceBuffer(전체) 나 updateInstanceBufferRange(일부, bufferSubData). 몸, 바깥선 껍데기, 그림자, 화면 공간 바깥선의 선의 판이 같은 GPU 버퍼를 같이 쓴다.
- 화면 밖 거르기: 모형의 경계 구를 보기와 투영의 절두체에 대어 밖이면 그리지 않는다. (인스턴스는 하나씩 걸러 남은 것만 올린다)
- 그림자: ShadowMap 에 beginShadowPass 와 drawMesh 로 드리우고, setShadow 로 받는다. (3x3 PCF, 치우침은 ShadowMap.setBias 의 텍셀 단위 값에 텍셀 크기와 기울기를 곱한다) 점광과 스포트라이트 그림자는 ShadowAtlas 에 beginShadowAtlasPass, 칸마다 setShadowAtlasTile 과 drawMesh 로 드리우고, setLocalShadows 로 받는다. (점광은 큐브 여섯 칸, 스포트라이트는 원근 한 칸) 그 빛의 받는 몫에 그림자를 곱해 그늘 램프에 넣는다. (해와 같은 꼴) castsShadow 가 true 인 점광만 칸을 받는다. (SHADOW_ATLAS_MAXIMUM_LIGHTS 까지) 그림자를 받지 않을 때도 두 그림자 유닛에 1x1 비교 깊이 텍스처를 묶는다. (sampler2DShadow 유닛에 깊이 텍스처가 없으면 맥 드라이버가 알리고, 색 텍스처가 묶여 있으면 WebGL 이 그리기를 거부한다)
- HDR: setHdrOutput(true) 면 감마를 걸지 않은 선형 색을 낸다. 실수 렌더 타겟(ToonPostProcess)에 그리고 블룸과 톤매핑으로 마무리한다.
- 사용: createMesh(arrays) → 매 프레임 beginFrame(보기와 투영) → drawMesh / drawMeshInstanced → endFrame() → 다 쓰면 deleteMesh. beginFrame 이 앞의 그리기 상태(섞기, 깊이, 면 가리기, 프로그램, 버텍스 어레이)를 적어 두고 깊이 시험과 면 가리기를 켜며, endFrame 이 적어 둔 상태로 돌린다. (엔진 2D 그리기 사이에 끼울 때, 그 전에 Graphic.flushBatch) beginFrameWithMatrices(보기, 투영) 는 두 행렬로 시작한다. (직교 원 행렬 카메라) 카메라의 자리와 보기 돌림(하이라이트, 림, 소프트 엣지, 매트캡)은 보기와 투영에서 읽는다.
- 프로그램마다 프레임 값(보기와 투영, 카메라, 그림자, HDR)과 빛 묶음은 바뀔 때만 올린다. 그리기마다 바뀌는 값(모형 행렬, 틴트, 텍스처)만 매번 올린다.
- readProgramSources(material, instanceLayout) 로 ShaderWarmer 에 넘길 소스를 준다.
- 노드 사각형 안에 그리기: setScreenRect(x, y, 너비, 높이) 를 주면 beginFrame 이 보기와 투영의 클립 공간을 그 사각형으로 옮기고 가위로 밖을 자른다. 사각형은 beginFrame 때의 뷰포트(보통 드로잉 버퍼 전체) 안의 픽셀이고 왼쪽 위가 원점이다. (2D 노드의 draw 에서 graphic.getTransformMatrix 로 셈한 자리) 화면 밖 거르기는 옮기기 전의 절두체로 한다. endFrame 이 가위를 푼다. 카메라의 가로 세로 비는 사각형의 비로 맞춘다. (Camera3D.setAspectRatio)
- beginFrameWithCamera(Camera3D) 는 카메라의 보기와 투영으로 beginFrame 을 부른다. 2D 표시(Camera3D.projectToView)와 같은 카메라를 쓴다.
- drawMeshOutline 은 바깥선 껍데기만 그린다. (ToonDrawQueue 가 불투명한 몸을 다 그린 뒤 바깥선을 몰아 그릴 때, 그린 수는 세지 않는다)
- 텍스처: createTexture(그림이나 { width, height, data }, { isMipmapped, isRepeated, isFiltered, isColorData }) 로 RGBA 텍스처를 짓는다. UV (0, 0) 이 그림의 왼쪽 위다. (glTF 와 같음)
- 색 공간: 생성의 options.colorSpace(기본은 엔진의 EngineConfiguration.colorSpace, 엔진이 없으면 gamma)로 정하고 바뀌지 않는다. (getColorSpace) gamma(기본): 넘기는 색(꼭짓점 색, 틴트, 빛남 색, 데칼 색, 바깥선 색)과 색 텍스처는 sRGB 이고 바탕색, 틴트, 데칼은 sRGB 로 곱하고 섞은 뒤 pow(색, 2.2) 로 선형으로 바꿔 빛을 셈한다. 화면에 낼 때 pow(1 / 2.2) 를 건다. (HDR 출력이면 선형 그대로) linear: 색 텍스처를 sRGB 형식으로 올려 GPU 가 선형으로 풀고, 넘기는 색은 sRGB 표준 곡선(IEC 61966-2-1)으로 선형으로 바꿔 곱하고 섞는다. 화면에 낼 때 같은 곡선으로 sRGB 로 바꾼다. 셰이더 소스마다 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어간다. (ToonPostProcess, ToonScreenOutline 도 같은 값으로 짓는다)
- 텍스처 유닛: 점광 그림자 아틀라스 0, 램프 1, 매트캡 2, 해 그림자 3, 바탕색 4, 빛남 5, 데칼 6, 천사 고리 7, 머티리얼 8 ~ 15. 유닛 0 의 묶음은 beginFrame 이 적어 두고 endFrame 이 돌린다. 유닛마다 묶인 텍스처가 같으면 묶지 않고, 고른 유닛도 그리기마다 0 으로 되돌리지 않는다. (고른 유닛은 endFrame 이 돌린다, 단계 콜백과 onBeforeDraw 에는 유닛 0 을 고른 채 넘긴다)
- 2 번 UV: 배열에 uv1Data 가 있으면 vertexUv 가 (UV, 2 번 UV) 넷이다. 셰이더 조각은 ToonSurface.uv1 로 읽는다. (없으면 (0, 1))
- 빛 색 쓰기(setLightColorUsage), 그늘 쪽 림(setShadeRimLight), 빛 세기 막기(setLightIntensityLimited)는 빛 묶음(ToonLightSet)에 둔다.
Toon renderer. (draws MeshBuilder and readGlbArrays arrays with single-color material and outline)
- Light: holds one ToonLightSet as the default. Sun (direction and color, shadow), ambient light of sky color and ground color, fill light, point lights and spotlights (up to TOON_MAXIMUM_POINT_LIGHTS), rim light, highlight, light model (÷π). Cel shading is a shade ramp. (Base, 1st shade, 2nd shade with Step and Feather of the Unity Toon Shader, shadows enter as the shade color, boundaries without stairs by fwidth, a ramp texture also works) The sun receives the whole ramp color, while the fill light, point lights and spotlights receive the ramp's brightness level. Highlight and rim range from the hard toon form to the soft form. The math is in the ToonLightSet header. setLight, setSunDirection, setFillLight, setShade, setShadeRamp, clearShadeRamp, setBandCount, setBandRamp, setRampTexture, setRimLight, setSpecular, setPointLights, setPointLightLimit, setLightModel change the default set. Another set (createLightSet) can be given per draw with options.lightSet. (When the shade color differs per material)
- Normals: transformed by the transpose of the inverse of the upper left 3x3 of the model matrix and the joint matrix. (Light stays correct on stretched and squashed models, the same goes for matrices changed by the vertex chunk)
- Material: vertex color (sRGB), glow (multiplied by the base color and added), unlit. If vertex UVs (arrays.uvData, 2 each) exist, textures are sampled.
- Draw options (options, defaults give the same image as before):
tintColor [r, g, b, a] sRGB and alpha. If tintAmount (0 ~ 1) is given, the tint is mixed in sRGB instead of multiplied. (Hit flash, broken red, mixed in linear in the linear color space)
glowScale multiplier for vertex glow (default 1), colorScale multiplier for the final linear color (default 1, darkens mirrored reflections), emissiveColor [r, g, b] sRGB and emissiveIntensity (linear multiplier, default 1, color default black).
baseColorTexture (multiplied into base color, alpha into opacity), emissiveTexture (multiplied into glow color), uvTransform [u offset, v offset, u scale, v scale] (offset, scale of KHR_texture_transform).
decalTexture overlays the base color by alpha (color = texture x decalColor). Glows in that color by decalEmission. decalUvTransform is for picking one cell of an atlas.
alphaCutoff discards pixels whose opacity is below it. (0 disables, glTF MASK)
blendMode: ToonBlendMode.alpha (default, straight alpha), premultiplied (premultiplied alpha), additive (additive). If not alpha, drawn as translucent.
softEdge multiplies opacity by pow(|dot(N, V)|, softEdge) to fade the edges. (0 disables, Fresnel style)
isMirrored draws with flipped winding. If not given, flips automatically when the model matrix determinant is negative. If the view matrix is mirrored, that is added to the flip as well.
indexStart, indexCount draw only that span of the body vertex indices. (GLB material range, hidden parts) outlineIndexStart, outlineIndexCount are for the outline shell.
material (ToonMaterial), textures ({ uniform name: texture }), onBeforeDraw(program, webGL2RenderingContext, ToonProgramKind) are extension points. (toonmaterial.js header comment)
lightSet (ToonLightSet) is the light set for that draw.
If receivesShadow (default true) is false, the sun's shadow is not looked up. shadeOffset is added to the received light amount to move the shade boundary. (Vertex color threshold of Guilty Gear Xrd, Shading Grade Map form of the Unity Toon Shader)
specularScale, rimScale (default 1) are the highlight and rim multipliers of that draw. (0 means none, strength per material)
matcapTexture is a matcap read with the view-space normal. matcapStrength (default 1), matcapBlend (ToonMatcapBlend.multiply default, add)
outlineColor [r, g, b, a] sRGB is the shell outline color of that draw (setOutlineColor if not given), outlineWidthScale (default 1) is the multiplier of the built thickness.
outlineOffsetZ (default 0) is the world length the shell is pushed away from the camera. (So it does not show in front of the body, Offset Z of the Unity Toon Shader)
angelRingTexture is the angel ring texture. u is the x of the view-space normal, v is the y of the second UV mixed with the y of the view normal by angelRingOffsetV (default 0.3). (Angel Ring of the Unity Toon Shader)
angelRingColor [r, g, b] (linear multiplier, default white), angelRingOffsetU (0 ~ 0.5, default 0), isAngelRingAlpha (default false adds, true covers with the texture alpha)
The angel ring UV is rotated back by the camera roll. (readCameraRoll, Camera Rolling Stabilizer of the Unity Toon Shader, the ring stays on the head even when the camera is tilted)
lineId, hasScreenOutline, hasCreaseLine are values ToonDrawQueue passes to the screen-space outline. (The renderer does not read them)- Outline shell (inverted hull): uploads the base position and push direction (built thickness, the averaged normal of the same position) of the shell MeshBuilder built, and the shader pushes it by outlineWidthScale and draws only back faces. If setOutlineDistanceScale(reference distance, minimum scale, maximum scale) is given, distance to the camera / reference distance is multiplied into the thickness to keep the screen thickness. (Perspective only) If setOutlineFadeDistance(near distance, far distance) is given, the thickness goes to 0 as the distance from the model position to the camera approaches the far distance. (smoothstep, Nearest and Farthest Distance of the Unity Toon Shader) The shell color is multiplied by the sun color when the outline light color usage of the light set is on (default). (Divided by its intensity when the intensity is 1 or more, same as the Unity Toon Shader outline)
- Skeleton: passes the bone matrices computed by writeSkinPose to drawMesh. (up to TOON_MAXIMUM_JOINTS)
- GPU instancing: drawMeshInstanced draws many copies of the same model at once with a matrix and tint per instance. (both body and outline, culled and uploaded on every draw) Long-lived instances build a persistent buffer with createInstanceLayout and createInstanceBuffer and are drawn with drawMeshInstanceBuffer. (Culled as a whole by the bounds of the entire buffer, the material vertex chunk reads user attributes) To change it use updateInstanceBuffer (whole) or updateInstanceBufferRange (part, bufferSubData). The body, outline shell, shadows and the screen-space outline's line target share the same GPU buffer.
- Off-screen culling: tests the model's bounding sphere against the view-projection frustum and skips drawing if outside. (instances are culled one by one and only the rest are uploaded)
- Shadows: cast into a ShadowMap with beginShadowPass and drawMesh, received with setShadow. (3x3 PCF, the bias is the texel-unit value of ShadowMap.setBias multiplied by the texel size and slope) Point light and spotlight shadows are cast into a ShadowAtlas with beginShadowAtlasPass and, per tile, setShadowAtlasTile and drawMesh, and received with setLocalShadows. (A point light uses six cube tiles, a spotlight one perspective tile) The shadow is multiplied into that light's received amount and goes into the shade ramp. (Same form as the sun) Only point lights with castsShadow true get tiles. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS) Even when shadows are not received, a 1x1 comparison depth texture is bound to both shadow units. (Without a depth texture on a sampler2DShadow unit the Mac driver reports it, and if a color texture is bound WebGL refuses to draw)
- HDR: setHdrOutput(true) outputs linear color without gamma. Draw into a float render target (ToonPostProcess) and finish with bloom and tone mapping.
- Usage: createMesh(arrays) → every frame beginFrame(view and projection) → drawMesh / drawMeshInstanced → endFrame() → deleteMesh when done. beginFrame records the previous draw state (blending, depth, face culling, program, vertex array) and enables depth testing and face culling, and endFrame restores the recorded state. (When inserted between engine 2D drawing, call Graphic.flushBatch before it) beginFrameWithMatrices(view, projection) starts with two matrices. (Orthographic or raw matrix camera) The camera position and view rotation (highlight, rim, soft edge, matcap) are read from the view and projection.
- Per program, frame values (view and projection, camera, shadow, HDR) and the light set are uploaded only when they change. Only per-draw values (model matrix, tint, textures) are uploaded every time.
- readProgramSources(material, instanceLayout) provides the sources to pass to ShaderWarmer.
- Drawing inside a node rectangle: given setScreenRect(x, y, width, height), beginFrame moves the view-projection clip space into that rectangle and scissors out the rest. The rectangle is in pixels within the viewport at beginFrame time (usually the whole drawing buffer), with the origin at the top left. (position computed with graphic.getTransformMatrix in a 2D node's draw) Off-screen culling uses the frustum before the move. endFrame releases the scissor. The camera's aspect ratio is matched to the rectangle's ratio. (Camera3D.setAspectRatio)
- beginFrameWithCamera(Camera3D) calls beginFrame with the camera's view and projection. Uses the same camera as 2D display (Camera3D.projectToView).
- drawMeshOutline draws only the outline shell. (when ToonDrawQueue draws all outlines together after drawing every opaque body, draws are not counted)
- Textures: createTexture(image or { width, height, data }, { isMipmapped, isRepeated, isFiltered, isColorData }) builds an RGBA texture. UV (0, 0) is the top left of the image. (Same as glTF)
- Color space: set by the constructor's options.colorSpace (default is the engine's EngineConfiguration.colorSpace, gamma without an engine) and never changes. (getColorSpace) gamma (default): passed colors (vertex color, tint, glow color, decal color, outline color) and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB, then converted to linear with pow(color, 2.2) for lighting. pow(1 / 2.2) is applied for screen output. (Linear as is for HDR output) linear: color textures are uploaded in an sRGB format and the GPU decodes them to linear; passed colors are converted to linear with the sRGB standard curve (IEC 61966-2-1) before multiplying and mixing. Screen output is converted back to sRGB with the same curve. Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (Build ToonPostProcess and ToonScreenOutline with the same value)
- Texture units: point light shadow atlas 0, ramp 1, matcap 2, sun shadow 3, base color 4, glow 5, decal 6, angel ring 7, material 8 ~ 15. beginFrame notes the binding of unit 0 and endFrame restores it. A unit is not rebound when it already holds the same texture, and draws do not switch the active unit back to 0. (endFrame restores the active unit; stage callbacks and onBeforeDraw are called with unit 0 active)
- Second UV: if the arrays have uv1Data, vertexUv is four values (UV, second UV). Shader chunks read it as ToonSurface.uv1. ((0, 1) if none)
- Light color usage (setLightColorUsage), shade-side rim (setShadeRimLight) and light intensity limit (setLightIntensityLimited) live in the light set (ToonLightSet).
import { ToonRenderer, MeshBuilder, createCapsuleGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
renderer.setLight([-0.4, -1, -0.3], [1, 0.96, 0.9], [0.45, 0.5, 0.6], [0.25, 0.22, 0.2]);
renderer.setOutlineColor([0.1, 0.06, 0.08, 1]);
const builder = new MeshBuilder();
builder.addPart(createCapsuleGeometry(0.3, 0.6, 8, 16), Matrix4.createIdentity(), "#a0d0a0", { outlineWidth: 0.02 });
const mesh = renderer.createMesh(builder.readArrays());
webGL2RenderingContext.clearColor(0.9, 0.9, 0.95, 1);
webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT | webGL2RenderingContext.DEPTH_BUFFER_BIT);
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(mesh, Matrix4.createIdentity());
renderer.drawMesh(mesh, Matrix4.createTranslation(0, 0, 50));
renderer.endFrame();
const statistics = renderer.getFrameStatistics();
if (statistics.drawnObjectCount !== 1 || statistics.culledObjectCount !== 1) {
throw new Error("unexpected statistics");
}
renderer.deleteMesh(mesh);
renderer.destroy();생성.
Constructor.
- webGL2RenderingContextWebGL2RenderingContext
- 그릴 WebGL2 렌더링 컨텍스트.WebGL2 rendering context to draw with.
- optionsobject | null
- { colorSpace (ColorSpace, 기본은 엔진의 색 공간 EngineConfiguration.colorSpace, 엔진이 없으면 gamma) }{ colorSpace (ColorSpace, default is the engine's color space EngineConfiguration.colorSpace, gamma without an engine) }
짝Counterpart: vanilla-engine ToonRenderer.new
static readProgramSources(material = null, instanceLayout = null, isAmbientOcclusion = false, colorSpace = readEngineColorSpace())#셰이더 소스 반환. (ShaderWarmer 로 미리 링크할 때, 머티리얼과 인스턴스 꼴이 없으면 기본 프로그램)
Returns shader sources. (for pre-linking with ShaderWarmer, default programs if no material or instance layout)
- materialToonMaterial | null
- 셰이더 조각을 끼울 머티리얼. (기본 null)Material to insert shader chunks with. (Default null)
- instanceLayoutToonInstanceLayout | null
- 인스턴스 꼴. (기본 null)Instance layout. (Default null)
- isAmbientOcclusionboolean
- 모서리 어둠을 켠 프레임의 몸 프로그램인지. (기본 false, setAmbientOcclusionTexture 로 텍스처를 건 프레임은 이 몸 프로그램을 쓴다)Whether this is the body program for frames with ambient occlusion on. (default false, frames with a texture set by setAmbientOcclusionTexture use this body program)
- colorSpacestring
- 색 공간. (ColorSpace, 기본은 엔진의 색 공간, 렌더러가 짓는 것과 같은 값을 준다)Color space. (ColorSpace, default is the engine's color space, give the same value the renderer builds with)
반환ReturnsArray<object> { vertexShader, fragmentShader, attributeLocationTable } 의 배열. (몸, 바깥선, 그림자 깊이)Array of { vertexShader, fragmentShader, attributeLocationTable }. (body, outline, shadow depth)
짝Counterpart: vanilla-engine ToonRenderer.read_program_sources
import { ToonRenderer, ToonMaterial, ShaderWarmer } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const material = new ToonMaterial({ name: "warm", surfaceChunk: "void applySurface(inout ToonSurface surface) { surface.baseColor *= vec3(1.1, 1.0, 0.9); }" });
const shaderWarmer = new ShaderWarmer(webGL2RenderingContext, ToonRenderer.readProgramSources().concat(ToonRenderer.readProgramSources(material)));
shaderWarmer.update();
const renderer = new ToonRenderer(webGL2RenderingContext);
renderer.prepareMaterial(material);머티리얼 짓기. (셰이더 조각, toonmaterial.js 머리말)
Creates a material. (shader snippets, toonmaterial.js header comment)
- chunksobject
- { name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (없는 칸은 빈 글){ name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (missing slots are empty strings)
반환ReturnsToonMaterial 지은 머티리얼.The built material.
짝Counterpart: vanilla-engine ToonRenderer.create_material
머티리얼의 프로그램을 미리 짓기. (처음 그릴 때의 멈춤을 피할 때, 짓지 못하면 false)
Prebuilds a material's programs. (to avoid a stall on first draw, false on failure)
- materialToonMaterial | null
- 미리 지을 머티리얼. (null 이면 기본 프로그램)Material to build in advance. (Default program if null)
- instanceLayoutToonInstanceLayout | null
- 함께 쓸 인스턴스 꼴. (기본 null)Instance layout to use with it. (Default null)
반환Returnsboolean 짓지 못하면 false.false if it could not be built.
짝Counterpart: vanilla-engine ToonRenderer.prepare_material
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const material = renderer.createMaterial({
name: "checker",
surfaceChunk: "void applySurface(inout ToonSurface surface) { vec3 cell = floor(surface.worldPosition * 4.0); surface.baseColor *= mod(cell.x + cell.y + cell.z, 2.0) < 1.0 ? 0.7 : 1.0; }",
});
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
const isReady = renderer.prepareMaterial(material) && renderer.prepareMaterial(material, instanceLayout);
if (!isReady) {
renderer.deleteMaterial(material);
}처음 보는 몸 변형을 맡기고 기본 몸으로 그릴지. (기본 true, KHR_parallel_shader_compile 이 없으면 이 값과 상관없이 그 자리에서 짓는다)
Whether to hand off a body variant first seen and draw with the default body meanwhile. (Default true; without KHR_parallel_shader_compile it is built on the spot regardless of this value)
- isAsyncboolean
- true 면 장면 중간에 처음 보는 몸 변형을 그 자리에서 짓지 않고, 다 지어질 때까지 전부 켠 기본 몸(같은 화면)으로 그린다. false 면 그 자리에서 짓고 기다린다.If true, a body variant first seen mid-scene is not built on the spot; it is drawn with the default body with every feature on (same picture) until it finishes building. If false, it is built on the spot and waited for.
짝Counterpart: vanilla-engine ToonRenderer.set_async_program_build
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setAsyncProgramBuild(false);
if (renderer.isAsyncProgramBuild() !== false) {
throw new Error("async program build must be off");
}처음 보는 몸 변형을 맡기고 기본 몸으로 그리는지 읽기.
Reads whether a body variant first seen is handed off and the default body is drawn meanwhile.
반환Returnsboolean 처음 보는 몸 변형을 맡기고 기본 몸으로 그리면 true.True if a body variant first seen is handed off and the default body is drawn meanwhile.
짝Counterpart: vanilla-engine ToonRenderer.is_async_program_build
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
if (typeof renderer.isAsyncProgramBuild() !== "boolean") {
throw new Error("not boolean");
}그리기 줄에 담긴 것이 쓸 프로그램 변형을 그리지 않고 미리 짓기. (유니티 ShaderVariantCollection.WarmUp, 언리얼 PSO 캐시 꼴)
- 머티리얼, 인스턴스 꼴, 몸 기능 비트(빛 묶음과 그리기 꼴이 정함), 모서리 어둠 몸, 바깥선, 그림자 깊이를 그리기 줄이 그릴 때와 같은 열쇠로 짓는다.
- 첫 그리기에서 처음 보는 조합의 프로그램을 짓느라 한 프레임이 끊기는 것을 불러오는 동안으로 옮긴다. 장면을 담은 뒤 첫 프레임 앞에서 한 번 부른다.
- KHR_parallel_shader_compile 이 있으면 컴파일만 맡기고 프레임마다 끝났는지 물어 주 스레드를 막지 않는다. 없으면 이 호출 안에서 짓는다.
- 미리 짓기가 끝나기 전에 그려도 된다. 아직 안 지어진 변형은 그 자리에서 지어 쓴다. (동작은 같다)
Prewarms, without drawing, the program variants that the items in a draw queue will use. (Same idea as Unity ShaderVariantCollection.WarmUp and Unreal PSO caches)
- Builds the material, instance layout, body feature bits (decided by the light set and draw options), ambient occlusion body, outline and shadow depth programs with the same keys the draw queue uses when drawing.
- Moves the one-frame hitch of building a program for a combination first seen in the first draw into loading time. Call it once after adding the scene and before the first frame.
- With KHR_parallel_shader_compile it only hands off compiling and polls for completion each frame so the main thread is not blocked. Without it, programs are built inside this call.
- Drawing before the prewarm finishes is fine. A variant not built yet is built on the spot. (Same behavior)
- queueToonDrawQueue
- 변형을 읽을 그리기 줄. (담은 것만 읽고 그리지 않는다)Draw queue to read the variants from. (Only reads what was added; does not draw)
- optionsobject
- 게임이 장면 중간에 쓸 조합 목록. (유니티 ShaderVariantCollection 처럼, 기본은 빈 객체)List of combinations the game will use mid-scene. (Like Unity ShaderVariantCollection; default is an empty object)
반환ReturnsToonProgramPrewarm 미리 짓기의 진행. (isReady, wait)Progress of the prewarm. (isReady, wait)
짝Counterpart: vanilla-engine ToonRenderer.prewarm_draw_queue
import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#f0e8e0");
const mesh = renderer.createMesh(builder.readArrays());
const queue = new ToonDrawQueue();
queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
const prewarm = renderer.prewarmDrawQueue(queue);
prewarm.wait().then(() => {
if (!prewarm.isReady()) {
throw new Error("prewarm is not ready");
}
});import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#f0e8e0");
const mesh = renderer.createMesh(builder.readArrays());
const queue = new ToonDrawQueue();
queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
const prewarm = renderer.prewarmDrawQueue(queue, { lightFeatureList: [["rim"], ["rim", "shadeRim"]] });
prewarm.wait().then(() => {
if (!prewarm.isReady()) {
throw new Error("prewarm is not ready");
}
});머티리얼의 프로그램 지우기. (모든 인스턴스 꼴의 것, 다시 그리면 새로 짓는다)
Deletes a material's programs. (for all instance layouts, rebuilt when drawn again)
- materialToonMaterial
- 프로그램을 지울 머티리얼.Material whose programs to delete.
짝Counterpart: vanilla-engine ToonRenderer.delete_material
빛 묶음 짓기. (그리기마다 options.lightSet 으로 줄 것, 기본 빛과 같은 값으로 시작)
Creates a light set. (to pass per draw via options.lightSet, starts with the same values as the default lighting)
반환ReturnsToonLightSet 기본 빛과 같은 값으로 시작하는 새 빛 묶음.A new light set starting with the same values as the default light.
짝Counterpart: vanilla-engine ToonRenderer.create_light_set
기본 빛 묶음 반환.
Returns the default light set.
반환ReturnsToonLightSet 기본 빛 묶음.The default light set.
짝Counterpart: vanilla-engine ToonRenderer.get_light_set
인스턴스 꼴 짓기. ([{ name, size }], toonmaterial.js 의 ToonInstanceLayout)
Creates an instance layout. ([{ name, size }], ToonInstanceLayout in toonmaterial.js)
- attributesArray<object>
- { name, size } 의 배열.Array of { name, size }.
반환ReturnsToonInstanceLayout 지은 인스턴스 꼴.The built instance layout.
짝Counterpart: vanilla-engine ToonRenderer.create_instance_layout
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceOffset", size: 3 }, { name: "instanceTint", size: 4 }]);
const material = renderer.createMaterial({
name: "offset",
vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.modelMatrix[3].xyz += instanceOffset; }",
});
if (!renderer.prepareMaterial(material, instanceLayout) || instanceLayout.getFloatCount() !== 7) {
throw new Error("layout failed");
}영구 인스턴스 버퍼 짓기. (꼴의 수 개수씩 담은 data, ToonBufferUsage.static 이면 한 번 올리고 오래 그림)
Creates a persistent instance buffer. (data holding the layout's value count per instance, with ToonBufferUsage.static it is uploaded once and drawn for a long time)
- instanceLayoutToonInstanceLayout
- 인스턴스 하나의 꼴.Layout of one instance.
- dataFloat32Array
- 꼴의 수 개수씩 인스턴스를 이어 담은 수.Numbers of instances stored one after another, layout float count each.
- usagestring
- ToonBufferUsage 의 값. (기본 static)Value of ToonBufferUsage. (Default static)
반환Returnsobject 인스턴스 버퍼. ({ layout, buffer, usage, floatCount, vertexArrays, generation, bounds, data, renderer })
generation 은 고치거나 지울 때마다 1 씩 는다. (그림자 캐시가 버퍼 바뀜을 안다) bounds 는 버퍼 전체의 경계다. (꼴에 행렬이 있을 때만, 아니면 null)
data 는 경계를 다시 셀 사본이다. (행렬이 있을 때만, 고치지 않는다) 그리는 길(drawMeshInstanceBuffer, ToonScreenOutline.drawMeshInstanceBuffer, ToonDrawQueue.addMeshInstanceBuffer)이 모두 이 한 GPU 버퍼를 같이 쓰고 다시 올리지 않는다.Instance buffer. ({ layout, buffer, usage, floatCount, vertexArrays, generation, bounds, data, renderer })
generation grows by 1 each time it is changed or deleted. (The shadow cache learns the buffer changed) bounds is the bounds of the entire buffer. (Only when the layout has a matrix, otherwise null)
data is a copy for recomputing the bounds. (Only when there is a matrix, do not change it) All drawing paths (drawMeshInstanceBuffer, ToonScreenOutline.drawMeshInstanceBuffer, ToonDrawQueue.addMeshInstanceBuffer) share this one GPU buffer and do not upload it again.
짝Counterpart: vanilla-engine ToonRenderer.create_instance_buffer
import { ToonRenderer, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
const floatCount = instanceLayout.getFloatCount();
const data = new Float32Array(floatCount * 9);
for (let index = 0; index < 9; ++index) {
data.set(Matrix4.createTranslation(index % 3 - 1, 0, Math.floor(index / 3) - 1).getElements(), index * floatCount);
data.set([1, 1 - index * 0.05, 1, 1], index * floatCount + 16);
}
const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);인스턴스 버퍼 고치기. (전체를 다시 올림)
Updates an instance buffer. (re-uploads the whole thing)
- instanceBufferobject
- createInstanceBuffer 의 결과.Result of createInstanceBuffer.
- dataFloat32Array
- 새 수. (인스턴스 수가 바뀌어도 된다)New numbers. (The instance count may change)
짝Counterpart: vanilla-engine ToonRenderer.update_instance_buffer
인스턴스 버퍼의 일부 고치기. (firstInstance 번째부터 data 의 인스턴스 수만큼만 올림, bufferSubData)
Changes part of an instance buffer. (Uploads only as many instances as data holds, starting at the firstInstance-th, bufferSubData)
- instanceBufferobject
- createInstanceBuffer 의 결과.Result of createInstanceBuffer.
- firstInstancenumber
- 고칠 첫 인스턴스 번호. (0 부터)Number of the first instance to change. (From 0)
- dataFloat32Array
- 꼴의 수 개수씩 고칠 인스턴스를 이어 담은 수. (버퍼에 든 인스턴스 수를 넘으면 던진다, 늘리려면 updateInstanceBuffer)Values holding the instances to change one after another, the layout's value count each. (Throws if it goes past the number of instances in the buffer, use updateInstanceBuffer to grow it)
짝Counterpart: vanilla-engine ToonRenderer.update_instance_buffer_range
import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098");
const rockMesh = renderer.createMesh(builder.readArrays());
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
const data = new Float32Array(20 * 3);
for (let index = 0; index < 3; ++index) {
data.set(Matrix4.createTranslation(index - 1, 0, 0).getElements(), index * 20);
data.set([1, 1, 1, 1], index * 20 + 16);
}
const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data, "dynamic");
const moved = new Float32Array(20);
moved.set(Matrix4.createTranslation(0, 0.5, 0).getElements(), 0);
moved.set([1, 0.6, 0.6, 1], 16);
renderer.updateInstanceBufferRange(instanceBuffer, 1, moved);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 2, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
renderer.drawMeshInstanceBuffer(rockMesh, instanceBuffer, 3);
renderer.endFrame();
if (instanceBuffer.generation !== 1) {
throw new Error("generation failed");
}인스턴스 버퍼 지우기. (그 버퍼로 지은 버텍스 어레이도, 모형보다 먼저 지운다, 지운 버퍼로 그리면 아무것도 그리지 않는다)
Deletes an instance buffer. (also the vertex arrays built with it, delete before the model, drawing with a deleted buffer draws nothing)
- instanceBufferobject
- createInstanceBuffer 의 결과.Result of createInstanceBuffer.
짝Counterpart: vanilla-engine ToonRenderer.delete_instance_buffer
텍스처 짓기. (ImageBitmap, 캔버스, 이미지, ImageData 나 { width, height, data: Uint8Array RGBA })
- 선형 색 공간(ColorSpace.linear)이면 색 텍스처(바탕색, 빛남, 데칼, 매트캡, 천사 고리, 램프)를 sRGB 형식(SRGB8_ALPHA8)으로 올린다. GPU 가 읽을 때 선형으로 풀어 거르기와 밉맵이 선형 공간에서 일어나고, 셰이더는 받은 값을 선형 색으로 그대로 쓴다. (유니티, 언리얼의 sRGB 텍스처와 같음) 노멀, 마스크, 번호 같은 자료 텍스처는 isColorData: false 로 RGBA8 에 그대로 올린다. (머티리얼 조각이 읽는 자료)
- 감마 색 공간(기본)은 isColorData 와 상관없이 RGBA 로 올리고 셰이더가 색 텍스처를 pow 2.2 로 선형으로 바꾼다. (지금까지와 같음)
Builds a texture. (ImageBitmap, canvas, image, ImageData or { width, height, data: Uint8Array RGBA })
- In the linear color space (ColorSpace.linear), color textures (base color, glow, decal, matcap, angel ring, ramp) are uploaded in an sRGB format (SRGB8_ALPHA8). The GPU decodes them to linear when reading, so filtering and mipmaps happen in linear space, and the shader uses the received value as a linear color as is. (Same as sRGB textures in Unity and Unreal) Data textures such as normals, masks and IDs are uploaded as is to RGBA8 with isColorData: false. (Data read by material chunks)
- The gamma color space (default) uploads as RGBA regardless of isColorData, and the shader converts color textures to linear with pow 2.2. (Same as before)
- sourceobject
- ImageBitmap, 캔버스, 이미지, ImageData 나 { width, height, data }.ImageBitmap, canvas, image, ImageData or { width, height, data }.
- optionsobject
- { isMipmapped (기본 true), isRepeated (기본 true, false 면 가장자리 붙임), isFiltered (기본 true, false 면 가까운 화소), isColorData (기본 true 면 색, false 면 노멀이나 마스크 같은 자료, 선형 색 공간에서만 가른다) }{ isMipmapped (default true), isRepeated (default true, false clamps to the edge), isFiltered (default true, false uses the nearest pixel), isColorData (default true is color, false is data such as normals or masks, only distinguished in the linear color space) }
반환ReturnsWebGLTexture 지은 RGBA 텍스처.The built RGBA texture.
짝Counterpart: vanilla-engine ToonRenderer.create_texture
import { ToonRenderer, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const canvas = document.createElement("canvas");
canvas.width = 64;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = "#f0e0c0";
context.fillRect(0, 0, 64, 64);
context.fillStyle = "#c04040";
context.fillRect(0, 0, 32, 32);
const baseColorTexture = renderer.createTexture(canvas, { isRepeated: true });
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#ffffff", { 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(), { baseColorTexture: baseColorTexture, uvTransform: [0, 0, 2, 2] });
renderer.endFrame();
renderer.deleteTexture(baseColorTexture);텍스처 지우기.
Deletes a texture.
- textureWebGLTexture | null
- 지울 텍스처. (null 이면 하지 않는다)Texture to delete. (Does nothing if null)
짝Counterpart: vanilla-engine ToonRenderer.delete_texture
모형 올리기. (MeshBuilder.readArrays 나 readGlbArrays 의 결과, 몸이 비면 null)
Uploads a model. (result of MeshBuilder.readArrays or readGlbArrays, null if the body is empty)
- arraysobject
- MeshBuilder.readArrays 나 readGlbArrays 의 결과.Result of MeshBuilder.readArrays or readGlbArrays.
반환Returnsobject | null GPU 에 올린 모형. (몸의 꼭짓점 번호가 비면 null)Model uploaded to the GPU. (null if the body has no vertex indices)
짝Counterpart: vanilla-engine ToonRenderer.create_mesh
import { ToonRenderer, MeshBuilder, createBoxGeometry, createSphereGeometry, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(0.8, 1, 0.5), Matrix4.createTranslation(0, 0.5, 0), "#6080c0", { hasOutline: true });
builder.addPart(createSphereGeometry(0.3, 20, 14), Matrix4.createTranslation(0, 1.3, 0), "#f0d0b0", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
if (mesh === null) {
throw new Error("empty mesh");
}
renderer.deleteMesh(mesh);빈 그림자 텍스처 짓기. (1x1 깊이 1, 비교 샘플링)
Creates the empty shadow texture. (1x1 depth 1, comparison sampling)
반환ReturnsWebGLTexture 1x1 비교 깊이 텍스처.1x1 comparison depth texture.
렌더러 지우기. (모든 프로그램과 빈 텍스처, 모형과 인스턴스 버퍼와 텍스처는 따로)
Deletes the renderer. (all programs and the empty texture, models, instance buffers and textures are deleted separately)
짝Counterpart: vanilla-engine ToonRenderer.destroy
모형 지우기.
Deletes a model.
- meshobject | null
- createMesh 의 결과. (null 이면 하지 않는다)Result of createMesh. (Does nothing if null)
짝Counterpart: vanilla-engine ToonRenderer.delete_mesh
그리기 전의 상태 적어 두기.
Records the state before drawing.
적어 둔 상태로 돌리기.
Restores the recorded state.
- isFramebufferRestoredboolean
- 프레임버퍼와 뷰포트도 돌릴지.Whether to restore the framebuffer and viewport too.
프레임의 그리기 상태 걸기. (섞기 끔, 깊이 시험 LEQUAL 과 쓰기, 뒷면 가리기, 앞면 CCW, ToonDrawQueue 가 단계 콜백 뒤에 다시 건다)
Applies the frame's draw state. (blending off, depth test LEQUAL and depth write, back-face culling, front face CCW, ToonDrawQueue reapplies it after stage callbacks)
짝Counterpart: vanilla-engine ToonRenderer.apply_frame_state
프레임 시작. (보기와 투영과 절두체를 정하고, 앞의 상태를 적어 둔 뒤 깊이 시험과 면 가리기를 켠다, 깊이를 비우는 것은 부르는 쪽이 정한다)
Begins a frame. (sets view, projection and frustum, records the previous state, then enables depth testing and face culling, the caller decides whether to clear depth)
- viewProjectionMatrixMatrix4
- 보기와 투영 행렬. (투영 x 보기)View and projection matrix. (Projection x view)
짝Counterpart: vanilla-engine ToonRenderer.begin_frame
프레임 끝. (적어 둔 상태로 돌린다)
Ends a frame. (restores the recorded state)
짝Counterpart: vanilla-engine ToonRenderer.end_frame
카메라로 프레임 시작. (Camera3D 의 보기와 투영으로 beginFrame)
Begins a frame with a camera. (beginFrame with the Camera3D's view and projection)
- cameraobject
- Camera3D. (보기와 투영을 읽는다)Camera3D. (Reads view and projection)
짝Counterpart: vanilla-engine ToonRenderer.begin_frame_with_camera
import { ToonRenderer, MeshBuilder, createCylinderGeometry, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createCylinderGeometry(0.4, 0.4, 1, 24), Matrix4.createIdentity(), "#c0a0e0", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
const camera = new Camera3D();
camera.setPerspective(0.8, 0.1, 100);
camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0));
renderer.beginFrameWithCamera(camera);
renderer.drawMesh(mesh, Matrix4.createIdentity());
renderer.endFrame();보기와 투영 행렬로 프레임 시작. (Camera3D 없이, 투영 x 보기로 beginFrame)
Begins a frame with view and projection matrices. (without Camera3D, beginFrame with projection x view)
- viewMatrixMatrix4
- 보기 행렬.View matrix.
- projectionMatrixMatrix4
- 투영 행렬.Projection matrix.
짝Counterpart: vanilla-engine ToonRenderer.begin_frame_with_matrices
이번 프레임의 카메라 반환. (보기와 투영에서 읽은 것)
Returns this frame's camera. (read from view and projection)
반환Returnsobject 이번 프레임의 카메라. ({ position [x, y, z, w(1 원근, 0 직교)], forward, isMirrored })Camera of this frame. ({ position [x, y, z, w (1 perspective, 0 orthographic)], forward, isMirrored })
짝Counterpart: vanilla-engine ToonRenderer.get_frame_camera
그릴 화면 사각형 설정. (뷰포트 픽셀, 왼쪽 위 원점, 다음 beginFrame 부터)
Sets the screen rectangle to draw into. (viewport pixels, top-left origin, from the next beginFrame)
- xnumber
- 왼쪽 끝. (뷰포트 픽셀)Left edge. (Viewport pixels)
- ynumber
- 위쪽 끝. (뷰포트 픽셀, 위가 0)Top edge. (Viewport pixels, top is 0)
- widthnumber
- 너비. (픽셀)Width. (pixels)
- heightnumber
- 높이. (픽셀)Height. (pixels)
짝Counterpart: vanilla-engine ToonRenderer.set_screen_rect
import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 240;
const renderer = new ToonRenderer(canvas.getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createOctahedronGeometry(0.6), Matrix4.createIdentity(), "#60c0a0", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
renderer.setScreenRect(200, 16, 104, 78);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 104 / 78, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createIdentity());
renderer.endFrame();
renderer.clearScreenRect();그릴 화면 사각형 풀기. (뷰포트 전체에 그림)
Clears the screen rectangle to draw into. (draws to the whole viewport)
짝Counterpart: vanilla-engine ToonRenderer.clear_screen_rect
그릴 화면 사각형 반환. (없으면 null)
Returns the screen rectangle to draw into. (null if none)
반환Returnsobject | null 그릴 화면 사각형. ({ x, y, width, height }, 없으면 null)Screen rectangle to draw in. ({ x, y, width, height }, null if none)
짝Counterpart: vanilla-engine ToonRenderer.get_screen_rect
그림자 깊이 패스 시작. (ShadowMap 의 프레임버퍼에 빛의 보기와 투영으로, 앞의 프레임버퍼와 뷰포트는 endShadowPass 가 돌린다)
Begins the shadow depth pass. (into the ShadowMap's framebuffer with the light's view and projection, endShadowPass restores the previous framebuffer and viewport)
- shadowMapobject
- ShadowMap. (깊이를 그릴 곳, updateLightMatrix 로 빛 행렬을 정해 둔다)ShadowMap. (Where depth is drawn, the light matrix is set beforehand with updateLightMatrix)
짝Counterpart: vanilla-engine ToonRenderer.begin_shadow_pass
import { ToonRenderer, MeshBuilder, createBoxGeometry, ShadowMap, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(0.6, 0.6, 0.6), Matrix4.createTranslation(0, 0.6, 0), "#e0b080", { hasOutline: true });
builder.addPart(createBoxGeometry(4, 0.1, 4), Matrix4.createTranslation(0, -0.05, 0), "#a0b0a0", { hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
const sunDirection = renderer.getSunDirection();
shadowMap.updateLightMatrix(Vector3.create(0, 0, 0), Vector3.create(sunDirection[0], sunDirection[1], sunDirection[2]), 3, 0.5, 20);
renderer.beginShadowPass(shadowMap);
renderer.drawMesh(mesh, Matrix4.createIdentity());
renderer.endShadowPass();
renderer.setShadow(shadowMap, 0.7);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(2, 3, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
renderer.drawMesh(mesh, Matrix4.createIdentity());
renderer.endFrame();그림자 아틀라스 깊이 패스 시작. (아틀라스를 묶어 비우고 앞의 상태를 적어 둔다, 칸마다 setShadowAtlasTile 뒤에 drawMesh 가 깊이만 그린다, 끝은 endShadowPass)
Start the shadow atlas depth pass. (Binds and clears the atlas and notes the previous state, after setShadowAtlasTile per tile drawMesh draws only depth, end with endShadowPass)
- shadowAtlasobject
- ShadowAtlas.
짝Counterpart: vanilla-engine ToonRenderer.begin_shadow_atlas_pass
import { ToonRenderer, MeshBuilder, createBoxGeometry, ShadowAtlas, Matrix4 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createTranslation(0, 0.5, 0), "#c0a080", { hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
renderer.setPointLights([{ position: [0, 2.5, 1], color: [1, 0.8, 0.6], intensity: 3, range: 8, castsShadow: true }]);
const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 1024);
shadowAtlas.updateLights(renderer.getLightSet().getPointLights());
renderer.beginShadowAtlasPass(shadowAtlas);
for (let tileIndex = 0; tileIndex < shadowAtlas.getTileCount(); ++tileIndex) {
renderer.setShadowAtlasTile(shadowAtlas, tileIndex);
renderer.drawMesh(mesh, Matrix4.createIdentity());
}
renderer.endShadowPass();
renderer.setLocalShadows(shadowAtlas, 1);그림자 아틀라스의 칸 고르기. (그 칸의 보기와 투영과 절두체, 뷰포트를 건다, beginShadowAtlasPass 와 endShadowPass 사이)
Select a tile of the shadow atlas. (Sets that tile's view, projection, frustum and viewport, between beginShadowAtlasPass and endShadowPass)
- shadowAtlasobject
- ShadowAtlas.
- tileIndexnumber
- 칸 번호.Tile number.
짝Counterpart: vanilla-engine ToonRenderer.set_shadow_atlas_tile
그림자 깊이 패스 끝. (프레임버퍼와 뷰포트와 상태를 돌린다)
Ends the shadow depth pass. (restores the framebuffer, viewport and state)
짝Counterpart: vanilla-engine ToonRenderer.end_shadow_pass
경계 구가 절두체 안에 드는지. (모형 행렬로 옮긴 가운데, 가장 큰 크기를 곱한 반지름)
Whether the bounding sphere is inside the frustum. (center transformed by the model matrix, radius multiplied by the largest scale)
- meshobject
- createMesh 의 결과.Result of createMesh.
- modelElementsFloat32Array
- 모형 행렬의 수 16.The 16 numbers of the model matrix.
반환Returnsboolean 절두체 안에 들면 true.true if inside the frustum.
짝Counterpart: vanilla-engine ToonRenderer.is_visible
모형 하나 그리기. (그림자 패스면 깊이만, 화면 밖이면 건너뛴다)
Draws one model. (depth only in the shadow pass, skipped if off-screen)
- meshobject
- createMesh 의 결과.Result of createMesh.
- modelMatrixMatrix4
- 모형 행렬.Model matrix.
- optionsobject
- 클래스 머리말의 그리기 꼴과 jointMatrices Float32Array, hasOutline (기본 true), isCulled (기본 true)Draw options from the class header comment plus jointMatrices Float32Array, hasOutline (default true), isCulled (default true)
짝Counterpart: vanilla-engine ToonRenderer.draw_mesh
import { ToonRenderer, MeshBuilder, createRoundedBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createRoundedBoxGeometry(0.8, 0.8, 0.8, 4, 0.1), Matrix4.createIdentity(), "#e0e0e0", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createTranslation(-1, 0, 0), { tintColor: [1, 0.6, 0.6, 1], outlineColor: [0.4, 0.05, 0.05, 1], outlineWidthScale: 1.5 });
renderer.drawMesh(mesh, Matrix4.createTranslation(0, 0, 0), { tintColor: [1, 0.2, 0.2, 1], tintAmount: 0.7, shadeOffset: 0.2 });
renderer.drawMesh(mesh, Matrix4.createTranslation(1, 0, 0), { alpha: 0.5, softEdge: 1.5, hasOutline: false });
renderer.endFrame();같은 모형 여럿을 한 번에 그리기. (GPU 인스턴싱, 화면 밖 인스턴스는 걸러 남은 것만 올린다, 뼈대 모형은 같은 자세)
Draws many copies of the same model at once. (GPU instancing, off-screen instances are culled and only the rest are uploaded, skinned models share the same pose)
- meshobject
- createMesh 의 결과.Result of createMesh.
- instancesArray<object>
- { modelMatrix: Matrix4, tintColor: [r, g, b, a], emissiveColor: [r, g, b], emissiveIntensity: number } 의 배열. 틴트는 곱하는 sRGB 와 알파(기본 1), emissiveColor 는 그 인스턴스에 더하는 빛남 sRGB(기본 없음, 명암과 무늬 위에 더해 그 인스턴스만 밝힘), emissiveIntensity 는 빛남의 선형 배(기본 1). 모형 행렬은 아핀으로 읽는다. (TOON_INSTANCE_FLOAT_COUNT 머리말)Array of { modelMatrix: Matrix4, tintColor: [r, g, b, a], emissiveColor: [r, g, b], emissiveIntensity: number }. The tint is the multiplying sRGB and alpha (default 1), emissiveColor is the emission sRGB added to that instance (default none, added on top of the shading and pattern so only that instance brightens), and emissiveIntensity is the linear multiplier of the emission (default 1). The model matrix is read as affine. (See the TOON_INSTANCE_FLOAT_COUNT header)
- optionsobject
- drawMesh 와 같다. (모든 인스턴스에 같게 건다)Same as drawMesh. (Applied the same to all instances)
짝Counterpart: vanilla-engine ToonRenderer.draw_mesh_instanced
import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098", { hasOutline: true });
const rockMesh = renderer.createMesh(builder.readArrays());
const instances = [];
for (let index = 0; index < 20; ++index) {
const shade = 0.7 + (index % 4) * 0.1;
instances.push({ modelMatrix: Matrix4.createTranslation(index % 5 - 2, 0, Math.floor(index / 5) - 2), tintColor: [shade, shade, shade, 1] });
}
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 4, 6), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
renderer.drawMeshInstanced(rockMesh, instances, { specularScale: 0 });
renderer.endFrame();import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098", { hasOutline: true });
const rockMesh = renderer.createMesh(builder.readArrays());
const instances = [0, 1, 2].map((index) => ({ modelMatrix: Matrix4.createTranslation(index - 1, 0, 0) }));
instances[1].emissiveColor = [1, 0.85, 0.3];
instances[1].emissiveIntensity = 0.35;
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
renderer.drawMeshInstanced(rockMesh, instances);
renderer.endFrame();영구 인스턴스 버퍼로 그리기. (버퍼 전체의 경계로 통째 거른다, instanceCount 개, 꼴에 행렬이 없으면 정점 조각이 자리를 정하고 거르지 않는다)
Draws with a persistent instance buffer. (Culled as a whole by the bounds of the entire buffer, instanceCount instances, if the layout has no matrix the vertex chunk sets the position and it is not culled)
- meshobject
- createMesh 의 결과.Result of createMesh.
- instanceBufferobject
- createInstanceBuffer 의 결과.Result of createInstanceBuffer.
- instanceCountnumber
- 그릴 인스턴스 수. (버퍼에 든 수를 넘으면 자른다)Number of instances to draw. (Clamped if more than the buffer holds)
- optionsobject
- drawMesh 와 같다. (material 의 정점 조각이 사용자 어트리뷰트를 읽는다, isCulled 가 false 면 거르지 않는다)Same as drawMesh. (The material's vertex chunk reads user attributes, not culled if isCulled is false)
짝Counterpart: vanilla-engine ToonRenderer.draw_mesh_instance_buffer
import { ToonRenderer, MeshBuilder, createCylinderGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createCylinderGeometry(0.02, 0.15, 0.6, 6), Matrix4.createTranslation(0, 0.3, 0), "#60a050", { hasOutline: true });
const grassMesh = renderer.createMesh(builder.readArrays());
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceOffset", size: 3 }]);
const material = renderer.createMaterial({ name: "grass", vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.modelMatrix[3].xyz += instanceOffset; }" });
const data = new Float32Array(3 * 50);
for (let index = 0; index < 50; ++index) {
data.set([(index % 10) * 0.4 - 2, 0, Math.floor(index / 10) * 0.4 - 1], index * 3);
}
const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 3, 5), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
renderer.drawMeshInstanceBuffer(grassMesh, instanceBuffer, 50, { material: material });
renderer.endFrame();
renderer.deleteInstanceBuffer(instanceBuffer);모형 하나의 바깥선만 그리기. (거르지도 세지도 않는다, 껍데기가 없거나 hasOutline 이 false 면 그리지 않는다)
Draws only the outline of one model. (neither culled nor counted, not drawn if there is no shell or hasOutline is false)
- meshobject
- createMesh 의 결과.Result of createMesh.
- modelMatrixMatrix4
- 모형 행렬.Model matrix.
- optionsobject
- drawMesh 와 같다.Same as drawMesh.
짝Counterpart: vanilla-engine ToonRenderer.draw_mesh_outline
그리기마다의 공용 유니폼 올리기. (모형 행렬, 뼈대, 인스턴싱)
Uploads the common per-draw uniforms. (model matrix, skeleton, instancing)
- shaderProgramShaderProgram
- 지금 쓰는 프로그램.The program in use.
- modelElementsArrayLike<number>
- 모형 행렬의 수 16.The 16 numbers of the model matrix.
- isSkinnedboolean
- 뼈대로 움직일지.Whether to move by skeleton.
- instancedModenumber
- 0 아님, 1 인스턴스 행렬과 틴트, 2 인스턴스 틴트만0 none, 1 instance matrix and tint, 2 instance tint only
- jointMatricesFloat32Array | null
- 본 행렬의 수. (뼈대가 아니면 null)Numbers of the joint matrices. (null if not skeletal)
drawWithCount(mesh, modelElements, instanceCount, options, instanceBuffer, parts = DRAW_PART_ALL, vertexArrays = null)#그리기 본체. (instanceCount 가 0 이면 보통, 아니면 인스턴스로, instanceBuffer 가 있으면 그 꼴로)
Core draw. (normal draw if instanceCount is 0, otherwise instanced, using its layout if instanceBuffer is given)
- meshobject
- createMesh 의 결과.Result of createMesh.
- modelElementsArrayLike<number>
- 모형 행렬의 수 16. (인스턴스면 감기를 가릴 첫 행렬)The 16 numbers of the model matrix. (For instances, the first matrix that decides the winding)
- instanceCountnumber
- 인스턴스 수. (0 이면 보통 그리기)Instance count. (0 means an ordinary draw)
- optionsobject
- drawMesh 의 그리기 꼴.Draw options of drawMesh.
- instanceBufferobject | null
- createInstanceBuffer 의 결과. (없으면 null)Result of createInstanceBuffer. (null if none)
- partsnumber
- 그릴 것. (DRAW_PART_OUTLINE 바깥선 껍데기, DRAW_PART_BODY 몸, 기본 둘 다, 꼴의 hasOutline, isBodyDrawn 이 false 면 그것도 뺀다)What to draw. (DRAW_PART_OUTLINE the outline shell, DRAW_PART_BODY the body, both by default, hasOutline and isBodyDrawn false in the options also leave that out)
- vertexArraysobject | null
- 모형 대신 쓸 버텍스 어레이. ({ body, outline }, 자동 인스턴싱의 묶음 자리, 기본 null)Vertex arrays to use instead of the mesh's. ({ body, outline }, the batch slot of auto-instancing, null by default)
빛 설정. (해가 비추는 방향, 해의 색, 하늘색, 땅색, 모두 선형 색 0 ~, HDR 이면 1 을 넘어도 된다, 기본 빛 묶음)
Sets the lighting. (sun direction, sun color, sky color, ground color, all linear colors 0 ~, may exceed 1 with HDR, default light set)
- sunDirectionArray<number>
- 해가 비추는 방향. ([x, y, z], 빛이 나아가는 쪽)Direction the sun shines. ([x, y, z], the way the light travels)
- sunColorArray<number>
- 해의 선형 색.Linear color of the sun.
- skyColorArray<number>
- 위에서 오는 바탕빛의 선형 색.Linear color of the ambient light from above.
- groundColorArray<number>
- 아래에서 오는 바탕빛의 선형 색.Linear color of the ambient light from below.
짝Counterpart: vanilla-engine ToonRenderer.set_light
해가 비추는 방향 설정. (빛이 나아가는 쪽, ToonLightSet 머리말)
Sets the sun direction. (the direction light travels, ToonLightSet header comment)
- sunDirectionArray<number>
- 빛이 나아가는 방향. ([x, y, z])Direction the light travels. ([x, y, z])
짝Counterpart: vanilla-engine ToonRenderer.set_sun_direction
해가 비추는 방향 반환. (ShadowMap.updateLightMatrix 에 넘긴다)
Returns the sun direction. (passed to ShadowMap.updateLightMatrix)
반환ReturnsArray<number> 해가 비추는 방향. ([x, y, z])Direction the sun shines. ([x, y, z])
짝Counterpart: vanilla-engine ToonRenderer.get_sun_direction
채움 빛 설정. (빛이 나아가는 방향과 선형 색)
Sets the fill light. (direction light travels and linear color)
- fillDirectionArray<number>
- 빛이 나아가는 방향. ([x, y, z])Direction the light travels. ([x, y, z])
- fillColorArray<number>
- 선형 색. (0 이면 없음)Linear color. (0 means none)
짝Counterpart: vanilla-engine ToonRenderer.set_fill_light
림 빛 설정. (ToonLightSet.setRimLight)
Set the rim light. (ToonLightSet.setRimLight)
- rimColorArray<number>
- 더할 선형 색.Linear color to add.
- rimPowernumber
- 거듭제곱. (0 이면 없음)Power. (0 means none)
- rimFeathernumber
- 0 단단한 테 ~ 1 부드러운 테. (기본 1)0 hard rim ~ 1 soft rim. (Default 1)
- rimLightMasknumber
- 1 이면 해를 받는 쪽에만. (기본 0)1 means only on the side facing the sun. (Default 0)
짝Counterpart: vanilla-engine ToonRenderer.set_rim_light
setSpecular(specularStrength, specularExponent = 48, specularFeather = 0, specularColor = [1, 1, 1])#하이라이트 설정. (ToonLightSet.setSpecular)
Set the highlight. (ToonLightSet.setSpecular)
- specularStrengthnumber
- 세기. (0 이면 없음)Strength. (0 means none)
- specularExponentnumber
- 블린 퐁 지수. (기본 48)Blinn-Phong exponent. (Default 48)
- specularFeathernumber
- 0 단단한 점 ~ 1 부드러운 빛. (기본 0)0 hard spot ~ 1 soft light. (Default 0)
- specularColorArray<number>
- 선형 색. (기본 흰색)Linear color. (Default white)
짝Counterpart: vanilla-engine ToonRenderer.set_specular
점광과 스포트라이트 설정. (ToonLightSet.setPointLights)
Set point lights and spotlights. (ToonLightSet.setPointLights)
- pointLightsArray<object>
- ToonLightSet.setPointLights 의 꼴.Form of ToonLightSet.setPointLights.
짝Counterpart: vanilla-engine ToonRenderer.set_point_lights
점광 수의 한도 설정. (ToonLightSet.setPointLightLimit)
Set the point light count limit. (ToonLightSet.setPointLightLimit)
- pointLightLimitnumber
- 받을 점광 수. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)Number of point lights to receive. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)
짝Counterpart: vanilla-engine ToonRenderer.set_point_light_limit
그늘 셋 설정. (ToonLightSet.setShade, 유니티 툰 셰이더의 바탕, 1 차 그늘, 2 차 그늘)
Set the three shades. (ToonLightSet.setShade, base, 1st shade and 2nd shade of the Unity Toon Shader)
- shadeobject
- 바탕에서 1 차, 2 차 그늘로 넘어가는 문턱, 부드러움, 색. ({ step, feather, color, secondStep, secondFeather, secondColor, isHalfLambert })Thresholds, softness and colors from base to 1st and 2nd shade. ({ step, feather, color, secondStep, secondFeather, secondColor, isHalfLambert })
짝Counterpart: vanilla-engine ToonRenderer.set_shade
import { ToonRenderer, MeshBuilder, createSphereGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setShade({ step: 0.55, feather: 0.01, color: [0.85, 0.62, 0.6], secondStep: 0.25, secondFeather: 0.01, secondColor: [0.6, 0.42, 0.45], isHalfLambert: true });
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 32, 20), Matrix4.createIdentity(), "#f8e0d0", { 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());
renderer.endFrame();그늘 램프 설정. (ToonLightSet.setShadeRamp)
Set the shade ramp. (ToonLightSet.setShadeRamp)
- positionsArray<number>
- 칸마다의 자리.Position per cell.
- colorsArray<Array<number>>
- 칸마다의 선형 배.Linear multiplier per cell.
- feathersArray<number>
- 칸마다의 부드러움.Softness per cell.
- isHalfLambertboolean
- 반 램버트로 셀지.Whether to count with half Lambert.
짝Counterpart: vanilla-engine ToonRenderer.set_shade_ramp
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.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);
const shadeRamp = renderer.getLightSet().getShadeRamp();
if (shadeRamp.positions.length !== 3) {
throw new Error("ramp not set");
}그늘 램프 끄기. (부드러운 램버트)
Turn off the shade ramp. (Smooth Lambert)
짝Counterpart: vanilla-engine ToonRenderer.clear_shade_ramp
고른 칸 설정. (ToonLightSet.setBandCount, 0 이면 부드럽게)
Set even cells. (ToonLightSet.setBandCount, 0 means smooth)
- bandCountnumber
- 칸 수.Number of cells.
짝Counterpart: vanilla-engine ToonRenderer.set_band_count
회색 칸 램프 설정. (ToonLightSet.setBandRamp)
Set a gray cell ramp. (ToonLightSet.setBandRamp)
- thresholdsArray<number>
- 오름차순 문턱.Ascending thresholds.
- valuesArray<number>
- 칸마다의 받는 몫.Received amount per cell.
- isHalfLambertboolean
- 반 램버트로 셀지.Whether to count with half Lambert.
짝Counterpart: vanilla-engine ToonRenderer.set_band_ramp
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setBandRamp([0.3, 0.7], [0.35, 0.7, 1], false);
renderer.setRimLight([0.4, 0.4, 0.5], 4, 0, 1);
renderer.setSpecular(0.5, 32, 0);램프 텍스처 설정. (ToonLightSet.setRampTexture, null 이면 칸으로)
Set the ramp texture. (ToonLightSet.setRampTexture, back to cells if null)
- rampTextureWebGLTexture | null
- createTexture 로 지은 램프 텍스처나 null.A ramp texture built with createTexture, or null.
- isHalfLambertboolean
- 반 램버트로 셀지. (기본 true)Whether to count with half Lambert. (Default true)
짝Counterpart: vanilla-engine ToonRenderer.set_ramp_texture
import { ToonRenderer, MeshBuilder, createTorusGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const rampData = new Uint8Array([60, 50, 110, 255, 110, 100, 160, 255, 200, 185, 215, 255, 255, 255, 255, 255]);
const rampTexture = renderer.createTexture({ width: 4, height: 1, data: rampData }, { isMipmapped: false, isRepeated: false, isFiltered: false });
renderer.setRampTexture(rampTexture, true);
const builder = new MeshBuilder();
builder.addPart(createTorusGeometry(0.4, 0.15, 16, 32), Matrix4.createIdentity(), "#ffffff", { hasOutline: true });
const mesh = 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(mesh, Matrix4.createIdentity());
renderer.endFrame();
renderer.setRampTexture(null);
renderer.deleteTexture(rampTexture);빛 꼴 설정. ({ isEnergyNormalized })
Sets the light model. ({ isEnergyNormalized })
- lightModelobject
- { isEnergyNormalized } (true 면 바탕색 x 빛을 π 로 나눈다){ isEnergyNormalized } (if true, base color x light is divided by π)
짝Counterpart: vanilla-engine ToonRenderer.set_light_model
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setLightModel({ isEnergyNormalized: true });
renderer.setLight([-0.3, -1, -0.4], [3.14, 3.0, 2.8], [0.4, 0.45, 0.55], [0.2, 0.18, 0.16]);
renderer.setPointLights([{ position: [0, 2, 1], color: [1, 0.8, 0.6], intensity: 30, range: 8 }]);바깥선 색 설정. (sRGB 0 ~ 1 과 알파)
Sets the outline color. (sRGB 0 ~ 1 and alpha)
- outlineColorArray<number>
- [r, g, b, a] (sRGB 0 ~ 1 과 알파)[r, g, b, a] (sRGB 0 ~ 1 and alpha)
짝Counterpart: vanilla-engine ToonRenderer.set_outline_color
껍데기 바깥선의 거리 배 설정. (기준 거리에서 지은 굵기, 멀면 그만큼 굵게 밀어 화면 굵기를 맞춘다, 배는 가장 작은 것과 큰 것 사이, 기준 거리 0 이면 끔)
- 원근 카메라에서만 건다. 꼭짓점마다 카메라까지의 거리 / 기준 거리 를 굵기에 곱한다. (길티기어 Xrd 처럼 거리와 상관없이 비슷한 화면 굵기)
Set the distance scale of the shell outline. (Built thickness at the reference distance, pushed thicker by that much when far to keep the screen thickness, the scale lies between minimum and maximum, reference distance 0 turns it off)
- Applied only with a perspective camera. Distance to the camera / reference distance per vertex is multiplied into the thickness. (Similar screen thickness regardless of distance, like Guilty Gear Xrd)
- referenceDistancenumber
- 지은 굵기 그대로인 거리. (0 이면 끔)Distance at which the built thickness is kept. (0 turns it off)
- minimumScalenumber
- 가장 작은 배. (기본 0.5)Minimum scale. (Default 0.5)
- maximumScalenumber
- 가장 큰 배. (기본 4)Maximum scale. (Default 4)
짝Counterpart: vanilla-engine ToonRenderer.set_outline_distance_scale
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setOutlineDistanceScale(6, 0.4, 3);껍데기 바깥선이 멀면 사라지는 거리 설정. (가까운 거리 이하는 지은 굵기, 먼 거리 이상은 0, 사이는 smoothstep, 먼 거리가 가까운 거리 이하면 끔)
- 유니티 툰 셰이더의 Nearest Distance, Farthest Distance 와 같은 꼴이다. 모형 행렬의 자리에서 카메라까지의 거리로 본다. (원근만)
Set the distance at which the shell outline fades when far. (Built thickness up to the near distance, 0 from the far distance, smoothstep in between, off if the far distance is not above the near distance)
- Same form as Nearest Distance and Farthest Distance of the Unity Toon Shader. Uses the distance from the model matrix position to the camera. (Perspective only)
- nearDistancenumber
- 지은 굵기 그대로인 거리.Distance at which the built thickness is kept.
- farDistancenumber
- 굵기가 0 이 되는 거리.Distance at which the thickness becomes 0.
짝Counterpart: vanilla-engine ToonRenderer.set_outline_fade_distance
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setOutlineFadeDistance(8, 20);껍데기 바깥선이 사라지는 거리 반환.
Return the distance at which the shell outline fades.
반환ReturnsArray<number> [가까운 거리, 먼 거리][near distance, far distance]
짝Counterpart: vanilla-engine ToonRenderer.get_outline_fade_distance
받을 점광과 스포트라이트 그림자 설정. (ShadowAtlas 나 null, 세기 0 ~ 1, 아틀라스는 기본 빛 묶음의 점광 목록으로 지은 것)
Set the point light and spotlight shadows to receive. (ShadowAtlas or null, strength 0 ~ 1, the atlas is the one built from the point light list of the default light set)
- shadowAtlasobject | null
- ShadowAtlas 나 null.ShadowAtlas or null.
- strengthnumber
- 그림자 세기. (기본 1)Shadow strength. (Default 1)
짝Counterpart: vanilla-engine ToonRenderer.set_local_shadows
import { ToonRenderer, ShadowAtlas } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
renderer.setPointLights([{ position: [0, 3, 0], color: [1, 0.9, 0.8], intensity: 4, range: 8, direction: [0, -1, 0], innerConeAngle: 0.3, outerConeAngle: 0.6, castsShadow: true }]);
const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 1024);
shadowAtlas.updateLights(renderer.getLightSet().getPointLights());
renderer.setLocalShadows(shadowAtlas, 0.8);
renderer.setLocalShadows(null);빛 색 쓰기 설정. (ToonLightSet.setLightColorUsage)
Set the light color usage. (ToonLightSet.setLightColorUsage)
- lightColorUsageobject
- { base, shade, highlight, rim, shadeRim, matcap, angelRing, outline } (주지 않은 것은 그대로){ base, shade, highlight, rim, shadeRim, matcap, angelRing, outline } (Ones not given stay as they are)
짝Counterpart: vanilla-engine ToonRenderer.set_light_color_usage
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setLightColorUsage({ rim: false, outline: false });빛 세기 막기 설정. (ToonLightSet.setLightIntensityLimited)
Set the light intensity limit. (ToonLightSet.setLightIntensityLimited)
- isLimitedboolean
- true 면 빛마다 받은 몫을 1 로 막는다. (기본 true)If true, limits what each light gives to 1. (Default true)
짝Counterpart: vanilla-engine ToonRenderer.set_light_intensity_limited
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setLight([-0.4, -1, -0.3], [3, 2.8, 2.6], [0.4, 0.45, 0.55], [0.2, 0.18, 0.16]);
renderer.setLightIntensityLimited(false);그늘 쪽 림 빛 설정. (ToonLightSet.setShadeRimLight)
Set the shade-side rim light. (ToonLightSet.setShadeRimLight)
- shadeRimColorArray<number>
- 더할 선형 색.Linear color to add.
- shadeRimPowernumber
- 거듭제곱. (0 이면 없음)Power. (0 means none)
짝Counterpart: vanilla-engine ToonRenderer.set_shade_rim_light
import { ToonRenderer } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
renderer.setShadeRimLight([0.18, 0.3, 0.62], 2.2);껍데기 바깥선의 거리 배 반환.
Return the distance scale of the shell outline.
반환ReturnsArray<number> [기준 거리, 가장 작은 배, 가장 큰 배][reference distance, minimum scale, maximum scale]
짝Counterpart: vanilla-engine ToonRenderer.get_outline_distance_scale
HDR 출력 설정. (true 면 감마를 걸지 않은 선형 색을 낸다)
Sets HDR output. (if true, outputs linear color without gamma)
- isHdrOutputboolean
- true 면 감마를 걸지 않은 선형 색을 낸다.If true, outputs linear color without gamma.
짝Counterpart: vanilla-engine ToonRenderer.set_hdr_output
받을 그림자 설정. (ShadowMap 이나 null, 세기 0 ~ 1)
Sets the shadow to receive. (ShadowMap or null, strength 0 ~ 1)
- shadowMapobject | null
- 받을 ShadowMap. (null 이면 그림자를 받지 않는다)ShadowMap to receive. (Shadows are not received if null)
- strengthnumber
- 그림자 세기 0 ~ 1. (기본 0.6)Shadow strength 0 ~ 1. (Default 0.6)
짝Counterpart: vanilla-engine ToonRenderer.set_shadow
import { ToonRenderer, MeshBuilder, createSphereGeometry, ShadowMap, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.3, 20, 14), Matrix4.createIdentity(), "#ffe080", { glow: 1, hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
const shadowMap = new ShadowMap(webGL2RenderingContext, 512);
shadowMap.updateLightMatrix(Vector3.create(0, 0, 0), Vector3.create(-0.3, -1, -0.2), 4, 0.5, 20);
renderer.setShadow(shadowMap, 0.8);
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(mesh, Matrix4.createTranslation(0, 1, 0), { receivesShadow: false });
renderer.endFrame();
renderer.setShadow(null);모서리 어둠 텍스처 설정. (ToonPostProcess.drawAmbientOcclusion 의 결과나 null, 다음 beginFrame 부터)
- 텍스처를 건 동안 몸은 모서리 어둠 몸 프로그램(TOON_AMBIENT_OCCLUSION)으로 그리고, 화면 자리의 보임을 바탕빛(하늘과 땅 빛)에 곱한다.
- 직접 빛 몫(directLightingStrength, 0 ~ 1)이 0 보다 크면 해, 채움빛, 점광과 스포트라이트의 확산과 반사광에도 1 - 몫 x (1 - 보임) 을 곱한다. (유니티 URP SSAO 의 Direct Lighting Strength 꼴) 칸(밝기 단계)을 고른 뒤에 곱해 칸 경계 자리는 옮겨 가지 않는다. 테두리빛, 빛남, 매트캡, 천사 고리는 그대로다. 몫 0 이면 바탕빛에만 곱한다.
- 비치는 것(alpha 나 틴트 알파가 1 보다 작음)과 텍스처의 깊이와 다른 면(선의 판에 없던 것)은 곱하지 않는다.
- null 이면 기본 몸 프로그램으로 돌아가 텍스처를 읽지 않는다. (끈 화면은 건 적이 없을 때와 같다)
- 머티리얼 텍스처 8 개를 다 쓰는 머티리얼은 조각 셰이더 유닛이 16 개인 기기에서 모서리 어둠 없이 그린다.
Sets the ambient occlusion texture. (the result of ToonPostProcess.drawAmbientOcclusion or null, from the next beginFrame)
- While a texture is set, bodies are drawn with the ambient occlusion body program (TOON_AMBIENT_OCCLUSION), and the visibility at the screen position multiplies the ambient light (sky and ground light).
- When the direct lighting strength (directLightingStrength, 0 to 1) is above 0, the diffuse and specular of the sun, fill light, point lights and spotlights are also multiplied by 1 - strength x (1 - visibility). (the form of Direct Lighting Strength in Unity URP SSAO) It is applied after the band (brightness step) is chosen, so band edges do not move. Rim light, glow, matcap and angel ring stay as they are. With strength 0 only the ambient light is multiplied.
- Transparent things (alpha or tint alpha below 1) and surfaces whose depth differs from the texture (not in the line target) are not multiplied.
- null returns to the default body program, which does not read the texture. (the screen with it off is the same as when it was never set)
- Materials that use all 8 material textures are drawn without ambient occlusion on devices with 16 fragment shader texture units.
- textureWebGLTexture | null
- 선의 판 크기의 RGBA8. (r 보임, gba 깊이 24 비트, null 이면 끈다)RGBA8 the size of the line target. (r visibility, gba 24-bit depth, null turns it off)
- directLightingStrengthnumber
- 직접 빛에 미치는 몫 0 ~ 1. (기본 0, 바탕빛에만 곱함)How much it affects direct lighting, 0 to 1. (default 0, multiplies only the ambient light)
짝Counterpart: vanilla-engine ToonRenderer.set_ambient_occlusion_texture
import { ToonRenderer } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const texture = webGL2RenderingContext.createTexture();
webGL2RenderingContext.bindTexture(webGL2RenderingContext.TEXTURE_2D, texture);
webGL2RenderingContext.texStorage2D(webGL2RenderingContext.TEXTURE_2D, 1, webGL2RenderingContext.RGBA8, 300, 150);
renderer.setAmbientOcclusionTexture(texture, 0.5);
if (renderer.getAmbientOcclusionTexture() !== texture || renderer.getAmbientOcclusionDirectLightingStrength() !== 0.5) {
throw new Error("ambient occlusion texture is not set");
}
renderer.setAmbientOcclusionTexture(null);모서리 어둠이 직접 빛에 미치는 몫 반환. (setAmbientOcclusionTexture 의 둘째 인자, 걸지 않았으면 0)
Returns how much ambient occlusion affects direct lighting. (the second argument of setAmbientOcclusionTexture, 0 when not set)
반환Returnsnumber 0 ~ 1.
짝Counterpart: vanilla-engine ToonRenderer.get_ambient_occlusion_direct_lighting_strength
모서리 어둠 텍스처 반환. (걸지 않았으면 null)
Returns the ambient occlusion texture. (null if not set)
반환ReturnsWebGLTexture | null setAmbientOcclusionTexture 로 건 텍스처.The texture set by setAmbientOcclusionTexture.
짝Counterpart: vanilla-engine ToonRenderer.get_ambient_occlusion_texture
이번 프레임의 그린 수와 거른 수와 드로우콜.
This frame's drawn count, culled count and draw calls.
반환Returnsobject 이번 프레임의 셈. ({ drawCallCount, drawnObjectCount, culledObjectCount })Counts of this frame. ({ drawCallCount, drawnObjectCount, culledObjectCount })
짝Counterpart: vanilla-engine ToonRenderer.get_frame_statistics
렌더링 컨텍스트 반환.
Returns the rendering context.
반환ReturnsWebGL2RenderingContext 그리는 컨텍스트.Context to draw with.
색 공간 반환. (생성 때 정한 값, 바뀌지 않는다)
Returns the color space. (Set at construction, never changes)
반환Returnsstring ColorSpace.gamma 나 ColorSpace.linear.ColorSpace.gamma or ColorSpace.linear.
짝Counterpart: vanilla-engine ToonRenderer.get_color_space
import { ToonRenderer, ToonPostProcess, ToonScreenOutline, ColorSpace } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext, { colorSpace: ColorSpace.linear });
const postProcess = new ToonPostProcess(webGL2RenderingContext, 320, 180, { colorSpace: renderer.getColorSpace() });
const screenOutline = new ToonScreenOutline(webGL2RenderingContext, { colorSpace: renderer.getColorSpace() });
if (renderer.getColorSpace() !== ColorSpace.linear || postProcess.getColorSpace() !== ColorSpace.linear || screenOutline.getColorSpace() !== ColorSpace.linear) {
throw new Error("color space is not linear");
}몸 프로그램 반환. (머티리얼을 주면 그 머티리얼의 것, 짓지 못했으면 null)
Returns the body program. (that material's if a material is given, null if it failed to build)
- materialToonMaterial | null
- 머티리얼. (기본 null 이면 기본 프로그램)Material. (Default program if null, the default)
반환ReturnsShaderProgram | null 몸 프로그램. (짓지 못했으면 null)Body program. (null if it could not be built)
짝Counterpart: vanilla-engine ToonRenderer.get_solid_program
바깥선 프로그램 반환.
Returns the outline program.
- materialToonMaterial | null
- 머티리얼. (기본 null 이면 기본 프로그램)Material. (Default program if null, the default)
반환ReturnsShaderProgram | null 바깥선 프로그램. (짓지 못했으면 null)Outline program. (null if it could not be built)
짝Counterpart: vanilla-engine ToonRenderer.get_outline_program
그림자 깊이 프로그램 반환.
Returns the shadow depth program.
- materialToonMaterial | null
- 머티리얼. (기본 null 이면 기본 프로그램)Material. (Default program if null, the default)
반환ReturnsShaderProgram | null 그림자 깊이 프로그램. (짓지 못했으면 null)Shadow depth program. (null if it could not be built)
짝Counterpart: vanilla-engine ToonRenderer.get_depth_program
ToonProgramPrewarm
프로그램 변형 미리 짓기의 진행. (ToonRenderer.prewarmDrawQueue 의 결과)
- 컴파일이 끝난 것을 프레임마다 나눠 끝낸다. (requestAnimationFrame, 병렬 컴파일 확장이 없으면 만들 때 이미 끝나 있다)
Progress of prewarming program variants. (The result of ToonRenderer.prewarmDrawQueue)
- Finishes compiled programs a few per frame. (requestAnimationFrame; without the parallel compile extension it is already finished when created)
import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#c0d0ff");
const mesh = renderer.createMesh(builder.readArrays());
const queue = new ToonDrawQueue();
queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
const prewarm = renderer.prewarmDrawQueue(queue);
await prewarm.wait();
console.log(prewarm.isReady());다 지었는지.
Whether everything is built.
반환Returnsboolean 모두 지었으면 true. (그려도 되지만 안 지은 것은 그 자리에서 짓는다)True if everything is built. (Drawing is allowed anyway; anything not built is built on the spot)
짝Counterpart: vanilla-engine ToonProgramPrewarm.is_ready
다 지을 때까지 기다리기.
Waiting until everything is built.
반환ReturnsPromise<void> 다 지으면 풀리는 약속.Promise that resolves when everything is built.
짝Counterpart: vanilla-engine ToonProgramPrewarm.wait
함수Functions
composeToonProgramSources(material, instanceLayout, isAmbientOcclusion = false, colorSpace = readEngineColorSpace(), disabledFeatures = [])#머티리얼과 인스턴스 꼴로 세 프로그램의 소스 짓기. (둘 다 null 이면 기본 프로그램)
Builds the sources of the three programs from a material and instance layout. (default programs if both are null)
- materialToonMaterial | null
- 셰이더 조각을 끼울 머티리얼. (null 이면 빈 조각)Material to insert shader chunks with. (Empty chunks if null)
- instanceLayoutToonInstanceLayout | null
- 사용자 어트리뷰트를 선언할 인스턴스 꼴. (null 이면 없음)Instance layout that declares user attributes. (None if null)
- isAmbientOcclusionboolean
- 몸 조각 셰이더에 TOON_AMBIENT_OCCLUSION 을 정의해 모서리 어둠 텍스처를 바탕빛에 곱할지. (기본 false)Whether to define TOON_AMBIENT_OCCLUSION in the body fragment shader so the ambient occlusion texture multiplies the ambient light. (default false)
- colorSpacestring
- 색 공간. (ColorSpace, 기본은 엔진의 색 공간, linear 면 소스마다 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어간다)Color space. (ColorSpace, default is the engine's color space, in linear every source gets #define VANILLA_COLOR_SPACE_LINEAR 1)
- disabledFeaturesArray<string>
- 몸 조각 셰이더에서 컴파일 때 지울 기능 갈래. (baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit 가운데, 기본은 없음, 지운 갈래를 그리기 때 켜면 그 갈래는 그려지지 않는다. 렌더러는 그리기가 쓰지 않는 갈래를 스스로 알아 넘긴다)Feature branches to remove from the body fragment shader at compile time. (Any of baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit, default none; a removed branch is not drawn if a draw turns it on. The renderer finds the branches a draw does not use and passes them itself)
반환Returnsobject 세 프로그램의 소스와 어트리뷰트 자리. ({ solidVertexShader, solidFragmentShader, outlineVertexShader, outlineFragmentShader, depthVertexShader, depthFragmentShader, attributeLocationTable })Sources and attribute locations of the three programs. ({ solidVertexShader, solidFragmentShader, outlineVertexShader, outlineFragmentShader, depthVertexShader, depthFragmentShader, attributeLocationTable })
짝Counterpart: vanilla-engine compose_toon_program_sources
import { composeToonProgramSources, ToonMaterial, ToonInstanceLayout } from "./vanilla.js";
const material = new ToonMaterial({ name: "sway", vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.localPosition.x += instanceSway * vertex.localPosition.y; }" });
const instanceLayout = new ToonInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceSway", size: 1 }]);
const sources = composeToonProgramSources(material, instanceLayout);
const context = document.createElement("canvas").getContext("webgl2");
const shader = context.createShader(context.VERTEX_SHADER);
context.shaderSource(shader, sources.solidVertexShader);
context.compileShader(shader);
if (!context.getShaderParameter(shader, context.COMPILE_STATUS) || sources.attributeLocationTable.instanceSway !== 13) {
throw new Error(context.getShaderInfoLog(shader));
}
context.deleteShader(shader);보기와 투영 행렬에서 절두체의 면 여섯. (ax + by + cz + d >= 0 이 안쪽, 정규화)
The six frustum planes from a view-projection matrix. (ax + by + cz + d >= 0 is inside, normalized)
- matrixMatrix4
- 보기와 투영 행렬. (투영 x 보기)View and projection matrix. (Projection x view)
반환ReturnsArray<Array<number>> 면 여섯의 [a, b, c, d]. (왼쪽, 오른쪽, 아래, 위, 가까운 면, 먼 면)[a, b, c, d] of the six planes. (Left, right, bottom, top, near, far)
짝Counterpart: vanilla-engine extract_frustum_planes
import { extractFrustumPlanes, Matrix4, Vector3 } from "./vanilla.js";
const viewProjectionMatrix = Matrix4.createPerspective(0.8, 16 / 9, 0.1, 50);
viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 2, 6), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
const planes = extractFrustumPlanes(viewProjectionMatrix);
const isSphereVisible = (center, radius) => planes.every((plane) => plane[0] * center[0] + plane[1] * center[1] + plane[2] * center[2] + plane[3] >= -radius);
if (!isSphereVisible([0, 0, 0], 1) || isSphereVisible([0, 0, 80], 1)) {
throw new Error("unexpected culling");
}모형 행렬 왼쪽 위 3x3 의 행렬식. (음수면 거울에 비친 행렬, 감기가 뒤집힌다)
Determinant of the model matrix's upper-left 3x3. (negative means a mirrored matrix, winding is flipped)
- elementsArrayLike<number>
- Matrix4 의 수. (열 차례)Elements of a Matrix4. (column order)
반환Returnsnumber 왼쪽 위 3x3 의 행렬식. (음수면 거울에 비친 행렬)Determinant of the upper left 3x3. (Negative means a mirrored matrix)
짝Counterpart: vanilla-engine read_matrix_determinant
import { readMatrixDeterminant, Matrix4 } from "./vanilla.js";
const modelMatrix = Matrix4.createTranslation(1, 0, 0);
modelMatrix.multiply(Matrix4.createScale(-1, 1, 1));
const isMirrored = readMatrixDeterminant(modelMatrix.getElements()) < 0;
if (!isMirrored) {
throw new Error("expected a mirrored matrix");
}보기와 투영 행렬에서 카메라 읽기. (원근이면 눈의 자리, 직교면 보는 방향, 행렬이 거울에 비친 것인지)
- 원근: 클립 x, y, w 가 모두 0 이 되는 점이 눈이다. (행 0, 1, 3 의 연립 방정식)
- 직교: 행 3 의 xyz 가 0 이라 눈이 무한히 멀다. 보는 방향은 행 0, 1 의 외적을 깊이가 느는 쪽으로 둔다.
- 보통의 투영(가까운 면 < 먼 면)은 왼쪽 위 3x3 의 행렬식이 음수다. 양수면 보기 행렬이 거울에 비친 것이다.
Reads the camera from view and projection matrices. (eye position if perspective, view direction if orthographic, whether the matrix is mirrored)
- Perspective: the eye is the point where clip x, y, w are all 0. (system of equations from rows 0, 1, 3)
- Orthographic: xyz of row 3 is 0, so the eye is infinitely far. The view direction is the cross product of rows 0, 1, oriented toward increasing depth.
- A normal projection (near plane < far plane) has a negative determinant in its upper-left 3x3. If positive, the view matrix is mirrored.
- elementsArrayLike<number>
- 보기와 투영 행렬의 수 16. (열 차례)The 16 numbers of the view and projection matrices. (Column order)
반환Returnsobject 읽은 카메라. ({ position [x, y, z, w(1 원근, 0 직교)], forward [x, y, z], isMirrored })The camera read. ({ position [x, y, z, w (1 perspective, 0 orthographic)], forward [x, y, z], isMirrored })
짝Counterpart: vanilla-engine read_frame_camera
import { readFrameCamera, Matrix4, Vector3 } from "./vanilla.js";
const viewProjectionMatrix = Matrix4.createPerspective(0.8, 16 / 9, 0.1, 100);
viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 2, 5), Vector3.create(0, 2, 0), Vector3.create(0, 1, 0)));
const frameCamera = readFrameCamera(viewProjectionMatrix.getElements());
const isPerspective = frameCamera.position[3] === 1;
if (!isPerspective || Math.abs(frameCamera.position[2] - 5) > 0.001 || frameCamera.forward[2] > -0.999 || frameCamera.isMirrored) {
throw new Error("unexpected camera");
}보기와 투영 행렬에서 보기 돌림 3x3 읽기. (열 차례, 행이 오른쪽, 위, 뒤, 매트캡의 보기 공간 노멀을 셀 때)
- 오른쪽은 행 0 의 xyz 에서 보는 방향 몫을 뺀 것이다. (대칭 원근과 직교, 화면 사각형으로 옮긴 투영 모두)
Read the 3x3 view rotation from the view and projection matrices. (Column order, rows are right, up, back, for computing the view-space normal of the matcap)
- Right is the xyz of row 0 minus its share along the view direction. (Works for symmetric perspective, orthographic and projections moved into a screen rectangle)
- elementsArrayLike<number>
- 보기와 투영 행렬의 수 16.The 16 numbers of the view and projection matrices.
- forwardArray<number>
- 보는 방향. (readFrameCamera 의 forward)View direction. (forward of readFrameCamera)
반환ReturnsArray<number> mat3 의 수 9. (열 차례)The 9 numbers of a mat3. (Column order)
짝Counterpart: vanilla-engine read_view_rotation
import { readFrameCamera, readViewRotation, Matrix4, Vector3 } from "./vanilla.js";
const viewProjectionMatrix = Matrix4.createPerspective(0.8, 1, 0.1, 100);
viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(3, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
const elements = viewProjectionMatrix.getElements();
const rotation = readViewRotation(elements, readFrameCamera(elements).forward);
const normal = [0, 1, 0];
const viewNormal = [0, 1, 2].map((row) => rotation[row] * normal[0] + rotation[3 + row] * normal[1] + rotation[6 + row] * normal[2]);
const matcapUv = [viewNormal[0] * 0.5 + 0.5, viewNormal[1] * 0.5 + 0.5];카메라 기울임을 되돌리는 각 읽기. (유니티 툰 셰이더의 천사 고리 Camera Rolling Stabilizer 와 같은 셈)
- 카메라 오른쪽(보기 돌림의 행 0)과 수평 오른쪽 축이 이루는 각 roll, 오른쪽의 y 가 음수면 쪽 dir 이 -1, 돌려주는 각은 -(dir x roll) 이다.
- 유니티는 왼손 좌표라 수평 오른쪽 축이 cross(뒤, 위) 이고, 엔진은 오른손 좌표라 같은 쪽이 cross(앞, 위) 다. 거울에 비친 프레임이면 축을 뒤집는다. (유니티 툰 셰이더의 mirrorFlag)
- 바로 위나 아래를 보면 수평 축이 없어 0 이다.
Read the angle that undoes the camera roll. (Same math as the angel ring Camera Rolling Stabilizer of the Unity Toon Shader)
- roll is the angle between the camera right (row 0 of the view rotation) and the horizontal right axis, the direction dir is -1 if the y of the right is negative, and the returned angle is -(dir x roll).
- Unity uses left-handed coordinates so the horizontal right axis is cross(back, up), and the engine uses right-handed coordinates so the same axis is cross(forward, up). In a mirrored frame the axis is flipped. (mirrorFlag of the Unity Toon Shader)
- When looking straight up or down there is no horizontal axis, so it is 0.
- viewRotationElementsFloat32Array | Array<number>
- mat3 의 수 9. (readViewRotation 의 결과, 열 차례)The 9 numbers of a mat3. (Result of readViewRotation, column order)
- isMirroredboolean
- 보기 행렬이 거울에 비쳤는지. (readFrameCamera 의 isMirrored)Whether the view matrix is mirrored. (isMirrored of readFrameCamera)
반환Returnsnumber 천사 고리 UV 를 (0.5, 0.5) 둘레로 돌릴 각. (라디안)Angle to rotate the angel ring UV around (0.5, 0.5). (Radians)
짝Counterpart: vanilla-engine read_camera_roll
import { readCameraRoll } from "./vanilla.js";
const roll = 0.3;
const rotation = [Math.cos(roll), -Math.sin(roll), 0, Math.sin(roll), Math.cos(roll), 0, 0, 0, 1];
const angle = readCameraRoll(rotation, false);
if (Math.abs(angle + roll) > 0.0001) {
throw new Error("unexpected camera roll");
}UV 꼭짓점 배열 짓기. (2 번 UV 가 없으면 점마다 UV 2, 있으면 UV 와 2 번 UV 를 섞어 4)
- 셰이더의 vertexUv 는 vec4 다. 2 개만 올리면 zw 는 (0, 1) 로 읽힌다.
Build the UV vertex array. (UV 2 per point without a second UV, UV and second UV interleaved as 4 with one)
- vertexUv in the shader is a vec4. If only 2 are uploaded, zw is read as (0, 1).
- uvDataFloat32Array
- UV. (점마다 2)UV. (2 per point)
- uv1DataFloat32Array | null
- 2 번 UV. (점마다 2, 없으면 null)Second UV. (2 per point, null if none)
- vertexCountnumber
- 점 수.Number of points.
반환ReturnsFloat32Array 점마다 2 나 4.2 or 4 per point.
짝Counterpart: vanilla-engine read_uv_data
import { readUvData } from "./vanilla.js";
const uvData = new Float32Array([0, 0, 1, 0, 1, 1]);
const uv1Data = new Float32Array([0.5, 0.5, 0.6, 0.5, 0.6, 0.6]);
const data = readUvData(uvData, uv1Data, 3);
if (data.length !== 12 || data[2] !== 0.5 || data[7] !== 0.5) {
throw new Error("unexpected uv data");
}껍데기 꼭짓점 배열 짓기. (점마다 바탕 자리 3 과 미는 쪽 3, 미는 쪽은 사본 자리 - 바탕 자리)
- 바탕 자리가 없거나 길이가 다르면(GLB 에 지어 둔 껍데기) 사본 자리를 바탕으로 두고 미는 쪽은 0 이다. (굵기 배를 걸지 않는다)
Build the shell vertex array. (Per point base position 3 and push direction 3, the push direction is copy position - base position)
- If there are no base positions or the length differs (a shell prebuilt in the GLB), the copy position becomes the base and the push direction is 0. (The thickness scale does not apply)
- outlineVertexDataFloat32Array
- 지은 굵기로 민 사본 자리. (3 씩)Copy positions pushed by the built thickness. (3 each)
- outlineBaseDataFloat32Array | undefined | null
- 밀기 전 바탕 자리. (3 씩)Base positions before pushing. (3 each)
반환ReturnsFloat32Array 점마다 6 개.6 per point.
짝Counterpart: vanilla-engine read_outline_vertex_data
import { readOutlineVertexData, MeshBuilder, createBoxGeometry, Matrix4 } from "./vanilla.js";
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#a0a0a0", { outlineWidth: 0.02 });
const arrays = builder.readArrays();
const outlineData = readOutlineVertexData(arrays.outlineVertexData, arrays.outlineBaseData);
const firstPush = Math.hypot(outlineData[3], outlineData[4], outlineData[5]);
if (outlineData.length !== arrays.outlineVertexData.length * 2 || firstPush <= 0) {
throw new Error("unexpected outline data");
}평면에 비친 행렬 짓기. (평면 위 한 점과 노멀, 평면 거울의 모형이나 보기 행렬에 곱한다)
- 비친 행렬로 그리면 감기가 뒤집힌다. ToonRenderer 는 모형 행렬의 행렬식이 음수면 스스로 앞면을 뒤집는다. (options.isMirrored 로 정할 수도 있다)
Builds a reflection matrix across a plane. (a point on the plane and its normal, multiplied into the model or view matrix for a planar mirror)
- Drawing with a reflected matrix flips the winding. ToonRenderer flips the front face itself if the model matrix determinant is negative. (can also be set with options.isMirrored)
- planePointArray<number>
- 평면 위 한 점. ([x, y, z])A point on the plane. ([x, y, z])
- planeNormalArray<number>
- 평면의 노멀. ([x, y, z], 길이는 상관없다)Normal of the plane. ([x, y, z], length does not matter)
반환ReturnsMatrix4 평면에 비친 행렬.Matrix reflected across the plane.
짝Counterpart: vanilla-engine create_reflection_matrix
import { ToonRenderer, MeshBuilder, createSphereGeometry, createReflectionMatrix, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.4, 24, 16), Matrix4.createIdentity(), "#e0a060", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
const modelMatrix = Matrix4.createTranslation(0, 0.6, 0);
const mirroredMatrix = createReflectionMatrix([0, 0, 0], [0, 1, 0]);
mirroredMatrix.multiply(modelMatrix);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1.5, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, mirroredMatrix, { colorScale: 0.4, hasOutline: false });
renderer.drawMesh(mesh, modelMatrix);
renderer.endFrame();모형을 인스턴스 버퍼로 그릴 때의 월드 경계 구. (버퍼의 경계에 모형의 경계 구를 가장 큰 크기로 더한 것, 걸러도 빠지는 화소가 없다)
The world bounding sphere when drawing a model with an instance buffer. (The buffer's bounds plus the model's bounding sphere at the largest scale, culling with it drops no pixels)
- meshobject
- ToonRenderer.createMesh 의 결과.Result of ToonRenderer.createMesh.
- instanceBufferobject
- ToonRenderer.createInstanceBuffer 의 결과.The result of ToonRenderer.createInstanceBuffer.
반환ReturnsArray<number> | null [x, y, z, 반지름]. (꼴에 행렬이 없어 경계를 모르면 null)[x, y, z, radius]. (null if the layout has no matrix and the bounds are unknown)
짝Counterpart: vanilla-engine read_instance_buffer_sphere
import { ToonRenderer, MeshBuilder, createCylinderGeometry, readInstanceBufferSphere, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createCylinderGeometry(0.02, 0.4, 1, 8), Matrix4.createTranslation(0, 0.5, 0), "#4a8040");
const treeMesh = renderer.createMesh(builder.readArrays());
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }]);
const data = new Float32Array(16 * 2);
data.set(Matrix4.createTranslation(-3, 0, 0).getElements(), 0);
data.set(Matrix4.createTranslation(3, 0, 0).getElements(), 16);
const sphere = readInstanceBufferSphere(treeMesh, renderer.createInstanceBuffer(instanceLayout, data));
if (sphere === null || sphere[0] !== 0 || sphere[3] < 3) {
throw new Error("bounds failed");
}인스턴스 버퍼를 모형으로 그릴 때의 경계 구를 주어진 배열에 쓰기. (readInstanceBufferSphere 와 같은 값, 새 배열을 짓지 않는다)
Writes the bounding sphere of an instance buffer drawn with a mesh into a given array. (Same value as readInstanceBufferSphere, no new array)
- sphereArray<number> | Float32Array | Float64Array
- 쓸 칸. ([x, y, z, 반지름], 넷 이상)Array to write. ([x, y, z, radius], four or more)
- meshobject
- createMesh 의 결과.Result of createMesh.
- instanceBufferobject
- createInstanceBuffer 의 결과.Result of createInstanceBuffer.
반환Returnsboolean 행렬이 없어 경계가 없으면 false. (그때는 sphere 를 고치지 않는다)false when there is no bounds because there are no matrices. (sphere is left unchanged then)
import { ToonRenderer, MeshBuilder, createBoxGeometry, writeInstanceBufferSphere, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#808080");
const boxMesh = renderer.createMesh(builder.readArrays());
const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }]);
const data = new Float32Array(16 * 2);
data.set(Matrix4.createTranslation(-2, 0, 0).getElements(), 0);
data.set(Matrix4.createTranslation(2, 0, 0).getElements(), 16);
const sphere = [0, 0, 0, 0];
if (!writeInstanceBufferSphere(sphere, boxMesh, renderer.createInstanceBuffer(instanceLayout, data)) || sphere[3] < 2) {
throw new Error("bounds failed");
}구가 절두체 안에 드는지. (extractFrustumPlanes 의 면 여섯)
Whether a sphere is inside the frustum. (The six planes of extractFrustumPlanes)
- frustumPlanesArray<Array<number>>
- extractFrustumPlanes 의 결과.The result of extractFrustumPlanes.
- sphereArray<number>
- [x, y, z, 반지름].[x, y, z, radius].
반환Returnsboolean 절두체 안에 들거나 걸치면 true.true if inside or straddling the frustum.
짝Counterpart: vanilla-engine is_sphere_in_frustum
import { extractFrustumPlanes, isSphereInFrustum, Matrix4, Vector3 } from "./vanilla.js";
const viewProjectionMatrix = Matrix4.createPerspective(0.8, 1, 0.1, 50);
viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 0, 5), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
const planes = extractFrustumPlanes(viewProjectionMatrix);
if (!isSphereInFrustum(planes, [0, 0, 0, 1]) || isSphereInFrustum(planes, [0, 0, 20, 1])) {
throw new Error("unexpected culling");
}상수Constants
한 모형이 쓰는 뼈대 수의 상한. (셰이더의 유니폼 배열 크기, 엔진 SkinnedModelRenderer 와 같은 96)
Upper limit on the number of joints one model uses. (shader uniform array size, 96, same as the engine's SkinnedModelRenderer)
짝Counterpart: vanilla-engine TOON_MAXIMUM_JOINTS
인스턴스 하나의 수 개수. (행렬 16, 틴트 4)
- 행렬은 아핀 3x4 로 읽는다. 아래 줄 네 칸(원소 3, 7, 11, 15)은 인스턴스 빛남(sRGB r, g, b 와 선형 세기)이다. (Godot MultiMesh, 유니티 BatchRendererGroup 의 3x4 행렬 꼴) Matrix4 원소를 그대로 담으면 아래 줄이 0, 0, 0, 1 이라 빛남이 없다.
Number of values per instance. (matrix 16, tint 4)
- The matrix is read as an affine 3x4. The four values of the bottom row (elements 3, 7, 11, 15) are the instance emission (sRGB r, g, b and a linear intensity). (The 3x4 matrix form of Godot MultiMesh and Unity BatchRendererGroup) Storing Matrix4 elements as they are leaves the bottom row 0, 0, 0, 1, so there is no emission.
반환Returnsnumber
짝Counterpart: vanilla-engine TOON_INSTANCE_FLOAT_COUNT
머티리얼이 그리기마다 묶을 수 있는 텍스처 수의 상한. (유닛 8 ~ 15)
Upper limit of textures a material can bind per draw. (Units 8 ~ 15)
반환Returnsnumber
짝Counterpart: vanilla-engine TOON_MAXIMUM_MATERIAL_TEXTURES
어트리뷰트 자리. (모든 프로그램이 같은 자리를 쓴다, 인스턴스 꼴의 사용자 어트리뷰트는 13 부터)
Attribute locations. (all programs use the same locations, instance layout user attributes start at 13)
짝Counterpart: vanilla-engine TOON_ATTRIBUTE_LOCATIONS
ToonProgramKindenum
그리기의 프로그램 종류. (onBeforeDraw 의 셋째 인자)
Program kind of a draw. (third argument of onBeforeDraw)
import { ToonRenderer, ToonMaterial, ToonProgramKind, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const material = new ToonMaterial({ name: "pulse", uniformChunk: "uniform float pulse;", surfaceChunk: "void applySurface(inout ToonSurface surface) { surface.emission += vec3(pulse); }" });
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#d06060", { 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,
onBeforeDraw: (program, context, kind) => {
if (kind === ToonProgramKind.solid) {
context.uniform1f(program.getUniformLocation("pulse"), 0.3);
}
},
});
renderer.endFrame();| 이름Name | 값Value | 설명Description |
|---|---|---|
solid | solid | 몸.Body. |
outline | outline | 바깥선 껍데기.Outline shell. |
depth | depth | 그림자 깊이.Shadow depth. |