vanilla.js 0.4.0
0.4.0
요약
- 폴더 정리: src/experimental 에 있던 다 자란 기능(3D, 툰 3D, 애니메이션, 컬렉션 등)을 러스트 vanilla-engine 과 같은 폴더로 옮겼다. import.js 로 쓰던 게임은 그대로 돌고, 파일 경로로 직접 import 하던 게임은 새 경로로 바꾼다.
- 게임에서 엔진으로: 출시 게임들(외계행성 광부, aberrant, 종말 생존, 우주생물, 찾았다)이 따로 만들어 쓰던 범용 기능을 엔진 기본으로 넣었다. 창 쌓기(UIWindowLayer, UIWindow, UIConfirmWindow), 로딩, 저장, 시간(AssetLoader, LoadingProgress, LocalStorage, PersistedStore, FixedStepper), 입력 동작(InputActions), 소리 표(SoundSystem), 언어 묶음과 글꼴(LanguagePack, UIFont), 단추와 알림 모션(ButtonMotion, ToastMotion), 마우스 커서(PointerCursor) 같은 것이다.
- 툰 3D: 툰 셰이딩과 화면 공간 바깥선(ToonScreenOutline)을 실시간 툰 렌더링의 정석 꼴로 다시 지었다. 툰 효과(ToonVfx), HDR 마무리(ToonPostProcess), 그림자 아틀라스(ShadowAtlas)도 있다.
- 렌더링: 묶어 그리기와 화면 밖 거르기를 기본으로 켰다. 엔진 루프 밖에서 Graphic 을 직접 써도 그 작업이 끝날 때 엔진이 남은 묶음을 그린다(2D 캔버스와 같다). WebGL 을 직접 다루는 패스를 끼울 때만 그 전에 flushBatch() 를 부른다.
- 러스트 판과 맞추기: 러스트 판에만 있던 범용 기능을 들여와 두 엔진의 공개 API 를 맞췄고, 두 엔진에 같이 있던 버그를 같이 고쳤다.
- UI: UIInputField 가 크롬처럼 낱말 이동과 지우기, 낱말 경계를 다루고, 크롬 textarea 같은 여러 줄 입력(setMultiline)과 엔진 되돌리기, 다시 하기를 한다. UIDocument 는 등록한 이름으로 적어 줄인 번들에서도 같은 문서가 되고, registerEditorTypes() 로 UI 에디터의 종류를 한 번에 등록한다.
- Scene 과 Engine: 씬 꼴과 상관없이 노드의 위젯이 터치를 받는다. 씬마다 그리기 앞에 뷰 좌표를 걸어, Scene 을 바로 이은 씬이 기기 픽셀 배율 2 화면에서 캔버스 왼쪽 위 1/4 에만 그리던 것을 고쳤다.
- 문서: 사이트가 판마다 문서를 지을 자료(공개 API docs/api/0.4.0.json, 가이드 docs/guide/0.4.0)와 뽑는 도구 tools/apidoc.cjs 를 둔다.
- 성능과 안정: WebGL 컨텍스트를 잃어도 되살아나고, 셰이더 짓기 실패를 게임이 받으며, 툰 몸 셰이더 기능 변형과 미리 짓기(조합 목록, 맡기고 기본 몸으로 그리기), 판 비우기, GL 상태 캐시, 글리프 아틀라스로 실기기(아이폰, 아이패드 사파리)의 프레임을 줄였다. GPU 메모리 셈은 기본 꺼짐이다.
- 옮길 것: 공개 API 나 쓰임이 바뀐 곳은 맨 아래 '옮기는 법' 절에 한곳으로 모았다. 게임이 바꿔야 하는 것은 그 절만 보면 된다. (Scene 터치, FbxLoader 이름, 씬 그리기 좌표, Singleton, Color, JsonAsset.load, List 와 Dictionary 의 콜백, ToonScreenOutline, 툰 셰이딩, isVisible, ToonVfx 자리, 그림 경로, Scene 배경, viewScaleMode 기본)
새 기능과 바뀐 것
- WebGL 컨텍스트 잃음 처리(정석: 유니티와 브라우저 게임의 webglcontextlost 와 webglcontextrestored 처리): 잃으면 엔진이 preventDefault 로 되살림을 받고, 잃은 동안 그리지 않고(씬 갱신만 한다, GL 을 부르지 않아 null 을 받아 던지던 예외가 프레임마다 쌓이지 않는다), 엔진 오류 길(console.error)로 한 번 알리고, 리스너에 lost 를 넘긴다. 되살아나면 엔진이 지은 기본 자원(기본 셰이더 프로그램, 버텍스 어레이, 흰 텍스처, 묶어 그리기, 파티클, 섞기 셰이더, 그림 텍스처, 글자 아틀라스)을 다시 짓고 그리기를 잇고 restored 를 넘긴다. 더한 것: Engine.addGraphicContextEventListener, removeGraphicContextEventListener, dispatchGraphicContextEvent, 열거 GraphicContextEvent(lost, restored), Graphic.isContextLost(). 게임이 지은 GL 객체(자기 셰이더 프로그램, 렌더 타겟, ToonRenderer 와 그 메시, 그림자 지도)는 잃은 컨텍스트의 것이라 엔진이 다시 짓지 못하니, 게임이 restored 에서 다시 짓는다. 전에는 잃어도 preventDefault 를 하지 않아 되살아나지 못했고 프레임마다 예외가 났다
- 셰이더 짓기 실패 알림(정석: 유니티의 셰이더 컴파일 오류 보고와 같은 꼴): 엔진이 셰이더 프로그램을 짓지 못하면(ToonRenderer 의 머티리얼, ScreenEffect 의 패스, Graphic.resolveShaderProgram 의 프로그램, ToonView3D 의 렌더러) 엔진 오류 길(console.error)에 더해 { kind, name, error } 를 그래픽 오류 리스너에 한 번 알린다. 더한 것: Engine.addGraphicErrorListener, removeGraphicErrorListener, dispatchGraphicError, 열거 GraphicErrorKind(shaderBuildFailed). 짓지 못한 프로그램은 전처럼 다시 짓지 않고 건너뛰어 그린다. 컨텍스트를 이미 잃은 뒤의 실패(gl.isContextLost())는 셰이더 탓이 아니라 알리지도 기억하지도 않고, 되살아난 뒤 다시 짓는다(전에는 이때 null 을 기억해 되살아나도 그 머티리얼이 영영 그려지지 않았다)
- GPU 메모리 셈(유니티 프로파일러의 메모리 모듈처럼 텍스처, 렌더버퍼, 버퍼가 쓰는 GPU 메모리를 보기): Graphic.readGpuMemoryUsage(), Engine.readGpuMemoryUsage() 와 클래스 GpuMemoryTracker(엔진 밖에서 만든 컨텍스트는 GpuMemoryTracker.attach)를 더했다. 컨텍스트에서 texImage2D, texStorage2D, generateMipmap, renderbufferStorage(Multisample), bufferData 와 지우는 함수를 가로채 객체마다 바이트를 적고, { totalBytes, canvasBytes, kindTable(texture, renderbuffer, buffer 별 count, bytes), ownerList(주인별, 큰 것부터) } 를 돌려준다. 주인은 객체를 지은 호출 스택의 위쪽 세 칸이다. 바이트는 형식과 크기로 셈한 이름값이다(멀티샘플은 샘플 수를 곱하고, 캔버스의 멀티샘플은 4 로 가정하며, 드라이버 정렬은 모른다). 개발용이고 화면은 그대로다. 기본은 꺼 두어 프레임 CPU 몫이 0 이고 GL 짓기 호출은 브라우저 본디 함수 그대로다. 켜는 길: EngineConfiguration.trackGpuMemory = true(엔진이 처음 짓는 자원까지 센다), 또는 나중에 Engine.enableGpuMemoryTracking(), Graphic.enableGpuMemoryTracking()(그 뒤에 지은 것부터 센다), 엔진 밖에서 만든 컨텍스트는 GpuMemoryTracker.attach. 켰는지는 isGpuMemoryTrackingEnabled(). readGpuMemoryUsage() 는 꺼져 있으면 그때 켜고 그 뒤에 지은 것부터 센다
- 툰 몸 셰이더 기능 변형(정석: 유니티 셰이더 키워드 변형처럼 쓰지 않는 갈래를 프로그램에서 뺌, 화면 그대로): 렌더러가 그리기의 텍스처(바탕, 빛남, 데칼, 맷캡, 천사 고리), 빛 묶음(램프 텍스처, 음영 단 두 개 이상, 테두리 빛 둘, 빛 세기 제한)을 보고 쓰는 기능 비트로 몸 조각 셰이더를 따로 짓는다. 쓰지 않는 갈래의 글이 컴파일 때 빠져 화소마다 비용이 준다(아이폰 SE2 광부 외곽선 그림자 끈 판 프레임 간격 앞 판 28.6
31.6 ms 대 24.725.3 ms, 거기서 점광만 끄면 24.525.5 대 21.922.6 ms, 모두 켠 판은 같음). 변형은 처음 그릴 때 짓고(그때 한 프레임 끊길 수 있다, ToonRenderer.prepareMaterial 은 기본 프로그램만 미리 짓는다), 변형 수는 쓰는 비트 조합만큼이다. 기본 프로그램은 모든 갈래를 켠 그대로다. 게임이 할 일과 API 는 없다. composeToonProgramSources 에 끝 매개변수 disabledFeatures 를 더했다(기본 없음) - 후처리를 쓰는 게임의 캔버스 antialias 권고(문서만, 동작 그대로): ToonPostProcess 가 자기 MSAA 판에 그리므로 그걸 쓰는 게임은 EngineConfiguration.antialias 를 false 로 짓는다. true 면 캔버스 자체가 MSAA 라 화면에 옮기는 패스와 UI 가 표본마다 섞여 값이 더 든다(맥미니 2560x1440 툰 후처리 장면 GPU 처리량 6.89 → 6.49 ms, 끈 판 6.81 → 5.22 ms)
- GPU 처리량 재기(유니티 프로파일러의 GPU 모듈, 언리얼 stat gpu 처럼 GPU 가 그리는 시간을 따로 보기): Engine.measureGpuThroughput(frameCount = 120) 을 더했다. 지금 장면을 씬 갱신(tick) 없이 엔진 프레임과 같은 그리기 길(엔진 루프의 씬 그리기를 뗀 같은 함수)로 잇달아 그리고 1 화소 readPixels 로 GPU 를 기다린 프레임당 벽시계 시간을 돌려준다({ frameCount, chunkFrameCount, millisecondsPerFrame, chunkMillisecondsPerFrame }). 렌더러, GPU 프로세스, GPU 실행 가운데 가장 느린 단의 몫이라 GPU 가 가장 느리면 GPU 가 실제로 그리는 시간이다. 크롬 트레이스의 GPU 프로세스 메인 스레드 시간은 명령을 푸는 CPU 시간이라 GPU 가 그리는 양이 바뀌어도 거의 움직이지 않는다(로비 꼴 장면에서 바깥선을 켜고 끄면 1.98, 1.99 ms). 다음 rAF 부터 데움 10 프레임 뒤 30 프레임씩 rAF 하나에 한 덩이를 그려 한 번에 길게 막지 않고, 재는 동안 엔진 시간, 입력, 엔진 프레임 함수, 프레임 번호, 화면 크기 맞추기, 찍기는 서 있으며, 다 재면 엔진 루프가 이어 돈다. 같은 상태를 되풀이해 그리므로 그림자 onChange 같은 캐시는 다시 굽지 않는다. 재는 도구 tools/perftrace.mjs 에 --throughput [프레임 수 120] 을 더해 트레이스 뒤에 페이지의 전역 엔진으로 이 함수를 불러 '(6) GPU 처리량' 줄을 찍는다(--attach, measureAttached(page, { throughput: 120 }) 도 같다, 엔진이 없거나 이 함수가 없는 판이면 '모름'). 맥미니 M2 Pro 헤드리스 크롬 1280x720 에서 로비 꼴 장면을 엔진 루프로 돌린 tests/graphics3d/toonlobbyengine.html(ToonPostProcess RGBA16F, MSAA 4, 블룸 다섯 단)의 처리량은 3.15 ms, 바깥선을 끄면(?outline=0) 1.58 ms 다. toonpost 예제 1.17 ms, toonshowcase 0.92 ms, panelayout 0.24 ms. (tests/core/gputhroughputchrome.test.mjs)
- 3D 색 공간 칸(유니티 Player Settings 의 Color Space: Gamma/Linear 꼴): EngineConfiguration.colorSpace 와 열거 ColorSpace(gamma, linear)를 더했다. 기본은 gamma 이고 지금까지와 화면이 바이트까지 같다. linear 면 툰 3D 가 정석 선형 길로 그린다. ToonRenderer.createTexture 가 색 텍스처(바탕색, 빛남, 데칼, 매트캡, 천사 고리, 램프)를 SRGB8_ALPHA8 로 올려 GPU 가 선형으로 풀고(거르기와 밉맵이 선형 공간), 셰이더는 그 텍스처에 pow 2.2 를 걸지 않으며, 넘기는 색(꼭짓점 색, 틴트, 빛남 색, 데칼 색, 바깥선 색)은 sRGB 표준 곡선(IEC 61966-2-1)으로 선형으로 바꿔 곱하고 섞는다(바탕색 x 틴트, tintAmount 섞기, 데칼). 화면 출력, ToonPostProcess 의 톤매핑 뒤, HDR 의 껍데기 바깥선과 ToonScreenOutline 선 색, GLB 바탕색(baseColorFactor 를 꼭짓점 sRGB 색으로)도 같은 곡선이다. 노멀, 마스크 같은 자료 텍스처는 createTexture 의 isColorData: false 로 RGBA8 에 그대로 올린다(감마에서는 가르지 않음). linear 면 엔진이 짓는 3D 셰이더에 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어가고, 머티리얼 조각에는 sRGB 색을 ToonSurface.baseColor 의 공간으로 바꾸는 toSurfaceColor(vec3) 를 더했다. ToonRenderer, ToonPostProcess, ToonScreenOutline 은 options.colorSpace 를 받고(기본은 엔진의 값, 엔진이 없으면 gamma) getColorSpace 로 알린다. composeToonProgramSources, ToonRenderer.readProgramSources, ToonScreenOutline.readProgramSources, readGlbArrays, readGlbNodeArrays 는 마지막 인자 colorSpace 를 받는다. Engine.getColorSpace, Graphic.getColorSpace 를 더했다. 2D(Graphic 의 2D 묶음, 글자, UI)는 어느 값이든 감마 공간에서 합성한다. 툰 예제 다섯과 재기 장면 둘이 gamma 에서 고치기 전과 바이트까지 같고, linear 는 모두 sRGB 로 바꾸던 갈래(jstoonsrgb)와 바이트까지 같다. (tests/graphics3d/tooncolorspacechrome.test.mjs)
- 툰 유니폼 블록 버퍼를 값마다 짓고 한꺼번에 지우지 않기(버퍼 풀, 쓰는 중인 버퍼를 고치지 않는 고리): 프레임 블록(ToonFrame)은 값이 바뀔 때마다 새 GPU 버퍼를 짓던 것을, 지어 둔 버퍼를 돌려 쓰게 바꿨다. 값이 같은 버퍼가 있으면 그것을 묶고(올림 없음), 새 값은 beginFrame 여덟 번 동안 쓰지 않은 버퍼에 bufferSubData 로 쓴다(GPU 가 아직 읽는 버퍼를 고치지 않는다, 모자라면 새로 짓는다). 멈춘 장면의 GL 호출은 앞과 같다. (한 버퍼의 여러 칸을 bindBufferRange 로 고르는 꼴도 재 봤는데 멈춘 로비와 광부 꼴의 GPU 프로세스 가운데가 늘어 버퍼마다 한 칸으로 뒀다) 재질 블록과 바깥선 블록은 갈래 한도(1024)에 닿으면 갈래를 통째 지우고 꼴 기억을 비우던 것을, 오래 안 쓴 블록 하나(시계 꼴)를 내보내고 그 버퍼에 새 값을 쓰는 것으로 바꿨다(내보낸 블록을 쥔 기억 칸은 다음 그리기에 값을 다시 푼다). 카메라가 움직이면 바뀐 패스마다 버퍼를 하나씩 짓고 1024 개가 차면 한 프레임에 모두 지우던 일(로비 꼴 500 프레임쯤마다)이 없다. 카메라가 도는 로비 꼴(lobbymove, toondrawbench.mjs, 240 프레임 합)의 createBuffer 983 → 521(장면 짓기 507 포함, 옛것은 512 프레임쯤에 deleteBuffer 1024 가 한 프레임에 몰린다), 판의 방을 카메라가 돌며(roommove) 642 → 180(짓기 167 포함), 멈춘 네 장면(lobby, room, roomitem, miner)의 GL 호출은 처음 프레임 블록을 쓸 때의 bufferSubData 셋만 다르다. GPU 프로세스 메인 스레드(tools/perftrace.mjs 10 초, 옛것과 두 번 번갈아, 헤드리스 크롬, 맥미니, 960x540): lobbymove 가운데 1.70, 1.95 → 1.27, 1.70 ms, p95 2.94, 3.77 → 1.84, 3.04 ms, 가장 큰 값 6.73, 6.44 → 2.94, 3.84 ms, roommove 가운데 1.27, 1.19 → 1.03, 1.20 ms, 가장 큰 값 6.92, 7.95 → 2.19, 3.92 ms, 600 프레임에 5 ms 넘는 프레임 lobbymove 1, 3 → 0, 0, roommove 1, 1 → 0, 0, 멈춘 lobby 가운데 1.62, 1.66 → 1.61, 1.70 ms(같음). 여섯 장면(lobby, lobbymove, room, roomitem, roommove, miner) 모두 화면 바이트가 같다. (tests/graphics3d/toonuniformblockchrome.test.mjs, toondrawbench.mjs 의 lobbymove, roommove 와 240 프레임 합, toonscenepage.html)
- 툰 화면 바깥선 가는 선 길(유니티 URP 화면 공간 외곽선과 같은 꼴, 굵기 반지름 안 이웃을 한 번에 보기): ToonScreenOutline 이 굵기 약 3.24 픽셀(2 x sqrt(4.5) - 1)까지는 점프 플러딩(씨앗, 모으기, 넓히기 셋) 없이, 씨앗 고르기와 같은 차례로 화소마다 바깥 선과 꺾임 선의 첫 경계 쪽을 담은 판(R8UI 한 바이트)을 고르고, 섞기가 둘레 3 x 3 화소의 씨앗을 점프 플러딩 마지막 걸음과 같은 차례로 보아(아홉 번 읽기, 갈래 없는 고르기) 가장 가까운 것까지의 거리로 덮는 몫을 셈한다. 광부 키우기가 쓰는 굵기(1.7 ~ 2.7 픽셀)가 모두 이 길이다. 선의 판 뒤 화면 전체 패스가 여섯(씨앗, 모으기, 넓히기 셋, 섞기)에서 둘(가면, 섞기)이 되고, 화소마다 쓰는 판이 RGBA16UI 셋(24 바이트)에서 R8UI 하나(1 바이트)가 된다. 굵은 선과 선 색 표는 지금 길 그대로이고, 씨앗 판과 넓히기 판은 처음 굵은 선을 그을 때 짓는다(가는 선만 쓰면 짓지 않는다). 판을 통째로 덮어쓰는 패스(가면, 씨앗, 모으기, 넓히기, 덮는 몫)는 앞에 판 비우기(clearBufferuiv, clearBufferfv)를 불러 타일 GPU 가 옛 내용을 읽어 들이지 않게 한다. invalidateFramebuffer 는 쓰지 않는다. 아이패드 미니 6 과 아이폰 SE2 사파리에서 이 판들에 부르면 프레임마다 약 10 ~ 25 ms 가 붙었다(아이패드 광부 값 배율 0.75 에서 바깥선 몫 31.7 에서 약 5.5 ms, SE2 12.4 에서 1.6 ms, 같은 프레임 연달아 그려 센 값). 비우기로 바꾸면 그 값이 붙지 않고 화면은 같다. 선의 자리와 굵기는 같다(선 색이 다른 두 번호가 맞닿은 자리에서 같은 거리의 토막 가운데 고르는 차례가 점프 플러딩 앞 걸음에서 씨앗을 넘겨받은 빈 화소만큼 달라 몇 화소의 색만 바뀐다). readProgramSources 는 일곱을 돌려준다(가는 선의 가면, 가는 선 섞기를 뒤에 더함). getLineTarget 에 edgeMaskTexture, outlinePath 가 더해지고, seedTexture 와 jumpFloodTextures 는 굵은 선을 긋기 전에는 비어 있다. 같은 까닭으로 모서리 어둠(ToonPostProcess.drawAmbientOcclusion 의 세 패스), 블룸(BloomEffect 의 밝은 몫과 흐림, MultiLevelBloomEffect 의 뽑기와 줄이기, 위 단에 더하는 키우기는 빼고)도 판을 통째로 덮어쓰는 패스 앞에 판 비우기를 부른다(화면은 같다).
- 소리 스트리밍 읽기(유니티 AudioClip 의 Load Type, 언리얼 사운드 웨이브 스트리밍, 웹의 HTMLMediaElement 를 MediaElementAudioSourceNode 로 그래프에 잇는 꼴): AudioAsset 에 읽기 방식 AudioLoadType(automatic, decompressOnLoad, streaming)과 setLoadType, getLoadType, isStreaming, getStreamUrl 을 더했다. 지금까지는 모든 소리를 decodeAudioData 로 통째로 PCM 으로 풀어 3 분 스테레오 배경음 하나가 약 61 MiB(float32)를 들었다. 스트리밍은 압축된 파일을 미디어 요소가 조금씩 풀어, AudioPlayer 가 플레이어마다 미디어 요소 하나를 같은 GainNode 에 잇는다. 재생, 멈춤, 반복, 음량, 음소거, 빠르기(음 높이도 바뀜), 위치(getTime, setTime), 끝(isPlaying 이 거짓)이 통째로 푼 소리와 같고, 오디오 컨텍스트가 멈추면(탭이 숨음, 음소거) 미디어 요소도 멈췄다가 이어 튼다. AudioAsset 의 기본은 통째로 풀기(decompressOnLoad, 유니티 AudioClip Load Type 기본과 같다)이고, automatic 을 고른 애셋만 1 MiB(AUTOMATIC_STREAMING_BYTE_THRESHOLD)보다 큰 파일을 스트리밍한다(받는 머리의 Content-Length 로 먼저 가려 몸을 받지 않는다). 엔진 SoundSystem 소리 표는 loadType 칸을 받고, 없으면 배경음악(isMusic)은 streaming, 효과음은 decompressOnLoad 다. 직접 AudioAsset 을 쓰는 코드가 스트리밍을 쓰려면 setLoadType 을 건다. 실기기 확인: 아이폰 SE2, 아이패드 미니 6(iOS 27.2.1)에서 첫 누름 뒤 소리가 나고(RMS 0.07~0.14), 미디어 요소 play() 거부 0/62, 탭이 숨었다 돌아오면 이어 틀고, 반복이 되고, 읽기는 SE2 137 ms 대 통째로 풀기 8,618 ms 였다. 3 분 128 kbps MP3 를 맥 헤드리스 크롬에서 잰 값: 통째로 풀기는 읽기 169 ms, 크롬 프로세스 메모리 +154 MB, 스트리밍은 읽기 7 ms(메타데이터만), +11 MB(트는 동안 +29 MB), 소리가 나기까지 둘 다 5 ms 안.
- UIInputField IME 세 가지(DOM 입력, 한 줄과 여러 줄): 글을 고른 채 조합하면 조합 중 보이는 글이 [고른 글 앞, 조합 글, 고른 글 뒤] 다(getDisplayText, 그리기, 커서와 밑줄 자리, 지금까지는 고른 글을 남긴 채 옛 커서 자리에 끼웠다). compositionstart 에서 DOM 선택이 엔진 선택과 다르면(틱이 맞추기 전에 키로 옮기거나 골랐으면) 엔진 선택을 맞추고 되돌리기 묶음을 끊는다(beforeinput 과 같다, 지금까지는 확정 글이 앞 치기 묶음에 붙어 Cmd + Z 가 바꾸기 전 값을 건너뛰었다). 조합 중 setText 는 조합 상태와 조합 글을 비운다(지금까지는 조합 상태에 갇혀 엔진 값이 DOM 입력과 어긋났다).
- 뼈 자세 고리(언리얼 AnimBP 의 Transform (Modify) Bone, 유니티 LateUpdate 의 뼈 덮어쓰기와 같은 꼴): writeSkinPose 에 일곱째 인자 poseAdjust 를 더했다. 움직임을 읽어 섞은 뒤, 스킨 행렬을 짓기 전에 뼈마다 지역 변환(자리, 돌림, 크기)을 고친다. 함수면 (locals, skeleton) 으로 불러 그 함수가 고치고(locals 의 배열은 그 부름만의 것이라 제자리에서 고쳐도 뼈대의 쉬는 자세가 바뀌지 않는다), 배열이면 뼈마다 고침 표({ nodeIndex 또는 name, translation, rotation, scale, mode, weight })로 건다. 표를 거는 adjustBones(locals, skeleton, modifiers) 와 고침 꼴 BoneModifyMode(add 는 자리를 부모 공간에서 더하고 돌림을 그 뼈 공간에서 뒤에 곱하고 크기를 곱함, replace 는 준 값으로 바꿈)를 더했다. weight 는 고치기 앞과 뒤 사이의 몫이다. 고리를 주지 않으면 지금과 비트까지 같고, 한 뼈를 고치면 그 뼈와 그 아래 본만 바뀐다.
- 3D 카메라 흔들림(유니티 Cinemachine Impulse, 언리얼 Camera Shake 꼴): CameraShake 를 더했다. add(options) 의 흔들림마다 자리 3 축과 돌림 3 축(pitch, yaw, roll)의 세기(amplitude, rotationAmplitude, 축마다 몫 positionAxes, rotationAxes), 주파수(frequency, 기본 10), 길이(duration), 오름(attack), 잦아듦((1 - 나이 / 길이) 의 decayExponent 제곱, 기본 2), 나이(age, 늦게 보인 사건을 그 나이로 넣으면 처음부터 넣은 것과 같은 값이 이어짐, 음수면 늦게 시작), 씨앗(seed)을 받는다. 결은 축마다 주파수가 조금 다른 사인파 둘이고, 사는 흔들림은 겹쳐 더하며, 같은 씨앗이면 같은 값이다. update(초), read()(카메라 지역 축의 { position, rotation }), isShaking, clear 가 있다. 거는 곳으로 Camera3D.setViewOffset(position, rotation)(보기 행렬 마지막에 카메라 지역 덧붙임, 셈하는 길과 원 행렬 모두, getEyePosition 은 덧붙이기 앞 값)과 게임이 셈한 보기 행렬에 거는 createOffsetViewMatrix(viewMatrix, position, rotation) 를 더했다. ToonVfx 의 2D 흔들림(addShake, readShake)과 Shaker 는 그대로다.
- glTF 양자화 읽기(KHR_mesh_quantization): 툰 GLB 읽기(readGlbArrays, readGlbNodeArrays, readGlbNodeInfos)와 SkinnedModel 이 꼭짓점 속성을 정수로 담은 GLB 를 읽는다. 정규화 정수는 glTF 명세의 공식(부호 있는 것은 max(c / 127, -1), max(c / 32767, -1))으로 나누고 정규화가 아닌 정수는 값 그대로 읽는다. 위치의 되풀이는 노드 변환이나 inverseBindMatrices 가 맡고, 텍스처 좌표는 재질 텍스처의 KHR_texture_transform 을 구워 넣는다. 움직임의 정규화 정수 돌림도 읽는다. 이름 없는 메시 노드는 이름 있는 부모 노드의 부품에 든다(양자화 도구가 되풀이 변환을 맡기는 잎 노드). extensionsRequired 에 읽지 못하는 확장(EXT_meshopt_compression, KHR_draco_mesh_compression 등)이 있으면 분명한 오류를 던진다. 외계행성 광부의 채굴선 모형을 gltfpack 기본 양자화(압축 없음)로 바꾸면 파일 1.78 MB 에서 1.15 MB, zip 1.06 MB 에서 0.58 MB 이다. (tests/graphics3d/meshquantization.test.mjs)
- glTF 노멀 없는 프리미티브(glTF 2.0 명세 'Using Primitive Data': 노멀이 없으면 평평한 노멀이고 탄젠트는 무시한다): 툰 GLB 읽기(readGlbArrays, readGlbNodeArrays)가 노멀이 없는 프리미티브를 지금까지는 빼서 예제 여우(fox.glb)가 빈 그림이었다. 이제 꼭짓점을 번호 차례대로 삼각형마다 풀고 삼각형마다 (p1 - p0) x (p2 - p0) 을 길이 1 로 줄여 세 꼭짓점에 준다(넓이 0 인 삼각형은 0). 몸으로 새로 짓는 바깥선 껍데기도 그 프리미티브를 넣는다. SkinnedModel 은 노멀이 없으면 업로드 때 부드러운 노멀(번호 있는 메시는 꼭짓점마다 면 노멀을 더해 평균)을 지어 명세와 달랐다. 이제 interpretContent 가 같은 셈으로 꼭짓점을 풀어 평평한 노멀을 주고 indices 는 null 이다(위치, 텍스처 좌표, 조인트, 가중치, 모프 델타도 푼다). 메시 빌더의 노멀 길이(addPart, addTriangles, addTriangleShell 의 노멀, 바깥선 밀기의 합)를 러스트 판과 같은 sqrt(x * x + y * y + z * z) 로 셈해, 대칭인 모형에서 노멀이 서로 지워지는 점의 껍데기 값까지 러스트 판과 바이트로 같다. 노멀이 있는 GLB(예제와 채굴선, 마네킹, 그 양자화판)의 배열은 바이트까지 그대로다. (tests/graphics3d/meshquantization.test.mjs, modelreading.test.mjs)
- GameScene 로딩이 덮어쓸 수 있는 훅에 기대지 않게: 첫 프레임 전에 load 가 불렸을 때의 로딩 시각과 로딩 화면 누름을 drawOnLoad 대신 load 가 건 엔진 프레임 함수(엔진이 로딩 중 프레임마다 부르는 자리)가 잡는다. 게임이 drawOnLoad 를 super 없이 덮어쓰면 load 가 끝나지 않고 initialize 도 안 불린 채 오류 없이 멈추던 것을 고쳤다. (tests/core/gamesceneloadchrome.test.mjs)
- 찍기 모드 결정성(러스트 판과 같게): 찍기 모드(?capture=)에서 씬을 불러온 뒤 로딩 화면 0.3 초 기다림(SceneManager.loadScene 의 setTimeout 300)과 GameScene, UIScene 의 최소 노출 시간 기다림(setTimeout 50 으로 보던 것, UIScene 은 Date.now)을 엔진 시계(프레임마다 1/60 초)로 엔진 프레임마다 센다. 0.3 초를 다 센 프레임의 머리(씬 갱신 앞)에서 initialize 해 러스트 판처럼 그 프레임부터 씬을 그린다. 그림은 시간 한도로 나누지 않고 한 번에 올린다. 불러오는 동안(애셋 받기처럼 실제 시간이 드는 것, GameScene 과 UIScene 은 loadAssets 까지) 프레임 번호와 시계를 올리지 않아, 다 받은 뒤부터 센다. 같은 예제를 두 번 찍으면 같은 프레임 번호의 그림이 바이트까지 같다. (tests/core/capturedeterminismchrome.test.mjs)
- 툰 3D 묶음 이름 ToonMesh, ToonGlb 를 걷었다. 메시 빌더(meshbuilder.js)와 GLB 읽기(glbmeshreader.js)의 함수와 클래스는 이름마다 바로 내보낸다(러스트 판과 같다). 러스트 판의 ToonMesh 는 렌더러의 모형(ToonRenderer 가 짓는 것)이라 같은 이름을 다른 뜻에 쓰지 않는다. flushSpriteBatch 도 걷었다.
- 맨 위 이름을 러스트 판과 같은 집합으로: import.js 가 폐기 예정 Camera(Camera2D 가 덮는다), SceneManager(엔진 안쪽, Engine.getSceneManager 도 감춤), List, Dictionary, Queue, Stack(언어의 배열과 Map 을 쓴다, 러스트 판은 Vec, HashMap, VecDeque), Singleton 을 내보내지 않는다. Engine.getAllLoadedScenes() 를 더했다(러스트 판 get_all_loaded_scenes). 툰 메시 빌더와 GLB 읽기 함수는 러스트 판처럼 이름마다 낸다(MeshBuilder, createBoxGeometry 같은 도형 함수, createPartMatrix, readColorValues, readGlbArrays, readGlbImages, decodeGlbImage, readGlbNodeArrays, readGlbNodeInfos, readAnimationSwing, writeSkinPose). 이름 공간 ToonMesh, ToonGlb 는 폐기 예정으로 남겨 두고 다음 판에서 뺀다(러스트 판의 ToonMesh 는 렌더러의 메시라 한 이름이 두 뜻이 되지 않게).
- 러스트 판에만 있던 공개 기능(같은 이름): ViewManager.limitRenderPixelRatio(devicePixelRatio) (상한을 건 배율, calculateViewRect 가 쓴다), GraphicsQualityGovernor.applyPageQuery(liteKey) (지금 페이지 주소의 쿼리로 덮어쓰기, applySearchText(location.search) 와 같다), DevTools.inspectNode(node) (보이고 Node Hierarchy 탭으로 바꾸고 조상을 펼쳐 그 노드를 고른다), Graphic.measureTextWithFontString(fontString, text) (지금 글꼴을 바꾸지 않고 재기), LocalStorage.setStorageDirectory(storageDirectoryPath) (러스트 판 데스크탑의 저장 폴더, 원본은 브라우저 저장소를 써 아무것도 하지 않는다).
- UIDocument 를 전역 상태 없는 인스턴스로(러스트 판 UIDocument::new 와 같게): 종류 표(컴포넌트, 노드), 그림 해석기, 노드 참조와 그림을 맡아 두는 목록이 모듈 전역이던 것을 문서 객체마다 든다. new UIDocument() 가 엔진 기본 종류를 등록해 두고, 정적이던 setImageResolver, resolveImage, serializeNode, deserializeNode, toJsonText, fromJsonText, collectGeneratedComponentTypes, getComponentTypeNames, registerNodeType, registerComponentType, registerEditorTypes, saveByReflection, loadByReflection 이 인스턴스 메서드가 된다. 상태가 없는 getReflectedProperties, findNodePath, findNodeByPath 는 그대로 정적이다. 러스트 판과 같은 이름으로 loadImages(jsonText)(문서의 imagePath 마다 ImageAsset 을 요청하고 읽기 프로미스 목록을 돌려준다), bindPendingImages()(맡아 둔 그림을 넣고 아직 읽히는 수를 돌려준다, fromJsonText 와 deserializeNode 가 끝에 부른다), createComponent(node, typeName), getNodeTypeName(node) 를 더했다. serializeNode 와 deserializeNode 는 러스트 판처럼 노드 참조를 그 노드 기준 경로로 적고 잇는다. 찾지 못한 그림은 경고를 낸다. getComponentType, getSerializeRootNode, saveNodeReferences, loadNodeReferences 는 감췄다(러스트 판에 없는 안쪽 함수). UIListView 에 setTemplateNodeWithDocument(templateNode, uiDocument) 를 더했고(setTemplateNode 는 새 문서로), Visual.createNode 는 문서를 받는다(러스트 판 create_node 와 같게). UI 에디터와 비주얼 에디터는 저마다 문서 하나를 든다.
- ToonView3D 화면 사각형과 출력(러스트 판 Rect, ToonViewOutput 과 같게): getScreenRect() 가 { x, y, width, height } 객체 대신 Rect(복사본)를 돌려준다. 그리기 함수가 (renderer, camera, screenRect, webGL2RenderingContext, output) 이 되어, screenRect 는 그릴 사각형 Rect 이고, 화면 사각형 객체에 실려 있던 outputFramebuffer, outputViewport 는 다섯째 인자 output 객체({ outputFramebuffer, outputViewport })로 옮겼다.
- 원본에만 있던 공개 함수 정리(러스트 판과 같은 표면): 안쪽에서만 쓰던 WorldNode.isComponentDrawCulled, Camera3D.refreshMatrices, LocalStorage.readStorage 를 감췄다(러스트 판도 공개하지 않는다, 행렬은 게터가 알아서 다시 셈한다). 아무 일도 하지 않던 UIButton.setStateEvent 를 뺐다. 러스트 판에 같은 이름의 WorldNode::copy_content_size_to, ShadowAtlas::get_light_count 를 더했다.
- 기본 글꼴(러스트 판 default_font_url, 글꼴 이름 "default" 와 같게): EngineConfiguration.defaultFontUrl 의 처음 값이 jsDelivr 의 DOSGothic 주소에서 빈 글로 바뀌어, 엔진은 쓰지 않는 글꼴을 늘 받지 않는다. 주소를 주면 그 글꼴을 글꼴 이름 "default" 로 올린다(전에는 "DOSGothic"). 글꼴이 없는 글(Text, ShadowText, DynamicFont, buildFontString(null))은 시스템 글꼴 사슬 대신 엔진 기본 글꼴 사슬 DEFAULT_FONT_FAMILY_STRING('"default", ' 다음 SYSTEM_FONT_STRING)을 써서, 러스트 판 "32px default" 처럼 기본 글꼴이 있으면 그것을, 없으면 시스템 글꼴을 고른다. 통계 창도 "16px default" 로 그린다.
- 굽는 컴포넌트의 색을 Color 로(러스트 판 ShadowText, SoftShade, ShadowImage 와 같게): ShadowText, SoftShade, ShadowImage 가 색을 "#rrggbb" 글 대신 Color 로 담는다. 세터는 전처럼 Color 와 색 글을 다 받고 받은 Color 는 복사해 담는다. SoftShade.getColor() 는 Color, ShadowImage.getImageColor() 는 Color 나 null 을 돌려주고, UIDocument 는 ShadowImage 의 ImageColor 를 러스트 판처럼 수 넷 배열([r, g, b, a])로 적는다(색 글로 적힌 옛 문서도 그대로 읽는다). ShadowText 의 글 색 알파는 글자 불투명도다. 모듈 함수 readColorText 는 readColor(Color 를 돌려줌)로, buildRGBAString 은 Color 를 받는다.
- 화면 페이드 손잡이(러스트 판 ScreenFadeHold, fade_screen_with_hold 와 같게): ScreenFadeHold(release, isReleased) 와 GameScene.fadeScreenWithHold(onDark) 를 더했다. 다 어두워지면 onDark 에 새 손잡이를 넘기고 release 할 때까지 어둡게 둔다. fadeScreen 의 onDark 도 Promise 말고 ScreenFadeHold 를 돌려주면 release 할 때까지 어둡게 둔다(러스트 판 fade_screen 이 Option
를 받는 것과 같다). import.js 가 ScreenFadeHold 를 내보낸다. - 예약어 이름 없애기(러스트 판과 같은 이름): 두 엔진 모두 예약어(use, move, loop, in)를 이름으로 쓰지 않는다. Cooldown.use() 를 빼고 activate() 하나로(러스트 판 activate), FullscreenPass.use() 와 ShaderProgram.use() 는 useProgram()(러스트 판 use_program), PointerGesture.move(x, y) 는 movePointer(x, y)(러스트 판 move_pointer), Action.loop(조건, 안쪽) 은 repeatWhile(조건, 안쪽)(러스트 판 repeat_while), Tween.easingFunction 의 in, out, inOut 은 easeIn, easeOut, easeInOut(러스트 판 ease_in, ease_out, ease_in_out). 타임라인 자료의 이징 이름("quadratic.in" 같은)은 자료 꼴이라 그대로다.
- 맨 위 이름 맞추기(러스트 판과 같은 이름): 개발자 도구 클래스 이름을 DEVTools 에서 DevTools 로 바꿨다(러스트 판 DevTools 와 같다). 글자 안티앨리어싱은 두 엔진 모두 Graphic 메서드다: Graphic.setTextAntialiasEnabled(참 거짓), isTextAntialiasEnabled()(러스트 판 Graphic::set_text_antialias_enabled, is_text_antialias_enabled). 안티앨리어싱은 그 Graphic 에만 걸리고, 바꾸면 이미 만든 글도 다음 그리기부터 새 꼴로 그린다(전에는 모든 Graphic 이 같이 쓰는 값이었고 바꾼 뒤 새로 굽는 글에만 걸렸다).
- UIInputField 여러 줄 입력과 되돌리기(러스트 판 set_multiline, set_line_height, set_tab_size, get_scroll_top, set_scroll_top, can_undo, can_redo, TextEditBuffer 의 묶음 규칙과 같게): setMultiline(참) 이면 크롬 textarea 같은 여러 줄 입력이다(DOM 입력은 숨긴 textarea). 글은 white-space: pre-wrap, overflow-wrap: break-word 처럼 줄바꿈 문자와 폭으로 나누고, 줄 나눔 자리는 크롬 자신의 줄 나누기에서 읽어 러스트 판(크롬 158 textarea 에서 뜬 30 글과 같은 셈)과 같은 줄이 된다. Enter 는 줄을 넣고(제출하지 않는다), 위아래는 첫 위아래 이동의 가로 자리를 지키고, PageUp, PageDown, Home, End(보이는 줄의 앞과 끝), Ctrl(맥은 Cmd) + Home, End(맥은 위, 아래)와 맥의 Home, End, PageUp, PageDown 넘기기는 러스트 판과 같다. 넘치면 커서가 보이게 스크롤하고 휠과 썸 끌기로 넘기며 썸을 그린다. 클래식 스크롤 막대(윈도우, 리눅스, 맥 클래식 설정)는 크롬 textarea 처럼 넘칠 때 막대 두께만큼 글 폭을 던다. setLineHeight(null 이면 CSS normal), setTabSize(기본 8), getScrollTop, setScrollTop 을 더했다. 되돌리기와 다시 하기는 캔버스 모드와 DOM 입력 모두 엔진 이력이다(Ctrl(맥은 Cmd) + Z, Ctrl(맥은 Cmd) + Shift + Z, 윈도우와 리눅스는 Ctrl + Y, 윈도우는 Alt + Backspace 도, 이어 친 글자는 한 묶음, 커서를 옮기면 끊기고, 붙여넣기와 잘라내기는 따로 한 묶음, 최대 1000). DOM 입력은 브라우저 되돌리기 키와 historyUndo, historyRedo 를 막고 엔진 이력으로 해서 문맥 메뉴로 붙여넣은 것도 되돌린다. IME 조합 중에는 되돌리지 않고, 확정한 글은 앞 글자 넣기 묶음에 붙는다. canUndo(), canRedo() 를 더했다. setText 는 목록을 비운다
- 그림 풀기와 올리기를 로딩 때로(유니티, 언리얼의 로딩 때 올리기, 웹의 createImageBitmap 과 같은 꼴): ImageAsset 이 읽을 때 바이트를 받아 그림 요소와 함께 createImageBitmap 으로 주 스레드 밖에서 풀어 두고(크롬은 Blob 을 일꾼 스레드에서 푼다), 처음 올릴 때 그것을 올린 뒤 닫는다. 그림 요소를 texImage2D 로 올리면 크롬이 그 자리에서 주 스레드로 다시 풀어 새 화면의 첫 그리기 프레임이 멈칫했다. SceneManager 는 씬의 load 가 끝난 뒤 로딩 화면 동안 읽은 그림을 프레임마다 2 밀리초씩(유니티 asyncUploadTimeSlice 기본값) 나눠 GPU 에 올린다(Graphic.prepareLoadedImages, 최소 0.3 초 기다림과 겹친다). 코드로 만든 캔버스는 씬의 load 에서 Graphic.prepareImage 로 올려 둔다. 화면 결과는 그대로다: ImageBitmap 결과가 그림 요소를 올린 결과와 바이트까지 같은 꼴(8 비트 PNG 가운데 알파가 없거나 색 조각이 없거나 sRGB 조각만 있는 것, JPEG, 알파와 움직임이 없는 WebP)만 미리 풀고, 나머지(sRGB 가 아닌 색 프로필에 알파가 있는 PNG, 16 비트 PNG, 알파 WebP, GIF, AVIF, SVG)는 그림 요소를 로딩 때 올린다. 크롬 158 은 ImageBitmap 을 미리 곱한 채 풀어 색을 바꾸고 texImage2D 는 곱하지 않은 채 풀어 색을 바꾼 뒤 곱해, 그런 그림은 최대 6/255 어긋났다. 그림 많은 장면(1024 PNG 16 장, 2048 JPEG 8 장, 맥미니 M2 Pro 헤드리스 크롬 158 ANGLE Metal)의 첫 그리기 프레임이 336 ms 에서 1.4 ms 로 줄었다.
- 러스트 판 꼴 맞추기(작은 것 여덟): Graphic.resolveShaderProgram(묶음 이름, 프로그램 이름, () => [버텍스 소스, 프래그먼트 소스]) 를 더했다(이름으로 담아 두고, 짓기에 실패하면 한 번만 알리고 null 을 담는다, 러스트 판 resolve_shader_program 과 같다). ShaderSprite 가 이것을 쓴다. Color.create(red, green, blue, alpha) 를 더했다. Animation.setFramesFromRects 가 HTMLImageElement 뿐 아니라 캔버스, OffscreenCanvas, ImageBitmap 도 받는다(지금까지는 이미지가 아니면 소리 없이 무시했다). UIInputField 는 setEngine 을 안 불러도 Engine.getEngine() 으로 문맥 메뉴와 입력 손잡이를 붙인다. LayoutSolver 오류 글에서 긴 줄표를 뺐다(러스트 판 LayoutError 글과 같다). UIInputField, ToonRenderer, ToonVfx 의 안쪽 함수(attachDOMInput, handleCanvasKeydown, createProgramSet, drawBands 같은 것)는 @private 으로 돌려 API 자료에서 뺐다. 게임이 부르던 곳은 없다.
- 찍기 모드 시간(러스트 판 VANILLA_CAPTURE_* 와 같게): 주소 쿼리 ?capture 로 건 찍기 모드는 결정적으로 찍게 TimeManager 의 시간이 실제 시각 대신 프레임마다 1/60 초씩 간다(프레임 번호 x 1000 / 60 밀리초, 러스트 판과 같은 셈이라 같은 프레임의 시간이 같은 비트). 같은 시각이 되풀이되어 최대 FPS 제한이 프레임을 넘기지 못하므로 찍기 모드에서는 제한을 건너뛴다. 초안 타일맵 addTileset 문서에 '타일셋은 여러 지도가 나눠 쓰는 자산이라 넣은 뒤 고치지 않는다' 를 적었다(러스트 판도 Rc
으로 같은 약속) - 보이기 플래그(러스트 판 WorldNode::set_visible, is_visible, NodeTree::is_visible_in_hierarchy 와 같게): TransformNode.setVisible(참 거짓) 을 더했다. 켜짐(setActive), 투명도와 따로 두는 플래그이고, 거짓이면 그 노드와 자손을 그리지 않고 TouchRaycaster 의 누름도 받지 않는다. (갱신은 돈다) isVisible() 은 이제 그 플래그만 돌려준다. (지금까지는 켜져 있고 투명도가 0 보다 크면 참) 새 isVisibleInHierarchy() 는 자신과 조상 모두가 켜져 있고, 플래그가 참이고, 로컬 투명도가 0 보다 클 때 참이다
- ToonVfx 자리와 기본값(러스트 판 ToonParticleOptions, ToonFireballOptions, ToonGlintOptions 의 position: [f32; 3], ToonRibbonOptions, ToonBeamOptions 의 alpha 기본 1 과 같게): emitParticles, addFireball, queueGlint 가 자리를 x, y, z 세 칸 대신 position: [x, y, z] 로 받는다. (주지 않으면 [0, 0, 0]) queueRibbon, queueBeam(과 그것으로 그리는 queueLightning)은 alpha 를 주지 않으면 1 이다. (지금까지는 그리지 않았다) queueGlint 의 size 기본은 0.2 다
- 그림 경로(러스트 판 set_image_path, get_image_path 와 같게): Sprite, ShadowImage, UIImageView 에 setImagePath(경로), getImagePath() 를 더했다. 적어 두기만 하고 그림을 읽지 않는다. UIDocument 와 비주얼 에디터는 컴포넌트에 붙이던 expando component.imagePath 대신 이것을 쓴다. 문서 JSON 의 imagePath 칸은 그대로다
- Scene 배경(러스트 판 SceneBase 의 set_scene_background_color, get_scene_background_color, draw_scene_background 와 같게): setSceneBackgroundColor(Color 나 색 글), getSceneBackgroundColor(), drawSceneBackground(graphic) 가 GameScene, UIScene 에서 Scene 으로 옮겼다. GameScene, UIScene 은 지금처럼 preDraw 에서 칠하고, Scene 을 바로 이은 씬은 preDraw 에서 drawSceneBackground 를 부르면 같게 칠한다. setSceneBackgroundColor 는 준 색의 사본을 담는다
- EngineConfiguration.viewScaleMode(러스트 판 EngineConfiguration::view_scale_mode, 기본 StretchShort 과 같게): 주석으로 막혀 있던 칸을 살렸다. 기본은 ViewScaleMode.stretchShort 이고 엔진이 만들 때 뷰 매니저에 넣는다. UIScene, GameScene 은 지금처럼 initialize 에서 저마다의 모드(setViewScaleMode, 기본 none)로 바꾼다. 그 앞(로딩 화면)은 설정의 모드다
- UIScene 세이프 에어리어(GameScene 과 같게, 러스트 판 compute_safe_area_rect 와 같게): computeSafeAreaRect 와 레이아웃 가이드 인셋이 env(safe-area-inset-*) 를 따로 재던 것을 ViewManager.getSafeAreaInsets 로 읽는다. setSafeAreaOverride, 주소의 ?safeArea=, setIgnoredSafeAreaSides 가 UIScene 에도 닿는다
- 러스트 판에 있던 공개 API: Color.from(Color 나 색 글, 러스트 판 From<&str> for Color), 색을 받는 세터(러스트 판 impl Into
자리)가 색 글도 받는다. UIScene.getDevTools, import.js 가 GameScene 과 isViewPositionInsideNode 를 내보낸다. WorldNode.convertNodePositionToViewPosition, convertViewPositionToNodePosition(뒤집지 못하면 null), UIDropdown.getOptionList, getPopupNode, getOptionNodes, UIDialog.getPopupMotion, getOverlayNode, getPanelNode, getConfirmNode, getCancelNode - runExternalPass: 바깥 패스가 스텐실 테스트를 끄거나 스텐실 쓰기 마스크를 바꾸고 돌아와도 셰이더 자르기를 지우는 DECR 이 스텐실에 닿게 테스트와 마스크를 다시 걸고, 셰이더 자르기가 없으면 스텐실 자르기 상태를 되돌린다(그 뒤의 스텐실 자르기가 깨지던 것). batchclipchrome 시험에 그 경우를 더함
- 렌더 배율 상한(ViewManager.setMaxRenderPixelRatio)을 도는 중에 바꾸면 한 프레임이 까맣던 것: tick 이나 draw 에서 캔버스 크기를 바꾸면 그리기 버퍼가 비워지는데, 그 프레임은 프레임 머리에서 맞춘 옛 뷰포트로 그렸다. 이제 값만 적고 다음 프레임 머리에서 엔진이 창 크기 바뀜과 같은 길(Engine.resize)로 캔버스를 맞춘다. 씬도 화면 영역이 바뀐 것을 받는다(지금까지는 받지 못했다). 같은 값이면 아무것도 하지 않는다. ViewManager.isViewRectPending() 을 더했다. 헤드리스 크롬(기기 픽셀 배율 2)에서 도는 중 상한 1 을 걸면 지금까지는 그 프레임의 화소가 (0, 0, 0) 이었다.
- 3D 렌더 스케일(ToonView3D.setRenderScale, getRenderScale, 유니티 URP renderScale, 언리얼 화면 비율과 같은 뜻): 배율이 1(기본, 지금 그대로)이 아니면 ToonView3D 가 3D 를 내용 영역의 화면 크기 x 배율의 판(깊이 포함, 캔버스가 안티에일리어싱이면 멀티샘플 4)에 투명하게 비운 뒤 그리고, 2D 그리기 길로 선형 거르기, source-over 로 늘여 얹는다. UI 는 기기 화소 그대로라 글자가 흐려지지 않는다(ViewManager.setMaxRenderPixelRatio 는 캔버스 전체라 UI 도 흐려진다). 2D 자르기를 따르고, 3D 가 덮지 않은 곳은 아래 2D 가 비친다. 판은 제 깊이를 써서 setDepthCleared(false) 로 앞의 3D 깊이를 이어 쓰는 것은 배율 1 일 때만 된다. 그리기 함수가 받는 사각형에 outputFramebuffer(지금 묶인 프레임 버퍼, null 이면 캔버스)와 outputViewport(그 안의 GL 뷰포트, 정수, 왼쪽 아래 원점)를 더했다. examples/toonview 는 ?renderScale=0.5 로 볼 수 있다. ToonPostProcess.setResolutionScale 과 겹쳐 걸면 두 배율이 곱해진다. 판에 비치는 것이 맞게 쌓이도록 ToonRenderer 의 비치는 섞기(ToonBlendMode.alpha)는 알파 칸을 미리 곱한 over 로(SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA, 유니티 Blend SrcAlpha OneMinusSrcAlpha, One OneMinusSrcAlpha), 더하기(additive)는 알파를 바꾸지 않게(ONE, ONE, ZERO, ONE) 했다. 캔버스는 알파가 없어 색이 같다(헤드리스 크롬 전후 화소 같음). (까닭: 광부 키우기 갤럭시 폴드3 에서 캔버스 배율 상한 2 로 33 ms 에서 19 ms 였으나 UI 글자까지 흐려졌다)
- 안티에일리어싱 켜고 끄기: EngineConfiguration.antialias(기본 true, 지금 보기 그대로)를 더했다. 끄면 캔버스의 WebGL 컨텍스트를 antialias: false 로 만들어 기본 프레임 버퍼의 멀티샘플(MSAA)을 쓰지 않는다. 고해상도 모바일에서 프레임마다 드는 리졸브 비용이 빠진다(광부 키우기 실기기 아이패드 미니 6, 2266 x 1316 에서 MSAA 가 프레임마다 3 ~ 9 ms, 무거운 장면 35.7 ms 에서 26.2 ms). 웹은 켬과 끔만 고르고 표본 수는 브라우저가 정한다. Graphic 생성자의 세 번째 인자(antialias, 기본 true)로 들어간다.
- 글꼴 이름 default(러스트 판과 같게): 글꼴 글(Graphic.setFontString, measureTextWithoutGraphic, 글자 굽기)의 이름 default(대소문자, 따옴표 가리지 않음)를 엔진 기본 글꼴 사슬로 읽는다. 그 자리는 이름 default 로 올린 글꼴만 찾고, 목록 끝에 SYSTEM_FONT_STRING 사슬을 잇는다(러스트 판은 이름 목록 다음에 기본 폰트, 시스템 글꼴 사슬 차례로 찾는다). 지금까지는 CSS 에서 따옴표 없는 default 가 예약어라 캔버스가 글꼴 글을 통째로 버리고 앞에 쓴 글꼴과 크기로 재고 그렸다(헤드리스 크롬에서 "16px default" 너비가 앞의 40px serif 로 잰 417 이었다, 이제 139). 애셋 없는 DynamicFont 도 "-apple-system, sans-serif" 대신 SYSTEM_FONT_STRING 으로 굽는다(러스트 판 처음 글꼴 이름 default, Text 와 같다). 새 시험 tests/core/defaultfontchrome.test.mjs
- 해 그림자 치우침을 그림자 텍셀 크기에 맞춤(유니티 URP 의 Depth Bias, Normal Bias 텍셀 단위와 받는 쪽 노멀 치우침, 기울기 비례 치우침 꼴): ToonRenderer 가 셰이더에 박아 두었던 노멀 밀기 0.02(월드)와 깊이 치우침 0.0015(깊이)를 ShadowMap 의 새 setBias(depthBias, normalBias), getDepthBias, getNormalBias(텍셀 단위, 기본 1, 1)로 바꿨다. 텍셀 하나의 월드 크기(빛 행렬의 가로 폭 / 해상도)와 3x3 PCF 반지름 1.5 를 곱해 걸고, 빛과 면이 스칠수록 커지는 기울기 비례 치우침(텍셀 2.5 x tan, tan 은 10 까지)을 더한다. 박아 둔 값은 extent 와 해상도를 따라가지 않아, extent 40 에서 해와 스치는 면(84 도, 해상도 512 면 73 도까지)이 통째로 제 그림자를 받았고(여드름), near 1 far 100 에서는 깊이 치우침이 월드 0.15 라 높이 0.1 의 드리우개가 그림자를 아예 드리우지 않았다(떠 보임). 새 크롬 시험(tests/graphics3d/shadowbiaschrome.test.mjs)이 둘 다 본다. 점광과 스포트라이트 그림자(ShadowAtlas)는 이미 텍셀 크기와 기울기에 맞춘 노멀 치우침이라 그대로다.
- 툰 인스턴스 버퍼를 여러 패스가 같이 쓰기(유니티 Graphics.RenderMeshInstanced 와 GraphicsBuffer, 고도 MultiMesh 꼴): ToonDrawQueue.addMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, options) 를 더했다. ToonRenderer.createInstanceBuffer 로 한 번 올린 버퍼를 몸과 바깥선 껍데기, 그림자 깊이, 화면 공간 바깥선의 선의 판이 같이 쓰고 다시 올리지 않는다. (addMeshInstanced 는 인스턴스마다 걸러 몸, 그림자, 선의 판이 같은 배열을 프레임마다 따로 올린다) ToonScreenOutline.drawMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, lineId, options) 가 같은 버퍼로 선 번호를 그린다. 인스턴스마다 선 번호는 인스턴스 꼴의 새 예약 이름 instanceLineId(크기 1, TOON_INSTANCE_LINE_ID_NAME, 자리는 사용자 어트리뷰트의 마지막 자리 TOON_INSTANCE_LINE_ID_LOCATION, 있으면 사용자 어트리뷰트는 둘까지, ToonInstanceLayout.hasLineId)에서 읽고, 없으면 options.lineId 다. 아핀 행렬 아래 줄의 빛남 칸(3, 7, 11, 15)과 틴트는 그대로다. ToonRenderer.updateInstanceBufferRange(instanceBuffer, firstInstance, data) 는 일부만 bufferSubData 로 고친다(범위 밖이면 던진다). 버퍼는 고치거나 지울 때마다 generation 이 1 씩 늘고, 그림자 캐시(ShadowUpdateMode.onChange)는 드리우개 기록에서 버퍼와 generation 을 견줘 고친 프레임에 다시 굽는다. 버퍼 전체의 경계(bounds, 만들 때와 고칠 때 자리와 가장 큰 크기로 셈)로 통째 거른다. drawMeshInstanceBuffer 도 이제 같은 경계로 통째 거른다(options.isCulled 가 false 면 거르지 않는다, 꼴에 행렬이 없으면 경계를 몰라 거르지 않는다). 새 함수 readInstanceBufferSphere(mesh, instanceBuffer), isSphereInFrustum(planes, sphere). 지운 버퍼로 그리면 아무것도 그리지 않는다. 광부 mid 꼴 장면(tests/graphics3d/toonminerscene.mjs, 바위 세 종 460 개, 건물 스무 채, 해 그림자, 화면 공간 바깥선, 맥미니 M2 Pro 헤드리스 크롬)을 재기 도구(tests/graphics3d/tooninstancebufferbench.mjs)로 잰 값: 프레임당 버퍼 올림(bufferData, bufferSubData)은 인스턴스 묶음 셋에서 6 → 0, 청크로 나눈 묶음 열여덟에서 36 → 0(바위 하나를 고친 프레임은 bufferSubData 하나), 드로 콜은 같다(73, 118). 스크립트 시간 가운데 값(array 와 buffer 를 번갈아 아홉 번씩)은 묶음 셋에서 0.200 → 0.095 ms(기계 부하 68 에서도 같음), 묶음 열여덟에서 부하 4 일 때 0.27 → 0.17 ms(선의 판 0.085 → 0.035, 인스턴스 몸 그리기 0.09 → 0.045, 그림자 0.015 → 0.005 ms)이고, 부하 55 ~ 69 일 때는 0.24 → 0.29 ms(buffer 만 반복마다 0.145 ~ 0.34 로 갈림, 까닭은 아직 못 찾음), 바위 하나를 고친 프레임은 0.635 → 0.355 ms(묶음 셋). 크롬 시험(tests/graphics3d/tooninstancebufferchrome.test.mjs)이 같은 장면을 두 길로 75 프레임 그려 화소가 바이트까지 같은지(인스턴스마다 다른 선 번호와 setLineColor 색, 빛남, 그림자 포함), 바위 하나를 고친 프레임에 바로 반영되고 올림이 bufferSubData 하나만 느는지, 그림자 캐시가 그대로인 프레임은 그리지 않고 고친 프레임에 다시 굽는지 본다(선 번호를 일부러 읽지 않게 하면 첫 프레임에서 잡힌다).
- 툰 그리기 줄 자동 인스턴싱과 프레임 블록(유니티 GPU 인스턴싱과 SRP Batcher, 언리얼 auto-instancing 꼴): ToonDrawQueue 가 정렬로 이어진 같은 모형, 같은 재질 값(재질 블록이 같음, 꼴 객체는 따로라도 됨)의 보통 모형(addMesh)을 인스턴스 그리기(drawElementsInstanced) 하나로 묶는다. 몸, 바깥선 껍데기, 그림자 깊이(drawShadows, drawLocalShadows 의 칸마다), 화면 공간 바깥선의 선의 판이 같은 묶음을 쓴다. 행렬은 묶음 자리의 인스턴스 버퍼에 담고 값이 바뀔 때만 다시 올리며(몸과 바깥선 껍데기가 한 자리를 같이 써 움직이지 않는 것은 올림이 없다), 틴트는 1, 빛남은 0 이라 모형마다 그린 것과 화면이 바이트까지 같다(인스턴스 셰이더 길은 같은 프로그램의 같은 셈이고 모형 행렬만 어트리뷰트에서 읽는다). 선의 판은 담은 차례로 거르고 초점 거리에 더한 뒤 같은 모형과 선 꼴(hasCreaseLine, hasScreenOutline, indexStart, indexCount)인 것을 모아 그리고, 번호는 인스턴스마다 담으며, 묶지 않는 것은 담은 차례의 제자리에서 그린다. 머티리얼(ToonMaterial)이나 모형, 재질 값, 텍스처, 빛 묶음, 그리는 범위가 다르거나, 감기가 뒤집혔거나(행렬식이 음수, isMirrored), 뼈대 행렬이나 onBeforeDraw 가 있거나, 비치는 것은 묶지 않는다(비치는 것은 지금처럼 먼 것부터 하나씩). 화면 밖인 것은 하나씩 먼저 거른다. 정렬 열쇠에 넷째로 재질 블록을 더해(재질, 모형, 바탕색 텍스처, 재질 블록) 같은 꼴이 이어지게 했다. 선의 판의 instanced, instanceLineIds, skinned, lineFlags 유니폼은 바뀔 때만 올린다. 프로그램마다 프레임마다 올리던 프레임 값 열여덟(보기와 투영, 빛 행렬, 카메라 자리와 앞, 보기 돌림, 카메라 기울기, HDR, 해 그림자 켬과 세기와 텍셀과 치우침, 바깥선 거리 배와 사라지는 거리, 점광 그림자 아틀라스와 칸, 모서리 어둠 텍스처의 화면 원점)은 std140 블록 ToonFrame(바인딩 2) 하나에 담아 패스마다 한 번 값을 쓰고, 재질 블록과 같은 꼴로 값이 같은 블록을 찾아 묶는다(지은 버퍼는 고치지 않아 카메라와 빛이 그대로면 올림이 없다. 같은 버퍼를 패스마다 bufferSubData 로 고치던 첫 꼴은 onChange 그림자를 구운 프레임의 화면이 everyFrame 과 달라 shadowcachechrome 시험이 잡았다, 원인은 가르지 않음). 크롬 트레이스로 가르니 고치기 전 로비 꼴 장면의 프레임 스크립트 시간 2.94 ms 가운데 2.05 ms 가 렌더러가 GPU 프로세스의 명령 버퍼 자리를 기다리는 몫(CommandBufferHelper::WaitForAvailableEntries)이고 GPU 프로세스는 그동안 명령을 푸는 데(2.89 ms) 바빴다. 그러니 자바스크립트가 아니라 GL 호출과 그리기 수 자체가 프레임 시간을 정한다. 잰 값(맥미니 M2 Pro 헤드리스 크롬, 고치기 전 사본과 번갈아 세 번씩, 기계 부하 1 분 평균 5.5 ~ 8.9): 로비 꼴 장면 프레임당 GL 호출 4929 → 1761, 그리기 호출 773 → 276(렌더러가 센 드로 콜 484 → 230), 유니폼 호출 2980 → 383, 버텍스 어레이 묶기 388 → 277, 텍스처 묶기 205 → 205, 프로그램 바꿈 41 → 41, 버퍼 올림 0 → 38, 블록 묶기 0 → 163, 스크립트 시간 가운데 값 1.36 → 1.02 ms, 트레이스(40 프레임, 트레이스를 켠 채)의 프레임 스크립트 시간 2.94 → 0.66 ms, GPU 프로세스 명령 풀기 2.89 → 0.64 ms, 렌더러의 명령 버퍼 기다림 2.05 → 0.15 ms. 광부 mid 꼴 장면(인스턴스 버퍼, 청크 여섯): GL 호출 849 → 453, 그리기 호출 118 → 67, 유니폼 호출 395 → 92, 스크립트 시간 0.41 → 0.10 ms. 화면은 두 장면과 툰 예제 다섯(toonstyle, toonshowcase, toonview, toonmaterial, toonfx)이 고치기 전과 바이트까지 같다. 크롬 시험(tests/graphics3d/toonautoinstancechrome.test.mjs)이 같은 모형과 재질 값만 묶고 머티리얼, 모형, 틴트, 뒤집은 감기가 다르면 묶지 않는지(인스턴스 수 목록), 묶지 않게 한 그리기 줄과 화면이 바이트까지 같은지, 행렬이 그대로면 묶음 자리를 다시 올리지 않는지 본다.
- 툰 선의 판 묶음 자리(ToonScreenOutline.drawMeshBatch, 유니티 GPU 인스턴싱의 인스턴스 버퍼를 프레임 너머 남기는 꼴): 선의 판의 자동 인스턴싱 묶음은 모형이 몸, 그림자와 같이 쓰던 인스턴스 버퍼(mesh.instanceBuffer)에 프레임마다 다시 올렸다(몸 쪽은 묶음 자리에 값을 남겨 같으면 올리지 않았다). 선의 판도 자기 묶음 자리(자리마다 버퍼와 모형별 버텍스 어레이, 그리기 줄이 프레임마다 같은 차례로 자리 번호를 줌)를 두고 행렬과 번호가 앞 프레임과 같으면 올리지 않는다(번호는 틴트 칸이라 몸 자리와 값이 달라 따로 둔다). 몸의 버텍스 어레이를 짓는 코드는 모듈 함수로 옮겨 두 곳이 같이 쓴다(렌더러 쪽 동작은 그대로). 센 값(헤드리스 크롬, 맥미니 M2 Pro, 프레임당 선의 판 자리 bufferData 수와 바이트, 고치기 전 → 후): 로비 꼴 30 번 21840 바이트 → 1 번 720, 판의 방 꼴 36 번 17280 → 12 번 5760(방 꼴은 프레임마다 행렬이 바뀌는 것이라 몸 쪽과 같은 수), 광부 꼴(인스턴스 버퍼, 청크 여섯) 2 번 1520 → 0. 화면은 로비, 방, 방 이동, 광부 장면의 프레임 6 과 11 의 해시가 고치기 전과 같다. 크롬 시험(tests/graphics3d/toonlinebatchchrome.test.mjs)이 멈춘 프레임에 선의 판 올림이 0 이고 화면이 같은지, 행렬 하나가 바뀌면 그 묶음 하나만 올리고 화면이 처음부터 그린 것과 바이트까지 같은지 본다.
- 툰 선의 판의 거울 항목 묶기(ToonDrawQueue, ToonScreenOutline.drawMeshBatch 의 isMirrored 칸, 거울에 비친 모습을 그리는 게임이 바닥으로 뒤집은 행렬로 같은 배우를 한 번 더 담는 꼴): 감기를 뒤집는 항목(행렬식이 음수나 isMirrored)은 선의 판에서만 하나씩 따로 그렸다(몸, 바깥선 껍데기, 그림자는 이미 뒤집은 것끼리 묶었다). 선의 판도 같은 모형과 선 꼴이면 뒤집는 것끼리 인스턴스 그리기 한 번으로 묶고, 묶음 안은 모두 같은 감기로 그린다(frontFace 만 묶음마다 한 번). 애버런트 로비(맥미니 M2 Pro, 2560x1440, 거울 항목 78 개)로 가르니 거울 몫 GPU 1.55 ms 는 선의 판(끄면 6.90 에서 6.97 로 같음), 그림자(담지 않음), 겹쳐 그리기(거울을 몸 패스 맨 뒤로 보내도 6.94, 앞에서부터 깊이 순으로 그려도 7.10)가 아니라 몸 패스에서 거울 화소를 칠하는 셰이더 몫이다(거울의 몸을 깊이 셰이더로만 그리면 5.39 로 거울을 뺀 5.41 과 같고, 고정색으로 칠하면 5.75, 빛 셈을 빼면 6.12, 점광만 빼면 6.76, 그림자와 반사광과 가장자리 빛을 끄거나 모서리 어둠을 빼도 변화 없음). 그래서 화면이 같은 채로 줄일 수 있는 것은 CPU 쪽뿐이며 렌더러 스레드 몫이 1.72 에서 1.39 ms 로 줄었다. 크롬 시험(tests/graphics3d/toonautoinstancechrome.test.mjs)이 뒤집은 감기 셋이 선의 판에서도 묶음 하나가 되고 화면이 묶지 않고 그린 것과 바이트까지 같은지 본다.
- 툰 모서리 어둠(화면 공간 AO, GTAO: Jimenez, Wu, Pesce, Jarabo 2016 "Practical Realtime Strategies for Accurate Indirect Occlusion", 유니티 URP SSAO 처럼 간접광에만): ToonPostProcess.setAmbientOcclusion(isEnabled, intensity, radius, resolutionScale)(기본 꺼짐, 세기 0.5, 반지름 0.5 월드 길이, 반 해상도), getAmbientOcclusion, isAmbientOcclusionEnabled, drawAmbientOcclusion(lineTarget, viewMatrix, projectionMatrix), getAmbientOcclusionTexture, getAmbientOcclusionPrepass 와 ToonRenderer.setAmbientOcclusionTexture, getAmbientOcclusionTexture, ToonDrawQueue.setPostProcess, getPostProcess 를 더했다. 반 해상도 칸마다 화면 방향 조각 넷을 돌려 양쪽으로 여섯 걸음씩 가장 높은 지평선을 찾고 투영한 노멀로 코사인 가중 보임을 닫힌 식으로 적분한다(반지름 0.6 배부터 반지름까지 줄임). 조각 각과 걸음은 인터리브드 그래디언트 잡음(Jimenez 2014)으로 흩는 고정 무늬라 멈춘 화면은 흔들리지 않는다. 접평면 거리와 노멀 각으로 가장자리를 지키며 가로 7 탭으로 흐린 뒤, 세로 7 탭 두 열로 흐리며 화소의 깊이와 노멀로 골라 온 해상도로 키운다(Kopf 2007 joint bilateral 꼴). 깊이는 역투영 행렬로 풀어 원근과 직교(setMatrices 로 준 원 행렬도)를 함께 받는다. 노멀과 깊이는 화면 바깥선의 선의 판을 다시 쓰고, 바깥선이 없는 장면은 선은 긋지 않고 선의 판만 그린다(ToonScreenOutline 은 바깥 선과 꺾임 선 굵기가 둘 다 0 이면 씨앗과 넓히기를 건너뛰고 drawOutline 이 긋지 않는다). ToonDrawQueue 는 선의 판 뒤, 몸 앞에 셈해 렌더러에 걸고 endFrame 뒤에 푼다. 몸 셰이더는 TOON_AMBIENT_OCCLUSION 을 정의한 몸 프로그램(바깥선과 그림자 깊이는 같이 씀)으로 바꿔 화면 자리의 보임을 바탕빛(하늘과 땅 빛)에만 곱한다. 해 칸, 채움빛, 점광, 반사광, 테두리빛은 그대로라 칸이 더러워지지 않는다. 비치는 것과 선의 판과 깊이가 다른 면(2^-16 넘게)은 곱하지 않는다. 텍스처 유닛은 16 이다(머티리얼 텍스처 8 개를 다 쓰는 머티리얼은 조각 셰이더 유닛 16 개 기기에서 AO 없이 그린다). 엔진에 있던 AmbientOcclusionEffect 는 원근 시야각으로만 깊이를 풀고 RGB 노멀과 커버리지 알파를 받는 반구 표본 꼴이라 직교 카메라와 선의 판(팔면체 노멀)에 맞지 않아 쓰지 않았다. 비용(시험 장면 640 x 360, 맥미니 M2 Pro 헤드리스 크롬): 한 프레임의 GL 호출은 바깥선 없는 장면 92 → 249(그리기 5 → 12, 미리 그리기 넷과 AO 세 패스), 바깥선 장면 278 → 368(그리기 14 → 17, AO 세 패스만), 몸 프로그램 바꿈은 늘지 않는다(AO 몸 프로그램이 기본 몸 자리를 대신함). readPixels 로 끝을 기다린 프레임 벽시계는 끔 0.20 ~ 0.41 ms, 켬 0.49 ~ 0.80 ms 다(GPU 시간 재기 확장이 없어 벽시계, 큰 해상도는 재지 않음). 트인 면은 보임을 0.96 으로 나눠 1 에서 잘라 정확히 1 이라 화면이 그대로다. 꺼짐이면 텍스처를 읽지 않는 기본 몸 프로그램(바탕빛 식이 그대로)으로 그려 화면이 고치기 전과 바이트까지 같다. 크롬 시험(tests/graphics3d/toonambientocclusionchrome.test.mjs)이 방 구석과 상자, 다리 둘 달린 로봇을 원근, 직교, 바깥선과 함께 그려, 꺼짐과 켰다 끈 화면이 고치기 전 저장소와 바이트까지 같은지(TOON_AO_BASE_PATH), 켜면 벽과 바닥이 만나는 곳, 상자 옆, 로봇 발밑이 어두워지고 트인 바닥은 그대로인지, 로봇 머리의 해 칸 경계가 바이트까지 그대로인지, 바깥선의 선의 판을 다시 쓴 AO 판과 미리 그리기의 AO 판이 같은지 본다.
- 툰 바깥선 낮은 턱(유니티, 언리얼의 깊이 노멀 경계 검출에서 문턱을 측정 오차에 맞추는 꼴): ToonScreenOutline 이 같은 번호 안의 가려진 실루엣을 가를 때, 가린 화소가 가려진 화소의 접평면에서 떨어진 거리를 쓴다. 지금까지는 두 화소의 접평면 거리 가운데 작은 쪽을 썼는데, 가린 쪽이 둥근 면의 실루엣이면 그 접평면이 시선을 품어 거리가 화소 한 칸 밑으로 줄어, 몸 위에 얹힌 돔의 이음선 같은 선이 점선으로 끊겼다. 문턱에 더하던 고정 여유(그 깊이의 화소 크기 두 배)는 잰 오차에 비례하는 여유로 바꿨다: 노멀 8 비트 팔면체의 각 오차(가장 큰 값 0.0165 rad, 무작위 200 만 표본으로 잼) x 두 화소 자리 사이 거리, 꺾인 줄을 사이에 둔 두 화소의 화소 한 칸 x 두 노멀이 벌어진 사인, 깊이 24 비트 한 칸. 그래서 두 면이 나란한 턱은 화소 한 칸보다 낮아도 잡히고, 비스듬한 평면과 울퉁불퉁한 면에는 노멀 오차만큼만 여유가 붙는다. 여유 배율 setDepthMargin, getDepthMargin(기본 2)과 getDepthThreshold 를 더했다. 노멀 판은 RGBA8 그대로다(16 비트 두 칸으로 바꾸면 각 오차는 0.00006 rad 이지만 선의 판 쓰기와 씨앗 읽기가 두 배가 되고, 8 비트 오차 몫은 비스듬한 면 45 도에서 화소 한 칸의 0.02 배라 턱을 가르는 데 걸리지 않는다). 기본값에서 엔진 예제 여섯(toonstyle, toonview, toonfx, toonpost, toonshowcase, toonmaterial) 가운데 toonstyle 만 도넛 안쪽 실루엣의 두 끝이 16 화소 더 이어지고 나머지는 바이트까지 같다. 같은 번호 하나로 지은 낮은 턱, 비스듬한 평면, 울퉁불퉁한 면 장면(원근과 직교, DPR 1, 2, 3)에서 문턱 0.05 에 둥근 면과 돌의 바닥 위 실루엣 빈틈이 이어지고(선 화소 -0.1 ~ +13 %, 줄어든 것은 유리판 아래 모서리 끝 34 화소까지) 평면과 돌의 안쪽에는 잔선이 없다.
- 툰 모서리 어둠의 직접 빛 몫(유니티 URP SSAO 의 Direct Lighting Strength, HDRP ScreenSpaceAmbientOcclusion.directLightingStrength 꼴): ToonPostProcess.setAmbientOcclusion 에 다섯째 인자 directLightingStrength(0 ~ 1, 기본 0)와 getAmbientOcclusionDirectLightingStrength, getAmbientOcclusion 의 directLightingStrength 칸, ToonRenderer.setAmbientOcclusionTexture 의 둘째 인자와 getAmbientOcclusionDirectLightingStrength 를 더했다. 몸 셰이더는 칸(밝기 단계)을 고른 뒤 해의 칸 빛, 채움빛, 점광과 스포트라이트의 확산과 반사광에 1 - 몫 x (1 - 보임) 을 곱한다. URP 는 직접 빛의 색(light.color)에 lerp(1, ssao, 몫) 을 곱해 확산과 반사광이 같이 줄고, HDRP 도 직접 확산과 직접 반사광에 같은 몫을 건다. 테두리빛, 빛남, 매트캡, 천사 고리는 그대로고 바탕빛은 전처럼 보임을 다 곱한다. 칸 좌표에는 걸지 않아 칸 경계 자리가 옮겨 가지 않는다. 값은 프레임 블록 ToonFrame 끝의 ambientOcclusionDirectLightingStrength(자리 168, 블록 168 → 172 float)로 올린다. 해 빛이 큰 장면에서 바탕빛에만 곱하면 구석이 거의 보이지 않던 것을 몫으로 키운다. 몫 0 과 꺼짐은 고치기 전과 바이트까지 같다(시험 장면의 원근, 직교, 바깥선 켬과 끔 여섯 화면). 크롬 시험(tests/graphics3d/toonambientocclusionchrome.test.mjs)이 몫 0, 0.25, 0.5, 1 에서 벽 구석의 어두워진 밝기가 4.9, 5.9, 7.3, 9.8, 로봇 발밑이 4.2, 6.0, 8.1, 12.1 로 커지는지, 트인 바닥과 로봇 머리(해 칸 경계)는 몫 1 에서도 끔과 바이트까지 같은지 본다.
- 투명도 층(CSS opacity 같은 묶음 투명도): Graphic 의 beginOpacityLayer, endOpacityLayer(러스트 판 begin_opacity_layer, end_opacity_layer)가 그 사이에 그린 것을 화면 크기 칸에 모았다가 한 번에 지금 전역 알파로 얹는다. 노드는 setOpacityLayer(true)(러스트 판 set_opacity_layer)를 켜고 투명도가 1 보다 작으면 그 노드와 자손을 층으로 그려, 겹친 자식끼리 비치지 않는다(크롬 CSS opacity 와 같다). 층 안의 자르기(Mask)도 그대로 되고 층은 겹쳐 열 수 있다. 두 엔진이 같다. 러스트 판 데스크탑 Pane 은 CSS opacity 를 이 층으로 그려 웹 DOM 과 같다. 헤드리스 크롬에서 겹친 자리가 층 없이는 (64, 0, 128), 층으로는 (0, 0, 128) 로 아래가 비치지 않음을 확인했다
- GameScene 로딩(러스트 판과 같게): 로딩 최소 시간을 Date.now 대신 엔진 시계(TimeManager.getRealtimeSinceStartup)로 재고, 엔진 시계가 아직 돌지 않았으면(첫 프레임 전) 첫 로딩 화면 프레임부터 잰다. 로딩 화면 누름은 window pointerdown 대신 엔진 입력(InputManager.isTouchPressed)으로 drawOnLoad 가 프레임마다 본다.
- 개발자 도구 메모리 칸(러스트 판과 같은 규칙): performance.memory 의 쓰는 중과 잡아 둔 힙을 못 읽으면 셋 다, 한도(jsHeapSizeLimit)만 못 읽으면 그 칸만 "(N/A)" 다. 러스트 데스크탑은 같은 칸에 운영체제 API 로 읽은 같은 뜻의 값을 적는다.
- Action: 대상을 들지 않고 매번 넘기는 startWith(target), stepWith(target, timeDelta) 를 더했다(러스트 판 start_with, step_with 와 짝). start(target), step(timeDelta), getTarget 은 그대로 대상을 들고, 러스트 판 start(node_tree, Some(node_id)), step(node_tree, time_delta), get_target 과 짝이다. repeat, forever, loop 의 안쪽 액션은 러스트 판처럼 startWith, stepWith 로 돌아 대상을 들지 않는다.
- 입력 필드 문맥 메뉴: 직접 누름 필드(setUseDirectTouch)의 오른쪽 클릭이 브라우저 편집 칸 메뉴 대신 다른 필드와 같은 엔진 문맥 메뉴다. (DOM 입력의 contextmenu 기본 동작을 막는다) 메뉴에 모두 선택(글이 있을 때)을 더했고, UIInputFieldMenuAction.selectAll 이 생겼다. 러스트 판과 같은 네 항목이다
- 입력 필드 문맥 메뉴를 엔진이 그린다: 오른쪽 클릭 문맥 메뉴가 body 에 붙던 DOM 요소(CSS box-shadow) 대신 루트의 마지막 자식 노드(UIInputFieldContextMenu 컴포넌트)로 캔버스에 그려진다. 러스트 판과 같은 코드 길과 같은 치수(폭 140, 항목 34, 글자 14px, 모서리 8)이고, 그림자는 CSS 0 4px 16px rgba(0, 0, 0, 0.18) 을 블링크처럼 시그마 8 의 가우스로 구워(새 src/core/blurshadow.js, 러스트 core/blurshadow.rs 와 같은 셈) 그린다. 메뉴는 뷰 좌표에 놓여 뷰 배율을 따른다. showContextMenu 의 인자가 (clientX, clientY) 에서 viewPosition(뷰 좌표 Vector2)으로 바뀌었다. 필드 밖을 오른쪽 클릭하면 띄운 메뉴가 닫힌다.
- FBX 재질 여럿: 메시 하나에 재질이 여럿인 FBX(LayerElementMaterial 의 Materials, MappingInformationType ByPolygon 이나 AllSame)를 폴리곤의 재질 번호대로 부분 메시로 나눠 재질마다 드로어블 하나로 그린다. (three.js FBXLoader 의 그룹, 유니티와 언리얼의 서브메시) 지금까지는 재질 번호를 폴리곤 순번이 아니라 폴리곤 정점 순번으로 찾았고, 메시마다 소유 노드의 첫 재질 하나로만 그려 Quaternius 마네킹(M_Main, M_Joints)이 온통 주황이었다. 새 정적 함수 SkinnedModel.splitFbxCornersByMaterial, FBX 메시 서술과 드로어블에 materialName(FBX Material 이름, glb 처럼), FbxLoader 재질에 name. 러스트 판과 같다. 문서 그림 ancient-mountain, 셰이더 해시를 바꾼 뒤의 shader-sprite, screen-effect 다시 찍음(1280 x 720, cwebp -q 85). 묶음과 UI 에디터 다시 지음.
- Engine.alert, confirm, prompt(와 alertAsync, confirmAsync, promptAsync), isModalDialogOpen: 러스트 판 Engine 과 같은 이름과 동작으로 엔진이 캔버스 위에 그린 질문 창(크롬 탭 모달 대화 상자와 같은 모양, 제목 "이 페이지 내용:" 과 단추 글은 브라우저 화면 언어)을 띄우고 ModalDialogHandle(isFinished, getResult, isConfirmed, getPromptText, setCallback)을 돌려준다. 브라우저 window.alert, confirm, prompt 는 부르지 않는다. 창에 답하면 손잡이가 끝나고, 떠 있는 동안 isModalDialogOpen 이 참이며 엔진은 씬을 갱신하지 않는다(그리기는 멈춘 화면 그대로, 키는 창만 받는다). 그림자는 크롬 bubble_border 두 겹을 새 src/core/blurshadow.js 로 굽는다. 새 모듈 src/core/modaldialog.js(ModalDialogKind, ModalDialogResult, ModalDialogHandle), src/core/browseruitext.js(크롬 번역 표, 러스트 판과 같은 로케일 고르기). DevTools 의 Local Storage 탭도 브라우저 창 대신 엔진 질문 창으로 묻는다(러스트 판 DevTools 와 같다).
- Scene.setTouchDispatchEnabled(isEnabled), isTouchDispatchEnabled(): 씬 기본 터치 넘기기(tickTouch 가 레이캐스터로 노드에 넘기기)를 켜고 끄는 스위치. 러스트 판 SceneBase.set_touch_dispatch_enabled 와 같은 일이다. setTouchRaycaster(null) 과 같은 효과이고 레이캐스터는 그대로 둔다.
- SpriteAnimator: 러스트 판과 같은 꼴로 정적 SpriteAnimator.play(node, clipName, options)(옛 playOnNode, 노드의 애니메이터로 틀고 그 자리에서 첫 프레임을 넣음)와 인스턴스 playClip(clipName, options)(러스트 판 play_clip)을 둔다. 인스턴스 play 는 뺐다. (옮기는 법: 인스턴스 animator.play(clipName, options) 는 animator.playClip(clipName, options) 로)
- InputActions: 유니티 Input System 처럼 프레임 처음의 update 에서 한 번 갱신하고 그 프레임 안에서는 같은 값을 읽는다. readGamepadStick, readMoveAxis 도 읽을 때 입력 매니저를 다시 보지 않고 update 때 적은 이동 키와 패드 축을 읽는다. (러스트 판과 같다)
- 사인, 코사인, 탄젠트: 엔진 Math.sin, cos(테일러 급수 10 항 근사)와 tan(sin / cos)이 브라우저 Math.sin, cos, tan 을 그대로 부른다. 크롬 158 은 바르게 반올림한 값(참값에 가장 가까운 수)을 내고, 러스트 판이 같은 셈을 해 두 엔진이 같은 입력에 같은 비트를 낸다. 끝자리가 바뀐다. (예: sinusoidal.inOut 의 0.5 는 0.5000000000000017 이 아니라 0.49999999999999994, 타임라인 색 #ff000080 → #0000ffff 의 1 초는 #7f0080c0 이 아니라 #80007fc0)
- 셰이더 해시: hash21(ScreenEffect, ShaderSprite)과 hashPoint(toon VFX)를 MurmurHash3 의 fmix32 마무리(Austin Appleby, 공개 도메인)로 float 비트를 섞는 정수 해시로 바꿨다. 출처 원문을 확인하지 못한 꼴(셰이더토이에서 퍼진 Hash without Sine 과 sin 해시)을 대신한다. 필름 입자, 글리치, 값 잡음, toon VFX 잡음의 무늬가 바뀐다. (밝기 분포와 쓰는 법은 같다)
- 사람 피부 환경 BRDF: Karis 근사 대신 엔진이 분할 합 적분(GGX, Smith Schlick-GGX k = alpha / 2, Schlick 프레넬)을 직접 셈해 맞춘 식을 쓴다. 적분 표와의 오차 실효값이 크기 0.071, 치우침 0.029 에서 0.002, 0.006 으로 줄었다. 환경 반사가 바뀐다. (거칠기 0.5 정면은 0.72 → 0.89 로 밝아지고, 거칠기 1 정면은 0.45 → 0.31 로 어두워진다)
- Scene 터치: 씬 꼴과 상관없이 노드의 위젯이 터치를 받는다. (유니티 EventSystem 처럼, 러스트 판 SceneBase.tick 과 같다) Scene.tickTouch 가 씬의 터치 레이캐스터(create 에서 만드는 TouchRaycaster)로 가장 앞의 누를 수 있는 노드에 먼저 넘기고, 그 뒤에 터치 훅(touchPress, touchMove, touchRelease, touchCancel, touchWheel)을 부른다. 휠도 그 자리의 가장 앞 스크롤 칸에 넘긴다. Scene.setTouchRaycaster(touchRaycaster 나 null), getTouchRaycaster() 를 더했다. UIScene 과 GameScene 은 지금처럼 터치 훅에서 제 TouchRecognizer 로 넘기고(개발자 도구, 페이드, 놀이 입력 판정이 넘기기 앞뒤에 낀다) 씬 기본 넘기기는 꺼서 두 번 넘기지 않는다. (두 씬의 getTouchRaycaster 는 그 TouchRecognizer)
- FbxLoader: 노드(Model)와 애니메이션 스택 이름에서 바이너리 FBX 의 종류 꼬리("\u0000\u0001Model", "\u0000\u0001AnimStack")를 뗀다. 클립 이름은 "Take 001\u0000\u0001AnimStack" 이 아니라 "Take 001", 본 이름은 "mixamorig:Hips" 다. (three.js FBXLoader 는 BinaryReader.getString 이 첫 널 바이트에서 자르고, Assimp 는 "AnimStack::Take 001" 로 바꾼 뒤 FBXConverter 가 "AnimStack::", "Model::" 를 뗀다, 러스트 판도 같이 바꿨다) glTF 로 읽은 모델에 FBX 애니메이션을 더할 때(addAnimationsFromFbx*)의 본 이름 맞추기도 이 이름으로 맞는다.
- 폴더 정리: src/experimental 에 있던 다 자란 기능을 제자리로 옮겼다. 러스트 vanilla-engine 과 같은 폴더다. import.js 로 쓰던 게임은 그대로 돌고, 파일 경로로 직접 import 하던 게임은 새 경로로 바꾼다. (옛 경로 → 새 경로, 내용은 그대로)
- src/experimental/graphics/.js (3D) → src/graphics3d/.js
- src/experimental/graphics/toon/.js (툰 3D) → src/graphics3d/toon/.js
- src/experimental/graphics/fullscreenpass.js → src/core/fullscreenpass.js
- src/experimental/animation/animator.js, timeline.js → src/animation/animator.js, timeline.js
- src/experimental/action.js → src/animation/action.js
- src/experimental/indicator.js → src/misc/indicator.js
- src/experimental/visual/visual.js → src/misc/visual.js
- src/experimental/bunchasset.js → src/resource/bunchasset.js
- src/experimental/visual/visualasset.js → src/resource/visualasset.js
- src/experimental/collection/.js (List, Dictionary, Queue, Set, Stack) → src/base/collection/.js
- src/experimental/camera.js → src/deprecated/camera.js
- src/experimental/aabb.js, transform2d.js, graphics/gl2d.js, graphics/webgl2.js (죽은 코드, 내보내지 않음) → src/deprecated/
- Engine: 씬마다 그리기 앞(preDraw, 로딩 중이면 drawOnLoad 앞)에 뷰 좌표(viewManager.applyViewRect)를 걸어 둔다. 지금까지는 변환을 걸지 않은 채 씬을 불러, Scene 을 바로 이은 씬(UIScene, GameScene 이 아닌)은 그리기 버퍼의 실제 픽셀로 그려 기기 픽셀 배율이 2 인 화면(레티나 맥, 고밀도 휴대폰)에서 캔버스 왼쪽 위 1/4 에만 그려졌고 터치 좌표와도 어긋났다. 배율 1 화면과 UIScene, GameScene 은 그대로다. 옮기는 법: 실제 픽셀로 그리던 씬은 preDraw 에서 graphic.setTransform(1, 0, 0, 1, 0, 0) 을 부른다
- UIInputField 캔버스 모드 낱말 이동과 지우기: 크롬처럼 윈도우와 리눅스는 Ctrl, 맥은 Option 과 왼쪽, 오른쪽 화살표(Shift 와 함께면 고르기를 넓힌다), Backspace, Delete 로 낱말 단위로 옮기고 지운다. (맥은 Option + Ctrl + Backspace, B, F 도) 자리는 블링크 NextWordPosition, PreviousWordPosition 대로, 오른쪽은 윈도우만 다음 낱말 앞(맥과 리눅스는 지금 낱말 끝), 맥은 넓히던 고르기가 고정 끝을 넘지 않는다. 고른 것이 있으면 고른 것만 지운다. (전에는 Ctrl + 화살표가 아무것도 하지 않고, 맥 Option + 화살표는 한 글자씩 움직였다)
- UIInputField 낱말 경계: 크롬처럼 마침표는 숫자 사이에서만 잇고("www.example.com" 은 다섯 조각, "3.14" 는 한 낱말), 쌍점은 잇지 않는다. (크로미엄 ICU wordbrk.patch, 크롬 밖의 브라우저에서도 DOM 입력의 두 번 누르기가 크롬과 같은 낱말을 고른다)
- UIDocument: 문서에 적는 노드와 컴포넌트 종류 이름을 클래스 이름(constructor.name) 대신 표에 등록한 이름으로 적는다. 번들러가 클래스 이름을 줄여도(esbuild --minify) 같은 문서가 된다. (등록하지 않은 종류만 지금처럼 클래스 이름, 지금까지는 줄인 번들에서 WorldNode 가 "o" 처럼 적혀 다시 읽지 못했다)
- UIDocument.registerEditorTypes(): UI 에디터가 등록하는 종류(컴포넌트 35, 노드 종류 12)를 한 번에 등록한다. 에디터가 저장한 문서를 읽는 게임은 fromJsonText 앞에 한 번 부른다. 이미 등록한 이름은 그대로 둔다. (러스트 register_editor_types 와 같다) 표에 없는 노드 종류와 컴포넌트를 읽으면 console.warn 으로 알린다. (지금까지는 말없이 WorldNode 로 읽거나 건너뛰어 UIInputField, UIScrollBar 가 빈 노드가 되고 UISnapScrollView 가 빠졌다)
- UIDocument: 다시 읽을 때 노드 생성자나 위젯이 만든 컴포넌트와 자식(UIWindow 의 제목 막대, UIImageView 가 붙이는 Sprite 같은)은 문서의 앞에서부터 차례와 종류(자식은 이름)가 맞으면 그것에 문서 값을 넣고 겹쳐 만들지 않는다. 읽고 다시 쓰면 같은 문서다. (지금까지는 겹쳐 만들어 UIWindow 를 읽으면 노드와 컴포넌트가 두 벌이었다, 러스트와 같다)
- Version: 엔진 Object 를 잇는다. (version.js 가 Object 를 import 하지 않고 다시 내보내기만 해서 자바스크립트 내장 Object 를 이었다)
- Enum.readonly(dictionary): 얼린 dictionary 를 돌려준다. (Object.freeze 처럼, 지금까지는 undefined)
- Format.formatCompactNumber: 반올림해 1000 이 되면 다음 단위로 올린다. (999999 는 "1000K" 가 아니라 "1M", Intl 의 compact 표기와 같다)
- Singleton: 인스턴스가 이미 있는 클래스를 다시 new 하면 던진다. getInstance() 로 받는다. (하위 클래스 생성자는 super() 가 돌려준 첫 인스턴스에 제 필드와 생성자 몸통을 다시 돌려 첫 인스턴스를 덮어썼고, 비공개 필드가 있으면 TypeError 였다)
- Node.setParent, addChild: 자신이나 자기 자손 밑으로는 붙이지 않고 false 를 돌려준다. (고리가 되면 isActiveInHierarchy 같은 위로 오르는 셈이 끝나지 않았다, 자신이면 빈 오류를 던지던 것도 false) 붙였거나 떼었으면 true. removeChild 는 제 자식일 때만 뗀다. (러스트 NodeTree 와 같다)
- ObjectPool.release: 이미 되돌려 놀고 있는 객체를 또 놓으면 무시한다. (두 번 놓으면 다음에 두 쓰임이 한 객체를 빌렸다)
- Platform.getSafeAreaRect(canvas): 캔버스의 CSS 크기(clientWidth, clientHeight)로 잰다. 돌려주는 사각형은 모두 CSS 픽셀이고 너비와 높이는 0 이상이다. (여백은 CSS 픽셀인데 그리기 버퍼 크기 width, height 에서 빼서 고해상도 화면에서 섞인 단위였다)
- Color: 성분을 0 ~ 1 로 자르지 않고 그대로 담는다. (빛나는 색처럼 1 을 넘는 HDR 색, 유니티 Color 처럼, 러스트 판과 같다) 0 ~ 255 글(toRGBAString, toHEXString)로 낼 때만 성분은 0 ~ 255, rgba 의 알파는 0 ~ 1 로 자른다. 옮기는 법: 0 ~ 255 값으로 new Color(255, 128, 0) 처럼 만들던 코드는 Color.createFromBytes 나 0 ~ 1 값으로 바꾼다. (전에는 1 로 잘려 흰색이었고 이제는 그대로 담긴다)
- UINode: isInteractable, setInteractable, contains, getWorldCorners, convertToViewPosition, touchPress, touchMove, touchRelease, touchCancel. UINode 에 붙인 UIButton 이 솔버가 푼 자리로 눌린다. (TouchRaycaster 가 WorldNode 만 맞히고 UINode 는 누름 판정이 없어 눌리지 않았다, 러스트는 UINode 가 WorldNode 의 컴포넌트라 원래 눌렸다) UIButton 은 setInteractable 이 있는 노드면 붙을 때 켠다
- UIScrollBar: 자동 숨김이 노드를 끄지 않고 켜 둔 채 숨긴다. (끄면 갱신이 멈춰 콘텐트가 길어져도, setAutoHide(false) 를 해도 다시 나오지 않았다) 숨은 동안 그리지 않고 누름도 받지 않는다. isAutoHidden() 추가
- LanguagePack, UIFont: JsonAsset.load 가 실패를 거부하게 되어 받기 실패를 못 읽은 것으로 받는다. (지금처럼 경고를 내고 null, false) UIFont 머리 주석의 목록 꼴을 코드와 맞췄다({ fonts: [...] }, { faces: [...] })
- ShaderSprite.isDrawnInsideContent: 뒤집어도 참이다. (Sprite 가 뒤집어도 내용 영역 안에 그리게 되어 같게)
- Sprite.setImage: HTMLCanvasElement, OffscreenCanvas 도 받는다. (전에는 HTMLImageElement 와 ImageAsset 말고는 무시했다, UIImageView.setImage 로 넘긴 OffscreenCanvas 도 이제 그려진다)
- Graphic.drawPolyline, drawLine, drawLineLoop, drawStrokeRoundRect, drawConvexPolygon: 정점 버퍼(4096 정점)가 차면 쌓인 것을 그리고 이어 적는다. 전에는 683 번째 선분(볼록 다각형은 1366 번째 삼각형)부터 버렸다.
- Graphic.setCullingEnabled: 머리 주석의 기본값을 실제(켬, true)에 맞췄다.
- SoundSystem: 소리 표 줄에 volume 이 없으면 1 로 낸다. (전에는 NaN 이 되어 0, 소리가 나지 않았다)
- TouchRaycaster: WorldNode 만 맞히던 것을 노드 종류를 가리지 않게 했다. isInteractable 과 contains 가 있는 노드는 모두 맞고 누름을 받는다.
- ParticleSystem.applyDescription: 서술의 imageDataUrl(파티클 편집기가 고른 그림의 data: 주소)을 읽어 입자 이미지로 건다. (null 이나 빈 글이면 그림을 뗀다) 저장한 서술을 게임에서 다시 불러도 고른 그림이 되살아난다.
- ParticleEmitterShape: 머리 주석의 edge 방향을 실제(아래쪽 +y)에 맞췄다.
- FontAsset.load(assetPath): 경로만 정하고 읽지 않던 것을 실제로 읽게 했다. 파일 이름에서 확장자를 뗀 것을 패밀리 이름으로 loadFont 한다. ("assets/DOSGothic.woff" 면 "DOSGothic")
- JsonAsset.load: 받기나 해석이 실패하면 거부한다. (TextAsset, ImageAsset 과 같다) 옮기는 법: 실패해도 풀린다고 보고 await 뒤 data 가 null 인지 보던 코드는 try/catch 로 감싼다. SpriteAtlas.load 는 그대로 JSON 실패에도 알리고 풀린다.
- Asset.unload: 로드되었을 때는 undefined, 아닐 때는 풀린 프로미스를 돌려주던 것을 두 갈래 모두 아무것도 돌려주지 않게 맞췄다. (덮어쓴 하위 클래스, 러스트와 같다)
- LayoutSolver: 변수가 없는 항(LayoutTerm(null), 값 0)이 든 식을 받으면 updateVariables 에서 TypeError 를 냈다. 이제 그런 항은 계수가 0 인 항처럼 건너뛴다. (그런 항만 남은 5 == 0 은 모순 제약, 0 == 0 은 받는다)
- UISnapScrollView: setSnapToNearest, setVelocityThreshold 가 값만 담고 스냅 계산에 쓰이지 않았다. 이제 한 칸 모드(기본)는 놓을 때 드래그 속도가 setVelocityThreshold(기본 200, 스크롤 오프셋의 초당 픽셀) 이상이면 끈 거리와 상관없이 속도 방향으로 한 칸 넘기고(플링), 아니면 지금처럼 setPageChangeThreshold 비율로 정한다. setSnapToNearest(true) 는 끄는 동안 칸 범위를 자르지 않고, 놓으면 스냅 오프셋이 가장 가까운 아이템으로 간다. getDragVelocity() 를 더했다. (마지막으로 끈 tick 의 스크롤 축 오프셋 속도, 다음 칸 쪽이 음수) 느리게 끄는 기존 동작은 그대로다
- ImageScroller: setImage(ImageAsset) 이 import 없는 ImageAsset 을 써서 ReferenceError 였다. 이제 ImageAsset 이면 그 getImage() 를, 그 밖의 그림(HTMLImageElement, 캔버스 등)은 그대로 쥔다. (HTMLImageElement 전역이 없는 곳에서도 된다)
- NodeLayout: 빌더의 anchoredPosition 이 부모에 붙기 전에 걸려 앵커를 무시했다. 이제 build 에서 부모에 붙인 뒤 부모 contentSize 의 앵커 점 기준으로 건다. (앵커는 anchoredPosition 을 부를 때의 앵커, 나중에 부른 localPosition 이 이긴다, 러스트 판과 같다) 선언 없이 남은 옛 "레이아웃 인스턴스 생성" 주석 덩이를 지웠다
- Camera2D: 머리 주석의 사용 줄 camera.follow([heroPosition], 6) 에 timeDelta 가 빠져 그대로 쓰면 위치가 NaN 이었다. camera.follow([heroPosition], 6, timeDelta) 로 고쳤다. setPosition 에 제 머리 주석을 달았다. (전에는 "접근자." 절 머리가 설명으로 읽혔다)
- LanguagePack: loadLanguageList 가 읽은 languages.json 의 줄에 aliases 가 없으면 matchLanguageTag 가 TypeError 였다. 이제 파일에서 읽은 목록도 setLanguageList 를 거친다. code 가 글이 아닌 줄은 빼고, aliases 와 countries 가 없으면 빈 배열, 글은 소문자로 맞춘다. (러스트 판과 같다)
- DEVTools: Settings 의 Show FPS 가 저장만 되고 쓰이지 않았다. 켜면 패널을 닫아도 창 왼쪽 위에 "FPS 값" 상자(지난 1 초의 프레임 수, canvas-native 좌표)를 그린다. 패널이 보이면 패널 위에 그린다
- UIListView: 공개 API 의 설명, @param, @returns, 예제(500 줄 템플릿 목록, 만들기 함수, 끝 알림)를 채웠다
- UIInputField 커서와 지우기: 왼쪽, 오른쪽 화살표와 Delete 가 크롬처럼 글자 묶음(확장 자소 묶음, Intl.Segmenter) 단위로 움직이고 지운다. 뒤로 지우기는 블링크 BackspaceStateMachine 을 옮겨 코드 포인트 하나씩 지우되 CR LF, 이모지 표현 선택자와 바탕, 피부색 조정자, ZWJ 이모지, 국기, 키캡, 태그 묶음은 통째로 지운다. 서로게이트 쌍을 쪼개던 버그를 고쳤다. (헤드리스 크롬 textarea 의 execCommand 결과와 같음)
- UIInputField 선택이 있을 때 Shift 없는 왼쪽, 오른쪽 화살표는 크롬처럼 선택의 앞, 뒤로 접는다. 누른 자리(measureIndexAtLocalX)는 글자 묶음 경계에만 선다. moveCursor 에 서로게이트 쌍 가운데 자리를 주면 그 글자 뒤로 본다.
- UIInputField.deleteRange(startIndex, endIndex) 추가. deleteCharAt(index) 는 그 자리부터 글자 묶음 하나를 지운다. (전에는 UTF-16 한 칸)
- UIInputField 최대 길이: setText 는 서로게이트 쌍을 쪼개지 않는 데까지 자르고, 넣기(replaceSelection, 붙여넣기, 글자 치기)는 블링크 입력 칸처럼 넣는 글을 남은 길이까지만 넣는다. (전에는 값 전체를 잘라 커서 뒤 글이 지워질 수 있었다)
- UIInputField.setFont 에 FontAsset 을 주면 그 fontFace 를 쓴다. (전에는 FontAsset 을 그대로 들어 글꼴을 읽기 전이면 글 재기의 CSS font 가 깨졌다) 글 재기와 선택, 커서 그리기는 UILabel 과 같은 buildFontString 으로 짓는다.
- UIInputField DOM 입력은 크롬 입력 칸처럼 마우스로 두 번 누르면 낱말(윈도우는 뒤 공백까지), 세 번 누르면 글 전체를 고르고, 그 뒤 끌면 낱말 단위로 넓힌다. 누름 수는 캔버스 mousedown 의 detail 이다.
- List, Dictionary: find, findAll 의 콜백이 색인이나 키를 this 로 받던 것을 정석 꼴로 바꿈. List 는 콜백(요소, 색인, 리스트)(Array.prototype.find 처럼), Dictionary 는 콜백(값, 키, 딕셔너리)(Map.prototype.forEach 처럼). 옮기는 법: function 콜백에서 this 로 색인이나 키를 읽던 곳은 두 번째 인자로 받는다. (첫 인자만 쓰던 콜백은 그대로 돈다)
- Animator: 상태를 바꾸지 않던 뼈대를 정석 상태 기계로 완성. AnimationState 에 속도(setSpeed, getSpeed), 되풀이(setLoop, isLoop, null 이면 클립을 따름), getDuration, getNormalizedTime, getFrameIndex. AnimationTransition 에 종료 시각(setExitTime, getExitTime, 정규화 시간, 되풀이 상태의 1 미만은 바퀴마다), 섞는 시간(setDuration, getDuration, 크로스페이드), setCanTransitionToSelf, canTransitionToSelf, 조건(addCondition(이름, 견주는 법, 기준 값), getConditions), isExitTimeReached, from 이 null 이면 어느 상태에서나(Any State). 새 AnimationConditionMode(if, ifNot, greater, less, equals, notEqual). Animator 에 매개변수(setFloat, getFloat, setInteger, getInteger, setBool, getBool, setTrigger, resetTrigger, getTrigger, getParameters), play, findTransition, startTransition, isConditionSatisfied, getCurrentStateIndex, getCurrentNormalizedTime, getCurrentFrame, isInTransition, getNextStateIndex, getNextNormalizedTime, getNextFrame, getTransitionWeight. tick 이 상태 시간을 흘리고 Any State 를 먼저, 그다음 지금 상태의 전이를 넣은 차례로 보고 처음 맞는 하나를 탄다(조건으로 쓴 트리거는 풀림, 섞는 동안은 새 전이를 보지 않음). 처음 더한 상태에서 시작한다. 옮기는 법: setProperty, getProperty, getProperties 는 없어졌다. 종류에 맞게 setFloat, setInteger, setBool, setTrigger 와 그 게터로 바꾼다. 안의 Animation 처리기(getAnimation)도 없어졌다. 고른 프레임은 getCurrentFrame, getNextFrame 과 getTransitionWeight 로 읽는다.
- Visual: 문서 글(setDocumentText, getDocumentText)과 createNode 추가. createNode 가 문서로 새 노드 트리를 지어 뿌리의 로컬 위치를 location 으로 둔다. 공개 API 의 설명과 예제를 채움.
- Localization.isRightToLeft: setRightToLeft 처럼 소문자로, 밑줄을 하이픈으로 읽는다. ("ar_EG" 를 오른쪽에서 왼쪽 언어로 못 잡던 것)
- Material.createFromDescription: 중간 이미지를 풀지 못하면 그때까지 지은 텍스처를 지우고 거절된다. createTexture 는 그림을 다 푼 뒤에 텍스처를 지어, 풀지 못하면 텍스처를 남기지 않고 기다리는 동안 다른 텍스처가 묶여도 제 텍스처에 올린다. (예전에는 기다리기 전에 묶어, 그사이 묶인 다른 텍스처에 올릴 수 있었다)
- ShaderProgram: 프래그먼트 셰이더 컴파일이나 링크에 실패하면 먼저 지은 셰이더(와 프로그램)를 지운다
- UINode.addConstraint: 솔버가 받지 않은 제약(이미 더한 것, 모순)은 목록에 남기지 않는다. (다음 setSolver 가 같은 오류로 멈추던 것)
- UISpinner.calculateDotOpacity: 점이 없으면(dotCount 0) 0 나누기로 NaN 이 되지 않는다
- UIListView.setHorizontal: 바뀌면 스크롤 영역을 다시 재고 보이는 항목을 새 축에 다시 놓는다
- Camera(src/deprecated/camera.js): 폐기 예정. Camera2D(src/misc/camera2d.js)가 회전과 begin, end 까지 모두 덮는다. import.js 는 아직 Camera 로 내보내고, 다음 판에서 빠질 수 있다
- 외계행성 광부 키우기(webgame-rimminer)가 게임 쪽에 따로 만들어 쓰던 범용 기능을 엔진으로 옮긴다. (게임 코드는 건드리지 않았다, 게임은 지금처럼 자기 것을 쓴다)
- Outline: 테만 그리는 컴포넌트. (Paint 는 속을 채우기만 한다) 둥근 네모 테(setRoundSize) 또는 동그라미 테(setCircle), 선은 내용 크기 안쪽에 들어온다. setColor(Color 나 "#rrggbb", "rgba(...)"), setLineWidth
- UIProgressRing: 진행 고리 컴포넌트. 노드의 꼴(둥근 네모, 둥근 정도가 크기의 반이면 동그라미)을 따라 위 가운데에서 시계 방향으로 채운 몫(setRatio)만큼 채운 색, 나머지는 바탕 색으로 그린다. 둘레의 점은 크기, 둥근 정도, 굵기가 바뀔 때만 셈한다
- UIHitArea: 누르는 자리 넓히기. UIHitArea.attach(buttonNode, minimumSize) 로 단추 바로 뒤 형제로 투명한 누름 자리를 두어 가로세로를 minimumSize 이상으로 넓힌다. 넓힌 몫을 누르면 단추의 클릭 알림을 부르고, 단추가 꺼지거나 누를 수 없으면 따른다. 단추의 자리, 크기, 피봇을 프레임마다 따라간다. setClipNode 로 넓힌 몫을 창이나 스크롤 칸 안으로 자를 수 있다
- FrameProbe: 처지는 기기 가리기. 기다리는 초 뒤 재는 초 동안 프레임 간격을 보아, 목표 간격의 1.4 배를 넘긴 프레임이 25% 이상이면 처지는 기기다. (90 Hz 화면의 60 FPS 처럼 늘 한 장 걸러 그리는 것은 처진 것으로 보지 않는다) restart, measureAgain, 값은 setSeconds, setSlowFrameThreshold 로 바꾼다
- PointerCursor: 마우스 커서. 켜면(PointerCursor.getInstance().setEnabled(true)) 엔진이 프레임 끝마다 캔버스의 커서를 정한다. UIButton 위(누르는 중 포함)면 단추의 커서(처음은 pointer), 아니면 setScreenCursor 로 정한 커서다. registerImageCursor 로 1 배와 2 배 그림 커서를 더한다. 손가락 기기에서는 건드리지 않는다. 꺼져 있으면(기본) 지금까지와 같다
- UIButton: 마우스가 올라 있거나 누르는 중이면 PointerCursor 에 알린다. (PointerCursor 가 꺼져 있으면 아무 일도 없다)
- Platform: isDesktopWeb() (모바일이 아니고, 손가락 입력이 여럿 되는 맥인 아이패드도 아님), isCoarsePointer() (CSS pointer: coarse)
- ViewManager: getCssPixelScale(). 뷰 한 단위가 화면에서 몇 CSS 픽셀인지. (작은 화면에서 UI 층만 키울 배율을 셈할 때 쓴다)
- SoftShade, SoftShadeShape: 부드러운 그늘 컴포넌트. 글 뒤를 어둡게 눌러 밝은 바탕 위에서도 읽히게 한다. 띠(가운데가 가장 짙고 위아래와 양옆으로 엷어짐) 또는 바닥(아래가 가장 짙은 세로 그라데이션)을 작은 캔버스에 구워 내용 크기로 늘려 그린다. 크기, 모양, 색, 짙기가 바뀔 때만 다시 굽는다
- ShadowText: 그림자를 깐 한 줄 글 컴포넌트. 그림자 위에 글을 얹은 모습을 캔버스 한 장에 구워 그리므로 노드의 불투명도가 글과 그림자에 한 장째로 먹는다. (Text 두 벌로 깔면 흐리게 할 때 밑의 그림자가 비친다) 그림자는 번지게(setShadow 의 shadowBlur) 할 수 있고, 넘치면 setFitMinimumRatio 까지 줄여 맞춘다. 가로 정렬과 자리는 Graphic.drawTextEntry 와 같은 셈, 세로는 가운데. setFontFace, setTextDirection
- ShadowImage: 그림자를 깐 그림 컴포넌트. 그림(또는 setImage(image, imageRect) 로 아틀라스의 조각)을 노드 안에 비를 지켜 가운데로 그리고, 그림의 모양 밑에 그림자를 칠해 한 장으로 굽는다. setImageColor 로 그림을 한 빛으로 칠할 수 있다
- buildRGBAString(colorText, opacity): "#rrggbb" 와 불투명도로 캔버스의 rgba 색 글을 만든다. (shadowtext.js)
- CameraGestures: 카메라 손짓. 3D 판이나 지도를 돌리고 밀고 키우는 손짓을 캔버스의 DOM 사건에서 따로 읽는다. 마우스 오른쪽 끌기(가로는 돌리기, 화면 너비가 한 바퀴, 세로는 기울이기, 끌지 않고 떼면 오른쪽 클릭), 가운데 끌기(밀기), 두 손가락(밀기, 오므려 키우기, 문턱을 넘게 비틀면 돌리기). 모인 양은 takePan, takeRotation, takeTilt, takeZoom, getZoomAnchor 로 매 프레임 꺼낸다. 손짓 중이면 isGestureActive. 손가락을 뗀 바로 뒤의 흉내 낸 마우스 사건은 무시한다. setThresholds 로 문턱을 바꾸고 dispose 로 뗀다
- SoundSystem, setSoundSystem, readSoundSystem: 소리 표로 다루는 배경음악과 효과음. (AudioManager 의 공유 AudioContext 와 AudioAsset 을 쓴다) 줄마다 { id, path 나 paths, volume, minimumInterval, isMusic, maximumVoices, pitchVariation, playSeconds, fadeOutSeconds }. 여러 녹음 중 바로 앞과 다른 것 고르기, 같은 소리 동시 수 제한, 음 높이 흔들기, 앞 몇 초만 틀고 줄여 끄기, 배경음악 겹쳐 바꾸기와 이어 틀기, 음악과 효과음 버스. 음소거는 사용자 단추, 페이지 가려짐, 터치 기기의 창 포커스 잃음(아이폰이 앱 전환 때 오디오가 얼어 되풀이되는 것을 막는다), setExternalMuteProvider 로 준 바깥 음소거(플랫폼 SDK, 광고) 가운데 하나라도 맞으면 걸리고, 그동안 AudioContext 를 멈춘다. 풀린 뒤 돌지 않으면 잠깐마다 다시 깨운다. setAutoplayAllowedProvider 로 누르기 전 깨우기를 막을 수 있다. 매 프레임 update()
- LanguagePack: 자산의 JSON 으로 두는 언어 묶음. (import 의 LanguagePack 이름 아래 함수들) languages.json(언어 목록, fallbackLanguage, 언어마다 code, name, englishName, fontGroup, direction, aliases, countries, file)과 언어마다의 표를 읽는다. 설정의 언어가 비면 setPreferredLanguageTag 로 준 언어(플랫폼이 알려 준 것), 그다음 기기의 언어, 목록에 없으면 기본 언어. 없는 열쇠는 기본 언어의 글자, 거기도 없으면 열쇠 그대로. translate, formatText({이름}), readTextDirection, isolateText(방향 격리), html 의 lang 과 탭 제목(setDocumentTitleKey). setLanguagePaths 로 경로를, setLanguageLoadedHandler 로 언어를 불러온 뒤 할 일(그 언어의 글꼴 받기)을 건다. Localization(코드 안의 표)은 그대로다
- UIFont: 여러 문자의 글꼴 조각을 한 글꼴 이름 아래 묶는다. (import 의 UIFont 이름 아래 함수들) Google Fonts 가 나눠 둔 조각마다 FontFace 를 그 조각의 글자 범위(unicode-range)로 올려, 화면에 쓰는 글자가 든 조각만 받는다. 고른 언어의 묶음을 라틴 바로 앞에 올려 한자가 그 언어의 글꼴로 나오고, 숫자와 영문은 늘 라틴 글꼴이다. 굵기는 두 가지로만 올려 범위로 함께 고르게 한다. 쓸 글자의 조각을 미리 받고(loadUiFontText, requestUiFontText), 처음 조각은 정한 시간까지만 기다린다. 나머지 묶음은 조금 뒤에 받는다. configureUiFont 로 이름, 목록 경로, 굵기, 기다리는 시간을 정하고 readUiFontFace 로 Text 와 ShadowText 에 줄 FontFace 를 읽는다
- ToastMotion, attachToastMotion, readToastSeconds: 알림 노드에 붙이는 나옴과 사라짐 모션. show(text, seconds, applyText) 로 바깥쪽(setEnterSide, 위나 아래)에서 미끄러져 들어오며 살짝 커졌다 돌아오고, 머문 뒤 떠오르며 사라지고 노드를 끈다. 떠 있는 동안 다른 글이 오면 앞 것이 빨리 비키고, 같은 글이 또 오면 시간만 다시 채우고 통 튄다. 자리는 놓인 자리를 기준으로 그 둘레에서만 움직인다. readToastSeconds 는 긴 글일수록 머무는 시간을 늘린다. (UIToast 는 줄 세운 알약 알림을 스스로 만들고, 이것은 게임이 만든 알림 노드를 움직인다)
- ButtonMotion, ButtonMotionStyle, attachButtonMotion, setButtonMotionArea, shakeButton: 단추 반응. UIButton 다음으로 붙이면 단추의 상태를 읽어 노드를 가운데를 두고 키우고 줄인다. normal 꼴은 올리면 커지고 누르는 동안 줄고 떼면 통 튄다. inset 꼴(창 안)은 커지지 않고, 올린 동안 바탕을 밝히고 안쪽에 흰 테를 둔다. 누를 수 없으면 shakeButton 으로 좌우로 흔든다. 꼴은 단추마다(setStyle) 또는 위 노드에 setButtonMotionArea 로 건다. 손가락 기기는 올림을 쓰지 않는다. 반응이 없을 때는 노드를 건드리지 않아 다른 연출과 겹치지 않는다. 단추에 얹은 꾸밈이 제 모양으로 밝히게 하려면 setLitHandler 로 함수를 건다
- ToonMesh(graphics3d/toon/meshbuilder.js): 툰 3D(점토 같은 한 색 재질과 바깥선)를 그릴 꼭짓점 배열 짓기. MeshBuilder 에 상자, 둥근 상자, 원기둥, 구, 회전체, 캡슐, 도넛, 팔면체 도형을 자리, 돌림, 크기를 곱해 한 덩어리로 담는다. 꼭짓점은 자리 3, 노멀 3, 색 3(sRGB), 재질 2(빛남, 빛을 받지 않음), 무늬 4(무늬 번호와 색, 뜻은 셰이더가 정함). 바깥선은 점마다 같은 굵기로 민 껍데기(inverted hull)를 따로 담고, 모서리에서 너무 튀지 않게 민다. 삼각형의 감기는 노멀을 보고 바깥이 앞면이 되게 맞춘다. 뼈대 모형은 본 번호와 무게를 따로 담는다
- ToonGlb(graphics3d/toon/glbmeshreader.js): 텍스처 없이 재질 색으로 칠하는 GLB 를 MeshBuilder 배열로 읽는다. (readGlbArrays, 노드마다 따로 readGlbNodeArrays, 노드 정보 readGlbNodeInfos) baseColorFactor 는 sRGB 로, emissiveFactor 는 빛남으로, 재질 extras 의 outline 과 basic 을 읽는다. 뼈대(skin)와 움직임(animations, extras)을 읽고 writeSkinPose 로 한 순간의 본 행렬을 셈한다. (앞 자세와 섞기, 흔들림 배율) 엔진의 SkinnedModel(텍스처 PBR)과는 따로다
- ToonRenderer(graphics3d/toon/toonrenderer.js): ToonMesh 와 ToonGlb 의 배열을 그리는 툰 렌더러. 해(방향, 색)와 하늘색, 땅색을 섞은 바탕빛, setBandCount 로 셀 셰이딩 칸, 꼭짓점의 빛남과 빛을 받지 않음, 모형마다 틴트와 불투명도, 바깥선 껍데기는 뒷면만 그린다. 뼈대는 writeSkinPose 의 본 행렬을 drawMesh 의 jointMatrices 로 넘긴다. (96 개까지, 엔진 SkinnedModelRenderer 와 같다) beginFrame 이 앞의 그리기 상태를 적어 두고 endFrame 이 돌려, 엔진 2D 그리기 사이(flushBatch 뒤)에 끼울 수 있다. readProgramSources 로 ShaderWarmer 에 넘길 소스를 준다. 외계행성 광부 키우기의 판 렌더러에서 땅 무늬와 화면 공간 선 같은 게임 몫은 빼고 새로 지었다
- ToonPostProcess: HDR 마무리. 반정밀 실수 RenderTarget 에 그린 씬을 BloomEffect 로 번지게 하고, 노출과 ACES 근사 톤매핑과 sRGB 감마로 화면에 낸다. (begin, end, setExposure, setBloom) 러스트 vanilla-engine 과 같은 구성이다
- Graphic.drawRoundRect: 꼭짓점 36 개의 cos / sin 을 모듈을 읽을 때 한 번 구해 둔 표로 셈하고, Vector2 배열을 만들지 않고 고쳐 쓰는 칸에 적은 좌표로 바로 버텍스를 쓴다. (노드마다 프레임마다 삼각함수 72 번, Vector2 36 개, 코너 객체 4 개가 없어진다) 표는 지금까지와 같은 식(엔진 base/math.js 의 cos / sin)으로 구해 꼭짓점 값이 비트까지 같다. buildRoundRectPositions 도 표를 쓴다. (돌려주는 Vector2 배열은 지금처럼 새로 만든다) drawRoundRect 는 이제 buildRoundRectPositions 를 거치지 않는다
- Graphic: writeRoundRectPositionData(rect, roundSize), drawRoundRectPositionData(color). 라운드 사각형 좌표를 모듈의 칸에 적고, 그 칸으로 채움을 그린다. (drawRoundRect 가 쓴다)
- Paint.draw: 그릴 때마다 Rect 하나(안의 Vector2 포함)와 내용 크기 복제본을 만들던 것을, 모듈에 하나 둔 사각 영역을 고쳐 쓰고 WorldNode.copyContentSizeTo 로 크기를 받게 바꾼다. graphic 의 그리기 함수에 넘긴 사각 영역은 다음 Paint 를 그릴 때 바뀐다. (엔진 안에서 받은 사각 영역을 들고 있는 곳은 없다)
- WorldNode: copyContentSizeTo(target). 내용 크기를 복제본 없이 target 에 적는다. getContentSize 를 덮어쓴 하위 클래스(UINode 등)면 그 함수가 주는 값을 적는다
- TransformNode, WorldNode 의 pushTransform: 위치, 크기, 피봇, 내용 크기를 복제본 없이 읽는다. (노드마다 프레임마다 Vector2 넷) TransformNode.applyLocalTransform(graphic) 이 로컬 위치, 회전, 크기를 건다. 그 getter 들을 덮어쓴 하위 클래스면 지금처럼 getter 를 불러 읽는다
- TransformMatrix: rotate(0) 과 scale(1, 1) 은 행렬을 셈하지 않고 돌아간다. (결과는 같다, 회전하지 않는 노드도 그릴 때마다 부른다)
- Graphic.pushState / popState: 저장할 때마다 행렬 복제본과 상태 객체를 만들지 않고, 스택 깊이마다 만들어 둔 칸에 지금 행렬 객체와 그 값을 적는다. 복원하면 저장할 때의 행렬 객체에 그 값을 되돌려 적고 다시 지금 행렬로 삼는다. 그래서 getTransformMatrix() 로 받아 둔 행렬은 복원 뒤에도 지금 행렬이다. (지금까지는 복원하면 저장해 둔 복제본으로 바뀌어, 받아 둔 행렬은 더는 지금 행렬이 아니었다)
- TransformNode.setLocalPosition / setLocalScale, WorldNode.setPivot / setContentSize: 받은 벡터를 복제하지 않고 가진 벡터에 값을 옮겨 적는다. getter 는 지금처럼 복제해 주므로 가진 벡터는 밖으로 나가지 않는다
- Rect: 생성자와 create() 가 갓 만든 Vector2 를 setter 로 한 번 더 복제하지 않는다. (Rect.create 하나에 Vector2 여덟 개이던 것이 두 개)
- Color.clone(): Reflection.clone 을 거치지 않고 rgba 를 바로 옮긴 새 Color 를 만든다. (Rect.clone 처럼 하위 클래스가 아니라 Color 를 돌려준다, 엔진 안에 Color 의 하위 클래스는 없다) setFillColor 처럼 그릴 때마다 부르는 곳이 있다
- Reflection.clone: getter 와 setter 를 함께 가진 프로퍼티 이름 목록을 프로토타입마다 처음 한 번만 훑어 두고 쓴다. (부를 때마다 프로토타입 사슬을 훑었다) 복사하는 차례와 값은 같다
- Graphic.drawVertices: 유니폼 자리(modelMatrix, mainColor, tintColor, globalAlpha)를 드로우 콜마다 이름으로 찾지 않고 셰이더 프로그램이 바뀔 때만 찾는다. (uploadDrawUniforms) 기본 프로그램의 틴트와 전역 투명도는 지난번에 올린 값과 같으면 다시 올리지 않는다. 프레임 시작(applySettings)과 프로그램이 바뀔 때 올린 값을 잊고, 바꿔 끼운 프로그램(setShaderProgramOverride)에는 늘 올린다. 게임이 기본 프로그램의 tintColor, globalAlpha 유니폼을 직접 올리면 다음 드로우 콜이 그 값을 바로잡지 않을 수 있다. (엔진 안에는 그런 곳이 없다)
- Engine: 최대 FPS 제한(EngineConfiguration.maximumFramePerSecond)을 처리한 프레임 수로 센다. 세기 시작한 때부터 처리한 프레임 수로 다음 프레임의 차례(시작 시각 + 수 × 간격)를 정하고, 차례보다 4 ms 넘게 일찍 온 프레임만 건너뛴다. 밀린 것은 다음 프레임에 처리해 평균이 최대 FPS 가 된다. 지금까지는 마지막으로 처리한 프레임 뒤로 간격보다 4 ms 덜 지났으면 건너뛰고 기준을 처리한 프레임의 시각으로 다시 잡아 밀린 것을 잊었으므로, 주사율이 최대 FPS 로 나누어떨어지지 않으면 제한이 어긋났다. (60 FPS 에서 90 Hz 는 한 프레임 걸러 45, 144 Hz 는 72, 75 Hz 는 하나도 건너뛰지 않아 75) 한 프레임 넘게 밀리면(창이 가려졌다 돌아옴 등) 몰아서 처리하지 않고 그 시각부터 다시 센다. 차례보다 1 ms 안쪽으로 일찍 온 프레임을 처리하면 그 시각부터 다시 세어, 주사율이 최대 FPS 와 거의 같은 화면(60.05 Hz 등)에서 조금씩 앞서 간 것이 쌓여 가끔 한 프레임을 건너뛰지 않는다. 최대 FPS 를 바꾸면 다시 센다. 60 Hz 화면의 60 FPS, 주사율의 약수인 최대 FPS(90 Hz 의 30 FPS 등)는 지금까지와 같다.
- UIDocument: getReflectedProperties(component) 로 컴포넌트의 짝 맞는 get(또는 is)/set 속성 목록을 연다. (에디터의 인스펙터가 쓴다) 컴포넌트 종류 표에 Outline, SoftShade, ShadowText, UIProgressRing 을 더했다
- 렌더링: 같은 셰이더 프로그램과 같은 텍스처를 다시 거는 호출을 거른다. Graphic 이 마지막으로 쓰게 한 프로그램과 0 번 텍스처 유닛에 묶은 텍스처를 기억해 같으면 useProgram, bindTexture 를 부르지 않는다. (useShaderProgram, bindTexture) 묶어 그리기(flushBatch)와 파티클 그리기(drawColoredQuads)는 그린 뒤 기본 프로그램으로 되돌리지 않고 다음에 그리는 쪽이 제 프로그램을 쓰게 해, 묶음을 잇달아 그릴 때 프로그램을 오가지 않는다. 그리는 결과는 같다. (예제 uishowcase, uisample, spriteeffects, particleeffects, timelineshowcase 와 바깥 GL, ShaderSprite, ScreenEffect, 씬 둘, 밉맵 바꾸기를 섞은 시험 장면을 시계와 난수를 고정해 같은 프레임에서 뜨면 묶기 끔, 켬 모두 고치기 전과 픽셀이 같다)
- Engine: 씬마다 그리기 전(preDraw, 로딩 중이면 drawOnLoad)에 Graphic 의 묶음 기억을 잊는다. (앞 씬의 그리기와 이 씬의 갱신 사이에 바깥 WebGL 이 텍스처를 바꿨을 수 있다)
- Text: 줄바꿈한 줄 배열을 기억해 두고, 글, 글꼴, 크기, 굵게, 기울임, 폭, 줄바꿈 방식이 바뀌거나 웹 글꼴이 받아지거나(loadingdone) 문서에 글꼴 얼굴이 올라가고 빠질 때만 다시 나눈다. (readWrappedLines) 그릴 때마다 단어와 글자마다 measureText 하던 것이 없어진다
- Sprite.draw: 그릴 때마다 만들던 Vector2 넷(위치, 내용 크기 복제, 뒤집기, 곱한 크기)과 그림 영역이 없을 때의 Rect 를 없앤다. 모듈의 벡터를 고쳐 쓰고 WorldNode.copyContentSizeTo 로 크기를 받으며, 영역이 없으면 그림 전체를 바로 그린다. Graphic.drawImageWithImageRect 도 영역이 없을 때 Rect 를 만들지 않는다
- Graphic.beginClipRect: 영역과 변환 행렬의 복제본을 만들지 않고 클립 깊이마다 만들어 둔 칸에 값을 적는다. endClipRect 는 그 칸을 지금 행렬 객체로 삼지 않고 값만 옮겨 적는다. (popState 가 begin 때의 행렬로 되돌리는 것은 같다) Mask.beginClip 도 클립 영역을 새로 만들지 않는다
- TextStringTextureCache.getEntry: 찾을 때마다 열쇠 문자열을 만들지 않고, 문자열별 엔트리 목록에서 나머지 값(방식, 방향, 배율, 선 두께, 색, 글꼴)을 견준다. 열쇠 문자열은 구울 때 한 번 만들어 엔트리에 둔다. (LRU 차례와 상한, invalidateFontFaces 는 같다)
- ParticleSystem: 수명이 다한 파티클을 splice 로 하나씩 빼지 않고(뒤를 매번 당긴다) 살아 있는 것을 앞으로 당겨 담는다. (그리는 차례는 같다) 그림 파티클은 그릴 때마다 Vector2 둘을 만들지 않는다
- Graphic: isCullingEnabled(), isLocalRectVisible(rect) (지금 변환으로 옮긴 사각형이 드로잉 버퍼에 걸치는지), addCulledNodeCount(count), getLastFrameCulledNodeCount(). 엔진 통계(useStatistics)에 culledNodes 줄을 더했다
- HeatHazeEffect(experimental): 없는 graphic.getCanvasRenderingContext() 를 부르던 Canvas2D 시절 코드를 지금 WebGL Graphic 으로 다시 짰다. 묶음을 먼저 그린 뒤 노드 영역의 화면 바운딩 박스를 copyTexSubImage2D 로 텍스처에 떠 오고, 줄마다 쿼드 한 장씩 정점 색 쿼드(drawColoredQuads)로 사인 곡선만큼 옮겨 그린다. (러스트 vanilla-engine 과 같은 방식, 흔들림 0 이면 효과가 없는 화면과 픽셀이 같다) 영역이 화면 밖으로 나가면 가장자리 픽셀을 늘인다. 내용 크기와 피봇을 쓰므로 TransformNode 대신 WorldNode 를 상속한다. (TransformNode 에는 setContentSize, getWorldBounds 가 없어 만들 때부터 죽었다) 떠 온 텍스처는 destroy() 가 지운다
- 입력: 출시 게임들(찾았다, 종말 생존, 우주생물, aberrant, 외계행성 광부)이 게임 쪽에 따로 만들어 쓰던 입력을 엔진 기본으로 옮긴다. (게임 코드는 건드리지 않았다, 게임은 지금처럼 자기 것을 쓴다)
- GamepadKind, readGamepadKind(gamepadId): 패드 이름(Gamepad.id)으로 종류를 가른다. 플레이스테이션(054c, playstation, dualshock, dualsense, sony), 닌텐도(057e, nintendo, joy-con, pro controller), 엑스박스(045e, xbox, xinput, microsoft), 그 밖은 other
- GamepadManager.vibrate(strongMagnitude, weakMagnitude, seconds): 연결된 패드를 모두 브라우저 vibrationActuator 의 dual-rumble 로 떤다. 세기는 0 ~ 1 로 자른다. 진동 장치가 없는 패드와 브라우저는 건너뛴다
- GamepadManager.getActiveGamepadId(): 마지막 갱신에 단추를 누르거나 축을 0.5 넘게 기울인 패드의 이름. (없으면 빈 글, 마지막으로 쓴 장치를 가릴 때)
- GamepadManager.setInputLogEnabled, isInputLogEnabled: 단추와 축이 바뀔 때마다 찍던 console.log 를 끄고 켠다. 기본 동작을 바꿨다: 기본이 꺼짐이라 이제 단추와 축 로그는 찍지 않는다. (스틱을 조금만 움직여도 프레임마다 로그가 쏟아졌고, 로그에 기대는 게임이 없다) 연결과 해제 로그는 그대로 찍는다
- InputManager: 마우스 단추 셋(MouseButton.left, middle, right)의 눌림과 이번 프레임의 누름과 뗌(setMouseButtonDown, isMouseButtonDown, isMouseButtonJustPressed, isMouseButtonJustReleased). 프레임 사이에 눌렀다 뗀 것도 그 프레임에 잡힌다. 러스트 vanilla-engine 과 같은 꼴이다
- InputManager.setTouchFromLeftButtonOnly: 켜면 마우스 왼쪽 단추만 터치로 넘긴다. 끄면(기본) 지금까지처럼 어느 단추든 터치다
- InputManager.setContextMenuPrevented, isContextMenuPrevented: 캔버스의 오른쪽 클릭 메뉴를 막을지. 처음은 참으로 지금까지와 같다
- InputManager.isKeyJustPressed, isKeyJustReleased 의 바뀐 동작: 프레임 끝의 키 사진을 견주지 않고, 지난 프레임 끝 뒤로 온 키 사건(pushKey, popKey)을 쌓아 본다. 프레임 사이에 눌렀다 뗀 키를 놓치던 것을 고쳤다. (그때는 isKeyPressed 가 거짓이고 isKeyJustPressed 와 isKeyJustReleased 가 함께 참이다) 눌린 채 오는 키 되풀이(keydown repeat)는 새 누름이 아니다. updateFrameSnapshot 은 쌓인 사건을 비운다
- TouchPoint, TouchPhase, InputManager.getTouchPoints(), getEndedTouchPoints(): 닿아 있는 손가락 목록. 손가락마다 identifier(Touch.identifier), phase(began, moved, stationary), canvasNativePosition, viewPosition. 이번 프레임에 떨어진 손가락은 getEndedTouchPoints 에 ended 나 cancelled 로 한 프레임 남는다. 엔진이 touchstart, touchmove, touchend, touchcancel 의 바뀐 손가락마다 beginTouchPoint, moveTouchPoint, endTouchPoint 를 부르고, 사건의 touches 에 없는 손가락은 취소로 지운다. 첫 손가락이 터치로 가는 것은 그대로다
- ViewManager.convertClientToView(clientX, clientY): DOM 사건의 화면 좌표를 뷰 좌표로 바꾼다
- InputDevice, InputManager.getLastInputDevice, getLastGamepadKind (setLastInputDevice, setLastGamepadKind): 마지막으로 쓴 장치(keyboard, mouse, touch, gamepad)와 패드 종류. 키를 누르면 keyboard, 마우스 단추와 휠과 6 픽셀 넘는 움직임은 mouse(손가락을 뗀 뒤 0.8 초 안의 흉내 낸 마우스 사건은 빼고), 손가락은 touch, 패드는 getActiveGamepadId 로 gamepad 와 그 종류. 처음은 손가락 기기(pointer: coarse)면 touch, 아니면 keyboard
- InputManager.setPreventedKeys(keys), getPreventedKeys, isKeyPrevented, isTypingInTextField: 브라우저 기본 동작을 막을 키(Tab 의 초점 옮기기, Space 의 쪽 넘기기 같은 것). 글자 입력칸(Engine.isTextInputFocused 의 글자 input, textarea, contenteditable 와 select)에 초점이 있으면 막지 않는다. 처음은 비어 있어 지금까지와 같다
- InputActions(inputactions.js): 입력 동작. InputManager 가 하나 들고(getInputActions) tick 에서 갱신한다. 동작 이름에 키(bindKey), 게임패드 단추(bindGamepadButton), 게임패드 축의 한쪽(bindAxis(action, axisIndex, direction), setAxisPressThreshold 만큼 기울면 눌림)을 묶고 unbindAction 으로 푼다. isPressed, isJustPressed, isJustReleased, readValue(0 ~ 1), readAxis(negativeAction, positiveAction), readGamepadStick(xAxisIndex, yAxisIndex), readMoveAxis(WASD 와 방향키, 왼쪽 스틱, 바깥 입력원 가운데 가장 긴 것, 길이 1 이하). 죽은 구역(setDeadZone, 처음 0.2)은 빼고 나머지를 0 ~ 1 로 다시 편다. setRepeat(action, delaySeconds, intervalSeconds) 를 건 동작은 누르고 있으면 반복 때도 isJustPressed 가 참이고, 프레임이 길게 끊기면 몰아서 반복하지 않는다. 바깥 입력원(addSource, removeSource)은 readActionValue(action), readMoveAxis(), readGamepadKind() 를 가진 객체로, 플랫폼 SDK 의 패드를 게임이 끼운다. 글자 입력칸에 쓰는 동안은 키를 듣지 않는다(setKeysIgnoredWhileTyping). 키는 프레임 사이에 눌렀다 뗀 것도 한 번 눌린 것이다
- Engine: 창이 포커스를 잃으면(blur) 마우스 단추 셋도 뗀다. (InputManager.clear 는 손가락 목록과 마우스 단추, 입력 동작도 비운다)
- Camera3D(graphics3d): 원근(setPerspective)과 직교(setOrthographic), 가로 세로 비(setAspectRatio), lookAt, 보기와 투영 행렬을 값이 바뀔 때만 다시 셈해 담아 둔다(getViewProjectionMatrix, getInverseViewProjectionMatrix). projectToView(x, y, z, viewRect) 는 월드 점을 3D 를 그리는 사각형 안의 자리와 카메라 앞인지(isInFront)로, unprojectToPlane(viewPosition, planeHeight, viewRect) 는 사각형 안의 자리에서 나간 시선이 수평면 y = planeHeight 와 만나는 점으로, readViewDepth 는 보는 쪽 깊이로 셈한다. 렌더러와 2D 표시가 같은 카메라를 쓴다. (외계행성 광부, aberrant, 종말 생존이 화면마다 createLookAt, createPerspective 를 다시 짓고 투영을 손으로 셈하던 것)
- ToonRenderer: setScreenRect(x, y, 너비, 높이), clearScreenRect, getScreenRect. 노드 사각형 안에만 그린다. beginFrame 이 보기와 투영의 클립 공간을 사각형으로 옮기고 가위로 밖을 자르며, endFrame 이 가위를 푼다. 화면 밖 거르기는 옮기기 전의 절두체로 한다. beginFrameWithCamera(Camera3D), drawMeshOutline(바깥선만 그리고 세지 않음). 화면 사각형을 주지 않으면 지금과 같다
- ToonDrawQueue: 한 프레임에 그릴 모형을 담아 두었다가 불투명한 몸, 불투명한 것의 바깥선, 비치는 것(카메라에서 먼 것부터, 깊이 쓰기 끔) 차례로 그린다. addMesh, addMeshInstanced, drawShadows(renderer, shadowMap), draw(renderer, camera). (종말 생존 ModelRenderer3D 의 담아 그리기에서)
- Graphic: runExternalPass(callback, { clearDepth }) 와 clearDepthBuffer(). 2D 그리기 사이에 WebGL 패스를 끼운다. 앞의 2D 묶음을 그리고(flushBatch), 깊이를 비운 뒤 callback 을 부르고, 끝나면(던져도) restoreRenderState 를 부른다. 자르기(스텐실)를 건 뒤 깊이를 비우면 갤럭시 폴드3(Adreno 660)에서 3D 가 하나도 안 그려진 일이 있어(외계행성 광부), 자르기 안에 3D 를 그릴 노드는 beginClipRect 앞에서 clearDepthBuffer 를 부르고 clearDepth: false 를 준다. (게임 노드 넷이 같은 차례를 손으로 쓰던 것)
- ToonView3D(컴포넌트): 노드 사각형 안에 툰 3D 를 그린다. 내용 영역을 지금 변환으로 드로잉 버퍼 사각형으로 옮기고, runExternalPass 안에서 렌더러의 화면 사각형을 걸고 그리기 함수(setDrawCallback)를 부른다. 렌더러는 처음 그릴 때 짓고, 짓지 못하는 기기면 다시 짓지 않고 setFallbackDrawCallback 의 2D 로 그린다. 여러 노드가 렌더러 하나를 함께 쓰려면 setRenderer. 카메라(getCamera)의 가로 세로 비는 그릴 때마다 사각형에 맞춘다. 부모 Mask 안이면 setDepthCleared(false) 와 clearDepthBuffer 로 위 함정을 피한다
- ToonPostProcess: setColorGrade(채도, 대비, 색조 색, 색조 양, 안개빛 색, 안개빛 양), setVignette(가장자리 어둡게). 톤매핑과 감마 뒤에 건다. 색조 색은 밝기를 1 로 맞춰 곱하고, 안개빛은 어두운 곳일수록 그 색 쪽으로 끌어올린다. 기본 값(채도 1, 대비 1, 나머지 0)이면 보정이 없어 지금과 같다. 노드 사각형에 낼 때는 resize(사각형 크기) 뒤 end 의 뷰포트로 사각형을 준다. 번짐은 이미 있는 setBloom 이다. (종말 생존 SceneEffects3D 의 색 고르기에서)
- ToonMesh: MeshBuilder.combine(pieces) 는 움직이지 않는 조각 여럿({ arrays, offset: [x, y, z] })을 옮겨 한 배열로 잇는다. 바깥선 껍데기와 껍데기 기준 자리, 안쪽 범위도 옮겨 잇고 뼈대는 잇지 않는다. createFacetedChunkGeometry(반지름, 꼭짓점 배, 축 배) 는 이십면체의 꼭짓점 열둘을 저마다 늘이고 줄여 면마다 꼭짓점을 따로 둔 각진 돌덩이다. (종말 생존 combineMeshArrays, 외계행성 광부 meshbuilder.js)
- GraphicsQualityGovernor, GraphicsQuality(auto, high, low): 가벼운 길(isLite)을 덮어쓰기(applySearchText 의 ?light, setLiteOverride) → 설정(낮음은 늘, 높음은 아님) → 자동(setAutoLiteDefault 이거나 FrameProbe 가 처지는 기기로 잼) 차례로 정한다. update(프레임 초, 최대 프레임) 는 자동일 때만 재고 가벼운 길이 바뀐 프레임에 true 를 돌려준다. setRenderPixelRatioLimits(보통, 가벼운 길) 와 applyRenderPixelRatio(viewManager) 로 렌더 배율 상한을 바뀔 때만 건다. 가벼운 길에서 무엇을 줄일지는 게임이 정한다. (외계행성 광부 readIsLite, aberrant isLight)
- 출시 게임들이 따로 만들어 쓰던 로딩, 저장, 시간 기능을 엔진 기본으로 넣는다. (게임의 화면 모양과 출시처 코드는 가져오지 않았다, 기본 동작은 LocalStorage 읽기 하나만 바꿨다)
- TimeManager: setMaximumTimeDelta(seconds), getMaximumTimeDelta(). 한 프레임 간격의 상한을 바꾼다. (지금까지 0.25 초로 박혀 있었고 기본값은 그대로다) 물이나 물리가 한 번에 크게 나아가면 안 되는 게임이 0.1, 0.05 로 줄인다. 0 보다 작거나 숫자가 아니면 0.25
- Engine: setMaximumFramePerSecond(n), getMaximumFramePerSecond(). 실행 중에 최대 FPS 를 바꾼다. EngineConfiguration.maximumFramePerSecond 에 적고, 엔진은 프레임마다 그 값을 읽어 바뀐 프레임부터 다시 센다. (게임들이 설정 객체를 직접 고치던 것과 결과가 같다) 0 보다 작거나 숫자가 아니면 0(제한 없음)
- FixedStepper: 고정 걸음. new FixedStepper(stepSeconds, maximumStepsPerFrame) 의 advance(timeDelta, stepFunction) 가 쌓인 시간만큼 stepFunction(stepSeconds) 을 부르고 남은 몫(0 ~ 1, 앞 걸음과 지금 걸음을 섞어 그릴 때 쓴다)을 돌려준다. 한 프레임 상한만큼 돌고도 걸음이 남으면 남은 시간을 버리고(느린 기기에서 몰아 돌지 않게), stepFunction 이 false 를 돌려주면 그 프레임은 거기서 멈추고 시간을 쌓아 둔다. getAlpha, getLastStepCount, reset, setStepSeconds, setMaximumStepsPerFrame
- LocalStorage: 읽기(getString, getBoolean, getNumber)가 없는 키에 기본값을 써 넣지 않는다. (기본 동작을 바꾼 것이다) 읽기만 해도 저장소에 키가 생겨서, 새 판에서 기본값을 바꿔도 옛 기본값이 저장된 값처럼 남고 containsKey 가 늘 참이 됐다. 출시 게임 여섯 가운데 엔진 LocalStorage 를 쓰는 곳은 pipemania 하나이고, 읽은 값만 쓰며 키가 있는지(containsKey, getKeys)는 보지 않아 이 동작에 기대지 않는다. (2026-11-25 게임 코드 grep) 개발자 도구의 저장소 창에는 읽기만 한 키가 더는 보이지 않는다
- PersistedStore: setStorageBackend(backend), getStorageBackend(). 저장소 하나만 다른 곳(getItem, setItem, removeItem 을 가진 객체)에 둔다. 갈아 끼우면 그곳에서 다시 읽고 구독자에게 알리며, 그곳의 접근도 try 로 감싼다. 생성할 때 읽기가 저장소에 빈 키를 만들던 것도 위 LocalStorage 바뀜으로 없어졌다
- AssetLoader: 애셋 함께 받기. addImage, addJson, addText, addBlob, addAudio, addFont(family, path, descriptors), addAsset(asset, path), addTask(path, loadFunction) 로 넣고 await load() 로 setConcurrency(기본 6) 개씩 함께 받는다. 실패해도 멈추지 않고 실패 목록({ path, error })을 돌려준다. getProgress(끝난 수 / 전체 수), getLoadedCount, getFinishedCount, getTotalCount, getFailedList, isFinished, setProgressHandler, setCompleteHandler
- GameScene: 로딩 화면 바꾸기. setLoadingColors(바탕, 게이지 바탕, 게이지, 바깥) 로 색만, setLoadingDrawer((graphic, viewSize, progress, elapsedSeconds) => ...) 로 바탕 위의 그림 전체를 바꾼다. setLoadingProgress(progress) 나 trackAssetLoader(assetLoader) 로 진행률을 알리면 게이지가 최소 노출 시간의 경과 대신 그 진행률을 부드럽게 따라가고(getLoadingProgress 의 LoadingProgress), loadAssets 가 끝나면 1 로 채운다. 아무것도 정하지 않으면 지금과 같다. (검은 바탕, #333333 과 #ffffff 게이지, 경과 시간 게이지)
- ToonScreenOutline, ToonOutlineWidthUnit: 툰 화면 공간 바깥선. (외계행성 광부 키우기 boardrenderer3d.js 와 애버런트 scenerenderer3d.js 가 따로 쓰던 셰이더 바깥선을 엔진으로) ToonRenderer 의 모형을 같은 행렬로 한 번 더 그려 노멀, 선 번호, 깊이를 선의 판에 쓰고(beginLineIds, drawMesh, drawMeshInstanced, endLineIds), 한 번 훑어 선의 진하기 가면을 쓴 뒤 drawOutline 으로 화면에 섞는다. 실루엣 바깥, 다른 번호와 맞닿은 곳, 한 번호 안에서 꺾인 곳에 선다. 어느 모형과 부품(indexStart, indexCount)에 어떤 번호를 줄지, 인스턴스마다의 번호(instances[i].lineId)는 부르는 쪽이 정한다. 굵기는 월드 길이나 픽셀(setWidth, 원근의 월드 굵기는 setFocusDistance 의 거리에서, 주지 않으면 그린 모형의 평균 거리), 깊이는 투영 행렬로 직교와 원근을 가려 원근이면 미터로 푼다. setDepthThreshold, setCrease(각, 진하기, 이어짐 픽셀), setResolutionScale(0.25 ~ 1), setSampleCount(바깥선 4 ~ 28, 꺾임 0 ~ 4), setColor, setHdrOutput. beginLineIds 때의 뷰포트를 그리는 영역으로 삼아 화면 일부에 그린 3D 에도 맞는다. 껍데기 바깥선과 함께 써도 된다
- ToonVfx, ToonVfxSlot, ToonVfxLook, ToonVfxShape, ToonVfxDecalMode: 툰 3D GPU 효과의 바탕. (외계행성 광부 키우기 boardvfx.js 와 애버런트 effects.js 의 범용 부분, 효과 처방과 램프 색은 게임 몫이라 가져오지 않았다) 그림 파일 없이 코드로 짓는 아틀라스(연기 플립북 16 칸, 알갱이, 줄기, 빛살, 충격 띠, 빔 결, 그을음, 패인 땅, 둘레 빛, 색 램프 여덟 줄), 인스턴스 GPU 파티클(emitParticles: 꼴 point, sphere, ring, disc, cone, line, 끌림, 중력, 바닥에서 멈춤, 속도 쪽 늘임, 램프, 일곱 꼴), 불덩이(addFireball), 충격파 띠와 바닥 빛(addShockwave), 바닥 자국(addDecal, queueDecal, 그을음, 빛, 흐르는 테, 퍼지며 커짐), 연기 기둥(addPlume), 회전체 빔(queueBeam), 리본(queueRibbon)과 감아 내린 번개(queueLightning), 빛 점(queueGlint). update(초) 로 나아가는 자체 시계, 파티클 상한(생성자, setParticleCapacity, 넘으면 오래된 것부터 덮음)과 내는 수의 몫(setCountRatio, 폰과 가벼운 길), 램프 색(setRamps), 바닥 높이 콜백(setFloorHeightReader, 자국, 충격파, 기둥이 그 높이에 놓이고 isGrounded 파티클이 멈춤). draw(보기, 투영) 는 원근이면 빔과 리본이 카메라 자리를, 직교면 카메라 쪽을 향하고 그리기 상태를 돌린다
- 출시 게임들(외계행성 광부, aberrant, 종말 생존, 우주생물)이 따로 만들어 쓰던 창 쌓기와 화면 틀을 엔진 기본으로 옮겼다. (판 모양, 테마, 연출, 출시처 코드는 가져오지 않았다, 게임은 지금처럼 자기 것을 쓴다)
- UIWindowLayer: 창 쌓기. openWindow 로 맨 위에 쌓고 맨 위 창만 보인다. closeWindow 는 목록에서 바로 빼고(누름과 덮임이 바로 풀림) PopupMotion 닫는 움직임이 끝난 뒤 떼어 낸다. (덮여 있던 창은 바로) closeAllWindows, closeTopWindow(뒤로 가기, 바깥 닫기를 끈 창은 닫지 않음), getTopWindow, findWindow, hasOpenWindow, getWindowCount. 창이 뜨고 닫힐 때 setWindowChangeEvent 의 함수를 부른다(놀이 멈춤). 층은 UIScale.read 만큼 커지고(setUIScaleOptions, null 이면 키우지 않음, getUIScale) 창에는 그만큼 나눈 영역 크기(setViewSize)와 세이프에어리어 너비(setViewBleed)를 알린다. 휠은 맨 위 창의 handleWheel, 받지 않으면 그 자리의 스크롤 뷰(scrollWindowAt)
- UIWindow: 창 하나. 영역 전체와 세이프에어리어까지 덮는 어둠(누름을 삼킴) 위 가운데에 판을 띄운다. 판은 영역 가로에 맞춰 넓어지되 setMaximumWidth(기본 480)를 넘지 않고, 세로는 layoutContent(panelWidth) 가 돌려준 값(기본 setPanelHeight), 영역보다 크면 판을 통째로 줄인다. 바깥을 누르면 닫힌다(setOutsideCloseEnabled 로 창마다 끔). close, setCloseEvent(내려갈 때 알림). 판 모양은 Paint 한 장이고 게임은 상속해 틀(getFrameNode)에 꾸밈을 붙이고 layoutPanel, applyMotion, setCovered, handleWheel, dispose 를 덮어써 바꿔 끼운다. getPanelNode, getPanelPaint, getDimPaint, getPopupMotion
- UIConfirmWindow: 확인 창. 제목, 묻는 글, 취소와 확인 두 단추. 글은 판 너비에서 줄을 바꾸고, 영역 세로를 넘으면 글 칸만 스크롤된다. setRightToLeft(true) 면 단추 차례를 뒤집는다(확인이 왼쪽). 확인은 setConfirmEvent 뒤 닫히고, 취소 단추, 바깥 누르기, closeTopWindow, closeAllWindows 로 닫히면 setCancelEvent. setTitle, setMessage, setButtonTexts. (UIDialog 는 그대로 둔다)
- UIScale.read(viewWidth, viewHeight, options): 뷰 한 단위가 minimumCssScale(0.8) CSS 픽셀보다 작으면 UI 층만 키울 배율. (1 ~ maximumScale 1.8, 낮은 화면은 minimumLayerHeight 아래로 키우지 않음(기본 0 이면 보지 않음), 세로 화면(가로가 세로의 portraitRatio 1.1 배 이하)은 상한 없음, cssPixelScale 을 주지 않으면 ViewManager.getCssPixelScale) UIScale.isPortrait
- GameScene: fadeScreen(onDark). 다 어두워지면 onDark 를 부르고, 그것이 Promise 를 돌려주면 끝날 때까지(실패해도) 어둡게 두었다가 밝힌다. 이미 페이드 중이면 false. setScreenFadeColor(기본 검정), setScreenFadeSeconds(기본 0.35), isScreenFading, getScreenFadeAlpha. 막은 postDraw 에서 세이프에어리어까지 캔버스 전체에 그리고, 배율을 곱하지 않은 시간으로 움직인다. 막이 걸린 동안은 누름과 휠을 받지 않는다
- GameScene: isUserInterfaceAt(viewPosition) (그 자리에 누를 수 있는 노드가 있는지, 감춰져 있던 터치 인식기의 raycast), setPlayInputHandler({ press, move, release, wheel }) (UI 가 받지 않은 누름과 그 누름의 이동과 뗌(취소 포함), UI 밖의 휠을 세이프에어리어 왼쪽 위 기준 게임 영역 좌표로 넘긴다), convertViewToPlayArea. 창 층 안을 가리킨 휠은 UIWindowLayer.scrollWindowAt 으로 넘긴다
- GameScene: setPlayAreaReference(fixedLength, isLandscape). 세이프에어리어를 뺀 게임 영역의 고정 쪽 길이가 늘 fixedLength 가 되게 기준 해상도를 늘린다. (캔버스 길이 : 세이프에어리어를 뺀 길이 = 기준 해상도 길이 : fixedLength, 뷰 배율 방식도 가로 고정 stretchWidthExpandHeight, 세로 고정 stretchHeightExpandWidth 로 둔다, resize 와 initialize 에서 다시 셈)
- ViewManager: setIgnoredSafeAreaSides(sides), getIgnoredSafeAreaSides. getSafeAreaInsets 가 그 쪽을 0 으로 돌려준다. (어느 쪽을 무시할지는 게임이 넘긴다)
- GameScene 의 바뀐 동작: computeSafeAreaRect 가 env(safe-area-inset-*) 를 따로 재던 것을 ViewManager.getSafeAreaInsets 로 읽는다. 지금까지는 setSafeAreaOverride, 주소의 ?safeArea=, (새) setIgnoredSafeAreaSides 가 GameScene 의 세이프에어리어 노드에 닿지 않았다. env 값만 쓰는 게임은 인셋이 정수로 잘리지 않는 것 말고 같다. (computeSafeAreaRect 를 덮어쓴 게임은 그대로)
- 출시 게임들(외계행성 광부, 우주생물, aberrant, 찾았다, 종말 생존)이 따로 만들어 쓰던 글자, 노드 편의, 그리기 기능과 최적화를 엔진 기본으로 넣는다. (게임의 화면 모양과 연출은 가져오지 않았다, 게임 코드는 그대로다)
- Text, UILabel: setFitWidth(width, minimumRatio = 0.55), getFitWidth, getFittedFontSize. 한 줄 글이 맞출 너비를 넘치면 처음 크기에서 최소 비율까지 0.1 단위로 줄여 그린다. 정한 크기(getFontSize)는 그대로이고 글, 글꼴, 굵기, 너비가 바뀌거나 웹 글꼴이 받아지면 다시 맞춘다. 최소 비율로도 넘치면 넘친 채 그린다. 줄을 바꾸는 글과 리치텍스트는 맞추지 않는다
- Text, UILabel: setLetterSpacing(letterSpacing), getLetterSpacing. 글자 묶음마다 뒤에 더하는 간격(픽셀, CSS letter-spacing 과 같은 뜻, 음수는 좁힘, 처음은 0). 글 너비는 글자 묶음 수 x 간격만큼 늘고(마지막 글자 뒤에도 더한다) 줄바꿈, 맞춤 너비, 정렬, 밑줄이 그 너비로 잰다. 글자 묶음마다 앞뒤 짝을 재어 자리를 잡아 짝 커닝은 남고, 크롬 캔버스 letterSpacing 로 잰 너비와 같다. 오른쪽에서 왼쪽으로 쓰는 글과 리치텍스트는 간격을 쓰지 않는다. 러스트 판 set_letter_spacing, get_letter_spacing 과 같다
- Engine.openUrl(url): 바깥 주소를 새 탭으로 연다(window.open(주소, "_blank", "noopener")). 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열리고, 입력과 상관없이(타이머, 프레임) 부르면 브라우저가 막는다. http, https, mailto, tel 만 열고 그 밖의 꼴(javascript:, file: 같은)은 false. 러스트 판 Engine::open_url 은 데스크탑에서 운영체제의 기본 프로그램(맥 open, 윈도우 ShellExecuteW, 리눅스 xdg-open)으로, 웹에서 window.open 으로 연다
- UIView.setBackdropBlur(blurRadius), getBackdropBlur: 뒤 화면 흐림(CSS backdrop-filter: blur(), 언리얼 UMG BackgroundBlur 와 같은 뜻, 처음은 0 으로 꺼짐). 인자는 CSS blur(Npx) 의 N 과 같은 표준편차(노드 좌표 단위, 화면에서는 변환 배율을 곱한 기기 픽셀)다. 켜면 이 뷰가 그려질 때 그보다 먼저 그려진 화면을 이 뷰의 내용 영역만 ScreenEffectType.gaussianBlur(분리형 가우스 가로 세로 두 번, 3 시그마까지, 선형 샘플링으로 탭을 반으로, 모서리는 거울 접기)로 흐리고 그 위에 배경색(반투명)을 얹는다. 크롬 CSS backdrop-filter 와 화소 차이 평균 1 미만(표준편차 3, 8, 20, tests/ui/uibackdropblurcss.test.mjs). 화면에 그릴 때만 되고 켜진 동안은 기하 캐시를 쓰지 않는다. 끄면 화면은 바이트 그대로. 러스트 판 UIView::set_backdrop_blur, get_backdrop_blur 와 같다(두 엔진 화소 같음)
- UIView.setBackdropCornerRadius(cornerRadius), getBackdropCornerRadius: 뒤 화면 흐림과 바탕색의 둥근 모서리(CSS border-radius). 흐림이 켜져 있을 때 흐림 영역과 바탕색이 둥근 사각형 안에만 깔린다. 처음은 0(사각형). 러스트 판 set_backdrop_corner_radius, get_backdrop_corner_radius
- ScreenEffectType.gaussianBlur: 표준편차 가우시안 블러(parameters = [표준편차 픽셀], CSS filter: blur() 와 같은 뜻). 기존 blur 는 그대로. 러스트 판 ScreenEffectType::GaussianBlur
- Engine.readLocalTime(minuteOffset = 0): 지금에서 분 오프셋만큼 더한 때를 이 기계의 시간대로 본 달력 시각 { year, month(1 에서 12), day, hour, minute, second, weekday(0 이 일요일) } 을 돌려준다. 더한 때의 일광 절약 시간까지 반영한다(new Date(Date.now() + 오프셋) 과 같다). 게임이 시계 표시나 로그에 현지 시각이 필요할 때 두 엔진이 같은 이름으로 읽는다. 러스트 판 Engine::read_local_time 은 웹에서 Date, 맥과 리눅스에서 localtime_r, 윈도우에서 SystemTimeToTzSpecificLocalTime 으로 읽는다
- 뼈 행렬 유니폼 블록(유니티 GPU 스키닝의 상수 버퍼, 언리얼의 뼈 버퍼와 같은 길): 뼈 행렬 96 개는 vec4 384 칸이라 WebGL2 가 보장하는 최소 정점 유니폼 한도(MAX_VERTEX_UNIFORM_VECTORS 256 칸)를 넘어, 데스크탑(4096)은 돌아도 안드로이드(갤럭시 Z 폴드3)는 링크에 실패했다. 이제 뼈 행렬은 std140 유니폼 블록 JointBlock(6144 바이트, 최소 보장 MAX_UNIFORM_BLOCK_SIZE 16384 바이트 안)으로 넘긴다. 더한 것: JOINT_BLOCK_GLSL(셰이더에 끼우는 선언), JOINT_BLOCK_MAXIMUM(96), JOINT_BLOCK_NAME, JOINT_BLOCK_BINDING(3), JointBlockBuffer, MORPH_WEIGHT_VECTOR_COUNT(24), SkinnedModelRenderer.uploadJointMatrices. 툰 렌더러, 툰 바깥선, 스키닝 렌더러, 피부 렌더러가 모두 이 길을 쓰고, ShaderProgram 이 링크 뒤에 JointBlock 블록을 같은 자리로 묶는다. 모프 가중치 배열은 float 96 개(96 칸)에서 vec4 24 칸으로 줄였다. 정점 유니폼 칸 수는 tests/graphics3d/uniformlimitchrome.test.mjs 가 엔진이 짓는 프로그램마다 한도(256, 조각 224)를 넘지 않는지 크롬에서 본다. 화면은 그대로다
- Text, UILabel: measureText(text, fontSize) (주지 않으면 지금 글과 정한 크기). 그 글자의 글꼴, 굵게, 기울임으로 잰 너비
- Text.setText, UILabel.setText: 같은 글이면 건너뛴다. (UILabel 은 리치텍스트 모드가 아닐 때, 내재 크기를 다시 셈하게 하지 않는다) Text.setTextColor: 같은 색 문자열이고 가진 색이 그대로면 다시 풀지 않는다
- Text 그리기: 색을 "#rrggbb" 글로 바꿔 Graphic 에 넘기던 것을 Color 로 바로 넘긴다. (프레임마다 글 만들기와 풀기가 없어진다) 8 비트로 떨어지지 않는 색(rgba 의 0.5 알파 등)은 1/255 안쪽으로 다를 수 있다
- Graphic: setTextBakeMotionScaleStep, getTextBakeMotionScaleStep(기본 0.25), setTextBakeScaleMoving, isTextBakeScaleMoving, readNodeTextBakeScaleMoving. 글자 굽기 배율 단계(setTextBakeScaleStep)가 0 일 때, 그리는 노드의 변환 배율이 지난 프레임과 다르면(ButtonMotion, PopupMotion, 트윈, 카메라 확대) 이 단계로 묶은 배율로 굽고, 멈추면 정확한 배율로 다시 굽는다. (확대 움직임 동안 프레임마다 글을 새로 굽지 않는다, 1 에서 1.09 로 커지는 단추가 굽는 수가 프레임 수만큼에서 2 장) 처음 그리는 노드는 움직이지 않는 것으로 본다. 단계가 0 이 아니면(기본) 아무것도 셈하지 않는다. ShadowText, ShadowImage 도 같은 배율을 쓴다
- TransformNode: setLastDrawnMaximumScale, getLastDrawnMaximumScale (Graphic.drawNode 가 쓴다)
- ShadowText, ShadowImage, SoftShade: 같은 모양이면 구운 그림을 열쇠별로 나눠 쓴다. 열쇠마다 쓰는 컴포넌트 수를 세어 쓰는 것은 버리지 않고, 아무도 쓰지 않게 된 것은 128 개까지 남겨 두었다 오래 안 쓴 것부터 버린다. 노드에서 떨어질 때(detach) 놓고, 놓지 않고 수거된 컴포넌트는 FinalizationRegistry 가 놓는다. (sharedbakecache.js 의 acquireSharedBake, releaseSharedBake, readSharedBakeCount) ShadowImage 는 그림마다 번호를 붙여 열쇠로 쓰고 setImage 할 때 새 번호를 붙인다
- WorldNode: setContentSizeXY(width, height), setRect(x, y, width, height) (왼쪽 위가 (x, y) 에 오게 피봇까지 셈해 로컬 위치와 내용 크기를 둔다, 앵커는 로컬 위치 셈에 들지 않아 그대로), convertViewToLocal(viewPosition) (뷰 좌표를 부모 변환까지 거쳐 내용 영역 왼쪽 위 기준 좌표로, contains 와 같은 네 귀퉁이 셈). TransformNode: setLocalPositionXY(x, y), setLocalScaleXY(x, y). XY 함수는 Vector2 를 만들지 않는다
- LanguagePack: isRightToLeft(), mirrorLayoutX(x, width, parentWidth), readLayoutTextAlign(align). 지금 언어가 오른쪽에서 왼쪽으로 쓰면 배치의 가로 자리와 정렬의 왼쪽, 오른쪽을 뒤집는다
- TouchRaycaster.touchWheel: 휠을 그 자리를 덮는 것 가운데 그리는 순서로 가장 앞인 스크롤 칸이 받는다. (칸 안의 글이나 그림처럼 누를 수 없는 것 위에서 굴려도 받는다, 지금까지는 누를 수 있는 노드의 조상만 찾아 칸 안 글 위의 휠이 사라졌다) 가장 앞이 누를 수 있는 노드면 지금처럼 그 노드와 조상의 스크롤 칸이 받는다. 받은 칸이 있으면 true. findWheelScrollView, findScrollViewComponent
- GameScene.touchWheel: 받은 스크롤 칸이 있으면 true 를 돌려준다. 덮어쓴 게임 씬은 super.touchWheel 이 false 일 때만 게임(지도 확대 등)으로 넘기면 창의 스크롤과 겹치지 않는다
- Graphic: drawRing(center, innerRadius, outerRadius, startRadian, endRadian) (setFillColor), drawArc(center, radius, startRadian, endRadian, lineWidth) (setStrokeColor). 조각마다 네모 하나를 겹치지 않게 이어 한 번에 그려 반투명이어도 이음매가 짙어지지 않는다. 조각 수는 drawCircle 처럼 화면에서의 반지름을 따라(한 바퀴 16 ~ 64) 그리는 각도만큼. 각도는 0 이 오른쪽, 시계 방향
- Graphic: drawLineSegments(positionValues, size) (setStrokeColor). 숫자 배열 하나(선분마다 x0, y0, x1, y1)로 선분 여럿을 한 번에 그린다. Vector2 를 만들지 않고, 정점 버퍼가 차면 거기까지 그리고 이어 담는다
- SpriteAtlas: 아틀라스 읽기. load(jsonPath), loadData(data, baseDirectory), readFrame(name) (Frame, 없으면 null), hasFrame, applyFrame(sprite, name), getPageImages, getFrameNames. tools/atlas.cjs 의 JSON 과 { pagePaths, frames: { 이름: [쪽, x, y, 가로, 세로] } } 꼴을 읽는다. 이름은 확장자를 떼고도 찾는다. 여러 아틀라스는 SpriteAtlas.addSearchAtlas 로 넣은 차례로 찾는다(findFrame, applySearchFrame, removeSearchAtlas, clearSearchAtlases)
- Sprite.setFrame(frame): Frame 의 그림과 영역을 함께 건다. (null 이면 그림을 비운다)
- ParticleSystem: isFinished(방출할 것이 더 없고 남은 입자도 없음, 루프가 아니면 duration 이 지나고 버스트를 다 냈을 때), getParticlePositionList(입자 자리 목록, 같은 씨앗 비교와 시험용). 러스트 판과 같은 씨앗이면 같은 입자 자리가 나온다
- HeatHazeEffect: experimental 노드에서 effect 컴포넌트로 옮겼다. (src/effect/heathazeeffect.js, import.js 에서 내보냄) node.addComponent(HeatHazeEffect) 로 붙이고, 붙을 때 노드 내용 크기가 비어 있으면 300 x 300 으로 정한다. getTimer, calculateRowOffset
- ScreenEffect: destroy 가 렌더 대상과 함께 패스 프로그램과 버텍스 어레이도 지운다
- Material.createTexture: 이미지를 곧은 알파, 색 프로필 변환 없이 받는다. (createImageBitmap 의 premultiplyAlpha, colorSpaceConversion 을 "none" 으로) 지금까지 브라우저 기본값으로 알파가 곱해져 알파 0 텍셀 색이 검어지고, OLD FACE 의 머리카락과 수염 카드 가장자리가 어두웠다
- ToonRenderer, SkinnedModelRenderer, HumanSkinRenderer: 그림자를 받지 않을 때 섀도우 유닛에 1x1 비교 깊이 텍스처를 묶는다. (맥 드라이버의 "sampler type (Depth)" 알림과 WebGL 의 샘플러 불일치를 막는다) SkinnedModelRenderer.getEmptyShadowTexture, ToonRenderer.destroy
- ToonVfx: 빛 파티클과 빛 점의 rim(0 은 더하는 빛, 1 은 테로 덮기, 음수는 엷게 덮는 빛무리), 리본과 번개의 번짐 색 glow, setRimColor, 사는 동안 다시 꺾이는 번개 addLightning(life), 화면 섬광 addFlash, 엔진 Shaker 로 셈하는 카메라 흔들림 addShake, readShake, isShaking. getActiveCounts 에 lightningCount, flashCount. draw 가 깊이 함수도 되돌린다. (게임 aberrant 의 효과에서 범용 몫만, 게임 색과 처방은 매개변수로)
- SkinnedModel: 바이트에서 읽기, 해석과 업로드 나누기, createWithoutShaderProgram(포즈 계산만), destroy. 기본 모프 가중치를 glTF 노드 weights 에서 읽는다. Material.createImageDescription, destroy. ShadowMap, FullscreenPass, 화면 공간 효과의 destroy(풀스크린 패스까지 지움). FbxLoader 가 2^53 을 넘는 64 비트 id 를 정확히 읽고 빠진 노드는 건너뛴다
- Camera2D: 회전(setRotation, getRotation, 도, 화면 가운데 축). 그리기 변환, screenToWorld, worldToScreen, panByScreen, fling, zoomAt 이 회전을 따르고, 경계 클램프는 돌아간 뷰를 감싸는 상자(getVisibleHalfExtent)로 잰다. convertScreenDeltaToWorld, begin, end(pushState 와 applyTransform, popState). deprecated/camera.js(옛 experimental/camera.js)의 기능을 모두 덮는다. (Camera.setZoom 의 clamp 인자 버그도 고쳤다)
- Tween: setTarget(node), getTarget, TweenProperty(localPosition, localScale, localRotation, localOpacity, contentSize) 값을 노드에 바로 쓴다, applyTweenProperty, Tween.createNodeTween. 대상이 처음 돈 노드 트리에서 떨어지면 콜백 없이 끝난다. duration 0 이하는 바로 끝. Scene.getTweenCount
- Animator: AnimationState setClip, getClip, AnimationTransition setFrom, setTo, getFrom, getTo(상태 번호), getAnimation, addState, getStates, addTransition, getTransitions
- Indicator: getRadius, getRotation, buildTeethSegments, import.js 에서 내보낸다. Visual.getLocation 의 쓰지 않는 인자를 뺐다. VisualAsset setVisual, getVisual
- UI 갈래: 러스트 vanilla-engine 과 UI 기능 차이를 없앤다. 러스트에만 있던 범용 기능을 넣는다
- UIButton.fireClickEvents(): 누르지 않고 클릭이 난 것처럼 clicked, click 알림을 차례로 부른다. UIHitArea 가 넓힌 자리의 클릭을 넘길 때 이것을 쓴다
- UILineChart.calculatePoints(width, height), UIBarChart.calculateBarRects(width, height): 그리기와 같은 자리의 폴리라인 점과 막대 사각형을 셈한다. draw 가 이것을 쓴다
- UISpinner: calculateDotOpacity(dotIndex), getDotColor, getRotationSpeed, getDotNodes
- UIScrollBar: getAxis, getThumbRect (썸이 꺼져 있으면 null)
- ToastMotion.getPhase(), ToastPhase 를 내보낸다. PopupMotion.isInstantEnabled(). UIImageView.getColor()
- UILabel: getWrapMode, getVisibleCharacterCount. UIInputField: getPlaceholder, getMaxLength, getFontSize, getPadding, getBackgroundColor, getRoundSize, getTextColor, getPlaceholderColor, getCursorColor, getCursorIndex, getSelectionStart, getComposition, isComposing
- UIWindow: setDimColor, setPanelColor (어둠과 판의 Paint 색)
- UIListView: setCreateItemEvent(() => WorldNode) 로 템플릿 대신 항목 노드를 만드는 함수를 받는다. 항목 크기를 정하지 않았으면 처음 만든 항목의 크기를 읽는다. isHorizontal()
- TouchRecognizer: getTouchTarget (드래그를 넘겼으면 스크롤 뷰 노드), isTouching
- GameScene: setSafeAreaInsets({ top, right, bottom, left }) 로 세이프 에어리어 인셋을 CSS 픽셀로 직접 정한다. (null 이면 뷰 매니저의 값, 게임 영역 기준도 이 값을 쓴다) 정적 calculateSafeAreaRect(viewSize, targetResolutionScale, insets). setPlayInputEnabled(true) 로 놀이 입력을 모아 두고 takePlayInputs() 로 { kind, position, wheelDelta } 를 꺼낸다. (처리기와 함께 써도 된다) setLoadingOutsideColor, hasLoadingDrawer, isLoadTouchedToSkip, getDevTools
- UIScene: EngineConfiguration.useDevTools 가 꺼져 있으면 GameScene 처럼 개발자 도구를 만들지 않는다. (지금까지는 늘 만들었다)
- 글자, 글꼴을 러스트 판(vanilla-engine)과 맞췄다:
- 표시 글자 수(Text.setVisibleCharacterCount)와 Typewriter 는 글자 묶음 단위로 센다. (전에는 UTF-16 단위라 이모지와 결합 부호가 쪼개졌다) 여러 줄 글에서 남은 수가 음수로 떨어지면 다음 줄을 통째로 그리던 것을 고쳤다. (0 이 되면 다음 줄부터 그리지 않는다) Typewriter 의 글자 공개 알림은 글자 묶음을 받는다. countGraphemes, sliceGraphemes
- Text.calculateDrawnRect: 줄을 바꾸는 글도 사각형을 안다. (화면 밖 거르기) getMeasuredLineCount
- RichText: 글자 방향을 쓴다. 조각을 이은 글로 문단 방향을 정하고(이 글자의 방향, "inherit" 면 Graphic 의 방향), 오른쪽에서 왼쪽이면 조각을 오른쪽부터 놓는다. 정렬 "start" / "end" 도 그 방향으로 푼다. (전에는 조각에 방향을 쓰지 않았다)
- ShadowText: setItalic, setUnderline, setStrikethrough 와 게터, isBold. 밑줄과 취소선도 그림자와 함께 굽는다. 글 방향에 "auto"(글의 첫 강한 글자로)
- Graphic: detectTextDirection(text) 를 내보낸다. (setTextDirection("auto") 와 같은 셈)
- DynamicFont: buildAtlas 로 글자를 더하면 든 글자를 모두 새 캔버스에 다시 놓는다. (전에는 새 글자만 새 캔버스에 놓아 앞서 구운 글자가 어긋났다) 글자 묶음 단위, rebuildAtlas, measureText. import.js 에서 DynamicFont, GlyphInfo 를 내보낸다
- LanguagePack: setLanguageList(data), setLanguageTexts(code, texts, fallbackTexts) (파일 없이 바로 넣기)
- import.js: splitGraphemes, splitWords, countGraphemes, sliceGraphemes, detectTextDirection
- 비주얼 에디터(tools/visualeditor/visualeditor.html)를 위 엔진으로 다시 빌드했다
- 코어, 플랫폼, 기반 갈래. 러스트 판(vanilla-engine)에만 있던 범용 기능을 들여와 두 엔진의 공개 API 를 맞춘다.
- Color.createFromBytes(red, green, blue, alpha) (0 ~ 255), withAlpha(alpha) (알파만 바꾼 새 색), Color.lerp(from, to, time)
- Math.easeOutQuad(time)
- Matrix4.writeToArray(array), writeToSlice(array, offset): 열 우선 16 칸을 배열(의 offset 자리)에 적는다
- Vector2: addScalar, subtractScalar, multiplyScalar, divideScalar, moduloScalar. Vector3: addScalar, subtractScalar, multiplyScalar, divideScalar. (add(number) 와 같다)
- Rect.intersects(other): 겹치는지. 변이 닿기만 한 것은 겹친 것이 아니다. (overlaps 는 닿기만 해도 겹친 것)
- Cooldown.activate(): use() 와 같다
- TransformMatrix.invert(): 역행렬을 새로 돌려준다. (행렬식이 0 이면 null)
- Platform.applyUserAgent(userAgent): 넘긴 user agent 글로 플랫폼, 브라우저, 모바일 여부를 고른다. (getPlatformInfo 가 브라우저의 글로 부른다)
- Engine: setTitle(title), writeClipboardText(text), readClipboardText() (Promise, 글이 없거나 막히면 null), isCoarsePointer(), loadScene, unloadScene, unloadAllScenes (SceneManager 와 같다), isExitRequested()
- Engine 페이지 이벤트: PageEvent(hidden, visible, blurred, focused, pointerDown), addPageEventListener(listener), removePageEventListener(listener), isPageHidden()
- Engine 검증용 화면 저장: requestFrameCapture(frameNumber) 는 그 프레임을 다 그린 뒤 캔버스를 PNG data URL 로 넘긴다. (Promise, 지난 번호면 이번 프레임) 주소 쿼리 ?capture=120,240 은 그 프레임들을 내려받기로 저장하고, captureName 은 파일 이름("{frame}" 은 번호, 기본 capture_{frame}.png), captureExit=1 은 마지막 저장 뒤 exitApplication 을 부른다
- InputManager: isTouchDown() (누른 프레임부터 뗄 때까지 참, 누른 채 움직이지 않아도 참), isWheelWithCtrl() (마지막 휠을 Ctrl 과 함께 굴렸는지, 터치패드 오므리기), isTouchInput() (마지막 입력이 손가락인지)
- Component.isTickNeeded(): 거짓이면 노드가 그 컴포넌트의 tick 을 부르지 않는다. 기본은 tick 을 다시 정의했는지로 본다. Sprite, Text 는 그리기만 하므로 거짓(하위 클래스가 tick 을 다시 정의하면 참), Paint 처럼 tick 이 없는 컴포넌트도 거짓
- ImageAsset.loadFromBytes(assetPath, bytes), TextAsset.loadFromBytes, JsonAsset.loadFromBytes, BlobAsset.loadFromBytes (assetPath, bytes), AudioAsset.loadFromBytes(bytes), FontAsset.loadFontFromBytes(family, bytes, descriptors): 이미 가진 바이트로 읽는다. (내장 자료나 직접 받은 것, 넘긴 바이트는 바뀌지 않는다)
- SpriteAtlas.getPageCount(), SpriteAtlas.findFrameInOrder(atlasList, name), applyFrameInOrder(atlasList, sprite, name): 찾을 아틀라스 목록을 쓰지 않고 넘긴 아틀라스들에서 차례로 찾는다
- SoundSystem: addSoundAsset(soundId, audioAsset) (메모리에서 지은 소리를 그 id 의 녹음 무리에 덧붙인다, 크기와 간격은 소리 표의 줄을 따른다), getEffectVoiceCount()
- Collision2D.findNearestIndexInRadius(targetList, getPositionHandler, center, radius): findNearestInRadius 의 번호판. (없으면 -1)
- Localization: selectLanguage(candidateList, supported, default) (태그의 뒤 조각부터 떼며 맞추기, detectLanguage 도 이것을 쓴다. "zh-Hant-TW" 가 "zh-hant" 에 맞는다), setLanguageAliases, setRightToLeft, isRightToLeft, mirrorLayoutX, readLayoutTextAlign, isolateText, textNamed(key, values) (LanguagePack.formatText 와 같은 이름 자리 채우기), setTableFromJson(languageCode, tableJson)
- PersistedStore.unsubscribe(subscription): subscribe 가 돌려준 것을 넘겨 해지한다. (돌려받은 해지 함수를 부르는 것과 같다)
- SpriteAnimator.getCurrentFrameIndex(), SpriteAnimator.playOnNode(node, clipName, options) (노드의 애니메이터로 play)
- WebSocketClient: 수신 콜백이 없으면 받은 JSON 을 모아 두고 takeReceivedMessages() 로 꺼낸다. (1024 개까지, 넘치면 오래된 것부터 버린다) 바이너리 메시지도 UTF-8 JSON 이면 받는다. tick() (할 일 없음, 다른 플랫폼과 같은 코드로 쓴다). getReceiveEvent() 가 웹소켓을 돌려주던 것을 고쳐 수신 콜백을 돌려준다
- AudioBus(src/core/audiobus.js, import.js 에서 낸다): AudioManager.createAudioBus(), AudioBus.createAudioPlayer() (그 버스로 트는 플레이어), setVolume, getVolume, mute, unmute, isMuted, isAvailable, getGainNode. 출력에 이은 GainNode 하나이고, 버스로 만든 플레이어는 출력 대신 버스에 잇는다. AudioPlayer 생성자는 둘째 인자로 내보낼 노드(outputNode)를 받는다. (없으면 audioContext.destination) 러스트 판과 같은 꼴이다
- SoundSystem.getMusicBus(), getEffectBus() 는 GainNode 대신 AudioBus 를 돌려준다. (노드는 getGainNode()) 설정 크기는 전처럼 그 GainNode 에 setTargetAtTime 으로 건다. 버스로 만든 플레이어도 설정 크기와 음소거를 따른다
- Platform.getResourceUsage(): 바른 이름을 더했다. 옛 이름 getResouceUsage() 는 같은 것을 부르는 별칭으로 남긴다
- Node.findDescendantByName(name): findChildRecursiveByName 과 같다. Node.destroyChildrenWhere(predicate): 조건에 맞는 직계 자식을 떼어 destroy 하고 그 수를 돌려준다. (러스트 판 find_descendant_by_name, destroy_children_where 와 같은 이름)
- GamepadManager.isButtonJustPressed, isButtonJustReleased: 이번 갱신에 방금 눌리거나 떼어진 버튼인지. (러스트 판과 같다)
- 러스트 판에만 있던 범용 기능:
- DEVTools: setVisible, getActiveTab, setActiveTab, getSelectedNode, setSelectedNode, isNodeExpanded, setNodeExpanded, getPanelRect. (F2 는 setVisible 을 부른다)
- UIDialog.requestDismiss(isConfirmed): 다음 tick 에 닫는다
- UIInputField.getDisplayText() (값의 커서 자리에 조합 글을 끼운 글), requestMenuAction(menuAction) (다음 tick 에 잘라내기 / 복사 / 붙여넣기), UIInputFieldMenuAction (import.js 에서 낸다)
- AmbientOcclusionEffect.buildSampleKernel(), SubsurfaceScatteringEffect.buildKernel(falloffColor, strengthColor): WebGL 없이 커널을 짓는 정적 함수. computeKernel 이 이것을 쓴다
- FbxLoader.parseNodeRecords(arrayBuffer) (머리 확인과 최상위 노드 레코드, parse 의 앞부분), FbxLoader.readVersion(arrayBuffer) (정적, 머리의 판 번호)
- AudioManager.getContextTime() (AudioContext 시계, 없으면 0), AudioAsset.getLoadError() (마지막 읽기 실패의 까닭, 없으면 null), AssetLoader.getInFlightCount() (일꾼이 집어 받는 중인 수). 러스트 판의 get_context_time, get_load_error, get_in_flight_count 와 같은 자리다
- Graphic.setBlendMode: source-over 로 대신 그리던 17 가지를 제대로 그린다. 이제 SpriteBlendMode 26 가지가 모두 된다
- source-out, source-atop, destination-atop, xor 는 W3C Compositing and Blending Level 1 의 포터 더프 계수 그대로 blendFunc 로 건다
- overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity 는 그리기마다 그릴 영역(정점의 경계 상자)만 지금 프레임버퍼에서 blitFramebuffer 로 떠 와 셰이더로 섞는다. 공식은 W3C 그대로(분리 섞기, 비분리 섞기, Cs' = (1 - αb) x Cs + αb x B(Cb, Cs) 뒤 source-over 합성)이고 바탕 알파가 있는 렌더 타겟(RGBA8, RGBA16F)에서도 맞다. darken, lighten 은 blendEquation MIN / MAX 가 반투명에서 W3C 식과 달라 셰이더로 섞는다
- 셰이더 섞기 모드에서는 묶어 그리지 않는다. 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번(M2 Pro, 1280x720 에서 그리기 하나에 0.065 ms 안팎, 대부분 복사가 렌더 패스를 끊는 값)
- 이미지, 도형, 글자, 나인슬라이스, 자르기, 파티클, 바꿔 끼운 셰이더(ShaderSprite) 모두 된다. 파티클은 서로 겹치지 않는 쿼드끼리 모아 한 번 떠 와 그려 Canvas2D 처럼 쿼드마다 앞 쿼드 위에 섞인다. 바꿔 끼운 셰이더는 섞기 함수를 모르므로 덧그림 칸(RGBA16F, 안 되면 RGBA8)에 먼저 그린 뒤 섞어 옮긴다
- 크롬 Canvas2D 와 같은 장면(여러 색 바탕 위에 반투명 그림, 사각형, 다각형)을 26 모드로 견주면 도형 안쪽 차이가 2 단계 안이다. Canvas2D 는 source-in, source-out, destination-in, destination-atop, copy 가 그린 도형 밖도 지우는데 Graphic 은 지금처럼 도형 안만 바꾼다
- 모르는 이름의 경고 글을 "unknown blend mode" 로 바꿨다
- 툰 후처리, 효과, 카메라를 애버런트와 광부 키우기가 엔진 그대로 쓰게 넓힌다. (새 옵션이 기본값이면 지금 화면과 화소까지 같다, 두 엔진 같은 API 와 같은 셰이더 글, 게임의 처방과 색 값은 매개변수로 받는다)
- BloomEffect.setUseFloatColor: 주고받는 판을 RGBA16F 로 지어 1 을 넘는 밝은 값이 잘리지 않게 한다. (기본 RGBA8 그대로)
- ToonPostProcess: 생성 옵션 { sampleCount, useFloatColor, depthBits, useDepthTexture }, isFloatColorSupported(실수 판을 못 쓰는 기기는 RGBA8 판의 LDR 길로, 그때 씬에는 화면 색을 그리고 합성은 톤매핑과 감마 없이 블룸과 색 보정만 건다), setSampleCount, setResolutionScale(3D 판만 출력 크기 x 배율로 그리고 end 의 뷰포트로 키운다, UI 는 기기 화소 그대로), setBloomLevels(단 수, 문턱, 무릎, 0 이면 기본 반 해상도 9 탭), setBloomFloatColor, setBrightness, setLitArea 와 clearLitArea(씬 깊이 텍스처로 화소마다 월드 자리를 되짚어 그 자리에서 수평 거리 안쪽은 밝기 1), getSampleCount, getUseFloatColor, getResolutionScale, getBloomLevelCount. 광부 키우기가 셰이더 안에서 LDR 로 걸던 밝기, 채도, 밝힌 자리를 LDR 길의 후처리로 걸 수 있다. (채도의 밝기 무게는 엔진의 Rec. 709 다, 광부는 Rec. 601)
- 툰 색 공간 규약: 씬 판은 선형이다. (ToonRenderer.setHdrOutput(true), ToonScreenOutline.setHdrOutput(true), ToonVfx 의 색도 선형으로 본다) 애버런트처럼 감마를 건 값 g 를 실수 판에 쓰고 합성에서 g^2.2 로 되돌리던 게임은 옮길 때 값을 선형으로 바꾼다. 색은 c^2.2, 감마 쪽에서 곱하던 밝기 배 k 는 선형 k^2.2 다. (1.37 은 2, 1.6 은 2.81, 2.08 은 5, 밝기 1.6 에 배 1.6 은 7.9) 블룸 문턱 1 과 무릎 0.25, 노출 1, 세기 0.6 은 애버런트가 선형으로 되돌린 뒤 쓰던 값이라 그대로다
- Camera3D.setMatrices(보기, 투영): 게임이 셈한 원 행렬을 그대로 쓴다. (광부 키우기의 기울인 직교처럼) 눈, 보는 곳, 위쪽, 직교인지를 행렬에서 뽑고 projectToView, unprojectToPlane, readViewDepth, ToonRenderer.beginFrameWithCamera 가 그 행렬로 돈다. hasRawMatrices, clearRawMatrices, setPerspective 와 setOrthographic 과 lookAt 은 원 행렬을 버린다
- ToonVfx: emitParticles, addFireball, addShockwave, addDecal, addPlume, addLightning, addFlash 의 options.age(이미 지난 초, 늦게 보인 효과를 그 나이부터, 음수면 그만큼 늦게) 와 options.key(사건 열쇠, 이미 낸 열쇠면 다시 내지 않음, clear 가 잊음, registerEventKey), setLookGain 과 getLookGain(파티클과 빛 점의 꼴마다 밝기 배, 기본 1), setGlintCapacity 와 getGlintCapacity(프레임마다 빛 점 상한, 기본 96), 바닥 자국 꼴 stain(tint 로 덮고 테 둘레가 테 색으로 물듦), sheen(기름 윤), shade(둥글게 엷어지는 그늘) 와 자국 options.flicker(깜빡이는 반주기 초), queueBlobShadow({ x, z, radius, alpha })(발밑 그늘), 불덩이, 충격파, 리본, 번개의 options.rim(몸을 덮고 가장자리를 테 색으로 두르는 꼴의 몫, 밝은 바탕용, 0 이면 지금의 더하는 빛). 흔들림(addShake)은 Shaker 의 지수 감쇠라 늦게 보인 사건이면 세기 x exp(-9 x 나이) 로 넘긴다
- 러스트 판에만 있던 범용 기능을 넣었다. Text.calculateFittedFontSize(), UILabel.calculateFittedFontSize() (그릴 때의 크기를 그 자리에서 잼, 이 판은 Graphic 없이 재므로 getFittedFontSize 와 같은 값), Text.wrapLinesWithoutGraphic(maximumWidth) (지금 글과 글꼴로 나눈 줄 목록, 잴 캔버스가 없으면 null), measureTextWithoutGraphic(fontString, text) (import.js 에서 낸다, measureTextMetrics 와 같음)
- Graphic.readFramebufferPixels() (지금 그린 화면을 { width, height, pixels } 로, 위에서 아래로 놓인 RGBA, 알파 255), getDrawingBufferWidth(), getDrawingBufferHeight() (마지막으로 맞춘 뷰포트), getImageSmoothingQuality()
- ToonRenderer 확장 자리와 빛 모델: 애버런트와 광부 키우기가 게임마다 렌더러를 고치지 않고 엔진 툰 위로 옮겨 올 수 있게 표준 기능을 먼저 갖추고, 표준으로 안 되는 무늬만 셰이더 조각으로 넣는 자리를 둔다. 새 옵션이 기본값이면 지금과 같은 화면이다. (옛 렌더러와 같은 멈춘 장면을 그려 LDR, 셀 3 칸은 화소 차이 0, HDR 실수 판은 최대 3.8e-4 로 확인)
- ToonLightSet(toonlightset.js): 빛 값 한 덩어리. 렌더러가 기본 묶음을 들고 setLight, setSunDirection, setFillLight, setRimLight, setSpecular, setPointLights, setPointLightLimit, setBandCount, setBandRamp, clearBandRamp, setLightModel 이 그것을 고친다. createLightSet, getLightSet, 그리기마다 options.lightSet. 고칠 때마다 판 번호가 올라 바뀔 때만 올린다
- 해 방향의 뜻: 빛이 나아가는 쪽(해에서 면으로, three.js DirectionalLight 와 같음). 받는 몫은 max(dot(N, -sunDirection), 0). 면에서 해 쪽 방향을 쓰던 쪽은 부호를 뒤집어 넘긴다
- 채움 빛 setFillLight(방향, 색): 그림자 없는 둘째 방향광. 림 빛 setRimLight(색, 거듭제곱): pow(1 - max(dot(N, V), 0), power) 를 빛처럼 더한다. 정반사 setSpecular(세기, 지수 기본 48): 해의 블린-퐁, 그림자를 받는다
- 점광 setPointLights([{ position, color 선형, intensity, range, decay, rangeExponent, wrap }]): 8 개까지(TOON_MAXIMUM_POINT_LIGHTS), setPointLightLimit 로 가벼운 길에서 줄인다. 감쇠 = 창 (1 - (d / range)^rangeExponent) 를 막아 제곱 x 1 / max(d^decay, 0.01). 기본 decay 2, rangeExponent 4 는 three.js, 언리얼, 고도 4 의 꼴이고 decay 0, rangeExponent 1 이면 (1 - d / range)^2. 받는 몫은 감싸기 빛 (dot + wrap) / (1 + wrap)
- 띠: setBandCount 는 그대로(해 몫을 n 칸으로 반올림). setBandRamp(문턱, 값, 반 램버트) 는 문턱으로 갈라 칸마다의 값(8 칸까지, TOON_MAXIMUM_BAND_STEPS), 점광 몫에도 건다. 광부 키우기의 반 램버트 4 단은 setBandRamp([0.25, 0.5, 0.75], [0.3725, 0.6471, 0.8627, 1], true)
- 빛 꼴 setLightModel({ isEnergyNormalized }): 바탕색 x 빛을 π 로 나눈다(램버트 BRDF, 빛 세기를 조도로 주는 three.js 물리 빛, glTF 빛과 같은 약속). 그때 정반사는 정규화한 블린-퐁 (지수 + 8) / 8π. 기본 false 는 지금과 같다
- 그리기 꼴(drawMesh, drawMeshInstanced, drawMeshInstanceBuffer, ToonDrawQueue.addMesh): tintAmount(틴트를 곱하지 않고 sRGB 로 섞음), glowScale(꼭짓점 빛남의 배), colorScale(마지막 선형 색의 배), emissiveColor 와 emissiveIntensity, baseColorTexture(바탕색에 곱하고 알파는 불투명도에), emissiveTexture, uvTransform([u 옮김, v 옮김, u 배, v 배]), decalTexture, decalColor, decalEmission, decalUvTransform(바탕색 위에 알파로 덮고 그 색으로 빛남, 묶음 그림의 한 칸), alphaCutoff, blendMode(ToonBlendMode.alpha 기본, premultiplied, additive, alpha 가 아니면 비치는 것), softEdge(pow(|dot(N, V)|, softEdge) 를 불투명도에), isMirrored(주지 않으면 모형 행렬의 행렬식이 음수일 때 스스로 감기를 뒤집음, 보기 행렬이 거울에 비쳤으면 그것도), indexStart, indexCount, outlineIndexStart, outlineIndexCount
- ToonMaterial(toonmaterial.js): createMaterial({ name, uniformChunk, surfaceChunk, lightChunk, vertexChunk }) 를 options.material 로. 표면 조각 applySurface(inout ToonSurface), 빛 조각 applyLight(ToonSurface, inout ToonLighting), 정점 조각 applyVertex(inout ToonVertex, 몸, 바깥선, 그림자 깊이 셋 모두). ToonSurface 에 sRGB 바탕색, 알파, 선형 빛남, 월드 노멀, 꼭짓점 빛남, 빛을 받지 않음, 무늬 넷(vertexDetail), UV, 지역 위치, 월드 위치, 보는 방향이 있다. options.textures({ 유니폼 이름: 텍스처 }, 유닛 7 부터, TOON_MAXIMUM_MATERIAL_TEXTURES 9), options.onBeforeDraw(program, gl, ToonProgramKind). 머티리얼과 인스턴스 꼴마다 프로그램을 짓고 기억한다(짓지 못하면 알리고 그 그리기는 건너뜀). prepareMaterial, deleteMaterial, getSolidProgram(material). readProgramSources(material, instanceLayout) 와 composeToonProgramSources 로 ShaderWarmer 에 넘긴다
- 인스턴스 꼴: createInstanceLayout([{ name, size }]) (instanceMatrix 16, instanceTint 4 는 엔진이 읽고, 그 밖의 사용자 어트리뷰트는 셋까지 자리 13 ~ 15, 정점 조각이 그 이름으로 읽음), createInstanceBuffer(꼴, 수, ToonBufferUsage.static | dynamic) 영구 버퍼, updateInstanceBuffer, deleteInstanceBuffer, drawMeshInstanceBuffer(모형, 버퍼, 수, 꼴). 모형과 버퍼를 묶은 버텍스 어레이는 처음 그릴 때 지어 둔다. 지금의 drawMeshInstanced(매 프레임 거르고 올림)는 그대로다
- 텍스처: createTexture(ImageBitmap, 캔버스, 이미지, ImageData 나 { width, height, data }, { isMipmapped, isRepeated, isFiltered }), deleteTexture. UV (0, 0) 이 그림의 왼쪽 위(glTF 와 같음). 그림자 3, 바탕색 4, 빛남 5, 데칼 6, 머티리얼 7 ~ 15 유닛을 쓰고 주지 않은 칸에는 1x1 흰 텍스처를 묶는다
- 프레임: beginFrameWithMatrices(보기, 투영) (Camera3D 없이, 직교 원 행렬), getFrameCamera, readFrameCamera(보기와 투영에서 눈의 자리, 직교면 보는 방향, 거울 여부), applyFrameState, createReflectionMatrix(평면 위 점, 노멀), readMatrixDeterminant
- 성능: 프로그램마다 프레임 값(보기와 투영, 카메라, 그림자, HDR, 바깥선 색)과 빛 묶음은 바뀔 때만 올리고, 그리기마다 바뀌는 값만 매번 올린다. 텍스처 유닛은 몸 프로그램을 지을 때 한 번 정한다
- 셰이더: 세 정점 셰이더가 같은 머리(자리, 노멀, 색, 재질, 무늬, UV)와 ToonVertex 를 쓰고, 몸 셰이더가 지역 위치, 월드 위치, 무늬 넷, UV 를 조각으로 넘긴다. TOON_ATTRIBUTE_LOCATIONS 에 vertexUv(12). 러스트 판과 셰이더 글이 같다
- ToonDrawQueue: addPass(ToonDrawStage.beforeOpaque | afterOpaque | afterOutline | afterTransparent, callback(renderer, gl)) 단계 콜백(평면 거울, 화면 공간 바깥선 섞기, 효과 자리, 부른 뒤 그리기 상태를 다시 건다), addMesh 꼴의 group 과 isDepthPrepassed(비치는 것을 한 덩어리로 가운데 깊이로 정렬하고, 깊이만 먼저 그린 뒤 같은 깊이에만 색을 칠해 겹친 부품이 두 겹으로 밝지 않음), blendMode 가 alpha 가 아니면 비치는 차례, drawWithMatrices(renderer, 보기, 투영). clear 가 단계 콜백도 비운다
- ToonMesh: 텍스처 좌표 uvData(꼭짓점마다 2, 준 꼭짓점이 없으면 빈 배열, 섞이면 없는 꼭짓점은 0). createBoxGeometry(면마다 0 ~ 1)와 createSphereGeometry(경도와 위도)가 uvs 를 짓고 addPart 가 담는다. addTriangles 의 마지막 선택 인자 uvs, addMaterialRange, combine 이 uvData 와 materialRanges 를 잇는다
- ToonGlb: TEXCOORD_0 을 uvData 로, 프리미티브마다 재질 범위 materialRanges({ name, materialIndex, nodeName, indexStart, indexCount, extras, alphaMode, alphaCutoff, baseColorFactor, emissiveFactor, baseColorImage, emissiveImage, hasUv }) 를 담는다. emissiveTexture 가 있으면 꼭짓점 빛남은 0 으로 두고 재질 범위로 넘긴다. readGlbImages(그림의 name, mimeType, data), decodeGlbImage(ImageBitmap). 부품 안 칸(강조색, 표시판)은 재질 이름이나 extras 로 고르고 indexStart, indexCount 로 그린다
- WorldNode.setPosition: getPosition 의 거꾸로를 더했다. 지금까지는 TransformNode.setPosition 이 부모 pivot 점의 자리(부모 contentSize x 부모 pivot)를 되돌리지 않아, 부모의 내용 크기와 피벗이 0 이 아니면 setPosition 으로 놓은 자리와 getPosition 이 달랐다. (부모 100x60, 피벗 가운데, 90 도, 크기 2 에서 (280, 200) 에 놓으면 (340, 100) 으로 읽혔다) 부모 스케일이 0 인 축은 부모 pivot 점에 놓는다. (러스트 판과 같이 고침)
- multiply 를 렌더 타겟(프레임버퍼를 묶은 동안)에 그릴 때는 그릴 영역 아래를 떠 와 W3C 식(B(Cb, Cs) = Cb x Cs)대로 셰이더로 섞는다. 고정 블렌딩(DST_COLOR, ONE_MINUS_SRC_ALPHA)은 바탕 알파가 1 보다 작으면 cs x (1 - αb) 항이 빠지고 알파가 바탕 알파로 남아, 반투명 바탕 렌더 타겟에서 크롬 Canvas2D 와 최대 221 달랐다. (이제 도형 안쪽 0) 기본 프레임버퍼(alpha: false)는 바탕 알파가 늘 1 이라 지금처럼 고정 블렌딩과 묶어 그리기로 그려 화면과 드로우 콜, 복사 수가 그대로다. 렌더 타겟의 multiply 는 셰이더 섞기 13 가지처럼 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번이 든다. 섞기 셰이더 글에 blendModeIndex 14 를 더했다. (러스트 판과 같이 고침)
- KeyCode.audioplay 의 값 "MediaPlay" 는 W3C KeyboardEvent.code 표(2025-04-22 권고안)에 없는 이름이다. 표의 이름이고 크롬이 흔한 재생/멈춤 키(USB 0x0C00CD, 윈도우 스캔 코드 0xE022)에 내는 "MediaPlayPause" 로 고쳤다. 크롬은 "MediaPlay" 를 리눅스와 크롬OS 의 재생 키(USB 0x0C00B0)에만 낸다. (러스트 판과 같이 고침)
- ToonScreenOutline: 화면 공간 바깥선을 실시간 툰 렌더링의 정석 꼴로 다시 지었다. (게임 하나에 맞춘 꼴이 아니라 엔진의 기준이다)
- 잡기: 선의 판(노멀, 선 번호, 깊이)에서 화소와 바로 이웃 넷 사이의 경계마다 한 번 보고, 선은 그 경계 가운데에 세운다. (Saito, Takahashi 1990 의 G 버퍼 가장자리, 유니티 셰이더 그래프 예제의 이웃 넷 보기) 지금까지는 꺾임 선을 가운데 화소에서 creaseRadius 떨어진 한 점의 노멀로 보아, 꺾임 양쪽이 띠로 서고 반 크기 판을 키우면 점선과 평행한 둘째 선이 서고, 둥근 면의 실루엣 안쪽에 띠가 한 겹 더 섰다
- 깊이: 이웃 두 화소를 보기 공간 자리로 풀어 서로의 접평면에서 떨어진 거리로 가려진 실루엣을 본다. 비스듬히 보는 바닥과 둥근 면의 둘레에 가짜 선이 서지 않는다. (보는 각도에 따라 문턱을 고치는 Roystan 식을 접평면으로 한 꼴) 가린 화소가 가려진 화소의 접평면에서 떨어진 거리를 쓰고(가린 쪽이 둥근 면의 실루엣이면 그 접평면은 시선을 품는다), 문턱에 잰 오차(노멀 8 비트 각 오차 x 두 자리 사이 거리, 꺾임의 화소 한 칸 x 사인, 깊이 24 비트 한 칸)에 여유 배율(setDepthMargin, 기본 2)을 곱해 더한다
- 넓히기: 경계 토막까지의 거리를 점프 플러딩(Rong, Tan 2006)으로 퍼뜨린다. 굵기에 상관없이 걸음은 log2 번이다. (Ben Golus, The Quest for Very Wide Outlines) 바깥 선과 꺾임 선은 따로 퍼뜨려 굵기를 따로 준다. 지금까지의 3 픽셀 반지름 한도가 없어졌다
- 섞기: 그리는 영역의 화소마다 가장 가까운 경계까지의 거리로 clamp(굵기 / 2 - 거리 + 0.5, 0, 1) 만큼 덮는다. 선의 판을 줄여도 거리를 그리는 영역에서 재므로 늘인 선이 끊기지 않는다
- 모형마다: drawMesh, drawMeshInstanced 의 options.hasScreenOutline (false 면 선은 내지 않고 뒤의 선만 가린다), options.hasCreaseLine, options.isMirrored (주지 않으면 행렬식으로 감기를 뒤집는다)
- readJumpFloodSteps(거리): 점프 플러딩 걸음 목록. (큰 것부터 1 까지)
- ToonScreenOutline 번호마다 선 색: setLineColor(lineId, color), removeLineColor(lineId), clearLineColors(), getLineColorCount(). (언리얼 Custom Stencil 꼴, 선의 판에 이미 있는 번호로 색을 고른다) 표는 선 번호 전부를 덮는 128 x 128 찾기 텍스처라 넣는 수에 상한이 없다. 맞닿은 선은 앞쪽 번호의 색이고, 표에 없는 번호는 setColor 의 색 그대로다. 표가 비면 섞기는 지금과 화소가 같다. (광부 키우기 #169 의 바위 강조처럼 고른 모형의 선만 강조 색으로)
- ToonRenderer 인스턴스마다 빛남: drawMeshInstanced 의 인스턴스에 emissiveColor([r, g, b] sRGB)와 emissiveIntensity(선형 배, 기본 1). 그 인스턴스의 명암과 무늬 위에 더해 그 인스턴스만 밝힌다. (틴트는 곱이라 어둡게만 됐다)
- 인스턴스 자료는 그대로 20 수다. 행렬을 아핀 3x4 로 읽고 아래 줄 네 칸(원소 3, 7, 11, 15)에 빛남을 싣는다. (Godot MultiMesh, 유니티 BatchRendererGroup 의 3x4 행렬 꼴) ToonInstanceLayout 의 instanceMatrix 도 같고, 정점 조각에서는 vertex.emissive 다. Matrix4 원소를 그대로 담으면 아래 줄이 0, 0, 0, 1 이라 빛남이 없어 지금 화면 그대로다.
- ToonDrawQueue: setScreenOutline(ToonScreenOutline 이나 null), getScreenOutline(). 맡기면 draw 와 drawWithMatrices 가 몸 앞에 불투명한 것을 선의 판에 그리고(번호는 options.lineId, 주지 않으면 담은 차례 + 1, 인스턴스는 instances[i].lineId 가 먼저), 바깥선 껍데기 뒤 afterOutline 단계 앞에 섞는다. 모형마다 options.hasScreenOutline, options.hasCreaseLine. 비치는 것은 선의 판에 그리지 않는다. 화면 사각형(setScreenRect)이 있으면 그 사각형을 선의 판의 그리는 영역으로 쓴다. 지금까지 afterOutline 단계 콜백에서 drawOutline 을 부르던 코드는 이것으로 바꾸면 된다
- 러스트 판 반사(#[reflect])와 맞추며 원본에서 고친 것
- Visual, UIListView: 생성자가 setComponentType 을 부르지 않아 getComponentType 이 "Component" 였고 UI 문서와 반사 저장에 ComponentType "Component" 로 적혔다. 이제 "Visual", "UIListView" 다
- UIScrollBar: getTrackColor, getThumbColor (트랙과 썸 Paint 의 색, 러스트 판과 같다)
- UIDocument: ShadowImage 를 표에 더했다. Sprite 처럼 imagePath 뒤에 반사 저장 꼴로 쓰고 읽는다. (지금까지는 기본 표에 없어, 에디터처럼 따로 등록하지 않으면 읽을 때 건너뛰었다)
- UIDocument.loadByReflection: 지금 값이 없는(null) 속성도 저장한 꼴로 읽는다. (수 넷 배열은 Color, 수 둘 배열은 Vector2, 수, 글, 불은 그대로) 지금까지는 지금 값이 null 인 속성의 수, 글, 불, 배열 값을 건너뛰었다
- docs/api/0.4.0.json 과 번역 표를 다시 뽑았다
- 툰 셰이딩을 실시간 툰 렌더링의 정석 꼴로 다시 지었다. (유니티 툰 셰이더, 언리얼 Substrate Toon BSDF, 고도의 diffuse_toon, 팀 포트리스 2, 길티기어 Xrd 를 견줘 고른 꼴, 게임 하나에 맞추지 않았다)
- 그늘 램프: 빛을 받는 몫(반 램버트 기본)에 그림자를 곱해 램프에 대어 색을 고른다. 칸마다 자리, 선형 색, 부드러움(Step 과 Feather), 경계는 fwidth 로 계단 없이 막는다. 그림자는 검정이 아니라 그늘 색으로 들어간다
- ToonLightSet.setShade({ step, feather, color, secondStep, secondFeather, secondColor, isHalfLambert }): 바탕, 1 차 그늘, 2 차 그늘. 기본은 반 램버트 0.5 에서 갈리는 두 단계(서늘한 보라 그늘)
- setShadeRamp(자리, 색, 부드러움, 반 램버트): 칸을 바로 (8 칸까지), clearShadeRamp(): 부드러운 램버트
- setRampTexture(텍스처, 반 램버트): 칸 대신 램프 텍스처의 가로를 읽는다. (팀 포트리스 2 의 warp, 원신과 붕괴의 램프 텍스처 꼴)
- setBandCount, setBandRamp 는 그대로 쓰되 같은 램프로 짓는다. (회색 칸, 경계가 계단지지 않는다)
- 빛마다: 해는 램프 색을 통째로 받아 그늘도 해의 색으로 물든다. 채움 빛, 점광, 스포트라이트는 램프의 밝기 단계(바닥 칸 0, 맨 위 칸 1)를 받아 등진 면을 밝히지 않는다. 지금까지 채움 빛은 띠를 거치지 않았다
- 하이라이트: setSpecular(세기, 지수, 부드러움, 색). 블린 퐁을 0.5 에서 가른 단단한 툰 점(부드러움 0, 기본)에서 부드러운 빛(1)까지. 해와 점광, 스포트라이트 모두에 서고 빛을 받는 단계로 가린다. (지금까지는 해만, 부드러운 꼴만, 빛 쪽 가림 없이 그림자만)
- 림 빛: setRimLight(색, 거듭제곱, 부드러움, 해 쪽 가림). 단단한 테에서 부드러운 테까지, 해를 받는 쪽에만 둘 수 있다. 바탕색에 곱하지 않고 더한다. (유니티 툰 셰이더의 Rim Light 와 같다, 지금까지는 빛처럼 바탕색에 곱했다)
- 스포트라이트: 점광에 direction, innerConeAngle, outerConeAngle 을 주면 스포트라이트다. (glTF KHR_lights_punctual 의 각 감쇠)
- 그리기 꼴: receivesShadow (기본 true), shadeOffset (그늘 경계 옮기기), specularScale, rimScale (재질마다 하이라이트와 림 배), matcapTexture, matcapStrength, matcapBlend (ToonMatcapBlend.multiply, add), outlineColor, outlineWidthScale (껍데기 바깥선의 그리기마다 색과 굵기 배)
- 표면 조각(ToonSurface)에 shadeOffset, specularMask, rimMask, 빛 조각(ToonLighting)에 rim, sunLevel 을 더했다. 합치기는 바탕색 x irradiance + specular x specularMask + rim x rimMask + 빛남
- 노멀을 모형 행렬과 본 행렬의 역행렬의 전치로 옮긴다. 늘이고 줄인 모형(크기가 축마다 다른 것)의 빛과 화면 공간 바깥선의 꺾임이 틀렸던 것을 바로잡았다. 정점 조각에서 노멀을 크기의 제곱으로 나눠 맞추던 코드는 빼야 한다
- 기본 빛을 바꿨다. 해 [0.9, 0.85, 0.8] → [0.84, 0.8, 0.74], 하늘 [0.45, 0.5, 0.6] → [0.3, 0.33, 0.42], 땅 [0.2, 0.18, 0.16] → [0.17, 0.16, 0.15]. (빛을 받는 면이 1 을 크게 넘지 않게, 두 단계 그늘과 맞춤)
- 그늘 램프: 빛을 받는 몫(반 램버트 기본)에 그림자를 곱해 램프에 대어 색을 고른다. 칸마다 자리, 선형 색, 부드러움(Step 과 Feather), 경계는 fwidth 로 계단 없이 막는다. 그림자는 검정이 아니라 그늘 색으로 들어간다
- ToonMatcapBlend: 매트캡을 섞는 방식. (multiply, add)
- 툰 폴더(graphics3d/toon)의 모든 파일에 주석과 예제를 채웠다. 공개 API 마다 머리 주석과 JSDoc @param, @returns 설명, 모듈과 클래스와 쓰는 법이 뻔하지 않은 멤버에 @example
제목 (예제는 import.js 이름만 쓰고 헤드리스 크롬에서 오류 없이 도는 것을 확인했다) - 툰을 유니티와 언리얼이 기본으로 갖춘 수준까지 채웠다. (유니티 툰 셰이더 소스의 식을 따랐다)
- ShadowMap: 모형을 지은 뒤에 ShadowMap 을 지으면 깊이 텍스처가 텍스처 유닛에 남아 그리기가 GL INVALID_OPERATION(되먹임 고리)이 되던 것을 고쳤다. 지을 때 앞의 텍스처와 프레임버퍼 묶음을 돌린다. 빛이 거의 바로 아래나 위로 나아가면 광원 행렬이 깨지던 것(위쪽 벡터가 빛과 나란함)을 고쳤다. 그때는 위쪽을 z 축으로 잡는다
- ShadowAtlas, SHADOW_ATLAS_MAXIMUM_LIGHTS(4): 점광과 스포트라이트의 실시간 그림자. 유니티 URP 의 추가 빛 그림자 아틀라스 꼴로 깊이 텍스처 한 장을 칸으로 나눠, 스포트라이트는 원근 한 칸, 점광은 큐브 여섯 면을 칸 여섯에 그린다. updateLights(점광 목록) 이 castsShadow 가 true 인 빛을 골라 칸과 칸마다의 보기와 투영을 셈한다. 툰 셰이더는 그 점광의 빛을 받는 몫에 그림자를 곱해 그늘 램프에 넣는다 (해와 같은 꼴, 3x3 PCF) 받는 자리는 노멀 쪽으로 칸 텍셀 (1 + 3 x (1 - dot(N, L))) 개만큼 밀어 빛에 비스듬한 면의 그림자 여드름을 막는다
- ToonRenderer: setLocalShadows(ShadowAtlas, 세기), beginShadowAtlasPass(아틀라스), setShadowAtlasTile(아틀라스, 칸 번호) (끝은 endShadowPass). ToonDrawQueue.drawLocalShadows(렌더러, 아틀라스)
- 점광: castsShadow (기본 false), shadowNear (기본 0.05, 먼 거리는 range, 0 이면 30)
- 빛 색 쓰기: ToonLightSet.setLightColorUsage({ base, shade, highlight, rim, shadeRim, matcap, angelRing, outline }) (렌더러에도). 색마다 빛 색을 곱할지 고른다. 끄면 바탕, 그늘, 하이라이트는 빛의 휘도만 받고 나머지는 빛을 받지 않는다. (유니티 툰 셰이더의 Is_LightColor_*, 기본 모두 켬) 이제 림, 매트캡, 껍데기 바깥선도 기본으로 해의 색을 곱한다. 지금까지 모습은 setLightColorUsage({ rim: false, matcap: false, outline: false })
- 그늘 쪽 림: ToonLightSet.setShadeRimLight(색, 거듭제곱) (렌더러에도). 해와 등진 쪽에 테를 (테 - 반 램버트) 만큼 더한다. (유니티 툰 셰이더의 Antipodean Rim Light)
- 껍데기 바깥선: setOutlineFadeDistance(가까운 거리, 먼 거리) 로 멀면 굵기가 0 이 된다. (유니티 툰 셰이더의 Nearest, Farthest Distance, 모형의 자리에서 카메라까지) 그리기마다 outlineOffsetZ 로 카메라에서 먼 쪽으로 밀어 몸 앞으로 비치지 않게 한다. (Offset Z)
- 천사 고리: 그리기 꼴 angelRingTexture, angelRingColor (기본 흰색), angelRingOffsetU (기본 0), angelRingOffsetV (기본 0.3), isAngelRingAlpha. u 는 보기 공간 노멀의 x, v 는 2 번 UV 의 y 와 보기 노멀의 y 를 offsetV 로 섞은 것이다. (유니티 툰 셰이더의 Angel Ring, 카메라에 붙은 머리 반사 띠)
- 2 번 UV: MeshBuilder 의 도형 uvs1, addTriangles 의 uvs1, readArrays 의 uv1Data, ToonGlb 가 TEXCOORD_1 을 읽는다. 셰이더의 vertexUv 가 vec4(UV, 2 번 UV)이고 ToonVertex.uv1, ToonSurface.uv1 을 더했다. readUvData 를 내보낸다
- 텍스처 유닛: 점광 그림자 아틀라스가 유닛 0, 천사 고리가 7 을 쓴다. 머티리얼 텍스처는 8 ~ 15 이고 TOON_MAXIMUM_MATERIAL_TEXTURES 가 9 → 8 이 되었다. 유닛 0 은 엔진 2D 가 기억하는 유닛이라 beginFrame 이 그 묶음을 적어 두고 endFrame 이 돌린다
- 셰이더 유니폼: lightColorUsage, lightColorUsageExtra, shadeRimLight, angelRingSettings, angelRingColor, localShadow* , pointLightShadowSlots, 껍데기의 outlineFadeDistance, outlineOffsetZ, outlineLightColor, cameraForward
- 천사 고리: 카메라 기울임만큼 UV 를 되돌려 돌린다. (유니티 툰 셰이더 소스의 Camera Rolling Stabilizer 와 같은 셈, readCameraRoll 을 내보낸다, 셰이더 유니폼 cameraRoll) 카메라를 기울여도 고리가 머리에 붙어 있다
- 빛 세기 막기: ToonLightSet.setLightIntensityLimited(참 거짓), isLightIntensityLimited() (렌더러에도 setLightIntensityLimited). 유니티 툰 셰이더의 Limit Light Intensity 와 같은 셈이고 기본은 유니티 툰 셰이더 기본처럼 켬이다
- 해와 채움 빛은 채널마다 1 로 자르고, 점광과 스포트라이트는 감쇠까지 곱한 색의 세기(0.299 R + 0.587 G + 0.114 B)가 1 을 넘으면 세기로 나눈다. 빛 꼴이 isEnergyNormalized 면 π 로 나눈 뒤의 몫을 막는다
- 1 을 넘는 해나 센 점광을 쓰던 장면은 화면이 바뀐다. (HDR 블룸에 센 빛을 쓰던 것) 지금까지 모습은 setLightIntensityLimited(false)
- 옛 게임 셰이더(빛 세기를 막지 않던 것)를 옮길 때나 세기 1 을 넘는 점광, HDR 블룸을 쓸 때는 setLightIntensityLimited(false)
- 빛 색 쓰기를 끈 색이 받는 세기도 유니티 툰 셰이더와 같은 0.299 R + 0.587 G + 0.114 B 로 바꿨다. 껍데기 바깥선에 곱하는 해의 색은 세기가 1 이상이면 세기로 나눈다 (유니티 툰 셰이더 바깥선)
- 툰 GLB 접근자 읽기: 바이너리 덩어리 밖을 읽는 접근자는 빈 모형이 아니라 오류("GLB 접근자 N 가 바이너리 덩어리 밖을 읽습니다.")를 던지고, bufferView 가 없는 접근자는 glTF 명세대로 0 으로 채운다 (러스트 판과 같다)
- 맨 위 내보내기에 여섯을 더함(러스트와 같게): import.js 가 AudioManager, DevTools, Pane, PaneStyle, PaneTheme, WebSocketClient 를 내보낸다(러스트 판 lib.rs 의 pub use 와 같다). 문서와 예제도 채웠다.
- 툰 몸 셰이더의 읽기 readShadeLevel 이 음영 단 색이 0 개일 때 동적 첨자 shadeStopColors[shadeStopCount - 1] 를 읽던 것을 고리로 바꿈: 아이폰 SE2(A13, iOS 27.2.1) 사파리에서 그 읽기가 있는 툰 프로그램으로 처음 그리면 GPU 프로세스가 죽어 WebGL 문맥을 잃었다(그 뒤 첫 셰이더 짓기가 'compile failed: null' 로 보임). 단이 둘 이상인 화면은 셈이 같아 바이트까지 그대로다. 옮기는 법: 없다.
성능
- 툰 그리기 줄과 GPU 메모리 셈의 CPU 줄임(화면 그대로): ToonRenderer.findDrawEntry 가 꼴 객체의 기억 칸을 WeakMap 에서 한 번만 찾는다(앞서는 있는지와 읽기를 두 번 찾았다). GpuMemoryTracker 는 GL 객체를 지을 때 호출 스택을 글로 풀어 주인 이름을 읽지 않고, 호출 칸만 잡아 두었다가 readUsage 가 주인을 읽을 때 한 번 푼다(재질 블록이나 텍스처를 프레임 중에 새로 지을 때마다 스택 글 만들기가 들었다). ownerList 의 결과는 같다.
- 툰 프로그램 변형 미리 짓기(정석: 유니티 ShaderVariantCollection.WarmUp, 언리얼 PSO 캐시처럼 첫 그리기 전에 지음, 화면 그대로): 몸 기능 변형은 처음 보는 조합을 그리는 첫 프레임에 프로그램을 지어 한 번 끊길 수 있었다(애버런트 아이폰 15 에서 판 시작 직후 250 ms 쯤). ToonRenderer.prewarmDrawQueue(queue) 를 더했다. 그리기 줄에 담긴 것이 그릴 때 쓸 변형(머티리얼, 인스턴스 꼴, 몸 기능 비트, 모서리 어둠 몸, 바깥선, 그림자 깊이)을 그리지 않고 같은 열쇠로 미리 짓는다. KHR_parallel_shader_compile 이 있으면 컴파일만 맡기고 프레임마다 끝난 것을 나눠 끝내 주 스레드를 막지 않으며, 없으면 호출 안에서 짓는다. 돌려주는 ToonProgramPrewarm 의 isReady(), wait()(Promise)로 끝을 안다. 끝나기 전에 그려도 되고 아직 안 지어진 변형은 지금처럼 그 자리에서 짓는다. ShaderProgram 은 생성자 끝 매개변수 isDeferred 와 isBuildComplete(), finishBuild(), 정적 isParallelCompileSupported(gl) 를 더했다(기본 동작 그대로). 맥 헤드리스 크롬에서 변형 셋과 인스턴스 꼴 하나를 담은 장면의 첫 그리기 프레임: 미리 짓기 없이 61 ms(compileShader 20 번, linkProgram 10 번), 미리 짓기 뒤 0.5 ms(0 번), 화면은 바이트까지 같다. (tests/graphics3d/toonprogramprewarmchrome.test.mjs)
- 툰 몸 변형: 장면 중간에 처음 나타나는 조합(빛 묶음에 림, 음영 림, 램프 텍스처 같은 것이 켜져 몸 기능 비트가 바뀌는 때)이 그 프레임을 막던 것을 줄였다(이슈 #2). 몸 기능 비트가 바뀌는 길은 빛 묶음 쪽 다섯(램프 텍스처, 음영 단, 림, 음영 림, 빛 세기 제한)과 그리기 꼴 쪽 여섯(텍스처 다섯, 그림자 받기)이다. (가) prewarmDrawQueue(queue, options) 에 선택 인자 options 를 더했다. options.lightFeatureList(조합마다 더 켜질 빛 기능 이름의 배열, 예 [["rim"], ["rim", "shadeRim"]]), options.lightSetList(앞으로 쓸 빛 묶음), options.queueList(나중에 나올 재질과 인스턴스 꼴을 담은 그리기 줄)로 게임이 쓸 조합 목록을 주면(유니티 ShaderVariantCollection 처럼) 그 조합을 미리 짓는다. (나) ToonRenderer.setAsyncProgramBuild(isAsync), isAsyncProgramBuild() 를 더했다(기본 true). KHR_parallel_shader_compile 이 있으면 장면 중간에 처음 보는 몸 변형은 컴파일만 맡기고, 다 지어질 때까지 전부 켠 기본 몸 프로그램으로 그려 프레임을 막지 않는다(기본 몸이 같은 화면을 내는 것은 시험으로 확인, 바이트까지 같음). 확장이 없으면 예전처럼 그 자리에서 짓는다. 맥 헤드리스 크롬, 빛이 네 번 바뀌는 장면의 프레임별 그리기 시간: 그 자리에서 짓기 7.6, 7.5, 9.7, 9.8 ms, 조합 목록으로 미리 짓기 0.1, 0, 0, 0 ms(짓기 0 번), 맡기고 기본 몸으로 그리기 0.3, 0.2, 0.1, 0.1 ms. (tests/graphics3d/toonprogramprewarmchrome.test.mjs)
- 툰 몸 셰이더의 점광 고리를 반지름 밖에서 건너뜀: 점광 반지름 밖(lightRange > 0 이고 rangeExponent > 0 이고 lightDistance >= lightRange)은 감쇠 창이 정확히 0 이라 기여가 0 인데도, 몸 셰이더가 그 화소에서 pow 둘, 그림자 읽기, 칸 읽기까지 끝까지 셈했다. 이제 도함수(fwidth)는 갈래 밖에서 모든 화소가 함께 셈하고(갈래 안 도함수는 쿼드 이웃이 건너뛰면 정해지지 않는다), 반지름 밖이면 도함수 없는 무거운 셈(감쇠, 칸 읽기, 색 한계)을 건너뛴다. 점광 그림자 읽기는 칸 값에 들어가 갈래 밖에서 읽는다. 건너뛴 화소의 원래 기여는 감쇠가 0 이라 readLimitedLocalColor(0) 과 readLightColor(0) 이 0 이고 칸 값은 모두 clamp 된 유한한 수라 화면은 바이트까지 같다. 광부(아이패드 미니 6, 등불 하나 range 2.6)가 갈라 점광 하나가 프레임 약 4 ms 를 쓰는 것을 찾았다.
- 툰 그리기의 activeTexture 줄이기: ToonRenderer 가 그리기마다 고른 텍스처 유닛을 0 으로 되돌려, 다음 그리기가 바탕색(유닛 4)만 바꿔도 activeTexture(4) 와 activeTexture(0) 을 다시 불렀다. 이제 그리기는 유닛을 되돌리지 않고(단계 콜백과 몸 그리기의 onBeforeDraw 에는 지금처럼 유닛 0 을 고른 채 넘기고, endFrame 이 앞서 고른 유닛을 돌린다), 상태 적어 두기는 이미 유닛 0 이면 유닛을 고르지 않으며, 돌리기는 상태 캐시가 같다고 기억하는 유닛 0 의 묶음과 고른 유닛을 다시 걸지 않는다. 프레임당 activeTexture(헤드리스 크롬, 1280x720) 판의 방 꼴(room, roommove, roomitem) 49 → 24, 로비 꼴 132 → 28, bindTexture 는 31 → 30, 73 → 72, 화면은 바이트까지 같다. 남은 판의 방 24 가운데 열일곱 남짓은 ToonScreenOutline 의 선의 판과 선 그리기다. 크롬 시험(tests/graphics3d/toontextureunitchrome.test.mjs)이 바탕색 텍스처가 그리기마다 바뀌는 프레임의 activeTexture 가 열둘 이하인지(고치기 전 26, 고친 뒤 11), 콜백이 유닛 0 을 고른 채 불리는지, 프레임 뒤 고른 유닛과 유닛 0 의 텍스처가 돌아오는지 본다.
- 툰 그리기 줄 남겨 두는 항목과 프레임마다 할당 없애기(유니티 MeshRenderer, 언리얼 프리미티브 컴포넌트, 프레임 루프 안 할당 없음): ToonDrawItem 과 ToonDrawQueue.createItem, addItem 을 더했다. 모형, 모형 행렬(복사해 쥠), 꼴을 한 번 짓고 쥐어 두면 그리기 줄이 꼴 객체를 프레임마다 견주거나 풀지 않고, 꼴을 바꿀 때만 setOption, setOptions, markDirty 로 표시한다. 바뀐 것이 없는 항목은 그림자 캐시(onChange)도 견주지 않는다. addMesh 로 프레임마다 새 꼴 객체를 넘기는 지금 꼴도 꼴 객체마다 기억 칸을 짓지 않고 담은 칸이 쥔 기억 칸의 얕은 사본과 견주어 값이 같으면 그대로 쓴다(같은 꼴 객체가 같은 칸에 다시 오면 꼴 객체마다 기억한다). 그리기 줄의 목록은 길이를 0 으로 줄이지 않고 칸에 써 길이만 맞추고(V8 은 length = 0 에서 칸을 놓아 프레임마다 다시 잡는다), 선의 판 묶음, 비치는 덩어리, 빛 열쇠, 그림자 드리우개 목록과 콜백, 인스턴스 버퍼의 경계 구와 단위 행렬, 묶음 올림의 subarray 를 다시 쓰는 칸으로 바꿨다. 행렬식(readMatrixDeterminant)은 배열을 짓지 않고, Math.hypot(V8 이 부를 때마다 인자 배열을 짓는다)은 같은 셈과 차례의 readHypot 으로 바꿨다(노드 25 에서 5 백만 쌍 비트 같음). Matrix4 의 multiply, translate, rotateX/Y/Z, scale 은 결과 칸을 다시 쓴다. writeInstanceBufferSphere(경계 구를 주어진 배열에), TransformNode 의 readPosition, readScale, readLocalPosition, readLocalScale 과 WorldNode 의 readPosition, readContentSize, readPivot(주어진 벡터에, get 함수는 그대로)을 더했고 UINode 의 변환은 지역 크기를 복제하지 않는다. WorldNode.contains(UIButton 이 프레임마다 마우스 올림을 묻는 길)는 getWorldCorners 와 같은 셈을 다시 쓰는 칸에 해 벡터, 배열, OBB 를 짓지 않는다(무작위 나무 1800 마디, 판정 36000 번 비트와 결과 같음). 설정 창 꼴 스크롤 목록(tests/ui/scrolllistbench.mjs, 멈춘 구간)의 엔진 프레임당 할당 457 → 75 KB, 광부 설정 창 꼴 388 → 59 KB. 패드가 하나도 붙지 않았으면 navigator.getGamepads 를 프레임마다 부르지 않고 1 초마다 한 번 훑는다(붙는 것은 gamepadconnected 사건, 사건을 놓친 패드는 훑기가 붙인다). 화면 공간 바깥선의 선 색 표는 같은 색을 다시 걸거나 비우고 같은 색을 다시 걸면 텍스처를 다시 올리지 않는다. 엔진 그리기 줄 프레임당 할당(헤드리스 크롬, 맥미니, 960x540, CDP HeapProfiler 표본): 판의 방 꼴(부품 많은 모형 서른여섯, 그리기 216, 꼴을 프레임마다 새로 지음) 309 → 43 KB, 같은 방을 ToonDrawItem 으로 312 → 43 KB, 로비 꼴 236 → 55 KB, 광부 mid 꼴 78 → 31 KB. 엔진 JS 자체 시간(CDP Profiler, ms/프레임) 판의 방 0.515 → 0.287, ToonDrawItem 0.508 → 0.248, 로비 0.498 → 0.461, 광부 0.114 → 0.064, 가비지 컬렉터 판의 방 0.047 → 0.008. 네 장면 모두 GL 호출 수와 화면 바이트가 같다. (tests/graphics3d/toondrawitemchrome.test.mjs, toondrawbench.mjs 의 room, roomitem, 할당 표본)
- 툰 화면 바깥선 해상도 몫(setResolutionScale, 기본 1, 유니티 URP renderScale, 언리얼 화면 비율과 같은 뜻): 이름대로 섞기 앞의 모든 판(선의 판, 가면, 씨앗, 넓히기 판)을 그리는 영역 x 몫으로 줄인다. 이전에는 넓히기 판만 줄였다. 기본 1 은 화면이 바이트까지 그대로다. 몫이 1 보다 작으면 가는 선(굵기 x 몫이 약 3.24 선의 판 픽셀 이하)은 가면과 같은 해상도에서 덮는 몫(진하기와 번호 색을 곱한 RGBA8 판, getLineTarget().coverageTexture)을 한 번 셈하고 마지막 섞기가 그것을 쌍선형으로 한 번만 읽는다(읽기 아홉에서 하나). 굵은 선은 선의 판 해상도에서 점프 플러딩을 하고 섞을 때 거리를 그리는 영역 픽셀로 곱해 잰다. 선 굵기(setWidth)는 어느 몫이든 그리는 영역 픽셀이다. getLineTarget 의 lineTexture, depthTexture 의 해상도는 그리는 영역 x 몫이 된다(lineTexture 의 약속, RGBA8 에 b 와 a 아래 6 비트가 번호, a 위 2 비트가 깃발, 굵기 0 이면 선의 판만 그리는 것은 그대로). outlinePath 에 "thinScaled" 가 더해지고 readProgramSources 는 아홉을 돌려준다. CSS 화소당 1.5 화소로 맞추려면 setResolutionScale(1.5 / (그리는 버퍼 화소 / CSS 화소)) 로 준다(캔버스 width / clientWidth, 엔진 해상도 설정이 버퍼를 묶으면 devicePixelRatio 와 다르다). 아이폰 SE2 광부 값(굵기 2.62, 알파 0.65, 750x990)에서 몫 1, 0.75, 0.5 의 바깥선 값이 17, 12.5, 8 ms 다(같은 프레임을 연달아 그리고 읽어 센 값).
- 묶어 그리기 이름을 러스트 판과 같게: Graphic.setSpriteBatchingEnabled, isSpriteBatchingEnabled, flushSpriteBatch 를 setBatchingEnabled, isBatchingEnabled, flushBatch 로 바꿨다(러스트 판 set_batching_enabled, is_batching_enabled, flush_batch). 묶음에는 그림만이 아니라 도형, 글자, 정점 색 쿼드도 들어 '스프라이트' 가 뜻을 좁혔다. flushSpriteBatch 는 걷었다.
- 엔진 루프 밖 그리기(2D 캔버스와 같은 약속): 묶어 그리기가 켜진 Graphic 에 엔진 루프 밖에서 그린 것(엔진 없이 만든 Graphic, 제 requestAnimationFrame, 입력 처리기)도 그 작업이 끝날 때(마이크로태스크) 남은 묶음을 엔진이 그린다. 브라우저가 캔버스를 화면에 내기 전이라 따로 내보내지 않아도 보인다. 지금까지는 엔진 프레임 끝에만 내보내, 엔진 루프 없이 Graphic 을 쓰는 예제 neonhorizon 의 OPTIONS 패널이 안 그려졌다(0.3.2 는 그려짐). 엔진 프레임 안에서는 프레임 끝에 엔진이 먼저 그려 하는 일이 없다.
- 글 재기 한 번으로: 글리프 배치가 배율 1 의 왼쪽에서 오른쪽 글을 통째로 잴 때 글 재기 캐시를 거친다. Text 가 화면 밖 거르기의 그린 자리를 재며 같은 글꼴 글과 글로 이미 잰 것을 다시 재지 않는다. 프레임마다 바뀌는 시각 글이 있는 timelineshowcase 의 measureText 가 프레임당 2.85 → 1.75 번. (남은 것은 처음 보는 글자 짝을 재는 것으로 캐시에 남는다, 0.3.2 는 1.05 번)
- Graphic 만들기 빠르게: 글리프 배치의 글자 덩어리 나누개(Intl.Segmenter)를 Graphic 을 만들 때가 아니라 아스키 밖 글을 처음 나눌 때 하나 만들어 나눠 쓴다. 인쇄할 수 있는 아스키 글은 글자 하나가 덩어리 하나라(UAX #29) 나누개 없이 나눈다. 크롬은 Intl.Segmenter 를 처음 만들 때 5 ms 쯤 든다. new Graphic(canvas) 14.3 → 8.3 ms(헤드리스 크롬, 8 번 가운데 값, 0.3.2 는 5.6 ms).
- 판 끝 첨부 버리기(invalidateFramebuffer)를 쓰지 않고, 판을 통째로 덮어쓰는 패스 앞은 판 비우기(clearBufferfv)로: 실기기 사파리(아이폰 SE2, 아이패드 미니 6)에서 자리마다 켜고 끄며 재니 이득이 재어지는 자리가 없었고 프레임마다 수 ~ 수십 ms 가 붙었다(툰 후처리와 블룸, 모서리 어둠 장면의 프레임: SE2 51 ms 가 끄면 11 ms, 멀티샘플 판과 다단 블룸은 41 ms 가 14 ms, 아이패드 90 ms 가 25 ms, 맥 크롬은 차이 없음). RenderTarget.resolve() 는 푼 뒤 첨부를 버리지 않고(resolve(isAttachmentKept) 의 인자는 더는 쓰지 않으며 남겨 둔다), 투명도 층(beginOpacityLayer)이 끝날 때도 층의 깊이와 스텐실을 버리지 않는다. 블룸의 밝은 몫 뽑기와 흐림, 다단 블룸의 뽑기와 줄이기, 모서리 어둠의 네 패스는 앞에 판을 비운다(비운 것이 안 부른 것과 같음을 SE2 에서 확인). 화면 결과는 그대로다.
- 글자 그리기를 글리프 아틀라스로(스키아 글리프 캐시, 유니티 TextMeshPro 동적 아틀라스, 언리얼 폰트 캐시와 같은 꼴): 문자열마다 캔버스에 통째로 구워 텍스처 한 장씩 올리던 것을, 글꼴(모드, 글꼴 글, 굽는 배율, 선 굵기)마다 글자 덩어리를 아틀라스(1024 x 1024 장, 가장 나중에 연 장에 이어 놓고 차면 새 장, 8 장까지, 넘으면 가장 오래 안 쓴 장을 비운다)에 한 번만 굽고 문자열은 글리프 사각형으로 묶음에 넣어 그리도록 바꿨다. 새 문자열은 처음 보는 글리프만 굽고, 같은 장의 글자는 드로 콜 하나로 묶인다. 결과 화소는 크롬이 문자열을 fillText 로 통째로 그린 것과 같다: 크롬(스키아)이 글리프를 가로 서브픽셀 4 칸(반올림 1/8)으로 따로 래스터해 정수 자리에 겹쳐 찍으므로, (글자 덩어리, 1/8 자리 칸) 열쇠로 굽고 measureText 로 잰 자리(앞 덩어리와 붙인 너비 - 이 덩어리 너비, 커닝 포함)에 놓는다. 합자, 이어진 꼴이 생길 수 있는 라틴, 키릴 같은 글자는 낱말째, 오른쪽에서 왼쪽 글(아랍어, 히브리어)과 256px 넘는 글꼴은 문자열째 굽는다. 헤드리스 크롬(맥, 한글, 영어, 숫자, 섞인 글, 이모지, 합자, 아랍어, 태국어, 데바나가리, 키릴, 여러 크기와 굵기, 바깥선, 기기 픽셀 배율 1 과 2)에서 예전과 다른 화소는 1:1(setTextBakeScaleStep(0), setTextPixelSnapEnabled(true)) 배율 1 에 6 개(최대 4 단계), 배율 2 에 2 개(1 단계)로, 글리프 잉크가 겹치는 화소의 8 비트 겹치기 반올림이다. 소수 자리에 놓이거나 늘려 그린 글은 이웃 글리프 잉크가 한 텍셀 안에 붙은 화소에서 선형 거르기가 글리프마다 따로 걸려 최대 10 단계 다를 수 있다(배율 1 의 기본 설정에서 57 개). 칸의 위아래 한 줄은 문자열 사각형의 가장자리 줄을 되풀이해, 세로 소수 자리에서 줄 높이를 넘는 잉크(아랍어 같은)가 문자열 사각형 끝에 걸릴 때 선형 거르기가 아틀라스의 다른 줄을 뽑던 것(9 화소, 최대 15 단계)을 없앴고, 공백 덩어리는 굽지 않는다. 글자 50 줄 화면의 드로 콜 100 이 1, 아는 글자로 된 새 문자열 300 개의 굽기(텍스처 올리기) 300 번이 0 번이 된다. TextStringTextureCache.getEntry 가 주는 엔트리는 texture 대신 glyphTextures, glyphRects(글리프마다 왼, 위, 오른, 아래, u0, v0, u1, v1)를 담고, readAtlasStatistics() 로 장 수, 글리프 수, 올린 수를 본다.
- 2D 묶어 그리기가 덜 끊긴다(화면 결과는 그대로): (1) 축에 맞고 화소 경계에 놓인 각진 자르기(beginClipRect, Mask, UIScrollView)는 스텐실 대신 정점에 실은 자르기 사각형 표 번호로 묶음 셰이더가 화소 가운데 기준으로 버려(유니티 RectMask2D, UI Toolkit 꼴) 자르기를 걸고 풀어도 묶음이 이어진다. 돌아갔거나 둥근 자르기, 멀티샘플 화면에서 경계가 화소 경계에 놓이지 않은 자르기는 지금처럼 스텐실이다(멀티샘플 스텐실은 경계 화소를 반쯤 칠해 화소 가운데 기준과 갈리기 때문). 묶지 않는 그리기(바꿔 끼운 셰이더, 셰이더 섞기, 셰이더 섞기 파티클)는 같은 사각형을 가위로 걸고, runExternalPass 는 그동안 셰이더 자르기를 스텐실에 적어 둔다. (2) 한 묶음에 텍스처를 여러 장(기기 MAX_TEXTURE_IMAGE_UNITS 와 16 가운데 작은 것) 묶어 이미지, 도형(흰 텍스처), 글자 텍스처가 번갈아도 이어진다(PixiJS 꼴). (3) drawColoredQuads(파티클, 아지랑이)도 고정 블렌딩이면 같은 묶음에 들어가 파티클 셰이더와 같은 식으로 셈한다. (4) 화면 밖 거르기가 걸린 자르기의 경계 상자도 봐 스크롤 칸 밖 줄의 컴포넌트를 그리지 않는다(유니티 RectMask2D, 옵션 없이 저절로). UIView(배경만 그리는 것), UIButton, UIProgressView 가 러스트 판처럼 isDrawnInsideContent 를 알려 그 노드도 거른다. 누름 판정은 이미 Mask 밖 자손을 건너뛰고 있었다. 묶음 정점 상한은 러스트 판과 같은 6 x 8192 다. 잰 값(헤드리스 크롬, 화소 비율 1.5, 바꾸기 전과 화소가 모두 같음): 설정 창 같은 장면(창 하나, UIScrollView, 줄 50 개, 줄마다 글자와 단추와 도형) 드로 콜 128 에서 1, 스크롤한 것 132 에서 1, examples/uigallery 61 에서 2, devtoolsshowcase 95 에서 4, particleeffects 72 에서 8, effectgallery 229 에서 150. 새 시험 tests/core/batchclipchrome.test.mjs(셰이더 자르기와 스텐실 자르기가 화소까지 같고 드로 콜이 적은지, 스크롤 칸 밖 줄을 거르는지)
- UI 기하 캐시(기본 켜짐, 화면 결과는 그대로): 노드가 컴포넌트를 Graphic.drawComponent 로 그려, Component.writeGeometryKey 로 그리기 입력을 알리는 컴포넌트(Paint, UIView, UILabel 의 Text, UIImageView 의 Sprite)는 그린 정점을 컴포넌트마다 캐시해 둔다. 입력(GeometryKey 에 적은 색의 칸, 크기, 글, 그림 등)과 배율, 회전, 섞기, 틴트가 그대로면 draw 를 부르지 않고, 이동과 투명도도 같으면 떠 둔 디바이스 정점을 묶음에 그대로 옮기고, 이동이나 투명도만 바뀌면(스크롤, 창 옮기기, 페이드) 캐시한 지역 정점에 새 행렬과 투명도만 다시 건다(유니티 UGUI 가 Graphic 의 메시를 지역 좌표로 두고 바뀐 것만 다시 짓는 꼴, 글은 픽셀 스냅까지 같게 셈). 바뀜은 세터의 더러움 표시가 아니라 입력 견주기로 알아채 받은 Color 를 바로 고쳐도 다시 셈한다. 그리기 안에서 자르기, 층, 섞기 바꾸기 등 묶음 밖의 일을 하는 컴포넌트와 draw 를 덮어쓴 하위 클래스는 지금처럼 프레임마다 그린다. Graphic.setGeometryCachingEnabled 로 끌 수 있고 getLastFrameGeometryCacheHitCount, getLastFrameGeometryRebuildCount 로 센다. 남긴 묶음: 묶음은 프레임 안 그리기 차례마다(32 차례까지) GPU 버퍼에 남겨 두고, 묶음에 넣은 정점을 차례대로 조각(기하 캐시 조각과 그 판, 캐시 없이 바로 쓴 구간의 정점 수)으로 적는다. 다음 프레임 같은 차례에서 같은 자리의 같은 조각은 정점을 옮기지도 올리지도 않고(바로 쓴 구간은 판이 없어 지난 프레임 같은 자리의 구간과 정점 값을 견준다), 바뀐 조각과 값이 바뀐 바로 쓴 구간, 앞 조각의 정점 수가 달라 밀린 뒤쪽만 bufferSubData 로 고쳐 올린다(사이가 정점 256 개 이하인 범위는 합치고 묶음마다 네 번까지, 넘으면 첫 범위부터 끝 범위까지 한 번). 모두 같으면 드로 콜만 낸다(유니티 UGUI Canvas 가 바뀐 것이 없으면 지난 묶음 메시를 그대로 그리고 바뀐 그래픽만 다시 짓는 꼴, 그리는 차례, 자르기 칸, 텍스처 칸, 섞기는 그대로라 화소가 같다). 처음이거나 정점이 늘었거나 모두 바뀌었으면 bufferData 로 새 저장소를 잡으며 모두 올린다. 맥과 iOS 의 ANGLE(메탈)은 GPU 가 아직 쓰는 버퍼를 bufferSubData 로 고치면 CPU 를 세우지 않고 새 버퍼에 고친 범위를 쓰고 나머지는 GPU 복사로 옮긴다(ANGLE BufferMtl::setSubDataImpl, putDataInNewBufferAndStartUsingNewBuffer). 예전에는 바깥선(Outline) 같은 캐시 없는 그리기가 하나만 끼어도 그 묶음 전체를 프레임마다 bufferData 로 다시 올렸다(줄 14 개에 바깥선 14 개를 단 멈춘 UI 시험 장면에서 프레임마다 227 KB, 이제 0, 줄 하나의 글만 프레임마다 바꾸면 3.7 KB, 아이콘 하나만 옮기면 1.7 KB 를 bufferSubData 한 번으로 올리고 화면은 바이트까지 같다). Graphic.getLastFrameRetainedBatchCount 로 센다(하나도 올리지 않은 묶음 수, 캐시를 꺼도 바로 쓴 정점이 지난 프레임과 같으면 센다). 2D 묶음 배열은 처음에 사각형 512 개(172 KB)로 짓고 모자라면 한도(사각형 8192 개)까지 두 배씩 늘리며, 프레임 끝 묶음 버퍼는 저장소를 미리 잡지 않는다(예전에는 처음부터 한도로 CPU 배열 2,688 KB 와 GPU 버퍼 2,688 KB 를 잡았다). 이동만 바뀐 그림 명령은 행렬 곱 앞부분을 Float64 로 떠 두고 이동만 더한다(셈 차례가 같아 비트까지 같다). 잰 값(헤드리스 크롬, 한 페이지에서 10 프레임마다 켬과 끔을 번갈아, 장면 트리 그리기와 프레임 끝 묶음 그리기의 CPU 시간 가운데 값, 괄호는 10 프레임 묶음 짝의 켬/끔 비 가운데 값): 보이는 칸 240 개(둥근 바탕과 글) 멈춤 0.930 에서 0.565 ms(0.56), 설정 창 같은 장면 멈춤 0.270 에서 0.215 ms(0.81), examples/uigallery 0.255 에서 0.230 ms(0.87), 자르기 장면(batchclip) 0.185 에서 0.170 ms(0.85), 설정 창 스크롤 중 0.275 에서 0.335 ms(0.94, 여러 번 잰 비 0.94 에서 1.02), 칸 240 개 옮기는 중 1.110 에서 1.335 ms(비 0.73 에서 1.20, 앞 판도 0.72 에서 1.42 로 흔들려 기계가 바쁜 동안은 가리지 못함). 새 시험 tests/ui/uigeometrycachechrome.test.mjs(캐시 켬과 끔이 멈춤, 스크롤, 위치, 색, 글, 보임, 투명도, 배율, 회전을 바꾼 때 화소까지 같고, 멈춘 프레임과 스크롤 프레임에 다시 셈하는 것이 없는지)
- 화면 밖 하위 트리 거르기(기본 켜짐, 화면 결과는 그대로): 노드마다 하위 트리 그리기 경계(자기 그림과 켜지고 보이는 자식들 경계의 합, 노드 내용 좌표)를 바뀐 때만 다시 셈해 두고, drawNode 가 노드에 변환을 건 뒤 그 경계가 화면과 걸린 자르기 밖이면 그 노드와 자손의 그리기 순회를 통째로 건너뛴다. 갱신(tick)은 그대로 돈다. 변환, 내용 크기, 피봇, 자식 더함과 뺌, 켜짐, 보임, 컴포넌트 더함과 뺌과 켜고 끔, 글(Text)의 글과 글꼴처럼 그리는 사각형을 바꾸는 값이 바뀌면 더러움 표시가 조상으로 번진다(장면 그래프의 경계 더러움 표시, 유니티 UGUI 의 SetVerticesDirty, Godot 의 item_rect_changed 와 같은 꼴). 경계를 모르는 것(경계를 알리지 않는 컴포넌트, draw 를 덮어쓰고 calculateDrawnRect 를 알리지 않는 노드, 기즈모를 그리는 노드, 위치나 변환 읽기를 덮어쓴 노드, 부모 좌표에 놓는 꼴을 알리지 않는 노드)이 든 하위 트리는 건너뛰지 않는다. 설정 창 같은 스크롤 목록(줄 120 개, 줄마다 바탕, 그림 칸, 글 둘, 단추 셋, 보이는 줄 10 개쯤)의 장면 그리기가 멈춤 0.92 ms 에서 0.26 ms, 스크롤 0.99 ms 에서 0.29 ms 로 줄어 게임이 보이지 않는 줄을 꺼 버린 것(0.26 ms, 0.27 ms)과 같아졌다(맥미니 M2 Pro 헤드리스 크롬, tests/ui/scrolllistbench.mjs). 새 API: Graphic.setSubtreeCullingEnabled, isSubtreeCullingEnabled, getLastFrameCulledSubtreeCount, TransformNode.readSubtreeDrawBounds, calculateSubtreeDrawBounds, markDrawBoundsDirty, markParentDrawBoundsDirty, getLastDrawnFrameNumber, WorldNode.calculateDrawnRect, Component.markDrawnRectDirty, Component.markAllDrawnRectsDirty, Component.getDrawnRectGeneration. 노드마다의 화면 밖 거르기는 갱신만 하는 컴포넌트(draw 를 덮어쓰지 않은 것, ButtonMotion 같은)를 그리지 않는 것으로 본다. 글 굽기 배율이 움직이는지 볼 때 지난 프레임에 그리지 않은 노드는 처음 그리는 것처럼 본다(setLastDrawnMaximumScale 이 프레임 번호도 받는다).
- 그리는 곳 알림 넓힘: UISlider(손잡이 원이 값이 움직이는 줄 전체에 반지름만큼, 값과 상관없는 사각형), ShadowText, ShadowImage(그림자 번짐 두 배와 내림), RichText(조각을 이은 한 줄), UILineChart(범위 밖 값), UIBarChart, HeatHazeEffect(흔들림 폭), UIInputField 의 문맥 메뉴(그림자)와 바탕, 덮개 층(한 줄이면 보이는 글 너비까지)이 calculateDrawnRect 로 그리는 곳을 알리고 그 사각형을 바꾸는 세터마다 markDrawnRectDirty 를 부른다. 하위 트리 경계 셈은 TransformNode 로 올리고, 자식을 부모 좌표에 옮기는 것은 노드 종류마다 transformDrawBoundsToParent 로 한다(WorldNode 는 위치, 회전, 배율, 피봇, UINode 는 솔버가 푼 자리). UINode 는 솔버가 푼 자리와 크기가 바뀌면(LayoutVariable.setValueChangedEvent) 경계를 다시 셈해 이제 건너뛸 수 있다. 위치, 배율, 회전, 보임, 피봇, 내용 크기 세터는 같은 값이면 더럽히지 않는다. 광부 키우기 설정 창의 엔진 컴포넌트를 그대로 단 장면(줄 120 개)의 그리기가 켬에서 멈춤 0.370 ms 에서 0.215 ms, 스크롤 0.390 ms 에서 0.265 ms 로 줄었다(끔 0.640 ms, 게임 거르기 0.140 ms, tests/ui/scrolllistbench.mjs). 새 API: TransformNode.calculateDrawnRect, transformDrawBoundsToParent, transformLocalRectToParent, WorldNode.transformDrawBoundsToParent, UINode.transformDrawBoundsToParent, UISlider, ShadowText, ShadowImage, RichText, UILineChart, UIBarChart, HeatHazeEffect 의 calculateDrawnRect, LayoutVariable.setValueChangedEvent, getValueChangedEvent. ParticleSystem, TrailRenderer, TouchEffect 는 아직 그리는 곳을 알리지 않는다(그 조상은 건너뛰지 않는다).
- 부모 좌표에서 먼저 거르기: 부모가 하위 트리 경계를 셈할 때 자식마다 부모 좌표로 옮긴 경계를 자식에 적어 두고(TransformNode.readParentDrawBounds, 자식의 변환이나 경계가 바뀌어 부모가 다시 셈할 때까지 그대로), drawNode 가 자식에 변환을 걸기 전에 그 경계를 부모 좌표의 보이는 사각형(화면과 걸린 자르기를 지금 변환으로 거꾸로 옮긴 경계 상자, 한 디바이스 픽셀 넉넉히, 변환과 자르기가 같으면 부모 하나에 한 번 셈)과 견주어 밖이면 변환을 걸지 않고 건너뛴다. 스크롤은 부모의 변환만 바뀌므로 자식들 경계는 다시 셈하지 않는다. 돌림, 기울임은 경계 상자라 넉넉하고, 그리기 차례는 그대로다. 납작한 목록(묶음 노드 아래 바로 자식 수백 개)에서 화면 밖 자식마다 변환을 걸던 일이 없어진다.
- 보이는 자식 범위만 그리기: 자식 그리기를 TransformNode.drawChildren 으로 모으고(TransformNode.draw, WorldNode.draw 가 부른다), 하위 트리 경계를 셀 때 자식마다 적은 부모 좌표 경계를 앞에서부터 모은 가장 큰 아래와 오른쪽, 뒤에서부터 모은 가장 작은 위와 왼쪽으로 두어, 그릴 때 보이는 사각형(새 Graphic.readLocalVisibleBounds)으로 이분 찾기해 범위 앞뒤 자식은 drawNode 도 부르지 않는다. 자식이 어떤 차례로 놓여도 맞고(차례대로 놓인 줄이면 보이는 줄만 남는다), 경계를 모르는 자식과 숨긴 자식은 그 자리를 넘어 좁히지 않고, 그리는 동안 노드 경계가 바뀌면 남은 자식을 모두 본다. 건너뛴 수는 하나씩 걸렀을 때와 같게 센다(새 Graphic.addCulledSubtreeCount). 그리기 차례는 그대로다.
- 보이는 사각형 안에 다 든 하위 트리(절두체 거르기의 '다 안' 표시): drawNode 가 노드의 하위 트리 경계가 보이는 사각형(화면과 걸린 자르기를 한 디바이스 픽셀 좁힌 것) 안에 다 든다고 보면(부모 변환이 축에 맞으면 변환을 걸기 전에 부모 좌표에서, 돌림이나 기울임이 있으면 변환을 건 뒤 디바이스 좌표에서 본다) 그 노드를 그리는 동안 자손은 하위 트리 견주기, 컴포넌트 거르기, 보이는 자식 범위 찾기를 하지 않고 그리며 그리는 것이 없는 자손(경계 크기 0)만 건너뛴다. 그 아래에서 자르기(마스크, 스크롤 칸)를 새로 걸면 그 자르기 안에서는 다시 견준다(자르기 상태 번호, 자르기를 풀면 앞 상태로 돌아간다). 건너뛴 수와 화면은 그대로다. 새 API: Graphic.isInsideVisibleBounds. 빈 글(Text, UILabel 의 글이 "")은 그리는 곳을 크기 0 으로 알린다. 전에는 모름이라 빈 글 라벨이 든 하위 트리는 화면 밖이어도 돌았다(광부 설정 창의 켬 칸 단추가 그 꼴, 화면 밖 슬라이더 줄마다 빈 글 라벨까지 돌아 글 컴포넌트 둘을 그렸다, 120 줄 장면에서 프레임마다 62 번). 광부 키우기 설정 창 꼴 장면(줄 120 개)의 그리기가 켬에서 멈춤 0.280
0.300 ms 에서 0.1900.200 ms, 스크롤 0.3150.330 ms 에서 0.2000.205 ms 로 줄어 게임이 보이지 않는 줄을 꺼 버린 것(0.2100.235 ms)보다 빨라졌다. 변환 건 수 153 에서 60(게임 124), 변환 뒤 화면 견주기 118 에서 7(게임 58), 컴포넌트 그리기 149 에서 87(게임 87). 광부 꼴의 차이는 거의 빈 글 몫이다(빈 글만 고친 판이 0.190 ms 로 게임 거르기와 같다). 엔진 장면은 켬 멈춤 0.3050.310 ms 에서 0.2400.290 ms(게임 0.2850.335 ms), 화면 견주기 156 에서 19(게임 78)(맥미니 M2 Pro 헤드리스 크롬, tests/ui/scrolllistbench.mjs, 전과 후 번갈아 두 번). - ParticleSystem, TrailRenderer 가 그리는 곳을 알린다(유니티처럼 프레임마다 경계를 다시 셈함): 살아 있는 파티클의 쿼드(크기의 반에 √2, 꼬리 쿼드는 머리와 꼬리, 흔들림 폭), 띠의 점(큰 굵기의 반). 시뮬레이션이 돌 때, 방출, 지움, 그리는 꼴을 바꾸는 세터에 markDrawnRectDirty 를 불러 화면 밖이면 그리기만 건너뛰고 시뮬레이션(tick)은 그대로 돈다. 월드 공간이면서 수동 틱인 파티클은 모른다(건너뛰지 않음).
- GL 상태 캐시(WebGLStateCache, three.js WebGLState 와 크롬 GPU 명령 버퍼 클라이언트의 상태 기억 꼴): Graphic 이 컨텍스트를 만들자마자 컨텍스트의 상태 함수(bindFramebuffer, viewport, scissor, enable, disable, clearColor, colorMask, blendFunc, blendFuncSeparate, blendEquation, depthMask, depthFunc, frontFace, cullFace, useProgram, bindVertexArray, activeTexture, bindTexture, pixelStorei 와 지우기)를 가로채 바뀐 값을 기억하고, getParameter, isEnabled 는 기억한 값으로 답해 GL 에 묻지 않는다. 사파리는 이 읽기가 GPU 프로세스까지 다녀오는 동기 호출이라, 엔진 2D(프레임 버퍼 되돌리기), 툰 3D(상태 적어 두기), 게임 렌더러가 그리는 중에 읽던 것이 모두 빠진다(광부 키우기 아이패드에서 게임 렌더러 쪽이 프레임마다 1.5 ms 쯤). 바뀌지 않는 한도 값(MAX_SAMPLES 같은 것)은 한 번만 묻는다. 기억하지 않는 값(스텐실 함수, 버퍼 묶음 같은 것)은 그대로 GL 에 묻는다. 모르는 값(처음, 검사하지 못한 인자, 링크 결과를 모르는 프로그램)은 다음에 읽을 때 한 번 묻는다. 헤드리스 크롬 시험(tests/core/webglstatecachechrome.test.mjs)이 틀린 인자, 지우기, 컨텍스트 잃기를 섞어 600 번 넘게 마구 부르며 캐시 답이 진짜 GL 과 같은지(다른 곳 0), 그리는 중에 GL 에 묻는 횟수가 0 인지 본다. 컨텍스트 잃음은 webglcontextlost, webglcontextrestored 이벤트로 세운 깃발로 알아, 가로챈 getParameter, isEnabled 마다 isContextLost 를 부르지 않는다(예전에는 읽을 때마다 불러 실측한 게임 화면에서 프레임마다 40 번, 엔진의 툰 방과 로비 장면에서 64 번이던 것이 0 번, GL 에 진짜로 묻는 getParameter 는 전후 모두 0 번, 시험도 그리는 중 isContextLost 0 번을 본다). 공개 함수 Graphic.getCurrentFramebuffer()(지금 그리는 프레임 버퍼, null 이면 캔버스), getCurrentViewport()(지금 뷰포트 Rect, 디바이스 픽셀, 왼쪽 아래 원점), resetGLStateCache()(three.js resetState 처럼 기억을 다시 맞춤)를 더했다.
- 툰 3D 그리기 상태 줄이기(유니티 SRP Batcher, three.js WebGLState 와 WebGLUniforms 꼴): ToonRenderer 가 그리기마다 프로그램, 텍스처 유닛 아홉, 앞면 감김과 가리는 면, 버텍스 어레이를 GL 상태 캐시에 물어 같으면 다시 걸지 않고, 유니폼은 프로그램마다 이름별로 마지막에 올린 값을 기억해 같은 값이면 올리지 않는다(본 행렬도 같다, 프레임과 그림자 판의 시작, 단계 콜백과 화면 공간 바깥선 뒤, 그 프로그램의 onBeforeDraw 뒤에는 잊고 다시 올린다). ShaderProgram.useProgram() 도 상태 캐시가 이미 그 프로그램을 쓴다고 기억하면 건너뛴다. ToonDrawQueue 는 불투명한 것(몸, 바깥선 껍데기, 그림자 깊이)을 재질, 모형, 바탕색 텍스처로 정렬해 그린다(같은 것끼리는 담은 차례, 비치는 것은 그대로 먼 것부터). 무거운 툰 장면(모형 58 개와 인스턴스 바위 400, 뼈대 모형 6, 해 그림자와 점광 그림자 둘, 바깥선 껍데기와 화면 공간 바깥선, 맥미니 M2 Pro 헤드리스 크롬)에서 프레임마다 GL 호출 6146 → 2476(useProgram 344 → 38, uniform 2918 → 1415, activeTexture 549 → 88, bindTexture 480 → 48, 상태 바꾸기 1353 → 385, 그리기 393 그대로), CPU 프레임 시간 중앙값 3.1 → 0.8 ms, 화면은 비트까지 같다. 상태 캐시 시험이 견주기 함수(isProgramInUse, isTextureBound 같은 것)가 같다고 답할 때 진짜 GL 값도 같은지 본다(518 번, 틀린 것 0).
- 그림자 다시 그리기 줄이기(유니티 HDRP 의 빛마다 그림자 갱신 방식, 언리얼의 캐시된 그림자 맵 꼴): ShadowMap 과 ShadowAtlas 에 setUpdateMode(ShadowUpdateMode, 프레임 수), getUpdateMode, getUpdateInterval, requestUpdate 를 더했다. ShadowUpdateMode 는 everyFrame(매 프레임 전부, 지금까지의 동작), onChange(기본), interval(N 프레임마다 전부, 사이의 프레임은 앞의 그림자를 그대로 쓴다). onChange 에서 ToonDrawQueue.drawShadows 와 drawLocalShadows 는 드리우개를 담은 차례로 앞의 프레임과 견준다(모형, 재질, 모형 행렬과 인스턴스 행렬, 관절 행렬, 번호 버퍼의 범위, 화면 밖 거르기, 뒤집기, 빛 행렬과 아틀라스 칸). 30 프레임 그대로인 드리우개는 따로 구운 판에 굽고, 움직이는 것(과 정점 조각이 있는 재질)만 매 프레임 구운 판을 판에 옮긴(blitFramebuffer) 뒤 그 위에 덧그린다. 구운 것이 바뀌거나 빠지거나 새로 구울 것이 생기면 다시 굽고, 빛이 바뀐 프레임은 전부를 판에 바로 그린다. 다 그대로면 하나도 그리지 않는다. 깊이는 LEQUAL 로 가장 가까운 것이 남아 굽고 덧그린 판은 전부를 한 번에 그린 판과 비트까지 같다. 무거운 툰 장면(위와 같은 장면, 맥미니 M2 Pro 헤드리스 크롬)에서 다 멈춘 프레임의 그리기 393 → 168, GL 호출 2476 → 1627, 뼈대 모형 여섯이 움직이는 프레임의 그리기 394 → 195, GL 호출 2477 → 1825, CPU 프레임 시간 중앙값 0.8 → 0.4 ms, 화면은 두 경우 모두 비트까지 같다. 크롬 시험(tests/graphics3d/shadowcachechrome.test.mjs)이 상자가 움직이다 서고 다시 움직이고, 인스턴스 하나가 옮겨 가고, 해와 점광이 움직이고, 모형 하나가 빠졌다 돌아오는 110 프레임 동안 everyFrame 과 onChange 의 화면이 프레임마다 같은지 본다(판정을 일부러 틀리게 하면 61 프레임에서 잡힌다).
- 해 그림자 초점 칸(카메라를 따라 초점이 움직이는 장면에서 onChange 캐시가 프레임마다 다시 그리던 것을 줄임): ShadowMap 에 setFocusStep(월드 칸), getFocusStep 을 더했다. 칸을 주면 updateLightMatrix 가 초점을 월드 x, y, z 각각 칸의 배수에 맞춰 옮겨 한 칸 안에서는 빛 행렬이 같고, 덮는 너비와 깊이에 칸만큼 여유를 더해 초점 둘레가 판 밖으로 나가지 않는다. 텍셀 맞춤은 그 위에 그대로 걸린다. 기본 0 은 지금까지와 같다(텍셀 맞춤만).
- 툰 그리기마다 CPU 비용 줄이기(유니티 SRP Batcher 꼴): 몸 프로그램의 재질 값 열아홉(tintColor, tintAmount, alpha, glowScale, colorScale, emissiveColor, softEdge, alphaCutoff, premultipliedOutput, textureEnabled, uvTransform, decalUvTransform, decalColor, receivesShadow, shadeOffset, highlightScale, matcapSettings, angelRingSettings, angelRingColor)을 std140 유니폼 블록 ToonDrawMaterial 하나에, 바깥선 껍데기의 값 여섯(outlineColor, outlineLightColor, outlineWidthScale, outlineOffsetZ, alpha, premultipliedOutput)을 ToonDrawOutline 에 담는다. 값이 같은 블록은 하나만 지어 두고(GPU 버퍼) 그리기마다 bindBufferBase 하나로 고르며, 이미 묶인 것이면 건너뛴다. 렌더러는 그리기 꼴 객체마다 얕은 사본(칸 이름과 차례, 값의 참조, 넷 이하 수 배열의 내용)과 푼 값을 기억해, 게임이 프레임마다 같은 꼴 객체를 넘기면 칸을 이름으로 찾아 다시 풀지 않는다(for-in 으로 있는 칸만 견줌, 난독화로 이름 읽기가 비싼 출시 빌드에서도 싸다). 틴트 배열을 그 자리에서 고치거나 칸을 더하고 빼면 그 그리기에 반영된다. ToonDrawQueue 는 draw, drawShadows 동안 꼴을 고치지 않는다는 약속(머리말)대로 꼴 객체마다 한 번만 견주고, 비치는지, 그림자, 선 번호, 묶음 같은 것도 푼 값으로 읽는다. 담은 것 칸을 프레임마다 다시 쓰고, 불투명한 것의 정렬 열쇠(재질, 모형, 바탕색 텍스처)가 앞 프레임과 같으면 차례를 다시 쓰며, 몸과 바깥선 껍데기를 그릴 때 꼴 객체를 새로 짓지 않는다. 프로그램 셋 찾기와 유니폼 칸 찾기는 마지막에 찾은 것을 기억한다. 애버런트 로비 꼴 장면(tests/graphics3d/toonlobbyscene.mjs, 모형 서른 종, 그리기 꼴 마흔, 표면 조각 머티리얼 넷, 물체 300, 해 그림자, 화면 공간 바깥선, 맥미니 M2 Pro 헤드리스 크롬)을 재기 도구(tests/graphics3d/toondrawbench.mjs, 고치기 전 사본과 번갈아)로 잰 값: 프레임당 GL 호출 4929 → 4437, 유니폼 호출 2980 → 2227(재질 값과 바깥선 값이 블록으로 옮겨 가고 bindBufferBase 261 이 더해짐), 프로그램 바꿈 41, 텍스처 묶기 205, 버텍스 어레이 묶기 388, 드로 콜 484 는 같다. 엔진이 꼴 객체의 칸을 읽는 수(Proxy 로 셈)는 프레임당 10454 → 6172(담은 것 하나에 34.7 → 20.5, 남은 몫의 반쯤은 ToonScreenOutline 의 선의 판). CDP 프로파일의 엔진 함수 자기 시간(ms/프레임)은 drawWithCount 0.133 → 0.109, writeUniformFloats 0.109 → 0.022, drawItem 0.120, drawMeshOutline 0.035, readOpaqueItemList 0.026 은 위 열넷 밖으로 빠졌다. 스크립트 시간 가운데 값(고치기 전과 번갈아 세 번씩, 기계 부하 2 ~ 15)은 2.31 → 2.30 ms 로 그대로다. 프로파일에서 시간의 대부분은 GL 호출 안(고치기 전 uniform4f 1.61, uniformMatrix4fv 0.88, 고친 뒤 bindTexture 1.10, uniformMatrix4fv 0.82, bindBufferBase 0.61 ms)이고, 그 몫이 호출 수보다 크게 어느 호출로든 옮겨 다녀 GPU 프로세스를 기다리는 몫으로 짐작한다(가르지는 않음). 그래서 난독화하지 않은 빌드에서는 자바스크립트 몫이 준 만큼이 프레임 시간으로 드러나지 않는다. (출시 빌드처럼 칸 이름 읽기가 비싼 난독화 빌드는 재지 못함) 광부 mid 꼴 장면(인스턴스 버퍼, 청크 여섯): GL 호출 849 → 803, 유니폼 호출 395 → 345, 드로 콜 75 는 같고, 스크립트 시간 가운데 값은 0.42 → 0.43 ms 로 같은 수준이다. 화면은 두 장면과 툰 예제 다섯(toonstyle, toonshowcase, toonview, toonmaterial, toonfx)이 고치기 전과 바이트까지 같다. 크롬 시험(tests/graphics3d/toondrawbatchchrome.test.mjs)이 재질 값을 바꾼 프레임에 반영되는지, 같은 꼴 객체의 값을 그 자리에서 고치면 반영되는지, 값이 같으면 블록을 다시 올리지 않는지, 새 렌더러로 같은 값을 그린 것과 바이트까지 같은지, 정렬 차례를 다시 쓰거나 담는 차례가 바뀌어도 화면이 같고 비치는 것은 깊이 차례인지 본다.
- 3D 자산 공유 캐시(SkinnedModelAsset): 같은 파일에서 지은 스킨드 모델 인스턴스들이 메시 버퍼와 버텍스 어레이, 머티리얼 원형과 그 텍스처, 모프 텍스처, 노드와 스킨 원형, 애니메이션 클립을 한 벌만 참조 수로 나눠 쓴다. (유니티의 메시와 sharedMaterial, three.js 복제본처럼) SkinnedModel.loadFromUrl, loadFromFbxUrl 은 셰이더 프로그램과 정규화한 주소(SkinnedModelAsset.normalizeKey)로 캐시를 찾아, 있으면 받지도 풀지도 않고 인스턴스를 돌려주고, 함께 받는 중이면 한 번만 받는다. 새로 createInstance(), createFromAsset(자산), getAsset(), getMaterial(번호)(유니티 Renderer.material, 처음 부르면 사본으로 갈라지고 텍스처는 빌려 씀), getSharedMaterial(번호), Material.createInstance(), setBaseColorFactor, getTextureByteCount, SkinnedModelAsset(find, register, clearCache, getCachedCount, normalizeKey, retain, release, getReferenceCount, getGpuByteCount 들)을 더했다. 인스턴스의 destroy 는 제 것(와이어프레임 버퍼, 갈라진 모프 텍스처와 머티리얼)만 지우고 자산을 놓으며, 마지막 인스턴스가 놓을 때 자산이 GPU 자원을 지우고 캐시에서 빠진다. 클립 목록은 인스턴스들이 나눠 쓰고 addAnimationsFromFbx* 로 같은 이름 클립을 더하면 그 자리를 바꾼다. addMorphTarget 은 그 인스턴스의 타깃 목록과 모프 텍스처만 갈라 낸다. 잰 값(헤드리스 크롬, examples/ancientmountain/assetcache_test.html, 같은 모형 20 개): fox.glb 421 ms, GPU 113.8 MB 에서 20 ms, 5.7 MB 로, mannequin_female.glb 250 ms, 32.0 MB 에서 9 ms, 1.6 MB 로. examples/ancientmountain 의 여우 여섯은 인스턴스마다 걸음 시점이 다르다. 러스트 판과 같은 API, 같은 시험(tests/graphics3d/skinnedmodelasset.test.mjs)이다.
- UILineChart: setMaxSampleCount 로 상한을 줄이면 이미 든 표본을 오래된 것부터 버린다. (전에는 다음 pushValue 까지 남아 점이 그래프 폭 밖으로 나갔다)
- ShaderWarmer: 셰이더 미리 링크. 켤 때 같은 소스를 KHR_parallel_shader_compile 로 뒤에서 링크해 브라우저 프로그램 캐시에 남겨, 나중에 ShaderProgram 이 같은 소스를 지을 때 주 스레드가 멈추지 않게 한다. 확장이 없으면 아무것도 하지 않는다. 매 프레임 update(), isFinished(), isSupported(). 어트리뷰트 위치는 ShaderProgram 과 같은 attributeLocationTable 로 준다
- Engine: 프레임 끝(묶어 그리기를 그린 뒤)에 PointerCursor.apply() 를 부른다
- ToonRenderer: GPU 인스턴싱(drawMeshInstanced, 인스턴스마다 { modelMatrix, tintColor }, 몸과 바깥선 모두), 화면 밖 거르기(모형의 경계 구를 절두체에, 인스턴스는 하나씩 걸러 남은 것만 올린다, options.isCulled), 그림자(beginShadowPass, drawMesh 가 깊이만, endShadowPass 가 프레임버퍼와 뷰포트를 돌린다, setShadow(ShadowMap) 로 3x3 PCF 로 받는다), HDR 출력(setHdrOutput), 한 프레임의 그린 수와 거른 수와 드로우콜(getFrameStatistics), extractFrustumPlanes
- 렌더링: 노드와 Paint 를 그릴 때 프레임마다 생기던 객체와 드로우 콜마다의 일을 줄인다. 그리는 결과는 같고 부르는 쪽의 사용법도 같다. (아래 벤치 장면과 예제 uishowcase, uisample, spriteeffects, particleeffects, timelineshowcase 를 시계를 고정해 같은 프레임에서 뜨면 화면 픽셀이 고치기 전과 같다) 크롬(헤드리스, 실제 GPU)에서 Paint 로 둥근 사각형을 그리는 노드 8천 개가 움직이는 장면(rustgame-test 의 같은 스펙 비교 벤치)을 같은 때에 재면 그리기가 78.0 ms 에서 13.0 ~ 14.4 ms, 프레임이 90.1 ms 에서 23.9 ~ 26.3 ms 가 되고, 60 FPS 를 지키는 노드 수는 1천에서 4천 ~ 6천이 된다. (한 PC 의 측정, 게임 로직 시간은 그대로다)
- Graphic: 바깥 WebGL 뒤의 2D 그리기. Graphic 은 쓰게 한 프로그램, 묶은 텍스처 같은 것을 따로 기억하지 않고, 그리기 바로 앞에 상태 캐시(WebGLStateCache)에 견주어 다른 것만 다시 건다. (프로그램, 기본 버텍스 어레이와 정점 버퍼, 텍스처 유닛과 활성 유닛, 섞기 켬과 식과 인자, 깊이 시험과 면 가리기 끔, 자르기 가위가 아니면 가위 끔, 드로잉 버퍼 전체 뷰포트) 게임이 runExternalPass 밖에서 같은 컨텍스트로 WebGL 을 써도(graphic.flushBatch 뒤 그림자 지도 같은 것) 다음 2D 와 ToonView3D 가 맞게 그린다. 남는 약속은 둘이다. 게임 프레임 버퍼를 묶었으면 들어올 때 것으로 돌려 두고, 스텐실 상태는 바꾸지 않는다. 바뀌지 않은 프레임에는 GL 을 더 부르지 않는다. (시험 장면의 프레임당 GL 부름 268 에서 219) 묶음 기억을 잊던 invalidateRenderStateCache 는 없앴다. (잊을 기억이 없다, 가로채지 못한 길로 상태를 바꿨으면 resetGLStateCache) 상태 캐시에 isArrayBufferBound, isCapabilitySet, isBlendFunction, isBlendEquation, isViewport 를 더했다. (GL 에 묻지 않는 견주기, 모르면 거짓) (광부 키우기가 알린 INVALID_OPERATION: uniformMatrix3fv, location is not from the associated program. 자르기 건 부모 안의 ToonView3D 가 runExternalPass 에서 셰이더 자르기를 스텐실에 적을 때, 게임이 바꾼 프로그램을 모르는 Graphic 의 프로그램 기억으로 그렸다)
- ImageTextureCache, TextStringTextureCache: 생성자의 둘째 인자로 텍스처를 묶는 함수(textureBinder)를 받는다. Graphic 이 넘겨, 캐시가 텍스처를 올릴 때도 묶은 텍스처를 기억한다. 없으면 지금처럼 바로 묶는다. ImageTextureCache.getTexture 는 텍스처를 만들거나 필터를 다시 걸 때만 묶는다. (그리려고 묶는 것은 Graphic 이 한다)
- 화면 밖 거르기: Graphic.setCullingEnabled(true) 면(기본 false, 지금까지와 같다) WorldNode 가 컴포넌트를 그리기 전에, 켜진 컴포넌트가 모두 내용 영역 안에서만 그린다고 알리면 내용 영역(한 단위씩 넓혀)을 지금 변환으로 옮긴 경계 상자가 화면에 걸치지 않을 때 그 노드의 컴포넌트 그리기를 건너뛴다. 판정은 그릴 때 Graphic 의 지금 변환(부모의 배율과 회전, pushState 로 건 것까지)으로 한다. 자식은 저마다 따로 보고 그대로 그리며, Mask 의 클립도 그대로 건다. draw 를 덮어쓴 노드와 TransformNode, UINode 는 거르지 않는다. (러스트 vanilla-engine 과 같은 방식이다, 러스트는 기본 켬)
- Component.isDrawnInsideContent(): 노드 내용 영역 안에서만 그리는지. 기본 false 라 알리지 않는 컴포넌트가 하나라도 켜진 노드는 거르지 않는다. Paint, Sprite 와 ShaderSprite(뒤집지 않았을 때, 조각과 나인 슬라이스와 타일 포함), Mask, Outline, SoftShade, UIProgressRing 만 true 를 알린다. draw 를 덮어쓴 하위 클래스는 false 로 돌아간다. 글자(Text, RichText, ShadowText 는 칸을 넘칠 수 있다), ShadowImage(그림자 여백), ParticleSystem, TrailRenderer, UI 위젯은 알리지 않는다
- Graphic: 묶어 그리기(setBatchingEnabled)와 화면 밖 거르기(setCullingEnabled)를 기본으로 켠다. 지금 엔진을 쓰는 게임(외계행성 광부, 우주생물, aberrant, 찾았다, 종말 생존)이 모두 묶어 그리기를 켜고 돌았고, 거르기는 내용 영역 안에만 그린다고 알린 컴포넌트만 거른다(예제 일곱 장면에서 켬과 끔의 픽셀이 같았다). 예전처럼 쓰려면 setBatchingEnabled(false), setCullingEnabled(false)
- LoadingProgress: 알려 준 진행률(setProgress, 0 ~ 1, 줄지 않음)을 보이는 값(getShownProgress)이 부드럽게 따라간다. 매 프레임 update(timeDelta), 따라가는 빠르기 setFollowRate(기본 초당 남은 거리의 6 배), isFinished, reset
- 글 재기 캐시: TextStringTextureCache.measureText 와 Text 의 재기가 글꼴 문자열과 글이 같으면 다시 재지 않는다. (2048 개, 오래 안 쓴 것부터 버림, 웹 글꼴이 받아지거나 문서의 글꼴 얼굴 수가 바뀌면 비움) measureTextMetrics(fontString, text) (textstringtexturecache.js). 돌려준 TextMetrics 는 나눠 쓰므로 고치지 않는다
- Component.calculateDrawnRect(rect): 내용 영역 밖까지 그리는 컴포넌트가 그리는 사각형을 알려 준다. (기본 false, 모름) WorldNode 의 화면 밖 거르기가 내용 영역 안에 그린다는 컴포넌트와 이 사각형을 합쳐 본다. Text 는 한 줄 글의 사각형(맞춘 크기, 넘쳐도 그 너비, 외곽선과 글꼴 크기 반만큼 양옆, 세로는 글꼴 크기의 1.5 배씩)을 알려 준다. RichText 는 모른다. UILabel 은 내용 영역 안에만(바탕) 그린다고 알린다
- 바뀐 동작: 지금까지 거르지 않던 한 줄 Text 와 UILabel 노드도 화면 밖이면 거른다. (거르기가 켜진 때, 줄을 바꾸는 글과 리치텍스트는 그대로 거르지 않는다) 노드 안에 직접 그리는 컴포넌트를 함께 붙였으면 그 컴포넌트는 지금처럼 알리지 않아 노드를 거르지 않는다
- Color.fromCache(colorString): 색 문자열("#..", "rgb(..)", "rgba(..)", 그 밖은 흰색)로 캐시한 색. 같은 문자열이면 같은 인스턴스(1024 개, 오래 안 쓴 것부터 버림), 고쳐 쓰지 않는다. Graphic.setFillColor, setStrokeColor 가 문자열을 받으면 이 캐시를 쓴다
- AudioPlayer.setPlaybackRate(playbackRate): 재생 빠르기. (1 이면 그대로, 음 높이도 같이 바뀐다, 다음 play 부터)
- Color.fromHEXCached: fromCache 처럼 1024 개를 넘으면 가장 오래 안 쓴 것부터 버린다. (전에는 끝없이 쌓였다) Color.getCachedColorCount(): fromCache 캐시에 든 수 (러스트 판의 get_cached_color_count)
- RenderTarget: options 의 sampleCount(2 이상이면 멀티샘플 렌더버퍼에 그리고 resolve() 가 컬러 텍스처마다와 깊이 텍스처로 푼다, MAX_SAMPLES 와 포맷마다 받는 표본 수 밑으로 줄이고 못 받거나 프레임버퍼가 완성되지 않으면 멀티샘플 없이), depthBits(깊이 렌더버퍼 16 이나 24), getSampleCount, getResolveFramebuffer, readSupportedSampleCount. 멀티샘플이면 getFramebuffer 는 그리는 멀티샘플 프레임버퍼다
- MultiLevelBloomEffect: 다단 블룸. 반 크기로 뽑으며 부드러운 무릎 문턱(밝기는 세 채널 가운데 큰 값), 반씩 줄이는 이중 거르개, 천막 꼴 아홉 점으로 두 배씩 키우며 위 단에 더한다. 단 수(setLevelCount), 문턱과 무릎(setThreshold), 판 정밀도
- ToonRenderer: 껍데기 바깥선을 셰이더에서 민다. 꼭짓점에 바탕 자리와 미는 쪽(MeshBuilder 가 같은 자리의 노멀을 평균하고 모서리를 덜 튀게 지은 굵기)을 올리고, 그리기마다 outlineColor, outlineWidthScale, setOutlineDistanceScale(기준 거리, 가장 작은 배, 가장 큰 배) 로 거리에 따라 굵기를 맞춘다. (원근만, 길티기어 Xrd 처럼 화면 굵기를 맞춤) 바탕 자리가 없는 껍데기(GLB 에 지어 둔 것)는 지은 자리 그대로 그린다
- 껍데기 버텍스 어레이의 어트리뷰트 1(vertexNormal 자리)에 미는 쪽이 든다. 정점 조각이 바깥선 프로그램에서 vertex.localNormal 을 고치면 껍데기 굵기가 바뀐다
- 프레임 유니폼 viewRotation (매트캡), 함수 readViewRotation, readOutlineVertexData 를 내보낸다
- ToonScreenOutline: 반 크기(줄인) 판에서 남던 계단을 없앴다. 선의 판과 씨앗은 늘 그리는 영역 해상도로 잡고, 점프 플러딩만 줄인 판에서 한다. 줄인 판의 칸에 온 해상도 씨앗 가운데 가장 가까운 것을 모으고(모으기 패스), 씨앗 자리는 그리는 영역 화소 좌표 그대로 넓혀 섞을 때 거리를 그리는 영역에서 잰다. (Ben Golus 가 말한, 낮은 해상도에서 점프 플러딩을 돌리되 자리를 겹선형으로 늘이지 말고 거리로 푸는 꼴)
- setResolutionScale 의 뜻이 선의 판과 넓히기 판의 몫(그리는 영역 x 몫)으로 바뀌었다. 기본 1 은 그리는 영역 해상도 그대로 그린다
- getLineTarget(): seedTexture (온 해상도 씨앗), jumpFloodTextures, jumpFloodIndex, jumpFloodWidth, jumpFloodHeight. (seedTextures, seedIndex 는 없어졌다) readProgramSources 가 다섯을 준다 (모으기 패스)
- ShadowAtlas: 칸 크기를 유니티 URP 기본과 같게 했다. new ShadowAtlas(컨텍스트, 해상도 기본 2048, 칸 해상도 기본 1024) 로 칸마다 1024 를 바라고, 다 들어가지 않으면 다 들어갈 때까지 반씩 줄인다 (URP 추가 빛 그림자 아틀라스 기본 2048, 해상도 단계 High 기본 1024, 빛의 기본 단계 High). getTileResolution
- 지금까지는 칸 수의 제곱근으로 격자를 나눠 점광 하나가 682 였는데 이제 512, 스포트라이트 하나는 2048 이었는데 이제 1024 다. 더 곱게 하려면 해상도와 칸 해상도를 올린다
고침
- UIInputField 줄 끝 탭 고침: 줄 끝 탭이 줄 끝 공백처럼 매달리지 않고 탭 자리가 줄 폭을 넘으면 빈 새 줄을 만들던 것을 고쳤다(크롬 white-space: pre-wrap 은 줄 끝 탭도 공백처럼 매달린다).
- 툰 미리 짓기: 그리지 않고 프레임만 넘기며 isReady() 를 기다리는 불러오기 화면에서 미리 짓기가 나아가지 않던 것을 고쳤다(게임 세션이 맥 헤드리스 크롬에서 잰 값: 45 프레임을 기다려도 끝나지 않아 한꺼번에 끝내며 8,183 ms 프레임 하나, 끝남을 묻는 getProgramParameter 하나가 52 ms). 맡긴 컴파일과 링크 명령은 그리기나 지우기가 없는 프레임에는 GPU 프로세스로 저절로 흘러가지 않을 수 있어(KHR_parallel_shader_compile 명세 원문에는 flush 얘기가 없다, 크로미엄 원문 확인은 못 했다) prewarmDrawQueue 가 맡긴 뒤, 그리고 ToonProgramPrewarm 의 걸음마다 아직 남았으면 gl.flush() 로 보낸다. ShaderProgram.isBuildComplete() 는 한 번 끝났다고 확인하면 다시 묻지 않는다(끝남 묻기는 GPU 프로세스와 오가는 일). 화면은 바이트 그대로, 공개 API 는 그대로. 이 기계의 헤드리스 크롬은 고치기 전에도 그리지 않는 프레임에서 끝나서(8 에서 32 프레임) 게임이 본 정체는 재현하지 못했다. 시험은 gl.flush 가 나가는지를 센다(고치기 전 0 번, 뒤 맡길 때 2 번과 프레임마다 1 번), 끝남 묻기 78 번에서 64 번. (tests/graphics3d/toonprogramprewarmwaitchrome.test.mjs)
- 툰 그림자 캐시(ShadowUpdateMode.onChange)가 틴트 같은 재질 값에 다시 굽던 것 고침(언리얼, HDRP 캐시 그림자처럼 드리우개를 물체마다 견줌): drawShadows 와 drawLocalShadows 가 드리우개 기록을 불투명한 것의 정렬 차례로 견주고 있었다. 정렬 열쇠에 재질 블록이 들어 있어 틴트 하나가 바뀌면 차례가 밀려, 바뀌지 않은 드리우개도 다르게 보여 구운 판을 통째로 다시 굽거나(로비 꼴) 아예 굽지 못하고 매 프레임 전부 덧그렸다. 이제 기록은 담은 차례로 견주고(머리말에 적힌 대로), 굽는 것과 덧그리는 것은 지금처럼 정렬 차례로 묶어 그린다. 견주는 값(모형, 재질, 행렬, 뼈대, 그리는 범위, 거르기, 뒤집기)은 그대로이고 틴트, 색, 빛남은 깊이에 닿지 않아 다시 굽지 않는다. 물체가 움직이면 지금처럼 그 프레임에 다시 굽는다. 로비 꼴 장면(tests/graphics3d/toonlobbyscene.mjs, 틴트가 40 프레임 주기로 돎) 600 프레임 동안 굽기 30 → 1(처음 한 번), 판의 방 꼴 장면의 그림자 그리기 122 → 118, 화면은 두 장면 모두 바이트까지 같다. 크롬 시험(tests/graphics3d/shadowcasterorderchrome.test.mjs)이 틴트만 바뀌는 프레임에 드리우개가 모두 구운 것이고 그림자 깊이를 하나도 그리지 않는지(고치기 전에는 바닥 말고는 굽지 못함), 구운 상자가 움직인 프레임에 다시 굽고 그 뒤 그 상자만 덧그리는지, 화면이 everyFrame 과 프레임마다 같은지 본다.
- UIDocument 그림과 노드 데이터 고침: 같은 문서로 적고 읽은 복제본이 본의 그림을 그대로 쓴다(serializeNode, toJsonText 가 imagePath 를 적은 컴포넌트의 그림을 경로로 기억하고, 해석기와 loadImages 애셋에서 못 찾으면 그 그림을 넣는다, 유니티 Instantiate 처럼). 그래서 UIListView.setTemplateNode 로 복제한 항목에 다시 그림이 나온다(문서 인스턴스 꼴로 옮긴 뒤 해석기 없는 새 문서로 복제해 그림이 빠졌다). bindPendingImages 는 그사이 게임이 그림을 넣었거나 경로를 바꾼 컴포넌트를 덮지 않는다. loadImages 가 읽지 못한 그림은 표에서 빼서 다음 loadImages 가 다시 요청한다. 노드 참조가 이름이 같은 앞 형제가 있는 노드를 가리키면 적을 때 경고한다(경로는 이름으로만 적어 다시 읽으면 앞 형제에 이어진다, 러스트 판 find_node_path 와 같은 꼴). 반사 속성의 지금 값이 Color 이고 문서 값이 글("#rrggbb" 같은, 옛 꼴)이면 Color.from 으로 읽는다(지금까지는 버리고 기본색으로 남았다). 숨긴 노드(setVisible(false))는 노드 데이터에 visible: false 를 적고 되살린다(보이는 노드는 적지 않아 지금까지 적은 문서와 기대값은 그대로다).
- 그리기와 그림 고침: 바꿔 끼운 셰이더(ShaderSprite 같은)에 셰이더 섞기를 주고 축에 맞는 자르기(UIScrollView 같은) 안에서 그리면 자르기 밖이 검게 덮이던 것, 투명도 층 안의 runExternalPass(clearDepth: false) 3D 가 지난 층의 깊이를 읽던 것(층마다 깊이를 비운다), ShadowMap.beginRender 가 가위 시험을 끄지 않아 2D 자르기 안에서 판 일부만 비우던 것(ShadowAtlas 와 같게), 엔진이 둘이면 한 엔진의 씬이 읽은 그림을 다른 엔진이 제 컨텍스트에 미리 올리고 미리 푼 그림을 닫던 것(그림을 읽기 시작할 때 씬을 불러오던 Graphic 만 미리 올린다)을 고쳤다.
- 셰이더 짓기 실패: ShaderSprite, ScreenEffect 가 효과 셰이더 짓기에 실패하면 예외를 던져 프레임을 멈추지 않고, 러스트 판처럼 한 번 알리고(console.error) 건너뛴다. (ShaderSprite 는 효과 없이 Sprite 로 그리고, ScreenEffect 는 그 단계를 건너뛴다) ScreenEffect.resolvePass 는 실패하면 null 이다.
- Engine: 창이 포커스를 잃으면(blur) 터치와 마우스 단추만이 아니라 키도 놓는다. (InputManager.clear 뒤 터치를 뗀 것으로, 러스트와 같다) keyup 이 오지 않아 키가 눌린 채 남던 것을 고쳤다.
- Sprite: 뒤집기(setHorizontalFlip, setVerticalFlip)가 내용 영역 밖(음의 크기 쪽)에 그리던 것을 내용 영역 안에서 거울처럼 뒤집게 고쳤다. 조각, 나인 슬라이스, 타일 모두 뒤집힌다. (나인 슬라이스는 작게 깨져 그려지고 타일은 뒤집히지 않던 것도 같이) 뒤집어도 isDrawnInsideContent 가 참이라 화면 밖 거르기를 받는다.
- Graphic.drawNode: 그리다 예외가 나도 try/finally 로 넣은 변환을 꺼내 변환 스택이 어긋나지 않는다.
- AudioPlayer: 멈춘 AudioContext 를 깨우는 동안 stop 하거나 play 를 다시 하면 늦게 끝난 지난 요청이 소리를 내던 것을 고쳤다. (요청 번호, 소리는 늘 하나) resume 거부를 잡아 처리되지 않은 거부가 남지 않는다. getTime 이 재생 중에 오디오 컨텍스트 시계로 흐른다. (재생 빠르기를 곱하고, 루프면 길이로 되감고, 아니면 길이에서 멈춘다, 멈췄거나 끝났으면 setTime 의 시작 위치)
- ParticleSystem: 루프 이음매(되풀이 경계)의 버스트가 첫 주기에만 터지던 것을 고쳤다. 0 초 버스트와 경계 바로 앞 버스트도 주기마다 터지고, 한 프레임에 여러 주기를 건너면 그 수만큼 터진다. (시간이 멈춘 0 초 프레임에는 다시 터지지 않는다)
- AnimationClip: 프레임 목록의 꼴을 실제로 담는 Rect 로 바로잡았다. (setFrames, getFrame, getFrames 의 JSDoc, 쓰지 않던 Frame 가져오기를 뺐다)
- UIView: setBackgroundColor(null 또는 undefined) 가 던지던 것을 고쳤다. 배경을 지운다. (처음 값인 알파 0 흰색으로 돌려 그리지 않는다)
- UIScrollBar: 썸 기본 색이 0 ~ 255 를 섞은 Color(255, 255, 255, 0.6) 이던 것을 Color(1, 1, 1, 0.6) 으로 고쳤다. (그려지는 모습은 같고 getThumbColor 값이 러스트 판과 같아진다) 공개 API 의 설명, @param, @returns, 예제를 채웠다
- UIInputField 숨은 DOM 입력의 자리: 페이지를 스크롤하면 어긋나던 버그를 고쳤다. body 에 붙은 absolute 요소라 뷰포트 좌표(getBoundingClientRect, clientX)에 window.scrollX, scrollY 를 더해 문서 좌표로 놓는다.
- VisualAsset: load 가 파일을 읽지 않던 것을 고침. fetch 로 비주얼 에디터가 저장한 UIDocument JSON(씬, 프리팹)을 받아 꼴을 보고, 그 글을 든 Visual 을 담은 뒤 읽힌 것으로 친다. 실패 응답이나 꼴이 틀린 문서는 거부된다. 정적 createVisualFromText 추가, unload 는 담은 Visual 도 비운다.
- Timeline: loadFromUrl 이 실패 응답(404 등)을 보지 않던 것을 고침. 이제 거부된다.
- SkinnedModel: 애니메이션 FBX 에 채널이 있는 스택이 여럿이면 모두 같은 클립 이름이 붙어 playAnimation 이 마지막 것만 틀던 것을 고침. 스택이 여럿이면 스택마다 "클립 이름/스택 이름"(스택 이름이 비면 차례 번호)이다. 스택이 하나면 전처럼 받은 이름이다.
- HumanSkinRenderer: 텍스처 유닛 주석의 눈 홍채 차례가 뒤바뀐 것을 바로잡음. (12 홍채 노멀, 13 홍채 색. 동작은 원래 맞았다)
- SkinnedModel: uploadMeshesAndMaterials 를 다시 부르면 예전 드로어블의 VAO, 버퍼, 모프 텍스처와 이 모델이 지은 머티리얼이 남아 새던 것을 고침. (먼저 destroy) uploadWireframeIndices 도 이미 올린 선 버퍼를 지우고 새로 올린다.
- Object: 비공개 필드(#instanceId, #isDestroyed)를 뺀다. 고유식별자는 처음 getInstanceId() 를 부를 때 모듈의 WeakMap 에 넣는다. 늘 false 이던 isDestroyed() 는 뺐다. (destroy() 가 파괴 표시를 남기지 않았고, 러스트 판은 버린 값이 없어지고 지운 노드의 핸들이 None 이라 같은 함수가 없다. 옮기는 법: isDestroyed() 를 부르던 곳은 늘 false 였으므로 그 검사를 지운다. 노드가 아직 트리에 있는지는 getParent() 로 본다) 모든 엔진 객체가 만들어질 때마다 채우던 칸 둘이 없어진다
- Indicator(misc): 없는 graphic.getCanvasRenderingContext() 와 isVisible() 을 부르고 import 경로("./graphic.js")가 깨져 있던 것을 고쳤다. Graphic 의 pushState, drawLine, drawStrokeCircle 로 그린다. (Graphic 의 선은 끝이 각져 Canvas2D 시절의 둥근 끝은 없다)
- 수학(base/math.js): sqrt 가 바빌로니아법 10 번으로 셈해 1 만을 넘으면 틀리던 것을 내장 제곱근으로 고쳤다. (sqrt(1e5) 가 317.2, sqrt(1e6) 이 1296, 2026-03-21 부터) 이 sqrt 를 쓰는 길이가 100 넘는 벡터의 length, normalize, distance(Vector2, Vector3)와 Quaternion, TransformMatrix, Graphic 의 긴 선(굵기와 이음새가 가늘고 짧았다), ParticleSystem 의 셈이 틀리던 것이라 게임에서 동작이 바뀔 수 있다
- 수학: asin, acos 가 급수 100 항으로 ±1 가까이에서 틀리던 것(asin(0.9999) 가 1.5132, 정답 1.5567)과 pow 가 지수가 분수면 틀리던 것(pow(4, 0.5) 가 1, pow(2, 2.2) 가 4)을 내장으로 고쳤다. Tween 의 exponential, elastic 이징과 Vector2.angle 이 바뀐다. floor, ceil, round 는 무한대를 NaN 으로 돌려주던 것을 그대로 돌려준다. (sin, cos, tan 은 내장과 4e-9 안으로 같아 그대로 둔다)
- Vector2: modulo 가 나머지 대신 나누기를 하던 것, half 가 반이 아니라 두 배를 돌려주던 것을 고쳤다
- Engine: 뒤로 가기 캐시에서 돌아올 때(pageshow 의 persisted) 없는 dispatchPageProcessRestored 를 불러 예외가 나던 것을 고쳤다. resume 때처럼 엔진 상태(오디오, 입력)를 되살리고 로드된 씬마다 onPageProcessRestored 를 부른다
- LocalStorage: 모든 접근을 try 로 감싼다. 저장소가 막혀 있거나(사생활 보호 창, window.localStorage 접근 예외) 가득 차 못 쓰면 예외 없이 이 페이지가 살아 있는 동안 메모리에 대신 둔다. (isMemoryFallback) setBackend({ getItem, setItem, removeItem, getKeys, clear }) 로 저장소를 갈아 끼운다. (플랫폼 SDK 의 저장소 같은 것, getKeys 와 clear 는 없어도 된다, null 이면 브라우저로) getBackend, getItem, setItem(저장소에 썼는지), removeItem, getJson(key, defaultValue), setJson(key, value)
- 효과, 3D, 애니메이션에서 러스트 vanilla-engine 과 다르던 것을 맞췄다. (러스트에만 있던 범용 기능을 넣고, 두 엔진에 같이 있던 버그를 같이 고쳤다)
- Animation: 비어 있던 pause, resume 을 채웠다. (gotoAndStop 이 멈춘다) stop 은 멈춰 있어도 첫 프레임으로 돌아간다. (setFrames 뒤 예전 번호가 남던 버그) SpriteAnimator.getCurrentFrameIndex
- Action: 조건 함수가 대상을 받는다. wait 의 duration 0 이하는 진행률 1(NaN 버그), repeat 0 번은 돌지 않는다
- Timeline: 같은 이름 무대 노드를 버리던 버그(모두 붙이고 이름 표에는 뒤의 것), 부모가 자기 자신이거나 고리면 무대 부모에 붙인다. Timeline.loadFromText, createFromJsonAsset
- Scene.tickTouch: 한 프레임 안에 누르고 뗀 것(빠른 탭, 클릭)의 뗌을 놓치던 것을 고쳤다. 지금은 touchPress 뒤 같은 프레임에 touchRelease 를 넘긴다. 누른 프레임에는 지금처럼 touchMove 를 넘기지 않는다
- AssetLoader: load() 를 부른 뒤 받는 동안 더한 것에 일꾼이 늘지 않던 것을 고쳤다. (처음 한 개로 load 하면 그 뒤에 더한 것을 일꾼 하나가 줄지어 받았다) 지금은 동시에 받는 수까지 일꾼을 더 띄운다
- Identifier.reset 이 처음 값으로 되돌린다. (자기 값을 자기에 다시 넣어 아무것도 하지 않던 버그, Enum.begin 이 열거마다 1 부터 센다)
- KeyCode.audiomute 의 값 "AudioMute" 는 W3C KeyboardEvent.code 표에 없는 이름이라 음소거 키를 눌러도 맞지 않았다. "AudioVolumeMute" 로 고쳤다. (러스트 판과 같이 고침)
- UI 원본 버그를 러스트 판과 같게 고쳤다:
- UIDocument 가 Sprite 의 nineSlice 를 쓰기만 하고 읽지 않던 것. 쓰는 꼴([왼쪽, 위, 왼쪽 + 오른쪽, 위 + 아래])을 거꾸로 풀어 읽는다
- UIDropdown: 머리 단추 틴트가 펼침 목록 행까지 잡아 고른 뒤 선택 강조가 옛 색으로 덮이던 것. 머리 단추 틴트에서 펼침 목록을 빼고(excludeNodeFromTint), 강조를 바꾸면 행 단추가 틴트 원래 색을 다시 담는다
- UIInputField: maxLength 로 잘린 붙여넣기에서 커서가 글 끝을 넘던 것. 글 끝으로 자른다
- LayoutSolver: 인공 변수 최적화가 예외로 끝나면 인공 행을 비우지 않고 남기던 것. try / finally 로 비운다
- UILabel 의 배경 그리는 차례는 이미 맞았다. (UILabel 이 require 한 Text, RichText 보다 앞 차례로 붙어 배경을 먼저 그린다)
- OBB.overlaps 가 늘 false 이던 버그를 고쳤다. (상대 꼭짓점을 other.length 로 돌아 상대 투영 범위가 비었다, 러스트 판과 같다)
- Platform.getSafeAreaRect 가 Window.getComputedStyle(없는 정적 함수)을 불러 예외를 내던 것을 window.getComputedStyle 로 고쳤다. (헤드리스 크롬에서 typeof Window.getComputedStyle 이 "undefined" 인 것을 확인)
- NodeLayout.arrangeFan: System 을 들여오지 않아 부르면 ReferenceError 로 멈추던 것과, 라디안 값을 도 단위 회전(setLocalRotation)에 넣던 것을 고쳤다. (러스트 판과 같다)
- TextAsset, BlobAsset: 실패 응답(404 등)을 받은 것으로 치던 것을 고쳐 예외를 낸다. (AssetLoader 의 실패 목록에 든다) AudioAsset 도 실패 응답이면 디코딩 전에 실패로 친다
- SoundEffectPool: 보이스 수가 0 이면 play 가 0 으로 나눠 예외를 내던 것을 고쳐 아무것도 하지 않는다. (러스트 판과 같다)
- Wait.nextFrame: 만든 Promise 를 기다리지 않아 바로 끝나던 것을 고쳤다. 이제 다음 requestAnimationFrame 까지 기다린다. (러스트 판 wait::next_frame 과 같다)
도구, 문서, 예제
- 엔진 묶음 짓기 도구와 쓰는 것만 묶기: node tools/bundle.cjs 가 build/vanilla.js(소스 맵 포함)와 vanilla.min.js 를 짓는다. 읽는 판 vanilla.js 는 줄과 들여쓰기를 남기고 주석을 뺀다(원래 소스와 주석은 소스 맵에 든다, esbuild 는 줄이지 않은 묶음에 주석을 남겨 주석이 묶음의 40% 쯤이었다). 4,083,510 → 2,209,932 바이트(gzip -9 742,055 → 409,865), 빈 페이지에서 묶음만 불러오는 시간 32.8 → 25.0 ms(헤드리스 크롬, 12 번 가운데 값, 0.3.2 는 16.3 ms). 저장소 맨 위 package.json 의 sideEffects 로, 게임을 소스에서 묶으면 쓰지 않는 모듈이 통째로 빠진다. 모듈 맨 위의 System.Object.freeze 같은 부름을 묶는 도구가 부수 효과로 보아 3D 모듈이 2D 게임에도 남던 것이다(2D 와 UI 만 쓰는 시험 진입 줄인 판 345,347 → 250,761 바이트, 3D 모듈 14 개가 빠짐).
- import.js: 러스트 판이 맨 위로 내는 것과 같게 TransformMatrix, KeyCode, GamepadButtonCode, GamepadAnalogStickCode, GamepadTriggerCode, ScrollMode, ButtonState, ProgressDirection, SpriteDrawMode, SpriteBlendMode, AssetType, MORPH_TARGET_MAXIMUM, VERTEX_FLOAT_COUNT, SKIN_FLOAT_COUNT, WRINKLE_CHANNEL_COUNT 를 낸다. (묶음 build/vanilla.js 에서도 바로 받는다)
- 예제 자산 라이선스 정리: 재배포 허락이 없는 Mixamo 원본 파일(ancientmountain 의 Remy.fbx 와 anims 의 클립 FBX, three.js 에서 온 Mixamo Vanguard 인 soldier.glb, toonshading 의 클립 FBX 와 mixamo_rest.json)을 지우고 Quaternius Universal Animation Library 1, 2 (Standard, CC0) 로 바꿨다. 받는 곳과 라이선스 문구는 자산 폴더의 README.md 와 THIRD_PARTY_LICENSES.md 의 Example Assets 에 있다. 뽑는 스크립트는 examples/ancientmountain/tools/export_quaternius.py (블렌더 5.2)
- ancientmountain: 캐릭터는 마네킹 mannequin.fbx(미터 단위라 CHARACTER_MODEL_SCALE 1), 클립은 idle(Idle_Loop), walk(Walk_Loop), run(Jog_Fwd_Loop), fall(Jump_Loop), land(Jump_Land), climb(ClimbUp_1m_RM). 마네킹에는 텍스처가 없어 Remy 의 PBR 맵은 빠졌다. 화면 아래에 캐릭터와 여우의 출처 줄을 넣었다. fbx_test.html, glb_test.html 도 새 자산으로
- toonshading: 클립 단추가 IDLE, WALK, RUN, ROLL, YES, TALK, PUNCH, DANCE 다. (JUMP, GREET, CLAP, CHEER 는 CC0 묶음에 같은 것이 없어 ROLL, YES, TALK, PUNCH 로 바꿨다) 뼈 대응표는 언리얼 마네킹 이름(pelvis, spine_01 같은)이고, T 포즈 표는 파일 대신 tpose.fbx(A_TPose) 첫 장면에서 셈한다
- fox.glb 의 표기를 바로잡았다. 예제 주석에 CC0 이라고 적었으나 Khronos 원문은 모형 PixelMannen CC0, 리깅과 애니메이션 tomkranis CC BY 4.0, glTF 변환 AsoboStudio 와 scurest CC BY 4.0 이다. 예제 화면과 THIRD_PARTY_LICENSES.md 에 저작자를 적었다
- glb 예제(glbmeshreader 의 API 예제, glb_test)는 soldier.glb 대신 mannequin_female.glb(여자 마네킹, Idle, Walk, Run, Dance)를 쓴다. 가이드 15-3d, architecture 의 Remy.fbx, soldier.glb 도 바꿨다
- oldface: MetaHuman(Walter 프리셋) 판으로 되살렸다. (에셋은 Epic Games 의 것, 데모 전용, examples/oldface/ASSETS_LICENSE.md) 엔진 쪽 이름 바뀜(FullscreenPass.useProgram, Graphic.flushBatch)에 맞췄고, 주소 인자 ?expression=이름 과 ?yaw=라디안 을 더했다. 피부 렌더러 HumanSkinRenderer 는 그대로다
- 라이선스 고지: 다른 원문에서 옮긴 파일(uiinputfield, spatialaudiomath, tween, matrix4, autolayout, subsurfacescatteringeffect, 초안의 tilemap, physics2d, dynamictree) 머리에 옮긴 원문과 라이선스 한 줄을 넣었다. THIRD_PARTY_LICENSES.md 에 공개 도메인과 CC0 코드(fmix32, Narkowicz 의 ACES 근사), DOSGothic(MIT 전문), Example Assets 절. tools/project.cjs build 가 출력에 LICENSE 와 THIRD_PARTY_LICENSES.md 를 복사한다. (같은 이름이 있으면 licenses/vanilla.js/ 아래에)
- 묶음에서 초안 빼기: import.js 가 초안(src/experimental 의 2D 물리, 타일맵, 2D 뼈대, 공간 소리, 세이브)을 Experimental 이름 공간으로 내보내던 줄을 뺐다. 기본 묶음과 웹 도구에 초안이 실리지 않는다. build/vanilla.min.js 1,035,048 바이트 → 849,276 바이트(약 1011 KB → 약 829 KB, gzip 약 288 KB → 약 235 KB), build/vanilla.js 4,075,155 → 3,324,094 바이트, UI 에디터 4,453,945 → 3,666,226 바이트, 비주얼 에디터 2,340,587 → 2,335,558 바이트. (파티클, 타임라인 에디터는 초안을 싣지 않았고 머리 주석만큼 늘었다) 초안은 src/experimental/experimental.js 를 직접 불러온다. experimental.js 는 맨 먼저 import.js 를 불러 엔진 모듈끼리의 차례를 맞춘다. (초안 모듈을 먼저 부르면 덜 읽힌 클래스를 만났다) tools/apidoc.cjs 는 초안 진입점을 Experimental 이름 공간으로 따로 읽어 --check, --check-examples 가 초안을 그대로 보고(문서 자료에는 지금처럼 넣지 않음), 초안 예제는 엔진을 ./import.js 로, 초안을 ./src/experimental/experimental.js 로 불러온다. 묶음과 웹 도구 html 머리에 엔진 라이선스 한 줄(/*! vanilla.js | (c) 2026 vanillapunch | MIT License | LICENSE 와 THIRD_PARTY_LICENSES.md 주소 */)을 넣었다. (README 와 가이드의 esbuild 명령에 --banner:js)
- 라이선스: 엔진 저작권자를 vanillapunch 로 적었다. (LICENSE 의 "Copyright (c) 2026 vanillapunch", README 와 가이드 개요의 "© vanillapunch", MIT 그대로) 제3자 라이선스 고지는 THIRD_PARTY_LICENSES.md 한 파일에 모았다. (README 의 라이선스 절)
- 묶음 다시 짓기: build/vanilla.js, vanilla.min.js 와 웹 도구 넷(tools/uieditor, particleeditor, timelineeditor, visualeditor 의 한 파일 html)을 지금 소스로 다시 지었다. (저장소의 묶음은 9월 것이었다) UI 에디터의 편집 화면과 결과 화면, 예제 ancientmountain, oldface, toonshading 의 HUD 는 엔진 루프 없이 Graphic 을 직접 쓰므로 그린 뒤 flushBatch() 를 부른다. (묶어 그리기가 기본으로 켜진 뒤 다시 지은 UI 에디터의 화면이 검게 비었고, HUD 의 마지막 묶음은 다음 프레임으로 밀릴 수 있었다) 배포 예제 여덟(ancientmountain, neonhorizon, oldface, particleeffects, spriteeffects, timelineshowcase, toonshading, uishowcase)이 엔진 주소에 붙이는 캐시 스탬프를 20261126a 로 바꿨다. README 와 가이드 개요의 vanilla.min.js 크기를 지금 소스로 다시 쟀다. (약 1011 KB, gzip 약 288 KB)
- tools/apidoc.cjs: 자료에 러스트 판의 짝(counterpart: { engine: "vanilla-engine", module, class, name })을 넣는다. 클래스, 열거, 멤버, 모듈 함수와 상수, 열거 값. 짝 표는 docs/api/counterpart.<판>.json 이고(러스트 판 도구가 이름으로 지은 표를 --counterpart 로 옮긴다), --check 가 짝 꼴과 수를 본다.
- tools/project.cjs build 와 README, 가이드의 vanilla.min.js 명령이 --minify 에 --keep-names 를 붙인다. (개발자 도구와 등록하지 않은 UIDocument 종류가 클래스 이름을 읽는다) project.cjs 머리 주석, 사용법 출력, TOOLS.md, 가이드의 도구 장을 코드와 맞췄다. (node tools/project.cjs, 빌드 템플릿의 기본 자리 tools/buildtemplate, -t 와 --template, stage 명령)
- tools/webm.cjs: fluent-ffmpeg, ffmpeg-static 이 없으면 설치 안내를 보이고 끝낸다. (지금까지는 안내를 보이기 전에 맨 위 require 에서 죽었다)
- tools/apidoc.cjs --gaps: 떨어진 머리 주석(머리 주석과 JSDoc 뒤에 선언 없이 다른 머리 주석이 오는 옛 덩이, "목록" 으로 끝나지 않는 머리 주석 바로 뒤의 머리 주석)을 찾는다. 찾은 옛 덩이를 지우고(UIButton, UIProgressView, UILabel, Text, Color, LocalStorage, NodeLayout, AnimationClip, SoundSystem) 절 머리처럼 쓰던 머리를 멤버 머리로 바꿨다(UISlider, PlatformerBody, Camera2D). API 문서의 그 멤버 설명이 바로잡힌다
- 가이드: 05, 12, 13, 19 장과 도구 장(ko, en)을 바뀐 것(--keep-names, UIDocument 등록 이름과 registerEditorTypes, UINode 누름, Animator 상태 기계)에 맞췄다
- import.js: 옛 "실험적 기능 목록" 묶음을 컬렉션, 애니메이션, 셰이더와 풀스크린 패스, 3D 그래픽스, 폐기 예정, 실험 묶음으로 나눴다. Visual 은 기타 기능 묶음, VisualAsset 과 BunchAsset 은 리소스 묶음으로 갔다. 내보내는 이름은 같다. (실험 묶음 자리는 주석뿐이고 초안은 src/experimental/experimental.js 에서 직접 불러온다)
- README, 가이드, ARCHITECTURE: 새 폴더로 고치고, 3D 와 툰 3D 를 실험 기능이라 하던 글을 뺐다. (README 의 "3D (실험)" 은 "3D")
- 비주얼 에디터(tools/visualeditor)를 유니티처럼 새로 지었다. 위 메뉴(File, Edit, Node, View, Window)와 도구 막대 밑에 도킹 창들(Hierarchy, Scene, Game, Inspector, Project, Console). 처음 배치는 왼쪽 하이어라키, 가운데 씬과 게임, 오른쪽 인스펙터, 아래 프로젝트와 콘솔
- 도킹(docklayout.js): 유니티나 VS Code 처럼 창 탭을 끌어 다른 창의 탭 줄이나 가운데에 놓으면 탭으로 합치고, 창 가장자리(30%)에 놓으면 그쪽으로 나누어 붙이고, 도킹 전체 가장자리에 놓으면 전체 바깥쪽에 붙인다. 끄는 동안 붙을 자리를 파란 칸으로 미끄러지듯 보여 주고, 탭 사이에 넣을 자리는 막대로 보인다. Esc 는 그만두기. 사이 막대를 끌어 크기를 바꾸고, 탭을 두 번 누르면 그 묶음을 크게 펼친다. 탭의 X 나 가운데 단추로 창을 닫고 Window 메뉴로 다시 연다(닫을 때 같이 있던 창 옆으로 돌아간다). Window > 창 배치 되돌리기. 배치는 브라우저에 남겨 두고 다시 열면 되살린다
- Scene 창과 Game 창은 캔버스 하나를 나누어 쓴다. 둘이 따로 보이면 고른 쪽에 캔버스를 달고 다른 쪽에는 누르면 옮겨 오는 안내를 둔다. 씬 뷰는 창 크기가 바뀌어도 보던 가운데를 지킨다
- 레티나처럼 픽셀 배율이 1 이 아닌 화면에서 씬 뷰가 왼쪽 위 일부에만 그려지던 것을 고쳤다 (EditorScene preDraw 에서 applyViewRect)
- 씬 뷰: 엔진 캔버스에 격자와 화면 틀(기준 해상도)을 깔고 실제 WorldNode 를 그린다. 누르면 고르고, 손잡이로 옮기기(W), 돌리기(E), 키우기(R), 밀기(Q, 스페이스, 가운데와 오른쪽 끌기), 마우스 바퀴와 Ctrl 바퀴(트랙패드 모으기)로 키우기, 트랙패드 두 손가락으로 밀기. Ctrl 은 10 단위, Shift 는 15 도에 맞춘다. 화살표로 1 칸(Shift 10 칸), F 는 고른 노드로, Home 은 화면 틀로
- 게임 뷰(Tab): 격자와 손잡이 없이 화면 틀을 뷰에 꽉 맞추고 틀 밖을 가린다. 재생하면 게임 뷰로, 멈추면 씬 뷰로 돌아온다
- 하이어라키: 펼치기와 접기, 두 번 눌러 이름 바꾸기, 끌어서 자식으로 넣거나 앞뒤 형제로 옮기기(화면 위치는 지킨다), 찾기 칸, 오른쪽 클릭으로 만들기, 복사, 붙여넣기, 복제, 지우기, 프리팹으로 저장
- 인스펙터: 켜기와 이름, 변환(위치, 회전, 크기, 내용 크기, 피봇, 앵커, 불투명도), 컴포넌트마다 반사로 모은 속성 칸(숫자, 글, 참거짓, 색과 알파, Vector2, 정해진 값은 고르기 칸). 숫자 이름표를 좌우로 끌면 값이 바뀐다. Sprite 의 그림은 프로젝트의 그림 애셋을 끌어다 놓고, 원래 크기 단추로 내용 크기를 그림에 맞춘다. 컴포넌트 더하기와 빼기
- 프로젝트: 폴더 열기(showDirectoryPicker, 크롬 계열)로 실제 애셋 폴더를 읽고 쓴다. 그 밖의 브라우저는 파일과 폴더를 끌어다 놓아 가져온다. 폴더 나무와 애셋 격자(그림 썸네일), 종류(그림, 소리, JSON, 씬, 프리팹, 모델, 글꼴, 글) 가르기, 가져오기 단추로 지금 폴더에 파일 복사. 애셋을 고르면 인스펙터에 미리보기(그림과 해상도, 소리 재생, JSON 과 글 내용, 글꼴 견본, GLB 는 메시와 뼈와 애니메이션 수와 툰 렌더러로 그려 끌어 돌리는 3D 미리보기)
- 그림 애셋을 씬 뷰에 놓으면 그 자리에 그림 크기의 Sprite 노드를 만든다. 프리팹(.prefab.json, UIDocument 문서 하나)은 놓거나 두 번 눌러 꺼내고, 씬(.scene.json)은 두 번 눌러 연다
- 씬 저장과 열기: UIDocument 형식에 에디터 값 frameSize 를 얹은 .scene.json. 게임은 new UIDocument() 의 fromJsonText 로 그대로 읽는다. 폴더를 열었으면 그 안에 바로 쓰고, 아니면 내려받는다. Sprite 의 그림은 imagePath 로 적고 프로젝트에서 찾아 잇는다
- 되돌리기와 다시 하기(200 칸, 같은 값을 잇달아 바꾸면 한 칸), 복사와 붙여넣기, 복제, 재생과 멈춤(멈추면 재생 전으로 되돌린다), 바꾸고 1 초 뒤 브라우저에 자동 보관하고 다시 열면 되살린다. 콘솔은 에디터 알림과 브라우저의 경고와 오류를 함께 보인다
- 앞의 입자 스크립트 시연 에디터는 이것으로 바꿨다
- BuildInfo: 빌드 판 읽기. await load() 가 페이지의 을 먼저 읽고, 없으면 version.json 을 캐시 없이(cache: "no-cache") 받는다. readText() 는 meta 의 글 그대로, 또는 version.json 의 "날짜 시각 (해시)" (해시가 없으면 version), 못 읽으면 빈 글. readVersionData(), isLoaded(), setMetaName, setVersionJsonPath, BuildInfo.composeText(versionData)
- tools/atlas.cjs: 여러 장(--max-size 를 넘으면 다음 쪽, 쪽마다 모두 들어가는 가장 작은 2 의 거듭제곱), 가장자리 늘여 붙이기(--extrude), 여백(--padding, 기본 2). 놓기를 선반에서 MaxRects 로 바꿔 같은 그림이라도 자리가 전과 다르다. (JSON 으로 읽으면 같다) JSON 의 images 에 page, meta 에 pages, extrude, padding 을 더했다. 쪽이 한 장이면 파일 이름이 전과 같다
- 예제 cameratour: 돌아가는 Camera2D(끌면 팬, 휠 줌), Tween.createNodeTween, Indicator
- BuildInfo: setPackageVersion, getPackageVersion. meta 도 version.json 도 없을 때 readText 가 돌려줄 판이다. (러스트 판의 빌드 때 판과 같은 자리, 넣지 않으면 지금처럼 빈 글) load 도 readText 와 같은 글을 돌려준다
- 문서를 지금 코드에 맞췄다. (코드는 그대로다)
- README: 소개(지금 소스를 묶은 번들 크기 약 765 KB, gzip 약 215 KB, 묶어 그리기와 거르기 기본 켬, 렌더 타겟 multiply), 주요 기능 표(입력 동작, 창 쌓기, 모션, 툰 3D, 애셋, 소리 표 같은 이번 판의 것), ShaderSprite 효과 수(none 을 빼면 49), 비주얼 에디터와 atlas.cjs 설명, 배포본이 없는 예제 cameratour, toonmaterial, 가운뎃점을 쉼표로
- ARCHITECTURE: 배치, 상속 계층(노드인 위젯, Object 를 상속하지 않는 것), 소유 구조(InputActions, PointerCursor, AssetLoader, 툰 3D), 프레임 루프(최대 FPS, 묶음 기억 잊기, 남은 묶음 그리기, 커서), 묶어 그리기와 거르기 기본 켬, multiply 는 렌더 타겟에서 셰이더로 섞음(알려진 공백 표에서 뺌), 미노출 목록(AudioPlayer, GamepadManager 는 이제 낸다), 9장 러스트 판과의 관계
- UPDATE.md 이 판 머리에서 두 갈래가 겹쳐 적은 줄(WebSocketClient, Localization, UILabel.getVisibleCharacterCount)을 하나씩 남겼다
- 문서 자료: 사이트가 판마다 문서를 지을 자료를 docs/ 에 둔다. (HTML 은 사이트가 짓는다)
- docs/api/<판>.json: import.js 가 내보내는 공개 API(모듈, 클래스, 멤버, 모듈 함수와 상수, 열거). 설명 칸은 { ko, en } 이고 ko 는 소스 주석 원문, en 은 docs/api/translation.en.json(ko 원문 → en) 표에서 온다. since 는 v0.0.8 부터의 태그를 훑어 그 클래스에 그 멤버가 처음 있던 판이다
- tools/apidoc.cjs: 위 자료를 뽑는다. (node 내장 모듈만 쓰는 작은 토크나이저, --missing 은 표에 없는 ko 글, --check 는 꼴 검사와 수 세기) 쓰는 법은 tools/TOOLS.md
- docs/guide/<판>/ko, en: 개요, 빠른 시작, 구조, 도구. (README, ARCHITECTURE, tools/TOOLS.md, NODE.md 에서 나눔, 저장소 상대 링크는 GitHub 주소로) docs/update/<판>.ko.md, .en.md: 이 판의 업데이트 기록
- README: UI Editor 가 저장하는 파일은 .uiasset.json 이다. (.ui.json 이라 적혀 있었다) tools/excel.cjs 는 명령줄 진입점이 없는 함수 모음이라 혼자 실행하면 아무것도 하지 않고, tools/table.cjs 는 빈 파일이라고 바로 적었다. 명령줄 도구 표에 apidoc.cjs 를 더했다
- 공개 API 주석과 예제: 공개 API 의 빈 ko 설명(모듈 요약, 멤버, 매개변수, 반환, 열거 값)과 빈 매개변수 꼴을 채우고, 값을 돌려주는데 @returns 가 없던 함수에 @returns 를, 머리 주석이 없던 비공개 함수에 머리 주석을 달았다. 설명은 코드를 읽고 실제 동작(단위, 범위, 기본값, null 일 때)대로 적었다. 모든 클래스와 클래스 없는 모듈에 @example 예제를 넣고, 쓰는 법이 이름만으로 뻔하지 않은 멤버에도 넣었다. (자료의 examples 칸, 314 개) 새 글의 영어는 번역 표에 더했다. 툰 3D 폴더(graphics3d/toon), visual.js, uilistview.js, uiscrollbar.js 는 따로 고치는 중이라 이번에 채우지 않았다
- tools/apidoc.cjs: --gaps(문서 빈 곳을 파일마다), --check-examples(API 예제와 가이드 코드 칸을 문법, 엔진 이름, node 워커, 헤드리스 크롬으로 돌려 검사, 외부 의존 없음), --missing, --gaps, --check-examples 의 --only, --exclude 거르개. 필드의 returns 는 값의 꼴만 담는 칸이라 ko 빈 칸으로 세지 않는다. 설명 앞의 하이픈은 "이름 - 설명" 꼴일 때만 뗀다. ("-1 이면" 이 "1 이면" 으로 읽히던 것)
- docs/guide/<판>/ko, en: 주제별 장 15 개를 더했다. 05 프로젝트 시작, 06 엔진과 씬, 07 노드와 컴포넌트, 08 그리기, 09 입력, 10 애셋 불러오기, 11 소리, 12 UI, 13 트윈과 애니메이션과 타임라인, 14 파티클, 15 3D, 16 저장, 17 언어, 18 개발자 도구, 19 저작 도구. (파일 이름 앞 두 자리 숫자가 차례, 장마다 도는 예제가 있고 모두 예제 검사에 걸린다)
- 고친 파일의 주석에서 긴 줄표와 가운뎃점을 쉼표로 바꿨다. (셰이더 문자열, 오류 글 같은 코드 안의 것은 그대로)
- examples/assets/beep.wav: 소리 예제에 쓰는 0.15 초 삑 소리. (스크립트로 지은 PCM)
- 예제 toonstyle: 툰 셰이딩과 바깥선 견주기 장면. (각진 상자, 둥근 공, 큰 면 결정, 잔 면 결정 덩이, 고리, 비스듬한 판, 그림자, 점광, ?scale=0.5 로 반 크기 선의 판, ?toggles=1 로 모형마다의 꼴) 러스트 예제 toonstyle 과 같은 장면이다
- 예제 toonmaterial: 애버런트 몸 셰이딩 식 대조(verifyAberrantShading)를 뺐다. (게임 하나의 식이라 엔진 예제에 둘 것이 아니고, 엔진의 빛 꼴이 정석으로 바뀌어 같은 값이 나오지 않는다) 바위 정점 조각의 노멀 크기 맞춤을 뺐다. (엔진이 역행렬의 전치로 옮긴다)
- 예제 toonstyle: 그늘 셋, 단단한 하이라이트, 해 쪽 림, 스포트라이트, 매트캡, ?shell=1 로 껍데기 바깥선(그리기마다 색과 굵기, 거리 배)
- 예제 toonstyle: 점광과 스포트라이트 그림자, 그늘 쪽 푸른 림, 짙은 공의 천사 고리, 껍데기 바깥선이 16 미터에서 사라지기와 카메라 쪽 밀기
- 예제 toonstyle: ?roll=라디안 으로 카메라를 기울인다 (천사 고리 기울임 되돌리기)
- 비주얼 에디터(tools/visualeditor)를 위 엔진으로 다시 빌드했다
옮기는 법
- WebGL 컨텍스트 잃음 처리: 게임이 webglcontextlost 에서 하던 preventDefault 와 그리기 멈춤은 지우고 addGraphicContextEventListener 로 restored 에서 자기 GL 객체만 다시 짓는다.
- 셰이더 짓기 실패 알림: 게임이 대체 그리기나 오류 보고를 하고 싶으면 addGraphicErrorListener 로 받는다.
- 툰 프로그램 변형 미리 짓기: 끊김이 거슬리는 게임은 장면을 담은 뒤 첫 프레임 앞에 한 번 부른다. (const prewarm = renderer.prewarmDrawQueue(queue); await prewarm.wait();)
- 툰 몸 변형: 기본이 맡기고 기본 몸으로 그리기로 바뀌었고 화면은 같다. 예전처럼 그 자리에서 짓고 싶으면 renderer.setAsyncProgramBuild(false). 장면 중간에 켤 빛 기능이 정해져 있으면 renderer.prewarmDrawQueue(queue, { lightFeatureList: [["rim"]] }) 로 미리 짓는다.
- 뼈 행렬 유니폼 블록: 대체 정점 셰이더(SkinnedModelRenderer 에 주는 셰이더, 툰 쪽 바깥선 셰이더)는 uniform mat4 jointMatrices[96]; 대신 JOINT_BLOCK_GLSL 을 끼운다. (본문의 jointMatrices[번호] 는 그대로) 뼈 행렬을 직접 올리던 코드(getUniformLocation("jointMatrices[0]") 와 uniformMatrix4fv)는 uploadJointMatrices(jointMatrixArray) 로 바꾼다. 모프 가중치를 직접 올리던 곳은 uniform float morphWeights[96] 대신 uniform vec4 morphWeights[24] 와 uniform4fv 로 올린다.
- GPU 메모리 셈: GPU 메모리 셈을 쓰던 곳은 EngineConfiguration.trackGpuMemory = true 로 짓는다(엔진 자원까지 처음부터 세려면). 안 쓰던 게임은 할 일이 없다.
- GPU 처리량 재기: 실기기 없이 GPU 과녁을 보던 게임은 perftrace 의 (3) 대신 --throughput 의 (6) 을 본다.
- 툰 그리기의 activeTexture 줄이기: 툰 렌더러로 그리는 동안(beginFrame 과 endFrame 사이) 바로 GL 을 부르는 코드는 고른 유닛이 0 이라고 기대하지 말고 activeTexture 를 먼저 부른다. (단계 콜백과 몸 그리기의 onBeforeDraw 는 지금처럼 유닛 0)
- 3D 색 공간 칸: 3D 를 선형으로 그릴 게임은 engineConfiguration.colorSpace = ColorSpace.linear 로 켜고, 노멀이나 마스크 텍스처는 createTexture 에 isColorData: false 를 준다. 머티리얼 조각에서 sRGB 색을 surface.baseColor 에 섞던 곳은 toSurfaceColor(색) 으로 바꿔 섞는다(감마에서는 그대로라 화면이 같다). 감마에서 맞춘 빛 세기와 색은 linear 에서 어두운 쪽이 더 어둡게 보이니 다시 맞춘다.
- 툰 그리기 줄 남겨 두는 항목과 프레임마다 할당 없애기: 부품이 많은 모형을 그리는 게임은 부품마다 ToonDrawItem 을 한 번 짓고(재질 범위의 indexStart, indexCount 를 꼴에) 프레임마다 queue.clear() 뒤 queue.addItem(item) 하고, 움직이면 item.setModelMatrix(행렬), 꼴을 바꾸면 item.setOption(이름, 값) 이나 꼴 객체를 고친 뒤 item.markDirty() 를 부른다. 프레임마다 getPosition, getScale 로 새 벡터를 받던 코드는 readPosition(벡터), readScale(벡터) 로 바꿀 수 있다.
- 툰 화면 바깥선 가는 선 길: getLineTarget 의 seedTexture 를 직접 읽던 코드는 굵기가 약 3.24 픽셀 이하면 null 인 것을 본다. readProgramSources 의 길이를 다섯으로 셈하던 코드는 일곱으로 본다.
- 툰 화면 바깥선 해상도 몫: setResolutionScale 을 이미 1 보다 작게 부르던 코드는 선 자리와 굵기는 같고 가장자리만 부드러워진다. readProgramSources 의 길이를 일곱으로 셈하던 코드는 아홉으로 본다.
- 소리 스트리밍 읽기: 엔진 SoundSystem 으로 틀던 배경음악은 소리 표에 loadType 이 없으면 스트리밍이 되므로, 그 애셋의 getAudioBuffer() 를 직접 쓰던 코드는 소리 줄에 loadType: "decompressOnLoad" 를 준다. AudioAsset 을 직접 쓰는 코드는 기본이 그대로(통째로 풀기)라 바꿀 것이 없고, 스트리밍을 쓰려면 setLoadType(AudioLoadType.streaming) 을 건다. 스트리밍 애셋은 getAudioBuffer() 가 null 이다.
- UIDocument 그림과 노드 데이터 고침: 템플릿 그림을 따로 잇던 게임은 그 코드를 지워도 된다.
- 뼈 자세 고리: 엔진 writeSkinPose 를 베껴 고리를 넣어 둔 게임은 베낀 함수를 지우고 같은 함수를 엔진 writeSkinPose 의 일곱째 인자로 넘긴다.
- 3D 카메라 흔들림: 흔들림을 따로 셈하던 게임은 CameraShake 를 하나 두고 사건마다 add, 프레임마다 update 하고, read() 를 Camera3D.setViewOffset 이나 createOffsetViewMatrix 로 건다. 월드 축에 더하던 흔들림은 카메라 지역 축(x 오른쪽, y 위, z 뒤)이 된다.
- glTF 노멀 없는 프리미티브: 노멀 없는 GLB 를 따로 노멀을 넣어 쓰던 게임은 그대로 읽어도 된다. SkinnedModel 의 노멀 없는 메시 서술을 읽던 코드는 normals 가 차 있고 indices 가 null 이다.
- GameScene 로딩이 덮어쓸 수 있는 훅에 기대지 않게: drawOnLoad 를 덮어쓰던 게임은 setLoadingDrawer 로 옮긴다. (덮어써도 이제 멈추지 않음)
- 묶어 그리기 이름을 러스트 판과 같게: graphic.setSpriteBatchingEnabled(x) 는 graphic.setBatchingEnabled(x), isSpriteBatchingEnabled() 는 isBatchingEnabled(), flushSpriteBatch() 는 flushBatch().
- 엔진 루프 밖 그리기: 루프 밖에서 그린 뒤 flushBatch() 를 부르던 코드도 그대로 돈다. WebGL 을 직접 다루는 패스를 끼울 때는 지금처럼 그 전에 flushBatch() 를 부른다.
- 엔진 묶음 짓기 도구와 쓰는 것만 묶기: README 의 esbuild 두 줄로 묶던 곳은 node tools/bundle.cjs 로 바꾼다. 공개 API 와 import 이름, vanilla.min.js 는 그대로다.
- 툰 3D 묶음 이름 ToonMesh, ToonGlb 를 걷었다. 메시 빌더: ToonMesh.MeshBuilder 는 MeshBuilder, ToonMesh.createBoxGeometry 같은 것은 createBoxGeometry 처럼 ToonMesh. 을 떼고, ToonGlb.readGlbArrays 도 readGlbArrays 처럼 ToonGlb. 을 뗀다. import { ToonMesh } 는 쓰는 이름을 그대로 가져오는 것으로 바꾼다. flushSpriteBatch() 는 flushBatch().
- 맨 위 이름을 러스트 판과 같은 집합으로: engine.getSceneManager().getAllLoadedScenes() 는 engine.getAllLoadedScenes(), 씬 올리고 내리기는 engine.loadScene, unloadScene, unloadAllScenes. Camera 는 Camera2D. List, Dictionary, Queue, Stack 은 Array 와 Map. ToonMesh.MeshBuilder, ToonMesh.createBoxGeometry, ToonGlb.readGlbArrays 같은 것은 앞의 ToonMesh., ToonGlb. 를 지우고 그 이름을 import 한다.
- UIDocument 를 전역 상태 없는 인스턴스로: UIDocument.fromJsonText(글) 처럼 정적으로 부르던 곳은 문서를 하나 지어 그 문서로 부른다. const uiDocument = new UIDocument(); uiDocument.registerEditorTypes(); uiDocument.setImageResolver(해석기); const rootNode = uiDocument.fromJsonText(글). 등록과 해석기는 그 문서에만 걸리므로 같은 문서로 읽는다. 해석기 대신 await Promise.all(uiDocument.loadImages(글)) 로 그림을 먼저 받아도 된다. UIDocument.getComponentType(이름) 으로 생성자를 받아 붙이던 곳은 uiDocument.createComponent(노드, 이름) 으로 붙인다. visual.createNode() 는 visual.createNode(uiDocument) 로, 게임 컴포넌트가 든 목록 템플릿은 listView.setTemplateNodeWithDocument(템플릿, 등록한 문서) 로 바꾼다.
- ToonView3D 화면 사각형과 출력: 그리기 함수에서 screenRect.x, y, width, height 는 screenRect.position.x, position.y, size.x, size.y 로, screenRect.outputFramebuffer, screenRect.outputViewport 는 다섯째 인자 output.outputFramebuffer, output.outputViewport 로 바꾼다. (ToonPostProcess.end(output.outputFramebuffer, output.outputViewport))
- 원본에만 있던 공개 함수 정리: camera.refreshMatrices() 는 지운다(getViewMatrix, getProjectionMatrix 가 알아서 셈한다). setStateEvent 는 지운다(아무 일도 하지 않았다). 상태마다 할 일은 setPressedEvent, setReleasedEvent, setClickEvent 로 건다.
- 기본 글꼴: DOSGothic 을 쓰던 게임은 defaultFontUrl 에 글꼴 주소를 주거나(이름은 "default"), FontAsset 으로 "DOSGothic" 을 올린다. "16px DOSGothic" 처럼 이름으로 고르던 곳은 FontAsset 으로 올리거나 "16px default" 로 바꾼다.
- 굽는 컴포넌트의 색을 Color 로: softShade.getColor(), shadowImage.getImageColor() 를 글로 쓰던 곳은 .toHEXString() 을 붙인다.
- 예약어 이름 없애기: cooldown.use() 는 cooldown.activate(), pass.use() 는 pass.useProgram(), shaderProgram.use() 는 shaderProgram.useProgram(), pointerGesture.move(x, y) 는 pointerGesture.movePointer(x, y), action.loop(...) 는 action.repeatWhile(...), Tween.easingFunction.quadratic.in 은 Tween.easingFunction.quadratic.easeIn 으로 바꾼다(out, inOut 도 easeOut, easeInOut). 옛 이름은 없다.
- 맨 위 이름 맞추기: DEVTools 는 DevTools 로 바꾼다(옛 이름은 없다). textstringtexturecache.js 의 setTextAntialiasEnabled(값) 를 직접 부르던 코드는 graphic.setTextAntialiasEnabled(값) 으로 바꾼다.
- UIInputField 여러 줄 입력과 되돌리기: 캔버스 모드 필드에서 Ctrl(맥은 Cmd) + Z 를 게임이 따로 쓰던 경우는 필드가 포커스를 가진 동안 필드가 그 키를 먹는다.
- 그림 풀기와 올리기를 로딩 때로: ImageAsset.getImage().src 는 바이트를 받았으면 blob: 주소다(애셋 경로는 getAssetPath). file:// 처럼 바이트를 받지 못하면 예전처럼 주소를 그대로 넣는다. 없는 그림(404)은 그림 요소를 짓지 않고 바로 Load fail 로 거부한다.
- 러스트 판 꼴 맞추기: new ScreenEffect(graphic) 은 new ScreenEffect() 로 바꾼다(그래픽은 begin(graphic), end(graphic) 이 받는다, 러스트 판 ScreenEffect::new() 와 같다, 넘긴 인자는 읽지 않는다). CameraGestures.takePan() 은 { x, y } 대신 Vector2 를 돌려준다(pan.x, pan.y 는 그대로 읽힌다).
- 보이기 플래그: isVisible() 로 켜져 있고 투명도가 0 보다 큰지를 보던 코드는 isVisibleInHierarchy()(조상까지) 나 isActive() && getLocalOpacity() > 0(그 노드만) 으로 바꾼다.
- ToonVfx 자리와 기본값: { x: 1, y: 2, z: 3 } 은 { position: [1, 2, 3] } 로 바꾼다. (옛 x, y, z 는 읽지 않아 원점에 나온다) alpha 를 빼서 리본이나 빔을 그리지 않던 코드는 alpha: 0 을 준다.
- 그림 경로: component.imagePath 를 읽거나 쓰던 코드는 component.getImagePath(), component.setImagePath(경로) 로 바꾼다.
- Scene 배경: GameScene, UIScene 을 쓰는 게임은 그대로다. setSceneBackgroundColor 에 준 Color 를 붙들고 고쳐 배경을 바꾸던 코드는 고친 뒤 setSceneBackgroundColor 를 다시 부른다.
- EngineConfiguration.viewScaleMode: Scene 을 바로 이은 씬은 뷰 배율이 none 에서 stretchShort 로 바뀐다. 지금 모습을 두려면 engineConfiguration.viewScaleMode = ViewScaleMode.none 을 준다. UIScene, GameScene 의 로딩 화면도 지금 모습을 두려면 같다.
- 러스트 판에 있던 공개 API: Paint, Outline 이 읽지 못하는 색 글은 흰색이다. GameScene 을 src/game/gamescene.js 경로로 불러오던 게임은 import.js 에서 불러와도 된다.
- 글자 그리기를 글리프 아틀라스로: getTextStringTextureCache().getEntry 의 entry.texture 를 직접 쓰던 코드(엔진 안에는 없음)는 glyphTextures, glyphRects 로 글리프마다 그린다.
- 화면 밖 하위 트리 거르기: Component.calculateDrawnRect 를 덮어쓴 컴포넌트는 그 사각형을 바꾸는 값이 바뀔 때 markDrawnRectDirty() 를 부른다. (부르지 않으면 화면 밖에 있던 노드가 넓어진 그림만큼 화면에 들어와도 그리지 않을 수 있다) draw 를 덮어쓴 WorldNode 는 지금처럼 건너뛰지 않고, 건너뛰게 하려면 calculateDrawnRect 를 덮어써 그리는 사각형을 알리고 바뀌면 markDrawBoundsDirty() 를 부른다. 끄려면 Graphic.setSubtreeCullingEnabled(false).
- 화면 밖 하위 트리 거르기: draw 를 덮어쓴 컴포넌트(게임의 껍데기 컴포넌트 같은)는 내용 영역 안에만 그리면 isDrawnInsideContent 를 true 로, 밖까지 그리면 calculateDrawnRect 와 markDrawnRectDirty 를 넣어야 그 노드의 조상이 건너뛰어진다.
- runExternalPass: WebGL 을 직접 다루며 텍스처 유닛 1 번 이상에 무엇이 묶여 있다고 기대하던 코드는 runExternalPass 안에서 제가 쓸 유닛을 스스로 묶는다(그 밖은 바뀐 것 없음). UIView 나 UIButton 을 이어 draw 를 덮어쓰지 않고 내용 영역 밖에 그리던 하위 클래스는 isDrawnInsideContent 를 덮어써 false 를 돌려준다.
- 렌더 배율 상한: setMaxRenderPixelRatio 바로 뒤에 getCanvasPixelSize 같은 캔버스 크기를 읽던 코드는 다음 프레임부터 새 값이 나온다. (바로 맞춰야 하면 calculateViewRect 를 부른다)
- 3D 렌더 스케일: ToonView3D 의 그리기 함수에서 ToonPostProcess.end(null, [x, drawingBufferHeight - y - 높이, 너비, 높이]) 처럼 캔버스 자리를 손으로 셈하던 것은 end(output.outputFramebuffer, output.outputViewport) 로 바꾼다(그리기 함수의 다섯째 인자 output). (배율 1 에서는 같은 자리고, 배율을 걸거나 투명도 층 안에서도 맞는 자리에 낸다)
- 안티에일리어싱 켜고 끄기: 같은 속성에 antialias 만 끈 컨텍스트를 캔버스에 먼저 만들어 넘기던 우회는 지우고 engineConfiguration.antialias = false 로 쓴다.
- GL 상태 캐시: 같은 컨텍스트 객체로 부른 GL 호출은 따로 알리지 않아도 된다. WebGL2RenderingContext.prototype 의 함수를 직접 부르는 것처럼 가로채지 못한 길로 상태를 바꾼 코드만 그 뒤에 graphic.resetGLStateCache() 를 부른다. 프레임 버퍼와 뷰포트를 getParameter 로 읽던 게임 코드는 그대로 빨라지고, 새로 짤 때는 getCurrentFramebuffer, getCurrentViewport 를 쓴다.
- 글꼴 이름 default: 애셋 없는 DynamicFont 는 윈도우에서 sans-serif(Arial) 대신 Segoe UI, 맑은 고딕으로 굽는다.
- 툰 3D 그리기 상태 줄이기: 깊이가 꼭 같은 불투명한 면(겹친 평면)은 그리는 차례가 바뀌어 다른 쪽이 보일 수 있으니 한 모형으로 합치거나 깊이를 띄운다. 그리는 중에 getSolidProgram() 같은 것으로 렌더러의 프로그램에 렌더러의 유니폼을 직접 올리던 코드는 onBeforeDraw 로 옮긴다.
- 해 그림자 초점 칸: 드리우개 기록이 못 보는 바뀜(모형의 꼭짓점을 고침, onBeforeDraw 로 그림자 깊이의 유니폼을 바꿈)이 있으면 그 프레임에 requestUpdate() 를 부르거나 setUpdateMode(ShadowUpdateMode.everyFrame) 를 준다. ToonDrawQueue 를 거치지 않고 renderer.beginShadowPass 로 그리는 코드는 지금처럼 매번 비우고 그린다.
- 해 그림자 치우침을 그림자 텍셀 크기에 맞춤: 그림자 경계가 조금 바뀐다(툰 스타일 예제에서 다른 화소 3387 / 576000, 가장 큰 차 37). 예전처럼 붙거나 떨어진 그림자가 필요하면 shadowMap.setBias(깊이, 노멀) 로 텍셀 단위 값을 준다.
- 툰 인스턴스 버퍼를 여러 패스가 같이 쓰기: 오래 두는 인스턴스(바위, 나무, 건물)는 createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }, { name: "instanceLineId", size: 1 }]) 와 createInstanceBuffer 로 한 번 올리고 addMeshInstanceBuffer 로 담는다. 하나만 바뀌면 updateInstanceBufferRange. 사용자 어트리뷰트를 셋 쓰던 꼴에 instanceLineId 를 더하면 던진다(둘로 줄인다).
- 툰 그리기마다 CPU 비용 줄이기: 몸과 바깥선 껍데기 프로그램의 엔진 재질 값은 이제 블록 안이라 getUniformLocation("tintColor") 같은 이름은 null 이다. (onBeforeDraw 는 머티리얼의 유니폼만 쓰는 자리라 바뀌는 쓰임은 없다) 꼴 객체는 평범한 객체로 넘긴다. (클래스의 get 칸으로 값을 바꾸면 가리지 못한다)
- 툰 선의 판의 거울 항목 묶기: 몸, 바깥선, 깊이 프로그램의 프레임 값은 이제 ToonFrame 블록 안이라 getUniformLocation("viewProjectionMatrix") 같은 이름은 null 이다. (머티리얼 조각은 같은 이름으로 그대로 읽는다) 선의 판은 같은 모형끼리 모아 그려 담은 차례와 다르게 그릴 수 있으니, 깊이가 꼭 같은 불투명한 면(겹친 평면)은 한 모형으로 합치거나 깊이를 띄운다.
- 툰 모서리 어둠: 굵기 0 인 바깥선(setWidth(0) 와 꺾임 굵기 0)은 이제 합치기를 돌리지 않는다.
- 툰 바깥선 낮은 턱: 같은 번호 안의 둥근 면 실루엣과 낮은 턱에 선이 더 선다. depthThreshold 를 낮춰 이음선을 잇던 게임은 옛 게임과 같은 문턱(0.05 같은)으로 되돌려도 된다. 둥근 면을 굵은 다각형으로 지은 모형에서 문턱을 아주 낮춰 잔선이 생기면 setDepthMargin 을 올린다.
- 툰 모서리 어둠의 직접 빛 몫: 해가 비추는 구석을 더 보이게 하려면 setAmbientOcclusion 의 다섯째 인자를 준다.
- GameScene 로딩: 캔버스 밖을 눌러도 로딩이 건너뛰어지던 것은 엔진 입력이 받는 누름만 건너뛴다.
- 3D 자산 공유 캐시: 같은 주소를 여러 번 받아 모델마다 머티리얼 값을 다르게 바꾸던 코드는 getMaterial(번호) 로 사본을 받아 바꾼다. (drawableList[i].material 이나 getSharedMaterial 을 고치면 같은 자산의 모든 인스턴스가 바뀐다) 받을 때마다 따로 풀린 자원이 필요하면 받기 전에 SkinnedModelAsset.clearCache() 를 부르거나 loadFromBytes 를 쓴다. 여러 인스턴스가 같은 FBX 클립을 더해도 한 벌만 남는다.
- Action: 안쪽 액션의 getTarget() 이 바깥 대상을 돌려준다고 보던 코드는 콜백이 받는 대상 인자를 쓴다. (안쪽 액션의 getTarget 은 그 액션에 따로 start 한 대상, 없으면 null)
- 입력 필드 문맥 메뉴를 엔진이 그린다: showContextMenu(clientX, clientY) 를 직접 부르던 게임은 showContextMenu(뷰 좌표) 로 바꾼다. (뷰포트 좌표는 viewManager.canvasPositionToViewPosition 으로 바꾼다) 메뉴가 DOM 요소라고 보고 document 에서 찾던 코드는 지운다. 메뉴는 씬의 다른 노드 위에 그려진다.
- 입력 필드 문맥 메뉴를 엔진이 그린다: 직접 누름 필드에서 브라우저 메뉴(맞춤법, 번역, 검사 같은 것)를 쓰던 게임은 엔진 메뉴를 쓴다.
- 셰이더 짓기 실패: 짓기 예외를 try 로 받던 코드는 그 검사를 지운다. resolvePass 를 직접 부르면 null 을 본다.
- FBX 재질 여럿: FBX 모델의 drawableList 가 재질 수만큼 늘어난다. drawableList[0] 하나가 메시 전체라고 기대하던 코드는 materialName 이나 materialIndex 로 찾는다.
- Engine.alert, confirm, prompt: window.alert(글) 은 engine.alert(글), window.confirm(글) 의 참거짓은 await engine.confirmAsync(글) 나 engine.confirm(글).setCallback(답 => 답.isConfirmed()), window.prompt(글, 기본값) 은 await engine.promptAsync(글, 기본값) 나 setCallback 으로 getText(). 답이 그 자리에서 오지 않으므로(창이 닫힐 때 온다) engine.confirm(글).isConfirmed() 를 바로 읽던 코드는 Async 나 setCallback 으로 바꾼다. 같은 게임 코드가 러스트 판에서도 돈다.
- SpriteAnimator: SpriteAnimator.playOnNode(node, ...) 는 SpriteAnimator.play(node, ...) 로 바꾼다.
- InputActions: update 와 같은 프레임 안에서 키나 패드를 바꾼 뒤 바로 readMoveAxis 로 새 값을 기대하던 코드(시험)는 update 를 한 번 더 부른 뒤 읽는다.
- 사인, 코사인, 탄젠트: 엔진 Math 의 sin, cos, tan 끝자리 값을 기대값으로 적은 시험은 다시 뽑는다. 부르는 코드는 그대로다.
- 묶음에서 초안 빼기:
import { Experimental } from "./import.js"(또는 묶음)를 쓰던 코드는import * as Experimental from "./src/experimental/experimental.js"로 바꾸고, 엔진은 묶음이 아닌./import.js로 불러온다. (초안과 엔진의 클래스가 하나여야 한다) 게임을 esbuild 로 묶으면 초안도 함께 묶인다. - Scene 터치: Scene 을 바로 이은 씬이 TouchRaycaster 나 TouchRecognizer 를 만들어 터치 훅에서 넘기던 코드는 이제 위젯이 두 번 눌린다. 만든 것을 setTouchRaycaster(그것) 으로 씬에 맡기고, 훅의 넘기기와 스크롤 칸을 찾아 wheel 을 부르던 touchWheel 을 지운다. 훅에서 터치를 가로채야 하면(막대 끌기 같은) setTouchRaycaster(null) 로 끄고 지금처럼 훅에서 넘긴다. (examples 의 uisample, uishowcase, particleeffects, spriteeffects 는 앞의 꼴로, timelineshowcase 는 뒤의 꼴로 바꿨다)
- FbxLoader: 꼬리가 붙은 이름으로 playAnimation 하거나 노드를 찾던 코드는 꼬리를 뗀 이름을 쓴다.
- 옮기는 법: Singleton 하위 클래스를 new 로 다시 만들던 코드는 getInstance() 로 받는다. 제 자식이 아닌 노드를 removeChild 로 떼던 코드는 node.setParent(null) 로 뗀다. 에디터가 저장한 문서를 읽는 게임은 읽을 문서에 registerEditorTypes() 를 한 번 부른다
- 애버런트를 옮길 때 값 바꾸기(엔진은 정석 그대로, 게임 값을 이렇게 바꾸면 같은 몸 셰이딩이 나온다, 시험 페이지에서 점광, ÷π, 해, 되비친 빛, 정반사를 넣고 실수 판에서 CPU 셈과 견줘 최대 차이 4.1e-8):
- 해와 되비친 빛(rim) 방향은 '면에서 빛 쪽'이라 부호를 뒤집어 setLight, setFillLight 로. ÷π 는 setLightModel({ isEnergyNormalized: true }). 정반사 세기는 8 / (48 + 8) 배(정규화한 블린-퐁)
- 점광은 decay 0, rangeExponent 1, color 는 readLinearColor 값 그대로(intensity 1)
- 빛 받은 몫을 1 로 막던 min(lit, 1) 은 엔진에 넣지 않았다. 빛 세기와 노출, 블룸 문턱을 다시 맞춘다. (막지 않는 곳에서는 값이 같다)
- HDR 판에 감마 값을 쓰던 것: 엔진은 선형으로 쓴다. 빛 받는 몸은 같은 값이 나오고, 빛을 받지 않는 몸의 min(색 x 배, 1) 은 sRGB 에서 곱하던 것이라 엔진의 colorScale 이나 빛남 배를 그 배의 2.2 제곱으로 준다. colorScale(거울 0.6)도 엔진 값은 0.6^2.2
- 빛남 배: 꼭짓점 빛남은 glowScale(배우 배 x 부품 배 x HDR 배), 강조색 빛은 emissiveColor 와 emissiveIntensity(0.45 x 1.6). HDR 의 밝은 부품 키우기는 메시마다의 빛남 세기로
- 색 키(#ff00ff 강조색, 표시판 키 0.02): GLB 프리미티브의 재질 범위로 갈라 그 칸만 tintAmount 1 과 강조색, 표시판은 UV 와 데칼 텍스처(로고, 숫자)로. 움직이는 얼굴 화면(표정, 시선, 깜빡임)은 표면 조각으로 둔다
- ToonScreenOutline: (공개 API 를 바꿨다)
- setCrease(각, 진하기, 이어짐 픽셀) → setCrease(각, 굵기, 진하기). 굵기는 setWidth 의 단위이고 기본 1, 진하기는 0 ~ 1 이고 기본 1. 이어짐 픽셀(creaseExtent)은 없어졌다. (화소 하나 사이만 보므로 필요 없다) 옛 setCrease(60, 0.5, 2) 와 비슷한 모습은 픽셀 단위면 setCrease(60, 1, 0.8), 월드 단위면 굵기를 바깥 선 굵기의 반쯤으로 (setWidth(0.022, world) 면 setCrease(60, 0.011, 0.8)). 굵기가 setWidth 의 단위라 월드 단위에 1 을 주면 1 미터 굵기가 된다
- setDepthThreshold(깊이 문턱, 맞닿음 문턱) → setDepthThreshold(깊이 문턱). 뜻이 접평면 거리로 바뀌었다. (월드 길이, 같은 값을 그대로 넣으면 된다) 맞닿음 문턱(contactTolerance)은 없어졌다. 선을 경계 가운데에 세우므로 어느 쪽에 그을지 가릴 일이 없다
- setWidth 의 뜻: 선 하나의 굵기이고, 경계를 가운데로 양쪽에 반씩 덮는다. (지금까지는 실루엣 바깥쪽에만 그 굵기) 기본 1.5 → 2 픽셀. 옛 모습의 바깥 두께를 맞추려면 두 배를 준다. 선 전체의 모습(덮는 몫의 합)을 맞추려면 두 배가 아니라 0.9 배쯤이다. (옛 셰이더를 같은 선의 판에 돌려 견줌, 애버런트의 옛 값 0.022 m, 꺾임 60 도 .5 2 px 는 setWidth(0.020, world), setCrease(60, 0.016, 0.5), setDepthThreshold(0.08) 가 가장 가깝다, toonstyle 장면 1280 x 720 에서 덮는 몫 합의 차이 1 %)
- setSampleCount, TOON_SCREEN_OUTLINE_MAXIMUM_SAMPLES, TOON_SCREEN_OUTLINE_MAXIMUM_CREASE_SAMPLES 는 없어졌다. (점프 플러딩은 굵기에 따라 걸음 수가 스스로 정해진다) 가벼운 길은 setResolutionScale 만 낮춘다
- getOutlineRadius() → getLineWidths() ([바깥 선, 꺾임 선] 의 그리는 영역 픽셀)
- 선 번호 상한 65535 → TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID (16383). 선의 판의 a 칸 위 두 비트에 모형마다의 꼴을 쓴다
- getLineTarget() 의 maskTexture 는 없어졌다. 대신 seedTextures (RGBA16UI 둘), seedIndex (넓히기를 마친 쪽)
- drawOutline 이 뷰포트를 beginLineIds 때의 그리는 영역으로 스스로 건다. (지금까지는 부르는 쪽의 뷰포트가 같아야 했다)
- ToonRenderer 인스턴스마다 빛남: 인스턴스 행렬의 아래 줄에 0, 0, 0, 1 이 아닌 값을 넣던 것(사영 인스턴스 행렬)은 이제 아핀으로 읽는다. ToonScreenOutline 의 선의 판도 같다.
- 툰 셰이딩을 실시간 툰 렌더링의 정석 꼴로 다시 지었다.: (공개 API 를 바꿨다)
- 부드러운 램버트(지금까지의 기본)를 그대로 쓰려면 clearShadeRamp() 나 setBandCount(0)
- clearBandRamp() → clearShadeRamp(). getBandRamp(), getBandCount() 는 없어졌다. getShadeRamp() 가 { positions, colors, feathers, isHalfLambert } 를 준다
- setSpecular(세기, 지수) 는 이제 단단한 툰 점이다. 지금까지의 부드러운 하이라이트는 setSpecular(세기, 지수, 1). getSpecular() 는 { strength, exponent, feather, color }
- setRimLight(색, 거듭제곱) 은 부드러운 테 그대로지만 바탕색에 곱하지 않고 더한다. 지금까지와 비슷한 밝기는 색에 바탕색의 대표 색을 곱해 준다. getRimLight() 는 { color, power, feather, lightMask }
- 점광의 뒷면이 밝지 않다. (그늘 램프가 있을 때) 지금처럼 램버트로 받게 하려면 clearShadeRamp()
0.4.0
Summary
- Folder cleanup: moved the grown-up features that were in src/experimental (3D, toon 3D, animation, collections and more) to the same folders as the Rust vanilla-engine. Games that use import.js keep working as is, and games that imported files directly by path switch to the new paths.
- From games into the engine: general-purpose features that the shipped games (webgame-rimminer, aberrant, steamgame-apocalypsesurvival, space-creature, retrogame-foundyou) had built separately are now part of the engine. These include window stacking (UIWindowLayer, UIWindow, UIConfirmWindow), loading, saving and time (AssetLoader, LoadingProgress, LocalStorage, PersistedStore, FixedStepper), input actions (InputActions), the sound table (SoundSystem), language packs and fonts (LanguagePack, UIFont), button and toast motion (ButtonMotion, ToastMotion) and the mouse cursor (PointerCursor).
- Toon 3D: rebuilt toon shading and the screen-space outline (ToonScreenOutline) in the standard form of real-time toon rendering. Toon effects (ToonVfx), HDR finishing (ToonPostProcess) and the shadow atlas (ShadowAtlas) are also in.
- Rendering: sprite batching and off-screen culling are on by default. Graphic used directly outside the engine loop is also drawn when that task ends, because the engine draws the remaining batch (the same as a 2D canvas). Call flushBatch() first only when inserting a pass that touches WebGL directly.
- Matching the Rust version: brought in the general-purpose features that only the Rust version had so the public APIs of the two engines match, and fixed the bugs the two engines shared in both.
- UI: UIInputField handles word movement, word deletion and word boundaries like Chrome, and supports multiline input like a Chrome textarea (setMultiline) and engine undo and redo. UIDocument writes registered names so a minified bundle gives the same document, and registerEditorTypes() registers the UI editor's types in one call.
- Scene and Engine: widgets on nodes receive touches whatever the scene type. The view transform is applied before each scene draws, which fixes scenes that directly extend Scene drawing only in the top-left quarter of the canvas on screens with a device pixel ratio of 2.
- Docs: the data the site builds each version's documentation from (the public API docs/api/0.4.0.json, the guide docs/guide/0.4.0) and the tool that extracts it, tools/apidoc.cjs.
- Performance and stability: a lost WebGL context is restored, a shader build failure is reported to the game, and toon body shader feature variants with prewarming (combination lists, hand off and draw with the default body), framebuffer clears, a GL state cache and the glyph atlas cut frames on real devices (Safari on iPhone and iPad). GPU memory tracking is off by default.
- Migration: where the public API or its usage changed, everything a game has to change is collected in the 'How to migrate' section at the end. (Scene touch, FbxLoader names, scene draw coordinates, Singleton, Color, JsonAsset.load, List and Dictionary callbacks, ToonScreenOutline, toon shading, isVisible, ToonVfx position, image path, Scene background, viewScaleMode default)
New features and changes
- WebGL context lost handling (the standard: the webglcontextlost and webglcontextrestored handling of Unity and browser games): when the context is lost the engine accepts the restore with preventDefault, does not draw while lost (it only updates scenes, and the exceptions thrown every frame from GL returning null no longer pile up), reports once through the engine error path (console.error), and passes lost to the listeners. When it comes back the engine rebuilds the base resources it made (the default shader program, vertex array, white texture, batching, particles, blend shaders, image textures, glyph atlases), resumes drawing and passes restored. Added: Engine.addGraphicContextEventListener, removeGraphicContextEventListener, dispatchGraphicContextEvent, the enum GraphicContextEvent (lost, restored), Graphic.isContextLost(). GL objects the game made (its own shader programs, render targets, ToonRenderer and its meshes, shadow maps) belong to the lost context and the engine cannot rebuild them, so the game rebuilds them on restored. Before, the engine did not call preventDefault, so it could not come back, and it threw an exception every frame
- Shader build failure notification (the standard: the same shape as Unity's shader compile error reporting): when the engine cannot build a shader program (a ToonRenderer material, a ScreenEffect pass, a Graphic.resolveShaderProgram program, the ToonView3D renderer) it reports { kind, name, error } once to the graphic error listeners, in addition to the engine error path (console.error). Added: Engine.addGraphicErrorListener, removeGraphicErrorListener, dispatchGraphicError, the enum GraphicErrorKind (shaderBuildFailed). A program that failed to build is still not rebuilt and is skipped when drawing, as before. A failure after the context was already lost (gl.isContextLost()) is not the shader's fault, so it is neither reported nor remembered, and the program is rebuilt after the context comes back (before, a null was remembered here and that material was never drawn again even after the restore)
- GPU memory tracking (like the Unity Profiler memory module, see the GPU memory that textures, renderbuffers and buffers use): added Graphic.readGpuMemoryUsage(), Engine.readGpuMemoryUsage() and the class GpuMemoryTracker (attach a context made outside the engine with GpuMemoryTracker.attach). It intercepts texImage2D, texStorage2D, generateMipmap, renderbufferStorage(Multisample), bufferData and the delete functions on the context, records bytes per object, and returns { totalBytes, canvasBytes, kindTable (count and bytes per texture, renderbuffer, buffer), ownerList (per owner, largest first) }. The owner is the top three frames of the call stack that created the object. Bytes are nominal values computed from format and size (multisample is multiplied by the sample count, the canvas multisample is assumed to be 4, driver alignment is unknown). It is for development and the picture is unchanged. It is off by default (zero per-frame CPU, and the GL create calls stay the browser's native functions). To turn it on, set EngineConfiguration.trackGpuMemory = true (counts the resources the engine creates first), or call Engine.enableGpuMemoryTracking() or Graphic.enableGpuMemoryTracking() later (counts what is created afterwards); attach a context made outside the engine with GpuMemoryTracker.attach. isGpuMemoryTrackingEnabled() tells whether it is on, and readGpuMemoryUsage() turns it on when it is off and counts what is created after that
- Toon body shader feature variants (the standard way, like Unity shader keyword variants: unused branches are removed from the program, picture unchanged): the renderer looks at what a draw uses (base, emissive, decal, matcap and angel ring textures, and from the light set a ramp texture, two or more shade stops, the two rim lights, light intensity limit) and builds the body fragment shader for those feature bits. Code of unused branches is gone at compile time, so each pixel costs less (iPhone SE2 frame interval of the miner game with outline and shadow off: 28.6-31.6 ms before vs 24.7-25.3 ms, and with the point light also off 24.5-25.5 vs 21.9-22.6 ms, the all-on version is the same). A variant is built the first time it is drawn (one frame may hitch then; ToonRenderer.prepareMaterial only prebuilds the default program) and the number of variants is the number of used bit combinations. The default program keeps every branch on. There is nothing for games to do and no API change. composeToonProgramSources gained a trailing parameter disabledFeatures (default none)
- Canvas antialias advice for games that use a post process (docs only, behavior unchanged): ToonPostProcess draws into its own MSAA target, so a game that uses it builds with EngineConfiguration.antialias set to false. With true, the canvas itself is MSAA, so the pass that copies to the screen and the UI blend per sample and cost more (Mac mini, 2560x1440 toon post process scene, GPU throughput 6.89 → 6.49 ms, with it off 6.81 → 5.22 ms)
- GPU throughput measurement (viewing the time the GPU spends drawing separately, like the GPU module of the Unity Profiler or Unreal's stat gpu): added Engine.measureGpuThroughput(frameCount = 120). It draws the current scene repeatedly without scene updates (tick) through the same drawing path as an engine frame (the same function split out of the engine loop's scene drawing), waits for the GPU with a 1-pixel readPixels, and returns the wall-clock time per frame ({ frameCount, chunkFrameCount, millisecondsPerFrame, chunkMillisecondsPerFrame }). It is the share of the slowest stage among the renderer, the GPU process and GPU execution, so when the GPU is the slowest it is the time the GPU actually spends drawing. The GPU process main thread time in a Chrome trace is CPU time for decoding commands, so it barely moves even when the amount the GPU draws changes (1.98 and 1.99 ms with the outline on and off in the lobby-like scene). From the next rAF, after 10 warm-up frames it draws one chunk of 30 frames per rAF so it does not block for long at once; while measuring, engine time, input, engine frame callbacks, the frame number, canvas resizing and capture stand still, and when it finishes the engine loop continues. Because the same state is drawn repeatedly, caches such as onChange shadows do not rebake. Added --throughput [frame count 120] to the measuring tool tools/perftrace.mjs, which calls this function through the page's global engine after the trace and prints a '(6) GPU throughput' row (same for --attach and measureAttached(page, { throughput: 120 }); 'unknown' if there is no engine or the engine version lacks this function). On a Mac mini M2 Pro in headless Chrome at 1280x720, tests/graphics3d/toonlobbyengine.html, which runs the lobby-like scene in the engine loop (ToonPostProcess RGBA16F, MSAA 4, five bloom levels), has a throughput of 3.15 ms, and 1.58 ms with the outline off (?outline=0). The toonpost example is 1.17 ms, toonshowcase 0.92 ms and panelayout 0.24 ms. (tests/core/gputhroughputchrome.test.mjs)
- 3D color space setting (the same shape as Color Space: Gamma/Linear in Unity's Player Settings): add EngineConfiguration.colorSpace and the enum ColorSpace (gamma, linear). The default is gamma, and the screen is byte-identical to before. With linear, toon 3D draws on the standard linear path. ToonRenderer.createTexture uploads color textures (base color, glow, decal, matcap, angel ring, ramp) as SRGB8_ALPHA8 so the GPU decodes them to linear (filtering and mipmaps in linear space), the shader no longer applies pow 2.2 to those textures, and passed colors (vertex color, tint, glow color, decal color, outline color) are converted to linear with the sRGB standard curve (IEC 61966-2-1) before multiplying and mixing (base color x tint, tintAmount mixing, decal). Screen output, ToonPostProcess after tone mapping, the hull outline and ToonScreenOutline line color in HDR, and the GLB base color (baseColorFactor to the sRGB vertex color) use the same curve. Data textures such as normals and masks are uploaded as is to RGBA8 with isColorData: false of createTexture (not distinguished in gamma). With linear, #define VANILLA_COLOR_SPACE_LINEAR 1 is added to the 3D shaders the engine builds, and material chunks get toSurfaceColor(vec3), which converts an sRGB color to the space of ToonSurface.baseColor. ToonRenderer, ToonPostProcess and ToonScreenOutline take options.colorSpace (default is the engine's value, gamma without an engine) and report it with getColorSpace. composeToonProgramSources, ToonRenderer.readProgramSources, ToonScreenOutline.readProgramSources, readGlbArrays and readGlbNodeArrays take a last colorSpace argument. Add Engine.getColorSpace and Graphic.getColorSpace. 2D (Graphic's 2D batch, text, UI) composites in gamma space either way. The five toon examples and the two measurement scenes are byte-identical to before in gamma, and in linear byte-identical to the branch that switched everything to sRGB (jstoonsrgb). (tests/graphics3d/tooncolorspacechrome.test.mjs)
- Toon uniform block buffers are no longer created per value or deleted all at once (a buffer pool that never modifies a buffer still in use): the frame block (ToonFrame) used to create a new GPU buffer whenever its values changed. It now reuses the buffers it has made. A buffer holding the same values is bound as is (no upload), and new values are written with bufferSubData into a buffer unused for eight beginFrame calls (a buffer the GPU may still read is never modified, a new one is created when none is free). Static scenes issue the same GL calls as before. (Selecting slots of one buffer with bindBufferRange was also measured and raised the GPU process median in the static lobby and miner scenes, so each buffer holds one block) Material and outline blocks used to delete the whole cache and forget the option entries when the cache limit (1024) was reached. They now evict one least recently used block (clock algorithm) and write the new values into its buffer (an entry holding an evicted block resolves its values again on the next draw). With a moving camera the old code created one buffer per changed pass and deleted all 1024 in one frame when the cache filled (about every 500 frames in the lobby scene). That no longer happens. Lobby scene with an orbiting camera (lobbymove, toondrawbench.mjs, 240-frame totals): createBuffer 983 -> 521 (507 of them building the scene, the old code also piles 1024 deleteBuffer calls into one frame at about frame 512). Room scene with an orbiting camera (roommove): 642 -> 180 (167 of them building the scene). The four static scenes (lobby, room, roomitem, miner) issue the same GL calls except three bufferSubData calls when a frame block is first written. GPU process main thread (tools/perftrace.mjs 10 s, two runs alternating with the old code, headless Chrome, Mac mini, 960x540): lobbymove median 1.70, 1.95 -> 1.27, 1.70 ms, p95 2.94, 3.77 -> 1.84, 3.04 ms, max 6.73, 6.44 -> 2.94, 3.84 ms, roommove median 1.27, 1.19 -> 1.03, 1.20 ms, max 6.92, 7.95 -> 2.19, 3.92 ms, frames over 5 ms in 600 frames lobbymove 1, 3 -> 0, 0, roommove 1, 1 -> 0, 0, static lobby median 1.62, 1.66 -> 1.61, 1.70 ms (unchanged). All six scenes (lobby, lobbymove, room, roomitem, roommove, miner) render the same bytes. (tests/graphics3d/toonuniformblockchrome.test.mjs, lobbymove, roommove and the 240-frame totals in toondrawbench.mjs, toonscenepage.html)
- Thin-line path for the toon screen outline (the same shape as Unity URP screen-space outlines, sampling the neighbours inside the width radius at once): up to a width of about 3.24 pixels (2 x sqrt(4.5) - 1), ToonScreenOutline skips jump flooding (seed, gather and three expand passes). It picks a target holding the first edge side of the contour and crease lines per pixel in the same order as the seed pass (one R8UI byte), and the composite looks at the seeds of the surrounding 3 x 3 pixels in the same order as the last jump flooding step (nine reads, branch-free selection) to take the coverage from the distance to the nearest one. All widths used by the Miner game (1.7 to 2.7 pixels) take this path. The full-screen passes after the line target go from six (seed, gather, three expands, composite) to two (mask, composite), and the targets written per pixel go from three RGBA16UI (24 bytes) to one R8UI (1 byte). Thick lines and the line color table keep the current path, and the seed and expand targets are built the first time a thick line is drawn (never when only thin lines are used). Passes that overwrite a whole target (mask, seed, gather, expand, coverage) clear the target first (clearBufferuiv, clearBufferfv) so tile GPUs do not load the old contents. invalidateFramebuffer is not used: on iPad mini 6 and iPhone SE2 Safari it added about 10 to 25 ms per frame when called on these targets (iPad, miner values, scale 0.75: outline share 31.7 down to about 5.5 ms, SE2 12.4 down to 1.6 ms, measured by drawing the same frame back to back). Clearing does not add that cost and the image is the same. Line positions and widths are the same (where two IDs with different line colors meet, the order of picking among segments at the same distance differs, so only the color of a few pixels changes). readProgramSources returns seven (the thin-line mask and thin-line composite are added at the end). getLineTarget gains edgeMaskTexture and outlinePath, and seedTexture and jumpFloodTextures are empty until a thick line is drawn. For the same reason, ambient occlusion (the three passes of ToonPostProcess.drawAmbientOcclusion) and bloom (BloomEffect bright pass and blur, MultiLevelBloomEffect extract and downsample, not the upsample that adds to the level above) also clear the target before passes that overwrite a whole target (the image is the same).
- Sound streaming load (the same shape as Unity AudioClip's Load Type, Unreal sound wave streaming, and on the web an HTMLMediaElement connected into the graph with a MediaElementAudioSourceNode): added the load type AudioLoadType (automatic, decompressOnLoad, streaming) and setLoadType, getLoadType, isStreaming, getStreamUrl to AudioAsset. Until now every sound was fully decoded to PCM with decodeAudioData, so one 3 minute stereo background track held about 61 MiB (float32). Streaming lets a media element decode the compressed file bit by bit, and AudioPlayer connects one media element per player to the same GainNode. Play, stop, loop, volume, mute, rate (pitch changes too), position (getTime, setTime) and end (isPlaying turns false) behave the same as a fully decoded sound, and when the audio context stops (hidden tab, mute) the media element pauses too and then resumes. The AudioAsset default stays fully decompressing (decompressOnLoad, the same as the Unity AudioClip Load Type default), and only assets that choose automatic stream files larger than 1 MiB (AUTOMATIC_STREAMING_BYTE_THRESHOLD) (it checks the Content-Length header first and does not download the body). The engine SoundSystem sound table takes a loadType field, and without it background music (isMusic) uses streaming and sound effects use decompressOnLoad. Code that uses AudioAsset directly calls setLoadType to stream. Checked on real devices (iPhone SE 2 and iPad mini 6, iOS 27.2.1): sound plays after the first tap (RMS 0.07 to 0.14), media element play() was rejected 0 of 62 times, playback resumes after the tab is hidden and shown again, looping works, and loading took 137 ms on the SE 2 against 8,618 ms for full decoding. Measured with a 3 minute 128 kbps MP3 in headless Chrome on Mac: full decoding took 169 ms to load and +154 MB of Chrome process memory, streaming took 7 ms to load (metadata only) and +11 MB (+29 MB while playing), and sound started within 5 ms in both.
- Three UIInputField IME fixes (DOM input, single and multi line): composing with a selection now shows [text before the selection, composition, text after the selection] (getDisplayText, drawing, caret and underline position; it used to keep the selection and insert at the old cursor). On compositionstart, if the DOM selection differs from the engine selection (moved or selected by keys before the tick synced it) the engine selection is synced and the undo group is cut (same as beforeinput; the committed text used to join the previous typing group so Cmd + Z skipped the value before the replacement). setText during composition clears the composing state and composition text (it used to stay stuck composing with the engine value out of sync with the DOM input).
- Bone pose hook (the same shape as Unreal AnimBP's Transform (Modify) Bone and bone overrides in Unity's LateUpdate): added a seventh argument poseAdjust to writeSkinPose. After the animation is sampled and blended, and before the skin matrices are built, it modifies each bone's local transform (translation, rotation, scale). A function is called with (locals, skeleton) and makes the changes (the arrays in locals belong to that call only, so modifying them in place does not change the skeleton's rest pose), and an array is applied as a per-bone modification table ({ nodeIndex or name, translation, rotation, scale, mode, weight }). Added adjustBones(locals, skeleton, modifiers), which applies the table, and the modification mode BoneModifyMode (add adds translation in parent space, multiplies rotation after in the bone's own space and multiplies scale, replace sets the given value). weight is the ratio between before and after the modification. Without a hook the result is bit-for-bit the same as before, and modifying one bone changes only that bone and the bones below it.
- 3D camera shake (the shape of Unity Cinemachine Impulse and Unreal Camera Shake): added CameraShake. Each shake from add(options) takes the strength of 3 position axes and 3 rotation axes (pitch, yaw, roll) (amplitude, rotationAmplitude, per-axis shares positionAxes, rotationAxes), frequency (frequency, default 10), duration (duration), attack (attack), decay ((1 - age / duration) to the power decayExponent, default 2), age (age, an event seen late added with that age continues with the same values as if added from the start, negative starts later) and seed (seed). The signal is two sine waves with slightly different frequencies per axis, live shakes are summed, and the same seed gives the same values. It has update(seconds), read() ({ position, rotation } in camera local axes), isShaking and clear. As places to apply it, added Camera3D.setViewOffset(position, rotation) (an offset in camera local axes applied last to the view matrix, on both the computed path and raw matrices, getEyePosition is the value before the offset) and createOffsetViewMatrix(viewMatrix, position, rotation), which applies it to a view matrix the game computed. ToonVfx's 2D shake (addShake, readShake) and Shaker are unchanged.
- glTF quantized mesh reading (KHR_mesh_quantization): the toon GLB readers (readGlbArrays, readGlbNodeArrays, readGlbNodeInfos) and SkinnedModel read GLB files whose vertex attributes are stored as integers. Normalized integers are divided with the glTF spec formulas (signed ones as max(c / 127, -1), max(c / 32767, -1)) and non-normalized integers are read as is. Position dequantization comes from the node transform or inverseBindMatrices, and texture coordinates get the material texture's KHR_texture_transform baked in. Normalized integer rotations in animations are read too. An unnamed mesh node belongs to the part of its named parent node (the leaf node a quantizer adds for the dequantization transform). If extensionsRequired lists an extension the reader cannot read (EXT_meshopt_compression, KHR_draco_mesh_compression and others), it throws a clear error. The Rim Miner mining ship model with gltfpack's default quantization (no compression) goes from 1.78 MB to 1.15 MB as a file and from 1.06 MB to 0.58 MB zipped. (tests/graphics3d/meshquantization.test.mjs)
- glTF primitives without normals (glTF 2.0 specification 'Using Primitive Data': without normals the primitive has flat normals and tangents are ignored): the toon GLB readers (readGlbArrays, readGlbNodeArrays) used to skip primitives without normals, so the example fox (fox.glb) drew nothing. Now vertices are split per triangle in index order, and each triangle's (p1 - p0) x (p2 - p0) scaled to length 1 is given to its three corners (0 for a triangle with zero area). The outline shell rebuilt from the body also includes those primitives. SkinnedModel used to build smooth normals at upload when normals were missing (for an indexed mesh, face normals summed and averaged per vertex), which differed from the specification. Now interpretContent splits the vertices with the same math and gives flat normals, and indices is null (positions, texture coordinates, joints, weights and morph deltas are split too). The mesh builder's normal lengths (normals in addPart, addTriangles, addTriangleShell and the sum in the outline push) are computed as sqrt(x * x + y * y + z * z) like the Rust version, so even the shell values at points where normals cancel on a symmetric model are byte-identical to the Rust version. The arrays of GLB files with normals (the examples, the mining ship, the mannequin and their quantized versions) stay byte-identical. (tests/graphics3d/meshquantization.test.mjs, modelreading.test.mjs)
- GameScene loading no longer relies on a hook that can be overridden: the loading time and the loading screen press before the first frame are now taken by an engine frame callback that load registers (a place the engine calls every loading frame), not by drawOnLoad. Fixed load never finishing and initialize never being called, without any error, when a game overrode drawOnLoad without super. (tests/core/gamesceneloadchrome.test.mjs)
- Capture mode determinism (same as the Rust edition): in capture mode (?capture=), the 0.3 second loading screen wait after a scene loads (SceneManager.loadScene's setTimeout 300) and the minimum display time wait of GameScene and UIScene (what setTimeout 50 watched; Date.now in UIScene) are counted every engine frame on the engine clock (1/60 second per frame). The scene is initialized at the head of the frame where the 0.3 seconds are reached (before the scene update) and drawn from that frame, as in the Rust edition. Images are uploaded at once, not split by a time limit. While loading (anything that takes real time, such as downloading assets, up to loadAssets for GameScene and UIScene), the frame number and the clock do not advance, so counting starts once everything has arrived. Capturing the same example twice gives byte-identical images for the same frame number. (tests/core/capturedeterminismchrome.test.mjs)
- Removed the toon 3D namespaces ToonMesh and ToonGlb. The functions and classes of the mesh builder (meshbuilder.js) and the GLB reader (glbmeshreader.js) are exported directly by name (same as the Rust version). In the Rust version ToonMesh is the renderer's mesh (what ToonRenderer creates), so the same name is not reused for another meaning. flushSpriteBatch is removed too.
- Top-level names as the same set as the Rust version: import.js no longer exports the deprecated Camera (Camera2D covers it), SceneManager (internal to the engine, Engine.getSceneManager is hidden too), List, Dictionary, Queue, Stack (use the language Array and Map, the Rust version uses Vec, HashMap, VecDeque) or Singleton. Added Engine.getAllLoadedScenes() (Rust get_all_loaded_scenes). The toon mesh builder and GLB reading functions are exported by name as in the Rust version (MeshBuilder, shape functions such as createBoxGeometry, createPartMatrix, readColorValues, readGlbArrays, readGlbImages, decodeGlbImage, readGlbNodeArrays, readGlbNodeInfos, readAnimationSwing, writeSkinPose). The namespaces ToonMesh and ToonGlb stay as deprecated and are removed in the next version (ToonMesh in the Rust version is the renderer's mesh, so one name does not get two meanings).
- Public features that existed only in the Rust version (same names): ViewManager.limitRenderPixelRatio(devicePixelRatio) (the ratio with the cap applied, used by calculateViewRect), GraphicsQualityGovernor.applyPageQuery(liteKey) (override from the query of the current page URL, same as applySearchText(location.search)), DevTools.inspectNode(node) (shows the panel, switches to the Node Hierarchy tab, expands the ancestors and selects the node), Graphic.measureTextWithFontString(fontString, text) (measures without changing the current font), LocalStorage.setStorageDirectory(storageDirectoryPath) (the save folder of the Rust version on desktop, does nothing in this version because it uses the browser storage).
- UIDocument becomes an instance without global state (same as Rust UIDocument::new): the type tables (components, nodes), the image resolver and the lists that hold node references and images, which were module globals, are held by each document object. new UIDocument() registers the engine's default types, and setImageResolver, resolveImage, serializeNode, deserializeNode, toJsonText, fromJsonText, collectGeneratedComponentTypes, getComponentTypeNames, registerNodeType, registerComponentType, registerEditorTypes, saveByReflection and loadByReflection, which were static, become instance methods. getReflectedProperties, findNodePath and findNodeByPath have no state and stay static. Added under the same names as Rust: loadImages(jsonText) (requests an ImageAsset for each imagePath in the document and returns the list of load promises), bindPendingImages() (sets the pending images and returns how many are still loading, fromJsonText and deserializeNode call it at the end), createComponent(node, typeName) and getNodeTypeName(node). serializeNode and deserializeNode write and connect node references as paths from that node, like Rust. An image that is not found gives a warning. getComponentType, getSerializeRootNode, saveNodeReferences and loadNodeReferences are now private (internal functions Rust does not have). Added UIListView.setTemplateNodeWithDocument(templateNode, uiDocument) (setTemplateNode uses a new document), and Visual.createNode takes a document (same as Rust create_node). UI Editor and Visual Editor each hold one document.
- ToonView3D screen rectangle and output (same as Rust Rect and ToonViewOutput): getScreenRect() returns a Rect (a copy) instead of an { x, y, width, height } object. The draw function becomes (renderer, camera, screenRect, webGL2RenderingContext, output): screenRect is the Rect to draw in, and outputFramebuffer and outputViewport, which rode on the screen rectangle object, move to the fifth argument, an output object ({ outputFramebuffer, outputViewport }).
- Public functions only the original had (same surface as Rust): WorldNode.isComponentDrawCulled, Camera3D.refreshMatrices and LocalStorage.readStorage, used only internally, are now private (Rust does not expose them either; the getters recompute the matrices themselves). UIButton.setStateEvent, which did nothing, is removed. Rust gains WorldNode::copy_content_size_to and ShadowAtlas::get_light_count with the same names.
- Default font (same as Rust default_font_url and the font name "default"): the default of EngineConfiguration.defaultFontUrl changes from the DOSGothic address on jsDelivr to an empty string, so the engine no longer always fetches a font it does not use. When an address is given, that font is added under the font name "default" (before, "DOSGothic"). Text with no font (Text, ShadowText, DynamicFont, buildFontString(null)) uses the engine default font chain DEFAULT_FONT_FAMILY_STRING ('"default", ' followed by SYSTEM_FONT_STRING) instead of the system font chain, so like Rust "32px default" it picks the default font when there is one and the system font otherwise. The statistics overlay also draws with "16px default".
- Baked components keep colours as Color (same as Rust ShadowText, SoftShade, ShadowImage): ShadowText, SoftShade and ShadowImage keep colours as Color instead of a "#rrggbb" string. The setters still take both a Color and a colour string, and copy the Color they get. SoftShade.getColor() returns a Color, ShadowImage.getImageColor() returns a Color or null, and UIDocument writes ShadowImage's ImageColor as an array of four numbers ([r, g, b, a]) like Rust (old documents with a colour string still load). The alpha of ShadowText's text colour is the text opacity. The module function readColorText is now readColor (returns a Color), and buildRGBAString takes a Color.
- Screen fade hold (same as Rust ScreenFadeHold, fade_screen_with_hold): added ScreenFadeHold (release, isReleased) and GameScene.fadeScreenWithHold(onDark). When the screen is fully dark, onDark receives a new hold and the screen stays dark until it is released. fadeScreen's onDark may also return a ScreenFadeHold instead of a Promise to stay dark until release (as Rust fade_screen takes an Option
). import.js exports ScreenFadeHold. - No reserved-word names (same names as Rust): neither engine uses a reserved word (use, move, loop, in) as a name. Cooldown.use() is removed in favour of activate() (Rust activate), FullscreenPass.use() and ShaderProgram.use() are useProgram() (Rust use_program), PointerGesture.move(x, y) is movePointer(x, y) (Rust move_pointer), Action.loop(condition, inner) is repeatWhile(condition, inner) (Rust repeat_while), and Tween.easingFunction's in, out, inOut are easeIn, easeOut, easeInOut (Rust ease_in, ease_out, ease_in_out). Easing names in timeline data (such as "quadratic.in") are a data format and stay the same.
- Top-level names aligned (same names as Rust): the developer tools class is renamed from DEVTools to DevTools (same as Rust DevTools). Text antialiasing is a Graphic method in both engines: Graphic.setTextAntialiasEnabled(boolean), isTextAntialiasEnabled() (Rust Graphic::set_text_antialias_enabled, is_text_antialias_enabled). Text antialiasing applies only to that Graphic, and after a change even text already made is drawn in the new form from its next draw (before, it was one value shared by every Graphic and applied only to text baked after the change).
- UIInputField multiline input and undo (same as set_multiline, set_line_height, set_tab_size, get_scroll_top, set_scroll_top, can_undo, can_redo and the TextEditBuffer grouping rules of the Rust edition): with setMultiline(true) it is a multiline input like a Chrome textarea (DOM input uses a hidden textarea). Text is split by line break characters and width like white-space: pre-wrap, overflow-wrap: break-word, and line break opportunities are read from Chrome's own line breaking, giving the same lines as the Rust edition (the same computation as the 30 texts captured from a Chrome 158 textarea). Enter inserts a line (no submit), up and down keep the horizontal position of the first vertical move, and PageUp, PageDown, Home, End (start and end of the visible line), Ctrl (Cmd on Mac) + Home, End (up, down on Mac) and the Mac Home, End, PageUp, PageDown scrolling match the Rust edition. When it overflows it scrolls to keep the caret visible, scrolls with the wheel and by dragging the thumb, and draws a thumb. With classic scrollbars (Windows, Linux, Mac classic setting) the text width shrinks by the scrollbar thickness when it overflows, like a Chrome textarea. Added setLineHeight (null for CSS normal), setTabSize (default 8), getScrollTop and setScrollTop. Undo and redo use an engine history in both canvas mode and DOM input (Ctrl (Cmd on Mac) + Z, Ctrl (Cmd on Mac) + Shift + Z, Ctrl + Y on Windows and Linux, also Alt + Backspace on Windows, consecutively typed characters are one group, moving the cursor breaks the group, paste and cut are separate groups, up to 1000). DOM input blocks the browser undo keys and historyUndo, historyRedo and uses the engine history, so a paste from the context menu can be undone too. It does not undo during IME composition, and committed text joins the preceding insert text group. Added canUndo() and canRedo(). setText clears the lists
- Image decoding and uploading moved to load time (the same shape as Unity and Unreal uploading at load time, and createImageBitmap on the web): when ImageAsset loads, it receives the bytes and decodes them off the main thread with createImageBitmap alongside the image element (Chrome decodes a Blob on a worker thread), and uploads that on the first upload and then closes it. Uploading the image element with texImage2D made Chrome decode it again on the main thread right there, so the first drawn frame of a new screen hitched. SceneManager uploads the loaded images to the GPU during the loading screen after a scene's load finishes, split 2 milliseconds per frame (Unity asyncUploadTimeSlice default) (Graphic.prepareLoadedImages, overlapping the minimum 0.3 second wait). Canvases made in code are uploaded in the scene's load with Graphic.prepareImage. The screen result is unchanged: only formats whose ImageBitmap result is byte-identical to uploading the image element are pre-decoded (8-bit PNGs that have no alpha, no color chunk or only an sRGB chunk, JPEG, WebP without alpha or animation), and the rest (PNGs with alpha and a non-sRGB color profile, 16-bit PNGs, WebP with alpha, GIF, AVIF, SVG) upload the image element at load time. Chrome 158 decodes an ImageBitmap premultiplied and then converts color, while texImage2D decodes unpremultiplied, converts color and then premultiplies, so such images differed by up to 6/255. The first drawn frame of an image-heavy scene (16 PNGs of 1024, 8 JPEGs of 2048, Mac mini M2 Pro headless Chrome 158 ANGLE Metal) went from 336 ms to 1.4 ms.
- Rust-edition shape alignment (eight small items): added Graphic.resolveShaderProgram(groupName, programName, () => [vertexSource, fragmentSource]) (caches by name; if building fails it reports once and caches null, same as the Rust edition resolve_shader_program). ShaderSprite uses it. Added Color.create(red, green, blue, alpha). Animation.setFramesFromRects now accepts canvases, OffscreenCanvas and ImageBitmap as well as HTMLImageElement (before, anything that was not an image was silently ignored). UIInputField now attaches its context menu and input handles through Engine.getEngine() even when setEngine was not called. Removed the em dash from LayoutSolver error messages (same text as the Rust edition LayoutError). Inner functions of UIInputField, ToonRenderer and ToonVfx (attachDOMInput, handleCanvasKeydown, createProgramSet, drawBands and the like) are now @private and left out of the API data. No game called them.
- Capture mode time (same as the Rust VANILLA_CAPTURE_*): capture mode set with the ?capture query advances TimeManager time by 1/60 s per frame instead of real time for deterministic captures (frame number x 1000 / 60 ms, the same arithmetic as the Rust version, so the time at the same frame is bit-identical). Capture mode skips the maximum FPS limit, because the repeated timestamp would keep the limit from passing frames. The draft tilemap addTileset documentation now says that tilesets are assets shared by several maps and must not be modified after adding (the Rust version makes the same promise with Rc
) - Visibility flag (the same as the Rust edition's WorldNode::set_visible, is_visible, NodeTree::is_visible_in_hierarchy): added TransformNode.setVisible(boolean). It is a flag kept separate from active (setActive) and opacity, and when false the node and its descendants are not drawn and do not receive TouchRaycaster presses. (Updates still run) isVisible() now returns only that flag. (Until now it was true when active and opacity above 0) The new isVisibleInHierarchy() is true when this node and all ancestors are active, have the flag set, and have local opacity above 0
- ToonVfx position and defaults (the same as the Rust edition's position: [f32; 3] in ToonParticleOptions, ToonFireballOptions, ToonGlintOptions and alpha default 1 in ToonRibbonOptions, ToonBeamOptions): emitParticles, addFireball, queueGlint take the position as position: [x, y, z] instead of three fields x, y, z. ([0, 0, 0] if omitted) queueRibbon and queueBeam (and queueLightning, which draws with it) use alpha 1 when alpha is omitted. (Until now they drew nothing) The default size of queueGlint is 0.2
- Image path (the same as the Rust edition's set_image_path, get_image_path): added setImagePath(path) and getImagePath() to Sprite, ShadowImage, UIImageView. They only record the path and do not load the image. UIDocument and the visual editor use them instead of the expando component.imagePath they attached to components. The imagePath field in document JSON is unchanged
- Scene background (the same as the Rust edition SceneBase's set_scene_background_color, get_scene_background_color, draw_scene_background): setSceneBackgroundColor(a Color or color text), getSceneBackgroundColor(), drawSceneBackground(graphic) moved from GameScene and UIScene to Scene. GameScene and UIScene fill it in preDraw as before, and a scene that extends Scene directly fills it the same way by calling drawSceneBackground in its preDraw. setSceneBackgroundColor stores a copy of the given color
- EngineConfiguration.viewScaleMode (the same as the Rust edition's EngineConfiguration::view_scale_mode, default StretchShort): revived the field that was commented out. The default is ViewScaleMode.stretchShort, and the engine puts it into the view manager when created. UIScene and GameScene switch to their own mode (setViewScaleMode, default none) in initialize as before. Before that (the loading screen) the configured mode applies
- UIScene safe area (the same as GameScene and the Rust edition's compute_safe_area_rect): computeSafeAreaRect and the layout guide insets read ViewManager.getSafeAreaInsets instead of measuring env(safe-area-inset-*) separately. setSafeAreaOverride, ?safeArea= in the URL, and setIgnoredSafeAreaSides now reach UIScene too
- Public API that the Rust edition had: Color.from(a Color or color text, Rust edition From<&str> for Color), and setters that take a color (the Rust edition's impl Into
places) also accept color text. UIScene.getDevTools, and import.js exports GameScene and isViewPositionInsideNode. WorldNode.convertNodePositionToViewPosition, convertViewPositionToNodePosition (null if it cannot be inverted), UIDropdown.getOptionList, getPopupNode, getOptionNodes, UIDialog.getPopupMotion, getOverlayNode, getPanelNode, getConfirmNode, getCancelNode - runExternalPass: even if the external pass returns with the stencil test disabled or the stencil write mask changed, the test and mask are set again so the DECR that erases shader clips reaches the stencil, and without shader clips the stencil clip state is restored (later stencil clips used to break). The batchclipchrome test covers the case
- Changing the render pixel ratio cap (ViewManager.setMaxRenderPixelRatio) while running made one frame black: resizing the canvas in tick or draw clears the drawing buffer, but that frame still drew with the old viewport set at the start of the frame. Now it only stores the value and the engine resizes the canvas at the start of the next frame through the same path as a window resize (Engine.resize). Scenes also receive the screen area change (they did not before). The same value does nothing. Added ViewManager.isViewRectPending(). In headless Chrome (device pixel ratio 2), setting a cap of 1 while running used to make that frame's pixels (0, 0, 0).
- 3D render scale (ToonView3D.setRenderScale, getRenderScale, same meaning as Unity URP renderScale and Unreal screen percentage): when the scale is not 1 (default, unchanged), ToonView3D clears a target of the on-screen content size x scale (with depth, multisampled with 4 samples when the canvas is anti-aliased) to transparent, draws the 3D into it and stretches it on through the 2D drawing path with linear filtering and source-over. The UI stays at device pixels, so text does not blur (ViewManager.setMaxRenderPixelRatio covers the whole canvas and blurs the UI too). It follows 2D clipping, and the 2D below shows where the 3D does not cover. The target has its own depth, so reusing earlier 3D depth with setDepthCleared(false) only works at scale 1. The rect passed to the draw function gained outputFramebuffer (the framebuffer bound now, null for the canvas) and outputViewport (the GL viewport inside it, integers, bottom-left origin). examples/toonview shows it with ?renderScale=0.5. Combined with ToonPostProcess.setResolutionScale the two scales multiply. So that translucent objects accumulate correctly in the target, the ToonRenderer translucent blend (ToonBlendMode.alpha) now builds the alpha channel as premultiplied over (SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA, Unity Blend SrcAlpha OneMinusSrcAlpha, One OneMinusSrcAlpha) and additive leaves alpha unchanged (ONE, ONE, ZERO, ONE). The canvas has no alpha, so colors are the same (same pixels before and after in headless Chrome). (reason: on Rimminer on a Galaxy Fold3 a canvas pixel ratio cap of 2 went from 33 ms to 19 ms but blurred the UI text as well)
- Anti-aliasing on and off: added EngineConfiguration.antialias (default true, same look as before). Turning it off creates the canvas WebGL context with antialias: false so the default framebuffer has no multisampling (MSAA). It removes the per-frame resolve cost on high-resolution mobile devices (on the Rimminer test device iPad mini 6, 2266 x 1316, MSAA cost 3 to 9 ms per frame, a heavy scene went from 35.7 ms to 26.2 ms). The web only chooses on or off and the browser picks the sample count. It is passed as the third Graphic constructor argument (antialias, default true).
- Font family name default (same as the Rust edition): the family name default (case and quotes ignored) in font strings (Graphic.setFontString, measureTextWithoutGraphic, glyph baking) is read as the engine default font chain. That position only looks up a font registered under the name default, and the SYSTEM_FONT_STRING chain is appended to the end of the list (the Rust edition looks up the default font and then the system font chain after the family list). Until now an unquoted default was a reserved word in CSS, so the canvas dropped the whole font string and measured and drew with the previous font and size (in headless Chrome the width of "16px default" was 417, measured with the previous 40px serif; it is now 139). DynamicFont without an asset also bakes with SYSTEM_FONT_STRING instead of "-apple-system, sans-serif" (same as the Rust edition's initial family name default and Text). New test tests/core/defaultfontchrome.test.mjs
- Sun shadow bias follows the shadow texel size (in the style of the texel-unit Depth Bias and Normal Bias, receiver normal bias and slope-scaled bias of Unity URP): the normal offset 0.02 (world) and depth bias 0.0015 (depth) that ToonRenderer had baked into the shader are replaced by the new ShadowMap setBias(depthBias, normalBias), getDepthBias and getNormalBias (in texels, default 1 and 1). They are multiplied by the world size of one texel (light matrix width / resolution) and the 1.5 texel radius of the 3x3 PCF, and a slope-scaled bias that grows as the light grazes the surface (2.5 texels x tan, tan clamped at 10) is added. The baked values did not follow the extent and resolution: at extent 40, faces grazed by the sun (84 degrees, down to 73 degrees at resolution 512) received their own shadow entirely (acne), and with near 1 and far 100 the depth bias was 0.15 in world units, so a caster 0.1 high cast no shadow at all (peter panning). A new Chrome test (tests/graphics3d/shadowbiaschrome.test.mjs) checks both. Point and spot light shadows (ShadowAtlas) already use a normal bias scaled by texel size and slope and are unchanged.
- Toon instance buffers shared by several passes (in the style of Unity's Graphics.RenderMeshInstanced with GraphicsBuffer and Godot's MultiMesh): added ToonDrawQueue.addMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, options). The body and outline shell, the shadow depth and the screen-space outline's line target share a buffer uploaded once with ToonRenderer.createInstanceBuffer and do not upload it again. (addMeshInstanced culls per instance and the body, shadows and line target each upload the same array every frame) ToonScreenOutline.drawMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, lineId, options) draws line IDs with the same buffer. The per-instance line ID is read from the new reserved instance layout name instanceLineId (size 1, TOON_INSTANCE_LINE_ID_NAME, its location is the last user attribute location TOON_INSTANCE_LINE_ID_LOCATION, with it up to two user attributes fit, ToonInstanceLayout.hasLineId), otherwise options.lineId. The emission slots of the bottom row of the affine matrix (3, 7, 11, 15) and the tint stay as they are. ToonRenderer.updateInstanceBufferRange(instanceBuffer, firstInstance, data) changes only part with bufferSubData (throws when out of range). A buffer's generation grows by 1 each time it is changed or deleted, and the shadow cache (ShadowUpdateMode.onChange) compares the buffer and generation in its caster record and bakes again on the frame it changed. It is culled as a whole by the bounds of the entire buffer (bounds, computed from positions and the largest scale on creation and on change). drawMeshInstanceBuffer now also culls as a whole with the same bounds (not culled if options.isCulled is false, and not culled when the layout has no matrix because the bounds are unknown). New functions readInstanceBufferSphere(mesh, instanceBuffer) and isSphereInFrustum(planes, sphere). Drawing with a deleted buffer draws nothing. Measured with the benchmark tool (tests/graphics3d/tooninstancebufferbench.mjs) on a miner mid style scene (tests/graphics3d/toonminerscene.mjs, 460 rocks of three kinds, twenty buildings, sun shadow, screen-space outline, Mac mini M2 Pro headless Chrome): uploads per frame (bufferData, bufferSubData) go from 6 to 0 with three instance batches and from 36 to 0 with eighteen batches split into chunks (the frame that changes one rock adds one bufferSubData), and draw calls stay the same (73, 118). The median script time (array and buffer alternated, nine times each) goes from 0.200 to 0.095 ms with three batches (the same at a machine load of 68), and with eighteen batches from 0.27 to 0.17 ms at load 4 (line target 0.085 to 0.035, instanced body draws 0.09 to 0.045, shadows 0.015 to 0.005 ms), while at load 55 to 69 it goes from 0.24 to 0.29 ms (only buffer splits between 0.145 and 0.34 ms per repeat, the cause is not found yet), and the frame that changes one rock goes from 0.635 to 0.355 ms (three batches). A Chrome test (tests/graphics3d/tooninstancebufferchrome.test.mjs) draws the same scene both ways for 75 frames and checks the pixels are the same to the byte (including per-instance line IDs and setLineColor colors, emission and shadows), that changing one rock shows on that frame and adds only one bufferSubData, and that the shadow cache draws nothing on unchanged frames and bakes again on the changed frame (deliberately not reading the line ID is caught on the first frame).
- Toon draw queue auto-instancing and a frame block (in the style of Unity GPU instancing and the SRP Batcher, and Unreal auto-instancing): ToonDrawQueue groups plain meshes (addMesh) that end up next to each other after sorting and share the model and the material values (the same material block; separate option objects are fine) into one instanced draw (drawElementsInstanced). The body, the outline shell, the shadow depth (drawShadows, and every tile of drawLocalShadows) and the line pass of the screen-space outline use the same groups. The matrices go into a batch slot instance buffer, which is uploaded again only when its values change (the body and the outline shell share a slot, so still objects upload nothing). The tint is 1 and the emission 0, so the screen is byte-identical to drawing each mesh on its own (the instanced shader path is the same arithmetic in the same program and only reads the model matrix from attributes). The line pass culls and adds to the focus distance in the order things were added, then draws the meshes with the same model and line settings (hasCreaseLine, hasScreenOutline, indexStart, indexCount) together, with a line id per instance; things it does not group keep their place in the added order. Meshes are not grouped when the material (ToonMaterial), the model, the material values, the textures, the light set or the drawn range differ, when the winding is flipped (negative determinant, isMirrored), when they have bone matrices or onBeforeDraw, or when they are transparent (transparent things are still drawn one at a time, far to near). Off-screen meshes are culled one by one first. The material block is now the fourth sort key (material, model, base color texture, material block) so that equal looks end up next to each other. The line pass uploads its instanced, instanceLineIds, skinned and lineFlags uniforms only when they change. The eighteen frame values that every program uploaded every frame (view projection, light matrix, camera position and forward, view rotation, camera roll, HDR, sun shadow switch, strength, texel and bias, outline distance scale and fade distance, point light shadow atlas and tiles, screen origin of the ambient occlusion texture) now live in one std140 block ToonFrame (binding 2): the values are written once per pass and, like the material blocks, a block with the same values is looked up and bound (built buffers are never modified, so nothing is uploaded while the camera and lights stay still; a first version that rewrote one buffer with bufferSubData every pass made the frame that bakes an onChange shadow differ from everyFrame, which the shadowcachechrome test caught; the cause was not isolated). A Chrome trace shows why: before this change, 2.05 ms of the 2.94 ms frame script time of the lobby-like scene was the renderer waiting for room in the GPU process command buffer (CommandBufferHelper::WaitForAvailableEntries) while the GPU process was busy decoding the commands (2.89 ms), so the frame time is set by the number of GL calls and draws, not by JavaScript. Measured (Mac mini M2 Pro, headless Chrome, alternating three times with the copy from before the change, one-minute load average 5.5 to 8.9): the lobby-like scene goes from 4929 to 1761 GL calls per frame, draw calls 773 → 276 (renderer draw calls 484 → 230), uniform calls 2980 → 383, vertex array binds 388 → 277, texture binds 205 → 205, program changes 41 → 41, buffer uploads 0 → 38, block binds 0 → 163, median script time 1.36 → 1.02 ms, and in the trace (40 frames with tracing on) the frame script time goes from 2.94 to 0.66 ms, GPU process command decoding from 2.89 to 0.64 ms and the renderer waiting for the command buffer from 2.05 to 0.15 ms. The Miner mid-like scene (instance buffers, six chunks): GL calls 849 → 453, draw calls 118 → 67, uniform calls 395 → 92, script time 0.41 → 0.10 ms. Both scenes and the five toon examples (toonstyle, toonshowcase, toonview, toonmaterial, toonfx) are byte-identical to before. A Chrome test (tests/graphics3d/toonautoinstancechrome.test.mjs) checks that only the same model and material values are grouped and that a different material, model, tint or flipped winding is not (the list of instance counts), that the screen is byte-identical to a draw queue that does not group, and that a batch slot is not uploaded again when the matrices stay the same.
- Toon screen outline batch slots (ToonScreenOutline.drawMeshBatch, in the style of Unity GPU instancing keeping instance buffers across frames): the line pass auto-instancing batches used to upload into the per-mesh instance buffer (mesh.instanceBuffer) every frame, while the body side kept its values in batch slots and skipped equal ones. The line pass now has its own batch slots too (a buffer per slot and a vertex array per mesh; the draw queue hands out slot numbers in the same order every frame) and uploads nothing when the matrices and line ids equal the previous frame (the line id lives in the tint column, so the values differ from the body slots and the slots stay separate). The code that builds a body vertex array moved into a module function that both sides use (the renderer behaves as before). Measured (headless Chrome, Mac mini M2 Pro, line pass bufferData count and bytes per frame, before to after): lobby-like scene 30 calls 21840 bytes to 1 call 720, room-like scene 36 calls 17280 to 12 calls 5760 (matrices change every frame in that scene, so the same count as the body side), Miner-like scene (instance buffers, six chunks) 2 calls 1520 to 0. The screen hashes of frames 6 and 11 of the lobby, room, room moving and Miner scenes equal the ones before the change. A Chrome test (tests/graphics3d/toonlinebatchchrome.test.mjs) checks that a still frame uploads nothing in the line pass and keeps the same screen, and that changing one matrix uploads only that batch and the screen is byte-identical to a fresh draw.
- Toon screen-outline batching of mirrored items (ToonDrawQueue, the isMirrored slot of ToonScreenOutline.drawMeshBatch, for games that draw a reflection by queueing the same actor again with a matrix flipped about the floor): items whose winding flips (a negative determinant or isMirrored) were drawn one by one, in the screen-outline board only (the body, the outline shell and the shadow already batched mirrored items among themselves). The screen-outline board now batches mirrored items of the same mesh and line style into one instanced draw too, and every item in a batch is drawn with the same winding (frontFace is set once per batch). Splitting the Aberrant lobby (Mac mini M2 Pro, 2560x1440, 78 mirror items) shows the mirror's 1.55 ms of GPU time is not the screen-outline board (skipping it: 6.90 vs 6.97, the same), not shadows (never queued), and not overdraw (moving the mirror to the end of the body pass: 6.94, drawing everything front to back: 7.10); it is the shader work that paints the mirror's pixels in the body pass (drawing the mirror's body with the depth shader only gives 5.39, the same as 5.41 without the mirror; a flat color gives 5.75, no lighting 6.12, no point lights 6.76, and turning off shadows, specular and rim light or removing ambient occlusion changes nothing). So the only saving that keeps the screen identical is on the CPU side: the renderer thread time went from 1.72 to 1.39 ms. The Chrome test (tests/graphics3d/toonautoinstancechrome.test.mjs) checks that three mirrored items become one batch in the screen-outline board too, and that the screen is byte-identical to the one drawn without batching.
- Toon ambient occlusion (screen-space AO, GTAO: Jimenez, Wu, Pesce, Jarabo 2016 "Practical Realtime Strategies for Accurate Indirect Occlusion", applied only to indirect light like Unity URP SSAO): added ToonPostProcess.setAmbientOcclusion(isEnabled, intensity, radius, resolutionScale) (off by default, intensity 0.5, radius 0.5 world length, half resolution), getAmbientOcclusion, isAmbientOcclusionEnabled, drawAmbientOcclusion(lineTarget, viewMatrix, projectionMatrix), getAmbientOcclusionTexture, getAmbientOcclusionPrepass, and ToonRenderer.setAmbientOcclusionTexture, getAmbientOcclusionTexture, ToonDrawQueue.setPostProcess, getPostProcess. For each half-resolution cell it turns four screen-space slices, finds the highest horizon six steps to each side, and integrates the cosine-weighted visibility with the projected normal in closed form (falloff from 0.6 times the radius to the radius). Slice angles and steps are scattered with interleaved gradient noise (Jimenez 2014) as a fixed pattern, so a still screen does not shimmer. It blurs with 7 horizontal taps while preserving edges by tangent plane distance and normal angle, then blurs with 7 vertical taps in two columns while upsampling to full resolution, choosing by the pixel's depth and normal (Kopf 2007 joint bilateral style). Depth is resolved with the inverse projection matrix, so perspective and orthographic (raw matrices given with setMatrices too) both work. Normals and depth reuse the screen outline's line target, and scenes without outlines draw only the line target with no lines (ToonScreenOutline skips seeds and flooding when both outline and crease widths are 0, and drawOutline draws nothing). ToonDrawQueue computes it after the line target and before bodies, sets it on the renderer and clears it after endFrame. The body shader switches to a body program with TOON_AMBIENT_OCCLUSION defined (sharing the outline and shadow depth programs) and multiplies the visibility at the screen position only into the ambient light (sky and ground light). Sun bands, fill light, point lights, specular and rim light stay as they are, so the bands stay clean. Transparent things and surfaces whose depth differs from the line target (by more than 2^-16) are not multiplied. The texture unit is 16 (materials that use all 8 material textures are drawn without AO on devices with 16 fragment shader units). The engine's existing AmbientOcclusionEffect resolves depth only from a perspective field of view and takes RGB normals with coverage alpha in a hemisphere-sample form, so it does not fit orthographic cameras and the line target (octahedral normals) and was not used. Cost (test scene 640 x 360, Mac mini M2 Pro headless Chrome): GL calls per frame go 92 → 249 in the scene without outlines (draws 5 → 12, four prepass draws and three AO passes) and 278 → 368 in the outline scene (draws 14 → 17, only the three AO passes), and body program switches do not increase (the AO body program takes the default body's place). The frame wall clock waiting for the end with readPixels is 0.20 ~ 0.41 ms off and 0.49 ~ 0.80 ms on (wall clock because there is no GPU timer extension, larger resolutions not measured). Open surfaces divide visibility by 0.96 and clamp at 1, so they are exactly 1 and the screen stays the same. With it off, bodies are drawn with the default body program, which does not read the texture (the ambient expression is unchanged), so the screen is byte-identical to before. A Chrome test (tests/graphics3d/toonambientocclusionchrome.test.mjs) draws a room corner, a crate and a two-legged robot in perspective, orthographic and with outlines, and checks that off and turned-on-then-off screens are byte-identical to the repository before the change (TOON_AO_BASE_PATH), that with it on the wall and floor junctions, beside the crate and under the robot's feet get darker while open floor stays the same, that the sun band edge on the robot head is byte-identical, and that the AO from the outline's line target equals the AO from the prepass.
- Toon outline low steps (in the style of Unity and Unreal depth-normal edge detection, which matches the threshold to the measurement error): when ToonScreenOutline separates occluded silhouettes within the same ID, it now uses the distance of the occluding pixel from the occluded pixel's tangent plane. Until now it used the smaller of the two pixels' tangent-plane distances; when the occluding side is the silhouette of a round surface, its tangent plane contains the line of sight, so the distance shrank below one pixel and lines such as the seam of a dome sitting on a body broke into dashes. The fixed margin added to the threshold (twice the pixel size at that depth) is replaced by a margin proportional to the measured error: the angular error of the 8-bit octahedral normal (at most 0.0165 rad, measured over 2 million random samples) x the distance between the two pixel positions, one pixel x the sine of the angle between the two normals for pixels on either side of a crease, and one step of the 24-bit depth. So a step between two parallel faces is caught even when it is lower than one pixel, and slanted planes and bumpy surfaces only get a margin as large as the normal error. Added the margin factor setDepthMargin, getDepthMargin (default 2) and getDepthThreshold. The normal target stays RGBA8 (two 16-bit channels would give an angular error of 0.00006 rad but double the line-target writes and seed reads, while the 8-bit error term is 0.02 of a pixel on a face at 45 degrees and does not get in the way of separating steps). With the defaults, of the six engine examples (toonstyle, toonview, toonfx, toonpost, toonshowcase, toonmaterial) only toonstyle changes, where the two ends of the donut's inner silhouette continue 16 pixels further; the others are byte-identical. In scenes of low steps, slanted planes and bumpy surfaces built with a single ID (perspective and orthographic, DPR 1, 2, 3), at a threshold of 0.05 the gaps in the silhouettes of round surfaces and rocks over the floor are joined (-0.1 ~ +13 % line pixels, the decrease being at most 34 pixels at the ends of the glass panel's lower edge) and no stray lines appear inside planes and rocks.
- Direct lighting strength for toon ambient occlusion (in the form of Direct Lighting Strength in Unity URP SSAO and HDRP ScreenSpaceAmbientOcclusion.directLightingStrength): added a fifth argument directLightingStrength (0 to 1, default 0) to ToonPostProcess.setAmbientOcclusion, getAmbientOcclusionDirectLightingStrength, a directLightingStrength field in getAmbientOcclusion, a second argument to ToonRenderer.setAmbientOcclusionTexture and getAmbientOcclusionDirectLightingStrength. After the band (brightness step) is chosen, the body shader multiplies the diffuse and specular of the sun band light, fill light, point lights and spotlights by 1 - strength x (1 - visibility). URP multiplies the direct light color (light.color) by lerp(1, ssao, strength), so diffuse and specular drop together, and HDRP applies the same strength to direct diffuse and direct specular. Rim light, glow, matcap and angel ring stay as they are, and the ambient light is still multiplied by the full visibility. It does not touch the band coordinate, so band edges do not move. The value is uploaded in ambientOcclusionDirectLightingStrength at the end of the ToonFrame frame block (slot 168, block 168 → 172 floats). In scenes with strong sunlight, corners were hardly visible when only the ambient light was multiplied; the strength makes them stronger. Strength 0 and off are byte-identical to before (six screens of the test scene: perspective, orthographic and outlines, on and off). A Chrome test (tests/graphics3d/toonambientocclusionchrome.test.mjs) checks that with strength 0, 0.25, 0.5 and 1 the darkening of the wall corner grows 4.9, 5.9, 7.3, 9.8 and under the robot's feet 4.2, 6.0, 8.1, 12.1, and that open floor and the robot head (sun band edge) stay byte-identical to off even at strength 1.
- Opacity layer (group opacity like CSS opacity): Graphic's beginOpacityLayer and endOpacityLayer (Rust edition begin_opacity_layer, end_opacity_layer) gather what is drawn between them in a screen-sized buffer and lay it down at once with the current global alpha. A node with setOpacityLayer(true) (Rust edition set_opacity_layer) and opacity below 1 is drawn with its descendants as a layer, so overlapping children do not show through each other (the same as Chrome CSS opacity). Clips (Mask) inside the layer still work and layers can be nested. Both engines are the same. The Rust edition's desktop Pane draws CSS opacity with this layer, matching the web DOM. In headless Chrome the overlap was (64, 0, 128) without the layer and (0, 0, 128) with it, so the lower box does not show through
- GameScene loading (the same as the Rust edition): the minimum loading time is measured with the engine clock (TimeManager.getRealtimeSinceStartup) instead of Date.now, and if the engine clock has not started yet (before the first frame) it is measured from the first loading screen frame. A press on the loading screen is read from engine input (InputManager.isTouchPressed) instead of window pointerdown, and drawOnLoad looks at it every frame.
- Developer tools memory fields (the same rule as the Rust edition): all three fields are "(N/A)" if the in-use and reserved heap of performance.memory cannot be read, and only that field if just the limit (jsHeapSizeLimit) cannot be read. The Rust desktop shows values with the same meaning read through operating system APIs in the same fields.
- Action: added startWith(target) and stepWith(target, timeDelta), which pass the target every time without holding it (paired with start_with and step_with in the Rust edition). start(target), step(timeDelta) and getTarget still hold the target and pair with start(node_tree, Some(node_id)), step(node_tree, time_delta) and get_target in the Rust edition. The inner actions of repeat, forever and loop run with startWith and stepWith like the Rust edition and do not hold the target.
- Input field context menu: right-clicking a direct-touch field (setUseDirectTouch) opens the same engine context menu as other fields instead of the browser edit-field menu. (the default action of the DOM input's contextmenu is blocked) The menu gains select all (when there is text), and UIInputFieldMenuAction.selectAll is added. It has the same four items as the Rust edition
- The input field context menu is drawn by the engine: the right-click context menu is no longer a DOM element attached to body (CSS box-shadow) but is drawn on the canvas as the last child node of the root (a UIInputFieldContextMenu component). It follows the same code path and the same sizes as the Rust edition (width 140, item 34, 14px text, corner 8), and its shadow bakes CSS 0 4px 16px rgba(0, 0, 0, 0.18) as a sigma 8 Gaussian like Blink (new src/core/blurshadow.js, the same math as the Rust core/blurshadow.rs). The menu is placed in view coordinates and follows the view scale. The arguments of showContextMenu changed from (clientX, clientY) to viewPosition (a Vector2 in view coordinates). Right-clicking outside the field closes an open menu.
- FBX with several materials: an FBX mesh with several materials (the Materials of LayerElementMaterial, MappingInformationType ByPolygon or AllSame) is split into sub-meshes by each polygon's material number and drawn as one drawable per material. (three.js FBXLoader groups, Unity and Unreal sub-meshes) Before, the material number was looked up by polygon vertex index instead of polygon index, and each mesh was drawn with only the first material of its owner node, so the Quaternius mannequin (M_Main, M_Joints) came out all orange. Added the static function SkinnedModel.splitFbxCornersByMaterial, materialName (the FBX material name, as with glb) on the FBX mesh description and drawables, and name on FbxLoader materials. The same as the Rust edition. Document images ancient-mountain, and shader-sprite and screen-effect after the shader hash change, were captured again (1280 x 720, cwebp -q 85). The bundle and the UI editor were rebuilt.
- Engine.alert, confirm, prompt (and alertAsync, confirmAsync, promptAsync), isModalDialogOpen: with the same names and behavior as the Rust Engine, they open a dialog drawn by the engine on top of the canvas (the same look as the Chrome tab modal dialog, with the title "This page says" and button labels in the browser UI language) and return a ModalDialogHandle (isFinished, getResult, isConfirmed, getPromptText, setCallback). The browser window.alert, confirm and prompt are not called. The handle finishes when the dialog is answered; while it is open isModalDialogOpen is true and the engine does not update scenes (the frozen screen is still drawn and only the dialog receives keys). The shadow bakes the two Chrome bubble_border layers with the new src/core/blurshadow.js. New modules src/core/modaldialog.js (ModalDialogKind, ModalDialogResult, ModalDialogHandle) and src/core/browseruitext.js (the Chrome translation table, the same locale selection as the Rust edition). The DevTools Local Storage tab also asks with the engine dialog instead of browser dialogs (same as the Rust DevTools).
- Scene.setTouchDispatchEnabled(isEnabled), isTouchDispatchEnabled(): a switch for the scene's default touch passing (tickTouch passing to nodes through the raycaster). Same as the Rust SceneBase.set_touch_dispatch_enabled. Same effect as setTouchRaycaster(null), and the raycaster is kept.
- SpriteAnimator: in the same form as the Rust engine, there is the static SpriteAnimator.play(node, clipName, options) (formerly playOnNode; plays with the node's animator and puts the first frame in right away) and the instance playClip(clipName, options) (the Rust play_clip). The instance play is removed. (To migrate: change the instance animator.play(clipName, options) to animator.playClip(clipName, options))
- InputActions: like the Unity Input System, it updates once in update at the start of the frame and reads the same values within that frame. readGamepadStick and readMoveAxis no longer look at the input manager again when reading, they read the move keys and pad axes recorded in update. (same as the Rust engine)
- Sine, cosine, tangent: the engine Math.sin and cos (a 10-term Taylor series) and tan (sin / cos) now call the browser Math.sin, cos and tan. Chrome 158 returns correctly rounded results (the double nearest the true value), and the Rust engine computes the same, so both engines give the same bits for the same input. Last digits change. (For example sinusoidal.inOut at 0.5 is 0.49999999999999994 instead of 0.5000000000000017, and the timeline color #ff000080 → #0000ffff at 1 second is #80007fc0 instead of #7f0080c0)
- Shader hash: hash21 (ScreenEffect, ShaderSprite) and hashPoint (toon VFX) now use an integer hash that mixes the float bits with the fmix32 finalizer of MurmurHash3 (Austin Appleby, public domain). It replaces forms whose source text could not be confirmed (Hash without Sine and the sin hash that spread from Shadertoy). The patterns of film grain, glitch, value noise and toon VFX noise change. (The brightness distribution and how to use them are the same)
- Human skin environment BRDF: instead of the Karis approximation, it uses a formula fitted to a split-sum integral the engine computes directly (GGX, Smith Schlick-GGX with k = alpha / 2, Schlick Fresnel). The RMS error against the integral table drops from 0.071 in scale and 0.029 in bias to 0.002 and 0.006. The environment reflection changes. (Roughness 0.5 head-on gets brighter, 0.72 to 0.89, and roughness 1 head-on gets darker, 0.45 to 0.31)
- Scene touch: a node's widgets receive touches regardless of the scene type. (Like Unity's EventSystem, same as the Rust version's SceneBase.tick) Scene.tickTouch first hands the touch to the frontmost pressable node through the scene's touch raycaster (the TouchRaycaster made in create), and then calls the touch hooks (touchPress, touchMove, touchRelease, touchCancel, touchWheel). The wheel is also handed to the frontmost scroll area at that position. Added Scene.setTouchRaycaster(touchRaycaster or null), getTouchRaycaster(). UIScene and GameScene keep handing touches to their own TouchRecognizer in the touch hooks as before (the developer tools, fades and gameplay input checks sit before and after the hand-off), and the scene's default hand-off is turned off so touches are not handed over twice. (The getTouchRaycaster of both scenes is that TouchRecognizer)
- FbxLoader: strips the binary FBX type suffix ("\u0000\u0001Model", "\u0000\u0001AnimStack") from node (Model) and animation stack names. A clip name is "Take 001", not "Take 001\u0000\u0001AnimStack", and a bone name is "mixamorig:Hips". (In three.js FBXLoader, BinaryReader.getString cuts at the first null byte, and Assimp converts to "AnimStack::Take 001" and then FBXConverter strips "AnimStack::", "Model::"; the Rust version was changed too) Bone name matching when adding FBX animations to a model read from glTF (addAnimationsFromFbx*) also matches by these names.
- Folder cleanup: moved the grown-up features that were in src/experimental to their proper places. The folders are the same as in the Rust vanilla-engine. Games that use import.js keep working as is, and games that imported files directly by path switch to the new paths. (old path → new path, contents unchanged)
- src/experimental/graphics/.js (3D) → src/graphics3d/.js
- src/experimental/graphics/toon/.js (toon 3D) → src/graphics3d/toon/.js
- src/experimental/graphics/fullscreenpass.js → src/core/fullscreenpass.js
- src/experimental/animation/animator.js, timeline.js → src/animation/animator.js, timeline.js
- src/experimental/action.js → src/animation/action.js
- src/experimental/indicator.js → src/misc/indicator.js
- src/experimental/visual/visual.js → src/misc/visual.js
- src/experimental/bunchasset.js → src/resource/bunchasset.js
- src/experimental/visual/visualasset.js → src/resource/visualasset.js
- src/experimental/collection/.js (List, Dictionary, Queue, Set, Stack) → src/base/collection/.js
- src/experimental/camera.js → src/deprecated/camera.js
- src/experimental/aabb.js, transform2d.js, graphics/gl2d.js, graphics/webgl2.js (dead code, not exported) → src/deprecated/
- Engine: applies view coordinates (viewManager.applyViewRect) before each scene draws (preDraw, or drawOnLoad while loading). Until now scenes were called with no transform applied, so scenes that directly extend Scene (not UIScene or GameScene) drew in the actual pixels of the drawing buffer, and on screens with a device pixel ratio of 2 (Retina Macs, high-density phones) they drew only in the top-left 1/4 of the canvas and were also out of line with touch coordinates. Ratio 1 screens and UIScene, GameScene are unchanged. How to migrate: scenes that drew in actual pixels call graphic.setTransform(1, 0, 0, 1, 0, 0) in preDraw
- UIInputField canvas mode word movement and deletion: like Chrome, Ctrl on Windows and Linux and Option on Mac, with the left and right arrows (with Shift, extends the selection), Backspace and Delete, moves and deletes by word. (On Mac also Option + Ctrl + Backspace, B, F) Positions follow Blink's NextWordPosition, PreviousWordPosition; going right lands before the next word only on Windows (on Mac and Linux, at the end of the current word), and on Mac a selection being extended does not cross its anchor end. If there is a selection, only the selection is deleted. (Previously Ctrl + arrow did nothing, and Mac Option + arrow moved one character at a time)
- UIInputField word boundaries: like Chrome, a period joins only between digits ("www.example.com" is five pieces, "3.14" is one word), and a colon does not join. (Chromium ICU wordbrk.patch; double-clicking in the DOM input selects the same word as Chrome even in browsers other than Chrome)
- UIDocument: writes node and component type names in the document as the name registered in the table instead of the class name (constructor.name). The document is the same even if a bundler shortens class names (esbuild --minify). (Only unregistered types use the class name as before; until now, in a minified bundle WorldNode was written as something like "o" and could not be read back)
- UIDocument.registerEditorTypes(): registers the types the UI editor registers (35 components, 12 node types) at once. Games that read documents saved by the editor call it once before fromJsonText. Names already registered are left as they are. (Same as Rust register_editor_types) Reading a node type or component not in the table reports it with console.warn. (Until now they were silently read as WorldNode or skipped, so UIInputField, UIScrollBar became empty nodes and UISnapScrollView was dropped)
- UIDocument: when reading back, components and children made by the node constructor or a widget (like UIWindow's title bar, or the Sprite that UIImageView attaches) receive the document's values if their order and type (name for children) match from the start of the document, instead of being made again on top. Reading and writing again gives the same document. (Until now they were made again on top, so reading a UIWindow gave two sets of nodes and components; same as Rust)
- Version: extends the engine Object. (version.js did not import Object and only re-exported it, so it extended JavaScript's built-in Object)
- Enum.readonly(dictionary): returns the frozen dictionary. (Like Object.freeze; until now undefined)
- Format.formatCompactNumber: moves up to the next unit when rounding reaches 1000. (999999 is "1M", not "1000K", same as Intl's compact notation)
- Singleton: throws when new is called again on a class that already has an instance. Get it with getInstance(). (The subclass constructor re-ran its own fields and constructor body on the first instance returned by super(), overwriting the first instance, and it was a TypeError if there were private fields)
- Node.setParent, addChild: does not attach under itself or its own descendants and returns false. (If it formed a cycle, upward computations like isActiveInHierarchy never ended; what used to throw an empty error for itself is also false now) true if attached or detached. removeChild detaches only when it is its own child. (Same as Rust NodeTree)
- ObjectPool.release: releasing an object that has already been returned and is idle is ignored. (Releasing twice made two users borrow one object next time)
- Platform.getSafeAreaRect(canvas): measures with the canvas CSS size (clientWidth, clientHeight). The returned rectangle is all in CSS pixels, and its width and height are 0 or more. (The insets are CSS pixels but were subtracted from the drawing buffer size width, height, mixing units on high-resolution screens)
- Color: stores components as they are without clamping them to 0 ~ 1. (HDR colors above 1 such as glowing colors, like Unity Color, same as the Rust version) Only when output as 0 ~ 255 text (toRGBAString, toHEXString) are components clamped to 0 ~ 255 and the rgba alpha to 0 ~ 1. How to migrate: code that created colors with 0 ~ 255 values like new Color(255, 128, 0) switches to Color.createFromBytes or 0 ~ 1 values. (Previously they were clamped to 1 and came out white; now they are stored as is)
- UINode: isInteractable, setInteractable, contains, getWorldCorners, convertToViewPosition, touchPress, touchMove, touchRelease, touchCancel. A UIButton attached to a UINode is pressed at the position the solver resolved. (TouchRaycaster hit only WorldNode and UINode had no press test, so it could not be pressed; in Rust UINode is a component of WorldNode, so it was always pressable) UIButton turns interactable on when attached, if the node has setInteractable
- UIScrollBar: auto hide hides the node while keeping it enabled instead of disabling it. (When disabled its update stopped, so it did not come back even when the content grew longer or setAutoHide(false) was called) While hidden it does not draw or receive presses. Added isAutoHidden()
- LanguagePack, UIFont: since JsonAsset.load now rejects on failure, a fetch failure is taken as a failed load. (Warns and gives null, false as before) Brought the list form in the UIFont header comment in line with the code ({ fonts: [...] }, { faces: [...] })
- ShaderSprite.isDrawnInsideContent: true even when flipped. (Same as Sprite, which now draws inside the content area even when flipped)
- Sprite.setImage: also accepts HTMLCanvasElement, OffscreenCanvas. (Previously it ignored anything other than HTMLImageElement and ImageAsset; an OffscreenCanvas passed through UIImageView.setImage now draws too)
- Graphic.drawPolyline, drawLine, drawLineLoop, drawStrokeRoundRect, drawConvexPolygon: when the vertex buffer (4096 vertices) fills up, draws what has accumulated and keeps writing. Previously everything from the 683rd segment (the 1366th triangle for convex polygons) on was dropped.
- Graphic.setCullingEnabled: brought the default in the header comment in line with the actual one (on, true).
- SoundSystem: if a sound table row has no volume, plays at 1. (Previously it became NaN, so 0, and no sound played)
- TouchRaycaster: hits nodes of any type instead of only WorldNode. Every node with isInteractable and contains is hit and receives presses.
- ParticleSystem.applyDescription: reads the description's imageDataUrl (the data: URL of the image chosen in the particle editor) and sets it as the particle image. (null or empty text removes the image) The chosen image comes back even when a saved description is loaded again in a game.
- ParticleEmitterShape: brought the edge direction in the header comment in line with the actual one (downward +y).
- FontAsset.load(assetPath): it only set the path and did not load; now it actually loads. Calls loadFont with the file name minus its extension as the family name. ("DOSGothic" for "assets/DOSGothic.woff")
- JsonAsset.load: rejects when the fetch or parse fails. (Same as TextAsset, ImageAsset) How to migrate: code that assumed it resolves even on failure and checked whether data was null after await is wrapped in try/catch. SpriteAtlas.load still reports and resolves on JSON failure.
- Asset.unload: it returned undefined when loaded and a resolved promise when not; now both branches return nothing. (Subclasses that override it too, same as Rust)
- LayoutSolver: an expression containing a term with no variable (LayoutTerm(null), value 0) threw a TypeError in updateVariables. Such terms are now skipped like terms with a coefficient of 0. (5 == 0 with only such terms left is a contradictory constraint; 0 == 0 is accepted)
- UISnapScrollView: setSnapToNearest, setVelocityThreshold only stored values and were not used in the snap computation. Now in one-item mode (default), on release, if the drag velocity is at or above setVelocityThreshold (default 200, scroll offset pixels per second), it moves one item in the direction of the velocity regardless of the dragged distance (fling); otherwise it decides by the setPageChangeThreshold ratio as before. setSnapToNearest(true) does not clamp to the item range while dragging, and on release the snap offset goes to the nearest item. Added getDragVelocity(). (The scroll-axis offset velocity of the last dragged tick, negative toward the next item) The existing behavior for slow drags is unchanged
- ImageScroller: setImage(ImageAsset) used ImageAsset without an import, giving a ReferenceError. Now for an ImageAsset it holds its getImage(), and other images (HTMLImageElement, canvas and so on) are held as they are. (Works even where there is no HTMLImageElement global)
- NodeLayout: the builder's anchoredPosition was applied before attaching to the parent and ignored the anchor. Now build applies it after attaching to the parent, relative to the anchor point of the parent's contentSize. (The anchor is the anchor at the time anchoredPosition is called, and a localPosition called later wins, same as the Rust version) Removed the leftover old "Creates a layout instance" comment block with no declaration
- Camera2D: the usage line camera.follow([heroPosition], 6) in the header comment was missing timeDelta, so using it as is gave a NaN position. Fixed to camera.follow([heroPosition], 6, timeDelta). Gave setPosition its own header comment. (Previously the "Accessors." section header was read as its description)
- LanguagePack: if a row in the languages.json read by loadLanguageList had no aliases, matchLanguageTag threw a TypeError. Now the list read from the file also goes through setLanguageList. Rows whose code is not text are dropped, missing aliases and countries become empty arrays, and text is lowercased. (Same as the Rust version)
- DEVTools: Show FPS in Settings was only saved and never used. When on, it draws an "FPS
" box (the frame count of the last 1 second, canvas-native coordinates) at the top left of the window even with the panel closed. When the panel is visible, it draws on top of the panel - UIListView: filled in descriptions, @param, @returns and examples (a 500-row template list, a create function, end notification) for the public API
- UIInputField cursor and deletion: the left and right arrows and Delete move and delete by grapheme cluster (extended grapheme cluster, Intl.Segmenter) like Chrome. Backward deletion ports Blink's BackspaceStateMachine, deleting one code point at a time but deleting CR LF, emoji variation selectors with their base, skin tone modifiers, ZWJ emoji, flags, keycaps and tag sequences as a whole. Fixed a bug that split surrogate pairs. (Matches the execCommand results of a headless Chrome textarea)
- UIInputField: with a selection, the left and right arrows without Shift collapse to the start or end of the selection like Chrome. The pressed position (measureIndexAtLocalX) lands only on grapheme cluster boundaries. Giving moveCursor a position in the middle of a surrogate pair treats it as after that character.
- Added UIInputField.deleteRange(startIndex, endIndex). deleteCharAt(index) deletes one grapheme cluster starting at that position. (Previously one UTF-16 unit)
- UIInputField maximum length: setText truncates up to where it does not split a surrogate pair, and insertion (replaceSelection, paste, typing) inserts only as much of the inserted text as the remaining length allows, like a Blink input field. (Previously the whole value was truncated, which could delete the text after the cursor)
- UIInputField.setFont uses the fontFace of a FontAsset when given one. (Previously it held the FontAsset as is, so before the font loaded the CSS font for text measurement was broken) Text measurement, selection and cursor drawing build it with the same buildFontString as UILabel.
- UIInputField DOM input, like a Chrome input field, selects a word (on Windows including the trailing space) on a mouse double-click and the whole text on a triple-click, and dragging after that extends by word. The click count is the detail of the canvas mousedown.
- List, Dictionary: changed the callbacks of find, findAll, which received the index or key as this, to the standard form. List takes callback(element, index, list) (like Array.prototype.find), Dictionary takes callback(value, key, dictionary) (like Map.prototype.forEach). How to migrate: where a function callback read the index or key from this, receive it as the second argument. (Callbacks that used only the first argument keep working)
- Animator: completed the skeleton that did not change states into a standard state machine. AnimationState gets speed (setSpeed, getSpeed), looping (setLoop, isLoop, follows the clip when null), getDuration, getNormalizedTime, getFrameIndex. AnimationTransition gets exit time (setExitTime, getExitTime, normalized time, below 1 on a looping state means every cycle), blend time (setDuration, getDuration, crossfade), setCanTransitionToSelf, canTransitionToSelf, conditions (addCondition(name, comparison mode, threshold), getConditions), isExitTimeReached, and from being null means from any state (Any State). New AnimationConditionMode (if, ifNot, greater, less, equals, notEqual). Animator gets parameters (setFloat, getFloat, setInteger, getInteger, setBool, getBool, setTrigger, resetTrigger, getTrigger, getParameters), play, findTransition, startTransition, isConditionSatisfied, getCurrentStateIndex, getCurrentNormalizedTime, getCurrentFrame, isInTransition, getNextStateIndex, getNextNormalizedTime, getNextFrame, getTransitionWeight. tick advances the state time, checks Any State first and then the current state's transitions in the order they were added, and takes the first one that matches (triggers used as conditions are reset; no new transitions are checked while blending). Starts in the first state added. How to migrate: setProperty, getProperty, getProperties are gone. Replace them with setFloat, setInteger, setBool, setTrigger and their getters according to the type. The internal Animation handler (getAnimation) is also gone. Read the selected frame with getCurrentFrame, getNextFrame and getTransitionWeight.
- Visual: added document text (setDocumentText, getDocumentText) and createNode. createNode builds a new node tree from the document and sets the root's local position to location. Filled in descriptions and examples for the public API.
- Localization.isRightToLeft: like setRightToLeft, reads in lowercase with underscores as hyphens. (It did not catch "ar_EG" as a right-to-left language)
- Material.createFromDescription: if an intermediate image cannot be decoded, deletes the textures built so far and rejects. createTexture builds the texture after the image is fully decoded, so if decoding fails no texture is left behind, and even if another texture is bound while waiting, it uploads to its own texture. (Previously it bound before waiting, so it could upload to another texture bound in the meantime)
- ShaderProgram: when fragment shader compilation or linking fails, deletes the shader (and program) built earlier
- UINode.addConstraint: constraints the solver did not accept (already added, contradictory) are not kept in the list. (The next setSolver stopped with the same error)
- UISpinner.calculateDotOpacity: with no dots (dotCount 0), it does not become NaN from dividing by 0
- UIListView.setHorizontal: when it changes, re-measures the scroll area and re-places the visible items on the new axis
- Camera (src/deprecated/camera.js): to be deprecated. Camera2D (src/misc/camera2d.js) covers everything including rotation and begin, end. import.js still exports it as Camera, and it may be dropped in the next version
- Moves general-purpose features that webgame-rimminer had built and used separately on the game side into the engine. (Game code was not touched; the game keeps using its own as before)
- Outline: a component that draws only the border. (Paint only fills the inside) Rounded rectangle border (setRoundSize) or circle border (setCircle); the line stays inside the content size. setColor(Color or "#rrggbb", "rgba(...)"), setLineWidth
- UIProgressRing: progress ring component. Following the node's shape (rounded rectangle; a circle when the roundness is half the size), draws the filled portion (setRatio) clockwise from the top center in the fill color and the rest in the background color. Perimeter points are computed only when the size, roundness or thickness changes
- UIHitArea: hit area expansion. UIHitArea.attach(buttonNode, minimumSize) places a transparent hit area as the sibling right behind the button, expanding its width and height to at least minimumSize. Pressing the expanded area calls the button's click notification, and it follows the button when the button is disabled or cannot be pressed. Tracks the button's position, size and pivot every frame. setClipNode can clip the expanded area to within a window or scroll area
- FrameProbe: slow device detection. After a wait period in seconds, observes frame intervals for a measurement period in seconds; the device is slow if 25% or more of frames exceed 1.4 times the target interval. (Constantly skipping every other frame, like 60 FPS on a 90 Hz display, is not counted as slow) restart, measureAgain; values are changed with setSeconds, setSlowFrameThreshold
- PointerCursor: mouse cursor. When enabled (PointerCursor.getInstance().setEnabled(true)), the engine sets the canvas cursor at the end of every frame. Over a UIButton (including while pressed) it is the button's cursor (pointer by default), otherwise the cursor set with setScreenCursor. registerImageCursor adds image cursors at 1x and 2x. Leaves the cursor untouched on touch devices. When disabled (default), behaves as before
- UIButton: notifies PointerCursor while the mouse is over it or it is being pressed. (Nothing happens if PointerCursor is disabled)
- Platform: isDesktopWeb() (not mobile, and not an iPad presenting as a Mac with multi-touch input), isCoarsePointer() (CSS pointer: coarse)
- ViewManager: getCssPixelScale(). How many CSS pixels one view unit spans on screen. (Used to compute the scale for enlarging only the UI layer on small screens)
- SoftShade, SoftShadeShape: soft shade component. Darkens the area behind text so it stays readable on bright backgrounds. Bakes a band (darkest in the middle, fading toward the top, bottom and sides) or a floor (vertical gradient, darkest at the bottom) into a small canvas and draws it stretched to the content size. Rebakes only when the size, shape, color or strength changes
- ShadowText: single-line text component with a shadow underneath. Bakes the text over the shadow into a single canvas and draws it, so the node's opacity applies to text and shadow as one layer. (With two Text layers, the shadow underneath shows through when faded) The shadow can be blurred (shadowBlur of setShadow), and on overflow the text shrinks down to setFitMinimumRatio to fit. Horizontal alignment and position use the same calculation as Graphic.drawTextEntry; vertical is centered. setFontFace, setTextDirection
- ShadowImage: image component with a shadow underneath. Draws the image (or an atlas piece via setImage(image, imageRect)) centered in the node preserving its aspect ratio, paints a shadow under the image's shape, and bakes them into one layer. setImageColor can tint the image a single color
- buildRGBAString(colorText, opacity): builds a canvas rgba color string from "#rrggbb" and opacity. (shadowtext.js)
- CameraGestures: camera gestures. Reads gestures for rotating, panning and zooming a 3D board or map independently from the canvas DOM events. Right mouse drag (horizontal rotates, screen width is one full turn; vertical tilts; releasing without dragging is a right click), middle drag (pan), two fingers (pan, pinch to zoom, twisting past a threshold rotates). Accumulated amounts are taken every frame with takePan, takeRotation, takeTilt, takeZoom, getZoomAnchor. isGestureActive during a gesture. Emulated mouse events right after fingers are lifted are ignored. setThresholds changes the thresholds and dispose detaches
- SoundSystem, setSoundSystem, readSoundSystem: background music and sound effects managed through a sound table. (Uses AudioManager's shared AudioContext and AudioAsset) Each row is { id, path or paths, volume, minimumInterval, isMusic, maximumVoices, pitchVariation, playSeconds, fadeOutSeconds }. Picking a recording different from the previous one among several, limiting simultaneous instances of the same sound, pitch variation, playing only the first few seconds and fading out, background music crossfade and continued playback, music and effect buses. Mute engages if any one of these holds: the user button, the page being hidden, window focus loss on touch devices (prevents iPhone audio freezing and repeating on app switch), or an external mute supplied via setExternalMuteProvider (platform SDK, ads); meanwhile the AudioContext is suspended. If it does not resume after unmuting, it is woken again periodically. setAutoplayAllowedProvider can prevent waking before a tap. update() every frame
- LanguagePack: language bundles kept as asset JSON. (Functions under the LanguagePack import name) Reads languages.json (language list, fallbackLanguage, and per language code, name, englishName, fontGroup, direction, aliases, countries, file) and the table for each language. If the language in settings is empty, uses the language given via setPreferredLanguageTag (reported by the platform), then the device language, and the default language if not in the list. A missing key falls back to the default language's text, and if missing there too, to the key itself. translate, formatText({name}), readTextDirection, isolateText (direction isolation), the html lang and the tab title (setDocumentTitleKey). setLanguagePaths sets the paths, and setLanguageLoadedHandler sets what to do after a language is loaded (fetching that language's font). Localization (in-code tables) is unchanged
- UIFont: groups font subsets for multiple scripts under one font name. (Functions under the UIFont import name) Registers a FontFace for each subset split by Google Fonts with that subset's character range (unicode-range), so only subsets containing characters used on screen are downloaded. The selected language's group is placed right before Latin so Han characters render in that language's font, while digits and English letters always use the Latin font. Weights are registered as only two, selected together through a range. Subsets for characters to be used are fetched in advance (loadUiFontText, requestUiFontText), and the first subsets are waited for only up to a set time. The remaining groups are fetched a little later. configureUiFont sets the name, list path, weights and wait time, and readUiFontFace reads the FontFace to give to Text and ShadowText
- ToastMotion, attachToastMotion, readToastSeconds: enter and exit motion attached to a notification node. show(text, seconds, applyText) slides in from the outer side (setEnterSide, top or bottom) while growing slightly and settling back, then after staying, floats up, fades out and disables the node. If different text arrives while shown, the previous one moves aside quickly; if the same text arrives again, only the time is refilled and it pops. Movement stays only around the placed position as the reference. readToastSeconds lengthens the stay time for longer text. (UIToast builds queued pill notifications by itself; this animates a notification node built by the game)
- ButtonMotion, ButtonMotionStyle, attachButtonMotion, setButtonMotionArea, shakeButton: button feedback. Attached after UIButton, it reads the button state and scales the node up and down around its center. The normal style grows on hover, shrinks while pressed and pops on release. The inset style (inside windows) does not grow; while hovered it brightens the background and adds a white inner border. When not pressable, shakeButton shakes it left and right. The style is set per button (setStyle) or on an ancestor node with setButtonMotionArea. Touch devices do not use hover. When there is no feedback, the node is left untouched so it does not conflict with other effects. To make decorations on the button light up in their own shape, set a function with setLitHandler
- ToonMesh(graphics3d/toon/meshbuilder.js): builds vertex arrays for drawing toon 3D (clay-like single-color material and outlines). Puts box, rounded box, cylinder, sphere, lathe, capsule, torus and octahedron shapes into MeshBuilder as one mesh, transformed by position, rotation and scale. Vertices are position 3, normal 3, color 3 (sRGB), material 2 (emissive, unlit), pattern 4 (pattern index and color, meaning defined by the shader). Outlines are stored separately as a shell pushed out by the same thickness at every point (inverted hull), pushed so it does not stick out too far at corners. Triangle winding is corrected using the normal so the outside is the front face. Skinned models store bone indices and weights separately
- ToonGlb(graphics3d/toon/glbmeshreader.js): reads GLB painted with material colors without textures into MeshBuilder arrays. (readGlbArrays, per node readGlbNodeArrays, node info readGlbNodeInfos) Reads baseColorFactor as sRGB, emissiveFactor as emissive, and outline and basic from material extras. Reads the skeleton (skin) and motion (animations, extras), and writeSkinPose computes bone matrices for a single moment. (Blending with the previous pose, sway scale) Separate from the engine's SkinnedModel (textured PBR)
- ToonRenderer(graphics3d/toon/toonrenderer.js): toon renderer that draws ToonMesh and ToonGlb arrays. Sun (direction, color) and ambient light blending sky and ground colors, cel shading bands with setBandCount, per-vertex emissive and unlit, per-model tint and opacity; the outline shell draws back faces only. For skeletons, bone matrices from writeSkinPose are passed to drawMesh as jointMatrices. (Up to 96, same as the engine SkinnedModelRenderer) beginFrame records the previous draw state and endFrame restores it, so it can be inserted between engine 2D drawing (after flushBatch). readProgramSources provides the sources to pass to ShaderWarmer. Rebuilt from the board renderer of webgame-rimminer with game-specific parts such as ground patterns and screen-space lines removed
- ToonPostProcess: HDR finishing. Applies BloomEffect to the scene drawn into a half-float RenderTarget, and outputs to the screen with exposure, approximate ACES tonemapping and sRGB gamma. (begin, end, setExposure, setBloom) Same setup as the Rust vanilla-engine
- Graphic.drawRoundRect: computes the cos / sin of the 36 vertices from a table built once at module load, and writes vertices directly from coordinates written into a reused slot instead of creating a Vector2 array. (Removes 72 trigonometric calls, 36 Vector2 and 4 corner objects per node per frame) The table is built with the same formula as before (cos / sin of engine base/math.js), so vertex values are bit-identical. buildRoundRectPositions also uses the table. (The returned Vector2 array is still newly created as before) drawRoundRect no longer goes through buildRoundRectPositions
- Graphic: writeRoundRectPositionData(rect, roundSize), drawRoundRectPositionData(color). Writes rounded rectangle coordinates into a module slot, and draws the fill from that slot. (Used by drawRoundRect)
- Paint.draw: instead of creating one Rect (including its inner Vector2) and a copy of the content size on every draw, reuses a single rectangle kept in the module and receives the size via WorldNode.copyContentSizeTo. The rectangle passed to graphic's draw functions changes when the next Paint is drawn. (Nothing in the engine holds on to the received rectangle)
- WorldNode: copyContentSizeTo(target). Writes the content size into target without a copy. For subclasses that override getContentSize (UINode etc.), writes the value that function returns
- pushTransform of TransformNode, WorldNode: reads position, scale, pivot and content size without copies. (Four Vector2 per node per frame) TransformNode.applyLocalTransform(graphic) applies the local position, rotation and scale. Subclasses that override those getters are still read through the getters as before
- TransformMatrix: rotate(0) and scale(1, 1) return without computing the matrix. (The result is the same; they are called on every draw even for nodes that do not rotate)
- Graphic.pushState / popState: instead of creating a matrix copy and a state object on every save, writes the current matrix object and its values into a slot pre-created for each stack depth. On restore, writes the values back into the matrix object from save time and makes it the current matrix again. So a matrix obtained via getTransformMatrix() is still the current matrix after restore. (Previously, restore switched to the saved copy, so a previously obtained matrix was no longer the current matrix)
- TransformNode.setLocalPosition / setLocalScale, WorldNode.setPivot / setContentSize: copy the values into the owned vector instead of cloning the given vector. Getters still return clones as before, so the owned vector does not leak out
- Rect: the constructor and create() no longer clone freshly created Vector2 a second time through setters. (Rect.create goes from eight Vector2 to two)
- Color.clone(): creates a new Color by copying rgba directly, without going through Reflection.clone. (Like Rect.clone, returns a Color rather than a subclass; there are no Color subclasses in the engine) Called on every draw in places such as setFillColor
- Reflection.clone: scans the list of property names that have both a getter and a setter only once per prototype and reuses it. (Previously walked the prototype chain on every call) Copy order and values are the same
- Graphic.drawVertices: looks up uniform locations (modelMatrix, mainColor, tintColor, globalAlpha) only when the shader program changes, rather than by name on every draw call. (uploadDrawUniforms) The default program's tint and global alpha are not uploaded again if equal to the last uploaded values. Uploaded values are forgotten at frame start (applySettings) and when the program changes, and are always uploaded for a swapped-in program (setShaderProgramOverride). If a game uploads the default program's tintColor, globalAlpha uniforms directly, the next draw call may not correct those values. (Nothing in the engine does so)
- Engine: Counts the maximum FPS limit (EngineConfiguration.maximumFramePerSecond) by the number of processed frames. The number of frames processed since counting started sets the slot of the next frame (start time + count × interval), and only frames arriving more than 4 ms before their slot are skipped. Backlog is processed on the next frame so the average reaches the maximum FPS. Previously, a frame was skipped if less than the interval minus 4 ms had passed since the last processed frame, and the reference was reset to the time of the processed frame, forgetting the backlog, so the limit was off when the refresh rate was not divisible by the maximum FPS. (At 60 FPS, 90 Hz skipped every other frame for 45, 144 Hz gave 72, 75 Hz skipped none for 75) When behind by more than one frame (window hidden and restored, etc.), does not catch up in a burst and restarts counting from that time. Processing a frame that arrives less than 1 ms before its slot restarts counting from that time, so on displays whose refresh rate is almost the same as the maximum FPS (60.05 Hz, etc.), small leads no longer accumulate into an occasional skipped frame. Changing the maximum FPS restarts counting. 60 FPS on a 60 Hz display and maximum FPS values that divide the refresh rate (30 FPS at 90 Hz, etc.) are the same as before.
- UIDocument: getReflectedProperties(component) exposes the list of a component's matching get (or is)/set properties. (Used by the editor's inspector) Added Outline, SoftShade, ShadowText, UIProgressRing to the component type table
- Rendering: Skips calls that rebind the same shader program and the same texture. Graphic remembers the program it last put in use and the texture bound to texture unit 0, and does not call useProgram, bindTexture when they are the same. (useShaderProgram, bindTexture) Batched drawing (flushBatch) and particle drawing (drawColoredQuads) no longer switch back to the default program after drawing and leave it to the next drawer to use its own program, so consecutive batches do not switch programs back and forth. The rendered result is the same. (Capturing the same frames with a fixed clock and random numbers from the examples uishowcase, uisample, spriteeffects, particleeffects, timelineshowcase and a test scene mixing external GL, ShaderSprite, ScreenEffect, two scenes and mipmap switching gives pixels identical to before the change with batching both off and on)
- Engine: Forgets Graphic's binding cache before each scene draws (preDraw, or drawOnLoad while loading). (External WebGL may have changed textures between the previous scene's draw and this scene's update)
- Text: Keeps the array of wrapped lines and re-splits only when the text, font, size, bold, italic, width or wrap mode changes, a web font finishes loading (loadingdone), or font faces are added to or removed from the document. (readWrappedLines) The per-word and per-character measureText on every draw is gone
- Sprite.draw: Removes the four Vector2 created on every draw (position, content size copy, flip, multiplied size) and the Rect when there is no image rect. Reuses module vectors, gets the size with WorldNode.copyContentSizeTo, and draws the whole image directly when there is no rect. Graphic.drawImageWithImageRect also no longer creates a Rect when there is no rect
- Graphic.beginClipRect: Does not copy the rect and transform matrix, writes the values into slots preallocated per clip depth. endClipRect copies only the values instead of making that slot the current matrix object. (popState restoring the matrix from begin is unchanged) Mask.beginClip also no longer creates a new clip rect
- TextStringTextureCache.getEntry: Does not build a key string on every lookup, compares the remaining values (mode, direction, scale, stroke width, color, font) in the per-string entry list. The key string is built once when baking and stored in the entry. (LRU order and limit, invalidateFontFaces are unchanged)
- ParticleSystem: Instead of removing expired particles one by one with splice (shifting the rest each time), compacts the living ones toward the front. (Draw order is unchanged) Image particles no longer create two Vector2 on every draw
- Graphic: isCullingEnabled(), isLocalRectVisible(rect) (whether a rect transformed by the current transform overlaps the drawing buffer), addCulledNodeCount(count), getLastFrameCulledNodeCount(). Added a culledNodes line to the engine statistics (useStatistics)
- HeatHazeEffect(experimental): Rewrote the Canvas2D-era code, which called the nonexistent graphic.getCanvasRenderingContext(), for the current WebGL Graphic. Draws pending batches first, then captures the screen bounding box of the node area into a texture with copyTexSubImage2D, and draws one quad per row with vertex color quads (drawColoredQuads), shifted along a sine curve. (Same approach as Rust vanilla-engine, with zero wobble the pixels are identical to the screen without the effect) When the area goes off screen, the edge pixels are stretched. Uses content size and pivot, so it inherits WorldNode instead of TransformNode. (TransformNode has no setContentSize, getWorldBounds, so it crashed on creation) The captured texture is deleted by destroy()
- Input: Moves the input that released games (retrogame-foundyou, steamgame-apocalypsesurvival, space-creature, aberrant, webgame-rimminer) each built separately on the game side into the engine defaults. (Game code was not touched, the games keep using their own as now)
- GamepadKind, readGamepadKind(gamepadId): Classifies the kind by pad name (Gamepad.id). PlayStation (054c, playstation, dualshock, dualsense, sony), Nintendo (057e, nintendo, joy-con, pro controller), Xbox (045e, xbox, xinput, microsoft), anything else other
- GamepadManager.vibrate(strongMagnitude, weakMagnitude, seconds): Vibrates all connected pads with the browser vibrationActuator dual-rumble. Magnitudes are clamped to 0 ~ 1. Pads and browsers without a vibration actuator are skipped
- GamepadManager.getActiveGamepadId(): The name of the pad that pressed a button or tilted an axis more than 0.5 in the last update. (Empty string if none, for telling which device was used last)
- GamepadManager.setInputLogEnabled, isInputLogEnabled: Turns off and on the console.log printed on every button and axis change. Changed default behavior: off by default, so button and axis logs are no longer printed. (Moving a stick even slightly flooded the log every frame, and no game relies on the log) Connection and disconnection logs are still printed
- InputManager: Held state and this frame's press and release of the three mouse buttons (MouseButton.left, middle, right) (setMouseButtonDown, isMouseButtonDown, isMouseButtonJustPressed, isMouseButtonJustReleased). A press and release between frames is also caught in that frame. Same form as Rust vanilla-engine
- InputManager.setTouchFromLeftButtonOnly: When on, only the left mouse button is passed as touch. When off (default), any button is touch as before
- InputManager.setContextMenuPrevented, isContextMenuPrevented: Whether to block the canvas right-click menu. Initially true, same as before
- InputManager.isKeyJustPressed, isKeyJustReleased changed behavior: Instead of comparing key snapshots at frame end, accumulates and checks key events (pushKey, popKey) that arrived since the end of the last frame. Fixed missing keys pressed and released between frames. (In that case isKeyPressed is false and isKeyJustPressed and isKeyJustReleased are both true) Key repeat while held (keydown repeat) is not a new press. updateFrameSnapshot clears the accumulated events
- TouchPoint, TouchPhase, InputManager.getTouchPoints(), getEndedTouchPoints(): list of fingers currently touching. Per finger: identifier (Touch.identifier), phase (began, moved, stationary), canvasNativePosition, viewPosition. Fingers lifted this frame stay in getEndedTouchPoints for one frame as ended or cancelled. The engine calls beginTouchPoint, moveTouchPoint, endTouchPoint for each changed finger of touchstart, touchmove, touchend, touchcancel, and removes fingers missing from the event's touches as cancelled. The first finger still goes to touch as before
- ViewManager.convertClientToView(clientX, clientY): converts a DOM event's screen coordinates to view coordinates
- InputDevice, InputManager.getLastInputDevice, getLastGamepadKind (setLastInputDevice, setLastGamepadKind): the last used device (keyboard, mouse, touch, gamepad) and gamepad kind. A key press means keyboard, mouse buttons, wheel and movement over 6 pixels mean mouse (excluding emulated mouse events within 0.8 seconds after a finger is lifted), fingers mean touch, gamepads mean gamepad and its kind via getActiveGamepadId. Initially touch on finger devices (pointer: coarse), otherwise keyboard
- InputManager.setPreventedKeys(keys), getPreventedKeys, isKeyPrevented, isTypingInTextField: keys whose default browser behavior is prevented (such as focus movement on Tab, page scrolling on Space). Not prevented while focus is in a text field (the text input, textarea, contenteditable of Engine.isTextInputFocused, and select). Empty by default, so behavior is unchanged
- InputActions (inputactions.js): input actions. InputManager holds one (getInputActions) and updates it in tick. Binds keys (bindKey), gamepad buttons (bindGamepadButton), and one side of a gamepad axis (bindAxis(action, axisIndex, direction), pressed when tilted by setAxisPressThreshold) to action names, and unbinds with unbindAction. isPressed, isJustPressed, isJustReleased, readValue (0 ~ 1), readAxis(negativeAction, positiveAction), readGamepadStick(xAxisIndex, yAxisIndex), readMoveAxis (the longest of WASD and arrow keys, left stick, and external sources, length at most 1). The dead zone (setDeadZone, default 0.2) is removed and the rest is rescaled to 0 ~ 1. Actions with setRepeat(action, delaySeconds, intervalSeconds) have isJustPressed true on repeats while held, and do not repeat in bulk after a long frame stall. External sources (addSource, removeSource) are objects with readActionValue(action), readMoveAxis(), readGamepadKind(), through which games plug in platform SDK gamepads. Keys are ignored while typing in a text field (setKeysIgnoredWhileTyping). A key pressed and released between frames still counts as one press
- Engine: also releases the three mouse buttons when the window loses focus (blur). (InputManager.clear also clears the finger list, mouse buttons, and input actions)
- Camera3D (graphics3d): perspective (setPerspective) and orthographic (setOrthographic), aspect ratio (setAspectRatio), lookAt, and view and projection matrices cached and recomputed only when values change (getViewProjectionMatrix, getInverseViewProjectionMatrix). projectToView(x, y, z, viewRect) computes a world point's position inside the 3D drawing rectangle and whether it is in front of the camera (isInFront), unprojectToPlane(viewPosition, planeHeight, viewRect) computes the point where the ray from a position in the rectangle meets the horizontal plane y = planeHeight, and readViewDepth computes view-space depth. The renderer and 2D overlays use the same camera. (Replaces webgame-rimminer, aberrant, steamgame-apocalypsesurvival rebuilding createLookAt, createPerspective per screen and computing projection by hand)
- ToonRenderer: setScreenRect(x, y, width, height), clearScreenRect, getScreenRect. Draws only inside the node rectangle. beginFrame moves the clip space of view and projection into the rectangle and cuts off the outside with scissor, and endFrame releases the scissor. Off-screen culling uses the frustum before the move. beginFrameWithCamera(Camera3D), drawMeshOutline (draws only the outline, not counted). Without a screen rectangle, behavior is unchanged
- ToonDrawQueue: collects the models to draw in a frame, then draws opaque bodies, outlines of opaque ones, and translucent ones (farthest from the camera first, depth write off) in that order. addMesh, addMeshInstanced, drawShadows(renderer, shadowMap), draw(renderer, camera). (From the queued drawing of steamgame-apocalypsesurvival ModelRenderer3D)
- Graphic: runExternalPass(callback, { clearDepth }) and clearDepthBuffer(). Inserts a WebGL pass between 2D draws. Draws the preceding 2D batch (flushBatch), clears depth, then calls callback, and when done (even if it throws) calls restoreRenderState. Clearing depth after setting a clip (stencil) once caused no 3D to be drawn at all on Galaxy Fold3 (Adreno 660) (webgame-rimminer), so nodes that draw 3D inside a clip call clearDepthBuffer before beginClipRect and pass clearDepth: false. (Four game nodes wrote the same sequence by hand)
- ToonView3D (component): draws toon 3D inside the node rectangle. Transforms the content area with the current transform into a drawing buffer rectangle, and inside runExternalPass sets the renderer's screen rectangle and calls the draw function (setDrawCallback). The renderer is created on first draw, and on devices where it cannot be created it is not retried and the 2D setFallbackDrawCallback draws instead. To share one renderer across multiple nodes, setRenderer. The aspect ratio of the camera (getCamera) is matched to the rectangle on every draw. Inside a parent Mask, setDepthCleared(false) and clearDepthBuffer avoid the pitfall above
- ToonPostProcess: setColorGrade(saturation, contrast, tint color, tint amount, haze color, haze amount), setVignette (darken edges). Applied after tone mapping and gamma. The tint color is multiplied after normalizing its brightness to 1, and haze lifts darker areas more toward its color. With default values (saturation 1, contrast 1, the rest 0) there is no grading, so behavior is unchanged. To output to a node rectangle, call resize (rectangle size), then pass the rectangle as the viewport of end. Bloom is the existing setBloom. (From the color grading of steamgame-apocalypsesurvival SceneEffects3D)
- ToonMesh: MeshBuilder.combine(pieces) offsets multiple static pieces ({ arrays, offset: [x, y, z] }) and joins them into one array. Outline shells, shell reference positions, and inner ranges are also offset and joined, skeletons are not joined. createFacetedChunkGeometry(radius, vertex scale, axis scale) is a faceted rock made by stretching and shrinking each of the 12 icosahedron vertices, with separate vertices per face. (steamgame-apocalypsesurvival combineMeshArrays, webgame-rimminer meshbuilder.js)
- GraphicsQualityGovernor, GraphicsQuality(auto, high, low): decides the lite path (isLite) in the order override (?light of applySearchText, setLiteOverride) → setting (low always, high never) → auto (setAutoLiteDefault, or FrameProbe measures the device as slow). update(frame seconds, maximum frame) measures only in auto and returns true on the frame the lite path changes. setRenderPixelRatioLimits(normal, lite path) and applyRenderPixelRatio(viewManager) apply the render pixel ratio cap only when it changes. What to reduce on the lite path is up to the game. (webgame-rimminer readIsLite, aberrant isLight)
- Loading, saving, and time features that shipped games built separately are added as engine defaults. (The games' screen looks and release platform code were not brought over, the only changed default behavior is LocalStorage reads)
- TimeManager: setMaximumTimeDelta(seconds), getMaximumTimeDelta(). Changes the cap on a single frame interval. (Previously hardcoded at 0.25 seconds, the default is unchanged) Games where water or physics must not advance in large steps lower it to 0.1, 0.05. Below 0 or not a number gives 0.25
- Engine: setMaximumFramePerSecond(n), getMaximumFramePerSecond(). Changes the maximum FPS at runtime. Writes to EngineConfiguration.maximumFramePerSecond, and the engine reads that value every frame and restarts counting from the frame it changes. (Same result as games editing the configuration object directly) Below 0 or not a number gives 0 (no limit)
- FixedStepper: fixed step. advance(timeDelta, stepFunction) of new FixedStepper(stepSeconds, maximumStepsPerFrame) calls stepFunction(stepSeconds) for the accumulated time and returns the remaining fraction (0 ~ 1, used to blend the previous and current step when drawing). If steps remain after running up to the per-frame cap, the remaining time is discarded (so slow devices do not catch up in bulk), and if stepFunction returns false, that frame stops there and the time stays accumulated. getAlpha, getLastStepCount, reset, setStepSeconds, setMaximumStepsPerFrame
- LocalStorage: reads (getString, getBoolean, getNumber) no longer write the default value for missing keys. (This changes default behavior) Merely reading created the key in storage, so after a default changed in a new version the old default remained as if it were a saved value, and containsKey was always true. Of the six shipped games, only pipemania uses the engine LocalStorage, and it only uses read values and does not check whether keys exist (containsKey, getKeys), so it does not rely on this behavior. (2026-11-25 grep of game code) Keys that were only read no longer appear in the storage panel of developer tools
- PersistedStore: setStorageBackend(backend), getStorageBackend(). Places just one store elsewhere (an object with getItem, setItem, removeItem). Swapping re-reads from there and notifies subscribers, and access there is also wrapped in try. Reading at construction no longer creates empty keys in storage either, due to the LocalStorage change above
- AssetLoader: concurrent asset loading. Add with addImage, addJson, addText, addBlob, addAudio, addFont(family, path, descriptors), addAsset(asset, path), addTask(path, loadFunction), and await load() fetches setConcurrency (default 6) at a time. Does not stop on failure and returns the failure list ({ path, error }). getProgress (finished count / total count), getLoadedCount, getFinishedCount, getTotalCount, getFailedList, isFinished, setProgressHandler, setCompleteHandler
- GameScene: loading screen customization. setLoadingColors(background, gauge background, gauge, outer) changes only the colors, setLoadingDrawer((graphic, viewSize, progress, elapsedSeconds) => ...) replaces the whole drawing over the background. When progress is reported with setLoadingProgress(progress) or trackAssetLoader(assetLoader), the gauge smoothly follows that progress instead of the elapsed minimum display time (LoadingProgress of getLoadingProgress), and fills to 1 when loadAssets finishes. If nothing is set, behavior is unchanged. (black background, #333333 and #ffffff gauge, elapsed time gauge)
- ToonScreenOutline, ToonOutlineWidthUnit: toon screen-space outline. (Brings into the engine the shader outlines that webgame-rimminer boardrenderer3d.js and aberrant scenerenderer3d.js wrote separately) Draws ToonRenderer models once more with the same matrices to write normals, line ids, and depth into a line buffer (beginLineIds, drawMesh, drawMeshInstanced, endLineIds), writes a line intensity mask in one pass, then blends it onto the screen with drawOutline. Lines appear outside silhouettes, where different ids meet, and at creases within one id. Which id to give which model and part (indexStart, indexCount), and per-instance ids (instances[i].lineId), are decided by the caller. Width in world length or pixels (setWidth, perspective world width at the distance of setFocusDistance, or the average distance of drawn models if not given), depth tells orthographic from perspective by the projection matrix and is linearized to meters for perspective. setDepthThreshold, setCrease(angle, intensity, continuation pixels), setResolutionScale(0.25 ~ 1), setSampleCount(outline 4 ~ 28, crease 0 ~ 4), setColor, setHdrOutput. Uses the viewport at beginLineIds as the drawing area, so it also fits 3D drawn on part of the screen. Can be used together with shell outlines
- ToonVfx, ToonVfxSlot, ToonVfxLook, ToonVfxShape, ToonVfxDecalMode: base for toon 3D GPU effects. (General-purpose parts of webgame-rimminer boardvfx.js and aberrant effects.js, effect recipes and ramp colors belong to the games and were not brought over) An atlas built in code without image files (16-cell smoke flipbook, particle, streak, light ray, shock band, beam texture, scorch, crater, rim glow, eight color ramp rows), instanced GPU particles (emitParticles: shapes point, sphere, ring, disc, cone, line, drag, gravity, stopping at the floor, stretching along velocity, ramps, seven looks), fireballs (addFireball), shockwave bands and floor glow (addShockwave), floor marks (addDecal, queueDecal, scorch, glow, flowing ring, expanding growth), smoke plumes (addPlume), lathe beams (queueBeam), ribbons (queueRibbon) and coiling downward lightning (queueLightning), glints (queueGlint). An internal clock advanced by update(seconds), a particle cap (constructor, setParticleCapacity, oldest overwritten first when exceeded) and an emission count ratio (setCountRatio, phones and lite path), ramp colors (setRamps), a floor height callback (setFloorHeightReader, marks, shockwaves, plumes are placed at that height and isGrounded particles stop). draw(view, projection) faces beams and ribbons toward the camera position in perspective and toward the camera direction in orthographic, and restores the draw state
- Window stacking and screen frames that shipped games (webgame-rimminer, aberrant, steamgame-apocalypsesurvival, space-creature) built separately were moved into engine defaults. (Panel looks, themes, presentation, and release platform code were not brought over, games keep using their own as before)
- UIWindowLayer: window stacking. openWindow stacks a window on top and only the top window is visible. closeWindow removes it from the list immediately (pressed and covered states are released immediately) and detaches it after the PopupMotion close motion finishes. (covered windows immediately) closeAllWindows, closeTopWindow (back navigation, does not close windows with outside close disabled), getTopWindow, findWindow, hasOpenWindow, getWindowCount. Calls the function of setWindowChangeEvent when a window opens or closes (pausing play). The layer scales by UIScale.read (setUIScaleOptions, null for no scaling, getUIScale) and tells windows the area size divided by that (setViewSize) and the safe area width (setViewBleed). Wheel goes to the top window's handleWheel, or if not handled, to the scroll view at that position (scrollWindowAt)
- UIWindow: a single window. Shows a panel centered over a dim (which swallows presses) covering the whole area and the safe area. The panel widens to the area width but not beyond setMaximumWidth (default 480), its height is the value returned by layoutContent(panelWidth) (default setPanelHeight), and if larger than the area the whole panel is scaled down. Pressing outside closes it (disabled per window with setOutsideCloseEnabled). close, setCloseEvent (notified when it goes down). The panel look is a single Paint, and games subclass it to attach decorations to the frame (getFrameNode) and override layoutPanel, applyMotion, setCovered, handleWheel, dispose to swap them. getPanelNode, getPanelPaint, getDimPaint, getPopupMotion
- UIConfirmWindow: Confirmation window. Title, message, and two buttons, cancel and confirm. Text wraps at the panel width, and when it exceeds the area height, only the text area scrolls. With setRightToLeft(true), the button order is reversed (confirm on the left). Confirm closes after setConfirmEvent, and closing via the cancel button, an outside press, closeTopWindow or closeAllWindows calls setCancelEvent. setTitle, setMessage, setButtonTexts. (UIDialog is left as is)
- UIScale.read(viewWidth, viewHeight, options): Scale that enlarges only the UI layer when one view unit is smaller than minimumCssScale(0.8) CSS pixels. (1 to maximumScale 1.8, short screens are not enlarged below minimumLayerHeight (not checked when it is 0, the default), portrait screens (width at most portraitRatio 1.1 times the height) have no upper limit, ViewManager.getCssPixelScale if cssPixelScale is not given) UIScale.isPortrait
- GameScene: fadeScreen(onDark). Calls onDark when fully dark, and if it returns a Promise, stays dark until it ends (even on failure), then brightens. false if already fading. setScreenFadeColor(default black), setScreenFadeSeconds(default 0.35), isScreenFading, getScreenFadeAlpha. The overlay is drawn in postDraw over the whole canvas including the safe area, and moves with unscaled time. While the overlay is up, presses and wheel are not accepted
- GameScene: isUserInterfaceAt(viewPosition) (whether there is a pressable node at that position, the previously hidden touch recognizer raycast), setPlayInputHandler({ press, move, release, wheel }) (passes presses not taken by the UI, the moves and releases of those presses (including cancel), and wheel outside the UI, as play area coordinates relative to the top-left of the safe area), convertViewToPlayArea. Wheel pointing inside the window layer is passed to UIWindowLayer.scrollWindowAt
- GameScene: setPlayAreaReference(fixedLength, isLandscape). Extends the reference resolution so that the fixed-side length of the play area excluding the safe area is always fixedLength. (canvas length : length excluding the safe area = reference resolution length : fixedLength, the view scale mode is also set to stretchWidthExpandHeight for horizontal fixed and stretchHeightExpandWidth for vertical fixed, recalculated in resize and initialize)
- ViewManager: setIgnoredSafeAreaSides(sides), getIgnoredSafeAreaSides. getSafeAreaInsets returns 0 for those sides. (The game passes which sides to ignore)
- GameScene behavior change: computeSafeAreaRect reads ViewManager.getSafeAreaInsets instead of measuring env(safe-area-inset-*) separately. Until now, setSafeAreaOverride, the URL's ?safeArea=, and (new) setIgnoredSafeAreaSides did not reach the GameScene safe area node. Games that use only env values are the same, except that insets are no longer truncated to integers. (Games that override computeSafeAreaRect are unchanged)
- The text, node convenience, and drawing features and optimizations that the shipped games (webgame-rimminer, space-creature, aberrant, retrogame-foundyou, Doomsday Survival) built and used separately are added to the engine defaults. (The games' screen look and presentation were not brought over, game code is unchanged)
- Text, UILabel: setFitWidth(width, minimumRatio = 0.55), getFitWidth, getFittedFontSize. When single-line text overflows the fit width, it is drawn shrunk from the original size down to the minimum ratio in steps of 0.1. The set size (getFontSize) stays the same, and it refits when the text, font, weight or width changes or a web font is loaded. If it still overflows at the minimum ratio, it is drawn overflowing. Wrapping text and rich text are not fitted
- Text, UILabel: setLetterSpacing(letterSpacing), getLetterSpacing. Spacing added after each grapheme cluster (pixels, same meaning as CSS letter-spacing, negative narrows, initially 0). The text width grows by cluster count x spacing (also added after the last character), and wrapping, fit width, alignment and underline measure with that width. Positions are set by measuring the previous/next pair per cluster, so pair kerning is kept, and the width matches what the Chrome canvas letterSpacing measures. Right-to-left text and rich text do not use the spacing. Same as the Rust version's set_letter_spacing and get_letter_spacing
- Engine.openUrl(url): opens an outside URL in a new tab (window.open(url, "_blank", "noopener")). It opens only when called inside user input (click, tap, key) handling; called regardless of input (timer, frame), the browser blocks it. Only http, https, mailto and tel are opened; other forms (such as javascript: and file:) return false. The Rust version's Engine::open_url opens with the OS default program on desktop (macOS open, Windows ShellExecuteW, Linux xdg-open) and with window.open on the web
- UIView.setBackdropBlur(blurRadius), getBackdropBlur: backdrop blur (same meaning as CSS backdrop-filter: blur() and Unreal UMG BackgroundBlur, initially 0 meaning off). The argument is a standard deviation equal to the N of CSS blur(Npx) (in node coordinate units; on screen, device pixels after the transform scale). When on, as this view is drawn, the screen drawn before it is blurred over this view's content area only with ScreenEffectType.gaussianBlur (separable Gaussian, horizontal then vertical, out to 3 sigma, linear sampling halving the taps, mirrored edges), and the (translucent) background color is laid on top. The average pixel difference from Chrome's CSS backdrop-filter is under 1 (standard deviations 3, 8, 20, tests/ui/uibackdropblurcss.test.mjs). It works only when drawing to the screen, and the geometry cache is not used while it is on. When off, the screen is byte for byte unchanged. Same as the Rust version's UIView::set_backdrop_blur and get_backdrop_blur (pixel-identical across the two engines)
- UIView.setBackdropCornerRadius(cornerRadius), getBackdropCornerRadius: rounded corners (CSS border-radius) for the backdrop blur and the background color. While the blur is on, the blurred area and the background color are laid only inside the rounded rectangle. Initially 0 (a rectangle). Rust version: set_backdrop_corner_radius, get_backdrop_corner_radius
- ScreenEffectType.gaussianBlur: Gaussian blur by standard deviation (parameters = [standard deviation in pixels], the same meaning as CSS filter: blur()). The existing blur is unchanged. Rust version: ScreenEffectType::GaussianBlur
- Engine.readLocalTime(minuteOffset = 0): returns the calendar time { year, month (1 to 12), day, hour, minute, second, weekday (0 is Sunday) } of now plus the minute offset, read in this machine's time zone. Daylight saving time at the added moment is applied (same as new Date(Date.now() + offset)). When a game needs local time for a clock display or logs, both engines read it with the same name. The Rust version's Engine::read_local_time reads it with Date on the web, localtime_r on Mac and Linux, and SystemTimeToTzSpecificLocalTime on Windows
- Bone matrix uniform block (the same road as Unity's GPU skinning constant buffer and Unreal's bone buffer): 96 bone matrices are 384 vec4 slots, which exceeds the minimum vertex uniform limit WebGL2 guarantees (MAX_VERTEX_UNIFORM_VECTORS 256 slots), so it ran on desktop (4096) but failed to link on Android (Galaxy Z Fold3). Bone matrices now go through the std140 uniform block JointBlock (6144 bytes, within the guaranteed MAX_UNIFORM_BLOCK_SIZE of 16384 bytes). Added: JOINT_BLOCK_GLSL (the declaration to put in a shader), JOINT_BLOCK_MAXIMUM (96), JOINT_BLOCK_NAME, JOINT_BLOCK_BINDING (3), JointBlockBuffer, MORPH_WEIGHT_VECTOR_COUNT (24), SkinnedModelRenderer.uploadJointMatrices. The toon renderer, toon outline, skinning renderer, and skin renderer all use this road, and ShaderProgram binds the JointBlock block to the same place after linking. The morph weight array went from 96 floats (96 slots) to 24 vec4 slots. tests/graphics3d/uniformlimitchrome.test.mjs checks in Chrome that every program the engine builds stays within the limits (256 vertex, 224 fragment). The screen is unchanged
- Text, UILabel: measureText(text, fontSize) (if not given, the current text and set size). Width measured with that Text's font, bold and italic
- Text.setText, UILabel.setText: skipped if the text is the same. (For UILabel, when not in rich text mode, it does not trigger an intrinsic size recalculation) Text.setTextColor: does not re-parse if the color string is the same and the held color is unchanged
- Text drawing: passes Color directly to Graphic instead of converting the color to a "#rrggbb" string. (No more string creation and parsing every frame) Colors that do not fall on 8 bits (such as 0.5 alpha in rgba) may differ within 1/255
- Graphic: setTextBakeMotionScaleStep, getTextBakeMotionScaleStep(default 0.25), setTextBakeScaleMoving, isTextBakeScaleMoving, readNodeTextBakeScaleMoving. When the text bake scale step (setTextBakeScaleStep) is 0 and the transform scale of the drawn node differs from the previous frame (ButtonMotion, PopupMotion, tweens, camera zoom), text is baked at a scale quantized to this step, and rebaked at the exact scale when it stops. (Text is not rebaked every frame during scale motion, a button growing from 1 to 1.09 goes from as many bakes as frames to 2) A node drawn for the first time is treated as not moving. When the step is not 0 (default), nothing is computed. ShadowText and ShadowImage use the same scale too
- TransformNode: setLastDrawnMaximumScale, getLastDrawnMaximumScale (used by Graphic.drawNode)
- ShadowText, ShadowImage, SoftShade: Baked images with the same shape are shared per key. The number of components using each key is counted, ones in use are not discarded, and ones no longer used by anyone are kept up to 128 and evicted least recently used first. Released when detached from the node (detach), and components collected without releasing are released by FinalizationRegistry. (acquireSharedBake, releaseSharedBake, readSharedBakeCount in sharedbakecache.js) ShadowImage assigns a number to each image to use as the key, and assigns a new number on setImage
- WorldNode: setContentSizeXY(width, height), setRect(x, y, width, height) (sets local position and content size, accounting for the pivot, so that the top-left is at (x, y), the anchor is not part of the local position calculation and stays as is), convertViewToLocal(viewPosition) (view coordinates through the parent transforms to coordinates relative to the top-left of the content area, same four-corner calculation as contains). TransformNode: setLocalPositionXY(x, y), setLocalScaleXY(x, y). XY functions do not create Vector2
- LanguagePack: isRightToLeft(), mirrorLayoutX(x, width, parentWidth), readLayoutTextAlign(align). When the current language is written right to left, flips the horizontal layout position and the left and right of alignment
- TouchRaycaster.touchWheel: The wheel is taken by the frontmost scroll view in draw order among those covering that position. (Taken even when scrolled over non-pressable things such as text or images inside the view, until now only ancestors of pressable nodes were searched, so wheel over text inside a view was lost) If the frontmost is a pressable node, the scroll view of that node and its ancestors takes it as before. true if a view took it. findWheelScrollView, findScrollViewComponent
- GameScene.touchWheel: Returns true if a scroll view took it. Overriding game scenes that pass to the game (map zoom, etc.) only when super.touchWheel is false do not conflict with window scrolling
- Graphic: drawRing(center, innerRadius, outerRadius, startRadian, endRadian) (setFillColor), drawArc(center, radius, startRadian, endRadian, lineWidth) (setStrokeColor). Joins one quad per segment without overlap and draws in one pass, so seams do not darken even when translucent. Segment count follows the on-screen radius like drawCircle (16 to 64 per full turn), in proportion to the drawn angle. Angle 0 is right, clockwise
- Graphic: drawLineSegments(positionValues, size) (setStrokeColor). Draws multiple line segments at once from one number array (x0, y0, x1, y1 per segment). Does not create Vector2, and when the vertex buffer fills, draws up to there and continues filling
- SpriteAtlas: Atlas reading. load(jsonPath), loadData(data, baseDirectory), readFrame(name) (Frame, null if missing), hasFrame, applyFrame(sprite, name), getPageImages, getFrameNames. Reads the JSON from tools/atlas.cjs and the { pagePaths, frames: { name: [page, x, y, width, height] } } form. Names are also found with the extension removed. Multiple atlases are searched in the order added with SpriteAtlas.addSearchAtlas (findFrame, applySearchFrame, removeSearchAtlas, clearSearchAtlases)
- Sprite.setFrame(frame): Sets the Frame's image and region together. (null clears the image)
- ParticleSystem: isFinished(nothing more to emit and no particles left, for non-looping when duration has passed and all bursts have been emitted), getParticlePositionList(list of particle positions, for same-seed comparison and testing). With the same seed as the Rust version, the same particle positions result
- HeatHazeEffect: Moved from an experimental node to an effect component. (src/effect/heathazeeffect.js, exported from import.js) Attach with node.addComponent(HeatHazeEffect), and when attached, if the node content size is empty, it is set to 300 x 300. getTimer, calculateRowOffset
- ScreenEffect: destroy also deletes the pass program and vertex array along with the render target
- Material.createTexture: Loads images with straight alpha and no color profile conversion. (premultiplyAlpha and colorSpaceConversion of createImageBitmap set to "none") Until now, with browser defaults alpha was premultiplied, making the color of alpha 0 texels black, and the edges of the hair and beard cards in OLD FACE were dark
- ToonRenderer, SkinnedModelRenderer, HumanSkinRenderer: Bind a 1x1 comparison depth texture to the shadow unit when not receiving shadows. (Prevents the Mac driver's "sampler type (Depth)" warning and the WebGL sampler mismatch) SkinnedModelRenderer.getEmptyShadowTexture, ToonRenderer.destroy
- ToonVfx: rim for light particles and light dots (0 is additive light, 1 is covering with a rim, negative is a faintly covering halo), glow bleed color for ribbons and lightning, setRimColor, lightning that re-bends over its life addLightning(life), screen flash addFlash, camera shake computed with the engine Shaker addShake, readShake, isShaking. lightningCount, flashCount in getActiveCounts. draw also restores the depth function. (Only the general-purpose part of the effects of the game aberrant, game colors and recipes as parameters)
- SkinnedModel: Loading from bytes, separate parsing and upload, createWithoutShaderProgram(pose computation only), destroy. Default morph weights are read from glTF node weights. Material.createImageDescription, destroy. destroy for ShadowMap, FullscreenPass and screen-space effects (also deletes the fullscreen pass). FbxLoader reads 64-bit ids above 2^53 exactly and skips missing nodes
- Camera2D: Rotation (setRotation, getRotation, degrees, axis at the screen center). The draw transform, screenToWorld, worldToScreen, panByScreen, fling and zoomAt follow the rotation, and the bounds clamp is measured with the box enclosing the rotated view (getVisibleHalfExtent). convertScreenDeltaToWorld, begin, end (pushState and applyTransform, popState). Covers all features of deprecated/camera.js (formerly experimental/camera.js). (Also fixed the clamp argument bug in Camera.setZoom)
- Tween: setTarget(node), getTarget, writes TweenProperty (localPosition, localScale, localRotation, localOpacity, contentSize) values directly to the node, applyTweenProperty, Tween.createNodeTween. Ends without callbacks when the target is detached from the node tree it first ran in. duration of 0 or less ends immediately. Scene.getTweenCount
- Animator: AnimationState setClip, getClip, AnimationTransition setFrom, setTo, getFrom, getTo (state index), getAnimation, addState, getStates, addTransition, getTransitions
- Indicator: getRadius, getRotation, buildTeethSegments, exported from import.js. Removed the unused argument of Visual.getLocation. VisualAsset setVisual, getVisual
- UI branch: Removes UI feature differences with the Rust vanilla-engine. Adds general-purpose features that existed only in Rust
- UIButton.fireClickEvents(): Calls the clicked and click notifications in order as if a click occurred, without pressing. UIHitArea uses this when passing on clicks in its enlarged area
- UILineChart.calculatePoints(width, height), UIBarChart.calculateBarRects(width, height): Compute the polyline points and bar rectangles at the same positions as drawing. draw uses these
- UISpinner: calculateDotOpacity(dotIndex), getDotColor, getRotationSpeed, getDotNodes
- UIScrollBar: getAxis, getThumbRect (null if the thumb is off)
- ToastMotion.getPhase(), ToastPhase exported. PopupMotion.isInstantEnabled(). UIImageView.getColor()
- UILabel: getWrapMode, getVisibleCharacterCount. UIInputField: getPlaceholder, getMaxLength, getFontSize, getPadding, getBackgroundColor, getRoundSize, getTextColor, getPlaceholderColor, getCursorColor, getCursorIndex, getSelectionStart, getComposition, isComposing
- UIWindow: setDimColor, setPanelColor (Paint colors of the dim and the panel)
- UIListView: setCreateItemEvent(() => WorldNode) accepts a function that creates item nodes instead of a template. If the item size is not set, reads the size of the first created item. isHorizontal()
- TouchRecognizer: getTouchTarget (the scroll view node if the drag was handed over), isTouching
- GameScene: setSafeAreaInsets({ top, right, bottom, left }) sets the safe area insets directly in CSS pixels. (null uses the view manager value, the play area reference also uses this value) Static calculateSafeAreaRect(viewSize, targetResolutionScale, insets). setPlayInputEnabled(true) collects play input, and takePlayInputs() takes out { kind, position, wheelDelta }. (Can be used together with the handler) setLoadingOutsideColor, hasLoadingDrawer, isLoadTouchedToSkip, getDevTools
- UIScene: when EngineConfiguration.useDevTools is off, does not create the developer tools, like GameScene. (Previously always created them)
- Aligned text and fonts with the Rust version (vanilla-engine):
- Visible character count (Text.setVisibleCharacterCount) and Typewriter count in grapheme clusters. (Previously in UTF-16 units, so emoji and combining marks were split) Fixed multi-line text drawing the whole next line when the remaining count dropped below zero. (At 0, nothing from the next line on is drawn) Typewriter's character reveal notification receives grapheme clusters. countGraphemes, sliceGraphemes
- Text.calculateDrawnRect: wrapped text also knows its rectangle. (Off-screen culling) getMeasuredLineCount
- RichText: uses text direction. Determines the paragraph direction from the joined text of the segments (this text's direction, or the Graphic's direction if "inherit"), and places segments from the right when right-to-left. Alignment "start" / "end" is also resolved in that direction. (Previously did not apply direction to segments)
- ShadowText: setItalic, setUnderline, setStrikethrough and getters, isBold. Underline and strikethrough are baked together with the shadow. "auto" for text direction (by the first strong character of the text)
- Graphic: exports detectTextDirection(text). (Equivalent to setTextDirection("auto"))
- DynamicFont: when adding characters with buildAtlas, re-places all contained characters on the new canvas. (Previously only new characters were placed on the new canvas, misaligning previously baked characters) Grapheme cluster units, rebuildAtlas, measureText. import.js exports DynamicFont, GlyphInfo
- LanguagePack: setLanguageList(data), setLanguageTexts(code, texts, fallbackTexts) (set directly without files)
- import.js: splitGraphemes, splitWords, countGraphemes, sliceGraphemes, detectTextDirection
- Rebuilt the visual editor (tools/visualeditor/visualeditor.html) with the engine above
- Core, platform, foundation branch. Brings in general-purpose features that existed only in the Rust version (vanilla-engine) to align the public APIs of the two engines.
- Color.createFromBytes(red, green, blue, alpha) (0 ~ 255), withAlpha(alpha) (new color with only alpha changed), Color.lerp(from, to, time)
- Math.easeOutQuad(time)
- Matrix4.writeToArray(array), writeToSlice(array, offset): writes the 16 column-major elements into the array (at offset)
- Vector2: addScalar, subtractScalar, multiplyScalar, divideScalar, moduloScalar. Vector3: addScalar, subtractScalar, multiplyScalar, divideScalar. (Same as add(number))
- Rect.intersects(other): whether they overlap. Edges that only touch do not count as overlapping. (overlaps counts touching as overlapping)
- Cooldown.activate(): same as use()
- TransformMatrix.invert(): returns a new inverse matrix. (null if the determinant is 0)
- Platform.applyUserAgent(userAgent): determines platform, browser, and mobile status from the given user agent string. (getPlatformInfo calls it with the browser's string)
- Engine: setTitle(title), writeClipboardText(text), readClipboardText() (Promise, null if there is no text or access is blocked), isCoarsePointer(), loadScene, unloadScene, unloadAllScenes (same as SceneManager), isExitRequested()
- Engine page events: PageEvent(hidden, visible, blurred, focused, pointerDown), addPageEventListener(listener), removePageEventListener(listener), isPageHidden()
- Engine frame capture for verification: requestFrameCapture(frameNumber) passes the canvas as a PNG data URL after that frame is fully drawn. (Promise, the current frame if the number has already passed) URL query ?capture=120,240 saves those frames as downloads, captureName is the file name ("{frame}" is the number, default capture_{frame}.png), captureExit=1 calls exitApplication after the last save
- InputManager: isTouchDown() (true from the press frame until release, true even when held without moving), isWheelWithCtrl() (whether the last wheel was scrolled with Ctrl, touchpad pinch), isTouchInput() (whether the last input was a finger)
- Component.isTickNeeded(): if false, the node does not call that component's tick. By default, determined by whether tick is overridden. Sprite, Text only draw, so false (true if a subclass overrides tick), components without tick such as Paint are also false
- ImageAsset.loadFromBytes(assetPath, bytes), TextAsset.loadFromBytes, JsonAsset.loadFromBytes, BlobAsset.loadFromBytes (assetPath, bytes), AudioAsset.loadFromBytes(bytes), FontAsset.loadFontFromBytes(family, bytes, descriptors): loads from bytes already in hand. (Embedded data or directly downloaded data, the passed bytes are not modified)
- SpriteAtlas.getPageCount(), SpriteAtlas.findFrameInOrder(atlasList, name), applyFrameInOrder(atlasList, sprite, name): searches the given atlases in order instead of using the search atlas list
- SoundSystem: addSoundAsset(soundId, audioAsset) (appends a sound built in memory to the recording group of that id, volume and interval follow the sound table row), getEffectVoiceCount()
- Collision2D.findNearestIndexInRadius(targetList, getPositionHandler, center, radius): index version of findNearestInRadius. (-1 if none)
- Localization: selectLanguage(candidateList, supported, default) (matches by stripping subtags from the end of the tag, detectLanguage also uses this. "zh-Hant-TW" matches "zh-hant"), setLanguageAliases, setRightToLeft, isRightToLeft, mirrorLayoutX, readLayoutTextAlign, isolateText, textNamed(key, values) (named placeholder filling, same as LanguagePack.formatText), setTableFromJson(languageCode, tableJson)
- PersistedStore.unsubscribe(subscription): unsubscribes by passing what subscribe returned. (Same as calling the returned unsubscribe function)
- SpriteAnimator.getCurrentFrameIndex(), SpriteAnimator.playOnNode(node, clipName, options) (play with the node's animator)
- WebSocketClient: without a receive callback, collects received JSON, retrieved with takeReceivedMessages(). (Up to 1024, oldest discarded first on overflow) Binary messages are also received if they are UTF-8 JSON. tick() (no-op, for writing the same code as on other platforms). Fixed getReceiveEvent() returning the WebSocket, now returns the receive callback
- AudioBus (src/core/audiobus.js, exported from import.js): AudioManager.createAudioBus(), AudioBus.createAudioPlayer() (a player that plays through that bus), setVolume, getVolume, mute, unmute, isMuted, isAvailable, getGainNode. A single GainNode connected to the output, and players created from a bus connect to the bus instead of the output. The AudioPlayer constructor takes the output node (outputNode) as its second argument. (audioContext.destination if omitted) Same shape as the Rust version
- SoundSystem.getMusicBus(), getEffectBus() return AudioBus instead of GainNode. (The node via getGainNode()) The settings volume is applied to that GainNode with setTargetAtTime as before. Players created from a bus also follow the settings volume and mute
- Platform.getResourceUsage(): added the correct name. The old name getResouceUsage() remains as an alias that calls the same thing
- Node.findDescendantByName(name): same as findChildRecursiveByName. Node.destroyChildrenWhere(predicate): detaches and destroys the direct children matching the condition and returns their count. (Same names as the Rust version's find_descendant_by_name, destroy_children_where)
- GamepadManager.isButtonJustPressed, isButtonJustReleased: whether the button was just pressed or released in this update. (Same as the Rust version)
- General-purpose features that existed only in the Rust version:
- DEVTools: setVisible, getActiveTab, setActiveTab, getSelectedNode, setSelectedNode, isNodeExpanded, setNodeExpanded, getPanelRect. (F2 calls setVisible)
- UIDialog.requestDismiss(isConfirmed): closes on the next tick
- UIInputField.getDisplayText() (the value with the composition text inserted at the cursor position), requestMenuAction(menuAction) (cut / copy / paste on the next tick), UIInputFieldMenuAction (exported from import.js)
- AmbientOcclusionEffect.buildSampleKernel(), SubsurfaceScatteringEffect.buildKernel(falloffColor, strengthColor): static functions that build kernels without WebGL. computeKernel uses them
- FbxLoader.parseNodeRecords(arrayBuffer) (header check and top-level node records, the first part of parse), FbxLoader.readVersion(arrayBuffer) (static, the version number in the header)
- AudioManager.getContextTime() (AudioContext clock, 0 if none), AudioAsset.getLoadError() (reason for the last load failure, null if none), AssetLoader.getInFlightCount() (number being downloaded by workers). Same role as the Rust version's get_context_time, get_load_error, get_in_flight_count
- Graphic.setBlendMode: correctly draws the 17 modes that were drawn as source-over instead. All 26 SpriteBlendMode modes now work
- source-out, source-atop, destination-atop, xor are set with blendFunc using the Porter-Duff coefficients of W3C Compositing and Blending Level 1 as is
- overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity copy only the area to be drawn (the bounding box of the vertices) from the current framebuffer with blitFramebuffer on each draw and blend in the shader. The formulas follow W3C as is (separable blending, non-separable blending, Cs' = (1 - αb) x Cs + αb x B(Cb, Cs) followed by source-over compositing) and are also correct on render targets with backdrop alpha (RGBA8, RGBA16F). darken, lighten blend in the shader because blendEquation MIN / MAX differs from the W3C formula for translucent pixels
- Shader blend modes are not batched. One area copy and one draw call per draw (about 0.065 ms per draw on M2 Pro at 1280x720, mostly the cost of the copy breaking the render pass)
- Images, shapes, text, nine-slice, clipping, particles, and swapped-in shaders (ShaderSprite) all work. Particles are grouped into mutually non-overlapping quads that are copied once and drawn, so like Canvas2D each quad blends over the previous quads. Swapped-in shaders do not know the blend function, so they are first drawn into an overlay buffer (RGBA16F, RGBA8 if unavailable) and then blended while being transferred
- Comparing the same scene as Chrome Canvas2D (translucent images, rectangles, polygons over multicolored backgrounds) across the 26 modes, the difference inside shapes is within 2 levels. Canvas2D also clears outside the drawn shape for source-in, source-out, destination-in, destination-atop, copy, whereas Graphic changes only the inside of the shape as before
- Changed the warning text for unknown names to "unknown blend mode"
- Extends toon post-processing, effects, and the camera so that aberrant and webgame-rimminer can use the engine as is. (With new options at their defaults, output is identical to the current screen down to the pixel, same API and same shader text in both engines, game recipes and color values are taken as parameters)
- BloomEffect.setUseFloatColor: builds the ping-pong buffers as RGBA16F so bright values above 1 are not clipped. (Default stays RGBA8)
- ToonPostProcess: constructor options { sampleCount, useFloatColor, depthBits, useDepthTexture }, isFloatColorSupported (devices that cannot use float buffers take the LDR path with RGBA8 buffers, in which case the scene draws screen colors and compositing applies only bloom and color grading, without tone mapping and gamma), setSampleCount, setResolutionScale (draws only the 3D buffer at output size x scale and upscales it with the viewport in end, UI stays at device pixels), setBloomLevels (level count, threshold, knee, 0 for the default half-resolution 9 taps), setBloomFloatColor, setBrightness, setLitArea and clearLitArea (reconstructs the world position of each pixel from the scene depth texture, brightness 1 within the horizontal distance from that position), getSampleCount, getUseFloatColor, getResolutionScale, getBloomLevelCount. Brightness, saturation, and lit areas that webgame-rimminer applied in LDR inside its shader can be applied as post-processing on the LDR path. (The luminance weights for saturation are the engine's Rec. 709, webgame-rimminer uses Rec. 601)
- Toon color space convention: the scene buffer is linear. (ToonRenderer.setHdrOutput(true), ToonScreenOutline.setHdrOutput(true), ToonVfx colors are also treated as linear) Games that, like aberrant, wrote gamma-encoded values g into a float buffer and converted them back with g^2.2 in compositing convert the values to linear when porting. Colors become c^2.2, and a brightness multiplier k applied on the gamma side becomes linear k^2.2. (1.37 becomes 2, 1.6 becomes 2.81, 2.08 becomes 5, brightness 1.6 with multiplier 1.6 becomes 7.9) Bloom threshold 1 and knee 0.25, exposure 1, intensity 0.6 stay as they are, since they are the values aberrant used after converting back to linear
- Camera3D.setMatrices(view, projection): uses the raw matrices computed by the game as is. (like the tilted orthographic view of webgame-rimminer) Extracts eye, target, up and whether it is orthographic from the matrices, and projectToView, unprojectToPlane, readViewDepth, ToonRenderer.beginFrameWithCamera run on those matrices. hasRawMatrices, clearRawMatrices; setPerspective, setOrthographic and lookAt discard the raw matrices
- ToonVfx: options.age for emitParticles, addFireball, addShockwave, addDecal, addPlume, addLightning, addFlash (seconds already elapsed, an effect seen late starts from that age, a negative value delays it by that much) and options.key (event key, a key already emitted is not emitted again, clear forgets it, registerEventKey), setLookGain and getLookGain (brightness multiplier per particle and glint look, default 1), setGlintCapacity and getGlintCapacity (glint limit per frame, default 96), floor mark looks stain (covers with tint, the rim edge is stained with the rim color), sheen (oil sheen), shade (shadow fading out in a circle) and mark options.flicker (flicker half period in seconds), queueBlobShadow({ x, z, radius, alpha }) (shadow under the feet), options.rim for fireball, shockwave, ribbon, lightning (share of the look that covers the body and outlines the edge with the rim color, for bright backgrounds, 0 is the current additive light). Shake (addShake) is the exponential decay of Shaker, so for an event seen late pass intensity x exp(-9 x age)
- Added general-purpose features that existed only in the Rust version. Text.calculateFittedFontSize(), UILabel.calculateFittedFontSize() (measures the draw-time size on the spot, this version measures without Graphic so the value equals getFittedFontSize), Text.wrapLinesWithoutGraphic(maximumWidth) (list of lines split with the current text and font, null if there is no canvas to measure with), measureTextWithoutGraphic(fontString, text) (exported from import.js, same as measureTextMetrics)
- Graphic.readFramebufferPixels() (the currently drawn screen as { width, height, pixels }, top-to-bottom RGBA, alpha 255), getDrawingBufferWidth(), getDrawingBufferHeight() (last set viewport), getImageSmoothingQuality()
- ToonRenderer extension points and light model: standard features come first so that aberrant and webgame-rimminer can move onto the engine toon renderer without modifying the renderer per game, with a place to insert shader chunks only for patterns the standard features cannot do. With the new options at their defaults the screen is the same as now. (verified by drawing the same frozen scene as the old renderer: LDR with 3 cel bands has pixel difference 0, HDR float buffer has maximum 3.8e-4)
- ToonLightSet(toonlightset.js): one bundle of light values. The renderer holds a default set, and setLight, setSunDirection, setFillLight, setRimLight, setSpecular, setPointLights, setPointLightLimit, setBandCount, setBandRamp, clearBandRamp, setLightModel modify it. createLightSet, getLightSet, options.lightSet per draw. Each modification bumps a version number, so it is uploaded only when changed
- Meaning of sun direction: the direction light travels (from the sun to the surface, same as three.js DirectionalLight). The received share is max(dot(N, -sunDirection), 0). Code that used the direction from the surface toward the sun passes it with the sign flipped
- Fill light setFillLight(direction, color): a second directional light without shadows. Rim light setRimLight(color, power): adds pow(1 - max(dot(N, V), 0), power) like light. Specular setSpecular(intensity, exponent default 48): Blinn-Phong of the sun, receives shadows
- Point lights setPointLights([{ position, color (linear), intensity, range, decay, rangeExponent, wrap }]): up to 8 (TOON_MAXIMUM_POINT_LIGHTS), setPointLightLimit reduces it on lightweight paths. Attenuation = window (1 - (d / range)^rangeExponent) clamped and squared x 1 / max(d^decay, 0.01). The defaults decay 2, rangeExponent 4 are the form used by three.js, Unreal, Godot 4, and decay 0, rangeExponent 1 gives (1 - d / range)^2. The received share is wrap lighting (dot + wrap) / (1 + wrap)
- Bands: setBandCount is unchanged (rounds the sun share into n steps). setBandRamp(thresholds, values, half Lambert) splits by thresholds into a value per step (up to 8 steps, TOON_MAXIMUM_BAND_STEPS), also applied to the point light share. The 4-step half Lambert of webgame-rimminer is setBandRamp([0.25, 0.5, 0.75], [0.3725, 0.6471, 0.8627, 1], true)
- Light model setLightModel({ isEnergyNormalized }): divides base color x light by π (Lambert BRDF, the same convention as three.js physical lights, which give light intensity as illuminance, and glTF lights). Specular is then normalized Blinn-Phong (exponent + 8) / 8π. The default false is the same as now
- Draw options (drawMesh, drawMeshInstanced, drawMeshInstanceBuffer, ToonDrawQueue.addMesh): tintAmount (mixes the tint in sRGB instead of multiplying), glowScale (multiplier on vertex glow), colorScale (multiplier on the final linear color), emissiveColor and emissiveIntensity, baseColorTexture (multiplies the base color, alpha goes to opacity), emissiveTexture, uvTransform([u offset, v offset, u scale, v scale]), decalTexture, decalColor, decalEmission, decalUvTransform (covers the base color by alpha and glows with that color, one cell of an atlas), alphaCutoff, blendMode (ToonBlendMode.alpha default, premultiplied, additive, anything other than alpha is translucent), softEdge (pow(|dot(N, V)|, softEdge) into opacity), isMirrored (if not given, flips the winding automatically when the model matrix determinant is negative, and also when the view matrix is mirrored), indexStart, indexCount, outlineIndexStart, outlineIndexCount
- ToonMaterial(toonmaterial.js): createMaterial({ name, uniformChunk, surfaceChunk, lightChunk, vertexChunk }) as options.material. Surface chunk applySurface(inout ToonSurface), light chunk applyLight(ToonSurface, inout ToonLighting), vertex chunk applyVertex(inout ToonVertex, all three of body, outline, shadow depth). ToonSurface has sRGB base color, alpha, linear glow, world normal, vertex glow, unlit, four pattern values (vertexDetail), UV, local position, world position, view direction. options.textures({ uniform name: texture }, from unit 7, TOON_MAXIMUM_MATERIAL_TEXTURES 9), options.onBeforeDraw(program, gl, ToonProgramKind). Builds and caches a program per material and instance layout (if it fails to build, reports it and skips that draw). prepareMaterial, deleteMaterial, getSolidProgram(material). Passed to ShaderWarmer via readProgramSources(material, instanceLayout) and composeToonProgramSources
- Instance layout: createInstanceLayout([{ name, size }]) (instanceMatrix 16, instanceTint 4 are read by the engine, up to three other user attributes at locations 13 ~ 15, read by name in the vertex chunk), createInstanceBuffer(layout, count, ToonBufferUsage.static | dynamic) persistent buffer, updateInstanceBuffer, deleteInstanceBuffer, drawMeshInstanceBuffer(model, buffer, count, layout). The vertex array binding the model and buffer is built on the first draw and kept. The current drawMeshInstanced (filters and uploads every frame) is unchanged
- Textures: createTexture(ImageBitmap, canvas, image, ImageData or { width, height, data }, { isMipmapped, isRepeated, isFiltered }), deleteTexture. UV (0, 0) is the top left of the image (same as glTF). Uses units shadow 3, base color 4, emissive 5, decal 6, material 7 ~ 15, and binds a 1x1 white texture to slots not given
- Frame: beginFrameWithMatrices(view, projection) (without Camera3D, raw orthographic matrices), getFrameCamera, readFrameCamera (eye position from view and projection, view direction if orthographic, whether mirrored), applyFrameState, createReflectionMatrix(point on plane, normal), readMatrixDeterminant
- Performance: per program, frame values (view and projection, camera, shadow, HDR, outline color) and the light set are uploaded only when changed, and only values that change per draw are uploaded every time. Texture units are set once when the body program is built
- Shaders: the three vertex shaders share the same header (position, normal, color, material, pattern, UV) and ToonVertex, and the body shader passes local position, world position, four pattern values, UV to the fragment stage. vertexUv(12) in TOON_ATTRIBUTE_LOCATIONS. The shader source is identical to the Rust version
- ToonDrawQueue: addPass(ToonDrawStage.beforeOpaque | afterOpaque | afterOutline | afterTransparent, callback(renderer, gl)) stage callbacks (planar mirror, screen-space outline blending, effect slots, draw state is reapplied after the call), addMesh options group and isDepthPrepassed (sorts translucent items as one group by center depth, draws depth only first and then colors only at equal depth so overlapping parts do not brighten twice), blendMode other than alpha goes to the translucent order, drawWithMatrices(renderer, view, projection). clear also empties the stage callbacks
- ToonMesh: texture coordinates uvData (2 per vertex, an empty array if no vertex was given one, 0 for vertices without them when mixed). createBoxGeometry (0 ~ 1 per face) and createSphereGeometry (longitude and latitude) build uvs and addPart stores them. The last optional argument uvs of addTriangles, addMaterialRange; combine joins uvData and materialRanges
- ToonGlb: stores TEXCOORD_0 as uvData, and per-primitive material ranges materialRanges({ name, materialIndex, nodeName, indexStart, indexCount, extras, alphaMode, alphaCutoff, baseColorFactor, emissiveFactor, baseColorImage, emissiveImage, hasUv }). If emissiveTexture is present, vertex glow is left at 0 and passed via the material range. readGlbImages (image name, mimeType, data), decodeGlbImage (ImageBitmap). Cells inside a part (accent color, display panel) are selected by material name or extras and drawn with indexStart, indexCount
- WorldNode.setPosition: added the inverse of getPosition. Until now TransformNode.setPosition did not undo the position of the parent pivot point (parent contentSize x parent pivot), so when the parent content size and pivot were nonzero, the position set with setPosition differed from getPosition. (with parent 100x60, pivot centered, 90 degrees, scale 2, placing at (280, 200) read back as (340, 100)) On axes where the parent scale is 0, it places at the parent pivot point. (fixed together with the Rust version)
- When drawing multiply to a render target (while a framebuffer is bound), the area under the draw region is copied and blended in a shader per the W3C formula (B(Cb, Cs) = Cb x Cs). Fixed blending (DST_COLOR, ONE_MINUS_SRC_ALPHA) drops the cs x (1 - αb) term when the backdrop alpha is below 1 and leaves the alpha as the backdrop alpha, differing from Chrome Canvas2D by up to 221 on render targets with a translucent backdrop. (now 0 inside shapes) The default framebuffer (alpha: false) always has backdrop alpha 1, so it is drawn as before with fixed blending and batching, and the screen, draw calls and copy count are unchanged. multiply on a render target, like the 13 shader blend modes, costs one region copy and one draw call per draw. Added blendModeIndex 14 to the blend shader source. (fixed together with the Rust version)
- The value "MediaPlay" of KeyCode.audioplay is a name not in the W3C KeyboardEvent.code table (2025-04-22 Recommendation). Changed it to "MediaPlayPause", the name in the table that Chrome emits for the common play/pause key (USB 0x0C00CD, Windows scan code 0xE022). Chrome emits "MediaPlay" only for the play key on Linux and ChromeOS (USB 0x0C00B0). (fixed together with the Rust version)
- ToonScreenOutline: rebuilt the screen-space outline in the standard form of real-time toon rendering. (It is the engine's baseline, not a form fitted to one game)
- Detection: checks once at each boundary between a pixel and its four direct neighbors in the line buffer (normal, line id, depth), and places the line at the middle of that boundary. (The G-buffer edges of Saito, Takahashi 1990, the four-neighbor check of the Unity Shader Graph example) Until now crease lines were checked with the normal of a single point creaseRadius away from the center pixel, so bands appeared on both sides of a crease, enlarging the half-size buffer produced dotted lines and a parallel second line, and one more band appeared inside the silhouette of round surfaces
- Depth: unprojects the two neighboring pixels to view-space positions and detects occluded silhouettes by the distance from each other's tangent plane. No false lines appear on floors seen at a grazing angle or around round surfaces. (The Roystan approach, which adjusts the threshold by viewing angle, done with the tangent plane) It uses the distance of the occluding pixel from the occluded pixel's tangent plane (when the occluding side is the silhouette of a round surface, that tangent plane contains the line of sight), and adds to the threshold the measured error (8-bit normal angular error x the distance between the two positions, one pixel x the sine at a crease, one 24-bit depth step) times the margin factor (setDepthMargin, default 2)
- Widening: propagates the distance to the boundary segments with jump flooding (Rong, Tan 2006). The number of steps is log2 regardless of width. (Ben Golus, The Quest for Very Wide Outlines) Outer lines and crease lines are propagated separately so they get separate widths. The previous 3-pixel radius limit is gone
- Blending: each pixel of the drawing area is covered by clamp(width / 2 - distance + 0.5, 0, 1), from the distance to the nearest boundary. Since the distance is measured in the drawing area even when the line buffer is reduced, widened lines do not break up
- Per model: options.hasScreenOutline of drawMesh, drawMeshInstanced (when false, it emits no lines and only occludes the lines behind it), options.hasCreaseLine, options.isMirrored (if not given, the winding is flipped by the determinant)
- readJumpFloodSteps(distance): list of jump flooding steps. (From the largest down to 1)
- ToonScreenOutline per-ID line color: setLineColor(lineId, color), removeLineColor(lineId), clearLineColors(), getLineColorCount(). (The Unreal Custom Stencil form, the color is picked by the ID already in the line target) The table is a 128 x 128 lookup texture covering every line ID, so there is no limit on how many are set. A line where two IDs touch takes the color of the nearer ID, and IDs not in the table keep the setColor color. With an empty table the composite is pixel-identical to before. (For highlighting only the lines of chosen models, like the rock highlight of Rimminer #169)
- ToonRenderer per-instance emission: emissiveColor ([r, g, b] sRGB) and emissiveIntensity (linear multiplier, default 1) on the instances of drawMeshInstanced. Added on top of that instance's shading and pattern so only that instance brightens. (The tint is a multiply and could only darken)
- The instance data stays 20 values. The matrix is read as an affine 3x4 and the emission goes into the four values of the bottom row (elements 3, 7, 11, 15). (The 3x4 matrix form of Godot MultiMesh and Unity BatchRendererGroup) The instanceMatrix of ToonInstanceLayout is the same, and in the vertex chunk it is vertex.emissive. Storing Matrix4 elements as they are leaves the bottom row 0, 0, 0, 1, so there is no emission and the screen is unchanged.
- ToonDrawQueue: setScreenOutline(ToonScreenOutline or null), getScreenOutline(). When one is given, draw and drawWithMatrices draw the opaque items into the line buffer before the bodies (the id is options.lineId, the order added + 1 if not given, and for instances instances[i].lineId comes first), and blend it after the outline shells, before the afterOutline stage. Per model options.hasScreenOutline, options.hasCreaseLine. Translucent items are not drawn into the line buffer. If there is a screen rectangle (setScreenRect), that rectangle is used as the line buffer's drawing area. Code that has been calling drawOutline in an afterOutline stage callback can switch to this
- Fixes to the original made while matching the Rust version's reflection (#[reflect])
- Visual, UIListView: the constructors did not call setComponentType, so getComponentType was "Component" and they were written with ComponentType "Component" in UI documents and reflection saves. Now they are "Visual", "UIListView"
- UIScrollBar: getTrackColor, getThumbColor (the colors of the track and thumb Paint, same as the Rust version)
- UIDocument: added ShadowImage to the table. Like Sprite, it is written and read in the reflection save form after imagePath. (Until now it was not in the default table, so unless registered separately as the editor does, it was skipped when reading)
- UIDocument.loadByReflection: also reads properties whose current value is missing (null) by the saved form. (Arrays of four numbers as Color, arrays of two numbers as Vector2, numbers, text and booleans as they are) Until now the number, text, boolean and array values of properties whose current value was null were skipped
- Regenerated docs/api/0.4.0.json and the translation table
- Rebuilt toon shading in the standard form of real-time toon rendering. (A form chosen by comparing the Unity Toon Shader, Unreal Substrate Toon BSDF, Godot's diffuse_toon, Team Fortress 2 and Guilty Gear Xrd, not fitted to one game)
- Shade ramp: multiplies the lit share (half Lambert by default) by the shadow and looks it up on the ramp to pick the color. Each cell has a position, linear color and softness (Step and Feather), and boundaries are kept free of stair-stepping with fwidth. Shadows come in as the shade color, not black
- ToonLightSet.setShade({ step, feather, color, secondStep, secondFeather, secondColor, isHalfLambert }): base, first shade, second shade. The default is two steps splitting at half Lambert 0.5 (a cool purple shade)
- setShadeRamp(positions, colors, softness, half Lambert): sets the cells directly (up to 8 cells), clearShadeRamp(): smooth Lambert
- setRampTexture(texture, half Lambert): reads the ramp texture horizontally instead of cells. (The warp of Team Fortress 2, the ramp texture form of Genshin Impact and Honkai)
- setBandCount, setBandRamp still work but are built with the same ramp. (Gray cells, boundaries without stair-stepping)
- Per light: the sun receives the full ramp color, so the shade is also tinted with the sun's color. The fill light, point lights and spotlights receive the ramp's brightness level (bottom cell 0, top cell 1), so they do not light faces turned away. Until now the fill light did not go through the bands
- Highlight: setSpecular(strength, exponent, softness, color). From a hard toon spot splitting Blinn-Phong at 0.5 (softness 0, default) to a soft highlight (1). Appears for the sun, point lights and spotlights alike, and is masked by the lit level. (Until now only the sun, only the soft form, and masked only by shadows with no light-side masking)
- Rim light: setRimLight(color, power, softness, sun-side mask). From a hard rim to a soft rim, and it can be limited to the side lit by the sun. It is added to the base color instead of multiplied by it. (Same as the Rim Light of the Unity Toon Shader; until now it was multiplied by the base color like light)
- Spotlight: giving a point light direction, innerConeAngle, outerConeAngle makes it a spotlight. (The angular attenuation of glTF KHR_lights_punctual)
- Draw options: receivesShadow (default true), shadeOffset (shifts the shade boundary), specularScale, rimScale (per-material highlight and rim multipliers), matcapTexture, matcapStrength, matcapBlend (ToonMatcapBlend.multiply, add), outlineColor, outlineWidthScale (per-draw color and width multiplier for shell outlines)
- Added shadeOffset, specularMask, rimMask to the surface chunk (ToonSurface), and rim, sunLevel to the light chunk (ToonLighting). Composition is base color x irradiance + specular x specularMask + rim x rimMask + glow
- Transforms normals by the transpose of the inverse of the model matrix and bone matrices. Corrected the lighting and screen-space outline creases that were wrong on stretched and squashed models (scale that differs per axis). Code in vertex chunks that compensated by dividing normals by the squared scale must be removed
- Changed the default lights. Sun [0.9, 0.85, 0.8] → [0.84, 0.8, 0.74], sky [0.45, 0.5, 0.6] → [0.3, 0.33, 0.42], ground [0.2, 0.18, 0.16] → [0.17, 0.16, 0.15]. (So lit faces do not go far above 1, matched to the two-step shade)
- Shade ramp: multiplies the lit share (half Lambert by default) by the shadow and looks it up on the ramp to pick the color. Each cell has a position, linear color and softness (Step and Feather), and boundaries are kept free of stair-stepping with fwidth. Shadows come in as the shade color, not black
- ToonMatcapBlend: how a matcap is blended. (multiply, add)
- Filled in comments and examples for every file in the toon folder (graphics3d/toon). Header comments and JSDoc @param, @returns descriptions for every public API, and @example
title on modules, classes and members whose usage is not obvious (the examples use only import.js names and were checked to run without errors in headless Chrome) - Filled out toon up to the level Unity and Unreal provide by default. (Followed the formulas in the Unity Toon Shader source)
- ShadowMap: fixed building a ShadowMap after building models leaving the depth texture on a texture unit, so drawing gave GL INVALID_OPERATION (feedback loop). Restores the previous texture and framebuffer bindings when building. Fixed the light matrix breaking when the light travels almost straight down or up (the up vector parallel to the light). In that case the z axis is taken as up
- ShadowAtlas, SHADOW_ATLAS_MAXIMUM_LIGHTS(4): real-time shadows for point lights and spotlights. In the form of the Unity URP additional light shadow atlas, one depth texture is split into tiles; a spotlight draws into one perspective tile, and a point light draws the six cube faces into six tiles. updateLights(point light list) picks the lights with castsShadow true and computes the tiles and the view and projection for each tile. The toon shader multiplies that point light's lit share by the shadow and feeds it into the shade ramp (the same form as the sun, 3x3 PCF) The receiving position is pushed toward the normal by (1 + 3 x (1 - dot(N, L))) tile texels to prevent shadow acne on surfaces slanted to the light
- ToonRenderer: setLocalShadows(ShadowAtlas, strength), beginShadowAtlasPass(atlas), setShadowAtlasTile(atlas, tile index) (ends with endShadowPass). ToonDrawQueue.drawLocalShadows(renderer, atlas)
- Point lights: castsShadow (default false), shadowNear (default 0.05; the far distance is range, 30 if 0)
- Light color usage: ToonLightSet.setLightColorUsage({ base, shade, highlight, rim, shadeRim, matcap, angelRing, outline }) (also on the renderer). Chooses for each color whether to multiply by the light color. When off, base, shade and highlight receive only the light's luminance, and the rest receive no light. (The Is_LightColor_* of the Unity Toon Shader, all on by default) Rim, matcap and shell outlines now also multiply by the sun's color by default. The previous look is setLightColorUsage({ rim: false, matcap: false, outline: false })
- Shade-side rim: ToonLightSet.setShadeRimLight(color, power) (also on the renderer). Adds a rim on the side facing away from the sun by (rim - half Lambert). (The Antipodean Rim Light of the Unity Toon Shader)
- Shell outlines: with setOutlineFadeDistance(near distance, far distance), the width becomes 0 when far. (The Nearest, Farthest Distance of the Unity Toon Shader, from the model's position to the camera) Per draw, outlineOffsetZ pushes it away from the camera so it does not show through in front of the body. (Offset Z)
- Angel ring: draw options angelRingTexture, angelRingColor (default white), angelRingOffsetU (default 0), angelRingOffsetV (default 0.3), isAngelRingAlpha. u is the x of the view-space normal, and v is the y of the second UV blended with the y of the view normal by offsetV. (The Angel Ring of the Unity Toon Shader, a hair reflection band attached to the camera)
- Second UV: MeshBuilder shape uvs1, addTriangles uvs1, readArrays uv1Data, and ToonGlb reads TEXCOORD_1. The shader's vertexUv is vec4(UV, second UV), and ToonVertex.uv1, ToonSurface.uv1 were added. Exports readUvData
- Texture units: the point light shadow atlas uses unit 0 and the angel ring uses 7. Material textures are 8 ~ 15, and TOON_MAXIMUM_MATERIAL_TEXTURES changed 9 → 8. Unit 0 is the unit the engine's 2D drawing remembers, so beginFrame records its binding and endFrame restores it
- Shader uniforms: lightColorUsage, lightColorUsageExtra, shadeRimLight, angelRingSettings, angelRingColor, localShadow* , pointLightShadowSlots, and for shells outlineFadeDistance, outlineOffsetZ, outlineLightColor, cameraForward
- Angel ring: rotates the UV back by the camera roll. (The same computation as the Camera Rolling Stabilizer in the Unity Toon Shader source; exports readCameraRoll, shader uniform cameraRoll) The ring stays on the head even when the camera is tilted
- Light intensity limit: ToonLightSet.setLightIntensityLimited(boolean), isLightIntensityLimited() (also setLightIntensityLimited on the renderer). The same computation as the Limit Light Intensity of the Unity Toon Shader, and on by default like the Unity Toon Shader default
- The sun and fill light are clamped to 1 per channel, and point lights and spotlights are divided by the intensity when the intensity of the color multiplied through attenuation (0.299 R + 0.587 G + 0.114 B) exceeds 1. If the light model is isEnergyNormalized, the share after dividing by π is limited
- Scenes that used a sun above 1 or strong point lights look different. (Those that used strong lights for HDR bloom) The previous look is setLightIntensityLimited(false)
- When porting an old game shader (one that did not limit light intensity), or when using point lights above intensity 1 or HDR bloom, use setLightIntensityLimited(false)
- The intensity received by colors with light color usage off was also changed to 0.299 R + 0.587 G + 0.114 B, the same as the Unity Toon Shader. The sun color multiplied into shell outlines is divided by its intensity when the intensity is 1 or more (the Unity Toon Shader outline)
- Toon GLB accessor reading: an accessor that reads outside the binary chunk throws an error ("GLB accessor N reads outside the binary chunk.") instead of yielding an empty model, and an accessor without a bufferView is filled with zeros per the glTF spec (same as the Rust edition)
- Added six to the top-level exports (same as Rust): import.js now exports AudioManager, DevTools, Pane, PaneStyle, PaneTheme and WebSocketClient (same as the pub use in the Rust lib.rs). Docs and examples are filled in too.
- The toon body shader's readShadeLevel no longer reads the dynamic index shadeStopColors[shadeStopCount - 1] when there are zero shade stops; it finds the last stop with a loop: on iPhone SE2 (A13, iOS 27.2.1) Safari the first draw with a toon program containing that read killed the GPU process and lost the WebGL context (the next shader build then showed 'compile failed: null'). A scene with two or more shade stops computes the same values, byte for byte. Migration: none.
Performance
- Less CPU in the toon draw queue and the GPU memory tracker (picture unchanged): ToonRenderer.findDrawEntry looks the options object's remembered entry up in the WeakMap once (it used to look it up twice, has then get). GpuMemoryTracker no longer formats and parses the call stack when a GL object is created; it only captures the frames and resolves the owner name once, when readUsage reads the owners (building the stack text cost time every time a material block or texture was created mid-frame). The ownerList result is the same.
- Toon program variant prewarm (the standard way, like Unity ShaderVariantCollection.WarmUp and Unreal PSO caches: build before the first draw, picture unchanged): body feature variants were built in the first frame that drew a combination not seen before, which could hitch once (about 250 ms right after a round starts in Aberrant on iPhone 15). Added ToonRenderer.prewarmDrawQueue(queue). It builds, without drawing and with the same keys, the variants the items in a draw queue will use (material, instance layout, body feature bits, ambient occlusion body, outline, shadow depth). With KHR_parallel_shader_compile it only hands off compiling and finishes the compiled ones a few per frame so the main thread is not blocked; without it, it builds inside the call. The returned ToonProgramPrewarm tells the end with isReady() and wait() (a Promise). Drawing before it finishes is fine, and a variant not built yet is built on the spot as before. ShaderProgram gained the last constructor parameter isDeferred, isBuildComplete(), finishBuild() and the static isParallelCompileSupported(gl) (default behavior unchanged). On headless Chrome on a Mac, the first draw frame of a scene with three variants and one instance layout took 61 ms without prewarm (20 compileShader calls, 10 linkProgram calls) and 0.5 ms after it (0 calls), with a byte-identical picture. (tests/graphics3d/toonprogramprewarmchrome.test.mjs)
- Toon body variants: reduced the hitch when a combination first appears mid-scene (a light set turning on rim, shade rim or a ramp texture changes the body feature bits) (issue #2). The body feature bits change through five light set bits (ramp texture, shade stops, rim, shade rim, light intensity limit) and six draw options bits (five textures, receive shadow). (a) prewarmDrawQueue(queue, options) gained the optional argument options. Pass the combinations the game will use, like Unity ShaderVariantCollection, with options.lightFeatureList (per combination, an array of the light feature names that turn on additionally, e.g. [["rim"], ["rim", "shadeRim"]]), options.lightSetList (the light sets to be used) and options.queueList (draw queues holding materials and instance layouts that appear later), and those combinations are prewarmed. (b) Added ToonRenderer.setAsyncProgramBuild(isAsync) and isAsyncProgramBuild() (default true). With KHR_parallel_shader_compile, a body variant first seen mid-scene only has its compiling handed off and is drawn with the default body program (every feature on) until it finishes, so the frame is not blocked (the default body gives the same picture, checked by a test, byte-identical). Without the extension it is built on the spot as before. On headless Chrome on a Mac, per-frame draw time of a scene whose light changes four times: built on the spot 7.6, 7.5, 9.7, 9.8 ms; prewarmed with a combination list 0.1, 0, 0, 0 ms (0 builds); handed off and drawn with the default body 0.3, 0.2, 0.1, 0.1 ms. (tests/graphics3d/toonprogramprewarmchrome.test.mjs)
- Toon body shader skips the point-light loop body outside the light radius : outside the radius (lightRange > 0, rangeExponent > 0 and lightDistance >= lightRange) the attenuation window is exactly 0 and the contribution is 0, yet the body shader still ran two pow calls, the shadow read and the shade-level reads for every such pixel. Derivatives (fwidth) are now computed outside the branch where every pixel runs together (derivatives inside a branch are undefined when a quad neighbour skips), and the derivative-free heavy work (attenuation, shade-level reads, color limit) is skipped there. The point-light shadow read feeds the ramp coordinate, so it stays outside the branch. The skipped contribution was exactly 0 (readLimitedLocalColor(0) and readLightColor(0) are 0, the shade values are clamped finite numbers), so the screen is byte-identical. The miner game (iPad mini 6, one lantern, range 2.6) bisected it: one point light cost about 4 ms per frame.
- Fewer activeTexture calls in toon drawing: ToonRenderer switched the active texture unit back to 0 after every draw, so the next draw called activeTexture(4) and activeTexture(0) again even when only the base color (unit 4) changed. Draws no longer switch back (stage callbacks and onBeforeDraw of body draws are still called with unit 0 active, and endFrame restores the previously active unit), saving state does not switch units when unit 0 is already active, and restoring skips the unit 0 binding and active unit when the state cache knows they already match. activeTexture per frame (headless Chrome, 1280x720): room scenes (room, roommove, roomitem) 49 -> 24, lobby 132 -> 28; bindTexture 31 -> 30 and 73 -> 72; the screen is byte-identical. About 17 of the remaining 24 in the room come from ToonScreenOutline's line pass and line drawing. A Chrome test (tests/graphics3d/toontextureunitchrome.test.mjs) checks that a frame whose base color texture changes on every draw makes at most 12 activeTexture calls (26 before the fix, 11 after), that callbacks see unit 0 active, and that the active unit and unit 0's texture are restored after the frame.
- Retained toon draw items and no per-frame allocation in the draw queue (Unity MeshRenderer, Unreal primitive component, no allocation in the frame loop): added ToonDrawItem and ToonDrawQueue.createItem and addItem. Build the mesh, model matrix (copied) and options once and hold them; the draw queue then does not compare or resolve the options object every frame, and only setOption, setOptions and markDirty mark a change. Items with no change are not compared by the shadow cache (onChange) either. The current pattern of passing a new options object to addMesh every frame no longer builds a memory entry per options object: the queue slot keeps its own entry and reuses it when the shallow snapshot is equal (an options object that comes back to the same slot is remembered per object). The queue's lists are written by index and only their length is set instead of being cut to length 0 (V8 releases the backing store at length = 0 and grows it again every frame), and the line pass groups, transparent groups, light key, shadow caster lists and callbacks, instance buffer bounding sphere and identity matrix, and the subarray of batch uploads now reuse their storage. readMatrixDeterminant builds no arrays, and Math.hypot (V8 builds an argument array on every call) is replaced by readHypot with the same arithmetic in the same order (bit-identical on 5 million triples in Node 25). Matrix4 multiply, translate, rotateX/Y/Z and scale reuse a result buffer. Added writeInstanceBufferSphere (bounding sphere into a given array), TransformNode readPosition, readScale, readLocalPosition, readLocalScale and WorldNode readPosition, readContentSize, readPivot (into a given vector, the get functions are unchanged); UINode's transform no longer clones the local scale. WorldNode.contains (the path UIButton uses every frame to ask whether the pointer is over it) does the same arithmetic as getWorldCorners into reused storage and builds no vectors, arrays or OBB (bit and result identical on 1800 nodes of random trees, 36000 tests). Engine allocation per frame in the settings window scroll list (tests/ui/scrolllistbench.mjs, still part) 457 to 75 KB, the miner settings window shape 388 to 59 KB. With no gamepad connected, navigator.getGamepads is not called every frame but scanned once per second (connections come from the gamepadconnected event, the scan picks up pads whose event was missed). The screen outline's line color table is not uploaded again when the same color is set again, or when colors are cleared and the same colors set again. Engine draw queue allocation per frame (headless Chrome, Mac mini, 960x540, CDP HeapProfiler sampling): room scene (36 multi-part models, 216 draws, options rebuilt every frame) 309 to 43 KB, the same room with ToonDrawItem 312 to 43 KB, lobby scene 236 to 55 KB, miner mid scene 78 to 31 KB. Engine JS self time (CDP Profiler, ms per frame) room 0.515 to 0.287, ToonDrawItem 0.508 to 0.248, lobby 0.498 to 0.461, miner 0.114 to 0.064, garbage collector in the room 0.047 to 0.008. All four scenes have the same GL call counts and screen bytes. (tests/graphics3d/toondrawitemchrome.test.mjs, toondrawbench.mjs room, roomitem, allocation sampling)
- Toon screen outline resolution scale (setResolutionScale, default 1, the same meaning as Unity URP renderScale and Unreal's screen percentage): as the name says, every target before the blend (the line target, the mask, the seeds, the jump flood targets) is shrunk to drawing area x scale. It used to shrink only the jump flood targets. The default 1 leaves the screen byte for byte the same. Below 1, a thin line (width x scale up to about 3.24 line-target pixels) computes its coverage (strength times the line-id color, an RGBA8 target, getLineTarget().coverageTexture) once at the mask resolution, and the final blend reads it once with bilinear filtering (nine reads become one). A thick line floods at the line-target resolution and measures the distance in drawing-area pixels when blending. The line width (setWidth) is in drawing-area pixels at any scale. The lineTexture and depthTexture of getLineTarget are drawing area x scale in size (the lineTexture contract stays: RGBA8, the id in b and the low 6 bits of a, flags in the top 2 bits of a, and width 0 draws only the line target). outlinePath gains "thinScaled" and readProgramSources returns nine. To match 1.5 pixels per CSS pixel, pass setResolutionScale(1.5 / (buffer pixels per CSS pixel)) (canvas width / clientWidth, which differs from devicePixelRatio when the engine resolution setting bundles the buffer). On an iPhone SE2 with the miner values (width 2.62, alpha 0.65, 750x990) the outline cost at scale 1, 0.75, 0.5 is 17, 12.5 and 8 ms (counted by drawing the same frame back to back and reading back).
- Batched drawing names same as the Rust version: Graphic.setSpriteBatchingEnabled, isSpriteBatchingEnabled and flushSpriteBatch are now setBatchingEnabled, isBatchingEnabled and flushBatch (Rust set_batching_enabled, is_batching_enabled, flush_batch). A batch holds not only images but also shapes, text and vertex color quads, so 'sprite' narrowed the meaning. flushSpriteBatch is removed.
- Drawing outside the engine loop (the same contract as a 2D canvas): what is drawn into a batching Graphic outside the engine loop (a Graphic made without an engine, your own requestAnimationFrame, an input handler) is now drawn by the engine when that task ends (a microtask). That is before the browser presents the canvas, so it shows without an explicit flush. Until now the batch was flushed only at the end of an engine frame, so the OPTIONS panel of the neonhorizon example, which uses Graphic without the engine loop, was not drawn (0.3.2 drew it). Inside an engine frame it does nothing, because the engine flushes first at the end of the frame.
- Measuring text once: glyph layout goes through the text measure cache when it measures a whole left-to-right string at scale 1. What Text already measured with the same font string and text for its drawn rectangle (off-screen culling) is not measured again. measureText in timelineshowcase, whose time text changes every frame, goes from 2.85 to 1.75 calls per frame. (The rest measures character pairs seen for the first time and stays in the cache, 0.3.2 made 1.05 calls)
- Faster Graphic construction: the grapheme segmenter (Intl.Segmenter) used by glyph layout is now created once, when non-ASCII text is first split, instead of when a Graphic is made, and it is shared. Printable ASCII text has one character per grapheme cluster (UAX #29), so it is split without the segmenter. Chrome takes about 5 ms to create the first Intl.Segmenter. new Graphic(canvas) goes from 14.3 to 8.3 ms (headless Chrome, median of 8, 0.3.2 takes 5.6 ms).
- Does not use discarding attachments at the end of a pass (invalidateFramebuffer); passes that overwrite a whole target clear it first (clearBufferfv): measured per site on real devices in Safari (iPhone SE2, iPad mini 6), no site showed a gain and each added several to tens of ms per frame (frame of the toon post process with bloom and ambient occlusion: 51 ms on SE2 becomes 11 ms with it off, 41 ms becomes 14 ms for the multisample target with multi-level bloom, 90 ms becomes 25 ms on iPad, no difference in desktop Chrome). RenderTarget.resolve() no longer discards attachments after resolving (the argument of resolve(isAttachmentKept) is no longer used and is kept), and the opacity layer (beginOpacityLayer) no longer discards its depth and stencil when it ends. The bloom bright extraction and blur, the multi-level bloom extraction and downsampling, and the four ambient occlusion passes clear their target first (clearing matches not calling anything, checked on SE2). The screen result is unchanged.
- Text drawing uses a glyph atlas (the same model as the Skia glyph cache, Unity TextMeshPro dynamic atlas and Unreal font cache): instead of baking each string whole on a canvas and uploading one texture per string, each grapheme chunk is baked once per font (mode, font string, bake scale, line width) into atlas pages (1024 x 1024, glyphs go into the newest page and a new page opens when it is full, up to 8, beyond that the least recently used page is cleared), and strings are drawn as glyph quads through the sprite batch. A new string bakes only glyphs it has not seen, and text on the same page is one draw call. The pixels match Chrome drawing the whole string with fillText: Chrome (Skia) rasterizes glyphs separately at 4 horizontal subpixel positions (rounding 1/8) and stamps them at integer positions, so glyphs are keyed by (grapheme chunk, 1/8 position slot) and placed where measureText puts them (width of the previous chunk joined with this one minus this chunk's width, kerning included). Latin, Cyrillic and similar letters that can form ligatures are baked per word, right-to-left text (Arabic, Hebrew) and fonts over 256px per string. In headless Chrome (macOS; Korean, English, digits, mixed, emoji, ligatures, Arabic, Thai, Devanagari, Cyrillic, several sizes and weights, outline, device pixel ratio 1 and 2) the pixels that differ from before are 6 at 1:1 (setTextBakeScaleStep(0), setTextPixelSnapEnabled(true)) ratio 1 (at most 4 levels) and 2 at ratio 2 (1 level), from 8-bit compositing where glyph ink overlaps. Text placed at fractional positions or stretched can differ by up to 10 levels where neighbouring glyph ink touches within one texel, because linear filtering runs per glyph (57 pixels with the default settings at ratio 1). The top and bottom row of each cell repeat the edge rows of the string rectangle, so at fractional vertical positions, when ink taller than the line (Arabic and the like) touches the end of the string rectangle, linear filtering no longer samples a different atlas row (9 pixels, up to 15 levels before), and blank chunks (spaces) are not baked. A 50-line text screen goes from 100 draw calls to 1, and 300 new strings made of known characters go from 300 bakes (texture uploads) to 0. The entry from TextStringTextureCache.getEntry holds glyphTextures and glyphRects (left, top, right, bottom, u0, v0, u1, v1 per glyph) instead of texture, and readAtlasStatistics() reports page, glyph and upload counts.
- 2D batching breaks less often (screen output unchanged): (1) Axis-aligned square clips whose edges lie on pixel boundaries (beginClipRect, Mask, UIScrollView) are clipped by the batch shader instead of the stencil, by pixel center, using a clip-rectangle table index carried in the vertices (the Unity RectMask2D and UI Toolkit scheme), so setting and releasing a clip keeps the batch going. Rotated or rounded clips, and clips whose edges are not on pixel boundaries on a multisampled canvas, use the stencil as before (a multisampled stencil half-covers edge pixels, which differs from the pixel-center rule). Draws that are not batched (swapped-in shaders, shader blending, shader-blended particles) get the same rectangle as a scissor, and runExternalPass writes the shader clips into the stencil for its duration. (2) One batch binds several textures (the smaller of the device MAX_TEXTURE_IMAGE_UNITS and 16), so it continues across images, shapes (white texture) and text textures (the PixiJS scheme). (3) drawColoredQuads (particles, heat haze) also joins the same batch under fixed blending and is computed with the same formula as the particle shader. (4) Off-screen culling also checks the bounding box of the active clips, so components of rows outside a scroll view are not drawn (like Unity RectMask2D, automatic, no option). UIView (background only), UIButton and UIProgressView report isDrawnInsideContent like the Rust edition, so such nodes are culled too. Hit testing already skipped descendants outside a Mask. The batch vertex cap is 6 x 8192, the same as the Rust edition. Measured (headless Chrome, pixel ratio 1.5, pixels identical to before): a settings-window scene (one window, UIScrollView, 50 rows, each with text, a button and a shape) 128 draw calls to 1, scrolled 132 to 1, examples/uigallery 61 to 2, devtoolsshowcase 95 to 4, particleeffects 72 to 8, effectgallery 229 to 150. New test tests/core/batchclipchrome.test.mjs (shader and stencil clips match to the pixel with fewer draw calls, rows outside a scroll view are culled)
- UI geometry cache (on by default, screen output unchanged): nodes draw components through Graphic.drawComponent, and components that report their draw inputs through Component.writeGeometryKey (Paint, UIView, the Text of UILabel, the Sprite of UIImageView) have their drawn vertices cached per component. While the inputs (color fields, sizes, text, images, etc. written to GeometryKey) and the scale, rotation, blend and tint stay the same, draw is not called: if the translation and opacity are also the same, the captured device vertices are copied into the batch as is, and if only the translation or opacity changes (scrolling, moving a window, fades), only the new matrix and opacity are applied to the cached local vertices (the model of Unity UGUI keeping each Graphic's mesh in local space and rebuilding only what changed; text recomputes pixel snapping identically). Changes are detected by comparing inputs rather than by dirty flags in setters, so mutating a Color in place is also recomputed. Components that do work outside the batch inside draw (clipping, layers, changing the blend mode, etc.) and subclasses that override draw are drawn every frame as before. Graphic.setGeometryCachingEnabled turns it off, and getLastFrameGeometryCacheHitCount and getLastFrameGeometryRebuildCount count it. Retained batches: each batch is kept in a GPU buffer per draw position in the frame (up to 32 positions), and the vertices put into it are recorded in order as segments (geometry cache segments with their versions, and the vertex counts of spans written directly without a cache). At the same position in the next frame, the same segment at the same place is neither copied nor uploaded (directly written spans have no version, so their vertex values are compared with the span at the same place in the previous frame); only the changed segments, the directly written spans whose values changed, and everything after a segment whose vertex count changed (shifting what follows) are uploaded with bufferSubData (ranges separated by 256 vertices or fewer are merged, at most four calls per batch, otherwise one call from the first range to the last). When everything is the same only the draw call is issued (the way a Unity UGUI Canvas redraws its previous batch mesh and rebuilds only the graphics that changed; draw order, clip slots, texture slots and blending stay the same, so pixels are identical). The first time, when the vertex count grew, or when everything changed, everything is uploaded with bufferData into new storage. ANGLE on Metal (macOS and iOS) does not stall the CPU when bufferSubData changes a buffer the GPU is still using: it writes the changed range into a new buffer and moves the rest with a GPU copy (ANGLE BufferMtl::setSubDataImpl, putDataInNewBufferAndStartUsingNewBuffer). Previously a single uncached draw such as an Outline made the whole batch upload again with bufferData every frame (227 KB per frame in a static UI test scene of 14 rows with 14 outlines, now 0; changing the text of one row every frame uploads 3.7 KB and moving one icon uploads 1.7 KB, each with one bufferSubData, and the screen is byte-identical). Counted with Graphic.getLastFrameRetainedBatchCount (batches that uploaded nothing; with the cache off it also counts batches whose directly written vertices equal the previous frame). The 2D batch array now starts at 512 quads (172 KB) and doubles when needed up to the limit (8192 quads), and the end-of-frame batch buffer no longer reserves storage up front (previously a 2,688 KB CPU array and a 2,688 KB GPU buffer were reserved at the limit from the start). A sprite command whose translation alone changed keeps the first part of the matrix product in Float64 and only adds the translation (same order of operations, bit-identical). Measured (headless Chrome, cache toggled every 10 frames in one page, median CPU time of the scene tree draw plus the end-of-frame batch draw, in parentheses the median on/off ratio of paired 10-frame blocks): 240 visible cells (rounded background and text) static 0.930 to 0.565 ms (0.56), a settings-window-like scene static 0.270 to 0.215 ms (0.81), examples/uigallery 0.255 to 0.230 ms (0.87), the clipping scene (batchclip) 0.185 to 0.170 ms (0.85), settings window while scrolling 0.275 to 0.335 ms (0.94, ratios over several runs 0.94 to 1.02), 240 cells while moving 1.110 to 1.335 ms (ratio 0.73 to 1.20; the previous version also swung from 0.72 to 1.42, so it cannot be told apart while the machine is busy). New test tests/ui/uigeometrycachechrome.test.mjs (cache on and off are identical to the pixel when static, scrolling, and after changing position, color, text, visibility, opacity, scale and rotation, and nothing is recomputed in static and scrolling frames)
- Off-screen subtree culling (on by default, screen output unchanged): each node keeps its subtree draw bounds (the union of its own drawing and the bounds of its active, visible children, in the node's content coordinates) and recalculates them only when something changed, and after drawNode applies a node's transform it skips the draw traversal of that node and its descendants entirely when those bounds are outside the screen and the active clips. Updates (tick) still run. When a transform, content size, pivot, added or removed child, active state, visibility, added, removed, enabled or disabled component, or a value that changes a drawn rectangle such as a Text's text and font changes, a dirty mark spreads to the ancestors (scene graph bound dirtying, the same shape as Unity UGUI SetVerticesDirty and Godot item_rect_changed). A subtree that contains something whose drawing area is unknown (a component that does not report its bounds, a node that overrides draw without reporting calculateDrawnRect, a node that draws gizmos, a node that overrides reading its position or transform, a node that does not report how it is placed in its parent's coordinates) is never skipped. Drawing the scene of a settings-window-like scroll list (120 rows, each with a background, an icon, two texts and three buttons, about 10 rows visible) went from 0.92 ms to 0.26 ms when still and from 0.99 ms to 0.29 ms while scrolling, the same as the game turning off the invisible rows itself (0.26 ms, 0.27 ms) (Mac mini M2 Pro, headless Chrome, tests/ui/scrolllistbench.mjs). New API: Graphic.setSubtreeCullingEnabled, isSubtreeCullingEnabled, getLastFrameCulledSubtreeCount, TransformNode.readSubtreeDrawBounds, calculateSubtreeDrawBounds, markDrawBoundsDirty, markParentDrawBoundsDirty, getLastDrawnFrameNumber, WorldNode.calculateDrawnRect, Component.markDrawnRectDirty, Component.markAllDrawnRectsDirty, Component.getDrawnRectGeneration. Per-node off-screen culling treats update-only components (those that do not override draw, such as ButtonMotion) as drawing nothing. When checking whether a node's text bake scale is moving, a node that was not drawn in the previous frame is treated like one drawn for the first time (setLastDrawnMaximumScale also takes the frame number).
- Wider drawn-area reporting: UISlider (the thumb circle spills by its radius along the whole range it moves over, a value-independent rectangle), ShadowText, ShadowImage (twice the shadow blur plus the offset), RichText (the joined single line), UILineChart (out-of-range values), UIBarChart, HeatHazeEffect (wobble amplitude), and UIInputField's context menu (shadow) and background and overlay layers (up to the visible text width on a single line) report where they draw through calculateDrawnRect and call markDrawnRectDirty in every setter that changes that rectangle. Subtree bounds calculation moved up to TransformNode, and moving a child into parent coordinates is done per node kind through transformDrawBoundsToParent (WorldNode by position, rotation, scale and pivot, UINode by the solver's placement). UINode now recalculates its bounds when the solver's position or size changes (LayoutVariable.setValueChangedEvent), so it can be skipped. Position, scale, rotation, visibility, pivot and content size setters no longer dirty anything when given the same value. Drawing a scene that carries the engine components of Rimminer's settings window as is (120 rows) went from 0.370 ms to 0.215 ms when still and from 0.390 ms to 0.265 ms while scrolling with culling on (off 0.640 ms, game culling 0.140 ms, tests/ui/scrolllistbench.mjs). New API: TransformNode.calculateDrawnRect, transformDrawBoundsToParent, transformLocalRectToParent, WorldNode.transformDrawBoundsToParent, UINode.transformDrawBoundsToParent, calculateDrawnRect on UISlider, ShadowText, ShadowImage, RichText, UILineChart, UIBarChart and HeatHazeEffect, LayoutVariable.setValueChangedEvent, getValueChangedEvent. ParticleSystem, TrailRenderer and TouchEffect do not report their drawn area yet (their ancestors are not skipped).
- Culling in parent coordinates first: when a parent calculates its subtree bounds, it writes each child's bounds moved into the parent's coordinates onto the child (TransformNode.readParentDrawBounds, valid until the child's transform or bounds change and the parent recalculates), and drawNode compares those bounds against the visible rectangle in parent coordinates (the screen and active clips moved back by the current transform as a bounding box, one device pixel looser, calculated once per parent while the transform and clip stay the same) before applying the child's transform, skipping the child without applying the transform when it lies outside. Scrolling changes only the parent's transform, so the children's bounds are not recalculated. Rotation and skew stay conservative through bounding boxes, and drawing order is unchanged. Flat lists (hundreds of direct children under one group node) no longer apply a transform to every off-screen child.
- Drawing only the visible range of children: child drawing is gathered into TransformNode.drawChildren (called by TransformNode.draw and WorldNode.draw). When the subtree bounds are calculated, the parent-coordinate bounds written for each child are kept as the largest bottom and right gathered from the front and the smallest top and left gathered from the back, and at draw time a binary search against the visible rectangle (the new Graphic.readLocalVisibleBounds) skips the children before and after the range without even calling drawNode. It is correct in any child order (rows laid out in order leave only the visible rows), a child with unknown bounds or a hidden child stops the narrowing at its position, and if the node's bounds change while drawing all remaining children are checked. Skipped children are counted as if culled one by one (the new Graphic.addCulledSubtreeCount). Drawing order is unchanged.
- Subtrees fully inside the visible rectangle (the 'fully inside' flag of frustum culling): when drawNode finds that a node's subtree bounds lie fully inside the visible rectangle (the screen and active clips shrunk by one device pixel; tested in parent coordinates before the transform when the parent transform is axis aligned, and in device coordinates after the transform when there is rotation or skew), its descendants are drawn without the subtree test, component culling or the visible child range search while that node is drawn, and only descendants that draw nothing (bounds of size 0) are skipped. When a new clip (mask, scroll view) is set below it, testing starts again inside that clip (a clip state number that returns to the previous state when the clip ends). Skipped counts and the image are unchanged. New API: Graphic.isInsideVisibleBounds. Empty text (Text, UILabel with text "") reports its drawn area as size 0. It used to be unknown, so a subtree holding an empty label was traversed even off screen (the toggle button of the Rimminer settings window: every off-screen slider row was traversed down to its empty label and drew two text components, 62 per frame in the 120-row scene). Drawing the Rimminer settings window scene (120 rows) with culling on went from 0.280
0.300 ms to 0.1900.200 ms static and from 0.3150.330 ms to 0.2000.205 ms while scrolling, now faster than the game turning off invisible rows (0.2100.235 ms). Transforms pushed 153 to 60 (game 124), screen tests after the transform 118 to 7 (game 58), component draws 149 to 87 (game 87). Most of the Rimminer gap was the empty text (a build with only that fix draws in 0.190 ms, the same as the game culling). The engine scene went from 0.3050.310 ms to 0.2400.290 ms static with culling on (game 0.2850.335 ms), screen tests 156 to 19 (game 78) (Mac mini M2 Pro headless Chrome, tests/ui/scrolllistbench.mjs, before and after alternated twice). - ParticleSystem and TrailRenderer report where they draw (bounds recalculated every frame, as in Unity): the quads of live particles (half the size times √2, head and tail for streak quads, plus the wobble amplitude) and the trail points (half the larger width). They call markDrawnRectDirty when the simulation runs, on emit, on clear, and in setters that change how they draw, so only drawing is skipped when off screen while the simulation (tick) keeps running. World-space particles with manual tick report unknown (not skipped).
- GL state cache (WebGLStateCache, in the style of three.js WebGLState and the state memory of the Chrome GPU command buffer client): right after Graphic creates the context it intercepts the context's state functions (bindFramebuffer, viewport, scissor, enable, disable, clearColor, colorMask, blendFunc, blendFuncSeparate, blendEquation, depthMask, depthFunc, frontFace, cullFace, useProgram, bindVertexArray, activeTexture, bindTexture, pixelStorei and the deletes) and remembers the changed values; getParameter and isEnabled answer from memory without asking GL. In Safari these reads are synchronous round trips to the GPU process, so the reads done while drawing by the engine 2D path (restoring the framebuffer), toon 3D (saving state) and game renderers all go away (about 1.5 ms per frame on the game renderer side of Rimminer on iPad). Limits that never change (MAX_SAMPLES and so on) are asked once. Values that are not remembered (stencil functions, buffer bindings and so on) still go to GL. Unknown values (at first, after arguments that cannot be checked, programs whose link result is unknown) are asked once on the next read. A headless Chrome test (tests/core/webglstatecachechrome.test.mjs) mixes wrong arguments, deletes and context loss over more than 600 random calls and checks that the cache answers match real GL (0 differences) and that GL is asked 0 times while drawing. Context loss is known from a flag set by the webglcontextlost and webglcontextrestored events, so isContextLost is not called for each intercepted getParameter and isEnabled (previously it was called on every read: 40 times per frame in a measured game screen and 64 times in the engine's toon room and lobby scenes, now 0; real getParameter queries to GL are 0 before and after; the test also checks 0 isContextLost calls while drawing). Added the public functions Graphic.getCurrentFramebuffer() (the framebuffer being drawn to, null for the canvas), getCurrentViewport() (the current viewport as a Rect, device pixels, bottom-left origin) and resetGLStateCache() (resynchronize the memory, like three.js resetState).
- Fewer toon 3D draw state changes (in the style of the Unity SRP Batcher and three.js WebGLState and WebGLUniforms): for every draw ToonRenderer asks the GL state cache about the program, the nine texture units, the front face winding and cull face, and the vertex array, and does not set them again when they are the same; for uniforms it remembers the last uploaded value per program and name and skips uploading the same value (bone matrices too; the memory is dropped and everything uploaded again at the start of a frame or shadow pass, after stage callbacks and the screen-space outline, and after that program's onBeforeDraw). ShaderProgram.useProgram() also skips when the state cache remembers that the program is already in use. ToonDrawQueue draws opaque things (bodies, outline shells, shadow depth) sorted by material, model and base color texture (ties keep the added order; transparent things stay farthest first). In a heavy toon scene (58 models and 400 instanced rocks, 6 skinned models, sun shadow and two point light shadows, outline shells and the screen-space outline, headless Chrome on a Mac mini M2 Pro) GL calls per frame went 6146 → 2476 (useProgram 344 → 38, uniform 2918 → 1415, activeTexture 549 → 88, bindTexture 480 → 48, state changes 1353 → 385, draws unchanged at 393), the median CPU frame time 3.1 → 0.8 ms, and the screen is bit-identical. The state cache test checks that whenever a comparison function (isProgramInUse, isTextureBound and so on) answers "same", the real GL value is the same too (518 times, 0 wrong).
- Fewer shadow redraws (in the style of the per light shadow update mode of Unity HDRP and the cached shadow maps of Unreal): added setUpdateMode(ShadowUpdateMode, frame count), getUpdateMode, getUpdateInterval and requestUpdate to ShadowMap and ShadowAtlas. ShadowUpdateMode is everyFrame (everything every frame, the behaviour so far), onChange (default) and interval (everything every N frames, the frames in between keep the previous shadow). With onChange, ToonDrawQueue.drawShadows and drawLocalShadows compare the casters with the previous frame in the order they were added (mesh, material, model matrix and instance matrices, joint matrices, index buffer range, frustum culling, mirroring, light matrices and atlas tiles). Casters unchanged for 30 frames are baked into a separate target, and only the moving ones (and materials with a vertex chunk) are drawn every frame on top after copying the baked target into the shadow target (blitFramebuffer). It bakes again when a baked one changes or is removed or a new one becomes bakeable, and a frame where the light changed draws everything straight into the target. When everything is unchanged nothing is drawn. Depth keeps the nearest with LEQUAL, so the baked and overdrawn target is bit for bit the same as drawing everything at once. In the heavy toon scene (the same scene as above, Mac mini M2 Pro headless Chrome) a frame where everything is still goes from 393 to 168 draws and from 2476 to 1627 GL calls, a frame where six skinned models move goes from 394 to 195 draws and from 2477 to 1825 GL calls, the median CPU frame time goes from 0.8 to 0.4 ms, and the screen is bit for bit the same in both cases. A Chrome test (tests/graphics3d/shadowcachechrome.test.mjs) checks over 110 frames, where a box moves, stops and moves again, an instance moves, the sun and a point light move and a model is removed and comes back, that the screens of everyFrame and onChange are the same every frame (deliberately breaking the check is caught at frame 61).
- Sun shadow focus step (cuts the onChange cache redraws every frame in scenes where the focus follows a moving camera): added setFocusStep(world step) and getFocusStep to ShadowMap. With a step, updateLightMatrix snaps the focus to multiples of the step along each world axis (x, y, z) so the light matrix stays the same inside one cell, and adds the step as margin to the covered width and depth so the area around the focus never leaves the map. Texel snapping still applies on top. The default 0 behaves as before (texel snapping only).
- Lower CPU cost per toon draw (in the style of Unity's SRP Batcher): the nineteen material values of the body program (tintColor, tintAmount, alpha, glowScale, colorScale, emissiveColor, softEdge, alphaCutoff, premultipliedOutput, textureEnabled, uvTransform, decalUvTransform, decalColor, receivesShadow, shadeOffset, highlightScale, matcapSettings, angelRingSettings, angelRingColor) go into one std140 uniform block ToonDrawMaterial, and the six values of the outline shell (outlineColor, outlineLightColor, outlineWidthScale, outlineOffsetZ, alpha, premultipliedOutput) into ToonDrawOutline. Blocks with the same values are built only once (GPU buffers) and each draw picks one with a single bindBufferBase, skipped when it is already bound. The renderer remembers, per draw options object, a shallow copy (property names and order, value references, the contents of number arrays of four or fewer) and the resolved values, so when a game passes the same options object every frame it does not look properties up by name and resolve them again (only present properties are compared with for-in, cheap even in release builds where obfuscation makes named reads expensive). Changing a tint array in place or adding and removing properties shows on that draw. ToonDrawQueue compares each options object only once during draw and drawShadows, following its promise (class header) that options are not changed meanwhile, and also reads transparency, shadows, line ID and group from the resolved values. It reuses item slots every frame, reuses the order when the opaque sort keys (material, mesh, base color texture) are the same as the previous frame, and builds no new options objects when drawing bodies and outline shells. Program set and uniform slot lookups remember the last one found. Measured with the benchmark tool (tests/graphics3d/toondrawbench.mjs, alternating with a copy from before the change) on an Aberrant lobby style scene (tests/graphics3d/toonlobbyscene.mjs, thirty mesh kinds, forty draw looks, four surface chunk materials, 300 objects, sun shadow, screen-space outline, Mac mini M2 Pro headless Chrome): GL calls per frame go from 4929 to 4437 and uniform calls from 2980 to 2227 (material and outline values moved into blocks, adding 261 bindBufferBase), while program switches 41, texture binds 205, vertex array binds 388 and draw calls 484 stay the same. The number of options property reads by the engine (counted with a Proxy) goes from 10454 to 6172 per frame (34.7 to 20.5 per item, about half of the rest is ToonScreenOutline's line target). In the CDP profile, engine self time (ms/frame) goes for drawWithCount from 0.133 to 0.109 and for writeUniformFloats from 0.109 to 0.022, and drawItem 0.120, drawMeshOutline 0.035 and readOpaqueItemList 0.026 drop out of the top fourteen. The median script time (alternating with the copy from before, three times each, machine load 2 to 15) stays at 2.31 to 2.30 ms. Most of the profiled time is inside GL calls (before: uniform4f 1.61, uniformMatrix4fv 0.88, after: bindTexture 1.10, uniformMatrix4fv 0.82, bindBufferBase 0.61 ms), and that share moves to whichever call regardless of the call counts, which we take to be waiting on the GPU process (a guess, not split apart). So in a non-obfuscated build the smaller JavaScript share does not show up as frame time. (An obfuscated build like the release one, where named property reads are expensive, was not measured) Miner mid style scene (instance buffers, six chunks): GL calls go from 849 to 803 and uniform calls from 395 to 345, draw calls stay at 75, and the median script time is about the same at 0.42 to 0.43 ms. The pixels of both scenes and the five toon examples (toonstyle, toonshowcase, toonview, toonmaterial, toonfx) are the same to the byte as before. A Chrome test (tests/graphics3d/toondrawbatchchrome.test.mjs) checks that changed material values show on that frame, that changing values of the same options object in place shows, that the same values upload no new block, that the result matches a new renderer drawing the same values to the byte, and that reusing the sort order or changing the add order keeps the image the same with transparent things in depth order.
- Shared 3D asset cache (SkinnedModelAsset): skinned model instances built from the same file share one copy of the mesh buffers and vertex arrays, the material prototypes and their textures, the morph textures, the node and skin prototypes and the animation clips, by reference count. (like Unity's mesh and sharedMaterial, or three.js clones) SkinnedModel.loadFromUrl and loadFromFbxUrl look the cache up by shader program and normalized path (SkinnedModelAsset.normalizeKey); on a hit they return an instance without fetching or parsing, and concurrent loads of the same file fetch once. Added createInstance(), createFromAsset(asset), getAsset(), getMaterial(index) (Unity Renderer.material: the first call forks a copy that borrows the textures), getSharedMaterial(index), Material.createInstance(), setBaseColorFactor, getTextureByteCount and SkinnedModelAsset (find, register, clearCache, getCachedCount, normalizeKey, retain, release, getReferenceCount, getGpuByteCount and more). An instance's destroy deletes only its own resources (wireframe buffers, forked morph textures and materials) and releases the asset; when the last instance releases it, the asset deletes its GPU resources and leaves the cache. The clip list is shared by the instances, and adding a clip with an existing name through addAnimationsFromFbx* replaces it in place. addMorphTarget forks only that instance's target list and morph texture. Measured (headless Chrome, examples/ancientmountain/assetcache_test.html, 20 copies of one model): fox.glb from 421 ms and 113.8 MB of GPU memory to 20 ms and 5.7 MB, mannequin_female.glb from 250 ms and 32.0 MB to 9 ms and 1.6 MB. The six foxes in examples/ancientmountain now walk out of step, one instance each. Same API and same test as the Rust edition (tests/graphics3d/skinnedmodelasset.test.mjs).
- UILineChart: lowering the cap with setMaxSampleCount drops the samples already held, oldest first. (Previously they stayed until the next pushValue and points went outside the graph width)
- ShaderWarmer: shader pre-linking. At startup, links the same sources in the background with KHR_parallel_shader_compile and leaves them in the browser program cache, so the main thread does not stall when ShaderProgram later builds the same sources. Does nothing if the extension is absent. update() every frame, isFinished(), isSupported(). Attribute locations are given with the same attributeLocationTable as ShaderProgram
- Engine: calls PointerCursor.apply() at the end of the frame (after drawing the batches)
- ToonRenderer: GPU instancing (drawMeshInstanced, per instance { modelMatrix, tintColor }, for both body and outline), off-screen culling (model bounding sphere against the frustum; instances are culled one by one and only the remaining ones are uploaded, options.isCulled), shadows (beginShadowPass, drawMesh draws depth only, endShadowPass restores the framebuffer and viewport, received with 3x3 PCF via setShadow(ShadowMap)), HDR output (setHdrOutput), drawn count, culled count and draw calls for one frame (getFrameStatistics), extractFrustumPlanes
- Rendering: reduces per-frame object creation and per-draw-call work when drawing nodes and Paint. Rendering results are the same and caller usage is the same. (Capturing the bench scene below and the examples uishowcase, uisample, spriteeffects, particleeffects, timelineshowcase at the same frame with a fixed clock gives screen pixels identical to before the change) Measured at the same time in Chrome (headless, real GPU) on a scene of 8,000 moving nodes drawing rounded rectangles with Paint (the same-spec comparison bench of rustgame-test), drawing goes from 78.0 ms to 13.0 ~ 14.4 ms, the frame from 90.1 ms to 23.9 ~ 26.3 ms, and the node count holding 60 FPS from 1,000 to 4,000 ~ 6,000. (Measured on one PC; game logic time is unchanged)
- Graphic: 2D drawing after outside WebGL. Graphic no longer keeps its own memory of the program in use or the bound textures; right before drawing it compares against the state cache (WebGLStateCache) and sets again only what differs. (program, default vertex array and vertex buffer, texture units and the active unit, blend enable, equation and factors, depth test and face culling off, scissor off unless it is the clip scissor, full drawing buffer viewport) Even when a game uses WebGL through the same context outside runExternalPass (a shadow map after graphic.flushBatch and the like), the next 2D draw and ToonView3D draw correctly. Two promises remain: if the game bound its own framebuffer it puts back the one it found, and it does not change the stencil state. Unchanged frames make no extra GL calls. (GL calls per frame in the test scene went from 268 to 219) invalidateRenderStateCache, which forgot that memory, is removed. (there is nothing to forget; after changing state in a way that cannot be intercepted, call resetGLStateCache) The state cache gains isArrayBufferBound, isCapabilitySet, isBlendFunction, isBlendEquation and isViewport. (comparisons that do not ask GL, false when unknown) (webgame-rimminer reported INVALID_OPERATION: uniformMatrix3fv, location is not from the associated program. When a ToonView3D inside a clipped parent wrote the shader clip to the stencil in runExternalPass, it drew with Graphic's program memory, which did not know the program the game had switched to)
- ImageTextureCache, TextStringTextureCache: Take a texture binding function (textureBinder) as the second constructor argument. Graphic passes it, so the bound texture is remembered even when a cache uploads a texture. Without it, binds directly as now. ImageTextureCache.getTexture binds only when creating a texture or reapplying a filter. (Binding for drawing is done by Graphic)
- Off-screen culling: When Graphic.setCullingEnabled(true) (default false, same as before), before a WorldNode draws its components, if all enabled components report that they draw only inside the content area, the node's component drawing is skipped when the bounding box of the content area (expanded by one unit) transformed by the current transform does not overlap the screen. The test uses Graphic's current transform at draw time (including the parent's scale and rotation and anything applied with pushState). Children are checked separately and drawn as usual, and Mask clipping is still applied. Nodes that override draw, TransformNode and UINode are not culled. (Same approach as Rust vanilla-engine, on by default in Rust)
- Component.isDrawnInsideContent(): Whether it draws only inside the node's content area. The default is false, so a node with any enabled component that does not report it is not culled. Only Paint, Sprite and ShaderSprite (when not flipped, including pieces, nine-slice and tiling), Mask, Outline, SoftShade, UIProgressRing report true. Subclasses that override draw fall back to false. Text (Text, RichText, ShadowText can overflow their box), ShadowImage (shadow margin), ParticleSystem, TrailRenderer and UI widgets do not report it
- Graphic: turns on batched drawing (setBatchingEnabled) and off-screen culling (setCullingEnabled) by default. All games using the current engine (webgame-rimminer, space-creature, aberrant, retrogame-foundyou, steamgame-apocalypsesurvival) ran with batched drawing on, and culling only culls components that report drawing only inside the content area (pixels with it on and off were identical in seven example scenes). For the old behavior, setBatchingEnabled(false), setCullingEnabled(false)
- LoadingProgress: the shown value (getShownProgress) smoothly follows the reported progress (setProgress, 0 ~ 1, never decreases). update(timeDelta) every frame, follow speed setFollowRate (default 6 times the remaining distance per second), isFinished, reset
- Text measurement cache: TextStringTextureCache.measureText and Text measurement do not re-measure when the font string and text are the same. (2048 entries, least recently used evicted first, cleared when a web font is loaded or the document's font face count changes) measureTextMetrics(fontString, text) (textstringtexturecache.js). The returned TextMetrics is shared, so do not modify it
- Component.calculateDrawnRect(rect): Lets a component that draws outside the content area report the rectangle it draws. (default false, unknown) WorldNode off-screen culling checks components that report drawing inside the content area together with these rectangles. Text reports the single-line text rectangle (fitted size, that width even when overflowing, outline plus half the font size on both sides, 1.5 times the font size each vertically). RichText reports unknown. UILabel reports drawing only inside the content area (background)
- Behavior change: single-line Text and UILabel nodes, which were not culled until now, are also culled when off-screen. (When culling is on, wrapping text and rich text are still not culled) If a component that draws directly inside the node is attached as well, that component does not report as before, so the node is not culled
- Color.fromCache(colorString): A color cached by color string ("#..", "rgb(..)", "rgba(..)", white otherwise). The same string returns the same instance (1024 entries, least recently used evicted first), do not modify it. Graphic.setFillColor and setStrokeColor use this cache when given a string
- AudioPlayer.setPlaybackRate(playbackRate): playback speed. (1 is unchanged, pitch changes too, from the next play)
- Color.fromHEXCached: like fromCache, discards the least recently used entries beyond 1024. (Previously grew without limit) Color.getCachedColorCount(): number of entries in the fromCache cache (the Rust version's get_cached_color_count)
- RenderTarget: options sampleCount (2 or more draws into a multisample renderbuffer and resolve() resolves into each color texture and the depth texture, reduced to within MAX_SAMPLES and the sample count each format accepts, without multisampling if unsupported or if the framebuffer is incomplete), depthBits (depth renderbuffer 16 or 24), getSampleCount, getResolveFramebuffer, readSupportedSampleCount. When multisampled, getFramebuffer is the multisample framebuffer being drawn to
- MultiLevelBloomEffect: multi-level bloom. Soft knee threshold while extracting at half size (brightness is the largest of the three channels), dual filter halving at each step, upsampling 2x at each step with a 9-tap tent filter and adding to the level above. Level count (setLevelCount), threshold and knee (setThreshold), buffer precision
- ToonRenderer: pushes shell outlines out in the shader. Uploads the base position and the push offset to the vertices (the width MeshBuilder builds by averaging the normals at the same position and keeping corners from sticking out), and per draw outlineColor, outlineWidthScale, setOutlineDistanceScale(reference distance, minimum multiplier, maximum multiplier) adjust the width with distance. (Perspective only, keeps the on-screen width like Guilty Gear Xrd) Shells without a base position (prebuilt in a GLB) are drawn at their built positions as they are
- Attribute 1 (the vertexNormal slot) of the shell vertex array holds the push offset. If a vertex chunk modifies vertex.localNormal in the outline program, the shell width changes
- Exports the frame uniform viewRotation (matcap) and the functions readViewRotation, readOutlineVertexData
- ToonScreenOutline: removed the stair-stepping left in the half-size (reduced) buffer. The line buffer and seeds are always taken at drawing area resolution, and only jump flooding runs on the reduced buffer. Each cell of the reduced buffer gathers the nearest of the full-resolution seeds (gather pass), and seed positions are widened as drawing area pixel coordinates as they are, so the distance is measured in the drawing area when blending. (The form Ben Golus described: run jump flooding at low resolution, but resolve by distance instead of bilinearly upscaling positions)
- The meaning of setResolutionScale changed to the fraction for the line target and the widening buffers (drawing area x scale). The default 1 draws at the drawing area resolution.
- getLineTarget(): seedTexture (full-resolution seeds), jumpFloodTextures, jumpFloodIndex, jumpFloodWidth, jumpFloodHeight. (seedTextures, seedIndex are gone) readProgramSources gives five (the gather pass)
- ShadowAtlas: made the tile size the same as the Unity URP default. new ShadowAtlas(context, resolution default 2048, tile resolution default 1024) asks for 1024 per tile, and if they do not all fit, halves until they all fit (URP additional light shadow atlas default 2048, resolution tier High default 1024, the light's default tier High). getTileResolution
- Until now the grid was split by the square root of the tile count, so one point light got 682 and now 512, and one spotlight got 2048 and now 1024. For finer shadows, raise the resolution and tile resolution
Fixes
- UIInputField trailing tab fix: a tab at the end of a wrapped line now hangs like a trailing space (Chrome white-space: pre-wrap) instead of starting an empty new line when the tab stop passes the line width.
- Toon prewarm: fixed prewarm not advancing on a loading screen that only skips frames while waiting for isReady() without drawing (the game session measured on headless Chrome on a Mac: still not finished after 45 frames, then one 8,183 ms frame when everything was finished at once, and one getProgramParameter completion query took 52 ms). Handed-off compile and link commands may not flow to the GPU process by themselves in frames with no draw or clear (the KHR_parallel_shader_compile spec text says nothing about flush, and the Chromium source was not checked), so prewarmDrawQueue now calls gl.flush() after handing off, and each ToonProgramPrewarm step calls it again while work remains. ShaderProgram.isBuildComplete() no longer asks again once it has seen completion (the query round-trips to the GPU process). The picture is byte-identical and the public API is unchanged. Headless Chrome on this machine finished while not drawing even before the fix (8 to 32 frames), so the stall seen in the game was not reproduced. The test counts gl.flush calls (0 before the fix; after it, 2 at hand-off and 1 per frame) and completion queries went from 78 to 64. (tests/graphics3d/toonprogramprewarmwaitchrome.test.mjs)
- The toon shadow cache (ShadowUpdateMode.onChange) no longer re-bakes on material values such as tint (casters are compared per object, as in Unreal and HDRP cached shadows): drawShadows and drawLocalShadows compared caster records in the sorted order of opaque items. The sort key includes the material block, so a single tint change shifted the order and unchanged casters looked changed, which either re-baked the whole cached map (lobby scene) or never baked at all and redrew everything every frame. Records are now compared in submission order (as the header comment already said), while baked and overlaid casters are still drawn in sorted order so auto-instancing batches stay intact. The compared values (mesh, material, matrices, joints, index range, culling, mirroring) are unchanged; tint, color and emission do not affect depth and do not trigger a re-bake. A moving object still re-bakes in that frame. Lobby scene (tests/graphics3d/toonlobbyscene.mjs, tint cycling every 40 frames) over 600 frames: bakes 30 -> 1 (the first one), room scene shadow draws 122 -> 118, and both scenes are byte-identical on screen. A Chrome test (tests/graphics3d/shadowcasterorderchrome.test.mjs) checks that frames where only a tint changes have every caster baked and draw no shadow depth (before the fix only the ground was baked), that moving a baked box re-bakes in that frame and then overlays only that box, and that the screen matches everyFrame on every frame.
- UIDocument image and node data fixes: a copy written and read with the same document now uses the original's images (serializeNode and toJsonText remember the image of each component that writes an imagePath, keyed by path, and use it when the resolver and the loadImages assets do not find one, like Unity Instantiate). So items cloned with UIListView.setTemplateNode show their images again (after the move to document instances they were cloned with a new document without a resolver and lost their images). bindPendingImages no longer overwrites a component whose image the game set or whose path it changed in the meantime. An image that loadImages failed to read is dropped from the table so the next loadImages requests it again. A node reference to a node that has an earlier sibling with the same name now warns when written (paths are names only, so reading back links to the earlier sibling; same form as the Rust find_node_path). A reflected property whose current value is a Color and whose document value is a string (such as "#rrggbb", the old form) is read with Color.from (it used to be dropped and keep the default color). A hidden node (setVisible(false)) writes visible: false in its node data and reads it back (visible nodes do not write it, so existing documents and expected data are unchanged).
- Drawing and image fixes: drawing with a swapped shader (such as ShaderSprite) and a shader blend mode inside an axis-aligned clip (such as UIScrollView) no longer paints black outside the clip; a runExternalPass(clearDepth: false) 3D pass inside an opacity layer no longer reads the previous layer's depth (each layer clears its depth); ShadowMap.beginRender turns off the scissor test so it no longer clears only part of the map inside a 2D clip (same as ShadowAtlas); with two engines, one engine no longer uploads the images another engine's scene read into its own context and closes their pre-decoded images (only the Graphic that was loading a scene when the image started loading pre-uploads it).
- Shader build failure: when ShaderSprite or ScreenEffect fails to build an effect shader, it no longer throws and stops the frame; like the Rust engine it reports once (console.error) and skips. (ShaderSprite draws as a plain Sprite, ScreenEffect skips that step) ScreenEffect.resolvePass returns null on failure.
- Engine: when the window loses focus (blur), releases keys too, not only touches and mouse buttons. (Through InputManager.clear followed by marking touches as released, same as Rust) Fixed keys staying pressed because keyup never came.
- Sprite: fixed flipping (setHorizontalFlip, setVerticalFlip) drawing outside the content area (on the negative size side); it now mirrors within the content area. Atlas pieces, nine-slice and tiles all flip. (Also fixes nine-slice being drawn small and broken and tiles not flipping) Since isDrawnInsideContent is true even when flipped, it gets off-screen culling.
- Graphic.drawNode: even if drawing throws, try/finally pops the pushed transform so the transform stack does not get out of balance.
- AudioPlayer: fixed a late-finishing earlier request playing sound when stop or play was called again while a suspended AudioContext was being woken. (Request numbers; there is always only one sound) Catches resume rejections so no unhandled rejection is left. getTime advances with the audio context clock during playback. (Multiplied by the playback rate, wrapped by the length when looping, otherwise stopping at the length; when stopped or finished, the start position from setTime)
- ParticleSystem: fixed bursts at the loop seam (repeat boundary) firing only in the first cycle. Bursts at 0 seconds and right before the boundary also fire every cycle, and if one frame passes several cycles they fire that many times. (They do not fire again on a 0-second frame where time is stopped)
- AnimationClip: corrected the frame list type to Rect, which it actually holds. (JSDoc of setFrames, getFrame, getFrames; removed the unused Frame import)
- UIView: fixed setBackgroundColor(null or undefined) throwing. It clears the background. (Resets it to the initial value, white with alpha 0, so it is not drawn)
- UIScrollBar: fixed the thumb default color, Color(255, 255, 255, 0.6) which mixed in 0 ~ 255, to Color(1, 1, 1, 0.6). (It looks the same when drawn, and the getThumbColor value now matches the Rust version) Filled in descriptions, @param, @returns and examples for the public API
- UIInputField hidden DOM input position: fixed a bug where it went out of place when the page was scrolled. Since it is an absolute element attached to body, window.scrollX, scrollY are added to the viewport coordinates (getBoundingClientRect, clientX) to place it in document coordinates.
- VisualAsset: fixed load not reading the file. Fetches the UIDocument JSON (scene, prefab) saved by the visual editor with fetch, checks its form, stores a Visual holding that text, and then counts as loaded. Failed responses and malformed documents are rejected. Added static createVisualFromText; unload also clears the stored Visual.
- Timeline: fixed loadFromUrl not checking failed responses (404 and so on). It now rejects.
- SkinnedModel: fixed an animation FBX with several stacks that have channels giving them all the same clip name, so playAnimation played only the last one. With several stacks, each stack is "clip name/stack name" (the order number if the stack name is empty). With one stack, it is the given name as before.
- HumanSkinRenderer: corrected the swapped eye iris order in the texture unit comment. (12 iris normal, 13 iris color. The behavior was already correct)
- SkinnedModel: fixed calling uploadMeshesAndMaterials again leaking the old drawables' VAO, buffers, morph textures and the materials this model built. (Calls destroy first) uploadWireframeIndices also deletes the line buffer already uploaded and uploads a new one.
- Object: removes the private fields (#instanceId, #isDestroyed). The unique identifier is put into a module WeakMap on the first getInstanceId() call. isDestroyed(), which was always false, is removed. (destroy() did not leave a destroyed flag, and the Rust engine has no such function because a dropped value is gone and the handle of a removed node is None. To migrate: isDestroyed() was always false, so remove that check. To see whether a node is still in a tree, use getParent()) Removes two fields that were filled every time any engine object was created
- Indicator(misc): Fixed calls to the nonexistent graphic.getCanvasRenderingContext() and isVisible() and a broken import path ("./graphic.js"). Draws with Graphic's pushState, drawLine, drawStrokeCircle. (Graphic lines have square ends, so the round ends of the Canvas2D era are gone)
- Math (base/math.js): Fixed sqrt, which computed with 10 iterations of the Babylonian method and was wrong above 10000, to use the built-in square root. (sqrt(1e5) was 317.2, sqrt(1e6) was 1296, since 2026-03-21) The length, normalize, distance (Vector2, Vector3) of vectors longer than 100, Quaternion, TransformMatrix, long Graphic lines (thickness and joins were thin and short) and ParticleSystem calculations that use this sqrt were wrong, so behavior in games may change
- Math: Fixed asin, acos, which used a 100-term series and were wrong near ±1 (asin(0.9999) was 1.5132, correct 1.5567), and pow, which was wrong for fractional exponents (pow(4, 0.5) was 1, pow(2, 2.2) was 4), to use the built-ins. Tween exponential, elastic easing and Vector2.angle change. floor, ceil, round now return infinity as is instead of NaN. (sin, cos, tan match the built-ins within 4e-9 and are left as is)
- Vector2: Fixed modulo doing division instead of remainder, and half returning double instead of half
- Engine: Fixed an exception when returning from the back-forward cache (pageshow persisted) caused by calling the nonexistent dispatchPageProcessRestored. Restores engine state (audio, input) as on resume and calls onPageProcessRestored on each loaded scene
- LocalStorage: wraps every access in try. If storage is blocked (private window, exception on window.localStorage access) or full and cannot be written, it keeps values in memory instead for the lifetime of this page, without exceptions. (isMemoryFallback) setBackend({ getItem, setItem, removeItem, getKeys, clear }) swaps the storage. (Such as a platform SDK's storage, getKeys and clear are optional, null goes back to the browser) getBackend, getItem, setItem (whether it was written to storage), removeItem, getJson(key, defaultValue), setJson(key, value)
- Aligned what differed from the Rust vanilla-engine in effects, 3D and animation. (Added general-purpose features that existed only in Rust, and fixed bugs present in both engines in both)
- Animation: Filled in the empty pause and resume. (gotoAndStop stops) stop returns to the first frame even when stopped. (Bug where the old index remained after setFrames) SpriteAnimator.getCurrentFrameIndex
- Action: Condition functions receive the target. wait with duration 0 or less has progress 1 (NaN bug), repeat 0 times does not run
- Timeline: Bug that discarded stage nodes with the same name (all are attached, the name table gets the later one), attaches to the stage parent if the parent is itself or a cycle. Timeline.loadFromText, createFromJsonAsset
- Scene.tickTouch: fixed missing the release of a press and release within one frame (quick tap, click). Now passes touchRelease after touchPress in the same frame. As before, touchMove is not passed on the press frame
- AssetLoader: fixed workers not increasing for items added while loading after load() was called. (If load started with one item, a single worker downloaded everything added afterward one after another) Now spawns more workers up to the concurrent download count
- Identifier.reset restores the initial value. (Bug where it assigned its own value to itself and did nothing, Enum.begin counts from 1 for each enum)
- KeyCode.audiomute value "AudioMute" is not a name in the W3C KeyboardEvent.code table, so pressing the mute key did not match. Fixed to "AudioVolumeMute". (Fixed together with the Rust version)
- Fixed UI source bugs to match the Rust version:
- UIDocument only wrote Sprite's nineSlice and never read it. Now reads it by inverting the written form ([left, top, left + right, top + bottom])
- UIDropdown: the header button tint also captured the dropdown list rows, so after selecting, the selection highlight was overwritten with the old color. Excludes the dropdown list from the header button tint (excludeNodeFromTint), and when the highlight changes, the row buttons recapture the tint's original color
- UIInputField: on a paste truncated by maxLength, the cursor went past the end of the text. Clamped to the end of the text
- LayoutSolver: when artificial variable optimization ended in an exception, the artificial rows were left in place instead of cleared. Cleared with try / finally
- UILabel's background draw order was already correct. (UILabel is attached in an order before the Text, RichText it requires, so it draws the background first)
- Fixed a bug where OBB.overlaps was always false. (It iterated the other's vertices by other.length, so the other's projection range was empty, same as the Rust version)
- Fixed Platform.getSafeAreaRect throwing by calling Window.getComputedStyle (a nonexistent static function), now window.getComputedStyle. (Confirmed that typeof Window.getComputedStyle is "undefined" in headless Chrome)
- NodeLayout.arrangeFan: fixed stopping with a ReferenceError when called because System was not imported, and passing radian values to a degree-based rotation (setLocalRotation). (Same as the Rust version)
- TextAsset, BlobAsset: fixed treating failure responses (404 etc.) as received, now throw. (Included in AssetLoader's failure list) AudioAsset also treats failure responses as failures before decoding
- SoundEffectPool: fixed play throwing on division by zero when the voice count is 0, now does nothing. (Same as the Rust version)
- Wait.nextFrame: fixed it finishing immediately because it did not wait for the Promise it created. It now waits until the next requestAnimationFrame. (same as wait::next_frame in the Rust version)
Tools, docs and examples
- Engine bundle tool and bundling only what is used: node tools/bundle.cjs builds build/vanilla.js (with its source map) and vanilla.min.js. The readable vanilla.js keeps lines and indentation and drops comments (the original sources and comments are in the source map; esbuild keeps comments in an unminified bundle, and they were about 40% of it). 4,083,510 to 2,209,932 bytes (gzip -9 742,055 to 409,865), and loading only the bundle on a blank page takes 32.8 to 25.0 ms (headless Chrome, median of 12, 0.3.2 takes 16.3 ms). With sideEffects in the package.json at the top of the repository, a game bundled from source drops unused modules entirely. Bundlers treated top-level calls such as System.Object.freeze as side effects, so 3D modules stayed in 2D games (a test entry using only 2D and UI, minified, 345,347 to 250,761 bytes, 14 3D modules dropped).
- import.js: exports TransformMatrix, KeyCode, GamepadButtonCode, GamepadAnalogStickCode, GamepadTriggerCode, ScrollMode, ButtonState, ProgressDirection, SpriteDrawMode, SpriteBlendMode, AssetType, MORPH_TARGET_MAXIMUM, VERTEX_FLOAT_COUNT, SKIN_FLOAT_COUNT and WRINKLE_CHANNEL_COUNT, the same as the Rust engine's top level. (also available straight from the bundle build/vanilla.js)
- Example asset licenses cleaned up: removed the Mixamo original files that have no redistribution permission (Remy.fbx and the clip FBX files of anims in ancientmountain, soldier.glb, which is Mixamo Vanguard from three.js, and the clip FBX files and mixamo_rest.json of toonshading) and replaced them with Quaternius Universal Animation Library 1 and 2 (Standard, CC0). Where they come from and the license text are in README.md of the asset folder and the Example Assets section of THIRD_PARTY_LICENSES.md. The extraction script is examples/ancientmountain/tools/export_quaternius.py (Blender 5.2)
- ancientmountain: the character is the mannequin mannequin.fbx (meters, so CHARACTER_MODEL_SCALE is 1), and the clips are idle (Idle_Loop), walk (Walk_Loop), run (Jog_Fwd_Loop), fall (Jump_Loop), land (Jump_Land), climb (ClimbUp_1m_RM). The mannequin has no textures, so Remy's PBR maps are gone. A source line for the character and the fox was added at the bottom of the screen. fbx_test.html and glb_test.html use the new assets too
- toonshading: the clip buttons are IDLE, WALK, RUN, ROLL, YES, TALK, PUNCH, DANCE. (JUMP, GREET, CLAP, CHEER have no equivalent in the CC0 pack, so they became ROLL, YES, TALK, PUNCH) The bone map uses Unreal mannequin names (pelvis, spine_01 and so on), and the T-pose table is computed from the first scene of tpose.fbx (A_TPose) instead of a file
- The fox.glb credit was corrected. The example comment said CC0, but the Khronos source says the model is PixelMannen CC0, rigging and animation tomkranis CC BY 4.0, and the glTF conversion AsoboStudio and scurest CC BY 4.0. The authors are written on the example screen and in THIRD_PARTY_LICENSES.md
- The glb examples (the glbmeshreader API example, glb_test) use mannequin_female.glb (female mannequin, Idle, Walk, Run, Dance) instead of soldier.glb. The 15-3d guide and Remy.fbx and soldier.glb in architecture were changed too
- oldface: restored with the MetaHuman (Walter preset) assets (Epic Games', demo only, examples/oldface/ASSETS_LICENSE.md). Adapted to the engine renames (FullscreenPass.useProgram, Graphic.flushBatch) and added the URL parameters ?expression=name and ?yaw=radians. HumanSkinRenderer itself is unchanged
- License notices: the files moved from other sources (uiinputfield, spatialaudiomath, tween, matrix4, autolayout, subsurfacescatteringeffect, the draft tilemap, physics2d, dynamictree) have the source and a license line at their head. THIRD_PARTY_LICENSES.md gains the public domain and CC0 code (fmix32, Narkowicz's ACES approximation), DOSGothic (MIT full text) and an Example Assets section. tools/project.cjs build copies LICENSE and THIRD_PARTY_LICENSES.md to the output. (Under licenses/vanilla.js/ if the same name exists)
- Drafts out of the bundles: removed the line in import.js that exported the drafts (2D physics, tilemap, 2D skeleton, spatial audio, save slots in src/experimental) as the Experimental namespace. The default bundles and the web tools no longer carry the drafts. build/vanilla.min.js 1,035,048 bytes → 849,276 bytes (about 1011 KB → about 829 KB, about 288 KB → about 235 KB gzipped), build/vanilla.js 4,075,155 → 3,324,094 bytes, UI editor 4,453,945 → 3,666,226 bytes, visual editor 2,340,587 → 2,335,558 bytes. (The particle and timeline editors did not carry the drafts and grew by the header comment) Drafts are imported directly from src/experimental/experimental.js. experimental.js imports import.js first so that the engine modules load in the right order. (Importing a draft module first ran into classes that were not loaded yet) tools/apidoc.cjs reads the draft entry point separately as the Experimental namespace, so --check and --check-examples still check the drafts (they are still left out of the doc data), and draft examples import the engine from ./import.js and the drafts from ./src/experimental/experimental.js. The bundles and the web tool html files start with a one-line engine license comment (/*! vanilla.js | (c) 2026 vanillapunch | MIT License | links to LICENSE and THIRD_PARTY_LICENSES.md */). (--banner:js in the esbuild commands of the README and the guide)
- License: the engine's copyright holder is now vanillapunch. (LICENSE reads "Copyright (c) 2026 vanillapunch", the README and the guide overview read "© vanillapunch", still MIT) Third-party license notices are collected in one file, THIRD_PARTY_LICENSES.md. (The license section of the README)
- Rebuilt bundles: rebuilt build/vanilla.js, vanilla.min.js and the four web tools (the single-file html of tools/uieditor, particleeditor, timelineeditor, visualeditor) from the current source. (The bundles in the repository were from September) The UI editor's edit and result views and the HUDs of the examples ancientmountain, oldface and toonshading use Graphic directly without the engine loop, so they call flushBatch() after drawing. (After sprite batching became the default, the rebuilt UI editor's view came out black, and the last batch of a HUD could slip to the next frame) Changed the cache stamp that the eight deployed examples (ancientmountain, neonhorizon, oldface, particleeffects, spriteeffects, timelineshowcase, toonshading, uishowcase) append to the engine URL to 20261126a. Re-measured the vanilla.min.js size in the README and the guide overview from the current source. (about 1011 KB, about 288 KB gzipped)
- tools/apidoc.cjs: puts the Rust version's counterpart (counterpart: { engine: "vanilla-engine", module, class, name }) into the data. For classes, enums, members, module functions and constants, and enum values. The counterpart table is docs/api/counterpart.
.json (the table the Rust version's tool built by name is carried over with --counterpart), and --check checks the counterpart form and count. - tools/project.cjs build and the vanilla.min.js commands in the README and guide add --keep-names to --minify. (The developer tools and unregistered UIDocument types read class names) Brought the project.cjs header comment, usage output, TOOLS.md and the guide's tools chapter in line with the code. (node tools/project.cjs, the build template's default location tools/buildtemplate, -t and --template, the stage command)
- tools/webm.cjs: if fluent-ffmpeg, ffmpeg-static are missing, shows installation instructions and exits. (Until now it died at the top-level require before showing the instructions)
- tools/apidoc.cjs --gaps: finds detached header comments (old blocks where a header comment and JSDoc are followed by another header comment with no declaration, and a header comment right after a header comment that does not end in "목록" (list)). Removed the old blocks it found (UIButton, UIProgressView, UILabel, Text, Color, LocalStorage, NodeLayout, AnimationClip, SoundSystem) and changed headers used like section headers into member headers (UISlider, PlatformerBody, Camera2D). The descriptions of those members in the API docs are corrected
- Guide: updated chapters 05, 12, 13, 19 and the tools chapter (ko, en) to the changes (--keep-names, UIDocument registered names and registerEditorTypes, UINode presses, Animator state machine)
- import.js: split the old "experimental features" block into collection, animation, shaders and fullscreen pass, 3D graphics, to be deprecated, and experimental blocks. Visual went to the other features block, VisualAsset and BunchAsset to the resources block. The exported names are the same. (The experimental block is only a comment, and the drafts are imported directly from src/experimental/experimental.js)
- README, guide, ARCHITECTURE: updated to the new folders and removed the text calling 3D and toon 3D experimental features. (README's "3D (experimental)" is now "3D")
- Rebuilt the visual editor (tools/visualeditor) like Unity. Docking windows (Hierarchy, Scene, Game, Inspector, Project, Console) below the top menu (File, Edit, Node, View, Window) and the toolbar. Initial layout: hierarchy on the left, scene and game in the center, inspector on the right, project and console at the bottom
- Docking (docklayout.js): as in Unity or VS Code, dragging a window tab onto another window's tab bar or center merges it as a tab, dropping it on a window edge (30%) splits and docks it on that side, and dropping it on the edge of the whole dock area docks it on the outer side of the whole. While dragging, the dock target is shown as a sliding blue box, and the insertion point between tabs as a bar. Esc cancels. Drag the splitters to resize, double-click a tab to maximize that group. Close a window with the tab's X or the middle button and reopen it from the Window menu (it returns beside the windows it was with when closed). Window > Reset Window Layout. The layout is kept in the browser and restored on reopen
- The Scene and Game windows share one canvas. When both are visible separately, the canvas is attached to the selected one and the other shows a notice that moves it over when clicked. The scene view keeps the center it was viewing when the window is resized
- Fixed the scene view drawing only in part of the top left on displays with a pixel ratio other than 1, such as Retina (applyViewRect in EditorScene preDraw)
- Scene view: lays a grid and the screen frame (reference resolution) on the engine canvas and draws the actual WorldNodes. Click to select, handles to move (W), rotate (E), scale (R), pan (Q, Space, middle and right drag), zoom with the mouse wheel and Ctrl wheel (trackpad pinch), pan with two trackpad fingers. Ctrl snaps to 10 units, Shift to 15 degrees. Arrows move 1 step (Shift 10 steps), F to the selected node, Home to the screen frame
- Game view (Tab): fits the screen frame to the view without grid and handles, and masks outside the frame. Play switches to the game view, stop returns to the scene view
- Hierarchy: expand and collapse, double-click to rename, drag to make a child or move before or after a sibling (screen position is kept), search box, right-click to create, copy, paste, duplicate, delete, save as prefab
- Inspector: enabled and name, transform (position, rotation, scale, content size, pivot, anchor, opacity), per-component property fields gathered by reflection (number, text, boolean, color and alpha, Vector2, dropdown for fixed values). Dragging a number label left or right changes the value. A Sprite's image is set by dragging and dropping an image asset from the project, and the native size button fits the content size to the image. Add and remove components
- Project: Open Folder (showDirectoryPicker, Chrome-based) reads and writes a real asset folder. Other browsers import by dragging and dropping files and folders. Folder tree and asset grid (image thumbnails), filtering by type (image, sound, JSON, scene, prefab, model, font, text), Import button copies files into the current folder. Selecting an asset shows a preview in the inspector (image and resolution, sound playback, JSON and text contents, font sample, for GLB the mesh, bone and animation counts and a 3D preview drawn with the toon renderer that rotates by dragging)
- Dropping an image asset in the scene view creates a Sprite node of the image's size at that spot. Prefabs (.prefab.json, a single UIDocument document) are instantiated by dropping or double-clicking, scenes (.scene.json) are opened by double-clicking
- Scene save and open: .scene.json, the UIDocument format with the editor value frameSize added. Games read it as is with fromJsonText of a new UIDocument(). If a folder is open, writes directly into it, otherwise downloads. A Sprite's image is written as imagePath and looked up and linked in the project
- Undo and redo (200 steps, consecutive changes to the same value count as one step), copy and paste, duplicate, play and stop (stop restores the state before play), auto-save to the browser 1 second after a change and restore on reopen. The console shows editor messages together with browser warnings and errors
- Replaced the earlier particle script demo editor with this
- BuildInfo: build version reading. await load() first reads the page's , and if absent fetches version.json without cache (cache: "no-cache"). readText() returns the meta text as is, or "date time (hash)" from version.json (version if there is no hash), or empty text if it cannot be read. readVersionData(), isLoaded(), setMetaName, setVersionJsonPath, BuildInfo.composeText(versionData)
- tools/atlas.cjs: Multiple pages (next page when exceeding --max-size, each page the smallest power of 2 that fits everything), edge extrusion (--extrude), padding (--padding, default 2). Placement changed from shelf to MaxRects, so positions differ from before even for the same images. (Same when read via JSON) Added page to images in the JSON, and pages, extrude, padding to meta. With a single page, the file name is the same as before
- Example cameratour: Rotating Camera2D (drag to pan, wheel to zoom), Tween.createNodeTween, Indicator
- BuildInfo: setPackageVersion, getPackageVersion. The version readText returns when there is neither meta nor version.json. (Same role as the Rust version's build-time version, empty string as before if not set) load also returns the same string as readText
- Updated the documentation to match the current code. (the code is unchanged)
- README: introduction (bundle size of the current sources about 765 KB, gzip about 215 KB, batching and culling on by default, render target multiply), main features table (this version's items such as input actions, window stacking, motion, toon 3D, assets, sound table), ShaderSprite effect count (49 excluding none), visual editor and atlas.cjs description, examples without a distribution build cameratour, toonmaterial, middle dots replaced with commas
- ARCHITECTURE: layout, inheritance hierarchy (widgets that are nodes, things that do not inherit Object), ownership structure (InputActions, PointerCursor, AssetLoader, toon 3D), frame loop (maximum FPS, clearing the batch cache, drawing remaining batches, cursor), batching and culling on by default, multiply is blended in a shader on render targets (removed from the known gaps table), unexposed list (AudioPlayer, GamepadManager are now exported), chapter 9 relationship with the Rust version
- In the header of this version in UPDATE.md, kept one each of the lines both branches had written twice (WebSocketClient, Localization, UILabel.getVisibleCharacterCount)
- Documentation data: keeps in docs/ the data the website uses to build the documentation for each version. (The website builds the HTML)
- docs/api/
.json: the public API exported by import.js (modules, classes, members, module functions and constants, enums). Description fields are { ko, en }; ko is the original source comment and en comes from the docs/api/translation.en.json table (ko original → en). since is the first version in which the member existed in that class, found by scanning tags from v0.0.8 - tools/apidoc.cjs: generates the data above. (A small tokenizer using only Node built-in modules; --missing lists ko text not in the table, --check validates the format and prints counts) Usage is in tools/TOOLS.md
- docs/guide/
/ko, en: overview, getting started, architecture, tools. (Split from README, ARCHITECTURE, tools/TOOLS.md and NODE.md, repository-relative links turned into GitHub URLs) docs/update/ .ko.md, .en.md: this version's update notes - README: the file UI Editor saves is .uiasset.json. (It said .ui.json) Corrected that tools/excel.cjs is a collection of functions with no command-line entry point, so running it alone does nothing, and that tools/table.cjs is an empty file. Added apidoc.cjs to the command-line tool table
- Public API comments and examples: filled the empty ko descriptions (module summaries, members, parameters, returns, enum values) and empty parameter types of the public API, added @returns to functions that return a value but had none, and added header comments to private functions that had none. Descriptions were written from the code as it actually behaves (units, ranges, defaults, what happens with null). Added @example to every class and to every module without a class, and to members whose usage is not obvious from the name. (the examples field of the data, 314 in total) The English for the new text was added to the translation table. The toon 3D folder (graphics3d/toon), visual.js, uilistview.js and uiscrollbar.js are being reworked separately and were not filled this time
- tools/apidoc.cjs: --gaps (documentation gaps per file), --check-examples (checks the API examples and the guide code blocks for syntax and engine names and runs them in Node workers and headless Chrome, no external dependencies), --only and --exclude filters for --missing, --gaps and --check-examples. The returns of a field only holds the value type, so it is not counted as an empty ko field. A leading hyphen in a description is removed only in the "name - description" form. ("-1 이면" used to be read as "1 이면")
- docs/guide/
/ko, en: added 15 topic chapters. 05 project setup, 06 engine and scenes, 07 nodes and components, 08 drawing, 09 input, 10 loading assets, 11 sound, 12 UI, 13 tweens, animation and timelines, 14 particles, 15 3D, 16 storage, 17 languages, 18 developer tools, 19 authoring tools. (the two-digit number in front of the file name is the order, every chapter has runnable examples and all of them go through the example check) - Replaced em dashes and middle dots in the comments of the edited files with commas. (those inside code such as shader strings and error messages are unchanged)
- examples/assets/beep.wav: a 0.15 second beep used by the sound examples. (PCM generated by a script)
- docs/api/
- Example toonstyle: a scene for comparing toon shading and outlines. (Angular box, round ball, crystal with large facets, cluster of crystals with small facets, ring, slanted plate, shadows, point light, ?scale=0.5 for a half-size line buffer, ?toggles=1 for per-model options) The same scene as the Rust example toonstyle
- Example toonmaterial: removed the aberrant body shading formula comparison (verifyAberrantShading). (It is one game's formula and does not belong in an engine example, and since the engine's lighting is now the standard form it no longer gives the same values) Removed the normal scale compensation in the rock vertex chunk. (The engine transforms by the inverse transpose)
- Example toonstyle: three shades, hard highlights, sun-side rim, spotlights, matcap, ?shell=1 for shell outlines (per-draw color and width, distance multiplier)
- Example toonstyle: point light and spotlight shadows, a blue shade-side rim, an angel ring on the dark ball, shell outlines vanishing at 16 meters and pushed along the camera direction
- Example toonstyle: ?roll=radians tilts the camera (undoing the angel ring tilt)
- Rebuilt the visual editor (tools/visualeditor) with the engine above
How to migrate
- WebGL context lost handling: drop the preventDefault and the drawing pause a game did on webglcontextlost, and rebuild only its own GL objects on restored through addGraphicContextEventListener.
- Shader build failure notification: A game that wants a fallback drawing or an error report receives it through addGraphicErrorListener.
- Toon program variant prewarm: A game that minds the hitch calls it once after adding the scene and before the first frame. (const prewarm = renderer.prewarmDrawQueue(queue); await prewarm.wait();)
- Toon body variants: The default became hand off and draw with the default body, and the picture is the same. To build on the spot as before, call renderer.setAsyncProgramBuild(false). If the light features to turn on mid-scene are known, prewarm them with renderer.prewarmDrawQueue(queue, { lightFeatureList: [["rim"]] }).
- Bone matrix uniform block: in a replacement vertex shader (a shader given to SkinnedModelRenderer, the toon outline shader), put JOINT_BLOCK_GLSL in place of uniform mat4 jointMatrices[96]; (the body's jointMatrices[index] stays). Code that uploaded bone matrices directly (getUniformLocation("jointMatrices[0]") and uniformMatrix4fv) changes to uploadJointMatrices(jointMatrixArray). Where morph weights were uploaded directly, use uniform vec4 morphWeights[24] and uniform4fv in place of uniform float morphWeights[96].
- GPU memory tracking: code that used GPU memory tracking builds with EngineConfiguration.trackGpuMemory = true (to count the engine resources from the start). Games that did not use it need nothing.
- GPU throughput measurement: Games that watched a GPU target without a real device look at (6) from --throughput instead of (3) from perftrace.
- Fewer activeTexture calls in toon drawing: Code that calls GL directly while the toon renderer is drawing (between beginFrame and endFrame) should call activeTexture first instead of expecting unit 0 to be active. (Stage callbacks and onBeforeDraw of body draws still get unit 0)
- 3D color space setting: A game that draws 3D in linear turns it on with engineConfiguration.colorSpace = ColorSpace.linear and gives isColorData: false to createTexture for normal or mask textures. Material chunks that mixed an sRGB color into surface.baseColor convert it with toSurfaceColor(color) first (unchanged in gamma, so the screen is the same). Light intensities and colors tuned in gamma look darker on the dark side in linear, so retune them.
- Retained toon draw items and no per-frame allocation in the draw queue: Games drawing models with many parts build one ToonDrawItem per part once (indexStart, indexCount of the material range in the options), call queue.addItem(item) every frame after queue.clear(), call item.setModelMatrix(matrix) when it moves, and item.setOption(name, value) or item.markDirty() after changing the options object. Code that got a new vector from getPosition or getScale every frame can switch to readPosition(vector) and readScale(vector).
- Thin-line path for the toon screen outline: Code that reads seedTexture from getLineTarget directly sees null when the width is about 3.24 pixels or less. Code that counted five entries from readProgramSources sees seven.
- Toon screen outline resolution scale: Code that already called setResolutionScale below 1 keeps the line position and width and only gets softer edges. Code that counted readProgramSources as seven now counts nine.
- Sound streaming load: background music played through the engine SoundSystem now streams when its sound table row has no loadType, so code that used getAudioBuffer() of that asset directly gives the row loadType: "decompressOnLoad". Code that uses AudioAsset directly has nothing to change (the default is still full decoding) and calls setLoadType(AudioLoadType.streaming) to stream. getAudioBuffer() of a streaming asset is null.
- UIDocument image and node data fixes: Games that relinked template images themselves can drop that code.
- Bone pose hook: Games that copied the engine's writeSkinPose to add a hook delete the copy and pass the same function as the seventh argument of the engine's writeSkinPose.
- 3D camera shake: Games that computed shakes themselves keep one CameraShake, call add per event and update per frame, and apply read() with Camera3D.setViewOffset or createOffsetViewMatrix. Shakes that were added in world axes become camera local axes (x right, y up, z back).
- glTF primitives without normals: A game that added normals to a GLB without normals can read it as is. Code that read SkinnedModel's mesh description for a mesh without normals now gets filled normals and null indices.
- GameScene loading no longer relies on a hook that can be overridden: a game that overrode drawOnLoad moves to setLoadingDrawer. (Overriding no longer stops loading)
- Batched drawing names same as the Rust version: graphic.setSpriteBatchingEnabled(x) becomes graphic.setBatchingEnabled(x), isSpriteBatchingEnabled() becomes isBatchingEnabled(), and flushSpriteBatch() becomes flushBatch().
- Drawing outside the engine loop: Code that calls flushBatch() after drawing outside the loop keeps working. When inserting a pass that touches WebGL directly, call flushBatch() first as before.
- Engine bundle tool and bundling only what is used: replace the two esbuild lines from the README with node tools/bundle.cjs. The public API, import names and vanilla.min.js stay the same.
- Removed the toon 3D namespaces ToonMesh and ToonGlb. The functions and classes of the mesh builder: drop the prefix, so ToonMesh.MeshBuilder becomes MeshBuilder, ToonMesh.createBoxGeometry becomes createBoxGeometry, and ToonGlb.readGlbArrays becomes readGlbArrays. Change import { ToonMesh } to import the names you use. flushSpriteBatch() becomes flushBatch().
- Top-level names as the same set as the Rust version: engine.getSceneManager().getAllLoadedScenes() becomes engine.getAllLoadedScenes(), and loading and unloading scenes use engine.loadScene, unloadScene, unloadAllScenes. Camera becomes Camera2D. List, Dictionary, Queue, Stack become Array and Map. For ToonMesh.MeshBuilder, ToonMesh.createBoxGeometry, ToonGlb.readGlbArrays and the like, delete the leading ToonMesh. or ToonGlb. and import that name.
- UIDocument becomes an instance without global state: where UIDocument was called statically, such as UIDocument.fromJsonText(text), make a document and call it on that document. const uiDocument = new UIDocument(); uiDocument.registerEditorTypes(); uiDocument.setImageResolver(resolver); const rootNode = uiDocument.fromJsonText(text). Registrations and the resolver apply only to that document, so read with the same document. Instead of a resolver you can load the images first with await Promise.all(uiDocument.loadImages(text)). Where UIDocument.getComponentType(name) gave a constructor to attach, attach with uiDocument.createComponent(node, name). Change visual.createNode() to visual.createNode(uiDocument), and list templates with game components to listView.setTemplateNodeWithDocument(template, registeredDocument).
- ToonView3D screen rectangle and output: in draw functions, change screenRect.x, y, width, height to screenRect.position.x, position.y, size.x, size.y, and screenRect.outputFramebuffer, screenRect.outputViewport to the fifth argument output.outputFramebuffer, output.outputViewport. (ToonPostProcess.end(output.outputFramebuffer, output.outputViewport))
- Public functions only the original had: delete camera.refreshMatrices() calls (getViewMatrix and getProjectionMatrix compute on their own). Delete setStateEvent calls (it did nothing). Hook per-state work with setPressedEvent, setReleasedEvent and setClickEvent.
- Default font: games that used DOSGothic give a font address to defaultFontUrl (its name is "default") or add "DOSGothic" with a FontAsset. Places that picked it by name, such as "16px DOSGothic", add it with a FontAsset or change to "16px default".
- Baked components keep colours as Color: where softShade.getColor() or shadowImage.getImageColor() was used as a string, append .toHEXString().
- No reserved-word names: cooldown.use() becomes cooldown.activate(), pass.use() becomes pass.useProgram(), shaderProgram.use() becomes shaderProgram.useProgram(), pointerGesture.move(x, y) becomes pointerGesture.movePointer(x, y), action.loop(...) becomes action.repeatWhile(...), and Tween.easingFunction.quadratic.in becomes Tween.easingFunction.quadratic.easeIn (out and inOut become easeOut and easeInOut). The old names are gone.
- Top-level names aligned: rename DEVTools to DevTools (the old name is gone). Code that called setTextAntialiasEnabled(value) from textstringtexturecache.js directly calls graphic.setTextAntialiasEnabled(value).
- UIInputField multiline input and undo: A game that used Ctrl (Cmd on Mac) + Z itself while a canvas mode field is focused now has the field take that key.
- Image decoding and uploading moved to load time: ImageAsset.getImage().src is a blob: address if the bytes were received (the asset path is getAssetPath). If the bytes cannot be received, as with file://, the address is put in as before. A missing image (404) is rejected right away with Load fail without building an image element.
- Rust-edition shape alignment: change new ScreenEffect(graphic) to new ScreenEffect() (the graphic is passed to begin(graphic) and end(graphic), same as the Rust edition ScreenEffect::new(); a passed argument is not read). CameraGestures.takePan() now returns a Vector2 instead of { x, y } (pan.x and pan.y still read the same).
- Visibility flag: code that used isVisible() to check active and opacity above 0 switches to isVisibleInHierarchy() (including ancestors) or isActive() && getLocalOpacity() > 0 (that node only).
- ToonVfx position and defaults: change { x: 1, y: 2, z: 3 } to { position: [1, 2, 3] }. (The old x, y, z are not read, so the effect appears at the origin) Code that left out alpha to keep a ribbon or beam from drawing passes alpha: 0.
- Image path: code that read or wrote component.imagePath switches to component.getImagePath() and component.setImagePath(path).
- Scene background: games using GameScene or UIScene are unchanged. Code that kept the Color given to setSceneBackgroundColor and modified it to change the background calls setSceneBackgroundColor again after modifying it.
- EngineConfiguration.viewScaleMode: a scene that extends Scene directly changes its view scale from none to stretchShort. To keep the current look, set engineConfiguration.viewScaleMode = ViewScaleMode.none. The same applies to keep the current look of the UIScene and GameScene loading screens.
- Public API that the Rust edition had: Color text that Paint and Outline cannot read is white. Games that imported GameScene from the src/game/gamescene.js path can import it from import.js.
- Text drawing uses a glyph atlas: Code that used entry.texture from getTextStringTextureCache().getEntry directly (none inside the engine) draws each glyph from glyphTextures and glyphRects.
- Off-screen subtree culling: a component that overrides Component.calculateDrawnRect calls markDrawnRectDirty() when a value that changes that rectangle changes. (otherwise a node that was off screen may not be drawn even when its widened drawing comes on screen) A WorldNode that overrides draw is still never skipped; to let it be skipped, override calculateDrawnRect to report the drawn rectangle and call markDrawBoundsDirty() when it changes. To turn it off, Graphic.setSubtreeCullingEnabled(false).
- Off-screen subtree culling: a component that overrides draw (such as a game's skin component) must set isDrawnInsideContent to true if it draws only inside the content area, or add calculateDrawnRect and markDrawnRectDirty if it draws outside, for the ancestors of its node to be skipped.
- runExternalPass: Code that touches WebGL directly and expected something bound on texture unit 1 or above binds the units it uses itself inside runExternalPass (nothing else changes). Subclasses of UIView or UIButton that draw outside the content area without overriding draw override isDrawnInsideContent to return false.
- Changing the render pixel ratio cap: code that read the canvas size, such as getCanvasPixelSize, right after setMaxRenderPixelRatio gets the new value from the next frame. (call calculateViewRect when it must apply right away)
- 3D render scale: in ToonView3D draw functions, replace hand-computed canvas positions such as ToonPostProcess.end(null, [x, drawingBufferHeight - y - height, width, height]) with end(output.outputFramebuffer, output.outputViewport) (output is the fifth argument of the draw function). (same place at scale 1, and the right place with a render scale or inside an opacity layer)
- Anti-aliasing on and off: remove the workaround that created a context with the same attributes but antialias off on the canvas beforehand, and set engineConfiguration.antialias = false.
- GL state cache: GL calls made through the same context object need no notice. Only code that changes state in a way that cannot be intercepted, such as calling WebGL2RenderingContext.prototype functions directly, calls graphic.resetGLStateCache() afterwards. Game code that read the framebuffer and viewport with getParameter gets faster as is; new code uses getCurrentFramebuffer and getCurrentViewport.
- Font family name default: DynamicFont without an asset bakes with Segoe UI and Malgun Gothic instead of sans-serif (Arial) on Windows.
- Fewer toon 3D draw state changes: Opaque faces at exactly the same depth (overlapping planes) may show the other one because the draw order changes; merge them into one model or offset their depth. Code that uploaded the renderer's own uniforms directly to the renderer's programs (through getSolidProgram() and so on) while drawing moves to onBeforeDraw.
- Sun shadow focus step: If there are changes the caster record cannot see (changing the vertices of a mesh, changing shadow depth uniforms in onBeforeDraw), call requestUpdate() on that frame or set setUpdateMode(ShadowUpdateMode.everyFrame). Code that draws with renderer.beginShadowPass without ToonDrawQueue clears and draws every time as before.
- Sun shadow bias follows the shadow texel size: Shadow edges shift slightly (the toon style example differs in 3387 of 576000 pixels, largest difference 37). If shadows need to sit closer or farther as before, pass texel-unit values with shadowMap.setBias(depth, normal).
- Toon instance buffers shared by several passes: Upload long-lived instances (rocks, trees, buildings) once with createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }, { name: "instanceLineId", size: 1 }]) and createInstanceBuffer and add them with addMeshInstanceBuffer. When only one changes, use updateInstanceBufferRange. Adding instanceLineId to a layout that used three user attributes throws (reduce them to two).
- Lower CPU cost per toon draw: The engine material values of the body and outline shell programs are now inside blocks, so names like getUniformLocation("tintColor") return null. (onBeforeDraw is for the material's own uniforms, so no use changes) Pass options as plain objects. (Values changed through class get properties are not detected)
- Toon screen-outline batching of mirrored items: The frame values of the body, outline and depth programs are now inside the ToonFrame block, so names like getUniformLocation("viewProjectionMatrix") return null. (Material chunks still read them by the same names) The line pass draws meshes of the same model together and so can draw in a different order than they were added; merge opaque faces at exactly the same depth (overlapping planes) into one model or offset their depth.
- Toon ambient occlusion: Outlines with width 0 (setWidth(0) and crease width 0) no longer run compositing.
- Toon outline low steps: More lines appear on round-surface silhouettes and low steps within the same ID. Games that lowered depthThreshold to connect seams can go back to the same threshold as the old game (such as 0.05). If stray lines appear on models that build round surfaces from coarse polygons when the threshold is very low, raise setDepthMargin.
- Direct lighting strength for toon ambient occlusion: To make corners in sunlight more visible, pass the fifth argument of setAmbientOcclusion.
- GameScene loading: A press outside the canvas used to skip loading; now only presses the engine input receives skip it.
- Shared 3D asset cache: code that loaded the same path several times and changed material values per model should take a copy with getMaterial(index) and change that. (changing drawableList[i].material or getSharedMaterial changes every instance of the asset) If each load needs its own parsed resources, call SkinnedModelAsset.clearCache() before loading or use loadFromBytes. Adding the same FBX clip from several instances keeps one copy.
- Action: code that expected an inner action's getTarget() to return the outer target should use the target argument the callbacks receive. (an inner action's getTarget is the target given to its own start, or null)
- The input field context menu is drawn by the engine: games that called showContextMenu(clientX, clientY) directly call showContextMenu(view position) instead. (convert viewport coordinates with viewManager.canvasPositionToViewPosition) Remove code that looked for the menu in document as a DOM element. The menu is drawn above the other nodes of the scene.
- The input field context menu is drawn by the engine: Games that relied on the browser menu (spell check, translate, inspect and so on) on direct-touch fields get the engine menu.
- Shader build failure: remove try checks around the build exception. Code that calls resolvePass directly checks for null.
- FBX with several materials: the drawableList of an FBX model grows to the number of materials. Code that expected drawableList[0] to be the whole mesh finds drawables by materialName or materialIndex.
- Engine.alert, confirm, prompt: window.alert(text) becomes engine.alert(text), the boolean of window.confirm(text) becomes await engine.confirmAsync(text) or engine.confirm(text).setCallback(result => result.isConfirmed()), and window.prompt(text, defaultValue) becomes await engine.promptAsync(text, defaultValue) or getText() in setCallback. The answer does not arrive on the spot (it arrives when the dialog closes), so code that read engine.confirm(text).isConfirmed() right away moves to the Async form or setCallback. The same game code then runs on the Rust engine.
- SpriteAnimator: SpriteAnimator.playOnNode(node, ...) becomes SpriteAnimator.play(node, ...).
- InputActions: code (tests) that changed keys or pads within a frame and expected readMoveAxis to return the new value right away calls update once more before reading.
- Sine, cosine, tangent: tests that pinned the last digits of the engine Math sin, cos or tan are regenerated. Calling code is unchanged.
- Drafts out of the bundles: code that used
import { Experimental } from "./import.js"(or a bundle) switches toimport * as Experimental from "./src/experimental/experimental.js"and imports the engine from./import.js, not a bundle. (The drafts and the engine must share one set of classes) Bundling a game with esbuild bundles the drafts along with it. - Scene touch: in scenes that directly extend Scene and made a TouchRaycaster or TouchRecognizer to hand touches over in the touch hooks, widgets are now pressed twice. Give what you made to the scene with setTouchRaycaster(it), and remove the hand-off in the hooks and the touchWheel that found the scroll area and called wheel. If a hook needs to intercept touches (like dragging a bar), turn it off with setTouchRaycaster(null) and hand touches over in the hook as before. (In examples, uisample, uishowcase, particleeffects, spriteeffects were changed to the former form, and timelineshowcase to the latter)
- FbxLoader: code that called playAnimation or looked up nodes with the suffixed names uses the names without the suffix.
- How to migrate: code that created a Singleton subclass again with new gets it with getInstance(). Code that detached a node that is not its own child with removeChild detaches it with node.setParent(null). Games that read documents saved by the editor call registerEditorTypes() once on the document they read with
- Value conversion when porting aberrant (the engine stays canonical, converting the game values this way gives the same body shading, on a test page with point lights, ÷π, sun, bounce light and specular, compared against CPU computation in a float buffer with maximum difference 4.1e-8):
- Sun and bounce light (rim) directions are 'from surface toward light', so flip the sign and pass them to setLight, setFillLight. ÷π is setLightModel({ isEnergyNormalized: true }). Specular intensity times 8 / (48 + 8) (normalized Blinn-Phong)
- Point lights use decay 0, rangeExponent 1, color as the readLinearColor value as is (intensity 1)
- min(lit, 1), which clamped the lit share to 1, was not put in the engine. Readjust light intensity, exposure and bloom threshold. (values are identical where it does not clamp)
- Gamma values written to the HDR buffer: the engine writes linear. Lit bodies give the same values, and min(color x multiplier, 1) of unlit bodies was multiplied in sRGB, so give the engine colorScale or glow multiplier as that multiplier to the power of 2.2. colorScale (mirror 0.6) is also 0.6^2.2 as an engine value
- Glow multipliers: vertex glow is glowScale (actor multiplier x part multiplier x HDR multiplier), accent color light is emissiveColor and emissiveIntensity (0.45 x 1.6). HDR boosting of bright parts via per-mesh glow intensity
- Color keys (#ff00ff accent color, display panel key 0.02): split by the material ranges of GLB primitives, giving only those cells tintAmount 1 and the accent color, and display panels UV and decal textures (logo, digits). Animated face screens (expression, gaze, blinking) stay as surface chunks
- ToonScreenOutline: (the public API changed)
- setCrease(angle, intensity, continuation pixels) → setCrease(angle, width, intensity). Width is in the units of setWidth with default 1, and intensity is 0 ~ 1 with default 1. Continuation pixels (creaseExtent) are gone. (Not needed since only the gap across one pixel is checked) A look similar to the old setCrease(60, 0.5, 2) is setCrease(60, 1, 0.8) in pixel units, and in world units a width about half the outer line width (setCrease(60, 0.011, 0.8) for setWidth(0.022, world)). Because the width is in the units of setWidth, giving 1 in world units makes a line 1 meter wide
- setDepthThreshold(depth threshold, contact threshold) → setDepthThreshold(depth threshold). Its meaning changed to the tangent-plane distance. (A world length; the same value can be passed as is) The contact threshold (contactTolerance) is gone. Since the line is placed at the middle of the boundary, there is no need to decide which side to draw it on
- The meaning of setWidth: the width of a single line, covering half on each side with the boundary at the center. (Until now that width was only on the outside of the silhouette) Default 1.5 → 2 pixels. To match the outer thickness of the old look, give twice the value. To match the overall look of the line (the sum of coverage), use about 0.9 times rather than twice. (Compared by running the old shader on the same line target: Aberrant's old values 0.022 m, crease 60 degrees .5 2 px are closest to setWidth(0.020, world), setCrease(60, 0.016, 0.5), setDepthThreshold(0.08); the coverage sums differ by 1 % in the toonstyle scene at 1280 x 720)
- setSampleCount, TOON_SCREEN_OUTLINE_MAXIMUM_SAMPLES, TOON_SCREEN_OUTLINE_MAXIMUM_CREASE_SAMPLES are gone. (With jump flooding the number of steps is set by the width on its own) For a lightweight path, lower only setResolutionScale
- getOutlineRadius() → getLineWidths() (drawing area pixels of [outer line, crease line])
- Line id limit 65535 → TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID (16383). The top two bits of the line buffer's a channel hold the per-model options
- The maskTexture of getLineTarget() is gone. Instead seedTextures (two RGBA16UI), seedIndex (the side that finished widening)
- drawOutline sets the viewport to the drawing area from beginLineIds on its own. (Until now the caller's viewport had to be the same)
- ToonRenderer per-instance emission: code that put values other than 0, 0, 0, 1 in the bottom row of instance matrices (projective instance matrices) is now read as affine. The ToonScreenOutline line target does the same.
- Rebuilt toon shading in the standard form of real-time toon rendering.: (the public API changed)
- To keep using smooth Lambert (the previous default), clearShadeRamp() or setBandCount(0)
- clearBandRamp() → clearShadeRamp(). getBandRamp(), getBandCount() are gone. getShadeRamp() gives { positions, colors, feathers, isHalfLambert }
- setSpecular(strength, exponent) is now a hard toon spot. The previous soft highlight is setSpecular(strength, exponent, 1). getSpecular() is { strength, exponent, feather, color }
- setRimLight(color, power) keeps the soft rim but is added to the base color instead of multiplied by it. For brightness similar to before, multiply the color by a representative base color. getRimLight() is { color, power, feather, lightMask }
- Faces turned away from point lights are not lit. (When there is a shade ramp) To have them receive light with Lambert as before, clearShadeRamp()