vanilla-engine 0.4.0
0.4.0
요약
- 이름: 러스트 규칙(Rust API Guidelines C-CASE)으로 바꿨다. 함수, 메서드, 변수, 필드, 모듈은 snake_case, 열거 값은 UpperCamelCase, 연관 상수는 SCREAMING_SNAKE_CASE 다.
- 원본 vanilla.js 와 같게: 원본 0.4.0 에 들어온 범용 기능(게임에서 옮긴 기능, 창 쌓기, 로딩과 저장, 입력 동작, 툰 3D 의 정석 꼴, 그림자 아틀라스)과 버그 고침을 같은 API 로 옮겼다. 폴더도 원본과 같아졌다. (모듈 경로는 그대로)
- Engine: 그래픽을 어디서나 쓴다. 씬의 create, initialize, tick, async 작업에서 engine.get_graphic() 으로 GL 자원을 짓는다. async/await 도 원본처럼 쓴다.
- 데스크탑이 브라우저가 하던 일을 스스로 한다: 소리 내기를 kira 에서 cpal 위의 엔진 믹서로 바꿨고, AVIF 와 HE-AAC 를 풀고, 낱말 나누기와 글꼴, Canvas2D 의 set_font, put_image_data 를 크롬과 맞췄다.
- Scene 과 Engine: Scene 터치는 원본도 러스트 판처럼 씬 꼴과 상관없이 노드의 위젯에 넘기게 바뀌어 두 엔진이 같다. 씬마다 그리기 앞에 뷰 좌표를 걸어 두게 원본과 같이 고쳤다.
- 문서: 문서 주석에서 API 자료를 뽑는 tools/apidoc(크레이트 vanilla-engine-apidoc), docs/api/0.4.0.json, 가이드 docs/guide/0.4.0/ko, en 을 둔다.
- 옮길 것: 공개 API 나 쓰임이 바뀐 곳은 맨 아래 '옮기는 법' 절에 한곳으로 모았다. 게임이 바꿔야 하는 것은 그 절만 보면 된다. (이름 규칙, SoundSystem::new 와 그 함수들, Image::get_pixels, ScreenEffect::destroy, JsonAsset.load, FbxLoader 이름, ToonScreenOutline, 툰 셰이딩)
새 기능과 바뀐 것
- GPU 메모리 셈(원본 afb9fc8, 14586d0 과 같게, 개발용): 텍스처, 렌더 버퍼, 버퍼의 바이트를 종류별과 주인별로 센다. 바이트는 형식과 크기로 셈한 이름값이고(멀티샘플 렌더 버퍼는 샘플 수를 곱함, 캔버스 기본 프레임 버퍼 몫은 색 4 + 깊이와 스텐실 4 바이트에 멀티샘플이면 4 배와 풀어 낸 색 한 장) 켜져 있을 때만 센다. 기본은 꺼져 있어 GlContext 의 짓기와 크기 정하기 호출은 깃발 하나만 보고 지나가고 프레임마다 드는 일은 없다. 더한 것: EngineConfiguration::track_gpu_memory(기본 false), Engine 과 Graphic 의 enable_gpu_memory_tracking, is_gpu_memory_tracking_enabled, read_gpu_memory_usage(꺼져 있으면 켜고 그 뒤에 지은 것부터 센다), 열거 GpuMemoryKind(Texture, Renderbuffer, Buffer)와 GpuMemoryUsage, GpuMemoryKindUsage, GpuMemoryOwnerUsage(원본 { totalBytes, canvasBytes, kindTable, ownerList } 의 짝). 주인은 지은 호출 스택의 위쪽 세 칸이고(데스크탑은 지을 때 스택 칸만 잡고 읽을 때 푼다, 웹은 스택이 없어 지은 소스 자리), 컨텍스트를 잃으면 모두 비운다. 센 곳은 GlContext 의 create_texture, create_buffer, create_renderbuffer, delete_*, tex_image_2d, tex_image_3d, tex_storage_2d, tex_storage_3d, generate_mipmap, renderbuffer_storage, renderbuffer_storage_multisample, buffer_data_size, buffer_data_u8_slice 이고 엔진 안에서 glow 컨텍스트로 바로 부르던 같은 호출은 GlContext 로 돌렸다. 웹의 이미지 원본 올리기(tex_image_2d_with_*, tex_image_3d_with_*)도 원본처럼 너비 x 높이 x 형식 바이트로 센다(이미지, 캔버스, 비디오, ImageBitmap, VideoFrame, ImageData). 이름 붙은 짓기(create_named_*)는 원본(WebGL2)에 없는 데스크탑 전용이고 버퍼 일부 갱신(buffer_sub_data)은 저장소 크기를 바꾸지 않아 원본도 세지 않으므로 세지 않는다.
- 그래픽 컨텍스트 잃음 처리와 셰이더 짓기 실패 알림(원본 afb9fc8 과 셰이더 짓기 실패 알림과 같게, 웹 판은 webglcontextlost 와 webglcontextrestored 를 같은 길로 받고 데스크탑은 컨텍스트를 잃지 않는다): Engine 에 add_graphic_context_event_listener, remove_graphic_context_event_listener, dispatch_graphic_context_event(열거 GraphicContextEvent 의 Lost, Restored, 리스너 GraphicContextEventListener), Graphic::is_context_lost, GlContext::is_context_lost 를 더했다. 웹은 잃으면 엔진이 preventDefault 로 되살림을 받고, 잃은 동안 그리지 않고(씬 갱신만 한다), 쌓인 묶음을 버리고, 표준 오류로 한 번 알리고, Lost 를 넘긴다. 되살아나면 엔진이 지은 기본 자원(기본 셰이더 프로그램, 버텍스 어레이, 흰 텍스처, 묶어 그리기, 파티클, 섞기 셰이더, 오프스크린 판, 그림 텍스처와 글자 캐시)을 다시 짓고 그리기를 잇고 Restored 를 넘긴다. 게임이 지은 GL 객체(툰 렌더러와 메시, 그림자 지도, 자기 셰이더, 렌더 타겟)는 엔진이 다시 못 지으니 게임이 Restored 에서 다시 짓는다. 엔진이 셰이더 프로그램을 짓지 못하면(툰 렌더러의 머티리얼, 화면 효과의 패스, Graphic::resolve_shader_program 의 프로그램, ToonView3D 의 렌더러) 표준 오류에 더해 GraphicError { kind, name, error } 를 그래픽 오류 리스너에 한 번 알린다. 더한 것: Engine::add_graphic_error_listener, remove_graphic_error_listener, dispatch_graphic_error, GraphicError, GraphicErrorKind::ShaderBuildFailed, GraphicErrorListener. 컨텍스트를 이미 잃은 뒤의 실패는 셰이더 탓이 아니라 알리지도 기억하지도 않고 되살아난 뒤 다시 짓는다. 툰 몸 조각 셰이더 readShadeLevel 의 음영 단 마지막 색 읽기를 원본과 글자까지 같게 상수 첨자와 고리로 바꿨다(아이폰 SE2 A13 이 동적 첨자 읽기에서 GPU 프로세스를 죽였다).
- 찍기 모드(VANILLA_CAPTURE_*) 첫 프레임 전에 불러온 씬의 0.3 초 세기를 첫 프레임 시각부터 센다(원본과 같게): 데스크탑은 파일을 바로 읽어 맡긴 애셋이 첫 프레임 전에 끝나 있어 세기가 시계 0 에서 시작했고, 원본은 fetch 가 첫 프레임 뒤에 끝나 세기가 첫 프레임 시각(1/60 초)에 시작해 씬의 첫 tick 이 원본 19, 러스트 18 프레임으로 한 프레임 어긋났다. 이제 둘 다 19 이고, 툰 쇼케이스를 같은 프레임 번호로 찍으면 원본과 36 화소(8 넘게 5) 다르다. 찍기 모드 밖은 그대로다.
- 후처리를 쓰는 게임의 캔버스 antialias 권고(문서만, 동작 그대로, 원본과 같게): ToonPostProcess 가 자기 MSAA 판에 그리므로 그걸 쓰는 게임은 EngineConfiguration::antialias 를 false 로 짓는다. true 면 캔버스 자체가 MSAA 라 화면에 옮기는 패스와 UI 가 표본마다 섞여 값이 더 든다(맥미니 2560x1440 툰 후처리 장면 GPU 처리량 6.89 → 6.49 ms, 끈 판 6.81 → 5.22 ms)
- 툰 몸 셰이더 기능 변형(원본 a5e964c 와 같게, 정석: 유니티 셰이더 키워드 변형처럼 쓰지 않는 갈래를 프로그램에서 뺌, 화면 그대로): 렌더러가 그리기의 텍스처(바탕, 빛남, 데칼, 맷캡, 천사 고리), 그림자 받기, 빛 묶음(램프 텍스처, 음영 단 두 개 이상, 테두리 빛 둘, 빛 세기 제한)을 보고 쓰는 기능 비트로 몸 조각 셰이더를 따로 짓는다. 쓰지 않는 갈래의 글이 컴파일 때 빠져 화소마다 비용이 준다(원본 아이폰 SE2 광부 외곽선 그림자 끈 판 프레임 간격 28.6
31.6 ms 대 24.725.3 ms). 변형은 처음 그릴 때 짓고(그때 한 프레임 끊길 수 있다, ToonRenderer::prepare_material 은 기본 프로그램만 미리 짓는다), 변형 수는 쓰는 비트 조합만큼이다. 기본 프로그램은 모든 갈래를 켠 그대로다. 게임이 할 일과 API 변화는 compose_toon_program_sources 의 끝 매개변수 disabled_features(&[&str], 빈 목록이 기본, 모르는 이름은 패닉) 하나뿐이다. 셰이더 글은 원본과 글자까지 같다. 그림자 입력이 없을 때 그림자 갈래를 빼지 않는 것(원본 맥 크롬에서 컴파일러가 식을 다르게 접어 8 화소가 1 단계 달라짐)까지 같다 - 툰 선의 판의 거울 항목 묶기(원본 c69269c 와 같게, ToonDrawQueue, ToonScreenOutline 의 draw_mesh_batch 끝 is_mirrored 칸, 거울에 비친 모습을 그리는 게임이 바닥으로 뒤집은 행렬로 같은 배우를 한 번 더 담는 꼴): 감기를 뒤집는 항목(행렬식이 음수나 is_mirrored)은 선의 판에서만 하나씩 따로 그렸다(몸, 바깥선 껍데기, 그림자는 이미 뒤집은 것끼리 묶었다). 선의 판도 같은 모형과 선 꼴이면 뒤집는 것끼리 인스턴스 그리기 한 번으로 묶고, 묶음 안은 모두 같은 감기로 그린다. 시험(toonbatchtests)은 뒤집은 감기 셋이 선의 판에서도 한 묶음이 되고 화면이 묶지 않고 그린 것과 바이트까지 같음을 본다
- 툰 인스턴스 버퍼 길(원본 293fe41 과 같게, 광부가 쓰는 길): ToonRenderer 에 update_instance_buffer_range(첫 인스턴스 번호부터 일부만 buffer_sub_data, 범위 밖은 Err), ToonInstanceBuffer 에 get_generation(고칠 때마다 1 씩), get_bounds(ToonInstanceBounds: 자리 상자 가운데, 가장 먼 자리까지의 거리, 가장 큰 크기), get_data, get_id 를 더했다. 인스턴스 꼴에 instanceLineId(크기 1, 자리 15, TOON_INSTANCE_LINE_ID_NAME, TOON_INSTANCE_LINE_ID_LOCATION, has_line_id, 있으면 사용자 어트리뷰트는 둘까지)를 더했다. ToonDrawQueue::add_mesh_instance_buffer 와 ToonScreenOutline::draw_mesh_instance_buffer 는 한 번 올린 GPU 버퍼를 몸, 바깥선 껍데기, 그림자, 선의 판이 같이 쓰고 다시 올리지 않는다(선의 판은 instanceLineId 칸을 번호로 읽음). 그림자 캐시는 버퍼 번호와 generation 으로 고친 것을 안다. 이미 있던 draw_mesh_instance_buffer 는 버퍼 전체의 경계로 통째 거른다(이름과 인자 그대로, 화면 밖이면 화소가 없어 화면은 같다, is_culled 가 false 면 거르지 않음). read_instance_buffer_sphere, is_sphere_in_frustum 을 공개한다. 인스턴스 꼴 셰이더 글과 선의 판 정점 셰이더 글은 원본과 글자까지 같다(시험이 원본 저장소를 node 로 불러 견준다). 시험(tooninstancebuffertests)은 광부 mid 꼴 장면을 array 와 buffer 두 길로 75 프레임 그려 화소가 바이트까지 같음, 올림 줄어듦(프레임 0 에서 24 대 6, 이후 13 대 0), 바위 하나 고친 프레임의 올림이 buffer_sub_data 하나, 그림자 캐시 다시 굽기를 본다
- 3D 색 공간 칸(원본 a803b71 과 같게, 유니티 Player Settings 의 Color Space: Gamma/Linear 꼴): EngineConfiguration::color_space 와 열거 ColorSpace(Gamma, Linear)를 더했다. 기본은 Gamma 이고 지금까지와 화면이 바이트까지 같다. Linear 면 툰 3D 가 정석 선형 길로 그린다. ToonRenderer::create_texture 가 색 텍스처(바탕색, 빛남, 데칼, 매트캡, 천사 고리, 램프)를 SRGB8_ALPHA8 로 올려 GPU 가 선형으로 풀고(거르기와 밉맵이 선형 공간), 셰이더는 그 텍스처에 pow 2.2 를 걸지 않으며, 넘기는 색(꼭짓점 색, 틴트, 빛남 색, 데칼 색, 바깥선 색)은 sRGB 표준 곡선(IEC 61966-2-1)으로 선형으로 바꿔 곱하고 섞는다. 화면 출력, ToonPostProcess 의 톤매핑 뒤, HDR 의 껍데기 바깥선과 ToonScreenOutline 선 색, GLB 바탕색(baseColorFactor 를 꼭짓점 sRGB 색으로)도 같은 곡선이다. 노멀, 마스크 같은 자료 텍스처는 ToonTextureOptions 의 is_color_data: false 로 RGBA8 에 그대로 올린다(감마에서는 가르지 않음). Linear 면 엔진이 짓는 3D 셰이더에 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어가고(셰이더 글은 원본과 같은 #ifdef 두 길), 머티리얼 조각에는 sRGB 색을 ToonSurface.baseColor 의 공간으로 바꾸는 toSurfaceColor(vec3) 를 더했다. ToonRenderer::new_with_options(ToonRendererOptions), ToonScreenOutline::new_with_options(ToonScreenOutlineOptions), ToonPostProcessOptions::color_space 로 색 공간을 받고(기본은 엔진의 값, 엔진이 없으면 Gamma, new 는 엔진의 값) get_color_space 로 알린다. Engine::get_color_space, Graphic::get_color_space 를 더했다. 데스크탑 GL 은 기본 프레임버퍼에 GL_FRAMEBUFFER_SRGB 를 켜지 않는다(셰이더가 곡선을 직접 걸므로, 웹 캔버스와 같음). 2D 는 어느 값이든 감마 공간에서 합성한다. 툰 예제 여섯(toonview, toonmaterial, toonpost, toonstyle, toonfx, toonshowcase)의 프레임 5, 40 과 시험 장면이 Gamma 에서 고치기 전과 바이트까지 같다. 찍기 시험(tests/tooncolorspace.rs)이 원본 tooncolorspacechrome 과 같은 검사(텍스처 부호화, 정의 줄, 반 섞기 감마 127, 선형 188 로 원본과 같은 값, 엔진 기본값)를 한다.
- 툰 모서리 어둠(원본 61a68fa 와 같게, 화면 공간 AO, GTAO: Jimenez, Wu, Pesce, Jarabo 2016, 유니티 URP SSAO 처럼 간접광에만): ToonPostProcess::set_ambient_occlusion(is_enabled, intensity, radius, resolution_scale, direct_lighting_strength), get_ambient_occlusion(ToonAmbientOcclusion), is_ambient_occlusion_enabled, draw_ambient_occlusion(gl, line_target, view_matrix, projection_matrix), get_ambient_occlusion_texture, get_ambient_occlusion_prepass(gl) 와 draw_ambient_occlusion_with_prepass, ToonRenderer::set_ambient_occlusion_texture, get_ambient_occlusion_texture, ToonDrawQueue::set_post_process, has_post_process 를 더했다. GTAO, 가로 흐림, 세로 흐림과 키우기 세 셰이더는 원본 글 그대로다. 노멀과 깊이는 화면 바깥선의 선의 판을 다시 쓰고, 바깥선이 없는 장면은 선은 긋지 않고 선의 판만 그린다(ToonScreenOutline 은 바깥 선과 꺾임 선 굵기가 둘 다 0 이면 씨앗과 넓히기를 건너뛰고 draw_outline 이 긋지 않는다). ToonDrawQueue 는 선의 판 뒤, 몸 앞에 셈해 렌더러에 걸고 end_frame 뒤에 푼다. 몸 셰이더는 TOON_AMBIENT_OCCLUSION 을 정의한 몸 프로그램(바깥선과 그림자 깊이는 기본 칸 것을 같이 씀, 짓지 못하면 기본 칸으로)으로 바꿔 화면 자리의 보임을 바탕빛에 곱한다. 텍스처 유닛은 16 이다. 원본은 원점을 프레임 블록 ToonFrame 의 ambientOcclusionOrigin 칸으로 올리고, 러스트는 프레임 블록이 아직 없어 같은 이름의 유니폼으로 같은 값을 올린다. 꺼짐은 기본 몸 프로그램이라 고치기 전과 바이트까지 같다. 찍기 시험(tests/toonambientocclusion.rs)이 원본 toonambientocclusionchrome 과 같은 장면(방 구석, 상자, 로봇)과 같은 검사를 하고, 잰 어두워진 밝기(벽 구석, 왼 구석, 상자 옆, 로봇 발밑)가 원본과 소수 첫째 자리까지 같다. 두 엔진 화면(640 x 360)의 다른 화소는 켬 원근 55, 직교 6, AO 판 25 ~ 140 이고 차이는 1 ~ 2 다.
- 툰 모서리 어둠의 직접 빛 몫(원본 50cb8de 와 같게, 유니티 URP SSAO 의 Direct Lighting Strength, HDRP ScreenSpaceAmbientOcclusion.directLightingStrength 꼴): set_ambient_occlusion 의 다섯째 인자 direct_lighting_strength(0 ~ 1, 원본 기본 0), get_ambient_occlusion_direct_lighting_strength(후처리와 렌더러), ToonAmbientOcclusion::direct_lighting_strength, ToonRenderer::set_ambient_occlusion_texture 의 둘째 인자를 더했다. 몸 셰이더는 칸을 고른 뒤 해의 칸 빛, 채움빛, 점광과 스포트라이트의 확산과 반사광에 1 - 몫 x (1 - 보임) 을 곱한다(원본 글 그대로, 곱하는 자리도 같아 몫 0 이 바이트까지 같다). 테두리빛, 빛남, 매트캡, 천사 고리는 그대로다. 값은 유니폼 ambientOcclusionDirectLightingStrength(원본은 프레임 블록 끝 칸)로 올린다. 찍기 시험이 몫 0, 0.25, 0.5, 1 에서 벽 구석 4.9, 5.9, 7.3, 9.8, 로봇 발밑 4.2, 6.0, 8.1, 12.1 로 원본과 같게 커지는지, 트인 바닥과 로봇 머리가 몫 1 에서도 끔과 바이트까지 같은지 본다.
- 툰 모서리 어둠 세로 흐림을 반 해상도로, 키우기를 깊이와 노멀 무게의 쌍선형 4 탭으로(원본 394f5af 와 같게, 유니티 URP SSAO 처럼 흐림은 줄인 판에서): 세로 흐림을 온 해상도 키우기 패스(7 x 2 = 14 탭)에서 떼어 반 해상도에서 가로 흐림과 같은 셰이더(방향 유니폼 blurDirection)로 하고, 키우기는 화소에서 가까운 반 해상도 2 x 2 칸을 쌍선형 무게에 화소의 깊이와 노멀로 고른 무게를 곱해 섞는 4 탭으로 바꿨다. 새 판 없이 GTAO 판과 흐림 판을 돌려 쓴다(가로는 GTAO 판에서 흐림 판으로, 세로는 흐림 판에서 GTAO 판으로). 셰이더 글은 원본과 글자까지 같다(시험이 원본 파일과 견준다). 같은 장면(방 구석, 상자, 로봇, 640 x 360, 원근과 직교와 바깥선)에서 원본 크롬과 화면이 최대 2/255(화소 0.5% 안쪽) 다르다.
- 판 끝 첨부 버리기(invalidate_framebuffer)를 쓰지 않고, 판을 통째로 덮어쓰는 패스 앞은 판 비우기(clear_buffer)로(원본 f94e794 와 같게): 실기기 사파리(아이폰 SE2, 아이패드 미니 6)의 원본에서 자리마다 켜고 끄며 재니 이득이 재어지는 자리가 없었고 프레임마다 수 ~ 수십 ms 가 붙었다(SE2 51 ms 가 끄면 11 ms, 아이패드 90 ms 가 25 ms). RenderTarget::resolve 는 푼 뒤 첨부를 버리지 않고(resolve_with_attachment_kept 의 is_attachment_kept 는 더는 쓰지 않으며 남겨 둔다), 투명도 층(begin_opacity_layer)이 끝날 때도 층의 깊이와 스텐실을 버리지 않는다. 블룸의 밝은 몫 뽑기와 흐림, 다단 블룸의 뽑기와 줄이기, 모서리 어둠의 네 패스는 앞에 판을 비운다. 화면 결과는 그대로다.
- 웹 그림 풀기를 브라우저로(원본과 같게)와 wasm 크기: 웹의 2D 그림은 원본처럼 늘 브라우저(HTMLImageElement)가 푼다. AssetLoader 의 그림과 ImageAsset::load 는 응답의 형과 확장자가 그림이 아니어도 형 없이 브라우저가 내용으로 가려 풀고(원본 img.src 와 같다), ImageAsset::load_from_bytes 는 원본 loadFromBytes 처럼 형 없는 Blob 을 브라우저가 풀 때까지 읽는 중이다(못 풀면 원본과 같은 "Load fail: 경로" 로 실패). 그래서 웹 wasm 에는 image 크레이트의 해독기(webp, gif, bmp, ico 포함), 엔진 JPEG 해독기, 색 프로필 읽기가 실리지 않는다. 웹의 색 글리프 PNG 풀기와 화면 찍기 PNG 쓰기는 image 밑의 png 크레이트로 한다(데스크탑은 그대로). image 크레이트는 웹에서 3D 재질과 GLB 그림을 그 자리에서 푸는 길(Material, decode_glb_image)에만 남고, 그 길을 쓰지 않는 게임에는 실리지 않는다. README 와 가이드의 wasm-bindgen 명령에 --remove-name-section --remove-producers-section 을 넣었다(함수 이름 절과 만든 도구 절을 뺀다). wasm-bindgen 뒤 _bg.wasm 크기(맥, wasm-release, 엔진 codegen-units 1, 앞은 고치기 전 README 명령, 뒤는 고친 뒤): uigallery 3,431,940 → 2,945,625 바이트(gzip -9 1,196,670 → 1,109,185), toonview 3,533,498 → 3,047,917(1,230,223 → 1,142,121). 그림을 읽는 loadingshowcase 는 절을 뺀 채로 견줘 5,356,171 → 4,931,916(2,195,165 → 2,047,645). 헤드리스 크롬에서 세 예제를 찍은 그림은 고치기 전과 화소 차이 0 이다.
- 소리 스트리밍 읽기(원본 AudioLoadType 과 같게, 유니티 AudioClip 의 Load Type, 언리얼 사운드 웨이브 스트리밍 꼴): AudioAsset 에 읽기 방식 AudioLoadType(Automatic, DecompressOnLoad, Streaming)과 set_load_type, get_load_type, is_streaming, get_stream_url, 문턱 AUTOMATIC_STREAMING_BYTE_THRESHOLD(1 MiB)를 더했다. 지금까지는 모든 소리를 통째로 PCM 으로 풀어 3 분 스테레오 배경음 하나가 약 61 MiB(f32)를 들었다. 기본은 원본처럼 통째로 풀기(DecompressOnLoad)이고, Automatic 을 고른 애셋만 1 MiB 보다 큰 파일(데스크탑은 파일 크기, 웹은 받는 머리의 Content-Length)을 스트리밍한다. 엔진 SoundSystem 의 소리 줄(SoundRow)에 load_type 칸을 더했고, None 이면 배경음악(is_music)은 Streaming, 효과음은 DecompressOnLoad 다. 데스크탑: 스트리밍 애셋은 압축된 자리(파일 경로나 메모리의 바이트)와 다듬기 계획만 들고(열 때 파일을 한 번 디먹스만 한다), 틀 때 플레이어마다 풀개 스레드가 조각마다 풀어 링 버퍼(16384 프레임, 스테레오 128 KiB)를 채우고 믹서의 스트리밍 소스가 읽는다(소리 스레드에서는 풀지 않는다). 패킷 읽기, 크롬과 같은 앞뒤 다듬기, SincResampler, 스피커 규칙을 통째로 풀기와 같은 코드로 써서 내놓는 표본이 통째로 푼 버퍼와 비트까지 같고(시험 소리 27 꼴), 스트리밍 소스도 버퍼 소스와 같은 셈이라 재생, 끝, 반복의 이음매, 되감은 자리, 멈춤, 빠르기, 다른 장치 표본율에서 출력이 비트까지 같다. 반복은 풀개가 끝에서 새로 열어 다음 바퀴를 바로 이어 써서 틈이 없고, 시작 자리(set_time)는 처음부터 풀어 그 자리까지 버린다. 링이 비면 그 동안 0 을 내고 자리는 컨텍스트 시계를 따른다. 길이(get_duration)는 컨테이너가 알리는 길이(시험 소리의 MP3, AAC, FLAC, WAV, Ogg 는 통째로 푼 것과 같고, 블록 길이를 적지 않는 WebM 은 4 밀리초 안팎(-68 ~ +177 프레임) 다를 수 있다)이고, 끝까지 한 번 풀면 푼 길이가 된다. 웹: 원본과 같게 HTMLAudioElement 를 MediaElementAudioSourceNode 로 플레이어의 GainNode 에 잇는다(플레이어마다 미디어 요소 하나, 음 높이는 빠르기를 따르고, 다른 출처는 CORS, 메모리에서 읽은 것은 blob: 주소). 컨텍스트가 멈추면 미디어 요소도 멈췄다가 이어 틀고, get_time 은 미디어 요소의 자리이며, SoundSystem 이 줄여 끄는 배경음악은 다 줄어든 시각에 멈춘다. 잰 값(맥미니 M2 Pro, 3 분 스테레오 AAC 2.92 MB, 출시 최적화): 통째로 풀기는 읽기 107 ~ 125 ms 에 PCM 63,504,000 바이트, 스트리밍은 읽기 1.6 ~ 1.8 ms(디먹스만)에 링 131,072 바이트, 처음부터 틀기 0.7 ~ 1.0 ms(링을 한 번 채움), 150 초 자리부터 틀기 0.03 ms(건너뛰기는 풀개 스레드가 처음부터 풀어 버리므로 그만큼 소리가 늦게 나고, 그 늦음은 재지 않았다). 원본 실기기(아이폰 SE2)는 읽기 137 ms 대 통째로 풀기 8,618 ms 였다.
- 그리는 사각형을 원본과 같게: Text 는 원본 calculateDrawnRect, calculateWrappedDrawnRect 그대로(한 줄은 기준선에서 위아래로 글꼴 크기의 1.5 배, 줄을 바꾸면 줄 묶음에 글꼴 크기만큼, 가로는 글꼴 크기의 반과 외곽선, Start 와 End 는 양쪽을 품는다). 전에는 잰 ascent, descent 로 좁게 잡아 원본이 그리는 스크롤 가장자리 줄을 러스트만 걸렀다. ShadowText 는 굽기와 상관없는 넉넉한 사각형(흐림 두 배와 굽는 여유, 그림자 내림), RichText 는 조각 합산 폭과 가장 큰 글꼴 크기와 외곽선(append_segment, clear_segments 가 더럽힌다), UILabel 리치 모드는 그 사각형, HeatHazeEffect 는 흔들림 폭 + 1, UIInputField 는 내용 영역과 한 줄 글 자리에 2 를 더한 것(그리는 값이 바뀌면 tick 이 더럽힌다), 입력 칸 문맥 메뉴는 그림자 여유를 알린다. 전에는 모두 모름이라 그 조상을 건너뛰지 않았다. 노드마다 하는 컴포넌트 거르기(WorldNode::draw_components)도 원본처럼 내용 영역 안에서만 그리는 컴포넌트가 있으면 내용 영역을 한 단위씩 넓혀 보고 크기 0 사각형은 뺀다(전에는 한 단위 좁아 스크롤 가장자리 칸을 원본보다 한 프레임 먼저 걸렀다).
- 하위 트리 '다 안' 표시(원본과 같게): 노드의 하위 트리 경계가 보이는 사각형(한 디바이스 픽셀 좁힘) 안에 다 들면 그 노드를 그리는 동안 자손은 하위 트리 견주기, 컴포넌트 거르기, 보이는 자식 범위 찾기를 건너뛰고 경계 크기만 본다. 자르기를 새로 걸면 그 안에서 다시 견준다(자르기 상태 번호). 부모 좌표 견주기는 변환이 축에 맞을 때 안쪽 사각형으로, 변환 뒤 견주기는 디바이스 좌표로 본다. Graphic::is_inside_visible_bounds 를 더했다. 예제 subtreecullinside(SUBTREECULL_CHECK=1)가 원본 subtreecullinsidechrome 장면을 켬, 끔, 모두 끔으로 찍어 화면 바이트, 칸마다 그린 수, '다 안' 으로 그린 수를 견준다.
- 로딩 화면 동안 그림 올리기(원본 prepareLoadedImages, prepareImage 와 같게, 유니티 asyncUploadTimeSlice, 언리얼 로딩 때 올리기 꼴): Graphic::prepare_loaded_images(time_limit_milliseconds) 와 prepare_image(image) 를 더했다. ImageAsset 과 AssetLoader 가 읽어 푼 그림(AssetLoadHandle::set_decoded_image)을 아직 올리지 않은 그림으로 맡기고(약한 참조), 엔진이 씬의 맡긴 애셋이 다 읽힌 뒤 로딩 화면 동안(0.3 초 더 보이기와 같이 세며) 프레임마다 2 밀리초씩 나눠 GPU 에 올린다. 다 올려야 initialize 한다. 찍기 모드는 한 번에 다 올린다. ImageAsset::load 를 부를 때 엔진에 든 Graphic 이 주인이고, Graphic 은 제 것만 올린다(주인을 모르면 Graphic 이 하나뿐일 때만, 원본과 같음). 지금까지는 처음 그리는 프레임에 올리기가 몰렸다.
- UIInputField IME 두 가지(원본과 같게, 한 줄과 여러 줄, 데스크탑 질문 창 입력 칸도): 글을 고른 채 조합하면 조합 중 보이는 글이 [고른 글 앞, 조합 글, 고른 글 뒤] 다(get_display_text, TextEditBuffer::build_display_text, 그리기, 커서와 밑줄 자리, 지금까지는 고른 글을 남긴 채 커서 자리에 끼웠다. 확정은 전처럼 고른 글을 갈음한다). TextEditBuffer::get_composition_start, get_composition_end, get_display_text_before_cursor 를 더했다. 조합 중 set_text 는 조합 상태와 조합 글을 비운다(지금까지는 조합 상태에 갇혀 보이는 글에 옛 조합 글이 남았다).
- 뼈 자세 고리(원본과 같은 자리, 언리얼 AnimBP 의 Transform (Modify) Bone, 유니티 LateUpdate 의 뼈 덮어쓰기와 같은 꼴): write_skin_pose 에 일곱째 인자 pose_adjust: Option
를 더했다. 움직임을 읽어 섞은 뒤, 스킨 행렬을 짓기 전에 뼈마다 지역 변환(자리, 돌림, 크기)을 고친다. ToonPoseAdjust::Hook(&mut 고리) 는 (locals, skeleton) 으로 불러 그 고리가 고치고(locals 는 그 부름만의 사본이라 제자리에서 고쳐도 뼈대의 쉬는 자세가 바뀌지 않는다), ToonPoseAdjust::Bones(&[BoneModifier]) 는 뼈마다 고침 표(node_index 또는 name, translation, rotation, scale, mode, weight, Default 는 아무것도 고치지 않음)로 건다. 표를 거는 adjust_bones(locals, skeleton, modifiers) 와 고침 꼴 BoneModifyMode(Add 는 자리를 부모 공간에서 더하고 돌림을 그 뼈 공간에서 뒤에 곱하고 크기를 곱함, Replace 는 준 값으로 바꿈)를 더했다. weight 는 고치기 앞과 뒤 사이의 몫이다. None 이면 지금과 비트까지 같고, 한 뼈를 고치면 그 뼈와 그 아래 본만 바뀐다. 원본을 크롬 158 에서 돌린 fox.glb 의 스킨 행렬(표, 섞기와 표, 고리)과 비트까지 같다. (tests/assets/skinposeadjust) - 자세 셈의 사원수 정규화(움직임 갈래 섞기, 두 돌림 섞기)를 원본처럼 Math.hypot 셈(엔진 hypot_list)으로 바꿨다. 전에는 제곱 합의 제곱근이라 길이 끝자리가 원본과 갈릴 수 있었다. (무작위 사원수 백만 개에서 34 %, 스킨 행렬은 f32 라 드물게 끝자리가 갈렸다)
- 3D 카메라 흔들림(원본과 같은 자리, 유니티 Cinemachine Impulse, 언리얼 Camera Shake 꼴): CameraShake 를 더했다. CameraShake::new(바탕 씨앗)(Default 는 1), add(CameraShakeOptions) 의 흔들림마다 자리 3 축과 돌림 3 축(pitch, yaw, roll)의 세기(amplitude, rotation_amplitude, 축마다 몫 position_axes, rotation_axes), 주파수(frequency, 기본 10), 길이(duration), 오름(attack), 잦아듦((1 - 나이 / 길이) 의 decay_exponent 제곱, 기본 2), 나이(age, 늦게 보인 사건을 그 나이로 넣으면 처음부터 넣은 것과 같은 값이 이어짐, 음수면 늦게 시작), 씨앗(seed: Option
)을 받는다. 결은 축마다 주파수가 조금 다른 사인파 둘이고, 사는 흔들림은 겹쳐 더하며, 같은 씨앗이면 같은 값이다. update(초), read()(카메라 지역 축의 CameraShakeOffset { position, rotation }), is_shaking, clear 가 있다. 거는 곳으로 Camera3D::set_view_offset(position, rotation)(보기 행렬 마지막에 카메라 지역 덧붙임, 셈하는 길과 원 행렬 모두, get_eye_position 은 덧붙이기 앞 값)과 게임이 셈한 보기 행렬에 거는 create_offset_view_matrix(&view_matrix, position, rotation) 를 더했다. 씨앗 뽑는 차례와 사인파 상수가 원본과 같아 원본을 크롬 158 에서 돌린 read() 값 852 개, 덧붙인 보기 행렬과 비트까지 같다. (tests/assets/camerashake) - glTF 양자화 읽기(KHR_mesh_quantization, 원본과 같게): 툰 GLB 읽기(read_glb_arrays, read_glb_node_arrays, read_glb_node_infos)와 SkinnedModel 이 꼭짓점 속성을 정수로 담은 GLB 를 읽는다. 정규화 정수는 glTF 명세의 공식(부호 있는 것은 max(c / 127, -1), max(c / 32767, -1))으로 나누고 정규화가 아닌 정수는 값 그대로 읽는다. 위치의 되풀이는 노드 변환이나 inverseBindMatrices 가 맡고, 텍스처 좌표는 재질 텍스처의 KHR_texture_transform 을 구워 넣는다. 움직임의 정규화 정수 돌림도 읽는다. 이름 없는 메시 노드는 이름 있는 부모 노드의 부품에 든다(양자화 도구가 되풀이 변환을 맡기는 잎 노드, read_glb_node_infos 는 이름마다 범위를 모은다). 정수 위치 뼈대 메시의 새로 짓는 바깥선 굵기는 쉬는 자세의 모형 좌표로 맞춘다. extensionsRequired 에 읽지 못하는 확장(EXT_meshopt_compression, KHR_draco_mesh_compression 등)이 있거나 접근자가 바이너리 덩어리 밖 버퍼(meshopt 의 fallback 버퍼)를 가리키면 원본과 같은 글의 Err 다. 새로 read_float_accessor_array, AccessorArray::Byte 와 Short, COMPONENT_TYPE_BYTE, COMPONENT_TYPE_SHORT 를 더했다. 원본 시험의 합성 GLB 와 원본 읽기가 낸 값(tests/assets/glbquantization)으로 두 엔진이 같은 값을 내는지 본다(tests/glbquantization.rs, 맥에서 차이 0). gltfpack 으로 양자화한 채굴선, 마네킹, 노멀 있는 여우도 두 엔진의 읽은 배열이 바이트까지 같다.
- glTF 노멀 없는 프리미티브의 평평한 노멀(원본 8cc37df 와 같게, glTF 2.0 명세 'Using Primitive Data': 노멀이 없으면 평평한 노멀이고 탄젠트는 무시한다): 툰 GLB 읽기(read_glb_arrays, read_glb_node_arrays)는 노멀이 없는 프리미티브의 꼭짓점을 번호 차례대로 삼각형마다 풀고 삼각형마다 (p1 - p0) x (p2 - p0) 을 길이 1 로 줄여 세 꼭짓점에 준다(넓이 0 인 삼각형은 0). 몸으로 새로 짓는 바깥선 껍데기도 같다. 전에는 그런 프리미티브를 담지 않아 예제 fox.glb 를 툰으로 읽으면 빈 그림이었다. SkinnedModel 은 노멀이 없으면 업로드 때 부드러운 노멀(번호 있는 메시는 꼭짓점마다 면 노멀을 더해 평균)을 지어 명세와 달랐다. 이제 interpret_content 가 같은 셈으로 꼭짓점을 풀어 평평한 노멀(원본 Float32Array 와 같게 32 비트 실수로 반올림)을 주고 indices 는 None 이다(위치, 텍스처 좌표, 조인트, 가중치, 모프 델타도 푼다). 실제 GLB 여덟(채굴선, 노멀 없는 여우와 있는 여우, 마네킹, 그 양자화판)을 두 엔진으로 읽은 툰 배열과 PBR 배열 110 파일이 바이트까지 같다(전에는 PBR 여우 둘이 달라 108). 메시 빌더 도형 열(상자, 둥근 상자, 원기둥, 구, 회전체, 캡슐, 도넛, 팔면체, 깎은 덩이, 노멀이 서로 지워지는 앞뒤 면의 사각형 껍데기와 삼각형 껍데기)의 몸과 껍데기 배열 28473 값도 원본과 바이트까지 같다. (tests/glbquantization.rs, skinnedmodel.rs 의 여우와 자산 시험)
- 툰 강조(원본 e85d927 과 같게): ToonScreenOutline 번호마다 선 색 set_line_color(line_id, color), remove_line_color(line_id), clear_line_colors(), get_line_color_count(). (언리얼 Custom Stencil 꼴, 선의 판에 이미 있는 번호로 색을 고른다) 표는 선 번호 전부를 덮는 128 x 128 찾기 텍스처라 넣는 수에 상한이 없고, 바뀐 때만 올린다. 맞닿은 선은 앞쪽 번호의 색이고, 표에 없는 번호는 set_color 의 색 그대로다. 표가 비면 섞기는 지금과 화소가 같다.
- ToonRenderer 인스턴스마다 빛남: ToonInstance 의 emissive_color(Option<[f64; 3]> sRGB, 기본 None)와 emissive_intensity(선형 배, 기본 1). 그 인스턴스의 명암과 무늬 위에 더해 그 인스턴스만 밝힌다. 인스턴스 자료는 그대로 20 수다. 행렬을 아핀 3x4 로 읽고 아래 줄 네 칸(원소 3, 7, 11, 15)에 빛남을 싣는다. (Godot MultiMesh, 유니티 BatchRendererGroup 의 3x4 행렬 꼴) ToonInstanceLayout 의 instanceMatrix 도 같고, 정점 조각에서는 vertex.emissive 다.
- 원본 크롬 시험과 같은 장면의 찍기 시험 tests/toonhighlight.rs (cargo test --test toonhighlight, 숨긴 창의 GL): 다섯 그림(바탕, 번호 색, 비운 뒤, 몸, 빛남)이 맥의 원본 크롬과 화소까지 같다. (480 x 200 의 96000 화소 가운데 다른 화소 0)
- 툰 GLB 접근자 범위: 툰 GLB 읽기(read_glb_arrays, read_glb_node_arrays, read_glb_node_infos)가 바이너리 덩어리 밖을 읽는 접근자를 0 으로 채우지 않고 Err("GLB 접근자 N 가 바이너리 덩어리 밖을 읽습니다. (바이트 시작 ~ 끝, 바이너리 덩어리 길이 바이트)") 로, bufferView 가 없는 접근자는 bufferView 0 을 읽지 않고 glTF 명세대로 0 으로 채운다. (원본 SkinnedModel 의 접근자 읽기와 같은 뜻이다. 원본 툰 읽기는 짧게 읽은 배열을 그대로 쓰고 bufferView 가 없으면 TypeError 라 같은 검사를 넣어 맞춘다)
- 해 그림자 치우침을 그림자 텍셀 크기에 맞춤(원본 025ea9d 와 같게, 유니티 URP 의 Depth Bias, Normal Bias 텍셀 단위와 받는 쪽 노멀 치우침, 기울기 비례 치우침 꼴): ToonRenderer 가 셰이더에 박아 두었던 노멀 밀기 0.02(월드)와 깊이 치우침 0.0015(깊이)를 ShadowMap 의 새 set_bias(depth_bias, normal_bias), get_depth_bias, get_normal_bias(텍셀 단위, 기본 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/shadowbias.rs(cargo test --test shadowbias, 숨긴 창의 GL)가 둘 다 보고, 잰 값(면의 어두워진 몫 0.0, 0.0, 낮은 벽 그림자 -1.505 ~ -1.53 깊이 98, 높은 벽 -1.505 ~ -2.095)이 원본 크롬과 같다. 셰이더 조각은 원본과 글자까지 같고, 치우침 셈은 원본 readShadowBias 와 비트까지 같다. 점광과 스포트라이트 그림자(ShadowAtlas)는 이미 텍셀 크기와 기울기에 맞춘 노멀 치우침이라 그대로다.
- 찍기 모드 결정성(원본과 같게): 찍기 모드(VANILLA_CAPTURE_*, 웹 ?capture=)에서 씬을 불러온 뒤 로딩 화면 0.3 초 기다림을 실제 시각 대신 엔진 시계(프레임마다 1/60 초)로 센다. 애셋 받기처럼 실제 시간이 드는 불러오기(엔진 시계로 열리는 GameScene 로딩 문을 뺀 맡긴 애셋과 작업)가 남은 씬이 있으면 그 프레임은 프레임 번호와 시계를 올리지 않아, 다 받은 뒤부터 센다. 같은 예제를 두 번 찍으면 같은 프레임 번호의 그림이 바이트까지 같다. (.github/scripts/capturedeterminism.cjs 가 quickstart, loadingshowcase 를 두 번씩 찍어 견준다)
- 씬 훅 꼴을 원본과 같게(전역 엔진이 어디서나 되므로 훅의 이름과 인자를 원본 Scene, GameScene, UIScene 과 같게): 불러오기 차례는 원본처럼 create() 다음 load(engine) 다음 initialize(engine) 다. 전의 create(engine)(원본 async load 자리)는 load(engine) 로 이름을 바꿨고, 인자 없는 create() 훅을 새로 둔다(load 앞에 한 번, 엔진이 그 사이에 루트를 뷰 크기로 맞춘다). 원본이 엔진을 받는 훅(load, initialize, finalize, unload)만 engine: &Engine 을 받고, 나머지는 원본 인자만 받는다: draw_on_load(graphic), destroy(), on_page_process_restored(), on_page_visibility_restored(), resize(canvas_native_size), tick(time_delta), pre_draw(graphic), draw(graphic), post_draw(graphic), draw_gizmos(graphic), touch_press, touch_move, touch_release, touch_cancel(view_input_position), touch_wheel(view_input_position, wheel_delta). GameScene, UIScene 의 load_assets(), layout() 도 원본 loadAssets(), layout() 처럼 인자가 없다. 바탕의 공개 함수도 원본과 같게: SceneBase::tick(time_delta), tick_touch(time_delta), draw_scene_background(graphic), GameSceneBase 와 UISceneBase 의 load(engine)(전 create), load_assets(), draw_on_load(graphic), resize(canvas_native_size), layout(), compute_safe_area_rect(), tick(time_delta), is_dev_tools_capturing_input(), pre_draw(graphic), post_draw(graphic), draw_screen_fade(graphic), apply_play_area_reference(). ScreenFadeDarkStarter::start(scene) 도 엔진을 받지 않는다.
- 전역 엔진(원본 static Engine.getEngine() 과 같은 자리, 언리얼 GEngine, 고도 Engine 싱글톤 꼴): 엔진은 처음 한 번 만들고 지우지 않는다. Engine::new 가 엔진을 프로그램 끝까지 사는 자리에 두고 &'static Engine 을 돌려주며, Engine::get_engine() 이 Result<&'static Engine, EngineAccessError> 로 만든 직후부터 어디서나(씬 함수, draw, 컴포넌트 tick 과 draw, 위젯 콜백, 페이지 이벤트 리스너, async 작업 안) 같은 엔진을 준다. 엔진의 공개 함수는 모두 &self 가 되었고(안쪽 가변성), 씬 훅과 작업 문맥(EngineContext::with, SceneContext::with)이 받는 엔진은 &mut Engine 에서 &Engine 으로 바뀌었다. 매니저와 그래픽 읽기는 get_x 가 Ref, get_x_mut 이 RefMut 을 주고(get_all_loaded_scenes, get_canvas, get_engine_configuration, get_platform 도 Ref), 같은 칸을 고치는 중에 또 빌리면 함수 이름과 칸 이름을 적은 패닉이다. 다른 스레드는 Err(OtherThread), 엔진을 만든 적이 없으면 Err(NotCreated). 원본 Scene.getEngine 은 SceneBase::get_engine, UIView.getEngine 은 UIView::get_engine 으로 같은 전역 엔진을 준다. ComponentContext::get_engine 은 문맥보다 오래 사는 &Engine 을 준다. (core/globalengine.rs)
- 안티에일리어싱 켜고 끄기(원본과 같은 칸): EngineConfiguration.antialias(기본 true, 지금 보기 그대로)를 더했다. 끄면 기본 프레임 버퍼의 멀티샘플(MSAA)을 쓰지 않는다. 데스크탑은 멀티샘플을 묻지 않고 표본이 가장 적은 GL 설정을 고르고, 웹은 WebGL 컨텍스트를 antialias: false 로 만든다. 고해상도 모바일에서 프레임마다 드는 리졸브 비용이 빠진다. 웹은 켬과 끔만 고르고 표본 수는 브라우저가 정한다. 데스크탑은 켜면 표본 4 다.
- 렌더 배율 상한(ViewManager::set_max_render_pixel_ratio)을 원본과 같은 꼴로: 같은 값이면 아무것도 하지 않고, 바뀌면 값만 적고 is_view_rect_pending 을 세운다. 데스크탑과 웹 모두 다음 프레임 머리에서 창 크기 바뀜과 같은 길(Engine::resize)로 캔버스와 뷰 영역을 맞추고 씬도 화면 영역이 바뀐 것을 받는다. 맞추면 calculate_view_rect 가 내린다. ViewManager::is_view_rect_pending() 을 더했다.
- 3D 렌더 스케일(ToonView3D::set_render_scale, get_render_scale, 원본과 같은 범위 0.05 ~ 4, 유니티 URP renderScale, 언리얼 화면 비율과 같은 뜻): 배율이 1(기본, 지금 그대로)이 아니면 ToonView3D 가 3D 를 내용 영역의 화면 크기 x 배율의 판(깊이 24, 기본 프레임 버퍼가 멀티샘플이면 표본 4)에 투명하게 비운 뒤 그리고(스텐실과 가위는 끄고, 다 그리면 리졸브), 2D 그리기 길로 선형 거르기, source-over 로 늘여 얹는다. UI 는 기기 화소 그대로라 글자가 흐려지지 않는다. 2D 자르기를 따르고, 3D 가 덮지 않은 곳은 아래 2D 가 비친다. 판은 제 깊이를 써서 set_depth_cleared(false) 로 앞의 3D 깊이를 이어 쓰는 것은 배율 1 일 때만 된다. 판은 노드에서 떨어질 때(detach)와 버려질 때 지운다. 그리기 함수의 다섯째 인자를 드로잉 버퍼 높이에서 ToonViewOutput(output_framebuffer 지금 묶인 프레임 버퍼, None 이면 기본 프레임 버퍼, output_viewport 그 안의 GL 뷰포트, 정수, 왼쪽 아래 원점, 원본 사각형의 outputFramebuffer, outputViewport)으로 바꿨다. examples/toonview 는 환경 변수 VANILLA_RENDER_SCALE=0.5 로 볼 수 있다(원본 ?renderScale=0.5). ToonRenderer 의 비치는 섞기는 원본처럼 알파 칸을 미리 곱한 over 로(ToonBlendMode::Alpha 는 SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA), 더하기는 알파를 바꾸지 않게(ONE, ONE, ZERO, ONE) 했다. 맥에서 toonview 배율 0.5 를 헤드리스 크롬 원본과 견주면 평균 차이 0.10, 8 넘는 화소 0.33%(가장자리 멀티샘플 무늬)다. UIDocument 시험 자료(ToonView3D 의 RenderScale 칸)는 원본 파일 그대로다.
- 원본과 같은 이름 더하기: WorldNode::copy_content_size_to(&mut Vector2)(원본 copyContentSizeTo), ShadowAtlas::get_light_count()(원본 getLightCount). 원본은 안쪽에서만 쓰던 isComponentDrawCulled, refreshMatrices, readStorage 를 감추고 아무 일도 하지 않던 UIButton.setStateEvent 를 뺐다.
- 툰 바깥선 깊이 여유(원본 836e59e 와 같게, 유니티, 언리얼의 깊이 노멀 경계 검출에서 문턱을 측정 오차에 맞추는 꼴): ToonScreenOutline 이 같은 번호 안의 가려진 실루엣을 가를 때, 가린 화소가 가려진 화소의 접평면에서 떨어진 거리를 쓴다. 지금까지는 두 화소의 접평면 거리 가운데 작은 쪽을 썼는데, 가린 쪽이 둥근 면의 실루엣이면 그 접평면이 시선을 품어 거리가 화소 한 칸 밑으로 줄어 선이 점선으로 끊길 수 있었다. 문턱에 더하던 고정 여유(그 깊이의 화소 크기 두 배)는 잰 오차에 비례하는 여유로 바꿨다: 노멀 8 비트 팔면체의 각 오차(0.0165 rad) x 두 화소 자리 사이 거리, 꺾인 줄을 사이에 둔 두 화소의 화소 한 칸 x 두 노멀이 벌어진 사인, 깊이 24 비트 한 칸. 여유 배율 set_depth_margin, depth_margin(기본 2)과 depth_threshold 를 더했다. 씨앗 셰이더 글은 원본과 같다. 두 엔진 바깥선 화면(toonao offOutline 640 x 360)의 다른 화소가 37(가장 큰 차이 153) → 0 이 되었다.
- GPU 처리량 재기(원본 9af0e19 와 같게, 유니티 프로파일러의 GPU 모듈, 언리얼 stat gpu 처럼 GPU 가 그리는 시간을 따로 보기): Engine::measure_gpu_throughput(frame_count) 을 더했다. 지금 장면을 씬 갱신(tick) 없이 엔진 프레임과 같은 그리기 길(엔진 갱신의 씬 그리기를 뗀 같은 함수)로 잇달아 그리고 1 화소 읽기로 GPU 를 기다린 프레임당 벽시계 시간을 GpuThroughput { frame_count, chunk_frame_count, milliseconds_per_frame, chunk_milliseconds_per_frame } 으로 돌려준다(Promise<Result<GpuThroughput, String>>). 다음 엔진 갱신부터 데움 10 프레임 뒤 30 프레임씩 갱신 하나에 한 덩이를 그려 한 번에 길게 막지 않고, 재는 동안 엔진 시간, 입력, 프레임 번호, 찍기는 서 있으며, 다 재면 엔진 루프가 이어 돈다. 같은 상태를 되풀이해 그리므로 그림자 OnChange 같은 캐시는 다시 굽지 않고, 화면에 내는 것은 덩이마다 마지막 프레임만 한다.
- 엔진 GL 컨텍스트 GlContext(원본 Graphic.getWebGL2RenderingContext 가 주는, 상태 함수를 가로챈 컨텍스트와 같은 자리): Graphic::get_gl, run_external_pass 의 pass, 툰 렌더러의 on_before_draw, ToonDrawQueue 의 단계 콜백, ToonView3D 의 그리기 함수가 glow::Context 대신 GlContext 를 준다. glow 의 HasContext 는 봉인된 트레이트라 밖에서 구현할 수 없어, GlContext 가 상태 함수(bind_framebuffer, viewport, scissor, enable, disable, is_enabled, clear_color, color_mask, blend_func, blend_func_separate, blend_equation, blend_equation_separate, depth_mask, depth_func, front_face, cull_face, use_program, link_program, delete_program, bind_vertex_array, active_texture, bind_texture, pixel_store_i32, 만들기와 지우기, get_parameter_* 읽기)를 glow 와 같은 이름, 같은 꼴의 메서드로 가로채 상태 캐시를 거쳐 부르고, 그 밖의 함수(HasContext 의 메서드 모두와 웹의 glow::Context 고유 메서드, 380 개 가운데 웹 전용 44 개)는 같은 이름, 같은 꼴의 메서드로 기계로 지어(src/core/glcontext/generated.rs, 머리 주석에 지은 법) 안의 glow::Context 를 그대로 부른다. Deref 는 없앴고 안의 glow::Context 를 꺼내는 공개 길도 없어,
&glow::Context를 받는 함수에 GlContext 를 넘기면 컴파일 오류가 난다(게임 코드가 상태 캐시를 건너뛸 길이 없다, 원본이 컨텍스트를 가로채 모든 상태 호출을 아는 것과 같음). 엔진 안에서 GL 을 받는 함수(공개와 비공개 모두)도&glow::Context대신&GlContext를 받는다. 데스크탑 GL 4.5 의 이름 붙은 만들기(create_named_framebuffer, create_named_texture, create_named_buffer, create_named_vertex_array), program_binary, pixel_store_bool, 웹의 bind_external_framebuffer 도 상태 캐시를 거치거나 그 기억을 잊게 손으로 두었다. 원본 WebGL2 에 없는 데스크탑 GL 함수(그리기 버퍼마다의 enable_draw_buffer, color_mask_draw_buffer, blend_func_draw_buffer, blend_equation_draw_buffer 같은 것과 viewport_f32_slice, scissor_slice, bind_texture_unit)는 상태 캐시가 그 값을 잊게 한다. 그래서 게임 코드가 한 콜백 안에서 GlContext 로 상태를 바꾼 직후 엔진 그리기를 이어 불러도 엔진이 건너뛰기를 틀리지 않는다. 상태 캐시에 섞기 식(blend_equation, blend_equation_separate)도 더했다(원본과 같음). 진짜 GL 시험 둘을 더했다: GlContext 와 엔진 길을 섞어 800 번 마구 부르며 잊기 없이 읽기 답과 건너뛰기 견주기가 진짜 GL 과 같은지(다른 곳 0), GlContext 로 프로그램, 텍스처, 활성 유닛, 섞기, 가위를 바꾼 직후 엔진 그리기의 픽셀이 맞는지(날 glow 로 바꾸면 틀리는 것도 같이 보아 시험이 문제를 잡는지 확인한다). 게임 길(GlContext)로만 상태 함수 44 갈래를 2000 번 마구 부르며 부를 때마다 검사 모드로 견주는 시험(어긋남 0)과, 날 glow::Context 를 꺼내거나&glow::Context를 받는 함수에 넘기는 코드가 컴파일되지 않는지 보는 compile_fail 문서 시험 다섯을 더했다. 엔진이 경계(get_gl, run_external_pass 의 pass 끝, on_before_draw 뒤, 단계 콜백 뒤)에서 잊던 안전망은 걷었다(원본과 같음). 예제 modelviewer, blendmodes, batchclip 의 화면은 바꾸기 전과 화소까지 같다(modelviewer 는 씬 시작이 실제 시각에 달려 프레임 번호가 둘 밀린 짝으로 견줌). - 2D 묶어 그리기가 덜 끊긴다(화면 결과는 그대로, 원본과 같은 꼴): (1) 축에 맞고 화소 경계에 놓인 각진 자르기(begin_clip_rect, Mask, UIScrollView)는 스텐실 대신 정점에 실은 자르기 사각형 표 번호로 묶음 셰이더가 화소 가운데 기준으로 버려(유니티 RectMask2D, UI Toolkit 꼴) 자르기를 걸고 풀어도 묶음이 이어진다. 돌아갔거나 둥근 자르기, 멀티샘플 화면(데스크탑은 기본 프레임버퍼의 표본 수, 웹은 원본처럼 컨텍스트 속성 antialias 로 본다)에서 경계가 화소 경계에 놓이지 않은 자르기는 지금처럼 스텐실이다(멀티샘플 스텐실은 경계 화소를 반쯤 칠해 화소 가운데 기준과 갈리기 때문). 묶지 않는 그리기(바꿔 끼운 셰이더, 셰이더 섞기, 셰이더 섞기 파티클)는 같은 사각형을 가위로 걸고, run_external_pass 는 그동안 셰이더 자르기를 스텐실에 적어 둔다. (2) 한 묶음에 텍스처를 여러 장(기기 MAX_TEXTURE_IMAGE_UNITS 와 16 가운데 작은 것) 묶어 이미지, 도형(흰 텍스처), 글자 텍스처가 번갈아도 이어진다(PixiJS 꼴). (3) draw_colored_quads(파티클, 아지랑이)도 고정 블렌딩이면 같은 묶음에 들어가 파티클 셰이더와 같은 식으로 셈한다. (4) 화면 밖 거르기(is_local_rect_visible)가 걸린 자르기의 경계 상자도 봐 스크롤 칸 밖 줄의 컴포넌트를 그리지 않는다(유니티 RectMask2D, 옵션 없이 저절로). DevTools 인스펙터에 UIView, UIButton, UIProgressView, UISlider 의 isDrawnInsideContent 가 원본과 같은 자리로 보인다. 묶음 정점 상한은 원본과 같은 6 x 8192 다. 잰 값(맥 데스크탑 숨긴 창 1920 x 1080, 예제 batchclip, 바꾸기 전과 화소가 모두 같음): 설정 창 같은 장면(창 하나, UIScrollView, 줄 50 개, 줄마다 글자와 단추와 도형) 드로 콜 45 에서 1, 원본 tests/core/batchclipchrome.test.mjs 와 같은 장면 51 에서 14(1e-9 라디안 돌려 스텐실 길로 그린 것과 화소가 모두 같음)
- 그림자와 알림 인자 꼴(원본과 같게): ShadowText::set_shadow, ShadowImage::set_shadow 가 원본 setShadow(색, 불투명도, 내려가는 만큼, 번지는 만큼) 처럼 불투명도를 따로 받는다(색의 알파는 읽지 않는다). ToastMotion::new() 는 원본 new ToastMotion() 처럼 인자가 없고(위에서 들어온다, set_enter_side 로 바꾼다), show(글, 머무는 초, 글 넣는 함수) 가 원본 show(text, seconds, applyText) 처럼 나오기 시작할 때 부를 FnOnce(&mut ComponentContext) 를 받는다. set_apply_text_handler 와 ToastApplyTextHandler 는 없다(ToastApplyText 로).
- 예약어 이름 없애기(원본과 같은 이름): 두 엔진 모두 예약어(use, move, loop, in)를 이름으로 쓰지 않는다. Cooldown::r#use 를 빼고 activate 하나로(원본 activate), FullscreenPass::r#use, ShaderProgram::r#use 를 빼고 use_program 하나로(원본 useProgram), PointerGesture::r#move 는 move_pointer(원본 movePointer), Action::r#loop 는 repeat_while(원본 repeatWhile), easing_function 의 r#in, out, in_out 은 ease_in, ease_out, ease_in_out(원본 easeIn, easeOut, easeInOut). 타임라인 자료의 이징 이름("quadratic.in" 같은)은 자료 꼴이라 그대로다.
- 글자 안티앨리어싱을 Graphic 메서드로(원본 Graphic.setTextAntialiasEnabled, isTextAntialiasEnabled 와 같은 자리): Graphic::set_text_antialias_enabled(bool), is_text_antialias_enabled() 를 더했다. 원본 import.js 도 AudioManager, DevTools(원본 DEVTools 에서 이름을 바꿈), Pane, PaneStyle, PaneTheme, WebSocketClient 를 내보내 두 엔진 맨 위 이름이 같아졌다.
- 두 엔진 차이 맞추기(러스트 쪽 작은 것들): 부드러운 원 텍스처(파티클 기본 스프라이트)는 원본처럼 반지름 0.7 까지 꽉 차고 0.7 ~ 1 을 smoothstep 으로 잦아든다(전에는 (1 - 거리)^2 라 파티클이 작고 옅었다). 노드 기즈모는 원본처럼 컴포넌트 기즈모를 먼저 그리고 테두리와 피봇 점을 '#00ff00' 으로, 피봇 점 반지름 4. BuildInfo 는 version.json 을 받지 못하면 원본처럼 조용히 넘어간다(손잡이가 빈 바이트로 끝나 AssetLoader 실패 목록에 들지 않는다). 개발 정보 창(use_statistics)은 원본 drawStatistics 처럼 1.4 배로 16px DOSGothic, 줄마다 16 씩 engineVersion, platformName, browserName, canvasNativeSize, referenceResolutionSize, viewScaleMode, viewNativeRect, viewSize, 입력 자리, time, framePerSecond, timeDelta, drawCalls, vertices, triangles, culledNodes 를 쓴다(ViewScaleMode::get_name 은 원본 값 글 "stretchShort" 같은 것). format_number, format_number_with_unit 은 언어 태그를 크롬(V8 CanonicalizeLanguageTag, ECMA-402 IsStructurallyValidLanguageTag)과 같은 차례로 검사하고 틀린 태그("EN_gb", 빈 글, "en-u" 같은 것)는 원본 RangeError 처럼 Err(FormatError::InvalidLanguageTag) 다(오류 글도 크롬과 같다, node 로 확인한 태그 77 개). 찍기 모드(VANILLA_CAPTURE_*, 웹 ?capture)는 결정적으로 찍게 시간이 프레임마다 1/60 초씩 간다(원본 ?capture 와 같은 셈, 30 번째 프레임의 시간이 크롬과 같은 비트. 크롬 견주기도 원본 찍기 모드로 같은 프레임 번호를 받는다. 씬의 로딩 뒤 0.3 초는 원본 setTimeout 처럼 실제 시각). SpriteAnimator::find_sprite(원본 findSprite, Sprite 가 든 노드의 NodeId 를 기억). UIDocument 의 to_json_text, serialize_node 는 원본 toJsonText, serializeNode 처럼 하나로 &mut self 게터까지 읽는다. UISceneBase::get_dev_tools, get_dev_tools_mut(원본 UIScene.getDevTools). 초안 타일맵은 원본처럼 타일셋을 나눠 쓴다(Rc
, 넣은 뒤 고치지 않는다) - 로직 수 f64(원본 자바스크립트 수와 같게, 언리얼 5 의 큰 세계 좌표처럼 CPU 는 f64, GPU 는 f32): 엔진의 로직 셈을 모두 f64 로 한다. Vector2, Vector3, Quaternion, TransformMatrix, Rect, OBB, Pivot, Color 의 성분, base::math, 트윈과 감속, 타임라인, 액션, 애니메이터, 입자, 노드 변환과 UI 풀이, 카메라, 입력 좌표, 시간(경과 시간, time_delta), 소리의 음량과 재생 위치, 3D 변환과 뼈대 셈, 반사 값과 UIDocument 의 수가 f64 다. f32 는 원본이 Float32Array, Math.fround, WebAudio float 를 쓰는 자리에만 남는다: GPU 로 가는 정점, 인덱스, 유니폼 배열(Graphic 의 정점 버퍼, ToonMeshArrays, 툰 인스턴스 자료, 관절 행렬, 모프 무게), Matrix4 의 칸(원본처럼 f32 로 담고 칸마다 f64 로 셈한 뒤 f32 로 담는다), 소리 표본과 믹서와 AudioParam 값(크롬 WebAudio 의 float), 글리프 래스터와 Canvas2D 안쪽(스키아의 float), 그림 해독기, 색 관리. GPU 로는 그리기 함수가 정점 버퍼에 넣을 때와 유니폼을 올릴 때 f32 로 줄인다. f32 셈 때문에 원본과 갈리던 끝자리가 같아졌다. (타임라인 색 1 초가 원본과 같은 #80007fc0, UIDocument 왕복에서 0.2 가 0.20000000298023224 로 적히던 것, 흐린 그림자의 가우스 합이 원본처럼 f64) 초안 물리 월드의 advance 는 원본처럼 FixedStepper 를 들고 돈다. (지금까지는 같은 셈을 월드 안에 따로 두었다) FixedStepper::get_alpha 는 원본 Math.max(0, Math.min(1, 몫)) 과 같은 뜻이다. (-0 은 +0)
- 웹 질문 창과 웹 문맥 메뉴: 원본이 엔진 창과 엔진 메뉴로 바뀐 것에 맞춰 러스트 웹도 브라우저 window.alert, confirm, prompt 와 DOM 문맥 메뉴를 쓰지 않는다. 데스크탑과 같은 엔진 질문 창(크롬 탭 모달 꼴, 떠 있는 동안 씬과 async 작업이 멈춘다, Enter 확인, Escape 취소)과 엔진 문맥 메뉴(UIInputFieldContextMenu)를 캔버스에 그린다. prompt 입력 칸의 글은 원본처럼 숨긴 DOM 입력이 받는다(IME). 필드와 엔진 메뉴 위의 오른쪽 클릭은 브라우저 메뉴를 막는다. 브라우저 글은 navigator.languages 로 크로미엄 번역 82 로케일에서 고른다
- 반사를 빠뜨릴 수 없게(원본처럼 모든 컴포넌트가 반사된다): Reflect 를 Component 의 상위 트레이트로 두었다. 컴포넌트를 만드는 길은 #[vanilla::reflect] 하나이고, impl 블록과 impl Component 블록 어느 쪽을 빠뜨려도 컴파일 에러가 붙일 자리를 알려 준다. 엔진 안에서 빠져 있던 컴포넌트(초안의 RigidBody2D, Tilemap, AudioSource2D, AudioListener2D, Skeleton2DAnimator, UIInputFieldQuickMenu, 웹 pane 셋, 트리의 자리 지킴이)도 모두 붙였다. UI 문서는 등록하지 않은 모든 컴포넌트를 원본처럼 반사로 적고, 개발자 도구 인스펙터는 모든 컴포넌트의 게터를 보인다. ("반사 없음" 줄과 저장 키로 갈음하던 길, 반사 없는 컴포넌트를 빼던 경고는 없앴다) 초안 Tilemap 의 열거 다섯(배치, 엇갈리는 축과 줄, 그리는 차례와 방식)은 원본 글로 반사한다. 초안 다섯 종류의 UI 문서 저장 결과(키, 차례, 값)가 원본과 같음을 견줬다.
- GameScene 로딩과 터치 인식기(두 엔진 같게): 로딩 최소 시간은 두 엔진 모두 엔진 시계(get_realtime_since_startup)로 재고, 엔진 시계가 아직 돌지 않았으면(첫 프레임 전) 첫 로딩 화면 프레임부터 잰다. 로딩 화면 누름은 엔진 입력(is_touch_pressed)으로 draw_on_load 가 본다. TouchRecognizer 는 원본처럼 initialize 에서 만든다.
- 개발자 도구 메모리 칸(데스크탑): jsHeapSizeLimit 자리에 운영체제가 이 프로세스의 힙에 허락하는 상한을 적는다. (platform::desktop::read_heap_size_limit, 맥과 리눅스는 RLIMIT_DATA 가 정해져 있으면 그것 아니면 물리 메모리, 윈도우는 GlobalMemoryStatusEx 의 물리 메모리와 가상 주소 크기 가운데 작은 것) 두 엔진 모두 힙을 못 읽으면 셋 다, 한도만 못 읽으면 그 칸만 "(N/A)" 다.
- 데스크탑 Pane 의 canvas 태그: 원본 도구가 미리보기 엔진의 캔버스를 넣는 자리(uieditor, particleeditor 의 canvas 요소)에 렌더 타겟 화면을 그린다. 미리보기 장면을 렌더 타겟에 그려 PaneElement::set_canvas_texture 로 넣으면 그 요소의 안쪽 상자(calculate_canvas_box_size, 원본 canvas 의 clientWidth, clientHeight 자리)에 늘여 그린다. 같은 장면(바탕 rgb(16, 17, 20) 상자 안 canvas 에 위 왼쪽 바닐라색, 아래 오른쪽 빨강)을 크롬과 데스크탑으로 찍어 자리와 위아래, 색이 같음을 확인했다. 원본은 DOM canvas 그대로라 바뀐 것이 없다
- 투명도 층(CSS opacity 같은 묶음 투명도): Graphic 의 begin_opacity_layer, end_opacity_layer(원본 beginOpacityLayer, endOpacityLayer)가 그 사이에 그린 것을 화면 크기 칸에 모았다가 한 번에 지금 전역 알파로 얹는다. 노드는 set_opacity_layer(true)(원본 setOpacityLayer)를 켜고 투명도가 1 보다 작으면 그 노드와 자손을 층으로 그려, 겹친 자식끼리 비치지 않는다(크롬 CSS opacity 와 같다). 층 안의 자르기(Mask)도 그대로 되고 층은 겹쳐 열 수 있다. 두 엔진이 같다. 데스크탑 Pane 요소는 CSS opacity 를 읽어 이 층으로 그린다. 같은 장면(겹친 빨강, 파랑 상자를 opacity 0.5 로 묶음)을 크롬과 데스크탑으로 찍어 겹친 자리 색이 같음(19, 19, 146)을 확인했다
- 글리프 래스터(윈도우, 리눅스 데스크탑): 크롬처럼 칠한다. 윈도우는 DirectWrite 로 스키아 SkScalerContext_DW 와 같은 설정(ClearType 이 켜진 기계는 크롬이 글자를 LCD 로 두어 캔버스에서 kGenA8FromLCD 가 걸리므로 ClearType 3x1 텍스처의 세 채널 평균, 꺼졌으면 그레이스케일 A8, 격자 맞춤, gasp 표와 크기와 바이트코드 힌트와 비트맵 글꼴로 고른 렌더링 모드, 가짜 기울임은 글자 행렬)으로 칠하고, 대비와 감마는 크롬 158 처럼 주 화면의 Avalon.Graphics 레지스트리 키가 있을 때만 DirectWrite 렌더링 값, 없으면 대비 1, sRGB 로 전보정한다. 리눅스는 크롬 158 이 시스템 글꼴과 보통 웹 글꼴을 FreeType 이 아니라 스키아 Fontations(skrifa)로 그리는 것을 따라 skrifa 윤곽에 fontconfig 의 hintstyle 로 같은 힌팅(가볍게는 Light 에 glyf 자동 힌팅, 보통은 Normal 에 자동 힌팅 대체, 꼭 힌팅이 있어야 하는 글꼴은 Strong)을 걸고 감마 1.2, 대비 0.2 로 전보정한다. 두 운영체제 모두 맥처럼 1/4 픽셀 서브픽셀 자리를 쓴다. CI 가 글자 장면(examples/glyphparity.rs)을 같은 기계의 크롬 158 과 견준다
- 소리 스레드 우선순위(데스크탑): cpal 의 realtime 기능(audio_thread_priority, MPL-2.0)을 끄고, 출력 콜백 스레드의 첫 부름에서 크롬의 kRealtimeAudio 와 같은 것을 운영체제 API 로 건다(platform/audio/threadpriority.rs). 윈도우는 크롬 wasapi_render_thread 처럼 THREAD_PRIORITY_TIME_CRITICAL 과 MMCSS "Pro Audio"(AVRT_PRIORITY_CRITICAL, 스레드가 끝나면 되돌림, 전에는 "Audio"), 리눅스는 크롬 SetThreadTypeLinux 처럼 SCHED_RR 우선순위 8 이 안 되면 nice -10(전에는 dbus 기능이 없어 아무것도 하지 않았다), 맥은 CoreAudio IO 스레드가 이미 시간 제약 정책이라 그대로 두고 아닌 스레드에만 크롬 SetPriorityRealtimeAudio 의 셋(timeshare 0, importance 63, 버퍼 길이 주기의 시간 제약)을 건다. 의존에서 audio_thread_priority 가 빠졌다.
- 데스크탑 Engine::new 가 그래픽을 짓는다: 원본 Engine 생성자처럼 엔진을 만든 직후부터 get_graphic 이 있다. 주 스레드에서 이벤트 루프를 짓고 그 루프로 창을 숨긴 채 만들어 GL 컨텍스트와 Graphic 을 짓고, run 은 같은 창을 보이고(찍기 모드는 숨긴 채) 그대로 그린다. run 전에 지은 텍스처, 렌더 타겟, 셰이더가 그대로 쓰인다. GL 을 지을 수 없는 기계(화면 없는 CI)와 주 스레드가 아닌 곳(단위 시험)은 지금처럼 run 이 창을 열 때 짓는다
- JPEG 해독(데스크탑, 웹 판의 Image::load_from_memory 도): image 크레이트(zune-jpeg) 대신 엔진에 짠 해독기(core/jpegimage.rs)로 푼다. 크롬 158 의 libjpeg-turbo 3.1.0 과 블링크 JPEGImageDecoder 가 고르는 셈(JDCT_ISLOW 정수 역 DCT, 부드러운 크로마 늘리기 h2v1, h1v2, h2v2, jdcolor.c 의 16 비트 YCbCr 표, 성분 번호와 JFIF, Adobe 표시로 색 공간 가리기)을 따라 크롬 WebGL texImage2D 와 시험 그림 51 장(4:4:4, 4:2:2, 4:2:0, 4:4:0, 4:1:1, 섞인 비율, 프로그레시브, 재시작, 회색, RGB, CMYK, YCCK, ICC, EXIF 방향, 무손실, 1x1 ~ 33x18 의 작은 그림)이 비트까지 같다(전에는 최대 2~5 단계). 무손실(SOF3)을 새로 풀고, EXIF 방향을 크롬처럼 건다(6, 8 은 폭과 높이가 바뀐다). CMYK JPEG 의 CMYK ICC 프로필을 skcms 처럼 바꾼다. 크롬이 풀지 못하는 12 비트, 산술 부호, 회색과 YCbCr 무손실, 다 받지 못한 파일(자료가 잘림, EOI 가 없음, 남은 스캔이 없음)은 크기만 읽은 투명한 그림이다(크롬은 onload 뒤 WebGL texImage2D 가 INVALID_VALUE 로 올리지 않는다. 전에는 일부를 풀거나 실패). 다 받지 못한 파일을 크롬 Canvas2D 는 받은 데까지 그려 그것과는 다르다. SVG 안의 JPEG 과 마우스 포인터 그림의 JPEG 도 같은 해독기로 푼다. image 크레이트의 jpeg 기능을 껐다.
- 입력 필드 문맥 메뉴: 직접 누르는 필드(set_use_direct_touch)의 오른쪽 단추도 다른 필드와 같은 엔진 문맥 메뉴다. 두 엔진 모두 원본처럼 잘라내기, 복사, 붙여넣기에 모두 선택(글이 있을 때)을 더한 네 항목이고, 원본도 직접 누름 필드에서 브라우저 편집 칸 메뉴를 막는다. 데스크탑이 따로 그리던 크롬 편집 칸 메뉴(실행 취소, 다시 실행, 일반 텍스트로 붙여넣기, 그림 이모티콘, 쓰기 방향, 검사)는 지웠다. 손가락 길게 누르기의 빠른 메뉴는 그대로이고, 고른 것도 붙여 넣을 것도 없을 때와 "..." 는 엔진 문맥 메뉴다
- 여러 줄 입력 필드의 줄 나누기: 데스크탑과 웹 캔버스 모드가 같은 셈이다. 크롬 textarea 처럼 블링크 줄 나누기(LazyLineBreakIterator 의 빠른 표: 아스키 짝은 여는 괄호 앞과 '-', '?' 뒤에서만, '-' 뒤 숫자는 앞이 영숫자일 때만, 라틴 1 짝은 두 글자 ICU 값)에 ICU4X LineSegmenter 사전판을 normal 엄격도(작은 가나와 장음 부호 앞에서 나눔)로 쓴다. 크롬 158 의 textarea 에서 뜬 30 글(영어, 주소, 문장 부호, 한국어, 일본어, 중국어, 태국어, 러시아어, 라틴 1)의 나눔 자리가 모두 같다. (지금까지 데스크탑은 순수 UAX #14 strict 라 '/' 뒤와 작은 가나 앞이 크롬과 달랐고, 웹 캔버스 모드는 낱말 경계로 갈음했다) icu_segmenter 가 웹 의존에도 들어간다
- 컴포넌트 찾기: get_component, get_components, has_component, get_or_add_component, remove_component, NodeTree.with_component_mut 이 원본 instanceof 처럼 품은 기반 타입으로도 찾는다. Component::get_base_component(_mut) 가 품은 기반(원본 상위 클래스)을 알리고, ShaderSprite 는 Sprite 와 Paint 로, UIButton 은 UIControl 과 UIView 로, RichText 는 Text 로 찾힌다. (그 밖에 Sprite, UIControl, UIDraggable, UISlider, UIToggleButton, UIScrollView, UISnapScrollView, UIImageView, UIProgressView, UILabel)
dyn Component에 is_instance_of, as_instance_of(_mut) 을 둔다. - DevTools: 트리의 Type 칸과 인스펙터 type 이 원본 constructor.name 처럼 노드 종류 이름(FloatingText, UIWindow 같은)이다. UIDocument.get_node_type_name(node) 를 둔다. DevTools 가 처음 드는 문서에 register_editor_types 를 부른다.
- DevTools 인스펙터: 노드를 가리키는 속성 값(UIHitArea.targetNode 같은)이 원본 constructor.name 처럼 그 노드의 종류 이름([FloatingText], [UILabel] 같은)으로 보인다(지금까지 늘 [WorldNode]). 반사가 없는 컴포넌트의 문서 값도 수를 원본 toFixed 처럼 반올림한다(0.125 → 0.13).
- Action: 이름을 원본과 짝 맞췄다. 대상을 드는 꼴은 start(node_tree, Some(node_id)), step(node_tree, time_delta), get_target() 이고(원본 start(target), step(timeDelta), getTarget), start(node_tree, None) 이 원본 start() 처럼 이전 대상으로 다시 시작한다. 대상을 들지 않고 매번 넘기는 꼴은 start_with(&mut 대상), step_with(&mut 대상, time_delta) 이고 원본에도 같은 startWith(target), stepWith(target, timeDelta) 가 생겼다. repeat, forever, loop 의 안쪽 액션은 두 엔진 다 이 꼴로 돌아 대상을 들지 않는다.
- Animator.get_parameters(): 원본 getParameters 처럼 이름과 AnimatorParameter(Float, Int, Bool, Trigger) 목록을 처음 넣은 차례로 돌려준다. AnimatorParameter 를 공개한다.
- FloatingText: 라벨을 원본처럼 UILabel 로 그린다. (같은 설정: 글, 크기, 색, 굵게)
- FloatingText::create: 원본 생성자처럼 FloatingText 노드의 피벗과 앵커를 왼쪽 위로 둔다. spawn 의 월드 좌표가 부모 왼쪽 위 기준이라 원본과 같은 자리에 뜬다(지금까지는 앵커가 가운데라 부모 크기의 반만큼 밀렸다). 같은 설정으로 두 엔진을 찍어 화소 차이 0 을 봤다.
- JSON 쓰기: 엔진이 JSON 을 쓰는 길(LocalStorage.set_json, PersistedStore, UIDocument.to_json_text, WebSocketClient.send, DevTools 설정, 초안 세이브)이 모두 storagetext::stringify_json 하나로 원본 JSON.stringify 와 글자까지 같은 글을 쓴다. 수는 원본 String(수) 꼴(1.0 → 1, 1e21 → 1e+21, 1e16 → 10000000000000000), 객체 칸은 원본 JS 객체처럼 배열 번호 꼴 이름을 먼저 쓴다. 들여 쓴 꼴은 stringify_json_with_space(원본 JSON.stringify(값, null, space)), 글 따옴표는 quote_json_text 다. JSON 읽기는 serde_json 의 float_roundtrip 을 켜 원본 JSON.parse 처럼 가장 가까운 수로 읽는다(123456789012345680000 이 한 자리 어긋나던 것).
- TouchEffect: 입자 그라디언트를 원본처럼 엔진 Canvas2D 의 방사 그라디언트(create_radial_gradient, fill_rect)로 굽는다. 헤드리스 크롬의 같은 캔버스 코드와 64x64 알파가 모두 같다.
- PersistedStore: get_string_code_units(path), set_string_code_units(path, code_units) 로 상태 안 글을 JS 글 단위(UTF-16)로 읽고 쓴다. 원본이 저장한 짝 없는 서로게이트를 원본 글 그대로 받는다. (LocalStorage 의 *_code_units 와 같은 꼴)
- 셰이더 짓기 실패: ShaderSprite, ScreenEffect 가 짓기에 실패하면 원본도 러스트 판처럼 한 번 알리고 건너뛴다. (원본은 예외로 프레임이 멈췄다) 두 엔진이 같다.
- 대체 글꼴 고르기(데스크탑)를 크롬 FontCache::PlatformFallbackFontForCharacter 처럼: measureText 217 글이 맥 크롬 158(arm64, 로제타 x86_64), 윈도우 크롬 158, 리눅스 크롬 158 에서 모두 같다. (전에는 맥 144, 윈도우 181, 리눅스 216)
- 기본 글꼴 사슬(원본 SYSTEM_FONT_STRING)은 기본 글꼴 이름 default 를 청했을 때만 잇는다. "16px Arial" 처럼 다른 이름이면 사슬 없이 운영체제 대체로 간다. (원본도 기본 글꼴일 때만 폰트 문자열이 그 사슬이다)
- 대체는 첫 글꼴(빈칸을 가진 첫 얼굴)과 폰트 문자열마다 따로 묻고, 대체 얼굴은 운영체제가 그 얼굴을 고른 글자만 그린다. 굵게를 청하면 굵은 얼굴(Helvetica.ttc 의 Helvetica-Bold, GeezaPro-Bold, 윈도우 tahomabd.ttf)도 따로 읽고, 맥과 윈도우의 대체 얼굴은 글꼴 이름 표의 무리 이름으로 묶어 굵기를 고른다. (굵기마다 파일이 다른 Tahoma 도 굵게면 Tahoma Bold) 리눅스는 크롬처럼 굵기와 기울기 없이 fontconfig 에 묻고 고른 파일을 그대로 써 가짜 굵게, 가짜 기울임으로 그리며, 굵게나 기울임이면 첫 이름의 보통 얼굴부터 본다. (굵은 아랍어가 DejaVuSans.ttf 의 가짜 굵게)
- 이름 목록의 얼굴이 합친 글자(ï)가 없어도 정준 분해한 글자(i, U+0308)가 있으면 HarfBuzz 처럼 그 얼굴로 그린다. (third_party/rustybuzz 에 decompose_character 를 더했다)
- 맥: 첫 글꼴의 CTFont(올린 글꼴은 바이트로 지은 것)에서 CTFontCreateForString 을 묻고, 특성이나 굵기가 다르면 같은 이름에서 다시 고른다. (지금까지는 시스템 UI 글꼴에서 물어 아랍어가 다른 글꼴로 그려졌다)
- 윈도우: 굵게나 기울임이면 첫 이름의 보통 얼굴, 블링크 font_fallback_win.cc 의 블록과 문자별 표(태국어 Tahoma, monospace 아랍어 Courier New, 한자는 화면 언어), 넓은 글꼴 목록, 첫 이름을 바탕으로 한 DirectWrite 차례. (지금까지는 Segoe UI 바탕의 DirectWrite 만 물어 태국어가 Leelawadee UI 였다)
- 모든 글자가 U+00FF 이하인 글은 크롬(HarfBuzzShaper 의 8 비트 글)처럼 라틴 문자로 모양 짓는다. 숫자처럼 Common 뿐인 낱말도 글꼴의 latn 기능을 쓴다. (리눅스 Norasi 는 DFLT 에만 숫자 커닝이 있어 16px "0123456789" 가 3.8px 좁았다)
- 웹도 같게: 브라우저에 넘기는 글꼴 목록 끝의 원본 SYSTEM_FONT_STRING 을 default 를 청했을 때만 붙인다.
- AVIF 의 YUV 를 RGB 로 바꾸는 셈(데스크탑): 크롬 158 처럼(AVIFImageDecoder 가 부르는 CrabbyAvif crabby_avifImageYUVToRGB, libyuv 기능) libyuv 가 받는 꼴(BT.601, 미지정, BT.709, BT.2020 NCL, 크로마 NCL 행렬의 8, 10, 12 비트)은 libyuv 의 정수 셈(YuvPixel, YPixel, 두 배 크로마 늘리기)으로, 그 밖은 libavif 실수 셈(값마다 나눈 뒤 크로마를 섞는 차례로 고침)으로 바꾼다. 높은 비트 깊이는 크롬 WebGL 처럼 16 비트로 담아 libyuv HalfFloatPlane 이 가수를 자른 반정밀로 푼다. 알파는 곧은 알파로 푼 뒤 반올림으로 곱한다. 크롬 158 WebGL texImage2D 와 시험 그림 19 장이 비트까지 같다. (지금까지는 libavif 실수 셈이라 1~23 단계 달랐다) 그림 픽셀이 한두 단계 바뀐다
- FBX 재질 여럿: 메시 하나에 재질이 여럿인 FBX(LayerElementMaterial 의 Materials, MappingInformationType ByPolygon 이나 AllSame)를 폴리곤의 재질 번호대로 부분 메시로 나눠 재질마다 드로어블 하나로 그린다. (three.js FBXLoader 의 그룹, 유니티와 언리얼의 서브메시) 지금까지는 재질 번호를 폴리곤 순번이 아니라 폴리곤 정점 순번으로 찾았고, 메시마다 소유 노드의 첫 재질 하나로만 그려 Quaternius 마네킹(M_Main, M_Joints)이 온통 주황이었다. 새 SkinnedModel::split_fbx_corners_by_material 과 FbxCornerArrays, FBX MeshDescription 과 드로어블의 material_name 이 FBX Material 이름(glb 처럼), FbxMaterial.name. 원본과 같다. 단위 시험 multiple_materials_split_by_polygon, mannequin_fbx_materials_from_examples(원본과 같은 삼각형 수 5732, 8012). 문서 그림 model-viewer, 셰이더 해시를 바꾼 뒤의 effect-gallery, shader-sprite, screen-effect 다시 찍음(같은 크기, cwebp -q 85).
- SceneBase.set_touch_dispatch_enabled(is_enabled), is_touch_dispatch_enabled(): 원본 Scene.setTouchRaycaster(null)(와 새 setTouchDispatchEnabled) 처럼 씬 기본 터치 넘기기를 끈다. 끄면 tick_touch 가 노드에 누름, 이동, 뗌, 휠을 넘기지 않고(첫 터치 콜백도) 씬의 터치 훅만 불려 훅에서 가로채 직접 넘길 수 있다.
- SpriteAnimator.play: 원본 play 처럼 그 자리에서 Sprite 에 첫 프레임을 넣는 노드를 받는 꼴이 기본이다. SpriteAnimator::play(&mut node, clip_name, options) (옛 play_on_node). 애니메이터만 받던 옛 play(&mut self, ...) 는 play_clip 이고, 노드가 없을 때(완료 콜백 안) 쓴다. 완료 콜백 뒤에는 같은 tick 에 프레임을 넣어 바로 바뀐다.
- GamepadManager: get_all_connected_gamepads, get_connected_gamepad 가 원본 navigator.getGamepads() 처럼 부를 때 그 자리에서 읽는다(데스크탑은 gilrs 사건을 비워 지금 상태, 그 사이 연결과 해제는 다음 갱신이 받음, 웹은 navigator.getGamepads()). 읽기는 &self 이고 그 자리에서 읽은 사본(Vec
, Option )을 돌려준다. (원본처럼 그 순간의 사본) gilrs 는 처음 부를 때(갱신, 진동, 목록 읽기) 만들어 첫 tick 전 vibrate 도 데스크탑에서 떤다. update_all_gamepads_with_list 로 목록을 넣은 관리자는 넣은 목록을 돌려준다. - AudioPlayer 버리기: 플레이어를 버려도 트는 소리는 원본 WebAudio 소스 노드처럼 끝까지 운다. 데스크탑은 믹서가 소스가 끝날 때까지 플레이어 노드(와 그리로 내는 버스 노드)를 들고 끝나면 뺀다. 웹은 onended 를 스스로 풀리는 콜백으로 바꿔 소스가 끝까지 울고, 끝나면 GainNode 를 뗀다. 컨텍스트 재개를 기다리던 재생도 원본처럼 재개 뒤에 튼다. (지금까지는 버리면 소리가 멈췄다)
- 사인, 코사인, 탄젠트: math::sin, cos, tan 과 트윈 감속 함수(sinusoidal, elastic)가 시스템 libm 대신 크롬 Math.sin, cos, tan 과 같은 셈(바르게 반올림한 f64, src/base/trigonometry.rs, 2/π 비트 표 Payne-Hanek 줄이기와 두 배 정밀도 급수, fma 없이)을 하고 f32 로 담는다. 크롬 158 과 22,000 입력에서 sin, cos, tan 이 모두 같은 비트였다. (맥 시스템 libm 은 sin 896, tan 8,719 곳이 달랐다) 시스템 libm 은 맥, 윈도우, 리눅스, wasm 마다 끝자리가 달랐다. math::tan 은 sin / cos 가 아니라 바로 셈한다. 셈이 표준 함수보다 느리다(호출 한 번 0.5 마이크로초 안팎).
- 셰이더 해시: hash21(ScreenEffect, ShaderSprite)과 hashPoint(toon VFX)를 MurmurHash3 의 fmix32 마무리(Austin Appleby, 공개 도메인)로 float 비트를 섞는 정수 해시로 바꿨다. (원본과 같은 셈) 필름 입자, 글리치, 값 잡음, toon VFX 잡음의 무늬가 바뀐다
- 사람 피부 환경 BRDF: Karis 근사 대신 엔진이 분할 합 적분을 직접 셈해 맞춘 식을 쓴다. (원본과 같은 계수, 오차 실효값 0.071, 0.029 → 0.002, 0.006) 환경 반사가 바뀐다
- 그림(데스크탑): 박힌 색 프로필을 크롬처럼 sRGB 로 바꾼다. PNG 의 cICP, iCCP, sRGB, gAMA 와 cHRM, JPEG 의 APP2 ICC, WebP 의 ICCP, AVIF 의 colr(ICC, nclx 의 원색과 전달 특성, PQ, HLG). ICC 는 스키아의 러스트 해석기처럼 읽고(para, curv, mft1, mft2, mAB, mBA, cicp), 색 공간 고르기는 크롬 skia/ext/color_profile.cc 와 SkColorSpace, 바꾸기는 skcms 와 SkColorSpaceXformSteps 의 셈이다(core/colorprofile.rs, 새 직접 의존 png 0.18 은 image 가 이미 쓰는 같은 판). 크롬 158 의 WebGL texImage2D 와 PNG, WebP 시험 그림 31 장이 비트까지 같다. AVIF 는 YUV 를 RGB 로 바꾸는 셈(크롬은 libyuv) 때문에 한두 단계, 프로필이 붙으면 몇 단계 다르고 JPEG 은 해독기 차이로 한두 단계 다르다. 3D 재질은 원본 createImageBitmap(colorSpaceConversion "none")처럼 바꾸지 않는다. (지금까지는 색 프로필을 걸지 않았다)
- 움직이는 AVIF(데스크탑): 크롬(CrabbyAvif)처럼 주 상표 avis 면 트랙의 첫 장, avif 면 주 그림 항목을 풀고, 트랙만 있는 파일도 푼다. 크롬도 drawImage 와 texImage2D 에서 늘 첫 장을 써서(bitmap_image.cc ImageForDefaultFrame, image_extractor.cc) 움직이지 않는다. (지금까지는 avis 파일에서 주 그림 항목을 풀어 크롬과 다른 장이 나올 수 있었고, 트랙만 있는 파일은 풀지 못했다) nclx 전달 특성 9, 10, 11, 12 인 AVIF 는 크롬처럼 풀지 못한다
- 글자 자리(데스크탑): 크롬 HarfBuzz 처럼 글자 크기의 16.16 고정 소수 배율에서 셈한다. (블링크 HarfBuzzFace::GetScaledFont, SkiaScalarToHarfBuzzPosition) 글꼴 단위 값은 em_scale, 가변 GPOS 델타는 em_scalef 로 그 배율에서 반올림하고, 축 값은 HarfBuzz hb_ot_var_normalize_coords 처럼 16.16 으로 정규화해 avar 를 실수로 사상한 뒤 2.14 로 줄이며, trak 자간도 em_scalef_x 로 반올림한다. 맥 SFNS(system-ui) 8 ~ 128px, 굵기 300, 400, 700 과 기울임의 세 글 228 개 가운데 222 개가 크롬 158 measureText 와 끝자리까지 같고 나머지도 6.1e-5px 안이다. (지금까지는 굵기 300 128px 의 "AVATAR Type Wolf" 가 0.093px 까지 달랐다)
- rustybuzz 0.20.1 에 배율이 없어 Face::set_scale 과 HarfBuzz 식 축 값 정규화를 더한 판을 third_party/rustybuzz 에, 짝 커닝(PairPos 꼴 1)의 장치 표를 2 바이트 어긋나게 읽던 ttf-parser 0.25.1 을 바로잡은 판을 third_party/ttf-parser 에 두고 경로로 의존한다. git 으로 받는 게임도 그대로 따라온다. 새 크레이트는 없다
- 글꼴 고르기(데스크탑, 맥): 기울인 system-ui 와 BlinkMacSystemFont 가 크롬 MatchSystemUIFont 처럼 SF 기울임 글꼴(SFNSItalic)이다. (지금까지는 바른 SFNS 에 가짜 기울임이라 13px 에서 0.7px, 48px 에서 7.4px 좁았다)
- 글꼴 이름(데스크탑): 크롬처럼 따옴표 친 일반 이름('monospace', 'serif', 'system-ui' 같은)은 기본 글꼴 표로 바꾸지 않고 그 글자의 글꼴과 올린 얼굴(FontFace)을 찾는다. 맥에는 그 이름의 글꼴이 없어 다음 이름이나 표준 글꼴이고, 'system-ui' 는 맥 크롬 FontCache 처럼 시스템 UI 글꼴이다. 따옴표 없는 일반 이름은 올린 얼굴을 찾지 않는다. -webkit-body 는 표준 글꼴이고, 목록의 마지막 일반 이름이 -webkit-body 면 올린 얼굴이 없는 이름도 표준 글꼴이다. 맥은 BlinkMacSystemFont 를 이름 system-ui 로 올린 얼굴에서 찾는다. (블링크 style_builder_converter.cc ConvertFontFamily, css_font_selector.cc GetFontData, font_selector.cc FamilyNameFromSettings, 맥 크롬 158 에서 잰 24 글) 웹 판도 브라우저에 넘기는 font 글에 따옴표 친 일반 이름을 따옴표째 넘긴다. (지금까지는 따옴표를 떼어 일반 이름이 됐다)
- 데스크탑 글자의 위아래 길이(TextMetrics 의 font_ascent, font_descent, 글자 기준선 top, middle, bottom 자리)를 크롬 캔버스와 같게: 블링크 FontMetrics::AscentDescentWithHacks 처럼 운영체제의 세로 수치(리눅스 USE_TYPO_METRICS 면 typo 아니면 hhea, 맥 hhea, 윈도우 USE_TYPO_METRICS 가 아니면 OS/2 win 값)를 각각 반올림하고, 위가 3px 보다 작거나 위 + 아래가 2px 보다 작은 작은 글꼴만 반올림하지 않는다. (캔버스의 subpixel_ascent_descent) 맥은 Times, Helvetica, Courier 의 위 길이에 15% 를 더한다. (줄 높이 셈과 같은 표) 지금까지는 hhea 값을 반올림하지 않아 윈도우와 리눅스 크롬과 0.27px 까지, 윈도우 Consolas 는 3.1px 달랐다. (CI 의 윈도우, 리눅스 크롬 157 measureText 로 확인)
- 데스크탑 글꼴 고르기: 폰트 문자열의 이름 목록에서 얼굴을 하나도 찾지 못하면(깔리지 않은 이름, 리눅스의 cursive, fantasy 처럼 기본 글꼴이 없는 일반 이름) 크롬처럼 화면 언어의 표준 글꼴(-webkit-standard, 윈도우와 리눅스 영어는 Times New Roman)이 첫 글꼴이다. 지금까지는 기본 글꼴 사슬(원본 SYSTEM_FONT_STRING)의 sans-serif 가 먼저라 윈도우, 리눅스 크롬과 폭이 달랐다. 이름 default 는 그대로 기본 글꼴이다
- 데스크탑 비트맵 색 글꼴(노토 컬러 이모지 같은 CBDT): 전진폭을 크롬 리눅스(FreeType 과 스키아)처럼 판의 글리프 수치에 적힌 정수 전진폭을 글자 크기 비로 옮긴 값으로, 실제로 닿는 상자(actual_bounding_box_*)를 그림 상자를 옮겨 바깥 정수로 넓힌 값으로 셈한다. 지금까지는 hmtx 를 바로 옮겨 16px 이모지 하나가 크롬보다 0.04px 좁았고, 상자는 0 이었다. (colorglyph::read_bitmap_glyph_advance, read_bitmap_glyph_bounds, LoadedFont::is_bitmap_only_font)
- 데스크탑 이모지 얼굴 고르기를 크롬 FontFallbackIterator 차례로: 이름 목록의 얼굴은 색과 상관없이 글리프가 있으면 먼저 쓰고(리눅스 크롬 157 은 "16px DejaVu Sans" 의 맨 😀 를 흑백으로 그린다), 이형 선택자가 붙은 묶음(❤️)은 그 표시에 맞는 얼굴만 받으며, 운영체제 대체 글꼴 단계에서만 색 글리프 얼굴을 먼저 고른다. 지금까지는 목록 어디에서든 색 얼굴을 먼저 골랐다. FontFaceDescriptors 에 is_system_fallback(운영체제 대체 글꼴의 얼굴인지, 기본 false)을 더했다
- 리눅스 손가락 판정: X11 입력 장치 읽기(XIQueryVersion)를 스레드끼리 한 번에 하나로 묶는다. libXi 가 확장 정보 표를 잠그지 않고 만들어, 여러 스레드가 InputManager 를 만들면(시험) libXext 의 XextAddDisplay 에서 SIGSEGV 로 죽었다. (CI 리눅스에서 gdb 로 확인)
- 데스크탑 도형 가장자리: 창의 GL 설정에 멀티샘플 4 를 묻는다. (원본 WebGL 컨텍스트의 기본 antialias 를 크롬은 min(4, GL_MAX_SAMPLES) 표본의 MSAA 로 칠한다, 블링크 DrawingBuffer) 맥 CGL 은 묻지 않으면 멀티샘플 없는 설정만 주어 원, 둥근 사각형, 선의 가장자리가 계단이었다. 4 이상인 설정이 없으면 묻지 않고 다시 골라 4 에 가까운 것을 쓴다. 맥에서 같은 장면의 도형 가장자리 차이 화소가 1894 에서 897 로 줄었다 (남은 것은 표본 자리가 위아래로 뒤집힌 몫, ARCHITECTURE 10 장)
- 맥 데스크탑 글자 래스터를 크롬과 같게: 색이 아닌 모든 글리프를 크롬 맥 Canvas2D 와 같은 길로 CoreText 가 칠한다. (블링크 FontPlatformData::CreateSkFont 의 kSubpixelAntiAlias 와 서브픽셀 자리, 투명 캔버스의 kUnknown_SkPixelGeometry, 스키아 SkScalerContext_Mac 의 A8-from-LCD: 흰 바탕 RGB 에 글꼴 부드럽게를 켜고 칠한 뒤 CoreGraphics 감마 2 를 풀고 밝기를 감마 전보정 표로, 표는 크롬 맥의 sRGB 와 대비 0, 글꼴 부드럽게가 회색이면 글자 색에 1/2) 글리프 자리는 스키아처럼 x 에 1/8 을 더해 내리고 나머지를 1/4 픽셀 단위로 CoreText 에 넘긴다. 겹치는 글리프는 캔버스처럼 위에 얹는다 (큰 값을 고르던 것) 가짜 기울임은 CoreText 글자 행렬의 기울기로 그린다. 바이트로 올린 글꼴도 CoreText 로 짓는다. 맥에서 같은 장면(10 ~ 48px 글, serif, 굵게, 기울임, 한글, 이모지, 소수 자리, 흰 바탕과 어두운 바탕)의 글자 차이 화소가 59438 에서 0 이 되었다
- TextStringTextureCache: rasterize_text_with_color(글자 색을 알려 받는 래스터, 원본이 글 색 그대로 굽는 ShadowText 와 2D 캔버스 fillText 가 쓴다), textshaping::rasterize_glyph_at(서브픽셀 자리와 글자 색으로 글리프 래스터)
- Engine: 그래픽을 어디서나 쓴다. Graphic 을 EngineRunner 대신 Engine 이 들고, 원본 getGraphic 처럼 engine.get_graphic(), get_graphic_mut() 로 씬의 create, initialize, tick, 컴포넌트의 tick(context.get_engine()), async 작업의 첫 구간과 await 다음 줄에서 GL 자원(텍스처, 렌더 타겟, 셰이더 프로그램, 툰 렌더러 같은)을 짓는다. (지금까지는 그리기 함수에서만 graphic 인자로 받았다) 그리기 함수는 지금처럼 graphic 인자를 받는다. 엔진이 든 그래픽을 Option::take 로 잠깐 꺼내 넘긴 것이라 그 안에서는 engine.get_graphic() 이 None 이고 인자의 graphic 을 쓴다. (RefCell 도 unsafe 도 쓰지 않아 이중 빌림으로 터질 길이 없다) 그리기 밖에서 엔진과 그래픽을 함께 &mut 로 쓰려면 새 engine.with_graphic(|engine, graphic| ...) 이다
- EngineContext::with_graphic, SceneContext::with_graphic 이 맡기는 자리의 첫 구간에서도 그래픽을 준다. (지금까지 None) 그리기 함수 안에서 맡긴 작업의 첫 구간만 엔진이 그래픽을 그 함수에 내어 준 동안이라 None 이다
- DevTools: 모든 기즈모 강제 표시(원본 setForceGizmosVisible)를 tick 끝에 엔진의 그래픽에 건다. 원본처럼 F2 와 Settings 칸을 누른 그 프레임의 그리기부터 보인다. (지금까지는 post_draw 의 draw 에서 걸어 한 프레임 늦었다)
- 예제: toonstyle, toonmaterial 은 원본 생성자처럼 create 에서, oldface, modelviewer 는 애셋을 다 받은 뒤 initialize 에서 GL 자원을 짓는다. 가이드의 DynamicFont 예제도 원본처럼 initialize 에서 한 번 굽는다
- ToonRenderer::create_mesh: GL 버퍼나 버텍스 어레이를 짓다 실패하면 그때까지 지은 버퍼와 버텍스 어레이를 지우고 None 을 돌려준다. (지금까지는 앞서 지은 것이 남아 샜다) 인스턴스 버퍼와 함께 묶는 버텍스 어레이도 바깥선 쪽을 짓지 못하면 몸 쪽을 지운다. (원본은 크롬의 createBuffer, createVertexArray 가 늘 객체를 돌려줘 중간에 실패하는 길이 없다)
- FbxLoader: 노드(Model)와 애니메이션 스택 name 에서 바이너리 FBX 의 종류 꼬리("\u{0}\u{1}Model", "\u{0}\u{1}AnimStack")를 뗀다. 클립 이름은 "Take 001\u{0}\u{1}AnimStack" 이 아니라 "Take 001", 본 이름은 "mixamorig:Hips" 다. (three.js FBXLoader 는 BinaryReader.getString 이 첫 널 바이트에서 자르고, Assimp 는 "AnimStack::Take 001" 로 바꾼 뒤 FBXConverter 가 "AnimStack::", "Model::" 를 뗀다, 원본도 같이 바꿨다) glTF 로 읽은 모델에 FBX 애니메이션을 더할 때(add_animations_from_fbx_*)의 본 이름 맞추기도 이 이름으로 맞는다.
- tools/apidoc: pub mod 사슬로 밖에서 닿는 묶음 모듈(아래 모듈을 둔 모듈, vanilla::experimental, experimental::tilemap 같은)은 아이템이 없어도 모듈 설명과 예제를 자료에 둔다. (원본 자료의 experimental/experimental 자리, 크레이트 뿌리 lib.rs 는 원본처럼 두지 않는다) 묶음 모듈은 예제 없는 모듈로 세지 않는다. 초안 예제 코드(물리 2D, 세이브 슬롯, pannermath)의 한글을 걷었다.
- 폴더: 원본 vanilla.js 가 src/experimental 에 있던 다 자란 기능을 제자리로 옮겨, 두 엔진의 폴더가 같아졌다. 러스트 판은 이미 이 자리였고 모듈 경로(vanilla::graphics3d 같은)는 그대로다. 원본에서 import.js 로 쓰던 게임은 그대로, 파일 경로로 직접 import 하던 게임은 새 경로로 바꾼다. 파일 머리 주석과 ARCHITECTURE 9장의 원본 경로를 새 경로로 고쳤다. (원본의 옛 경로 → 새 경로)
- src/experimental/graphics/.js (3D) → src/graphics3d/.js (러스트 graphics3d/)
- src/experimental/graphics/toon/.js (툰 3D) → src/graphics3d/toon/.js (러스트 graphics3d/toon/)
- src/experimental/graphics/fullscreenpass.js → src/core/fullscreenpass.js (러스트 core/fullscreenpass.rs)
- src/experimental/animation/animator.js, timeline.js, src/experimental/action.js → src/animation/ (러스트 animation/)
- src/experimental/indicator.js, visual/visual.js → src/misc/ (러스트 misc/)
- src/experimental/bunchasset.js, visual/visualasset.js → src/resource/ (러스트 resource/)
- src/experimental/collection/.js → src/base/collection/.js (러스트는 표준 Vec, HashMap 같은 것이 맡아 없다)
- src/experimental/camera.js → src/deprecated/camera.js (원본도 폐기 예정, 러스트는 Camera2D 가 덮어 없다)
- src/experimental/aabb.js, transform2d.js, graphics/gl2d.js, graphics/webgl2.js (죽은 코드) → src/deprecated/ (러스트에는 없다)
- UIInputField 낱말 이동과 지우기: 원본처럼 윈도우와 리눅스는 Ctrl, 맥은 Option 과 왼쪽, 오른쪽(Shift 와 함께면 고르기를 넓힌다), Backspace, Delete 로 낱말 단위로 옮기고 지운다. (맥은 키 묶음의 Option + Ctrl + Backspace, B, F 도) 자리는 블링크 NextWordPosition, PreviousWordPosition 대로, 오른쪽은 윈도우만 다음 낱말 앞(맥과 리눅스는 지금 낱말 끝), 맥은 넓히던 고르기가 고정 끝을 넘지 않고, 여러 줄은 크롬 textarea 처럼 글자가 있는 줄 앞에서 앞 줄로 넘지 않는다. 고른 것이 있으면 고른 것만 따로 한 되돌리기 묶음으로 지우고, 낱말 지우기는 새 묶음을 열어 뒤따른 지우기와 글자 넣기가 붙는다. (헤드리스 크롬 158 textarea 에서 잰 2309 자리와 같다)
- TextInputKey 에 WordLeft, WordRight, DeleteWordBackward, DeleteWordForward 를 더했다. TextEditKind 에 DeleteWordBackward, DeleteWordForward 를 더했다. (TextInputKey, TextEditKind 를 빠짐없이 match 하는 코드는 새 갈래를 넣는다)
- core::textinput 에 collect_word_boundaries, find_next_word_position, find_previous_word_position 를 더했다. 낱말 경계는 크롬처럼 마침표를 숫자 사이에서만 잇고 쌍점은 잇지 않는다. (크로미엄 ICU wordbrk.patch) 데스크탑 두 번 누르기 낱말 고르기도 이 경계를 쓴다. ("www.example.com" 을 두 번 누르면 전에는 통째로, 이제 크롬처럼 누른 조각만)
- Text 줄바꿈 낱말 나누기(데스크탑): 크롬의 ICU 처럼 마침표(숫자 사이 빼고)와 쌍점에서 나눈다. ("www.example.com" 이 한 덩이라 줄을 못 넘기던 것, 크롬에서 원본 splitWords 로 잰 값과 같다, 웹은 브라우저가 나눈다)
- Platform::get_safe_area_rect: 너비와 높이를 0 이상으로 자른다. area_size 는 CSS 픽셀 크기다. (원본 getSafeAreaRect 를 CSS 픽셀로 고친 것과 같다)
- UIDocument: 등록하지 않은 노드 종류를 읽으면 WorldNode 로 읽고 경고를 낸다. (컴포넌트처럼, 원본도 같이) 원본에 registerEditorTypes 와 다시 읽을 때 생성자가 만든 것에 채우기가 생겨 두 엔진의 문서 읽기가 같다
- Color: to_rgba_string, to_hex_string 이 성분을 0 ~ 255, rgba 의 알파를 0 ~ 1 로 잘라 적는다. (원본 toByteComponent 와 같게, 전에는 1.5 가 "17f" 였다) 담는 성분은 원본처럼 자르지 않는다. (HDR 색) create_from_rgba 는 원본 createFromRGBA 의 정규식과 같은 것을 읽는다. (rgb 로 시작, 정수 r, g, b, 알파는 parseFloat 처럼, ")(" 처럼 괄호가 뒤집힌 글에서 패닉하던 것도 고쳤다)
- RenderTarget::new, resize: 중간에 GL 객체를 못 만들면 그때까지 지은 것을 지우고 크기를 0 으로 둔다. (새던 것)
- Graphic.draw_polyline, draw_line, draw_line_loop, draw_convex_polygon: 정점 버퍼가 차면 쌓인 것을 그리고 이어 적는다. 전에는 683 번째 선분(볼록 다각형은 1366 번째 삼각형)부터 버렸다.
- AudioPlayer.get_time: 재생 중에 오디오 컨텍스트 시계(웹 currentTime, 데스크탑 믹서 시계)로 흐른다. 재생 빠르기를 곱하고, 루프면 길이로 되감고, 아니면 길이에서 멈춘다. 멈췄거나 끝났으면 set_time 의 시작 위치다. (원본과 같게)
- 웹: 키, 마우스, 손가락, 페이지 사건이 프레임 안에서 다시 들어와도(게임 코드의 dispatchEvent, focus() 같은 것) 멈추지 않는다. 전에는 keydown, keyup, blur 가 RefCell 을 또 빌려 wasm 이 unreachable 로 멈췄고, 마우스, 손가락, 페이지 사건은 그 사건을 버렸다(mouseup 을 버리면 단추가 눌린 채 남았다). 바로 빌릴 수 있으면 그 자리에서, 못 빌리면 줄에 쌓았다가 프레임 콜백 끝에 온 차례대로 처리한다. (platform/eventqueue.rs)
- 웹: EngineConfiguration.title 이 비어 있지 않고 기본값("바닐라엔진", 데스크탑 창 제목)이 아니면 원본처럼 시작할 때 문서 제목(document.title)에 쓴다.
- ParticleSystem.apply_description: 서술의 imageDataUrl(파티클 편집기가 고른 그림의 data: 주소)을 읽어 입자 이미지로 건다. 데스크탑은 그 자리에서 풀고, 웹은 브라우저가 다 풀면 그린다. (null 이나 빈 글이면 그림을 뗀다)
- FontAsset.load(engine, asset_path): 새로 더했다. 원본 load 처럼 파일 이름에서 확장자를 뗀 것을 패밀리 이름으로 load_font 한다.
- JsonAsset.load: 돌려준 손잡이를 await 하면 JSON 해석이 실패해도 실패로 끝난다. (원본 JsonAsset.load 의 거부, 받기 실패는 전에도 실패였다) 옮기는 법: 해석 실패에도 Ok 로 끝난다고 보던 코드는 Err 를 받는다. await 하지 않고 is_finished 와 get_data 로 보는 쪽(SpriteAtlas 등)은 그대로다.
- UISnapScrollView: set_snap_to_nearest, set_velocity_threshold 가 값만 들고 스냅 계산에 쓰이지 않았다. (원본도 같았다) 이제 한 칸 모드(기본)는 놓을 때 드래그 속도가 set_velocity_threshold(기본 200, 오프셋의 초당 픽셀) 이상이면 끈 거리와 상관없이 속도 방향으로 한 칸 넘기고, 아니면 지금처럼 set_page_change_threshold 비율로 정한다. set_snap_to_nearest(true) 는 끄는 동안 칸 범위를 자르지 않고, 놓으면 가장 가까운 칸으로 간다. get_drag_velocity() 를 더했다. (원본 getDragVelocity, 인스펙터 기대값 inspector_getters.json 에도 더함)
- UILineChart: set_max_sample_count 로 상한을 줄이면 이미 든 표본을 오래된 것부터 버린다. (원본과 같게 고침)
- DevTools: Settings 의 Show FPS 를 켜면 패널을 닫아도 창 왼쪽 위에 "FPS 값" 상자를 그린다. (원본과 같게, canvas native 좌표, 패널이 보이면 패널 위에)
- UIInputField 커서와 지우기: 원본처럼 왼쪽, 오른쪽 화살표와 Delete 는 글자 묶음(확장 자소 묶음) 단위, 뒤로 지우기는 블링크 BackspaceStateMachine(코드 포인트 하나, 이모지 묶음과 CR LF 는 통째로)이다. 선택이 있을 때 Shift 없는 화살표는 선택의 앞, 뒤로 접는다. 누른 자리는 글자 묶음 경계에만 선다. (core/textinput.rs 의 find_previous_grapheme_boundary, find_next_grapheme_boundary, collect_grapheme_boundaries, find_backward_deletion_boundary, TextEditBuffer::delete_range)
- UIInputField 최대 길이: 넣기는 블링크 입력 칸처럼 넣는 글을 남은 UTF-16 길이까지만 넣는다. (전에는 값 전체를 잘랐다)
- UIInputField 여러 줄과 Pane 의 line-height normal: 글꼴 크기의 1.2 배 대신 크롬 SimpleFontData 처럼 첫째 글꼴의 위아래 길이와 줄 사이를 반올림해 더한다. (리눅스는 USE_TYPO_METRICS 면 typo 아니면 hhea, 맥은 hhea 와 Times, Helvetica, Courier 의 15% 보정, 윈도우는 DirectWrite 의 win 값. 웹은 브라우저가 놓은 줄 높이) textstringtexturecache::measure_normal_line_height_without_graphic, LoadedFont::calculate_normal_line_height 추가.
- 맥 키 묶음: Home, End 는 크롬 맥처럼 커서를 두고 처음과 끝으로 넘기고(넘길 것이 없으면 줄 앞과 끝), Shift 와 함께면 글 앞과 끝까지 고른다. PageUp, PageDown 은 커서를 두고 한 화면만큼 넘기고(Option 과 함께면 옮기기, Shift 와 함께면 고르기), Ctrl + 왼쪽, 오른쪽은 줄 앞과 끝이다. TextInputKey 에 ScrollToDocumentStart, ScrollToDocumentEnd, ScrollPageUp, ScrollPageDown 을 더했다. (TextInputKey 를 match 하는 코드는 새 갈래를 넣는다)
- UIInputField 두 번, 세 번 누르기: DOM 입력을 흉내 내는 필드(use_dom_input, 여러 줄)는 크롬처럼 마우스로 두 번 누르면 낱말(윈도우는 뒤 공백까지), 세 번 누르면 문단을 고르고 끌면 그 단위로 넓힌다. 이어 누르기는 크롬 aura 처럼 500ms(맥은 NSEvent.doubleClickInterval) 안, 가로 세로 2 DIP 안이다. 웹은 mousedown 의 detail 이다. (TextInput::set_pointer_click_count, get_pointer_click_count, systemfont::read_double_click_seconds 추가)
- Pane(데스크탑): flex-wrap(wrap, wrap-reverse), flex-flow, align-content, row-gap, column-gap(gap 의 두 값), white-space 와 text-overflow: ellipsis 를 읽는다. 줄넘김은 CSS Flexbox 9.3, 9.4 대로 줄을 모으고 align-content: stretch 로 늘인다. (헤드리스 크롬과 같은 자리) 블록 안의 높이 auto 줄넘김 flex 는 그 폭에서 모은 줄 높이다.
- Pane(데스크탑)과 여러 줄 UIInputField 의 스크롤 막대: 크롬처럼 윈도우, 리눅스는 자리를 차지하는 Fluent 막대(두께 15, thin 10, 단추 18, 썸 9), 맥은 시스템 설정(NSScroller.preferredScrollerStyle)이 얹는 막대면 얹는 썸, 클래식이면 자리를 차지하는 막대(두께 15, thin 11)다. scrollbar-width 와 scrollbar-color 의 길 색을 읽는다. (web/pane.rs 의 read_classic_scrollbar_metrics, calculate_classic_thumb_span, systemfont::is_overlay_scrollbar_preferred 추가)
- Animator: 원본처럼 정석 상태 기계로 완성. AnimationState 에 set_speed, get_speed, set_loop(Option, None 이면 클립을 따름), is_loop, get_duration, get_normalized_time, get_frame_index. AnimationTransition 에 set_exit_time, get_exit_time, set_duration, get_duration, set_can_transition_to_self, can_transition_to_self, add_condition(이름, AnimationConditionMode, 기준 값), get_conditions, is_exit_time_reached, from 이 None 이면 어느 상태에서나(Any State). 새 AnimationConditionMode, AnimationCondition(lib.rs 에서도 내보냄). Animator 에 set_float, get_float, set_integer, get_integer, set_bool, get_bool, set_trigger, reset_trigger, get_trigger, play, find_transition, start_transition, is_condition_satisfied, get_current_state_index, get_current_normalized_time, get_current_frame, is_in_transition, get_next_state_index, get_next_normalized_time, get_next_frame, get_transition_weight. 같은 시나리오에서 원본과 같은 상태 차례, 가중치, 프레임을 낸다. 옮기는 법: set_property, get_property, get_properties(serde_json::Value)는 없어졌다. set_float, set_integer, set_bool, set_trigger 와 그 게터로 바꾼다. get_animation, get_animation_mut(안의 Animation)도 없어졌다. AnimationTransition 은 조건 목록을 들어 이제 Copy 가 아니다.
- Visual: set_document_text, get_document_text, create_node(UIDocument, 노드 트리) 추가. 문서로 새 노드 트리를 지어 뿌리의 로컬 위치를 location 으로 둔다. (문서가 없으면 Ok(None), 꼴이 틀리면 Err)
- SkinnedModel: 애니메이션 FBX 에 채널이 있는 스택이 여럿이면 스택마다 "클립 이름/스택 이름" 클립이 된다. (원본과 같이 고침, 전에는 모두 같은 이름이라 play_animation 이 마지막 것만 틀었다)
- Timeline: 공개 함수 인자에 쓰이던 핸들러 꼴 별칭 TimelineEventHandler, TimelineMarkerHandler, TimelineCompleteHandler, TimelineTargetResolver 를 공개하고 lib.rs 에서 내보냄. TIMELINE_EASING_NAMES 문서의 이름 꼴을 실제와 같게 "<종류>.<in|out|inOut>" 로.
- ImageTextureCache::get_texture: 픽셀 길이가 너비x높이x4 가 아닌 그림은 GL 에 넘기지 않는다. 다른 캐시가 올리며 픽셀을 놓은 그림은 그 텍스처에서 되읽어 올리고, 되읽지도 못하면 올리지 않고 None 이다. (빈 배열을 너비, 높이와 함께 tex_image_2d 에 넘겨 GL 이 배열 밖을 읽던 것)
- Image::create_from_premultiplied_pixels, Image::create_from_pixels: 픽셀 길이가 너비x높이x4 가 아니면 패닉한다. (원본 ImageData 가 길이가 틀리면 예외를 던지는 것과 같다)
- BloomEffect: new 와 set_use_float_color 가 중간에 실패하면 먼저 지은 패스와 렌더 타겟을 지운다. set_use_float_color 실패는 예전 판을 그대로 둔다. (GL 객체가 새던 것)
- NodeTree::add_component: 원본 addComponent 처럼 의존 컴포넌트(require)가 노드에 없으면 같은 길(attach, attach_to_tree)로 먼저 붙인다. 지금까지는 WorldNode::add_component 만 붙였다
- TextStringTextureCache: unregister_font_face, set_font_face_order, get_font_face_count, watch_unresolved_family_characters, take_unresolved_family_characters 도 register_font_face 처럼 이름의 감싼 따옴표를 떼고 찾는다. (따옴표째 올린 이름을 못 찾던 것)
- ScreenEffect::destroy, HeatHazeEffect::destroy: graphic 을 받지 않는다. (원본 destroy() 와 같다) 처음 GL 자원을 만들 때 컨텍스트의 약한 손잡이를 쥐어, destroy 와 버려질 때(Drop, 노드를 지우거나 씬을 내릴 때) 스스로 GL 자원을 푼다. 옮기는 법:
screen_effect.destroy(graphic)→screen_effect.destroy(), 씬을 내릴 때 부르지 않아도 풀린다. (공개 API 가 바뀐다) ScreenEffect 가 렌더 대상을 짓다 중간에 실패하면 먼저 지은 것을 지운다 - 이름을 러스트 규칙(Rust API Guidelines C-CASE)으로 바꿨다. 함수, 메서드, 변수, 필드, 모듈은 snake_case, 열거 값은 UpperCamelCase, 연관 상수는 SCREAMING_SNAKE_CASE. (setFillColor → set_fill_color, Colors::white → Colors::WHITE, Pivot::topLeft → Pivot::TOP_LEFT, ButtonState::normal → ButtonState::Normal) 이름 경고를 끄던 #![allow(non_snake_case)] 등을 lib.rs 와 예제에서 뺐다. 엔진을 쓰는 코드는 같은 규칙으로 이름을 바꿔야 한다. (공개 API 를 바꾸는 일이다) 바꾼 곳 11,071 군데, 동작은 같다. (cargo test 252 통과, 데스크탑과 웹 빌드 경고 0, 예제 화면이 전과 같음)
- README: macOS(애플 실리콘) 데스크탑에서 확인함을 적었다
- 외계행성 광부 키우기가 게임 쪽에 따로 만들어 쓰던 범용 기능을 엔진으로 옮긴다. (vanilla.js 에 먼저 넣은 것과 같은 기능, 게임의 콘텐츠 구현은 가져오지 않는다)
- Outline: 테만 그리는 컴포넌트. 둥근 네모 테(set_round_size) 또는 동그라미 테(set_circle), 선은 내용 크기 안쪽에 들어온다
- UIProgressRing: 노드 꼴을 따라 위 가운데에서 시계 방향으로 채우는 진행 고리. 둘레의 점은 크기가 바뀔 때만 셈한다
- SoftShade, SoftShadeShape: 띠(Band) 또는 바닥(Bottom) 그라데이션을 작은 그림에 구워 내용 크기로 늘려 그리는 부드러운 그늘
- FrameProbe: 처음 몇 초의 프레임 간격으로 처지는 기기를 가린다. (목표 간격의 1.4 배를 넘긴 프레임이 25% 이상, 90 Hz 의 한 장 걸러 그리기는 처진 것이 아니다)
- InputManager: 마우스 단추 셋(MouseButton::Left, Middle, Right)의 눌림과 이번 프레임의 누름과 뗌(is_mouse_button_down, is_mouse_button_just_pressed, is_mouse_button_just_released), 닿아 있는 손가락 목록(get_touch_points, TouchPoint), 마지막 입력이 손가락인지(is_touch_input), 휠을 Ctrl 과 함께 굴렸는지(is_wheel_with_ctrl)
- 웹: 마우스(누름, 움직임, 뗌, 휠)와 손가락(touchstart, touchmove, touchend, touchcancel)을 엔진 입력에 넣는다. 지금까지 웹 빌드는 캔버스의 누름을 엔진에 넘기지 않아, 웹에서는 UIButton 같은 위젯이 눌리지 않았다. 왼쪽 단추와 첫 손가락은 터치로 넘기고, 손가락을 뗀 바로 뒤 브라우저가 흉내 내 보내는 마우스 사건은 무시한다. 캔버스 위 손가락의 스크롤과 확대, 오른쪽 클릭 메뉴, 휠의 페이지 스크롤을 막는다
- 데스크탑: 가운데와 오른쪽 단추, 손가락(winit Touch)을 입력 매니저에 넣는다. 휠의 Ctrl 을 적는다
- CameraGestures: 카메라 손짓. 오른쪽 끌기(가로는 돌리기, 캔버스 너비가 한 바퀴, 세로는 기울이기, 끌지 않고 떼면 오른쪽 클릭), 가운데 끌기(밀기), 두 손가락(밀기, 오므려 키우기, 문턱을 넘게 비틀면 돌리기). 매 프레임 update(input_manager, view_manager) 로 읽고 take_pan, take_rotation, take_tilt, take_zoom 으로 꺼낸다
- PointerCursor, CursorValue: 마우스 커서. 엔진이 하나 들고(get_pointer_cursor_mut) 켜면 프레임 끝마다 커서를 정한다. UIButton 위(누르는 중 포함)면 단추의 커서, 아니면 set_screen_cursor 의 커서. 데스크탑은 winit 커서 아이콘, 웹은 캔버스 cursor 스타일(register_image_cursor 의 그림 커서 포함). 꺼져 있으면(기본) 지금까지와 같다
- Engine: is_coarse_pointer() (웹은 CSS pointer: coarse, 데스크탑은 처음엔 false 였고 뒤에 윈도우와 리눅스는 장치를 읽어 정한다). 플랫폼 층에 set_cursor, is_coarse_pointer 를 더했다
- UIHitArea: 누르는 자리 넓히기. UIHitArea::attach(node_tree, button_id, minimum_size) 로 단추 바로 뒤 형제로 투명한 누름 자리를 두어 가로세로를 minimum_size 이상으로 넓힌다. 넓힌 몫의 클릭은 단추의 Clicked, Click 알림을 부른다. 단추의 자리, 크기, 피봇을 프레임마다 따라가고, set_clip_node 로 넓힌 몫을 창이나 스크롤 칸 안으로 자른다. (부모가 돌아 있어도 노드 좌표로 바꿔 자른다)
- UIButton: fire_click_events(context). 누르지 않고 클릭 알림(Clicked, Click)만 부른다
- ToastMotion, ToastPhase, read_toast_seconds: 알림 노드에 붙이는 나옴과 사라짐 모션. show(text, seconds) 로 바깥쪽(위나 아래)에서 미끄러져 들어오며 살짝 커졌다 돌아오고, 머문 뒤 떠오르며 사라진다. 떠 있는 동안 다른 글이 오면 앞 것이 빨리 비키고, 같은 글이 또 오면 시간만 다시 채우고 통 튄다. show 는 요청만 받고 다음 tick 에서 움직이며, 글은 set_apply_text_handler 로 건 함수가 노드에 넣는다. 숨은 동안 노드는 보이지 않게만 한다
- ButtonMotion, ButtonMotionStyle, ButtonMotionArea, set_button_motion_area, shake_button: 단추 반응. Normal 꼴은 올리면 커지고 누르는 동안 줄고 떼면 통 튄다. Inset 꼴(창 안)은 커지지 않고, 올린 동안 바탕 Paint 를 밝히고 안쪽에 흰 테를 그린다. 꼴은 단추마다(set_style) 또는 위 노드에 set_button_motion_area 로 건다. 피봇을 읽어 가운데를 두고 키운다. 스크롤 칸 안 단추도 누르는 동안 줄인다. 손가락 기기는 올림을 쓰지 않는다. 반응이 없을 때는 노드를 건드리지 않는다. 꾸밈이 제 모양으로 밝히게 하려면 set_lit_handler
- ShaderWarmer, ShaderWarmerSource: 셰이더 미리 링크. 켤 때 같은 소스를 KHR_parallel_shader_compile 로 뒤에서 링크해 드라이버(웹은 브라우저)의 프로그램 캐시에 남겨, 나중에 ShaderProgram 이 같은 소스를 지을 때 멈추지 않게 한다. 확장이 없으면 아무것도 하지 않는다. 매 프레임 update(gl), is_finished, is_supported
- ShaderProgram 을 크레이트 맨 위에서 내보낸다
- 툰 3D(graphics3d/toon): 점토 같은 한 색 재질과 바깥선. (외계행성 광부 키우기의 판 3D 에서 범용 몫만)
- MeshBuilder, ToonGeometry, ToonPartOptions, ToonQuad, ToonMeshArrays: 상자, 둥근 상자, 원기둥과 원뿔, 구, 회전체, 캡슐, 고리, 팔면체(create_*_geometry)를 자리, 돌림, 크기(create_part_matrix)를 곱해 한 덩어리로 담는다. 꼭짓점은 자리 3, 노멀 3, 색 3(sRGB), 재질 2(빛남, 빛을 받지 않음), 무늬 4(번호와 색, 뜻은 셰이더가 정함). 바깥선은 같은 자리의 점끼리 함께, 모서리에서 너무 튀지 않게 민 껍데기(inverted hull)이고, 밀다 접혀 뒤집힌 면은 뺀다. 감기는 노멀을 보고 바깥이 앞면이 되게 맞춘다. 면으로 지은 지형은 add_quad, add_quad_shell
- read_glb_arrays, read_glb_node_arrays, read_glb_node_infos, write_skin_pose, read_animation_swing, ToonOutlineOptions, ToonSkeleton: 텍스처 없이 재질 색으로 칠하는 GLB 를 배열로 읽는다. baseColorFactor 는 sRGB 로, emissiveFactor 는 빛남으로, 재질 extras 의 outline(껍데기)과 basic(빛을 받지 않음). 바깥선 설정을 주면 ".outline" 짝이 있는 노드(또는 added_parts)의 몸으로 껍데기를 새로 짓는다. 뼈대와 움직임(extras 의 loop "once" 포함)을 읽고 한 순간의 본 행렬을 셈한다. (앞 움직임과 섞기, 흔들림 배율) 엔진의 SkinnedModel(텍스처 PBR)과는 따로다
- ToonRenderer, ToonMesh, ToonDrawOptions: 해와 하늘색, 땅색 바탕빛, set_band_count 로 셀 셰이딩, 빛남과 빛을 받지 않음, 틴트와 불투명도, 바깥선 껍데기를 뒷면으로 그린다. 뼈대는 96 개까지. (SkinnedModelRenderer 와 같다) begin_frame 이 앞의 그리기 상태를 적고 end_frame 이 돌려, 2D 그리기 사이(flush_batch 뒤, restore_render_state 앞)에 끼운다. read_program_sources 를 ShaderWarmer 에 넘길 수 있다
- ToonPostProcess: HDR 마무리. 반정밀 실수 렌더 타겟에 그린 씬을 BloomEffect 로 밝은 곳을 번지게 하고, 노출과 ACES 근사 톤매핑과 sRGB 감마로 화면에 낸다. (begin, end, set_exposure, set_bloom)
- SoundSystem, SoundRow: 소리 표로 다루는 배경음악과 효과음. 녹음 무리에서 바로 앞과 다른 것 고르기, 같은 소리를 다시 낼 수 있는 간격, 같은 소리와 전체의 동시 수 제한(넘으면 오래된 것을 끊음), 음 높이 흔들기, 앞 몇 초만 틀고 줄여 끄기, 배경음악 겹쳐 바꾸기와 멈춘 자리에서 잇기, 음악 크기와 음악의 비와 효과음 크기. 음소거는 사용자, 페이지 가려짐(set_page_hidden), 바깥(set_external_mute_provider) 가운데 하나라도 맞으면 건다. load_sounds(engine) 로 애셋 폴더에서 받고, add_sound_asset 으로 메모리의 소리를 더한다. 매 프레임 update(time_delta)
- 오디오 백엔드의 모듈 별칭 audioBackend 를 audio_backend 로 (이름 규칙)
- Localization: 언어 태그를 뒤 조각부터 하나씩 떼며 맞추고(zh-Hant-TW → zh-hant → zh, 밑줄은 하이픈) set_language_aliases 의 별칭도 본다. 오른쪽에서 왼쪽으로 쓰는 언어(is_right_to_left, set_right_to_left, 처음은 ar, fa, he, ur, ps, yi, dv), 넣는 값을 방향 격리 문자로 묶기(isolate_text), 이름 자리 채우기(text_named, 빗금으로만 이은 값들은 통째로 한 번 묶는다). (vanilla.js 의 LanguagePack 가운데 엔진 몫만, 목록 파일 읽기와 탭 제목과 글꼴 연결은 게임 틀 몫이라 옮기지 않았다)
- ShadowText: 그림자를 깐 한 줄 글. 그림자 위에 글을 얹은 모습을 그림 한 장에 구워 노드의 불투명도가 한 장째로 먹는다. 그림자는 상자 흐림 세 번으로 번지게, 넘치면 set_fit_minimum_ratio 까지 줄인다. 웹에서 글꼴 바이트 없이 시스템 글꼴로 굽는 경우는 그림자 없이 Graphic 의 글로 그린다
- ShadowImage: 그림자를 깐 그림. 그림(또는 조각)을 노드 안에 비를 지켜 가운데로, 그림의 모양 밑에 그림자를 깔아 한 장으로 굽는다. set_image_color 로 한 빛으로 칠한다. 줄이기는 겹친 넓이로 고르게 섞는다
- blur_coverage, compose_shadow_image: 덮인 정도를 번지게 하기와 그림자 위에 모양을 얹은 그림 짓기 (ShadowText, ShadowImage 가 쓴다)
- TextStringTextureCache: rasterize_text(text, font_string, bake_scale, padding) → TextRaster. 글의 모양만 래스터로 받는다. (텍스처로 올리지 않는다)
- README: 장점 위주 소개, 예제 화면 사진(docs/images), 사용법(씬 생명주기, 노드와 컴포넌트, 애셋 로딩, 웹 빌드), 기술 노트(제너레이셔널 핸들 노드 트리, 컴포넌트 접근, 배칭, 컬링, async 없는 애셋 로딩, 텍스트 렌더링, 2D 와 3D, 웹 한글 입력, 플랫폼 레이어), 성능 표를 새로 썼다
- README: 외부 의존성 섹션. 크레이트마다 버전, 쓰는 곳, 하는 일, 라이선스를 공통, 데스크탑, 웹으로 나눠 표로 정리했다
- UIDocument, UIDocumentSaveContext, UIDocumentLoadContext, UIDOCUMENT_VERSION: 노드 트리를 vanilla.js UIDocument 와 같은 JSON 문서(.scene.json, 비주얼 에디터가 저장하는 꼴)로 내보내고(to_json_text, serialize_node) 읽어 짓는다(from_json_text, deserialize_node). 키 차례와 탭 들여쓰기, 수의 글꼴까지 원본 toJsonText 가 낸 글과 같다. 리플렉션 대신 종류 이름마다 짓기, 쓰기, 읽기 함수를 표에 등록하고(register_component_type, 위젯은 register_widget_type), 원본 표의 Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView 와 ShadowImage 를 등록해 둔다. 원본이 반사로 저장하는 종류는 원본 반사 결과와 같은 키로 쓴다. 위젯의 content 안 자식(contentChildren), 위젯이 스스로 붙이는 컴포넌트 빼기, 노드 참조($nodeRef)도 원본대로다. 등록하지 않은 종류는 경고를 내고 건너뛴다. 그림 경로는 이미지 해석기(set_image_resolver)로 찾거나, 해석기가 없으면 load_images 가 요청한 ImageAsset 에서 찾고 나중에 읽힌 그림은 bind_pending_images 가 붙인다
- Sprite: set_image_path, get_image_path(원본 sprite.imagePath), set_round_size, get_round_size(원본은 Paint 를 상속해 쓰던 것). UIImageView: set_image_path, get_image_path. ShadowText: get_text_align, get_fit_minimum_ratio. ShadowImage: get_image_color, set_image_path, get_image_path
- serde_json 의 preserve_order 를 켰다. JSON 객체 키가 적힌 차례를 지킨다. (UIDocument 가 원본 JSON.stringify 와 같은 차례로 쓴다. 지금까지는 이름 차례였다)
- ParticleSystem: 원본의 렌더 모양(ParticleRenderShape 의 Circle, Rect, Streak, Image 와 set_render_shape), 끌개(set_attractor, clear_attractor, 방출점 기준 자리), 흔들림(set_wobble), 늘어짐 길이(set_streak_scale), 월드 공간(set_world_space), edge 방출 모양(EmitterShape::Edge, set_edge_width)을 옮겼다. 서술(apply_description)도 renderShape, attractor, wobble, streakScale, worldSpace, edgeWidth 를 원본 이름으로 읽는다. 그리기는 모양마다 쿼드를 모아 한 번에 그린다. (circle 은 부드러운 원, rect 와 streak 은 흰 텍스처, image 는 그림 텍스처) image 는 원본처럼 색 곡선 없이 시작 알파 x (1 - 수명 비율) 로만 흐려진다
- EmitterShape, ParticleRenderShape 를 크레이트 맨 위에서 내보낸다
- Format(base/format.rs, 원본 base/format.js): format_number(로캘 천 단위 표기), format_number_with_unit, format_compact_number(1.2K, 5.6M, 1.3B), format_padded_number(범위 자르기와 0 채우기), format_minutes_seconds(분:초). 반올림, 음수와 -0, 단위 경계, NaN 과 무한대, String(수)의 지수 꼴까지 원본과 같은 글을 낸다. 로캘은 Intl 대신 node 25(ICU 78.3)에서 뽑은 표(121 줄: 소수점, 천 단위 기호, 음수 앞붙이, 숫자 모양, 인도식 묶음, 최소 묶음 자리, NaN 글)로 쓰고, 표에 없는 태그는 en-US 다. (원본은 브라우저 기본 로캘, 틀린 태그는 RangeError) 원본 format.js 를 node 로 돌린 값 2 만 4 천 건과 같다
- Version: branch 필드와 create_with_branch. 브랜치가 있으면 to_string 이 "major.minor.patch-branch" 를 낸다. (원본 base/version.js) 브랜치가 글이라 Version 은 이제 Copy 가 아니다
- Platform: is_desktop_web(). 모바일이 아니고, 맥이라고 알리면서 손가락 입력이 여럿(navigator.maxTouchPoints > 1)인 아이패드도 아니면 true. 데스크탑 빌드는 늘 true (원본 base/platform.js)
- Rect: 원본 base/rect.js 의 남은 것. overlaps(변이 닿아도 겹친 것), intersection, union, Rect::clamp, get_min / set_min, get_max / set_max, get_center / set_center, get_left / get_top / get_right / get_bottom 과 set_..., set_width, set_height
- Vector2: 원본 base/vector2.js 의 남은 것. divide, divide_scalar, modulo, modulo_scalar, add_scalar, subtract_scalar, half, cross, length_squared, angle, get_x, get_y, minus_one, positive_infinity, negative_infinity, Vector2::lerp(원본 식 from * (1 - t) + to * t), Vector2::clamp. 원본의 버그 둘을 고쳤다: modulo 가 나누기를 하던 것을 나머지로, half 가 두 배를 돌려주던 것을 반으로
- math: 원본 base/math.js 의 남은 것. random_int(양 끝 포함), pick_random, shuffle, shuffle_with_random_function, approach, move_towards, min, max, round(반은 +무한대 쪽, -2.5 → -2), POSITIVE_INFINITY, NEGATIVE_INFINITY. 원본 이름의 floor, ceil, sqrt, abs, 삼각함수, pow 는 아래 math 줄에서 같은 이름으로 더했다. (f32 메서드로 셈한다. 원본이 손으로 다시 짠 sqrt, asin, acos, pow 가 틀리던 것은 원본에서도 내장 함수로 고쳤다)
- NodeTree: 형제 순서와 계층 판정. set_sibling_index(끝을 넘으면 맨 뒤), get_sibling_index, get_child_index, get_sibling_ids, is_active_in_hierarchy, is_visible_in_hierarchy(활성, 보이기 플래그, 불투명도 > 0 을 루트까지). WorldNode: get_child_index. (원본 base/node.js, core/node/transformnode.js)
- ViewManager: set_max_render_pixel_ratio / get_max_render_pixel_ratio(렌더 배율 상한, 웹은 다음 프레임 첫머리에 상한을 건 배율로 캔버스를 다시 맞춘다, 데스크탑은 GL 기본 프레임버퍼를 줄일 수 없어 쓰지 않는다), limit_render_pixel_ratio, apply_aspect_view_scale_mode(기준보다 세로로 길면 StretchWidthExpandHeight, 가로로 길면 StretchHeightExpandWidth, 바로 다시 셈한다), get_css_pixel_scale, set_safe_area_override 와 get_safe_area_insets(강제값 > 주소 ?safeArea=위,오른쪽,아래,왼쪽 > CSS env 실측, 뷰 좌표). (원본 core/viewmanager.js) 플랫폼 층에 read_page_query_value(웹 URLSearchParams, 데스크탑 None), read_safe_area_insets(웹 env 실측, 데스크탑 0)를 더했다
- Engine: unload_scene(scene_id). 씬 하나만 이번 프레임이 끝난 뒤 destroy 하고 뺀다. (원본 SceneManager.unloadScene) load_scene 이 SceneId 를 돌려주고, 씬은 get_scene_base().get_scene_id() 로 자기 핸들을 안다. 같은 프레임에 불러오고 내린 씬은 create 도 destroy 도 부르지 않는다
- Scene: on_page_process_restored, on_page_visibility_restored. (원본 core/scene.js) 엔진이 소리를 다시 깨우고 입력을 비운 뒤 씬마다 부른다. 웹은 visibilitychange 의 visible, 문서 resume, pageshow(persisted), 데스크탑은 창 가림이 풀릴 때(맥과 X11)와 suspended 뒤 resumed. 원본은 pageshow 에서 정의되지 않은 함수(dispatchPageProcessRestored)를 불러 예외가 나던 것을 러스트 판은 resume 과 같은 복구로 고쳤다
- Engine: 페이지 이벤트(PageEvent: Hidden, Visible, Blurred, Focused, PointerDown)와 add_page_event_listener, is_page_hidden. 플랫폼이 알리면 엔진이 리스너에 그 자리에서 넘긴다. (원본은 모듈마다 document 와 window 에 리스너를 단다)
- 오디오 백엔드: suspend_audio_context(웹 AudioContext.suspend, 데스크탑은 kira 메인 트랙을 무음으로 두고 resume 이 되돌린다), 플레이어의 좌우(웹 StereoPannerNode, 데스크탑 kira panning)
- Graphic: 틴트가 걸린 그리기도 묶는다. 원본처럼 정점마다 색과 틴트를 싣는 묶음 셰이더를 따로 두었다. (지금까지는 틴트가 걸리면 묶지 않고 하나씩 그렸다) 화면은 전과 같다. (uigallery 드로우콜 63 → 61, misctour 24 → 12)
- Graphic: 마지막으로 건 셰이더 프로그램과 텍스처 유닛 0 의 텍스처를 기억해, 같은 것을 다시 거는 use_program 과 bind_texture 를 건너뛴다. 묶음을 내보낸 뒤 기본 프로그램으로 되돌리는 호출도 다음에 낱장으로 그릴 때로 미뤘다. get_gl 로 GL 을 내줄 때, restore_render_state, 프레임 시작과 끝에는 기억을 잊어 툰, 스키닝, 블룸, SSAO, ScreenEffect, ShaderSprite 처럼 GL 을 직접 만지는 쪽 뒤에도 틀린 그림이 나오지 않는다
- Graphic: set_image_mipmap_bias, get_image_mipmap_bias. (원본 setImageMipmapBias) 밉맵 단계를 고를 때 더하는 값을 기본, 묶음, 파티클 셰이더의 textureLodBias 로 건다. 바꿔 끼운 셰이더는 그 유니폼이 있으면 받는다. 지금까지는 0 으로 박혀 있었다
- Text: 나눈 줄을 담아 두고 글, 폰트 문자열(이름, 크기, 굵게, 기울임), 줄바꿈 폭, 등록된 글꼴이 바뀔 때만 다시 센다. (지금까지는 그릴 때마다 셌다) 폰트 문자열도 세터에서만 만든다. TextStringTextureCache: get_font_registration_count. 구운 문자열을 키 문자열 대신 키의 해시로 찾아 그릴 때마다 키를 만들지 않는다. Graphic: push_state 가 폰트 문자열을 복제하지 않고 한 번 쓴 칸의 저장소를 다시 쓴다. set_font_string 은 같으면 그대로 둔다. NodeTree: tick 과 터치가 컴포넌트를 꺼낼 때 두는 빈 자리표를 다시 써 매번 잡지 않는다
- 화면 밖 거르기: 글도 거른다. Component 에 calculate_drawn_rect(실제로 그리는 사각형, None 이면 모름)를 두고, 노드의 켜진 컴포넌트가 모두 사각형을 주면 그 합을 그릴 때의 Graphic 변환으로 판정한다. 기본은 지금처럼 is_drawn_inside_content 면 content 영역, 아니면 모름(거르지 않음). Text 와 UILabel(리치텍스트가 아닐 때)은 정렬, 넘침, 줄바꿈 결과의 글 사각형, ShadowText 는 마지막으로 구운 한 장의 자리(바꾼 뒤 아직 굽지 않았으면 거르지 않음), ShadowImage 는 그림자 여백까지 넣은 사각형을 준다. (ShadowText, ShadowImage 는 지금까지 content 영역으로 걸러 넘친 글과 그림자가 화면 가장자리에서 잘릴 수 있었다) 넘치는 글, 5 배로 키운 글, 걸러진 부모의 자식, 아래로 맞춰 위로 자라는 여러 줄을 둔 장면에서 거르기를 켠 화면과 끈 화면이 같다. (uigallery2 드로우콜 83 → 81)
- 글자 꾸밈: Text, RichText, UILabel 에 set_underline, is_underline, set_strikethrough, is_strikethrough, set_wrap_mode, get_wrap_mode 와 TextWrapMode(Word, Character). (원본 setUnderline, setStrikethrough, setWrapMode "word" / "char") 밑줄과 취소선은 원본처럼 글자 색 선(두께 max(1, 크기 / 16))을 긋고, RichText 조각은 조각 속성이 없으면 Text 의 값을 쓴다. 기울임(set_italic)은 지금까지 값만 들었는데, 글자 캐시가 폰트 문자열의 italic, oblique 를 읽어 fontdue 래스터를 기준선 위는 오른쪽, 아래는 왼쪽으로 밀어(높이의 0.2 배) 흉내 낸다. 웹 시스템 글꼴은 Canvas2D font 에 italic 을 넣는다. FontDescription 에 is_italic. ShadowText 에도 set_italic, set_underline, set_strikethrough (원본에 없다, 선도 함께 구워 그림자가 깔린다. 한 줄을 줄여 맞추는 글이라 줄바꿈 방식은 두지 않았다). 예제 engineextras 오른쪽 위에 글자 꾸밈
- TextStringTextureCache: set_text_antialias_enabled, is_text_antialias_on. (원본 setTextAntialiasEnabled, isTextAntialiasOn) 끄면 구운 글자의 알파를 문턱값 128 로 0 과 255 로 가르고 텍스처를 NEAREST 로 뽑는다. (도트 글꼴용, 기본 켬) 웹 시스템 글꼴로 구운 글자도 같다. 원본은 이미 구운 글자를 그대로 두지만 여기서는 켜짐 여부를 캐시 키에 넣어 바꾼 다음 그리는 글자부터 그 방식으로 굽는다. 예제 engineextras 에 그리는 동안만 끄는 도트 글자
- Image: GPU 에 올린 뒤 CPU 픽셀을 놓아 메모리를 돌려준다. (지금까지는 텍스처와 같은 픽셀을 CPU 에도 끝까지 들었다) get_pixels 는 Ref<[u8]> 을 돌려주고 올린 뒤에는 비어 있을 수 있다. (공개 API 를 바꾸는 일이다) has_pixels, set_pixels_retained, is_pixels_retained 를 더했다. 픽셀을 다시 읽을 그림은 set_pixels_retained(true) 로 남긴다. ShadowImage 는 받은 그림을 스스로 남기고, 다른 곳에서 먼저 그려 이미 놓였으면 텍스처를 프레임버퍼에 붙여 되읽는다. (되읽은 픽셀이 원래 픽셀과 바이트까지 같다) 엔진에 GL 컨텍스트를 되살리는 길이 없어 놓은 픽셀로 다시 올릴 일은 없다
- 입력: 출시 게임들(찾았다, 종말 생존, 우주생물, aberrant, 외계행성 광부)이 게임 쪽에 따로 만들어 쓰던 입력을 엔진 기본으로 옮긴다. (vanilla.js 에 먼저 넣은 것과 같은 기능)
- GamepadKind, read_gamepad_kind(gamepad_id): 패드 이름으로 종류를 가른다. PlayStation(054c, playstation, dualshock, dualsense, sony), Nintendo(057e, nintendo, joy-con, pro controller), Xbox(045e, xbox, xinput, microsoft), 그 밖은 Other
- GamepadManager.vibrate(strong_magnitude, weak_magnitude, seconds): 연결된 패드를 모두 떤다. 데스크탑은 gilrs force feedback(리눅스, 윈도우), 웹은 vibrationActuator 의 dual-rumble. gilrs 가 진동을 대지 않는 macOS 는 아무것도 하지 않는다. 이 때문에 gilrs 를 진동을 켠 채 만든다. (데스크탑에서 gilrs 진동 스레드 하나가 돈다, 지금까지는 껐다)
- GamepadManager.get_active_gamepad_id(): 마지막 갱신에 단추를 누르거나 축을 0.5 넘게 기울인 패드의 이름
- GamepadManager.set_input_log_enabled, is_input_log_enabled: 단추와 축이 바뀔 때마다 찍는 로그를 끄고 켠다. 기본 동작을 바꿨다: 기본이 꺼짐이라 이제 단추와 축 로그는 찍지 않는다. (원본과 같이 바꿈, 스틱을 조금만 움직여도 프레임마다 로그가 쏟아졌고 로그에 기대는 게임이 없다) set_log_enabled 는 연결과 해제까지 모든 로그의 큰 스위치로 그대로다
- InputManager.is_key_just_pressed, is_key_just_released, is_mouse_button_just_pressed, is_mouse_button_just_released 의 바뀐 동작: 프레임 끝의 사진을 견주지 않고 지난 프레임 끝 뒤로 온 사건(push_key, pop_key, set_mouse_button_down)을 쌓아 본다. 프레임 사이에 눌렀다 뗀 것을 놓치던 것을 고쳤다. (그때는 눌림이 거짓이고 누름과 뗌이 함께 참이다) 원본과 같다
- TouchPoint 에 phase(TouchPhase: Began, Moved, Stationary, Ended, Cancelled)와 view_position 을 더했다. (구조체 필드가 늘어 TouchPoint 를 직접 짓는 코드는 고쳐야 한다) InputManager.begin_touch_point, move_touch_point, end_touch_point 로 손가락마다 받고, 이번 프레임에 떨어진 손가락은 get_ended_touch_points 에 한 프레임 남는다. 데스크탑과 웹 플랫폼이 이 길로 넣고, 웹은 사건의 touches 에 없는 손가락을 취소로 지운다. get_touch_points 는 지금처럼 닿아 있는 손가락만이다
- InputDevice, InputManager.get_last_input_device, get_last_gamepad_kind (set_last_input_device, set_last_gamepad_kind): 마지막으로 쓴 장치(Keyboard, Mouse, Touch, Gamepad)와 패드 종류. 플랫폼이 키, 마우스(웹은 6 픽셀 넘는 움직임), 손가락에서 적고, 패드는 tick 에서 get_active_gamepad_id 로 적는다. 처음은 손가락 기기면 Touch, 아니면 Keyboard
- InputManager.set_prevented_keys(keys), get_prevented_keys, is_key_prevented, is_typing_in_text_field: 브라우저 기본 동작을 막을 키. 웹 keydown 이 글자 입력칸에 쓰는 중이 아닐 때 막는다. (데스크탑 창에는 막을 기본 동작이 없다) 글자 입력칸은 엔진 입력 필드의 포커스와, 웹은 문서의 초점(글자 input, textarea, contenteditable, select). 플랫폼 층에 is_text_field_focused 를 더했다
- InputActions, InputActionSource(core/inputactions.rs): 입력 동작. InputManager 가 하나 들고(get_input_actions, get_input_actions_mut) tick 에서 갱신한다. bind_key, bind_gamepad_button, bind_axis(action, axis_index, direction), unbind_action, get_bound_keys, set_repeat(action, delay_seconds, interval_seconds), set_dead_zone(처음 0.2), set_axis_press_threshold(처음 0.5), set_keys_ignored_while_typing(처음 참), add_source(Box
) → 번호, remove_source(번호), is_pressed, is_just_pressed(반복 포함), is_just_released, read_value, read_axis(negative_action, positive_action), read_gamepad_stick(x_axis_index, y_axis_index), read_move_axis(WASD 와 방향키, 왼쪽 스틱, 바깥 입력원 가운데 가장 긴 것, 길이 1 이하). 원본과 달리 이동 키와 패드 축은 update 때 적어 둔 같은 프레임의 값을 읽는다 - Camera3D, ProjectedPoint: 3D 카메라. (vanilla.js 와 같이 넣음) 원근(set_perspective)과 직교(set_orthographic), 가로 세로 비(set_aspect_ratio), look_at, 보기와 투영 행렬을 값이 바뀔 때만 다시 셈해 담아 둔다(get_view_projection_matrix, get_inverse_view_projection_matrix). project_to_view(x, y, z, view_rect) 는 월드 점을 3D 를 그리는 사각형 안의 자리와 카메라 앞인지로, unproject_to_plane(view_position, plane_height, view_rect) 는 사각형 안의 자리에서 나간 시선이 수평면과 만나는 점으로, read_view_depth 는 보는 쪽 깊이로 셈한다. 렌더러와 2D 표시가 같은 카메라를 쓴다. (외계행성 광부, aberrant, 종말 생존이 화면마다 카메라 행렬을 다시 짓고 투영을 손으로 셈하던 것)
- ToonRenderer: set_screen_rect(x, y, 너비, 높이), clear_screen_rect, get_screen_rect. 노드 사각형 안에만 그린다. begin_frame 이 보기와 투영의 클립 공간을 사각형으로 옮기고 가위로 밖을 자르며, end_frame 이 가위를 푼다. 화면 밖 거르기는 옮기기 전의 절두체로 한다. begin_frame_with_camera(Camera3D), draw_mesh_outline(바깥선만 그리고 세지 않음). ToonDrawOptions 에 casts_shadow(ToonDrawQueue 가 읽음)와 is_body_drawn 을 더했다. (기본 true, 화면 사각형을 주지 않으면 지금과 같다)
- ToonDrawQueue: 한 프레임에 그릴 모형을 담아 두었다가 불투명한 몸, 불투명한 것의 바깥선, 비치는 것(카메라에서 먼 것부터, 깊이 쓰기 끔) 차례로 그린다. add_mesh, add_mesh_instanced, draw_shadows, draw(gl, renderer, camera). 모형을 빌려 담아 수명 'a 를 갖는다. (종말 생존 ModelRenderer3D 의 담아 그리기에서)
- Graphic: run_external_pass(is_depth_cleared, pass), clear_depth_buffer. 2D 그리기 사이에 GL 패스를 끼운다. 앞의 2D 묶음을 내보내고, 깊이를 비운 뒤 pass(gl) 를 부르고 restore_render_state 를 부른다. 자르기(스텐실)를 건 뒤 깊이를 비우면 갤럭시 폴드3(Adreno 660)에서 3D 가 하나도 안 그려진 일이 있어(원본 게임), 자르기 안에 3D 를 그릴 노드는 begin_clip_rect 앞에서 clear_depth_buffer 를 부르고 is_depth_cleared 를 false 로 준다
- ToonView3D, ToonViewDrawer, ToonViewPass: 노드 사각형 안에 툰 3D 를 그리는 컴포넌트. 내용 영역을 지금 변환으로 드로잉 버퍼 사각형으로 옮기고, run_external_pass 안에서 렌더러의 화면 사각형을 걸고 그리개(ToonViewDrawer::draw_toon)를 부른다. 렌더러는 처음 그릴 때 짓고, 짓지 못하는 기기면 다시 짓지 않고 draw_fallback 으로 2D 를 그린다. 카메라(get_camera_mut)의 가로 세로 비는 그릴 때마다 사각형에 맞춘다. 원본의 그리기 함수 대신 그리개를 타입 인자로 들고, 원본의 setRenderer(렌더러 공유)는 옮기지 않았다
- ToonPostProcess: set_color_grade(채도, 대비, 색조 색, 색조 양, 안개빛 색, 안개빛 양), set_vignette(가장자리 어둡게). 톤매핑과 감마 뒤에 건다. 색조 색은 밝기를 1 로 맞춰 곱하고, 안개빛은 어두운 곳일수록 그 색 쪽으로 끌어올린다. 기본 값이면 보정이 없어 지금과 같다. 노드 사각형에 낼 때는 resize(사각형 크기) 뒤 end 의 뷰포트로 사각형을 준다. (종말 생존 SceneEffects3D 의 색 고르기에서)
- MeshBuilder::combine(&[ToonMeshPiece]) 는 움직이지 않는 조각 여럿을 옮겨 한 배열로 잇는다. 바깥선 껍데기와 껍데기 기준 자리, 안쪽 범위도 옮겨 잇고 뼈대는 잇지 않는다. create_faceted_chunk_geometry(반지름, 꼭짓점 배, 축 배) 는 이십면체의 꼭짓점 열둘을 저마다 늘이고 줄인 각진 돌덩이다. (종말 생존 combineMeshArrays, 외계행성 광부 meshbuilder.js)
- GraphicsQualityGovernor, GraphicsQuality(Auto, High, Low): 가벼운 길(is_lite)을 덮어쓰기(apply_search_text, 웹은 apply_page_query 로 페이지 주소의 ?light, set_lite_override) → 설정(낮음은 늘, 높음은 아님) → 자동(set_auto_lite_default 이거나 FrameProbe 가 처지는 기기로 잼) 차례로 정한다. update(프레임 초, 최대 프레임) 는 자동일 때만 재고 바뀐 프레임에 true. set_render_pixel_ratio_limits(보통, 가벼운 길) 와 apply_render_pixel_ratio(view_manager). 가벼운 길에서 무엇을 줄일지는 게임이 정한다. (외계행성 광부 readIsLite, aberrant isLight)
- 출시 게임들이 따로 만들어 쓰던 로딩, 저장, 시간 기능을 엔진 기본으로 넣는다. (vanilla.js 에 넣은 것과 같은 기능, 게임의 화면 모양과 출시처 코드는 가져오지 않았다, 기본 동작은 LocalStorage 읽기 하나만 바꿨다)
- TimeManager: set_maximum_time_delta(seconds), get_maximum_time_delta(). 한 프레임 간격의 상한을 바꾼다. (지금까지 0.25 초로 박혀 있었고 기본값은 그대로다) 0 보다 작거나 유한하지 않으면 0.25
- Engine: set_maximum_frame_per_second(n), get_maximum_frame_per_second(). 실행 중에 최대 FPS 를 바꾼다. (지금까지는 EngineConfiguration 으로 처음에만 정할 수 있었다) 설정에 적고 데스크탑과 웹 플랫폼이 프레임마다 그 값을 읽는다. 0 보다 작거나 유한하지 않으면 0(제한 없음)
- FixedStepper: 고정 걸음. FixedStepper::new(step_seconds, maximum_steps_per_frame) 의 advance(time_delta, step_function) 가 쌓인 시간만큼 step_function(step_seconds) 을 부르고 남은 몫(0 ~ 1)을 돌려준다. 한 프레임 상한만큼 돌고도 걸음이 남으면 남은 시간을 버리고, step_function 이 false 를 돌려주면 그 프레임은 거기서 멈추고 시간을 쌓아 둔다. (원본은 false 일 때만 멈추고 돌려주지 않아도 되지만 러스트 판은 늘 bool 을 돌려준다) get_alpha, get_last_step_count, reset
- LocalStorage: 저장소 갈아 끼우기 set_backend(Some(Box
)), has_backend. LocalStorageBackend 는 get_item, set_item, remove_item 과 (없어도 되는) get_keys, clear 를 가진 트레이트이고, 원본의 예외 자리는 Err 다. 저장소가 없거나(웹의 막힌 localStorage) 쓰기가 실패하면(용량, 데스크탑 폴더를 못 만듦, 바꿔 낀 저장소의 Err) 이 실행 동안 메모리에 대신 둔다. (is_memory_fallback) get_item, set_item(저장소에 썼는지), remove_item, get_json(key, default_value), set_json(key, &value) - LocalStorage: 읽기(get_string, get_boolean, get_number)가 없는 키에 기본값을 써 넣지 않는다. (기본 동작을 바꾼 것이다, 원본과 같이 바꿨다) 읽기만 해도 키가 생겨서 새 판에서 기본값을 바꿔도 옛 기본값이 저장된 값처럼 남고 contains_key 가 늘 참이 됐다. 원본을 쓰는 출시 게임 가운데 이 동작에 기대는 곳이 없다. (2026-11-25 게임 코드 grep, vanilla.js UPDATE.md 에 자세히)
- PersistedStore: set_storage_backend(Option<Box
>), has_storage_backend. 저장소 하나만 다른 곳에 둔다. 갈아 끼우면 그곳에서 다시 읽고 구독자에게 알린다 - AssetLoader: 애셋 함께 받기. add_image, add_json, add_text, add_blob 은 아직 비어 있는 읽기 손잡이를 단 애셋을 바로 돌려주고, add_audio 는 Rc
(디코딩까지 끝나야 끝난 것), add_font(engine, family, path, is_bold) 는 읽기 손잡이, add_load_handle 은 바깥에서 요청한 손잡이(원본 addTask 자리)를 넣는다. load(engine) 가 set_concurrency(기본 6) 만큼 요청하고 update(engine) 를 프레임마다 부르면 끝난 만큼 다음 것을 요청한다. (데스크탑은 그 자리에서 읽혀 load 에서 끝난다) get_completion_handle 을 씬의 track_load_handle 로 맡기면 다 받을 때까지 initialize 를 미룬다. get_progress, get_loaded_count, get_finished_count, get_total_count, get_failed_list(AssetLoadFailure), is_finished, get_in_flight_count, set_progress_handler, set_complete_handler. 값싼 복제 손잡이다 - AssetBase: load_from_handle(load_handle). 남이 채울 읽기 손잡이를 단다. Engine: request_asset_bytes_into(path, &load_handle). 이미 만든 손잡이를 채우는 애셋 바이트 요청 (둘 다 AssetLoader 가 쓴다)
- LoadingProgress: 알려 준 진행률(set_progress, 0 ~ 1, 줄지 않음)을 보이는 값(get_shown_progress)이 부드럽게 따라간다. 매 프레임 update(time_delta), set_follow_rate(기본 초당 남은 거리의 6 배), is_finished, reset
- GameSceneBase: 로딩 화면 바꾸기. set_loading_colors(바탕, 게이지 바탕, 게이지), set_loading_outside_color(뷰 바깥), set_loading_drawer(Some(LoadingDrawer)) 로 바탕 위의 그림 전체를 바꾼다. (LoadingDrawer 는 graphic, 뷰 크기, 보이는 진행률, 경과 초를 받는 함수) set_loading_progress 나 track_asset_loader 로 진행률을 알리면 게이지가 경과 시간 대신 그 진행률을 부드럽게 따라간다. (get_loading_progress_state, 원본 getLoadingProgress 는 러스트 판에 같은 이름의 경과 시간 비율이 있어 이 이름이다) track_asset_loader 로 맡긴 것은 draw_on_load 가 update 를 불러 준다. 아무것도 정하지 않으면 지금과 같다
- BuildInfo: 빌드 판 읽기. BuildInfo::new(env!("CARGO_PKG_VERSION")) 의 load(engine) 가 웹에서는 페이지의 을 먼저 읽고, 없으면 페이지 기준 version.json 을 캐시 없이(fetch 의 cache: "no-cache") 요청한다. 데스크탑은 애셋 폴더의 version.json 을 읽는다. read_text() 는 meta 의 글, version.json 의 "날짜 시각 (해시)" (해시가 없으면 version), 둘 다 없으면 빌드 때 넣은 판. is_finished, get_load_handle(씬이나 AssetLoader 에 맡긴다), read_version_data, set_meta_name, set_version_json_path, BuildInfo::compose_text. meta 와 캐시 끄기는 브라우저에만 있는 것이라 데스크탑은 하지 않는다. 예제 loadingshowcase 에 판을 보인다
- ToonScreenOutline, ToonOutlineWidthUnit, ToonLineDrawOptions: 툰 화면 공간 바깥선. (vanilla.js ToonScreenOutline 과 같은 기능, 외계행성 광부 키우기와 애버런트가 따로 쓰던 셰이더 바깥선) ToonRenderer 의 모형을 같은 행렬로 한 번 더 그려 노멀, 선 번호, 깊이를 선의 판에 쓰고(begin_line_ids, draw_mesh, draw_mesh_instanced, end_line_ids), 가면을 쓴 뒤 draw_outline 으로 섞는다. 부품의 번호는 index_start, index_count 로, 인스턴스마다의 번호는 draw_mesh_instanced 의 line_id_list 로 준다. 굵기는 월드 길이나 픽셀(set_width, set_focus_distance), 직교와 원근은 투영 행렬로 가리고 원근은 깊이를 미터로 푼다. set_depth_threshold, set_crease, set_resolution_scale, set_sample_count, set_color, set_hdr_output
- ToonMesh: 크레이트 안에서 몸 버텍스 어레이와 인스턴스 버퍼를 읽는 get_body, get_instance_buffer. (화면 공간 바깥선이 같은 모형을 그릴 때)
- ToonVfx 와 ToonParticleOptions, ToonFireballOptions, ToonShockwaveOptions, ToonDecalOptions, ToonPlumeOptions, ToonBeamOptions, ToonRibbonOptions, ToonLightningOptions, ToonGlintOptions, ToonVfxRange, ToonVfxSlot, ToonVfxLook, ToonVfxShape, ToonVfxDecalMode, ToonVfxCounts: 툰 3D GPU 효과의 바탕. (vanilla.js ToonVfx 와 같은 기능과 셰이더, 외계행성 광부 키우기와 애버런트의 범용 부분, 처방과 램프 색은 게임 몫) 코드로 짓는 아틀라스, 인스턴스 GPU 파티클(emit_particles), 불덩이(add_fireball), 충격파(add_shockwave), 바닥 자국(add_decal, queue_decal), 연기 기둥(add_plume), 회전체 빔(queue_beam), 리본(queue_ribbon)과 번개(queue_lightning), 빛 점(queue_glint), update 로 나아가는 자체 시계, 파티클 상한(new, set_particle_capacity)과 내는 수의 몫(set_count_ratio), 램프 색(set_ramps, 0 ~ 1 의 [r, g, b] 줄), 바닥 높이 콜백(set_floor_height_reader). 효과마다 기본값을 가진 구조체로 값을 받는다
- 출시 게임들(외계행성 광부, aberrant, 종말 생존, 우주생물)이 따로 만들어 쓰던 창 쌓기와 화면 틀을 엔진으로 옮긴다. (vanilla.js 에 넣은 것과 같은 기능, 판 모양, 테마, 연출, 출시처 코드는 가져오지 않는다)
- UIWindowLayer: 창 쌓기 컴포넌트. UIWindowLayer::create(node_tree, parent_id) 로 층 노드를 만들고 open_window(tree, window_id) 로 맨 위에 쌓는다. 맨 위 창만 보인다. close_window 는 목록에서 바로 빼고 PopupMotion 닫는 움직임이 끝난 뒤 창 노드를 지운다(덮여 있던 창은 바로). close_all_windows, close_top_window(뒤로 가기, 바깥 닫기를 끈 창은 닫지 않음), get_top_window, find_window, has_open_window, get_window_count, set_window_change_event(떠 있는 창 수를 받는 알림). 층은 UIScale::read 만큼 커지고(set_view_size 가 CSS 배율을 받는다, set_ui_scale_options(None) 이면 키우지 않음, get_ui_scale) 창에는 그만큼 나눈 영역 크기와 세이프 에어리어 너비(set_view_bleed)를 알린다. open_window_in_tree
- UIWindow, UIWindowBehavior, UIWindowDefaultBehavior, UIWindowParts, UIWindowEvent: 창 하나. 영역과 세이프 에어리어까지 덮는 어둠(누름을 삼킴) 위 가운데에 판(Paint 한 장)을 띄운다. 판은 영역 가로에 맞춰 넓어지되 set_maximum_width(기본 480)를 넘지 않고, 세로는 layout_content(기본 set_panel_height), 영역보다 크면 통째로 줄인다. 바깥을 누르면 닫힌다(set_outside_close_enabled). close_in_tree, set_close_event, refresh_layout_in_tree. 원본 파생 클래스가 덮어쓰는 메서드(build, layout_content, layout_panel, apply_motion, set_covered, handle_wheel, handle_closed, dispose)는 UIWindowBehavior 트레이트이고 get_behavior_mut 으로 꺼낸다. 판 모양은 게임이 build 에서 틀(get_frame_node)에 꾸밈을 붙여 바꾼다. 휠은 그 자리의 스크롤 뷰가 먼저 받고 다음에 창이 받아 늘 삼킨다
- UIConfirmWindow, UIConfirmWindowOptions: 확인 창(UIWindowBehavior). 제목, 묻는 글, 취소와 확인 두 단추. 글이 영역 세로를 넘으면 글 칸만 스크롤된다. 글 줄 수는 그린 뒤에 알 수 있어 처음엔 한 줄로 놓고 다음 tick 에 다시 놓는다. set_right_to_left(true) 면 단추 차례를 뒤집는다. 확인은 set_confirm_event 뒤 닫히고, 취소 단추, 바깥 누르기, 창 층이 닫으면 set_cancel_event. confirm_in_tree, set_title, set_message. (UIDialog 는 그대로)
- UIScale, UIScaleOptions: 뷰 한 단위가 minimum_css_scale(0.8) CSS 픽셀보다 작으면 UI 층만 키울 배율. (1 ~ maximum_scale 1.8, 낮은 화면은 minimum_layer_height 아래로 키우지 않음(기본 0 이면 보지 않음), 세로 화면(가로가 세로의 portrait_ratio 1.1 배 이하)은 상한 없음) UIScale::read(view_width, view_height, css_pixel_scale, &options), is_portrait
- Text: get_measured_line_count(). 그린 뒤 글, 폰트, 줄바꿈 폭이 그대로일 때 마지막으로 나눈 줄 수. (Graphic 이 없는 레이아웃이 그린 결과를 읽을 때)
- GameSceneBase: fade_screen(on_dark), ScreenFadeHold, ScreenFadeEvent. 다 어두워지면 on_dark(트리, 엔진)를 부르고, ScreenFadeHold 를 돌려주면 release 할 때까지 어둡게 둔다(원본 Promise 자리). 이미 페이드 중이면 false. set_screen_fade_color(기본 검정), set_screen_fade_seconds(기본 0.35), is_screen_fading, get_screen_fade_alpha. 막은 post_draw(새로 더함, 씬 post_draw 에서 부른다)가 세이프 에어리어까지 캔버스 전체에 그리고, 배율을 곱하지 않은 시간으로 움직인다. 막이 걸린 동안은 누름과 휠을 막고 누르던 손가락의 이동, 뗌, 취소만 넘긴다
- GameSceneBase: is_user_interface_at(view_position), set_play_input_enabled, take_play_inputs, PlayInput(Press, Move, Release, Wheel), convert_view_to_play_area. UI 가 받지 않은 누름과 그 누름의 이동과 뗌(취소 포함), UI 밖의 휠을 세이프 에어리어 왼쪽 위 기준 게임 영역 좌표로 모은다. (원본은 처리기 객체, 러스트 판은 처리기가 씬 상태를 빌릴 수 없어 큐)
- GameSceneBase: set_play_area_reference(fixed_length, is_landscape, engine), apply_play_area_reference(engine), calculate_play_area_reference_length. 세이프 에어리어를 뺀 게임 영역의 고정 쪽 길이가 늘 fixed_length 가 되게 기준 해상도를 늘린다. initialize 는 스스로 걸고, resize 는 엔진을 바꿀 수 없어 씬이 resize 첫머리에 apply_play_area_reference 를 부른다
- ViewManager: set_ignored_safe_area_sides(&[SafeAreaSide]), get_ignored_safe_area_sides, SafeAreaSide. get_safe_area_insets 가 그 쪽을 0 으로 돌려준다
- TouchRecognizer: is_touching()
- GameSceneBase 의 바뀐 동작: set_safe_area_insets 로 정하지 않았으면 compute_safe_area_rect 가 플랫폼 env 를 따로 재던 것 대신 ViewManager::get_safe_area_insets 를 읽는다. 지금까지는 set_safe_area_override, 주소의 ?safeArea=, (새) 무시할 쪽이 GameSceneBase 의 세이프 에어리어에 닿지 않았다. 웹 env 값은 정수로 잘리지 않는 것 말고 같고, 데스크탑은 그대로 0 이다. 따로 재던 read_platform_safe_area_insets 와 parse_leading_integer 는 쓰지 않게 되어 뺐다
- 출시 게임들이 따로 만들어 쓰던 글자, 노드 편의, 그리기 기능과 최적화를 엔진 기본으로 넣는다. (vanilla.js 에 같이 넣은 것과 같은 기능, 게임의 화면 모양과 연출은 가져오지 않았다)
- Text, UILabel: set_fit_width(width, minimum_ratio), get_fit_width, get_fit_minimum_ratio, get_fitted_font_size, calculate_fitted_font_size. 한 줄 글이 맞출 너비를 넘치면 처음 크기에서 최소 비율까지 0.1 단위로 줄여 그린다. 정한 크기는 그대로이고, 최소 비율로도 넘치면 넘친 채 그리며 화면 밖 거르기의 글 사각형은 줄인 글의 너비를 따른다. 줄을 바꾸는 글과 리치텍스트는 맞추지 않는다. 줄인 크기는 줄을 나눌 때 재므로 Graphic 이 있어야 안다
- Text: set_letter_spacing, get_letter_spacing (UILabel, RichText 도 같은 이름). 글자 묶음마다 뒤에 더하는 간격(픽셀, CSS letter-spacing 과 같은 뜻, 음수는 좁힘, 처음은 0). 글 너비는 글자 묶음 수 x 간격만큼 늘고 줄바꿈, 맞춤 너비, 정렬, 밑줄이 그 너비로 잰다. 앞뒤 짝을 재어 자리를 잡아 짝 커닝은 남는다. 오른쪽에서 왼쪽으로 쓰는 글은 간격을 쓰지 않는다. 원본 setLetterSpacing 과 같다
- Engine::open_url(url): 바깥 주소를 연다. 데스크탑은 운영체제의 기본 프로그램(맥 open, 윈도우 ShellExecuteW, 리눅스 xdg-open), 웹은 window.open(주소, "_blank", "noopener") 새 탭이다. 웹은 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열린다(브라우저의 팝업 차단 규칙). http, https, mailto, tel 만 열고 그 밖의 꼴은 false. 원본 Engine.openUrl 과 같다
- Engine::read_local_time(minute_offset: f64) -> LocalTime: 지금에서 분 오프셋만큼 더한 때를 이 기계의 시간대로 본 달력 시각(LocalTime { year, month 1 에서 12, day, hour, minute, second, weekday 0 이 일요일 })을 돌려준다. 웹은 Date, 맥과 리눅스는 localtime_r, 윈도우는 SystemTimeToTzSpecificLocalTime 으로 읽고 더한 때의 일광 절약 시간까지 반영한다(원본 new Date(Date.now() + 오프셋) 과 같다). 원본 Engine.readLocalTime 과 같다
- UIView: set_backdrop_blur(blur_radius), get_backdrop_blur. 뒤 화면 흐림(CSS backdrop-filter: blur(), 언리얼 UMG BackgroundBlur 와 같은 뜻, 처음은 0 으로 꺼짐). 인자는 CSS blur(Npx) 의 N 과 같은 표준편차(노드 좌표 단위, 화면에서는 변환 배율을 곱한 기기 픽셀)다. 새 ScreenEffectType::GaussianBlur(분리형 가우스, 3 시그마까지, 선형 샘플링, 모서리는 거울 접기)로 흐린다. 원본 엔진과 화소가 같고(표준편차 3, 8, 20, 40, 최대 차 1) 크롬 CSS 와도 같다. 끄면 화면은 바이트 그대로
- UIView: set_backdrop_corner_radius(corner_radius), get_backdrop_corner_radius. 뒤 화면 흐림과 바탕색의 둥근 모서리(CSS border-radius). 처음은 0(사각형). 원본 setBackdropCornerRadius 와 같다
- 화면 저장: VANILLA_CAPTURE_FRAMES 와 웹 capture 에 0 을 주면 첫 프레임(1)으로 본다. (프레임 번호는 1 에서 시작해 0 은 오지 않아 영영 안 찍고 끝나지 않았다)
- ScreenEffectType::GaussianBlur: 표준편차 가우시안 블러(parameters = [표준편차 픽셀], CSS filter: blur() 와 같은 뜻). 기존 Blur 는 그대로
- SpriteAnimator: 같은 노드의 ShaderSprite 도 움직인다(원본은 ShaderSprite 가 Sprite 를 상속해서 같은 노드의 ShaderSprite 도 움직인다). play, tick, find_sprite 가 Sprite 가 없으면 ShaderSprite 를 쓴다
- Text, UILabel: measure_text(graphic, text, font_size). Graphic: measure_text_with_font_string(font_string, text)
- TextStringTextureCache: 글 재기(measure_text)를 폰트 문자열과 글이 같으면 다시 재지 않는다. (2048 개, 넘으면 오래 안 쓴 반을 버림, 글꼴을 새로 등록하면 비움) get_measure_count
- UILabel.set_text: 같은 글이면 건너뛴다. (리치텍스트 모드가 아닐 때) Text.set_text 는 전부터 같은 글을 건너뛴다. 색은 Copy 라 같은 색 건너뛰기는 따로 두지 않았다
- Graphic: set_text_bake_motion_scale_step, get_text_bake_motion_scale_step(기본 0.25), set_text_bake_scale_moving, is_text_bake_scale_moving, update_text_bake_scale_moving. 글자 굽기 배율 단계가 0 일 때, 그리는 노드의 변환 배율이 지난 프레임과 다르면(ButtonMotion, PopupMotion, 트윈) 이 단계로 묶은 배율로 굽고 멈추면 정확한 배율로 다시 굽는다. 처음 그리는 노드는 움직이지 않는 것으로 본다. 단계가 0 이 아니면(기본) 셈하지 않는다. NodeTree 가 노드마다 정하고, ShadowText, ShadowImage 도 같은 배율을 쓴다. WorldNode: set_last_drawn_maximum_scale, get_last_drawn_maximum_scale
- ShadowText, ShadowImage, SoftShade: 같은 모양이면 구운 그림을 열쇠별로 나눠 쓴다. (core/sharedbakecache.rs 의 acquire_shared_bake, read_shared_bake_count) 컴포넌트가 쥔 Rc 가 참조 수이고, 아무도 쓰지 않게 된 것은 128 개까지 남겨 두었다 새로 담을 때 오래 안 쓴 것부터 버린다. ShadowImage 는 그림의 인스턴스 식별자와 조각을 열쇠로 쓴다
- NodeTransform, WorldNode: set_local_position_xy, set_local_scale_xy, set_content_size_xy, set_rect(x, y, width, height) (왼쪽 위가 (x, y) 에 오게 피봇까지 셈해 로컬 위치와 내용 크기를 둔다, 앵커는 그대로). NodeTree: convert_view_to_local(node_id, view_position) (convert_view_position_to_node_position 과 같은 셈, 원본 이름)
- Localization: mirror_layout_x(x, width, parent_width), read_layout_text_align(text_align). 오른쪽에서 왼쪽 언어면 배치의 가로 자리와 정렬의 왼쪽, 오른쪽을 뒤집는다
- 휠: 그 자리를 덮는 것 가운데 그리는 순서로 가장 앞이 휠을 받는 칸(Component::is_wheel_receiver, UIScrollView 와 UISnapScrollView 가 true)이면 그 칸이 받는다. 가장 앞이 누를 수 있는 노드면 지금처럼 그 노드부터 부모 쪽으로 묻는다. (NodeTree::find_wheel_target_node, dispatch_wheel_at) SceneBase.tick_touch 와 TouchRecognizer(GameSceneBase)가 쓴다. 받은 것이 있었는지는 SceneBase::is_wheel_handled, TouchRecognizer::is_wheel_handled, GameSceneBase::is_wheel_handled (false 일 때만 게임의 지도 확대 등에 쓰면 창의 스크롤과 겹치지 않는다)
- Graphic: draw_ring(center, inner_radius, outer_radius, start_radian, end_radian) (set_fill_color), draw_arc(center, radius, start_radian, end_radian, line_width) (set_stroke_color), draw_ring_with_color. 조각마다 네모 하나를 겹치지 않게 이어 한 번에 그려 반투명이어도 이음매가 짙어지지 않는다. 조각 수는 draw_circle 처럼 화면에서의 반지름을 따라(한 바퀴 16 ~ 64) 그리는 각도만큼. 각도는 0 이 오른쪽, 시계 방향
- Graphic: draw_line_segments(position_values, size). 숫자 배열 하나(선분마다 x0, y0, x1, y1)로 선분 여럿을 한 번에 그린다. 정점 버퍼가 차면 거기까지 그리고 이어 담는다
- SpriteAtlas: tools/atlas.cjs(vanilla.js)의 JSON 과 { pagePaths, frames } 꼴을 읽는다. load(engine, json_path), load_data, update(웹은 JSON 이 온 뒤 쪽 그림을 청한다), is_loaded, track_json_asset, read_frame, has_frame, apply_frame, get_page_count, get_frame_names, 여러 아틀라스를 차례로 찾는 find_frame_in_order, apply_frame_in_order. 이름은 확장자를 떼고도 찾는다. Sprite.set_frame(frame)
- GamepadManager.vibrate: macOS 데스크탑에서도 떤다. (gilrs 의 macOS force feedback 이 비어 있어 지금까지 아무것도 하지 않았다) 플랫폼 층 platform/desktop/gamepadhaptics.rs 가 GameController 의 GCController.haptics 로 CoreHaptics 엔진을 지어, 무거운 모터는 왼손잡이, 가벼운 모터는 오른손잡이 엔진에 연속 진동으로 낸다. (둘을 대지 않는 패드는 엔진 하나에 큰 세기로) gilrs 패드와 컨트롤러는 이름(vendorName)이 같은 것을 먼저, 남은 것은 차례로 잇는다. 엔진은 컨트롤러마다 한 번 짓고, 멈춤과 리셋 뒤에는 다시 시작하고, 실패하면 다시 짓는다. macOS 는 길이나 세기가 0 이면 앞 진동을 멈춘다. 예제 inputgallery 에 패드 진동 시험(A, B, X, Y)을 더했고, 실제 패드가 붙어 있으면 스스로 끝나지 않는다. 의존성: objc2-game-controller, objc2-core-haptics, objc2, objc2-foundation, block2 (macOS 만)
- ParticleSystem 을 원본과 같게 했다. 기본값(최대 512 개, 속도 60, 크기 6, 원뿔 반각 0.5 라디안, set_cone_angle 은 원본처럼 반각), cone 은 반지름 안에서, box 는 위로만 낸다. 난수 차례와 셈이 원본과 같아 같은 씨앗이면 원본과 같은 입자 자리가 나온다. (모양 다섯에서 차이 0.0002 px 아래) 방출 원점은 원본처럼 컴포넌트 좌표 원점(내용 영역 왼쪽 위), simulate(time_delta), emit(count, Option 원점 보정). EmitterShape 는 ParticleEmitterShape, Rectangle 은 Box 로 이름을 바꿨다. duration 이 지나도 원본처럼 재생 중으로 남고 is_finished 가 끝남을 알려 준다. get_particle_position_list. 정점 한도를 넘는 입자도 나눠 다 그린다. (공개 API 가 바뀐다)
- HeatHazeEffect: 줄 수 한도(1365) 없이 나눠 그린다. (원본도 이제 같은 effect 컴포넌트다)
- ScreenEffect.set_timeline_property 가 &TimelineValue 를 받는다. (원본처럼 숫자, 문자열, 참거짓, 참거짓은 숫자로 1 과 0) TimelinePropertyTarget 도 값을 글로 바꾸지 않고 넘긴다. (공개 API 가 바뀐다)
- HumanSkinRenderer: 원본 humanskinrenderer.js 를 옮겼다. 피부(주름 맵, 마이크로 노멀, 높이 디테일, 이중 로브 GGX, 잔털), 눈(각막 굴절 시차, 홍채, 림버스), 머리카락(Kajiya-Kay 이방성, 흔들림, 컷아웃과 프린지 2 패스), 차폐, 유체를 셰이딩 모드로 나눈 한 셰이더다. GLSL 은 원본과 같다. 조도, 알베도, 스펙큘러, 노멀을 MRT 4 장으로 내고 컷아웃 깊이 패스가 있다. SkinnedModelRenderer 를 품고 Deref 로 기반 함수를 그대로 부른다
- ToonView3D: 원본처럼 그리기 함수와 대체 그리기 함수(set_draw_callback, set_fallback_draw_callback, 클로저)를 받고 set_renderer, get_renderer 로 여러 노드가 렌더러 하나를 나눠 쓴다. (Rc<RefCell
>) 타입 인자 없이 get_component_mut:: () 로 꺼낸다. ToonViewDrawer, ToonViewPass 는 없앴다. (공개 API 가 바뀐다) - Graphic::run_external_pass: pass 가 패닉해도 드롭 가드가 2D 상태를 되돌린다
- ToonRenderer, SkinnedModelRenderer, HumanSkinRenderer: 그림자를 받지 않을 때 섀도우 유닛에 1x1 비교 깊이 텍스처를 묶는다. (맥 드라이버의 "UNSUPPORTED (log once) ... sampler type (Depth)" 알림이 나던 까닭, 유니폼을 채우는 차례는 까닭이 아니었다) SkinnedModelRenderer::get_empty_shadow_texture
- ToonRenderer: set_shadow 가 원본처럼 (ShadowMap 이나 None, 세기) 를 받는다. destroy, get_solid_program, get_outline_program, get_depth_program, extract_frustum_planes
- ToonVfx: 빛 파티클과 빛 점의 rim, 리본과 번개의 번짐 색 glow, set_rim_color, 사는 동안 다시 꺾이는 번개 add_lightning, 화면 섬광 add_flash(ToonFlashOptions), 엔진 Shaker 로 셈하는 카메라 흔들림 add_shake, read_shake, is_shaking. set_ramps 가 "#rrggbb" 글과 [r, g, b] 를 둘 다 받는다(ToonRampColor). queue_lightning 이 count 0 이면 그리지 않는다. seed 는 Option. 예제 toonfx 에 보인다
- SkinnedModel: 기본 모프 가중치를 glTF 노드 weights 에서 읽는다. 화면 공간 효과의 destroy 가 풀스크린 패스도 지운다. ToonScreenOutline: get_line_target(ToonLineTarget), read_outline_radius
- Camera2D: 회전(set_rotation, get_rotation, 도). apply_transform, screen_to_world, world_to_screen, pan_by_screen, fling, zoom_at 이 회전을 따르고, 경계 클램프는 돌아간 뷰를 감싸는 상자(get_visible_half_extent)로 잰다. convert_screen_delta_to_world, begin, end
- Action: condition 스텝의 콜백은 ActionConditionCallbacks 다. (updated 가 원본처럼 대상만 받는다) repeat 0 번은 돌지 않는다
- Pane, PaneStyle, PaneTheme(원본 web/pane.js): DOM 화면 분할 패널. 웹(wasm32) 빌드에만 있다. 가로나 세로로 자식 패널을 늘어놓고 사이 리사이저를 끌어 크기를 바꾼다. 크기는 PaneSize(Flex, Fixed 픽셀, Ratio 비율), 최소와 최대 크기, 끌 수 있는지와 가장자리(PaneResizableEdges), set_visible(숨기면 자리와 맞닿은 리사이저도 빠진다), reset_layout, refresh, attach_to, set_callback. PaneStyle::create 는 원본 프리셋(toolbar, panel, button, input, textarea, text)을 넣은 요소를 만들고, 스타일 이름은 CSS 이름(background-color)이다. PaneTheme 은 PaneTheme::COLOR_BACKGROUND 꼴 연관 상수다
- DevTools: 원본 F2 개발자 도구를 옮겼다. 창 안쪽 논리 좌표로 오른쪽 아래에 붙는 패널, 끌어 옮기기와 모서리, 꼭짓점, 구분선 크기 바꾸기, 탭 넷(Statistics, Node Hierarchy, Local Storage, Settings), 트리(펼치기, 액티브와 기즈모 칸, 고르기, 스크롤), 인스펙터, 설정 저장("hierarchy.settings"), 화면 비율 가이드, 모든 기즈모 강제 표시. 씬이 tick 에서 tick(engine, node_tree, time_delta), post_draw 에서 draw(engine, node_tree, graphic) 를 부른다. 인스펙터의 컴포넌트 속성은 UIDocument 가 저장하는 키와 값이고, 데스크탑의 로컬 스토리지 입력은 패널 안 입력 창이다. (웹은 원본처럼 window.prompt, window.confirm)
- UIDocument: serialize_component(node_tree, root_id, component). 등록한 컴포넌트 하나를 문서 데이터로 (등록하지 않은 종류는 경고 없이 None)
- UI 갈래: vanilla.js 와 UI 기능 차이를 없앤다. (원본에 없던 것은 vanilla.js 에도 넣었다)
- UINode(원본 ui/uinode.js), 오토레이아웃(ui/autolayout: LayoutSolver, LayoutVariable, LayoutExpression, LayoutConstraint, LayoutStrength, LayoutPriority, LayoutRelation, LayoutConstraintAxis, LayoutError, 원본 Kiwi 기반 솔버 12 파일), UIScene(원본 ui/uiscene.js)을 옮겼다. UINode 는 노드에 붙는 컴포넌트로, 솔버 값을 노드의 자리(부모 UINode 의 왼쪽 위 기준)와 content_size 로 옮긴다. intrinsic content size 는 Component::get_intrinsic_content_size(Text, RichText, UILabel)를 모으고, 바뀌면 스스로 제약을 다시 건다. 솔버가 예외를 던지는 곳은 Result<(), LayoutError> 다
- UIScene 트레이트와 UISceneBase, ui_scene! 매크로: 솔버, 화면 가이드(screen_node), 세이프 에어리어 가이드(safe_area_layout_guide), tick 마다 트리의 UINode 에 솔버를 붙이고 풀어 노드에 옮긴다. 공통 틀(로딩, 터치, 개발자 도구)은 GameSceneBase 를 품는다
- GameScene 트레이트와 game_scene! 매크로: 원본 GameScene 을 상속해 덮어쓰는 꼴. 바탕을 먼저 부르고 씬의 같은 이름 함수(load_assets, initialize, layout, tick, pre_draw, draw, post_draw)를 부른다. layout 은 resize 와 뷰 크기 변화 때 바탕이 부르고, post_draw 의 페이드 막과 개발자 도구는 바탕이 그린다. GameSceneBase 함수를 직접 부르는 길도 그대로다
- GameSceneBase: resize 가 게임 영역 기준(apply_play_area_reference)을 스스로 다시 건다. (씬이 부르지 않아도 된다, resize 는 &Engine 을 받는다) tick 은 &Engine 을 받는다
- GameSceneBase: set_play_input_handler(Box<dyn FnMut(PlayInput)>) 로 원본처럼 UI 가 받지 않은 입력을 처리기로 받는다. (모으기 set_play_input_enabled, take_play_inputs 와 함께 쓸 수 있다) fade_screen_with_hold(on_dark) 는 on_dark 가 손잡이를 받아 두었다가 놓는 콜백 꼴이다. (원본 Promise 의 resolve 자리) get_loading_drawer, draw_screen_fade, get_dev_tools, get_dev_tools_mut
- GameSceneBase: EngineConfiguration::use_dev_tools(기본 true)면 initialize 에서 DevTools 를 만들고 tick 이 넘기고 post_draw 가 그린다. 판 위의 입력은 UI 와 놀이로 넘기지 않는다. (is_dev_tools_capturing_input 은 엔진을 받는다)
- GameSceneBase: 휠이 창 층(UIWindowLayer) 안을 가리키면 원본처럼 맨 위 창이 먼저 받고, 받지 않으면 그 자리의 스크롤 뷰가 받는다. (UIWindowLayer::scroll_window_at, find_scroll_view_at, find_window_layer_of) TouchRecognizer: tick_wheel, tick_pointer, mark_wheel_handled 로 나눴다. (tick_touch 는 그대로)
- UIWindowLayer: 닫는 움직임이 끝난 창 노드를 지우지 않고 층에서 떼어 내 원본처럼 같은 창을 open_window 로 다시 띄울 수 있다. (층의 자식이 아니면 붙인다)
- UIWindow: handle_wheel(node_tree, view_input_position, wheel_delta), UIWindowBehavior::handle_wheel 이 원본처럼 자리를 받는다. get_panel_paint(_mut), get_dim_paint(_mut), get_view_width, get_view_height, get_margin, get_panel_height, get_panel_rect, get_panel_scale
- UIConfirmWindow: 묻는 글의 줄 수를 Graphic 없이 처음 놓을 때부터 잰다. (등록된 글꼴로 재는 textstringtexturecache::measure_text_without_graphic, Text::wrap_lines_without_graphic, wrap_text_to_lines_by) set_button_texts, refresh_if_open_in_tree, set_title_in_tree, set_message_in_tree
- Text: 글자 크기, 이름, 굵게, 기울임을 바꾸면 한 줄 글의 그리는 폰트 문자열도 바로 바꾼다. (지금까지는 맞출 너비나 밑줄이 없으면 처음 32px 로 그렸다)
- UIListView: set_template_node(node_tree, template_id) 가 원본처럼 템플릿을 UIDocument 로 직렬화해 두고 복제한다. 게임 컴포넌트는 set_template_node_with_document 에 등록한 UIDocument 를 넘긴다
- UILabel: set_visible_character_count, get_visible_character_count. UIProgressRing::get_perimeter_points. attach_button_motion, attach_toast_motion
- UIInputField: set_use_dominput, is_using_dominput 을 러스트 이름 규칙대로 set_use_dom_input, is_using_dom_input 으로 바꿨다 (원본 setUseDOMInput)
- 글자, 글꼴을 원본(vanilla.js, 브라우저 Canvas2D)과 맞췄다:
- 글자 모양 짓기(core/textshaping.rs): 양방향 정렬(unicode-bidi)과 글자 모양 잇기(rustybuzz)로 오른쪽에서 왼쪽 글(아랍어 글자 잇기, 히브리어)과 섞인 글, 합자, 커닝, 결합 부호를 브라우저처럼 그린다. 모든 글이 이 길을 지난다
- 글자 방향: Graphic.set_text_direction, get_text_direction, resolve_text_direction, TextDirection(Inherit, Ltr, Rtl, Auto), detect_text_direction. resolve_text_align(text_align, text_direction) 은 원본처럼 방향을 받는다. (공개 API 를 바꾸는 일이다) 구운 글자의 키에 문단 방향이 든다. Text, RichText, UILabel, ShadowText 의 set_text_direction, get_text_direction. RichText 는 오른쪽에서 왼쪽 문단이면 조각을 오른쪽부터 놓는다
- 글꼴 얼굴: 이름 하나 아래에 굵기, 기울기, 글자 범위(unicode-range)가 다른 얼굴을 여럿 올린다. (TextStringTextureCache.register_font_face, unregister_font_face, set_font_face_order, clear, FontFaceDescriptors, Engine.register_font_face_when_loaded, unregister_font_face, set_font_face_order, clear_text_cache, FontAsset.load_font_with_descriptors, unload) 고르기는 CSS 차례(기울기, 굵기)를 따르고 나중에 올린 얼굴이 먼저다. 폰트 문자열의 숫자 굵기(500 등)를 읽는다
- 가짜 기울임은 Chromium 과 같은 기울기 1/4 (전에는 0.2), 가짜 굵게는 Skia 와 같은 두께(9px 이하 크기의 1/24, 36px 이상 1/32)로 글리프마다 입힌다. 기울인 얼굴, 굵은 얼굴이 있으면 그것을 쓴다. 웹의 default_font_url 글꼴은 보통 굵기로만 올려 굵은 글이 가짜 굵게가 된다. (원본과 같다)
- 얼굴을 올리면 그 이름과 글자 범위에 든 구운 글자만 버린다. (원본 invalidateFontFaces) ShadowText 도 글꼴이 올라오면 다시 굽는다
- 대체 글꼴: 데스크탑은 등록된 어느 글꼴에도 없는 글자가 나오면 EngineConfiguration.fallback_font_paths 의 시스템 글꼴을 앞에서부터 읽어 쓴다. (원본 브라우저의 시스템 글꼴 대체 자리) 웹은 올린 글꼴에 없는 글자를 브라우저 시스템 글꼴 조각으로 그린다. 결합 부호는 묶음을 모두 가진 얼굴로 그린다
- 웹에서 글꼴 바이트가 없어도 ShadowText 와 DynamicFont 가 브라우저 시스템 글꼴로 굽는다. (전에는 그림자 없이 그렸다)
- TextMetrics 에 actual_bounding_box_left, right, ascent, descent 를 더했다
- 줄바꿈(Text.wrap_text_to_lines): 원본과 같은 차례로 공백, 낱말 사이(공백 없는 한중일, 태국어), 글자 묶음으로 나눈다. 낱말은 데스크탑 ICU4X(icu_segmenter), 웹은 원본처럼 브라우저 Intl.Segmenter. 한글 덩어리는 브라우저처럼 따로 한 낱말이다. split_graphemes, split_words, segment_words, count_graphemes, find_grapheme_prefix_length, wrap_text_to_lines_with(재는 함수를 받는다)
- 표시 글자 수(set_visible_character_count)와 Typewriter 는 글자 묶음 단위로 센다. (이모지 묶음, 결합 부호가 쪼개지지 않는다) Typewriter 의 글자 공개 알림은 (&str, 번호) 를 받는다. (공개 API 를 바꾸는 일이다) UILabel 에 set_visible_character_count, get_visible_character_count 를 더했다
- Text: measure_wrapped_size(TextWrappedSize), calculate_intrinsic_content_size, calculate_text_bounds (원본 measureWrappedSize, getIntrinsicContentSize, calculateTextBounds)
- ShadowText: get_font_family, get_font_size, is_bold
- DynamicFont, GlyphInfo (misc/dynamicfont.rs, 원본 misc/dynamicfont.js): 글자를 아틀라스 한 장에 모아 굽고 잘라 그린다. build_atlas, rebuild_atlas, draw_text, measure_text, get_glyph, clear_atlas
- uifont (misc/uifont.rs, 원본 misc/uifont.js): 여러 문자의 글꼴 조각을 한 이름 아래 글자 범위로 올리고, 고른 언어의 묶음을 라틴 바로 앞에 두며, 쓸 글자의 조각만 받는다. load_ui_font, update, apply_ui_font_group, load_ui_font_text, request_ui_font_text, is_ui_font_ready, read_ui_font_face, build_ui_font_string, configure_ui_font(UiFontOptions), read_ui_font_family
- languagepack (misc/languagepack.rs, 원본 misc/languagepack.js): 자산의 JSON 언어 목록과 언어 표. load_language_list, load_language, apply_language_setting, update, is_loading, match_language_tag, resolve_language_code, translate, format_text, read_text_direction, isolate_text, mirror_layout_x, read_layout_text_align, read_all_texts, set_language_paths, set_document_title_key(웹은 탭 제목과 html lang, 데스크탑은 창 제목), set_language_loaded_handler, set_language_list_from_json, set_language_texts_from_json
- Color::from_cache: 1024 개를 넘으면 통째로 비우던 것을 원본처럼 가장 오래 안 쓴 것부터 버린다. get_cached_color_count
- Localization: 이름 자리 무리의 빗금 앞뒤 빈칸을 원본처럼 모든 빈칸 글자로 본다
- 새 의존성: rustybuzz, unicode-bidi, unicode-segmentation, icu_segmenter(데스크탑). 웹 wasm 이 커졌다 (uigallery wasm-bindgen 뒤 1.14 MB → 1.93 MB, gzip 0.40 MB → 0.68 MB)
- 코어, 플랫폼, 기반을 vanilla.js 와 맞췄다. (원본에 있는데 러스트 판에 없던 것과 다르게 옮긴 것, 러스트 판에만 있던 범용 기능은 vanilla.js 에도 넣었다)
- SoundSystem 을 원본 쓰임으로 바꿨다. (공개 API 를 바꾸는 일이다) SoundSystem::new(engine, sound_table), update(), play_effect(sound_id, volume, pan), play_music(sound_id, fade_seconds, is_resumed) 가 엔진과 시간을 받지 않는다. 음악과 효과음 크기는 원본처럼 0.05 초를 시간 상수로 따라가고, 같은 소리 간격과 다시 깨우기는 벽시계로, 줄이기와 음악의 멈춘 자리는 AudioContext 시계로 센다. 줄여 끄는 효과음에 fade_out_effects 를 다시 걸면 지금 크기에서 새로 줄이고 목록에서 뺀다. (stop_effects 와 수 제한에 들지 않는다) 배경음악 첫 파일을 받지 못했으면 틀지 않는다. load_sound, get_external_mute_provider, get_autoplay_allowed_provider(공급 함수는 Rc<dyn Fn() -> bool>), get_audio_manager, 함께 쓰는 소리 set_sound_system, read_sound_system 을 더했다. 러스트 판에만 있던 set_page_hidden 과 fade_out_music 은 뺐다. (엔진 페이지 이벤트와 play_music("", 초)로 같다)
- AudioManager: Clone(같은 AudioContext 를 보는 손잡이), get_context_time, get_audio_context, is_context_running 공개. AudioPlayer: get_audio_context. 오디오 백엔드에 get_audio_context_time
- math: 원본 이름 floor, ceil, sqrt, abs, sin, cos, tan, asin, acos, pow. round 는 원본처럼 무한대를 그대로 둔다. (전에는 NaN)
- Color: to_rgba_string, to_hex_string(원본처럼 알파가 1 미만일 때만 붙인다, 러스트 판의 to_hexstring 을 원본 이름으로 바꿨다), from_hex_cached. Version: get/set 접근자, get_version_string. TransformMatrix: copy_from, write_to_array 를 원본 이름 write_to_float32_array 로 바꿨다
- 데스크탑 렌더 배율 상한이 실제로 먹는다. 기본 프레임버퍼의 왼쪽 아래에 줄인 크기로 그리고 프레임 끝에 창 크기로 늘인다. (platform/desktop/renderscaler.rs) 상한을 바꾸면 다음 프레임에 다시 맞춘다
- EngineConfiguration: auto_resize_on_window_resize(웹, 끄면 페이지의 캔버스 크기, 러스트 판 기본은 켬), preserve_drawing_buffer(웹 컨텍스트), ignore_virtual_keyboard_resize(웹 화면 키보드), max_canvas_aspect_ratio(웹은 원본처럼 캔버스를 줄여 가운데, 데스크탑은 창 가운데에 그리고 나머지는 검게). 웹은 visualViewport 크기를 쓴다
- 데스크탑 페이지 이벤트: 창이 가려짐, 최소화(크기 0, is_minimized), 앱 멈춤을 합쳐 Hidden 과 Visible(+ on_page_visibility_restored)을 낸다. (윈도우는 최소화로 알린다) 시스템 잠자기에서 깨면(벽시계가 단조 시계보다 2 초 넘게 더 흐름) on_page_process_restored
- 데스크탑의 페이지 쿼리 값은 환경 변수 VANILLA_ 뒤 대문자 뱀꼴이다. (VANILLA_SAFE_AREA=44,0,34,0, VANILLA_QUALITY=lite) 입력 좌표는 창의 배율로 바꾼다. (렌더 크기와 상관없다)
- ViewManager: convert_client_to_view, get_client_native_size. 플랫폼 층에 read_canvas_client_position, read_client_native_size, save_capture_file
- 입력: 원본처럼 처음에는 어느 마우스 단추든 터치이고 set_touch_from_left_button_only 로 왼쪽만, set_context_menu_prevented(웹 오른쪽 클릭 메뉴), find_touch_point, is_touch_button. touch_moved 는 원본처럼 누를 때 켜고 뗄 때 끈다. (전에는 프레임마다 지웠다) Scene 과 TouchRecognizer 는 원본 tickTouch 차례로 뗌을 먼저 보고, 누른 프레임에는 Moved 를 넘기지 않는다. 창이 포커스를 잃으면 뗌으로 넘긴다. 데스크탑에서 창 밖으로 나가도 끌기를 끊지 않는다
- Scene: finalize, unload 훅(내릴 때 finalize, unload, destroy 차례), 씬의 터치 훅 touch_press, touch_move, touch_release, touch_cancel, touch_wheel(엔진이 tick 뒤 원본 차례로 부른다). Engine.unload_scene 은 &SceneBase 도 받는다
- Engine: 첫 프레임 번호를 원본처럼 1 로, request_frame_capture(PNG 바이트를 넘김, FrameCaptureHandler), 웹 화면 저장을 원본처럼 주소 쿼리 capture, captureName, captureExit 로 걸고 내려받기로 저장, remove_page_event_listener, resize, get_canvas, is_text_input_focused, request_asset_bytes_with_cache
- 노드: 원본 Node 의 set_parent, remove_child, remove_child_at, remove_children, remove_child_by_name(떼기만 하고 지우지 않는다), find_child, find_child_recursive, find_child_recursive_by_name, is_root, is_leaf, has_parent, has_child, get_child. 원본 TransformNode 의 전역 get/set_position, get/set_scale, get/set_rotation, get_opacity(NodeTree). get_or_add_component, get_components. Component.require(RequiredComponent, 붙기 전에 없으면 기본값으로 붙인다), detach(remove_component 가 부른다)
- AssetLoader: 다 받은 그림을 원본처럼 풀어 보고 깨진 것은 실패 목록에 넣는다. 푼 그림은 손잡이(AssetLoadHandle.get_decoded_image)에 담아 ImageAsset 이 다시 풀지 않는다
- TextAsset, JsonAsset: set_no_cache, is_no_cache(웹 fetch 의 cache: no-cache). FontAsset: load_font_from_bytes, load_font_from_bytes_with_descriptors(원본 loadFontFromBytes, 글꼴 얼굴 서술자 그대로)
- SpriteAtlas: 찾을 아틀라스 목록 add_search_atlas, remove_search_atlas, clear_search_atlases, find_frame, apply_search_frame(Rc<RefCell
>), get_page_images - BuildInfo: new() 와 set_version_json_path, is_loaded(load 전 거짓), read_meta_text 는 인스턴스 함수, 빌드 때 판은 set_package_version 으로. (BuildInfo::new(판) 을 바꾸는 일이다)
- PointerCursor: get_button_cursor_name, get_default_cursor_name, is_coarse_pointer. FrameProbe: 설정 반환 함수들. Platform: is_coarse_pointer, get_safe_area_rect, get_resouce_usage(원본 이름 그대로). Identifier(원본 차례 번호, reset 은 처음 번호로, 원본은 아무것도 하지 않던 버그)
- Localization.text_named: 빗금 앞뒤 빈칸을 원본 정규식 \s 처럼 탭과 줄바꿈까지 받는다. WebSocketClient.disconnect: 원본처럼 닫기만 걸고 다음 tick 에 끊긴 것으로 친다
- GameScene, UIScene 트레이트에 finalize, unload, on_page_process_restored, on_page_visibility_restored, 씬의 터치 훅(touch_press, touch_move, touch_release, touch_cancel, touch_wheel)을 더하고 game_scene!, ui_scene! 이 Scene 의 같은 함수로 넘긴다. (원본 GameScene, UIScene 하위 클래스가 덮어쓰던 것)
- 콜백 게터(원본 이름): UIButton.get_click_event, get_pressed_event, get_released_event, get_clicked_event, get_hover_event, UISlider.get_value_changed_event, UIToggleButton.get_toggled_event, ButtonMotion.get_lit_handler. 받은 콜백을 Rc
에 담고 게터는 그 Rc 를 돌려준다. 부르는 쪽은 borrow_mut 로 빌려 부른다. (set 쪽은 그대로 Box 를 받는다) 엔진도 그 Rc 를 하나 더 쥐고 부르므로 콜백이 이벤트를 새로 정해도 되고, 부르는 동안 같은 이벤트를 다시 부르면 건너뛴다. GameSceneBase.get_loading_drawer(전에는 부를 수 없는 &Box)와 WebSocketClient.get_receive_event(전에는 &mut self 의 &mut)도 같은 꼴로 바꿨다 - AudioBus(원본에도 같은 꼴로 넣었다): AudioManager.create_audio_bus, AudioBus.create_audio_player(그 버스로 트는 플레이어), set_volume, get_volume, mute, unmute, is_muted, is_available, get_gain_node(웹만). 데스크탑은 kira 메인 트랙 아래 하위 트랙(버스로 만든 플레이어의 트랙은 그 아래), 웹은 출력에 이은 GainNode 다. 크기와 음소거는 AudioPlayer 와 같은 규칙이다
- LocalStorage.get_backend, PersistedStore.get_storage_backend(원본 getBackend, getStorageBackend): 갈아 끼운 저장소를 Rc<RefCell<Box
>> 로 돌려준다. 그 대신 위의 has_backend, has_storage_backend 는 뺐다. (get_backend().is_some() 으로 본다) 꺼낸 저장소를 빌린 채로 LocalStorage 를 부르면 기본 저장소를 쓴다 - SafeAreaInsets { top, right, bottom, left }(원본의 인셋 객체): ViewManager.set_safe_area_override, get_safe_area_insets, GameSceneBase.set_safe_area_insets, calculate_safe_area_rect 가 [위, 오른쪽, 아래, 왼쪽] 배열 대신 이것을 받고 돌려준다. GameSceneBase.calculate_play_area_reference_length(fixed_length, is_landscape, canvas_native_size, safe_area_insets, inset_scale) 는 원본처럼 뷰 좌표 인셋과 캔버스 단위 배율을 받는다. (전에는 배율을 곱해 둔 인셋 배열)
- EngineConfiguration.auto_resize_on_window_resize 의 기본을 원본처럼 끔으로 바꿨다. 웹에서 캔버스를 창에 맞추려면 켠다. (예제와 README 에 켬을 적었다, 데스크탑은 늘 맞춘다)
- Platform.get_resource_usage: 바른 이름을 더했다. 옛 이름 get_resouce_usage 는 같은 함수를 부르는 별칭으로 남긴다. (원본에도 getResourceUsage 를 더했다)
- Color: From<&str> 이 원본 Graphic 의 parseColorValue 처럼 from_cache 를 거친다. from_hex_cached 도 from_cache 처럼 1024 개를 넘으면 가장 오래 안 쓴 것부터 버린다. (전에는 1024 개에서 통째로 비웠다, 원본 fromHEXCached 에도 같은 규칙을 넣었다) 두 캐시 모두 가장 오래 안 쓴 것을 훑지 않고 바로 찾는다
- UIToggleButton.get_clicked_event: 원본(UIButton 에서 물려받은 getClickedEvent)처럼 토글 버튼 안쪽의 클릭 처리 함수를 돌려준다. 부르면 켜짐을 뒤집고 토글 이벤트와 클릭됨 이벤트를 부른다
- 웹: 툰 3D 가 앞의 GL 상태를 원본처럼 돌린다. glow 웹 컨텍스트는 묶인 것이 없을 때(null) 읽으면 패닉해서 지금까지 웹은 앞의 프레임버퍼를 읽지 않고 기본 프레임버퍼로 돌렸다. 웹 플랫폼 층이 WebGL2 컨텍스트를 함께 들고 null 인지 먼저 보고(platform::is_gl_binding_present), 묶인 것이 있을 때만 glow 로 읽는다. (core::graphic 의 read_framebuffer_binding, read_texture_binding, read_program_binding, read_vertex_array_binding, graphics3d 가 다시 내보낸다)
- ToonRenderer 의 end_shadow_pass 와 ToonScreenOutline 의 end_line_ids, draw_outline 이 웹에서도 앞의 프레임버퍼로 돌린다. 웹에서 그림자 패스를 ToonPostProcess.begin 앞에 해야 하던 제약이 없어졌다. ToonScreenOutline 이 선의 판을 지은 뒤 앞의 텍스처도 돌린다
- ToonRenderer, ToonScreenOutline, ToonVfx 가 원본처럼 앞의 셰이더 프로그램과 버텍스 어레이로 돌린다. (지금까지는 데스크탑도 풀어 두었다)
- Graphic 이 놓은 픽셀을 텍스처에서 되읽을 때(ShadowImage) 웹에서 기본 프레임버퍼가 묶여 있으면 같은 까닭으로 패닉하던 것을 고쳤다
- 예제 toonshowcase: HDR 타겟(ToonPostProcess.begin)을 건 뒤 그림자 패스를 그린다. end_shadow_pass 가 HDR 타겟으로 돌아오는 것을 데스크탑과 웹에서 같게 본다
- ToonInstance.line_id: 인스턴스마다의 화면 공간 바깥선 번호. (원본 instances[i].lineId, None 이면 공통 번호, ToonRenderer 는 읽지 않는다) ToonInstance::default() (단위 행렬, 흰 틴트, 번호 없음). ToonScreenOutline::draw_mesh_instanced 의 line_id_list 인자를 뺐다. (공개 API 를 바꾸는 일이다, 원본과 같은 쓰임) ToonInstance 를 구조체 꼴로 짓는 코드는 line_id 를 주거나 ..ToonInstance::default() 를 붙인다. 예제 toonfx, toonshowcase, toonview 를 고쳤다
- 색 이모지: 글꼴의 색 글리프를 제 색으로 굽는다. (core/colorglyph.rs, 지금까지 데스크탑은 fontdue 가 색 글리프를 그리지 못해 흑백이나 빈칸이었다) 원본(브라우저 Canvas2D)처럼 흰 글자 위에 제 색으로 굽고 그릴 때 글자 색이 곱해진다
- 비트맵: sbix (Apple Color Emoji), CBDT/CBLC (Noto Color Emoji 비트맵 판)의 PNG 와 프리멀티플라이드 BGRA. 그 글리프를 가진 판 가운데 글자 크기 이상인 가장 작은 판을 골라 넓이 평균으로 줄인다. (Apple Color Emoji 는 판마다 빠진 글리프가 있다)
- 윤곽: COLR/CPAL v0 과 v1. ttf-parser 의 Painter 로 받아 넓이 누적 래스터, 한 색과 선형, 두 원 방사, 스윕 그라데이션(Pad, Repeat, Reflect), 변환, 자르기, 28 가지 합성을 직접 칠한다. 크롬처럼 OT-SVG 는 그리지 않는다
- 크롬과 같게: 가짜 기울임은 색 글리프에도 입히고 가짜 굵게는 입히지 않는다. 외곽선(Stroke)으로 구울 때 색 글리프는 테 없이 색 그대로 얹는다. ShadowText 는 이모지에 글자 색의 알파만 곱하고 그림자는 이모지 모양까지 드리운다. DynamicFont 아틀라스도 색 글리프를 제 색으로 굽는다. (맥 크롬 Canvas2D 로 확인)
- 얼굴 고르기: 이모지 표시 묶음(VS16 FE0F, Emoji_Presentation, 피부색, 국기, 키캡, 태그, 이음 문자 묶음)은 색 글리프를 가진 얼굴을, 그 밖(맨 ❤, VS15)은 색이 아닌 얼굴을 먼저 고른다. 크롬도 지정한 글꼴에 흑백 ❤ 가 있으면 ❤️ 는 색 이모지 글꼴로, 맨 ❤ 는 그 글꼴로 그린다. 웹에서 올린 글꼴에 색 글리프가 없으면 이모지 표시 묶음은 브라우저 조각(색 이모지)으로 둔다. (textshaping::is_emoji_presentation, unicode-properties 의 emoji 기능을 켰다)
- 대체 글꼴: EngineConfiguration.fallback_font_paths 기본값에 C:/Windows/Fonts/seguiemj.ttf, /System/Library/Fonts/Apple Color Emoji.ttc, /usr/share/fonts/truetype/noto/NotoColorEmoji.ttf 를 더했다. 후보는 더할 때 파일 머리의 표 목록만 엿봐 색 글리프 표(sbix, CBDT, COLR)가 있는지 적어 두고, 이모지 표시 글자는 색 후보를, 그 밖의 글자는 색이 아닌 후보를 먼저 읽는다. (190MB 남짓한 Apple Color Emoji 를 한중일 글자 때문에 읽지 않는다)
- GlyphRaster.color_pixels, TextRaster.color_pixels (색 글리프 몫, 프리멀티플라이드 RGBA). coverage 는 색 글리프를 뺀 글자의 덮인 정도다. 구조체에 필드가 늘어 직접 짓는 코드는 고쳐야 한다
- 최종 대조의 코어, 플랫폼 몫을 원본과 같게 맞췄다.
- 씬: 불러오면 create 바로 뒤에 루트를 원본 Scene.load 처럼 뷰 크기로 맞춘다. (자리 0, 왼쪽 위 피벗, 콘텐츠 크기는 뷰 크기) 맡긴 애셋이 다 끝난 뒤에도 원본 SceneManager.loadScene 처럼 로딩 화면(draw_on_load)을 0.3초 더 보이고 initialize 를 부른다.
- Engine.get_all_loaded_scenes (원본 SceneManager.getAllLoadedScenes, 씬 대신 SceneId 핸들), SceneBase.has_ever_touched (원본 Scene.hasEverTouched), Engine.dispatch_page_event 를 공개했다.
- 트윈: 대상 노드가 처음 돈 때의 노드 트리에서 떨어지면(맨 위 노드가 달라지면) 원본처럼 콜백 없이 끝난다. (지울 때만 끝나던 것) Tween::find_root_node (원본 Tween.findRootNode)
- 웹 최대 FPS: 원본처럼 세기 시작한 뒤의 프레임 수로 차례를 정한다. (platform/framelimiter.rs, 90 Hz 에서 60 FPS 가 45 가 되지 않는다)
- 웹 exit_application: 원본처럼 Capacitor 의 App.exitApp, 없으면 window.close 를 시도한다. (platform::exit_application)
- 웹 GL 컨텍스트: 캔버스의 webglcontextlost, webglcontextrestored 에서 원본 WebGLStateCache 처럼 GL 상태 기억을 잊는다. (reset_gl_state_cache)
- 데스크탑 Engine.is_text_input_focused: 늘 false 이던 것을 엔진 입력 필드의 포커스로 본다. (InputManager.is_typing_in_text_field 와 같다)
- 클립보드: Engine.read_clipboard_text_with_callback (원본 readClipboard 의 then 자리, 웹은 navigator.clipboard.readText 뒤, 데스크탑은 그 자리에서). 웹 UIInputField.paste 를 코드로 불러도 원본처럼 비동기로 읽어 붙인다. (예전에는 웹에서 아무것도 하지 않았다)
- 데스크탑 그림 커서: PointerCursor.register_image_cursor 의 그림을 winit CustomCursor 로 만든다. (맥은 1 배 그림, 윈도우와 리눅스는 창 배율로 늘이고 2 배 그림이 있으면 그것) CursorValue 에 image_url, image_url_2x, hotspot_x, hotspot_y 가 늘었고 platform::set_cursor 는 CursorValue 를 받는다.
- 데스크탑 키: winit 의 SuperLeft, SuperRight 를 W3C 의 MetaLeft, MetaRight 로, winit 의 Meta 를 Super 로 넣는다.
- KeyCode: 원본의 구두점(SEMICOLON 들), SCROLLLOCK, META, COMMAND, PAUSE, 오디오 7(AUDIOVOLUMEUP 들), NUM_LOCK, 텐키 16(NUMPAD_DIVIDE 들, NUMPAD0 ~ NUMPAD9)과 원본 이름 ARROWLEFT, ARROWUP, ARROWRIGHT, ARROWDOWN 을 더했다. (LEFT 들은 남긴다)
- 원본 버그를 같이 고쳤다: 음소거 키 값 "AudioMute" 는 W3C code 표에 없는 이름이라 눌러도 맞지 않았다. "AudioVolumeMute" 로 고쳤다.
- 게임패드: 웹은 gilrs 대신 원본처럼 navigator.getGamepads() 를 직접 읽어 브라우저가 주는 버튼과 축을 모두 받고(17, 4 개로 자르던 것), 연결과 해제는 gamepadconnected / gamepaddisconnected 로 받는다. 데스크탑은 표준 17 버튼, 4 축 뒤에 gilrs 가 표준으로 잇지 못한 단추와 축을 처음 움직인 차례로 붙인다. (gilrs 는 장치의 단추 목록을 주지 않아 처음 움직인 뒤에야 생긴다) 버튼, 축 수가 늘면 상태 칸을 늘린다. gilrs 는 데스크탑 의존만 된다.
- 스팀덱: 데스크탑 리눅스에서 환경 변수 SteamDeck=1, 또는 DMI 의 board_vendor Valve 와 board_name Jupiter, Galileo 면 PlatformType::SteamDeck 이다.
- 데스크탑 Platform.get_resource_usage: 비어 있던 것을 엔진이 애셋으로 읽은 파일(애셋 바이트 읽기, Engine::load_image, 오디오 파일, 그림 커서)로 채운다. (종류 "file", 전송량과 푼 크기는 파일 바이트 수)
- 윈도우 잠자기 깸: 시계 차이 판정(윈도우는 단조 시계가 잠든 동안에도 흘러 맞지 않았다) 대신 창을 서브클래싱해 WM_POWERBROADCAST 의 PBT_APMRESUMEAUTOMATIC 을 받아 on_page_process_restored 를 부른다. (platform/desktop/windowsplatform.rs, 윈도우만 windows-sys 0.52 의존) 맥과 리눅스는 시계 차이 판정 그대로다.
- 데스크탑 is_coarse_pointer: 윈도우는 크로미엄의 (pointer: coarse) 판정을 옮겼다. (태블릿으로 쓰는 중이거나 마우스 없이 터치만 있으면 참) 맥은 크로미엄도 늘 거짓, 리눅스는 처음엔 장치 목록을 못 읽어 거짓이었다. (뒤에 읽게 고침, 아래 리눅스 항목)
- FiniteStateMachine: 처리 함수 안에서 get_state_change_requester 로 받은 StateChangeRequester.change_state 로 전이를 부탁하면 그 처리 함수가 끝난 뒤 차례대로 전이한다. (예전에는 처리 함수 안에서 전이할 수 없었다)
- format: 표에 없는 로캘은 원본이 브라우저 기본 로캘로 쓰듯 시스템 언어(웹 navigator.languages, 데스크탑 LANGUAGE / LC_ALL / LC_MESSAGES / LANG 의 첫째)로, 그것도 표에 없으면 en-US 로 쓴다.
- Color: create_from_hex 를 원본 createFromHEX 처럼 # 이 있어야 하고 #rgba 를 읽고 두 자리씩 parseInt 꼴로 읽는다. to_hex_string, to_rgba_string 은 원본처럼 0 ~ 1 밖의 성분을 자르지 않는다.
- TimeManager.set_time_scale: 원본처럼 음수도 그대로 받는다. (0 으로 자르던 것)
- EngineConfiguration.rebake_text_on_font_load (원본 rebakeTextOnFontLoad, 기본 끔): 켰을 때만 글꼴 얼굴을 올리면 그 얼굴의 글자로 구운 문자열을 버린다. (예전에는 늘 버렸다)
- NodeTree.get_world_corners, get_world_bounds (원본 WorldNode.getWorldCorners, getWorldBounds)
- Cooldown.r#use, FullscreenPass.r#use, ShaderProgram.r#use: 원본 이름 use 를 r# 로 그대로 쓴다. activate, use_program 은 같은 일을 하는 이름으로 남긴다.
- 최종 대조의 UI, 효과, 애니메이션, 3D 몫을 원본과 같게:
- GameSceneBase: 원본처럼 로딩 문을 뺀 맡긴 애셋이 다 끝나면(진행률을 알린 적이 있을 때) 진행률을 1 로 채운다. (complete_loading_progress_if_assets_finished, 전에는 맡긴 AssetLoader 가 끝나야 1) SceneBase::are_tracked_assets_finished_except, AssetLoadHandle::is_same_load
- DevTools: Statistics 의 clientNativeSize 를 ViewManager::get_client_native_size 로, 웹 메모리를 원본처럼 Chrome 의 performance.memory 로 적는다. (데스크탑과 없는 브라우저는 (N/A)) set_ui_document, get_ui_document_mut 로 게임이 컴포넌트를 등록한 UIDocument 를 인스펙터에 건다
- UIDocument: ShadowText 를 원본 반사 저장처럼 TextDirection, Italic, Underline, Strikethrough 까지 쓰고 읽는다. create_component(트리, 노드, 이름) 가 원본 getComponentType 자리로 그 이름의 컴포넌트를 지어 붙인다
- UIConfirmWindow: 오른쪽에서 왼쪽 언어면 원본처럼 제목과 묻는 글에 Rtl 방향을 건다. (아니면 Inherit, 다음 놓을 때) set_right_to_left_in_tree 는 원본처럼 글 방향을 바로 건다
- UIScrollView::set_shows_vertical_scroll_bar_in_tree, set_shows_horizontal_scroll_bar_in_tree: 원본처럼 그 자리에서 스크롤바 노드를 만들고 켜거나 끄고 핸들을 돌려준다
- UIInputField: 공개 함수의 글자 자리(get_cursor_index, get_selection_start, get_selection_range, move_cursor, measure_index_at_local_x)와 max_length 를 원본처럼 UTF-16 단위로 센다. (공개 API 의 셈이 바뀐다. 한글은 같고 이모지 같은 글자에서만 다르다) 안에서는 문자 단위로 들어 서로게이트 쌍을 쪼개지 않는다. 웹 DOM 의 maxlength 와 같은 셈이 되었다
- Timeline: 핸들러가 원본처럼 타임라인 자신을 받는다. 이벤트 (대상 이름, 이벤트 이름, 키, &mut Timeline, &mut NodeTree), 마커 (마커 이름, 마커, &mut Timeline, &mut NodeTree), 완료 (&mut Timeline, &mut NodeTree). 핸들러 안에서 pause, seek 를 부를 수 있다. (공개 API 를 바꾸는 일이다)
- Timeline: TimelineTarget::External 이 Rc<RefCell
> 를 들고, evaluate 가 원본처럼 그 자리에서 set_timeline_property 를 부른다. apply_external_properties 는 뺐다. get_external_properties 는 마지막 evaluate 가 건 값이다. TimelineTarget 은 Copy, Eq 가 아니다. (공개 API 를 바꾸는 일이다, 끝 tick 의 값 걸기와 완료 핸들러 차례도 원본과 같아졌다) 예제 timelineshowcase 는 ScreenEffect 를 Rc 로 쥔다 - Timeline: 글 속성(text, number, fontSize, visibleCharacters, color)을 원본처럼 RichText 노드에도 건다. 무대 스프라이트의 data: 주소는 브라우저처럼 본문의 퍼센트 꼴을 먼저 풀고, ;base64 가 아니어도 읽는다. emit 이벤트는 그 자리의 노드 위치로 낸다
- ParticleSystem::emit_in_tree(트리, 노드, 수, 보정), set_node_position: 월드 공간에서 원본처럼 낼 때의 노드 위치로 낸다. (emit 만 부르면 지난 tick 에 읽어 둔 위치)
- 3D URL 함수를 원본처럼 데스크탑과 웹 둘 다: FbxLoader::load_from_url(엔진, 애셋 경로) → FbxLoadHandle (get_scene_data), SkinnedModel::load_from_url, load_from_fbx_url → SkinnedModelLoadHandle (create_model(gl, 렌더러)), SkinnedModel::add_animations_from_fbx_url(엔진, 경로, 클립 이름, 이동 무시) → FbxLoadHandle (다 받으면 다음 update 나 play_animation 에서 클립을 더한다), Material::load_image_description(엔진, 경로, 옵션) → ImageDescriptionLoadHandle (get_image_description, mime_type 은 Material::find_image_mime_type 으로 확장자에서). 엔진의 애셋 받기를 써서 데스크탑은 애셋 폴더 후보에서, 웹은 asset_base_url 에서 받는다. 받기 손잡이는 SceneBase::track_load_handle 로 맡길 수 있다. 데스크탑에서 현재 폴더 기준으로 읽던 load_from_path, load_from_fbx_path, add_animations_from_fbx_path, 경로를 받던 load_image_description 은 뺐다. (공개 API 를 바꾸는 일이다) 예제 modelviewer 는 URL 함수로 받는다
- 데스크탑 찍기 모드(VANILLA_CAPTURE_PATH)는 창을 숨기고 돈다. 검증 도구가 예제를 찍을 때 사용자 화면에 창이 뜨지 않는다. 숨긴 창은 다시 그리기 요청과 수직 동기가 없어 about_to_wait 에서 프레임을 바로 돌고, 최대 FPS 가 없으면 모니터 주사율(모르면 60)로 보일 때와 같은 빠르기를 맞춘다. 가려짐 알림은 받지 않는다. 맥은 독 아이콘과 포커스도 가져가지 않는다(활성화 정책 Accessory). 창을 보려면 VANILLA_CAPTURE_SHOW_WINDOW=1. (맥에서 toonshowcase, uigallery, textshaping 을 숨긴 채 찍어 확인)
- 데스크탑 AudioContext 멈춤을 원본 suspend 처럼 했다. 컨텍스트를 만들 때 메인 트랙 아래 뿌리 트랙(원본 destination 자리)을 두고 플레이어, 버스, 비프를 그 아래에 달아, 멈추면 뿌리 트랙을 kira pause 로 세운다. 소리가 그 자리에서 서고 다시 돌리면 이어 울며, 컨텍스트 시계(get_context_time)도 서고 is_context_running 은 거짓이다. (전에는 메인 트랙을 무음으로만 두어 소리와 시계가 흐르고 늘 돌고 있다고 했다) AudioPlayer.play 는 원본처럼 멈춘 컨텍스트를 깨운 뒤 튼다
- AudioPlayer::new(audio_manager, output_node), AudioBus::new(audio_manager) 를 공개했다. (원본 new AudioPlayer(audioContext, outputNode), new AudioBus(audioContext)) 내보낼 곳(platform::audio::AudioOutputNode)은 웹 &AudioNode, 데스크탑 kira &mut TrackHandle 이다. AudioBus::get_gain_node 가 데스크탑에서도 버스 트랙(RefMut
)을 빌려 준다. (공개 API 를 바꾸는 일이다: 오디오 백엔드의 create, is_audio_context_running, play_beep_tone 이 매니저 상태를 받는다) - SoundSystem: 무리에서 고르기와 음 높이 흔들기가 고정 씨앗(SeededRandom 0x50f7) 대신 원본 Math.random 자리인 math::random(시각으로 씨앗)을 쓴다. SoundRow.maximum_voices 를 Option
로 바꿨다. (공개 API 를 바꾸는 일이다) None 이면 효과음 전체의 수까지, Some(0) 이면 원본처럼 하나만 난다. (전에는 0 이 12 였다) - 데스크탑 소리 파일: kira 의 flac, isomp4, aac 기능을 켜 FLAC 와 M4A(AAC)도 읽는다. (새로 받는 크레이트: symphonia-bundle-flac, symphonia-format-isomp4, symphonia-codec-aac 0.6.1)
- BeepPlayer 데스크탑 파형을 크롬 WebAudio OscillatorNode(PeriodicWave)와 같은 셈으로 그린다. 푸리에 계수를 1/3 옥타브마다 덜어 낸 두 표 사이를 섞어 대역을 제한하고, 배음을 다 둔 표의 꼭대기로 크기를 맞춘다. 헤드리스 크롬 OfflineAudioContext 로 그린 오실레이터(사각, 톱니, 삼각, 사인, 150 / 440 / 1000 Hz, 2048 샘플)와 가장 큰 차이가 0.0003 이다. (전에는 대역 제한 없는 사각파, 톱니파였다)
- WebSocketClient: 데스크탑 wss:// 를 연다. (ewebsock 의 tls 기능, rustls 0.23 과 ring 0.17 을 새로 받는다. 붙을 때 rustls 암호 공급자를 ring 으로 정한다) receive_message(원본 receiveMessage) 를 공개했다
- CameraGestures 를 원본 규칙대로: 두 손가락에서 하나가 되어도 모두 뗄 때까지 손짓이 이어지고(움직임은 쓰지 않음), 손가락 수가 바뀌면 기준을 다시 잡는다. set_thresholds 가 넷째 인자(흉내 낸 마우스를 무시하는 밀리초, 처음 800)를 받는다. (공개 API 를 바꾸는 일이다) is_touch_input(처음에는 기기가 손가락이 주된 입력인지), is_coarse_pointer, is_last_wheel_ctrl 을 더했다. InputManager.is_touch_input 의 처음 값도 기기가 손가락이 주된 입력인지다
- AssetLoader.add_font 가 굵기 대신 FontFaceDescriptors(굵기, 기울기, 글자 범위)를 받아 register_font_face_when_loaded 로 넘긴다. (원본 addFont descriptors, 공개 API 를 바꾸는 일이다)
- JsonAsset: 풀지 못한 JSON 은 원본처럼 읽히지 않은 것이다. (is_loaded 거짓, AssetLoader 의 실패 목록에 든다) get_text(원본 TextAsset 의 text) 를 더했고 get_data 는 &self 로 부른다
- PersistedStore: read_stored_text 공개. 섞기를 원본 Object.assign 처럼: 배열(저장된 state 가 배열이어도)은 번호 키로 섞고, 키 차례는 JS 객체처럼 번호 꼴 키를 작은 수부터 앞에 둔다. (전에는 배열 state 면 기본값이었다)
- LocalStorage: 수를 글로 바꾸기와 글을 수로 읽기를 원본 String(number), Number(text) 그대로 한다. 1e21 이상과 1e-7 이하는 1e+21 같은 지수로 쓰고, 0x, 0o, 0b 표기와 "1.", ".5", JS 빈칸을 원본처럼 읽는다. (node 로 찍은 값과 견줬다)
- Localization.detect_language, languagepack 의 기기 언어: 데스크탑은 sys-locale 0.3 으로 시스템 선호 언어 차례를 읽는다. (윈도우, 맥도 원본 navigator.languages 처럼, 전에는 LANG 같은 환경 변수만 읽어 윈도우는 늘 기본 언어였다)
- GraphicsQualityGovernor.apply_search_text 가 원본 URLSearchParams 처럼 + 와 %XX 를 풀고 빈 조각을 건너뛴다
- 컴포넌트에 노드 출력 상태 앞뒤 훅 push_transform, pop_transform 을 더했다. (자기 컴포넌트와 자식, 기즈모를 감싸서 불린다, 원본 노드가 pushTransform, popTransform 을 덮어쓰던 자리) TouchEffect 가 이 훅으로 원본처럼 자식까지 더하기 블렌드로 그린다. (전에는 자기 입자만)
- Graphic 블렌드 모드: source-over 로 대신 그리던 17 가지를 제대로 그린다. 이제 BlendMode 26 가지가 모두 된다 (원본과 같은 동작, 같은 셰이더 글)
- SourceOut, SourceAtop, DestinationAtop, Xor 는 W3C Compositing and Blending Level 1 의 포터 더프 계수 그대로 blend_func 로 건다
- Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity 는 그리기마다 그릴 영역(정점의 경계 상자)만 지금 프레임버퍼에서 blit_framebuffer 로 같은 형식, 같은 자리의 칸에 떠 와 셰이더로 섞는다. 공식은 W3C 그대로(분리 섞기, 비분리 섞기, Cs' = (1 - αb) x Cs + αb x B(Cb, Cs) 뒤 source-over 합성)이고 바탕 알파가 있는 렌더 타겟(RGBA8, RGBA16F)에서도 맞다. 같은 자리로 옮기므로 데스크탑의 멀티샘플 기본 프레임버퍼에서도 된다. Darken, Lighten 은 blend_equation MIN / MAX 가 반투명에서 W3C 식과 달라 셰이더로 섞는다
- 셰이더 섞기 모드에서는 묶어 그리지 않는다. 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번 (M2 Pro, 64x64 그림 1000 장에서 그리기 하나에 데스크탑 0.062 ms, 웹 0.061 ms 안팎, 대부분 복사가 렌더 패스를 끊는 값. source-over 를 묶지 않고 그리면 0.002 ~ 0.004 ms)
- 이미지, 도형, 글자, 나인슬라이스, 자르기, 파티클, 바꿔 끼운 셰이더(ShaderSprite) 모두 된다. 파티클은 서로 겹치지 않는 쿼드끼리 모아 한 번 떠 와 그려 쿼드마다 앞 쿼드 위에 섞인다. 바꿔 끼운 셰이더는 덧그림 칸(데스크탑은 RGBA16F, 웹은 EXT_color_buffer_float 가 있을 때 RGBA16F, 없으면 RGBA8)에 먼저 그린 뒤 섞어 옮긴다
- 모르는 모드로 source-over 를 쓰던 길과 그 경고가 없어졌다. (BlendMode 는 열거형이라 모르는 값이 없다)
- 크롬 Canvas2D 와 같은 장면(여러 색 바탕 위에 반투명 그림, 사각형, 다각형)을 26 모드로 견주면 도형 안쪽 차이가 2 단계 안이다. 웹 판은 원본 엔진과 픽셀까지 같고, 데스크탑은 도형 안쪽이 같고 가장자리 안티에일리어싱만 다르다. Canvas2D 는 SourceIn, SourceOut, DestinationIn, DestinationAtop, Copy 가 그린 도형 밖도 지우는데 Graphic 은 원본처럼 도형 안만 바꾼다
- Graphic: 데스크탑에서 기본 프레임버퍼에 그릴 때는 알파를 쓰지 않는다. 원본과 웹은 캔버스가 alpha: false 라 화면 알파가 늘 1 인데, 데스크탑 기본 프레임버퍼는 알파가 있어 알파를 낮추는 모드(SourceOut, Xor, DestinationOut 같은 것) 뒤에 DST_ALPHA 를 쓰는 모드와 셰이더 섞기가 웹과 다르게 나왔다. (같은 칸에 SourceOut 으로 그림 뒤 사각형을 그리면 데스크탑만 사각형이 보였다) 렌더 타겟에는 알파도 쓰고, GL 을 밖에 내줄 때(get_gl, run_external_pass, 프레임 끝)는 모두 쓰는 마스크로 되돌린다
- 툰 후처리, 효과, 카메라를 애버런트와 광부 키우기가 엔진 그대로 쓰게 넓힌다. (원본 vanilla.js 와 같은 API 와 같은 셰이더 글, 새 옵션이 기본값이면 지금 화면과 화소까지 같다, 게임의 처방과 색 값은 매개변수로 받는다)
- RenderTarget: RenderTargetOptions 에 sample_count(2 이상이면 멀티샘플 렌더버퍼에 그리고 resolve() 가 컬러 텍스처마다와 깊이 텍스처로 푼다, MAX_SAMPLES 와 웹은 포맷마다 받는 표본 수 밑으로 줄이고 못 받거나 완성되지 않으면 멀티샘플 없이, 데스크탑 GL 3.3 은 포맷마다 묻는 함수가 없어 MAX_SAMPLES 만) 와 depth_bits(16 이나 24), get_sample_count, get_resolve_framebuffer, read_supported_sample_count. 구조체로 옵션을 짓던 곳은 ..RenderTargetOptions::default() 를 붙인다. 웹 플랫폼 층에 read_renderbuffer_sample_counts(WebGL2 의 SAMPLES 목록)
- BloomEffect.set_use_float_color(gl, 켜기): 주고받는 판을 RGBA16F 로 (기본 RGBA8 그대로)
- MultiLevelBloomEffect: 다단 블룸. (원본과 같은 셰이더, 반 크기 뽑기와 부드러운 무릎, 이중 거르개 줄이기, 천막 꼴 키우기, set_level_count, set_threshold)
- ToonPostProcess: new_with_options(gl, 너비, 높이, ToonPostProcessOptions { sample_count, use_float_color, depth_bits, use_depth_texture }) (new 는 기본 옵션), is_float_color_supported(못 쓰는 기기는 RGBA8 LDR 길), set_sample_count, set_resolution_scale, set_bloom_levels, set_bloom_float_color(이 넷은 gl 을 받고 Result), set_brightness, set_lit_area 와 clear_lit_area, get_sample_count, get_use_float_color, get_resolution_scale, get_bloom_level_count. 머리말에 색 공간 규약(씬 판은 선형, 감마를 건 실수 판 값을 옮기는 셈 c^2.2, 밝기 배 k^2.2)
- Camera3D.set_matrices(보기, 투영): 게임이 셈한 원 행렬을 그대로 쓴다. 눈, 보는 곳, 위쪽, 직교인지를 행렬에서 뽑고 project_to_view, unproject_to_plane, read_view_depth 와 렌더러가 그 행렬로 돈다. has_raw_matrices, clear_raw_matrices, set_perspective 와 set_orthographic 과 look_at 은 원 행렬을 버린다. 시험 하나
- ToonVfx: 옵션의 age(늦게 보인 효과를 그 나이부터) 와 key(사건 열쇠, 원본은 수나 글, 러스트 판은 u64, clear 가 잊음, register_event_key)를 파티클, 불덩이, 충격파, 자국, 기둥, 번개, 섬광에, set_look_gain 과 get_look_gain, set_glint_capacity 와 get_glint_capacity(기본 96), ToonVfxDecalMode::Stain, Sheen, Shade 와 자국 flicker, queue_blob_shadow(ToonBlobShadowOptions), 불덩이, 충격파, 리본, 번개의 rim. 옵션 구조체에 필드를 더했으니 ..Default::default() 로 짓는다. 기본값 시험 하나
- 원본에 있고 러스트 판에 없던 게터: ShadowImage.get_image, get_image_rect, get_bake_image(원본 getBakeCanvas), ShadowText.get_bake_image, SoftShade.get_color, get_fade_width, get_bake_unit, get_bake_maximum_size, get_bake_image
- slice_graphemes(text, count) (원본 sliceGraphemes, 앞에서 글자 묶음 count 개까지, 크레이트 맨 위에서 낸다)
- Graphic.set_image_smoothing_quality, get_image_smoothing_quality, ImageSmoothingQuality(Low, Medium, High, 처음 High. 원본처럼 보관만 한다), get_vertex_array, get_vertex_buffer, get_vertex_data (기본 그리기의 버텍스 어레이, 버퍼, 스크래치 배열)
- create_guid() (원본 base/reflection.js 의 createGUID, 앞 12 자리는 밀리초 시각이고 나머지는 난수인 UUID 꼴 글, 크레이트 맨 위에서 낸다)
- 데스크탑 기본 글꼴을 원본 SYSTEM_FONT_STRING 처럼 이름 차례의 사슬로 잇는다. (전에는 후보 경로 가운데 처음 읽힌 한 파일만 써서 윈도우는 라틴도 맑은 고딕으로 나왔다) -apple-system, Segoe UI, Roboto, Apple SD Gothic Neo, Malgun Gothic, sans-serif 를 운영체제 글꼴에서 찾아, 앞 글꼴에 없는 글자를 뒤 글꼴로 그린다. 맥은 라틴이 SF(시스템 UI 글꼴), 한글이 Apple SD Gothic Neo, 윈도우는 라틴이 Segoe UI, 한글이 맑은 고딕이다. 얼굴은 그 굵기와 기울기의 글자를 처음 쓸 때 읽는다. (TextStringTextureCache.set_system_font_chain)
- 폰트 문자열의 올리지 않은 이름도 운영체제 글꼴에서 찾는다. ("16px Menlo", "16px Helvetica" 가 시스템 글꼴로 그려진다, 브라우저와 같다) 일반 이름은 크롬의 기본 글꼴과 같게 맥 sans-serif Helvetica, serif Times, monospace Courier, 윈도우 Arial, Times New Roman, Consolas, 리눅스는 fontconfig 가 고른다
- 데스크탑 대체 글꼴: 박아 둔 13 개 파일 대신 운영체제가 고른다. 맥 CoreText CTFontCreateForString(시스템 UI 글꼴에서), 윈도우 DirectWrite IDWriteFontFallback.MapCharacters(사용자 언어), 리눅스 fontconfig(글자를 담은 FcFontSort), 원본 크롬과 같은 API 다. 굵게를 청하면 굵은 대체 얼굴을 따로 묻는다. 이모지 표시 글자는 색 이모지 글꼴을 먼저 본다. (platform/desktop/systemfont.rs: find_family_font_file, find_fallback_font_file, TextStringTextureCache.set_system_font_fallback_enabled)
- EngineConfiguration.default_font_paths, default_bold_font_paths, fallback_font_paths 의 기본값을 빈 목록으로 바꿨다. 비우면 위처럼 운영체제가 찾고, 주면 전처럼 그 파일을 쓴다. default_font_paths 는 읽히는 파일을 모두 차례로 잇고, default_bold_font_paths 는 같은 자리의 굵은 파일이다. (기본값의 경로 목록을 읽던 코드는 고쳐야 한다)
- 맥, 리눅스 굵은 글꼴과 TTC: 글꼴 모음(TTC)은 PostScript 이름이나 굵기, 기울기로 얼굴 번호를 고른다. (textshaping::find_collection_face_index, 맥 Apple SD Gothic Neo 의 진짜 Bold 가 나온다) 가변 글꼴(wght 축, 맥 SF)은 굵기를 축 값으로 만든다. (read_weight_variation) 가변 글꼴의 윤곽은 skrifa 로 받아 그린다. (fontdue 는 축 값을 읽지 못하고, ttf-parser 와 fontdue 는 글리프마다 변형이 32 개를 넘는 맥 SFNS 의 윤곽을 그리지 못한다) LoadedFont.create_from_shared_bytes(바이트, 얼굴 번호, 축 값), get_shaping_face, get_font_bytes, get_face_index, is_outline_raster, read_glyph_metrics, draw_glyph_outline. LoadedFont.shaping_face 필드는 get_shaping_face() 로 바꿨다
- 글꼴 언로드: LoadedFont 가 글꼴 바이트를 rustybuzz 얼굴과 함께 든다. (self_cell, 전에는 Box::leak 으로 붙잡아 등록을 지워도 돌려주지 않았다) 같은 파일의 여러 얼굴은 바이트(Rc)를 나눠 든다
- 맥 크롬 Canvas2D measureText 와 견준 값: 한글 "가나다라" 16px 55.360, "16px Helvetica" 113.508, "16px Menlo" 154.125 가 같다. (시험으로 넣었다) SF 라틴은 106.672 로 크롬 109.072 보다 2.2% 좁다. (크롬이 시스템 UI 글꼴에 거는 광학 크기와 자간을 다 맞추지 못했다) (뒤에 고침: 이 차이는 -apple-system 을 모르는 이름으로 둔 크롬과 달랐던 글꼴 고르기 때문이었다. 아래 SF 라틴 항목)
- 새 크레이트: self_cell 1, skrifa 0.50, 맥 objc2-core-text 0.3 과 objc2-core-foundation 0.3, 윈도우 dwrote 0.11 과 winapi 0.3, 리눅스 yeslogic-fontconfig-sys 6 (dlopen, 빌드할 때 잇지 않는다)
- 맥 색 이모지를 CoreText 로 그린다. (platform/desktop/coretextglyph.rs) 크롬 맥처럼 작은 글자 크기에서 이모지를 키워 그리고 아래로 내린다. (16px 에서 20px 그림, 24px 부터 글자 크기 그대로) 전진폭은 CoreText 가 그린 그림 상자의 높이를 정수로 반올림한 값이다. 크롬 measureText 와 8 ~ 128px 의 23 가지 크기에서 같고(8px 10, 13px 16, 16px 20, 21px 23), 12, 16, 20, 32, 64px 의 그림 상자와 알파 합이 크롬 캔버스 getImageData 와 같다. (색 합은 0.01% 안) 시스템에 올린 글꼴만 CoreText 가 이모지를 키우므로 PostScript 이름으로 글꼴을 짓는다
- 맥: 윤곽이 glyf, CFF, CFF2 에 없는 글꼴도 CoreText 로 그린다. 맥 26 의 중국어 대체 글꼴 PingFangUI.ttc 는 윤곽이 애플 전용 hvgl 표에 있어 열린 해석기로 그릴 수 없다. (전에는 간체 글자가 빈칸이었다) LoadedFont.with_source_path, is_core_text_raster, read_advance_scale, is_integer_advance
- 새 크레이트: 맥 objc2-core-graphics 0.3
- 데스크탑 낱말 나누기를 크롬 Intl.Segmenter(ICU4C 사전)와 맞췄다. 태국어, 라오어, 크메르어, 버마어는 LSTM 대신 사전으로 나눈다. (ICU4X WordSegmenter::new_dictionary) 한중일 덩어리는 ICU4X 가 가장 긴 낱말부터 고르고 ICU4C 는 낱말 값의 합이 가장 작은 나누기를 골라 일본어가 달랐다("今日|はい|い"). ICU4C CjkBreakEngine 의 셈(사전에 없는 글자 값 255, 이어진 가타카나 1 ~ 8 자의 길이 값, 사전 찾기 전 NFKC)을 옮겨 ICU4X 의 같은 사전(cjdict)으로 다시 나눈다. 일본어, 중국어, 태국어, 라오어, 크메르어, 버마어 22 문장이 크롬과 같다. (시험으로 넣었다)
- 새 크레이트: icu_provider 2, icu_collections 2 (icu_segmenter 가 이미 쓰는 판), unicode-normalization 0.1 (데스크탑)
- UIFont: 미리 받지 않은 글자도 그 글꼴로 재거나 그리면 update 가 그 글자의 조각을 받는다. (원본 브라우저는 document.fonts 에 올려 둔 FontFace 의 글자 범위에 든 글자를 캔버스가 그릴 때 그 얼굴을 받기 시작한다. 전에는 load_ui_font_text, request_ui_font_text 로 청한 글자만 받았다) 받기 전에는 원본처럼 다른 글꼴로 그리고 받으면 다시 굽는다. 글자 캐시가 지켜보는 이름으로 재거나 구운 글에서 올린 얼굴의 글자 범위에 들지 않은 글자를 모은다. (textstringtexturecache::watch_unresolved_family_characters, take_unresolved_family_characters)
- 그림 형식: 원본 Image 는 브라우저가 푸는 형식을 모두 받는다. 데스크탑은 image 크레이트의 GIF(첫 장), BMP, ICO 를 더하고, SVG 는 resvg 로 그림 크기(width, height, 없으면 viewBox)에 그린다. (글이 있는 SVG 는 시스템 글꼴을 처음 한 번 읽는다) 웹은 애셋을 받을 때 그림 확장자(png, jpg, gif, webp, bmp, ico, svg, avif)면 원본처럼 브라우저(HTMLImageElement 의 decode)로 풀어 손잡이에 둔다. ImageAsset 과 AssetLoader 는 그 그림을 그대로 쓴다. Image::create_from_premultiplied_pixels 를 더했다
- 새 크레이트: resvg 0.50 (데스크탑)
- 웹 래스터를 원본처럼 브라우저 Canvas2D 로: 글꼴 바이트가 있어도 fontdue 로 굽지 않고 늘 캔버스의 fillText, strokeText, measureText 로 굽고 잰다. 올린 글꼴 바이트(FontAsset, default_font_bytes, default_font_url, UIFont 조각)는 원본 new FontFace(이름, 바이트, 서술자) 처럼 document.fonts 에 올려 브라우저가 고르고 그린다. (같은 이름 안에서 나중 얼굴이 먼저, 기본 폰트는 VanillaEngineDefault, 대체 폰트는 VanillaEngineFallback1, 2 … 이름으로 폰트 문자열 이름 뒤, 시스템 글꼴 앞에 둔다) 올린 글꼴이 받아지면(loadingdone) 프레임 시작에 구운 글을 버린다. (TextStringTextureCache.is_browser_raster)
- 웹 ShadowText: 원본 bakeText 처럼 캔버스에 그림자(shadowColor, shadowBlur, shadowOffsetY)를 걸고 글자 색으로 fillText, 밑줄과 취소선은 fillRect 로 굽는다. 여백(2 + 번짐 올림)과 자리 셈이 원본과 같다. 웹 ShadowImage: 원본 readScaledImage, bakeImage 처럼 drawImage(imageSmoothingQuality high)로 줄이고 색은 source-in 으로 칠한 뒤 캔버스 그림자를 깐다. (데스크탑은 그대로 직접 셈한다)
- ToonRenderer 확장 자리와 빛 모델: (원본 vanilla.js 와 같은 API, 같은 셰이더 글) 애버런트와 광부 키우기가 게임마다 렌더러를 고치지 않고 엔진 툰 위로 옮겨 올 수 있게 표준 기능을 먼저 갖추고, 표준으로 안 되는 무늬만 셰이더 조각으로 넣는 자리를 둔다. 새 옵션이 기본값이면 지금과 같은 화면이다. (원본 쪽에서 옛 렌더러와 같은 장면을 그려 LDR 화소 차이 0, 예제 toonshowcase, toonview, toonfx 는 멈춘 것(바닥, 인스턴스 바위)의 화소가 같음)
- ToonLightSet(toon/toonlightset.rs): 빛 값 한 덩어리. 렌더러가 기본 묶음을 들고 set_light, set_sun_direction, set_fill_light, set_rim_light, set_specular, set_point_lights, set_point_light_limit, set_band_count, set_band_ramp, clear_band_ramp, set_light_model 이 그것을 고친다. create_light_set, get_light_set, get_light_set_mut, 그리기마다 ToonDrawOptions.light_set. ToonPointLight, ToonLightModel, ToonBandRamp, TOON_MAXIMUM_POINT_LIGHTS 8, TOON_MAXIMUM_BAND_STEPS 8. 복제하면 새 번호
- 해 방향의 뜻: 빛이 나아가는 쪽(해에서 면으로). 받는 몫은 max(dot(N, -sun_direction), 0). 면에서 해 쪽 방향을 쓰던 쪽은 부호를 뒤집어 넘긴다
- 점광 감쇠 = 창 (1 - (d / range)^range_exponent) 를 막아 제곱 x 1 / max(d^decay, 0.01), 받는 몫은 (dot + wrap) / (1 + wrap). 기본 decay 2, range_exponent 4. decay 0, range_exponent 1 이면 (1 - d / range)^2
- 빛 꼴 is_energy_normalized: ÷π 와 정규화한 블린-퐁 (지수 + 8) / 8π
- ToonDrawOptions 에 tint_amount, glow_scale, color_scale, emissive_color, emissive_intensity, base_color_texture, emissive_texture, uv_transform, decal_texture, decal_color, decal_emission, decal_uv_transform, alpha_cutoff, blend_mode(ToonBlendMode), soft_edge, is_mirrored(None 이면 행렬식으로 스스로), index_start, index_count, outline_index_start, outline_index_count, material, textures(&[(유니폼 이름, 텍스처)]), on_before_draw(&dyn Fn(&ShaderProgram, &glow::Context, ToonProgramKind)), light_set, group, is_depth_prepassed 를 더했다. 구조체 꼴로 다 적어 짓던 코드는 ..ToonDrawOptions::default() 를 붙인다. Debug 는 손으로 붙였다(콜백은 있는지만)
- ToonMaterial(toon/toonmaterial.rs): create_material(ToonMaterialChunks { name, uniform_chunk, surface_chunk, light_chunk, vertex_chunk }) (원본은 꼴 객체). prepare_material, delete_material, get_program(머티리얼, 인스턴스 꼴, ToonProgramKind). read_material_program_sources(머티리얼, 인스턴스 꼴)와 compose_toon_program_sources(ToonProgramSources, 어트리뷰트 자리 포함)로 ShaderWarmer 에 넘긴다. (원본 readProgramSources 의 선택 인자 자리, read_program_sources 는 기본 프로그램 그대로)
- 인스턴스 꼴: create_instance_layout(&[(이름, 크기)]) → ToonInstanceLayout, create_instance_buffer(gl, 꼴, 수, ToonBufferUsage) → ToonInstanceBuffer, update_instance_buffer, delete_instance_buffer, draw_mesh_instance_buffer(gl, 모형, 버퍼, 수, 꼴). TOON_MAXIMUM_INSTANCE_ATTRIBUTES 3, TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION 13
- 텍스처: create_texture(gl, 너비, 높이, RGBA 바이트, ToonTextureOptions { is_mipmapped, is_repeated, is_filtered }), delete_texture. TOON_MAXIMUM_MATERIAL_TEXTURES 9
- 프레임: begin_frame_with_matrices(gl, 보기, 투영), get_frame_camera, read_frame_camera(ToonFrameCamera), apply_frame_state, create_reflection_matrix, read_matrix_determinant
- 성능: 프로그램마다 프레임 값과 빛 묶음은 바뀔 때만 올린다
- TOON_ATTRIBUTE_LOCATIONS 에 vertexUv(12)가 늘어 길이 13 이다. ToonMesh::has_uv, get_index_counts, has_outline
- ToonDrawQueue: add_pass(ToonDrawStage::BeforeOpaque | AfterOpaque | AfterOutline | AfterTransparent, 콜백(gl, renderer)), 꼴의 group 과 is_depth_prepassed(비치는 덩어리를 깊이만 먼저 그린 뒤 같은 깊이에만 칠함), blend_mode 가 Alpha 가 아니면 비치는 차례, draw_with_matrices(gl, renderer, 보기, 투영). 단계 콜백은 RefCell 에 담아 draw(&self) 그대로 부른다. clear 가 콜백도 비운다
- MeshBuilder: ToonMeshArrays 에 uv_data, material_ranges(ToonMaterialRange), ToonGeometry 에 uvs 가 늘었다. (구조체 꼴로 다 적어 짓던 코드는 ..Default::default() 를 붙인다) create_box_geometry, create_sphere_geometry 가 uvs 를 짓고 add_part 가 담는다. add_triangles_with_uvs(원본 addTriangles 의 마지막 선택 인자), add_material_range, combine 이 uv_data 와 material_ranges 를 잇는다
- GLB 읽기: TEXCOORD_0, 프리미티브마다 재질 범위(재질 이름, extras, alpha_mode, alpha_cutoff, 선형 색, 텍스처 그림 차례), read_glb_images(ToonGlbImage), decode_glb_image(image 크레이트로 RGBA)
- 애버런트를 옮길 때 값 바꾸기: 원본 UPDATE.md 의 같은 항목과 같다. (해와 되비친 빛 부호, ÷π, 정반사 8 / 56 배, 점광 decay 0 과 range_exponent 1, min(lit, 1) 대신 빛 세기와 노출 다시 맞추기, HDR 감마 값 대신 선형과 2.2 제곱 배, 색 키 대신 재질 범위와 UV 텍스처, 얼굴 화면은 표면 조각)
- NodeTree.get_position 을 원본 WorldNode.getPosition 과 같게 했다. 로컬 위치를 부모 피벗 점(부모 내용 크기 x 부모 피벗) 기준으로 옮긴 뒤 부모의 전역 회전과 크기를 걸어, 그리는 변환(calculate_world_matrix)이 피벗 점을 놓는 자리와 같다. 지금까지는 원본 TransformNode.getPosition 처럼 부모 피벗을 빼지 않아 부모의 내용 크기와 피벗이 0 이 아니면 달랐다. set_position 은 그 거꾸로다. (원본 setPosition 이 부모 피벗을 되돌리지 않던 버그를 같이 고침) 엔진 안에서 get_position 을 부르는 곳은 set_position 뿐이고 UI, 레이아웃, 트윈, 타임라인은 로컬 위치와 월드 행렬로 셈해서 예제 화면은 그대로다
- Multiply 를 렌더 타겟에 그릴 때는 그릴 영역 아래를 떠 와 W3C 식(B(Cb, Cs) = Cb x Cs)대로 셰이더로 섞는다. (원본과 같이 고침) 고정 블렌딩은 바탕이 반투명하면 cs x (1 - αb) 항이 빠지고 알파가 바탕 알파로 남아 크롬 Canvas2D 와 최대 221 달랐다. 기본 프레임버퍼는 고정 블렌딩과 묶어 그리기 그대로라 화면, 드로우 콜, 복사 수가 같다. 렌더 타겟의 Multiply 는 셰이더 섞기 13 가지처럼 그리기 하나에 영역 복사 한 번과 드로우 콜 한 번이 든다. 예제 blendmodes 에 장면 6, 7(투명하게 비운 렌더 타겟에 반투명 바탕과 장면 0 을 그려 검정 위, 흰색 위로 옮김)을 더했다. 데스크탑과 웹 모두 크롬 캔버스와 도형 안쪽 1 단계 안이고 Multiply 는 0 이다
- Format 이 표에 없는 언어 대신 쓰는 시스템 언어는 Localization.detect_language 와 같은 공용 함수(localization::read_preferred_language_tags)의 첫째다. 위 format 줄의 "데스크탑 LANGUAGE / LC_ALL / LC_MESSAGES / LANG" 는 리눅스 이야기다. 데스크탑은 sys-locale 로 맥 CFLocaleCopyPreferredLanguages, 윈도우 GetUserPreferredUILanguages 를 읽는다. (맥에서 LANG 을 de_DE, fr_FR 로 바꿔도 시스템 선호 언어 ko-KR 을 따른다) format.rs 머리 주석을 맞게 고쳤다
- 글꼴을 맥 크롬 158 Canvas2D 와 더 맞췄다:
- 맥 시스템 UI 글꼴(system-ui, BlinkMacSystemFont, SFNS): 크롬처럼 opsz 축을 글자 크기로 걸고(SFNS 는 17 ~ 96 으로 자른다) trak 표의 자간을 더한다. 굵기는 wght 축 값 그대로 건다(300 같은 굵기도). 16px "Hello World Wifi" 가 크롬과 같은 115.867 이다. (전에는 처음 opsz 28 에 자간 없이 106.7) 8 ~ 128px 의 19 가지 크기와 굵기 300, 400, 700 에서 크롬과 0.004 안이다. 크롬은 opsz 를 맥 시스템 글꼴과 올린 글꼴(웹 글꼴)에 걸고 윈도우, 리눅스 시스템 글꼴에는 걸지 않는다. 그대로 따른다. (크로미엄 font_platform_data_mac.mm, font_custom_platform_data.cc)
- trak 자간은 rustybuzz 가 아니라 HarfBuzz 15 처럼 셈해 더한다. 크기 사이는 반올림하지 않고 곧게 잇고, 표 밖은 끝 값, STAT 표가 있는 글꼴에만, 글자 묶음의 첫 글리프 전진폭에만 더한다. (크롬 harfbuzz_face.cc 는 ptem 으로 글자 크기를 주고, 맥은 trak 이 있는 글꼴의 전진폭을 HarfBuzz 로 셈한다) STAT 이 없는 Apple Chancery 는 자간 없이 크롬과 같다
- LoadedFont: with_optical_sizing_auto, read_optical_size, read_horizontal_tracking, create_sized_shaping_face. draw_glyph_outline 이 글자 크기를 받는다. (공개 API 를 바꾸는 일이다, 축 값이 크기마다 다르다)
- 앞 기록의 "SF 라틴 106.672 대 크롬 109.072" 는 크롬이 -apple-system 을 모르는 이름이라 넘기고 기본 사슬의 Apple SD Gothic Neo 로 라틴을 그린 값이었다. 크롬처럼 -apple-system 과 ui-serif, ui-sans-serif, ui-monospace, ui-rounded 를 모르는 이름으로 둔다. 맥 데스크탑 기본 글꼴(SYSTEM_FONT_STRING 사슬)의 라틴이 SF 에서 Apple SD Gothic Neo 로 바뀐다. (원본을 크롬으로 돌린 화면과 같다. 사파리는 SF 다) BlinkMacSystemFont 는 크롬처럼 system-ui 와 같다
- 일반 이름(serif, sans-serif, monospace, cursive, fantasy, math)을 크롬의 기본 글꼴 표대로 고른다. (platform/desktop/systemfont.rs: GenericFamily, resolve_generic_family_name, read_browser_locale) 표는 크로미엄 locale_settings_mac.grd, _win.grd, linux.grd 의 IDS_FONT_FAMILY 와 화면 언어 번역(platform_locale_settings/.xtb)이다. 크롬은 문서 lang 이 없는 캔버스를 기본 로캘(화면 언어)로 고르고, 그 스크립트의 따로 정한 값은 등록하지 않아(prefs_tab_helper.cc) 화면 언어의 Common 값을 쓴다. 원본이 굽는 캔버스는 문서에 붙이지 않아 문서 lang 을 바꿔도 그대로다. (크롬으로 확인) 러스트 판은 시스템 선호 언어에서 크롬에 번역이 있는 첫 언어를 화면 언어로 본다. 쉼표로 시작하는 값은 깔린 첫 글꼴이다
- 맥 한국어: 표준과 sans-serif Apple SD Gothic Neo, serif AppleMyungjo, monospace Menlo, cursive Apple Chancery, fantasy Papyrus, math STIX Two Math. 16px "Hello World Wifi" 가 크롬과 같다(serif 124.097, sans-serif 109.072, monospace 154.125, cursive 111.352, fantasy 109.156, math 115.472). 전에는 serif Times 110.961, monospace Courier 153.625 였다. 영어는 Times, Helvetica, Menlo
- 윈도우: 크롬처럼 monospace 가 Courier New 이고 ClearType 이 켜져 있으면 Consolas, 한국어는 Batang, Malgun Gothic, Gulimche, Gungsuh. system-ui 는 크롬처럼 메뉴 글꼴(NONCLIENTMETRICS 의 lfMenuFont). 리눅스: Times New Roman, Arial, Monospace 같은 표의 이름을 fontconfig 로 찾되 크롬(Skia SkFontConfigInterface_direct.cpp)처럼 이름이 맞거나 치수가 같은 대체 글꼴(Liberation, Arimo 같은 표)이거나 sans, serif, monospace 일 때만 받는다. 윈도우, 리눅스는 그 갈래만 떼어 x86_64-pc-windows-msvc, x86_64-unknown-linux-gnu 로 컴파일해 보았고 실행해 크롬과 견주지는 못했다
- 이름 목록이 다 떨어진 글자는 크롬처럼 화면 언어의 표준 글꼴, 운영체제 대체 글꼴, 마지막 대체 글꼴(맥 Times) 차례로 그린다. 기본 글꼴에 결합 부호가 없는 "é"(e + U+0301) 는 맥 크롬처럼 Times 로 그려진다
- 맥: 이름 표에 맥 기록만 있는 글꼴 모음(Papyrus.ttc 같은)에서 PostScript 이름으로 얼굴을 고르지 못해 Condensed 로 그리던 것을 고쳤다. 글꼴 서술자에 보통 너비를 넣는다
- 크롬 캔버스(plain_text_node.cc 의 PlainTextNode)처럼 글을 낱말로 나눠 따로 모양 짓는다. 빈칸을 낀 커닝과 합자가 없다. 빈칸, 탭, ZWSP 는 하나씩, 한중일 글자와 이모지는 글자마다 따로다. (textshaping::find_chrome_word_end) STIX Two Math 의 빈칸과 W 커닝이 빠져 크롬과 같아졌다. 캔버스의 탭, 줄바꿈, 폼 피드, 캐리지 리턴은 빈칸으로 바꿔 모양 짓는다. (크롬 IsNormalizedCanvasSpaceCharacter)
- 폰트 문자열 크기를 크롬 캔버스처럼 셈한다. (parse_font_string) 원본이 쓰는 문서에 붙이지 않은 캔버스에서 크롬으로 잰 값과 같다:
- ex, ch, cap, ic, lh 는 부모 글꼴(크롬의 마지막 대체 글꼴, 맥 Times) 10px 의 x 높이('x' 글리프의 위), '0' 의 전진폭, 대문자 높이, '水' 의 전진폭(없으면 1em), 줄높이 normal. rem, rex, rch, rcap, ric, rlh 는 문서 뿌리(화면 언어의 표준 글꼴) 16px. (전에는 rem 을 10px 로 셈했다) vw, vh, vi, vb, vmin, vmax 와 sv, lv, dv 앞붙이, 컨테이너가 없는 cq 단위는 창의 논리 크기. (textstringtexturecache::set_font_viewport_size, 데스크탑이 창 크기가 바뀔 때 알린다)
- 이름 목록이 따옴표 없는 monospace 하나뿐이면 상대 크기에 13 / 16 을 곱하고 이름 크기는 고정폭 표(medium 13, large 16)다. calc(), min(), max(), clamp(), abs(), sign(), round(), mod(), rem(), hypot(), sqrt(), pow(), exp(), log() 와 pi, e, infinity 를 셈한다. 함수 안의 음수는 0, 10000 을 넘으면 10000, "+2px" ".5px" "1e1px" 는 되고 "2.px" 는 틀린 값이다
- 웹은 절대 길이 밖의 크기를 원본처럼 문서에 붙이지 않은 브라우저 캔버스의 font 에 넣고 다시 읽어 받는다. (platform/web/systemfont.rs 의 resolve_font_size) 윈도우와 리눅스의 부모 글꼴 치수(줄높이의 win, hhea 값 고르기)는 크롬 원문을 따라 옮겼고 견주어 보지 못했다
- 맥만 도는 크롬 견줌 시험: system_ui_font_matches_chrome_on_macos(크기 19 가지 x 굵기 3), generic_families_match_chrome_korean_defaults_on_macos(화면 언어가 한국어일 때), font_size_units_match_chrome_on_macos(단위와 calc 75 가지, 한국어면 뿌리 단위 12 가지 더). 예제 textshaping 을 같은 장면의 원본 JS 와 맥 크롬에서 견주면 줄마다 글자 가로 범위가 2 배 화면 1 픽셀 안이다. (웹 러스트는 원본 JS 화면과 픽셀 차이 최대 11)
- 남은 차이: rustybuzz 는 위치를 글꼴 단위 정수로 들어 GPOS 가변 델타(SFNS 의 W 와 o 사이 커닝 같은)를 반올림한다. HarfBuzz 15 는 소수로 든다. SFNS 18, 20, 21, 24px 의 "Hello World Wifi" 가 크롬과 0.002 ~ 0.004px 다르다
- 새 크레이트: unicode-script 0.5 (rustybuzz 와 usvg 가 이미 쓰는 판). unicode-properties 의 general-category 기능과 윈도우 windows-sys 의 Win32_Graphics_Gdi 기능을 켰다
- 데스크탑 wss:// 를 기본으로 켜는 tls 기능으로 뺐다. (ewebsock 의 tls 와 rustls) 기본 동작은 그대로다. 암호 공급자 ring 이 C 를 빌드해 맥에서 윈도우 대상을 검사하면 윈도우 C 헤더가 없어 막혔다. 이제 cargo check --target x86_64-pc-windows-msvc --no-default-features 로 엔진 전체를 윈도우 대상으로 검사한다. (경고 0, 윈도우에서만 컴파일되는 LocalStorage 의 이름 경고 userProfilePath 를 같이 고침) default-features = false 로 쓰면 데스크탑은 ws:// 만 열린다. 리눅스 대상은 cpal 의 alsa-sys 와 gilrs 의 libudev-sys 가 pkg-config 를 불러, 맥에서는 빈 플래그를 내는 pkg-config 를 PKG_CONFIG 로 주고 PKG_CONFIG_ALLOW_CROSS=1 로 검사한다
- AudioBus.get_gain_node 가 두 플랫폼 모두 AudioGainNode 를 돌려준다. (웹 GainNode, 데스크탑은 버스 트랙을 나눠 드는 Rc<RefCell
>) 그 as_deref() 가 AudioPlayer::new 의 내보낼 곳이라 AudioPlayer::new(&audio_manager, audio_bus.get_gain_node().as_deref()) 가 두 플랫폼에서 그대로 컴파일된다. (웹은 as_deref, 데스크탑은 as_deref_mut 로 갈라 쓰던 것, 공개 API 를 바꾸는 일이다) 데스크탑에서 버스 트랙을 빌린 동안 버스의 다른 함수를 못 부르던 것도 없어졌다 - 웹 플랫폼이 손가락 뒤 800 밀리초 안의 마우스 사건을 원본 engine.js 처럼 마지막 장치와 마지막 손에만 적지 않고, 단추, 자리, 터치는 그대로 넘긴다. 지금까지는 사건을 통째로 버려 CameraGestures 의 넷째 인자(흉내 낸 마우스를 무시하는 시간)를 800 보다 짧게 해도 먹지 않았다. (헤드리스 크롬에서 손가락 뒤 300 밀리초의 오른쪽 단추가 문턱 100 이면 손짓, 800 이면 무시. 고치기 전에는 둘 다 무시)
- 데스크탑 플레이스테이션 패드(소니 054c 의 듀얼쇼크4 05c4, 09cc, 0ba0, 듀얼센스 0ce6, 0df2, 0e5f)를 크롬 MapperDualshock4, MapperDualSense 처럼 버튼 18개로 하고 원시 단추 13번을 늘 TOUCHPAD(17) 에 둔다. (맥 IOKit 단추 쓰임 14, 윈도우 Windows.Gaming.Input 단추 13, 리눅스 hid-generic BTN_GAMEPAD + 13) gilrs 가 SDL 매핑의 touchpad:b13 을 이름 없는 단추(misc1 과 같은 Button::Unknown)로만 이어서 원시 코드로 찾는다. 그 밖의 단추(듀얼센스 마이크)와 축은 붙이지 않는다. 리눅스 hid-sony(4.10 부터), hid-playstation(5.12 부터)은 터치패드를 따로 장치로 내고 bcdHID 에 0x8000 을 붙여, 크롬 MapperPs4Ps5 처럼 버튼 17개다. 지금까지는 매핑에 없는 단추 가운데 처음 누른 것이 17 이었다. (실제 패드 없이 매핑 자료와 코드 길로 확인)
- 리눅스와 그 밖의 유닉스의 is_coarse_pointer: 크로미엄 데스크탑 리눅스처럼 터치스크린이 있고 켜진 마우스, 터치패드, 포인팅 스틱이 없으면 참이다. (늘 거짓이던 것) 장치 목록은 크로미엄처럼 화면 서버에서 읽는다. 웨이랜드는 wl_seat 의 pointer, touch 능력, X11 은 XListInputDevices 의 장치 형과 XIQueryDevice 의 쓰임, 켜짐, 직접 터치, Abs MT Position 축. (크로미엄의 evdev 분류는 크롬OS 의 것이다) 매 프레임 불리므로 읽은 값을 2 초 동안 쓴다. x11-dl, wayland-client 는 glutin, winit 이 이미 쓰는 같은 판이다
- 데스크탑도 AVIF 를 푼다. HEIF 상자는 엔진이 libavif 규칙대로 읽고(grid 타일 잇기, 알파 보조 형 둘, prem, colr nclx, clap 은 크롬처럼 원점 (0, 0) 일 때만, irot, imir) AV1 은 rav1d(dav1d 를 러스트로 옮긴 것, asm 을 꺼 nasm 이나 C 컴파일러 없이 빌드)로 푼다. YUV 를 RGB 로 바꾸는 셈은 libavif 의 기준 셈이다. 크롬 158 이 푼 것과 최대 차 1~4, 맥 ImageIO 로 만든 grid(1600 x 1200, 타일 12)와 알파 그림도 같다. 색 프로필 변환과 움직이는 AVIF 는 하지 않는다. rav1d 는 opt-level 0 이면 느리다. (1600 x 1200 이 dev 빌드 2.9 초, rav1d 만 opt-level 3 이면 0.9 초) 게임의 Cargo.toml 에 [profile.dev.package.rav1d] opt-level = 3 을 두면 dev 빌드에서도 빠르다
- Image::load_from_memory_with_mime_type(형을 아는 바이트, 브라우저처럼 image/svg+xml 일 때만 SVG, 그 밖은 내용으로 가린 래스터), sniff_image_mime_type(WHATWG MIME 스니핑의 그림 표와 AVIF) 를 더했다
- 그림의 형을 원본처럼 응답의 content-type 으로: 읽기 손잡이가 응답 머리를 든다. (AssetLoadHandle.get_content_type) 웹은 응답이 그림 형이거나 주소가 그림 확장자면 그 content-type 을 형으로 브라우저가 푼다. 원본 HTMLImageElement 처럼 SVG 는 형으로, 래스터는 내용으로 가린다. (확장자가 없어도 image/svg+xml 이면 풀리고, text/plain 으로 온 .svg 는 원본처럼 풀리지 않는다) Material 의 mime_type 은 원본 loadImageDescription 처럼 응답의 content-type 이고, 응답이 없는 데스크탑은 내용으로 고른 형이다. (경로의 확장자로 정하던 Material::find_image_mime_type 은 뺐다)
- 타임라인의 "data:" 주소 그림: 웹은 원본처럼 브라우저가 풀고(SVG, AVIF 포함) 다 풀리면 스프라이트에 걸어 서술의 칸을 고른다. (원본 image.onload 의 applySpriteFrame) 데스크탑은 주소의 형이 image/svg+xml 이면 resvg 로 그리고 그 밖은 내용으로 가린 래스터다. (형과 상관없이 내용으로 SVG 를 그리던 것)
- Platform.is_coarse_pointer, Engine.is_coarse_pointer 의 머리 주석을 실제와 맞췄다. (윈도우와 리눅스는 크로미엄 판정)
- async/await 를 원본처럼 쓴다. (지금까지는 받기 손잡이와 콜백으로 대신했다. 손잡이를 맡기는 동기 꼴과 콜백 API 는 그대로 둔다)
- 엔진이 스레드 하나짜리 실행기를 품는다. (core/task.rs, 외부 런타임 없음, 데스크탑과 웹이 같은 코드, 퓨처는 Send 가 아니어도 된다) Engine::spawn_task(엔진 작업), spawn_scene_task(씬 작업)는 원본 async 함수를 부를 때처럼 맡기는 자리에서 첫 await 까지 돌고, 남은 것은 프레임마다 시간과 입력을 갱신한 뒤 씬의 tick 앞에서 원본 마이크로태스크 줄처럼 깨운 차례대로 줄이 빌 때까지 폴링한다. (한 작업이 Promise 를 풀거나 끝나면 기다리던 작업이 같은 차례에 풀린 차례대로 이어 가고, 스스로를 깨운 퓨처는 다음 프레임) &Engine 만 있는 자리는 spawn_deferred_task, spawn_deferred_scene_task
- 작업은 컨텍스트(EngineContext, SceneContext<씬 타입>)의 with(|씬, 엔진| ...) 안에서만 씬과 엔진을 빌린다. 폴링하는 동안만 스레드 지역 칸에 둔 포인터를 꺼내 쓰고 되돌려 두 번째 &mut 가 생기지 않는다. 그래픽은 with_graphic. TaskHandle 로 끝났는지 묻거나 await 한다
- Promise, PromiseResolver: 원본 new Promise((resolve, reject) => ...) 자리. Promise::create, Promise::resolved, Promise<Result<T, E>> 의 reject(까닭)
- wait::seconds, wait::next_frame (원본 base/wait.js, 그동안 옮기지 않았다). seconds 는 원본 setTimeout 처럼 벽시계 초이고(시간 배율을 곱하지 않는다) 0 초라도 한 차례 쉬며, 밀리초를 WebIDL long 으로 감는 것도 같다. 원본 nextFrame 이 만든 Promise 를 await 하지 않아 바로 끝나던 것은 원본(vanilla.js dev 89847b7)에서도 고쳐 둘 다 다음 프레임까지 기다린다
- 씬: 원본 async load 자리로 create 에서 맡긴 작업을 SceneBase::track_task 로 맡기면 끝날 때까지 initialize 를 미룬다. unload 에서 맡기면 원본 await scene.unload 처럼 끝날 때까지 씬이 목록에 남는다(tick, draw 도 받는다). 씬을 내려도 그 씬의 작업은 원본의 Promise 사슬처럼 이어 돌고, 엔진은 작업이 끝날 때까지 씬 값을 살려 둔다(tick, draw 없이, with 는 그 씬을 준다). 불러오는 도중에 내린 씬은 원본 loadScene 처럼 불러오기가 끝나면 initialize 까지 받는다. destroy 는 씬 값을 버릴 때 부른다. Engine::load_scene_async, unload_scene_async, unload_all_scenes_async (원본 await SceneManager.loadScene 들, 내리기는 unload 의 작업까지 끝나야 풀린다)
- 원본에서 Promise 를 돌려주는 load 들이 애셋이나 씬을 빌리지 않는 await 할 수 있는 손잡이를 돌려준다. (원본 await this.atlas.load(경로) 가 scene_context.with(|씬, 엔진| 씬.atlas.load(엔진, 경로)).await 한 줄) ImageAsset(풀기까지, 풀지 못하면 실패), TextAsset, JsonAsset, BlobAsset, BunchAsset, VisualAsset(원본처럼 경로만 적고 바로 끝남), FontAsset 의 load_font 들(FontLoadHandle, 글꼴 목록에 올리기까지), AudioAsset 의 load, load_from_bytes, load_from_asset(AudioLoadHandle, 디코딩까지. 돌려주던 Result 대신 손잡이의 get_load_error 로 그 자리 실패를 본다), AssetLoader::load(실패 목록), SpriteAtlas 의 load, load_data(아틀라스를 빌리지 않는 나눠 든 상태), BuildInfo::load, SoundSystem::load_sounds, languagepack 의 load_language_list, load_language, apply_language_setting, uifont 의 load_ui_font, load_ui_font_text(UiFontTextLoadHandle). Engine::register_font_face_when_loaded 도 FontLoadHandle 을 돌려준다. 이미 load 한 것은 wait_for_load().await 로도 기다린다
- FbxLoadHandle, ImageDescriptionLoadHandle 은 IntoFuture. SkinnedModel::load_from_url_async, load_from_fbx_url_async (다 받으면 작업을 폴링하는 엔진의 GL 로 짓는다). Timeline::load_from_url (원본 loadFromUrl)
- SkinnedModel::add_animations_from_fbx_url 이 AnimationLoadHandle 을 돌려준다. await 가 끝날 때는 원본처럼 클립이 이미 더해져 있다. (클립 목록을 손잡이와 나눠 들어, 받은 차례로 더한다) get_animation_list 는 빌린 값(Ref)을 준다
- languagepack::set_language_loaded_async_handler: 퓨처를 돌려주는 불러온 뒤 함수. 원본 applyLanguageSetting 처럼 그 퓨처가 끝날 때까지 불러오는 중이다
- SpriteAtlas 는 원본처럼 다시 불러오는 동안 앞의 조각과 쪽 그림을 그대로 쓰고, JSON 을 읽지 못했거나 꼴을 모르면 조각 없이 끝난다. (지금까지는 빈 조각으로 읽힌 것으로 쳤다)
- Engine::read_clipboard_text_async (원본 readClipboardText, 없거나 거부되면 None), request_frame_capture_async (원본 requestFrameCapture, PNG 바이트)
- 화면 페이드: GameScene::fade_screen_async(on_dark), GameSceneBase::fade_screen_async::<씬 타입>. 다 어두워진 tick 에서 game_scene!, ui_scene! 이 on_dark 를 씬 작업으로 맡겨 그 자리에서 첫 await 까지 돌리고(원본 onDark 를 부르는 자리), 퓨처가 끝나면 밝아진다. Scene 을 직접 구현한 씬은 바탕 tick 뒤에 take_screen_fade_dark_starter 로 꺼내 start 한다
- Scene 트레이트에 SceneAny 바탕 트레이트(as_scene_any_mut, 모든 'static 씬에 저절로 붙는다)를 더했다. SceneContext 가 씬을 제 타입으로 되돌릴 때 쓴다
- 예제 asyncawait. 시험 17 개(실행기와 그 자리 첫 폴링, 깨우기, 깨운 차례 줄, 기다리기와 setTimeout 지연, 애셋과 그림 손잡이, 엔진을 빌리는 손잡이, 컨텍스트 접근, 빼돌린 컨텍스트의 패닉, 씬 불러오기, 내린 씬 살려 두기, unload 기다리기, 불러오는 도중 내린 씬, 페이드, 언어 묶음 async 함수, 애니메이션 손잡이)
- README 장점과 사용법(씬 생명주기, 애셋 로딩의 원본과 러스트 표, 예제), 기술 노트, ARCHITECTURE 배치와 소유 구조와 프레임 루프, 9장(원본 182 파일 옮김), 10장(async 를 정말 맞출 수 없는 것에서 빼고 with 만 일부러 정한 꼴에)
- 데스크탑을 크롬 위의 원본과 더 맞췄다. (크로미엄 소스로 크롬이 하는 것을 확인해 옮김, ARCHITECTURE 10장)
- 웨이랜드 페이지 이벤트 Hidden: 크롬 리눅스 웨이랜드처럼 보낸 wl_surface.frame 콜백이 3 초 동안 오지 않으면 가려짐으로 보고 Hidden, 다시 오면 Visible 과 on_page_visibility_restored 를 낸다. winit 창의 wl_display 에 wayland-client 를 손님 연결로 붙여 제 큐에서 콜백을 보낸다. 메사가 가려진 창에서 eglSwapBuffers 안에 멈추지 않게, 웨이랜드는 SDL 처럼 EGL 스왑 간격을 0 으로 두고 엔진이 지난 프레임 콜백을 1/20 초까지 기다린다. xdg_toplevel suspended 는 winit 이 쥐고 있어 받지 못한다
- 윈도우 터치 키보드: 크롬 윈도우처럼 손가락이나 펜으로 플랫폼 입력 필드(use_dominput)에 포커스하거나 누르면 창에 묶은 InputPane 으로 터치 키보드를 띄우고(300 밀리초로 고름), 포커스가 떠나면 내린다. 가린 영역의 세로만큼 visualViewport 를 줄여 auto_resize_on_window_resize 면 캔버스가 줄고, ignore_virtual_keyboard_resize 가 데스크탑에서도 원본처럼 그것을 막는다. 맥과 리눅스는 크롬처럼 뷰포트를 줄이지 않는다
- preserve_drawing_buffer: 원본처럼 켜면 프레임 첫머리에 색을 비우지 않는다. (원본 applySettings 는 스텐실만 비운다. 지금까지 러스트 판은 웹과 데스크탑 모두 늘 비워서, 켜도 지난 프레임 그림 위에 쌓아 그려지지 않았다) 데스크탑은 다 그린 프레임을 떠 두었다가 다음 프레임 첫머리에 되그린다. Graphic::new 가 원본 생성자처럼 preserve_drawing_buffer 를 받는다
- auto_resize_on_window_resize 를 끄면 데스크탑도 원본처럼 캔버스 비 상한(max_canvas_aspect_ratio)을 걸지 않는다. (원본은 이 설정이 켜졌을 때만 비 상한을 건다. 데스크탑 창은 캔버스가 창을 가득 채운 페이지로 본다)
- 데스크탑 Platform 의 브라우저를 Unknown 에서 Chrome 으로: 데스크탑 판이 크롬 위의 원본과 같은 결과를 내므로 게임 코드의 브라우저 분기도 크롬 갈래로 간다
- 개발자 도구의 메모리 칸: 데스크탑은 (N/A) 대신 시스템 할당자의 힙(맥 malloc_zone_statistics, 윈도우 프로세스 힙 HeapSummary, 리눅스 glibc mallinfo2)을 usedJSHeapSize, totalJSHeapSize 칸에 적는다. jsHeapSizeLimit 는 그런 상한이 없어 (N/A) 다
- 차이 표에서 뺀 것: 세이프 에어리어 인셋 0(크롬 데스크탑도 0, SetDisplayCutoutSafeArea 는 안드로이드에만 있다), set_prevented_keys 와 오른쪽 클릭 메뉴 막기(데스크탑 창에는 막을 브라우저 기본 동작이 없어 막은 것과 같다), 화면 키보드, 웨이랜드 Hidden, preserve_drawing_buffer, auto_resize_on_window_resize, 브라우저 이름
- 반사(리플렉션): 원본의 실행 중 반사(uidocument.js 의 collectReflectedProperties, getReflectedProperties, saveByReflection, loadByReflection, devtools.js 의 getComponentProperties)와 같은 일을 컴파일 때 짓는 코드로 한다. 언리얼 UHT, Qt moc 처럼 절차 매크로가 한다
- 저장소를 워크스페이스로 만들고 절차 매크로 크레이트 macros/(vanilla-engine-macros, syn, quote, proc-macro2)를 더했다. 엔진이 vanilla::reflect 로 다시 내보내 게임은 엔진 하나만 의존한다. 지은 코드는 ::vanilla 로 엔진을 가리키고, 엔진 안에서는 lib.rs 의 extern crate self as vanilla 로 같은 경로가 통한다
- #[vanilla::reflect] 를 컴포넌트의 impl 블록과 impl Component 블록에 붙인다. 인자 없는 pub get_*, is_* 게터와 짝 set_* 을 모아 Reflect 구현을 짓는다. 키는 원본 이름(get_line_width → LineWidth), 차례는 정의 차례다. 한쪽만 붙이면 컴파일 에러가 붙일 곳을 알려 준다
- 값으로 바꿀 수 없는 꼴의 게터는 자동 참조 특수화로 골라내 저장에서 빼고 인스펙터에는 [종류 이름] 으로 보인다. 함수에 #[reflect(skip)], #[reflect(transient)], #[reflect(name = "...")], 블록에 #[reflect(base = 필드)](원본 상위 클래스 몫을 품은 필드로 잇기)
- core/reflection.rs: ReflectValue, Reflect, ToReflectValue, FromReflectValue, ReflectedProperty, ReflectedGetter, collect_reflected_properties, read_reflected_property, write_reflected_property, collect_reflected_getters. Component::get_reflection, get_reflection_mut (기본 None). 원본에서 글인 열거(TextAlign, TextBaseline, TextDirection, TextWrapMode, SpriteDrawMode, BlendMode, ScrollMode, ProgressDirection, ScrollBarAxis, SoftShadeShape, ButtonMotionStyle, ToastPhase, ParticleEmitterShape, ParticleRenderShape, ShaderSpriteEffect)는 같은 글로, ButtonState 는 원본 Enum 수로 바꾼다
- 엔진 컴포넌트 51 종에 모두 붙였다. 원본 상위 클래스가 있는 것(UIControl, UIScrollView, UIProgressView, UILabel, UIImageView 는 UIView, UIButton, UISlider, UIDraggable 은 UIControl, UIToggleButton 은 UIButton, UISnapScrollView 는 UIScrollView, Sprite 는 Paint, ShaderSprite 는 Sprite)은 base 로 잇고 위임 함수는 뺐다. ShadowText 의 TextAlign, isBold, UIProgressRing 의 둘레 점, UIListView 의 isHorizontal 은 원본 차례로 옮겼다
- UIDocument: 원본처럼 쓰기, 읽기 함수(propertyHandler)가 없는 종류는 반사로 쓰고 읽는다. (save_by_reflection, load_by_reflection, get_reflected_properties, 원본 REFLECTED_PROPERTY_EXCLUDE_NAMES) 손으로 짠 Outline, SoftShade, ShadowText, UIProgressRing 직렬화를 지우고 반사로 돌렸다. 결과는 원본 saveByReflection 과 키, 차례, 값까지 같다. (원본을 node 로 돌려 낸 JSON 으로 시험)
- 공개 API 를 바꿨다: register_component_type(이름, 짓는 함수)이 원본 registerComponentType 이다. (반사) 쓰기, 읽기 함수가 있으면 register_component_type_with_handler, 위젯은 register_widget_type(이름, 짓는 함수, content, 스스로 붙이는 종류)과 register_widget_type_with_handler
- 등록하지 않은 종류도 반사가 있으면 원본처럼 반사로 적는다. (type 은 타입 이름) 쓰기 함수가 있는 종류도 노드를 가리키는 반사 속성은 원본 saveNodeReferences, loadNodeReferences 처럼 따로 얹고 읽는다
- 원본 노드 종류(WorldNode 하위 클래스)를 맡은 컴포넌트: register_node_type, UIDocumentNode, UIDocumentNodeParts. 그 컴포넌트가 붙은 노드의 type 이 그 이름이고, 원본 노드 생성자가 만든 컴포넌트와 자식을 원본 문서 꼴로 쓰고, 읽을 때는 설정으로 읽고 다시 짓지 않는다
- register_editor_types: 원본 에디터(tools/uieditor)가 저장한 문서의 UIInputField, UIScrollBar(원본 노드 종류)와 UISnapScrollView 를 한 줄로 등록한다. 지금까지는 읽을 때 버려졌다. UIInputField 는 바탕 색, 둥근 크기, 안내 글과 그 색, 글 크기, 값과 그 색을, UIScrollBar 는 트랙과 썸 색을 읽는다
- ShadowImage 는 imagePath 뒤에 반사 저장 꼴로 쓴다
- UIScrollBar: get_track_color, get_thumb_color
- DevTools: 인스펙터가 원본 getComponentProperties 처럼 컴포넌트의 get*, is* 게터를 모두 불러 보인다. (이름은 원본 formatMethodName, 값은 formatPropertyValue 꼴, 수는 원본 toFixed 와 같은 반올림) 반사가 없는 컴포넌트는 지금처럼 UIDocument 의 저장 키 또는 종류 이름만
- README(노드와 컴포넌트의 반사 매크로 쓰는 법, 기술 노트, 외부 의존성의 매크로 크레이트 표), ARCHITECTURE(배치, 9장, 10장 두 엔진의 차이의 반사 줄)
- 데스크탑 소리 해석을 원본(크롬 decodeAudioData)과 같게 했다. (platform/audio/decode)
- 크롬 158 은 FLAC, MP3, PCM, Vorbis 를 symphonia 0.6 으로, Opus 를 libopus 로, AAC 를 FFmpeg 로 푼다. 엔진도 kira 의 해석 기능을 끄고 symphonia 0.6.1 을 직접 불러 같은 해석기를 쓰고(크롬이 켜는 기능과 같게), Opus 는 libopus 를 러스트로 옮긴 opus-pure 를 symphonia 코덱 등록표에 넣어 푼다. webm.cjs 가 만드는 webm(Opus)을 이제 데스크탑에서 튼다
- 컨테이너도 symphonia 의 풀기(wav, ogg, mkv(webm), isomp4(m4a), flac, mp3, adts)로 하고, 꼴은 확장자나 형이 아니라 내용으로 가린다
- 크롬이 FFmpeg 의 시각과 다듬기 값으로 버리는 앞뒤를 같게 버린다. (Opus pre-skip, webm 의 CodecDelay 를 FFmpeg 가 ms 로 반올림해 생기는 몫, DiscardPadding, MP3 LAME 지연, Ogg granule 과 쪽 하나짜리 Vorbis, m4a 편집 목록과 iTunSMPB, AAC 마지막 패킷 길이)
- 정수 표본은 크롬 식(양수는 최대로, 음수는 최소로 나눔, 16 비트 FLAC 은 16 비트로)으로, MP3 는 -1 ~ 1 로 자른다. Opus 의 출력 게인과 5.1 의 크로미엄 채널 차례도 같다
- 크로미엄 SincResampler 를 옮겨 원본 DECODE_SAMPLE_RATE(44100)로 바꾼다. (Blink 와 같은 32 탭 커널과 길이 셈, 합의 차례는 크롬이 고르는 NEON, SSE, AVX2 와 같게)
- WebAudio 스피커 규칙으로 1 채널이나 2 채널로 내린다. (쿼드, 5.1 은 명세의 식, 그 밖은 앞 두 채널. 이제 3 채널 이상 파일도 튼다)
- 시험 소리 21 파일(tests/assets/audio, 모두 수 KB)을 크롬 158 의 결과(chromedecode.cjs 가 찍은 chrome_decode.json)와 견준다. 길이와 채널은 모두 같고, FLAC, MP3, PCM, Vorbis 는 표본까지 같으며 Opus, AAC 는 1e-7 안팎이다
- 남은 차이: HE-AAC(SBR, PS)와 3 채널 이상 AAC 는 symphonia 0.6.1 이 받지 않아 데스크탑에서 풀지 못했다. (크롬은 FFmpeg 로 푼다) (뒤에 고침: 지금은 oxideav-aac 로 푼다, 아래 HE-AAC 항목)
- 늘어난 크레이트 7: opus-pure, symphonia-format-mkv, rustfft(크롬처럼 symphonia 의 opt-simd 를 켜 FFT 를 같게)와 그 의존 primal-check, strength_reduce, transpose, num-integer. 줄어든 것은 없다 (kira 가 쓰던 symphonia 를 엔진이 직접 쓴다)
- "data:" 주소: 데스크탑 Engine::load_audio_asset, request_asset_bytes, request_asset_bytes_into, load_image 가 data: 주소를 풀어 읽는다. (타임라인 편집기가 넣는 data: 소리를 데스크탑에서도 튼다) base64 와 퍼센트 꼴 풀기를 타임라인에서 base/dataurl.rs 로 옮겼다. 웹은 asset_base_url 이 비어 있지 않으면 data: 주소 앞에도 기준 주소를 붙여 못 받던 것을 고쳤다
- 데스크탑 소리 내기를 kira 에서 cpal 위의 엔진 믹서로 바꿨다. (platform/audio/mixer.rs) 원본 소리 API 와 러스트 API(AudioPlayer, AudioBus, get_gain_node, BeepPlayer)는 그대로다
- 원본이 짓는 WebAudio 그래프를 그대로 짓는다. AudioBufferSourceNode → 플레이어 GainNode → (0 이 아닌 좌우를 처음 걸면) StereoPannerNode → 버스 GainNode 또는 출력, 비프 오실레이터 → 출력. 128 프레임 퀀텀으로 그린다
- 셈은 크롬과 같다. 소스는 audio_buffer_source_handler.cc 를 옮겼다(시작 위치의 1024 배 오버샘플 반올림, 빠르기 1 이면 그대로 베끼고 아니면 선형 보간, 끝의 선형 외삽, 버퍼 전체 루프, playbackRate 는 AudioParam 처럼 f32). 좌우는 stereo_panner.cc 의 식(모노는 x = (pan + 1) / 2, 스테레오는 pan <= 0 이면 L += R cos, R *= sin), GainNode 는 곱, 모노는 스피커 규칙으로 양쪽에, 출력은 -1 ~ 1 로 자른다. kira 는 4 점 3 차 보간과 sqrt 좌우 법칙으로 크롬과 달랐다
- 좌우와 음량은 다음 퀀텀부터 바로 걸린다. (kira 판의 좌우는 다음 재생부터였다) 비프는 컨텍스트(장치) 표본율로 그린다
- 컨텍스트 시계는 그린 시간이다. (원본 currentTime, 퀀텀마다 128 / 표본율 초) 멈춘 동안은 그리지 않아 소리와 시계가 그 자리에서 선다
- 스트림은 관리 스레드가 들고, 장치가 빠지면(맥이 아니면 기본 장치가 바뀌어도) 같은 믹서로 다시 연다. (kira 가 하던 것과 같다)
- AudioContext(데스크탑)는 엔진 믹서의 것이고 sample_rate(), current_time() 을 웹 AudioContext 와 같은 이름으로 낸다. AudioBuffer 는 duration(), length(), number_of_channels(), sample_rate() 을 낸다. (공개 API 를 바꾸는 일이다: 지금까지는 kira 의 AudioManager, StaticSoundData 였다)
- 버스로 만든 플레이어와 내보낼 곳을 직접 넘긴 플레이어는 원본 WebAudio 처럼 이어진 동안 버스 노드를 살려 둔다
- 그래프 다섯(같은 표본율과 다른 표본율의 소스, 빠르기와 루프와 시작 위치, 모노와 스테레오 좌우와 0, 버스, 섞기)을 크롬 158 OfflineAudioContext 결과(tests/assets/mixer/chromemixer.cjs 가 찍은 chrome_mixer.json)와 견주는 시험을 더했다. 1e-6 안에서 같다
- 줄어든 크레이트 8: kira, atomic-arena, crossbeam-utils, glam, mint, pastey, rtrb, triple_buffer. 직접 의존은 cpal 하나다 (kira 가 쓰던 cpal 0.18 그대로, realtime 기능)
- ToonScreenOutline: 화면 공간 바깥선을 실시간 툰 렌더링의 정석 꼴로 다시 지었다. (vanilla.js 와 같은 셰이더, 같은 값)
- 잡기: 선의 판(노멀, 선 번호, 깊이)에서 화소와 바로 이웃 넷 사이의 경계마다 한 번 보고, 선은 그 경계 가운데에 세운다. 지금까지는 꺾임 선을 creaseRadius 떨어진 한 점의 노멀로 보아 꺾임 양쪽이 띠로 서고, 반 크기 판에서 점선과 평행한 둘째 선, 둥근 면의 실루엣 안쪽 띠가 섰다
- 깊이: 이웃 두 화소를 보기 공간 자리로 풀어 서로의 접평면에서 떨어진 거리로 가려진 실루엣을 본다. 문턱에 그 깊이의 화소 크기 두 배를 더한다
- 넓히기: 경계 토막까지의 거리를 점프 플러딩으로 퍼뜨린다. (걸음 log2 번, 바깥 선과 꺾임 선을 따로) 3 픽셀 반지름 한도가 없어졌다
- 섞기: 그리는 영역의 화소마다 가장 가까운 경계까지의 거리로 clamp(굵기 / 2 - 거리 + 0.5, 0, 1) 만큼 덮는다. 줄인 선의 판에서도 선이 끊기지 않는다
- 모형마다: ToonLineDrawOptions 의 has_screen_outline (false 면 가리기만), has_crease_line, is_mirrored (None 이면 행렬식으로)
- read_jump_flood_steps(거리): 점프 플러딩 걸음 목록
- ToonDrawOptions: line_id (None 이면 그리기 줄이 담은 차례 + 1), has_screen_outline, has_crease_line. (화면 공간 바깥선의 모형마다 꼴, ToonRenderer 는 읽지 않는다)
- ToonDrawQueue: set_screen_outline(Option<&'a mut ToonScreenOutline>), has_screen_outline(). 맡기면 draw 와 draw_with_matrices 가 몸 앞에 불투명한 것을 선의 판에 그리고 바깥선 껍데기 뒤 AfterOutline 단계 앞에 섞는다. 화면 사각형이 있으면 그 사각형을 그리는 영역으로 쓴다
- 반사를 원본과 끝까지 맞췄다. (원본을 node 로 돌려 뽑은 기대값과 견주는 시험, src/ui/testdata/uidocument 의 generate.mjs 가 다시 뽑는다)
- 반사가 &mut self 게터(get_reflected_value_mut, collect_reflected_getters_mut), 트리를 받는 게터(collect_reflected_getters_in_tree), 트리와 값을 받는 세터(set_reflected_value_in_tree)를 부른다. UIDocument 는 읽을 때 컴포넌트를 트리에서 잠깐 꺼내(NodeTree::with_component_at_mut) 트리를 받는 세터를 원본처럼 그 자리에서 부르고, to_json_text_mut, serialize_node_mut 가 &mut self 게터까지 적는다. DevTools 인스펙터는 tick 에서 &mut self 게터를 읽어 두고 그릴 때 트리를 받는 게터를 부른다
- 매크로: 짝은 원본처럼 키(baseName)로 짓고, 읽기와 넣기는 따로 가장 아래 타입부터 찾는다. #[reflect(unsaved)](목록에는 두고 저장에서 빼기), #[reflect(after = "...")](impl Component 블록의 게터를 원본 클래스 몸통의 자리에 두기)를 더했다
- 인스펙터 게터 목록과 반사 속성 목록이 원본과 같다. 원본 클래스에 없는 러스트 판의 다시 정의(isTickNeeded 같은 것)를 빼고, Text, RichText, UILabel, UIButton 은 원본 정의 차례로 옮겼다. UIHitArea 의 getTargetButton(트리), ShadowText 의 FontFace, SoftShade, ShadowText, ShadowImage 의 BakeCanvas 처럼 원본 이름으로 보인다
- register_editor_types 가 원본 에디터처럼 엔진 컴포넌트 35 종과 노드 종류 12 종(FloatingText, TouchEffect, UIConfirmWindow, UIContextMenu, UIDialog, UIDropdown, UIInputField, UIScrollBar, UISpinner, UIToast, UIWindow, UIWindowLayer)을 등록한다. register_node_type_with_match 로 같은 컴포넌트를 쓰는 노드 종류(UIConfirmWindow 는 UIWindow 와 행동)를 가린다
- UIDocument 읽기: 노드 종류나 위젯이 붙을 때 지은 컴포넌트와 자식, require 로 함께 붙은 컴포넌트에 문서 값을 넣고 다시 짓지 않는다. UIImageView 의 품은 Sprite 를 원본처럼 뒤따르는 Sprite 로 쓰고 읽는다. 숨은 UIToast 는 원본처럼 active false 로 쓰고 읽는다
- NodeTree::add_component, WorldNode::add_component 가 원본처럼 컴포넌트 자리를 먼저 잡고 붙을 때 더 붙는 컴포넌트를 그 뒤에 둔다
- 원본과 같게 고친 것: UIConfirmWindow 의 제목과 글이 UILabel 이다. UIWindow 는 붙을 때가 아니라 create 에서 노드를 끈다. FloatingText 는 붙을 때 피봇과 앵커를 왼쪽 위로 둔다. UIDropdown 화살표는 원본 글자(▴, ▾)와 글 크기다. UIScrollBar 썸은 원본 썸 노드처럼 처음은 켜진 0 크기 사각형이다. UIInputField 는 tick 이 놓은 글 라벨 크기를 문서에 적는다. UIImageView 는 그림 경로를 품은 Sprite 와 따로 든다. UISpinner 점 자리는 원본처럼 f64 로 셈한다
- DevTools: 반사도 등록도 없는 컴포넌트는 "반사 없음" 줄로 매크로를 빠뜨린 것을 알린다
- 브라우저가 해 주던 것 2차 (남은 차이 가운데 방법이 있는 것)
- LocalStorage: 짝 없는 서로게이트로만 다른 두 키(원본에서 다른 키)를 따로 든다. 전에는 러스트 쪽에서 한 키가 되어, 데스크탑은 원본이 저장한 그런 두 키 가운데 하나를 읽을 때 잃고 다음 쓰기에 파일에서도 지웠다. 키도 원래 단위로 부르는 get_keys_code_units, get_item_by_key_code_units, set_item_by_key_code_units, remove_item_by_key_code_units, contains_key_code_units 를 더했다. 러스트 글 키는 그 글 그대로의 키가 있으면 그것, 없으면 그 글로 보이는 짝 없는 서로게이트 키의 첫째를 가리킨다. get_keys 는 보인 글이 같은 키를 한 번만 낸다
- PaneStyle(데스크탑): 원본 도구가 쓰는 CSS 를 읽는다. flex 배치(flex-direction column, flex, flex-grow, flex-shrink, flex-basis 를 CSS Flexbox 의 길이 셈대로, justify-content 의 space-between 같은 것, align-items 기본 stretch), min, max 크기, right 와 bottom, 쪽마다 안쪽과 바깥 여백과 테두리, line-height, text-align, overflow(넘친 자식 자르기, auto 와 scroll 은 휠과 썸 끌기로 넘기고 끝에 닿으면 휠을 부모에게 넘긴다, scrollbar-color). auto 크기 요소는 자식의 크기를 더해 잰다. PaneElement::get_scroll_offset, set_scroll_offset
- UIInputField::set_multiline: 크롬 textarea 같은 여러 줄 입력. 줄바꿈 문자와 폭으로 나누고(pre-wrap, break-word, 데스크탑은 ICU4X 유니코드 줄 나누기), Enter 는 줄 넣기, 위아래(가로 자리 지키기), Home 과 End(보이는 줄), Ctrl + Home, End(맥은 Cmd + 위, 아래), PageUp, PageDown(블링크의 87.5% 거리), 탭 자리, 선택과 끌기, 조합 밑줄, 휠과 썸 끌기 스크롤, 커서 따라 스크롤. set_line_height, set_tab_size, get_scroll_top, set_scroll_top. 웹 DOM 입력은 숨긴
- TextInputKey: Up, Down, PageUp, PageDown, DocumentStart, DocumentEnd. TextInputFieldState.is_multiline. 데스크탑 한 줄 DOM 입력 필드는 블링크처럼 위아래를 글 앞과 끝으로 옮기고, 넣는 글의 줄바꿈을 공백으로 바꾼다(끝 줄바꿈은 지운다). 맥 Cmd + 왼쪽, 오른쪽은 줄 앞과 끝
- Canvas2D, Path2D: arc, ellipse, arcTo, roundRect 를 크롬처럼 스키아 원뿔 곡선으로 담는다. (블링크 canvas_path.cc 의 각 다듬기와 납작한 타원, 스키아 SkPathBuilder::arcTo, SkConic::BuildUnitArc, SkRRect 반지름 줄이기와 addRRect 점 차례) 데스크탑은 칠할 때 스키아 CPU 래스터처럼 기기 픽셀 0.25 안의 2 차 곡선으로 나눈다. (전에는 3 차 베지어 근사)
- Canvas2D, Path2D: roundRect 가 타원 모서리를 받는다. (CanvasRadius::Elliptical, (x, y), 원본 DOMPointInit) 웹 Path2D 는 원본처럼 브라우저 Path2D 의 arc, roundRect 같은 함수를 그대로 부른다
- Canvas2D: GPU 에 올리며 CPU 픽셀을 놓은 엔진 Image 도 그린다. (그림이 기억한 텍스처를 되읽는다, 전에는 알리고 건너뛰었다)
- 입력 필드(데스크탑, DOM 입력을 직접 누르게 한 필드): 크롬 데스크탑 터치처럼 손가락으로 650ms 길게 누르면(크롬 aura 의 길게 누르기 500 + 누름 표시 150, 허용 거리 15 DIP) 그 자리 낱말을 고르고 터치 선택 손잡이(크롬 벡터 아이콘 꼴, 끌어 선택을 바꾼다)와 빠른 메뉴(잘라내기, 복사, 붙여넣기, "...", 뗀 뒤 100ms, 선택 위 가운데)를 띄운다. 고른 것도 붙여 넣을 것도 없으면 엔진 문맥 메뉴다. 윈도우는 뗄 때(블링크 context_menu_on_mouse_up) 정한다. 키, 마우스 누름, 휠은 손잡이와 메뉴를 지운다. "..." 는 선택 위 가운데에 엔진 문맥 메뉴
- 데스크탑이 HE-AAC v1(SBR), v2(PS)와 3 채널 이상 AAC 도 크롬처럼 푼다. (platform/audio/decode/aac.rs)
- AAC-LC 2 채널까지는 그대로 symphonia 로 풀고(크롬과 PNS 잡음까지 같다), symphonia 가 받지 않는 것(ASC 에 적힌 SBR, PS, 3 채널 이상)과 몸통에만 SBR 이 실린 것(ADTS 의 HE-AAC 같은, 첫 패킷의 표본율이 두 배가 되는지로 가린다)은 oxideav-aac 로 푼다
- oxideav-aac(MIT)는 ISO/IEC 14496-3, 13818-7 명세로 짠 순수 러스트 해석기다. 공개 저장소(OxideAV/oxideav-aac)의 커밋 역사가 명세 조항으로 짠 기록이고 FFmpeg 같은 LGPL 코드를 옮긴 흔적이 없다. 다른 후보 rusty_aac(Apache-2.0)는 해석기 소스의 공개 저장소와 커밋 역사가 없어(크레이트의 저장소 주소는 그것을 쓰는 다른 저장소) 출처를 확인할 수 없어 쓰지 않았다
- 정수로 반올림하기 전 실수 출력(set_float_pcm_capture)이 crates.io 판 0.1.7 에 없어 저장소 커밋 eac68f3 으로 묶었다. 다음 판이 나오면 crates.io 로 바꾼다
- 시험 소리 6 개(HE-AAC v1 m4a 와 adts, v2 m4a, 5.1 AAC m4a 와 adts, PNS 를 쓴 스테레오 AAC)를 더해 27 파일을 크롬 158 과 견준다. 길이와 채널이 같고 표본은 1.5e-7 안이다
- 남은 차이: 3 채널 이상 AAC 에 PNS 가 쓰이면 그 띠의 잡음 표본이 크롬과 다르다. (명세가 난수 생성기를 정하지 않아, 같게 하려면 FFmpeg 의 생성기를 옮겨야 한다)
- 늘어난 크레이트 4: oxideav-aac, oxideav-core, thiserror, thiserror-impl
- 표본율 바꾸기의 x86_64 합 차례(AVX2 와 FMA, SSE)는 크롬과 같게 짰지만, 기대값을 애플 실리콘 맥에서 뽑아 x86 실기에서는 돌려 보지 못했다
- SoundSystem 의 효과음 줄여 끄기, 앞만 틀기, 배경음악 겹쳐 바꾸기와 버스 크기 따라가기를 원본처럼 AudioParam 자동화로 한다. 지금까지는 웹과 데스크탑 모두 update 마다 같은 식을 셈해 음량을 걸었다
- 원본 soundsystem.js 와 같은 호출: 효과음은 gain.value 대입 뒤 setValueAtTime, linearRampToValueAtTime(0), source.stop(when), 줄여 끄기는 지금 gain.value 에서 cancelScheduledValues, setValueAtTime, linearRampToValueAtTime(0), stop(when), 음악은 setValueAtTime(0), linearRampToValueAtTime(크기) 와 지금 값에서 줄여 stop(when), 버스는 setTargetAtTime(크기, 지금, 0.05). 끝난 소리는 원본 onended 자리처럼 update 가 목록에서 뺀다
- 웹은 WebAudio AudioParam 과 AudioBufferSourceNode.stop(when)에 그대로 건다. (컨텍스트를 깨우는 동안 받은 stop 은 시작할 때 건다)
- 데스크탑 믹서의 GainNode gain 을 AudioParam 으로 바꿨다. (platform/audio/audioparam.rs, 크로미엄 audio_param_handler.cc 의 사건 넣기, 지난 사건 치우기, 새 사건 당기기, 선형과 지수 램프, 목표 따라가기, 목표 뒤 램프, 지우기를 옮겼다. x86_64 는 크롬의 SSE 4 줄 묶음과 같게) 자동화가 있는 퀀텀은 표본마다, 없으면 퀀텀마다 하나로 곱하고, 소스가 없어도 자동화는 흐른다. 소스의 stop(when)은 그 시각을 올림한 프레임에서 끊는다. 시계는 그린 프레임 수 / 표본율이다
- AudioPlayer, AudioBus 에 엔진 안에서 쓰는 apply_gain_automation, get_gain_value(원본 gain.value 읽기), stop_at_time 을 더했다. (공개 API 는 그대로다)
- 믹서 시험의 크롬 158 OfflineAudioContext 그래프를 다섯에서 아홉으로 늘렸다. (앞만 틀기와 버스 setTargetAtTime, 그리는 도중 suspend 로 멈춰 지금 gain.value 에서 줄여 끄기, 음악 겹쳐 바꾸기, 지수 램프와 목표 뒤 램프와 지우기) 모두 1e-6 안에서 같다
- BeepPlayer 의 데스크탑 톤을 원본 playTone 의 그래프 그대로 믹서에서 셈한다. 지금까지는 같은 엔벨로프와 파형을 식으로 그려 표본을 섞었다
- 그래프: OscillatorNode(type, frequency.setValueAtTime(주파수, 시작)) → GainNode(setValueAtTime(0.0001, 시작), linearRampToValueAtTime(최고, attack 끝), setValueAtTime(최고, release 시작), exponentialRampToValueAtTime(0.0001, 끝)) → 출력, start(시작), stop(끝 + 0.01). 시각은 부른 때의 컨텍스트 시계 + 지연이다 (원본과 같은 차례로 더한다, 웹판도 같은 BeepSchedule 을 쓴다)
- OscillatorNode 는 크로미엄 oscillator_handler.cc, periodic_wave_handler.cc 와 CPU 별 커널을 옮겼다. (platform/audio/oscillator.rs) 대역 제한 표(표본율에 따라 2048, 4096, 16384 칸, 1/3 옥타브마다 하나, 첫 표 꼭대기로 정규화), 시작과 정지 프레임(올림, 표본 사이 시작), frequency 가 자동화 중인 퀀텀의 표본마다 걸음(a-rate)과 그 밖의 퀀텀에 하나(k-rate), 두 점, 세 점, 다섯 점 보간을 크롬과 같은 차례, 같은 f32, f64 정밀도로 셈한다. 4 표본 묶음은 aarch64 는 NEON 판, x86 은 SSE2 판, 그 밖은 스칼라 판이다
- 자동화 시각은 원본 메인 스레드처럼 부른 때의 시계로 당기고, 그리기 전에 지금 퀀텀으로 한 번 더 당긴다. (AudioParam::apply_automation_at_call_time) 표는 컨텍스트처럼 표본율마다 한 번 지어 둔다
- 크롬 158 OfflineAudioContext 의 원본 playTone 그래프 아홉 경우(네 파형, 프리셋 시퀀스, 표본 사이 시작, 그리는 도중 부르기, 표본율 22050, 96000, 3 점과 5 점 보간, 나이퀴스트 가까이)와 표본마다 견주는 시험을 더했다. (tests/assets/mixer/chromebeep.cjs 가 찍은 chrome_beep.json) 모두 1.2e-7 안이다
- x86 의 SSE2 판은 크롬과 같게 짰지만 기대값을 애플 실리콘 맥(arm64 크롬)에서 뽑아 x86 크롬과는 견주지 못했다. (시험은 CPU 가 다르면 1e-4 로 본다)
- 툰 셰이딩을 실시간 툰 렌더링의 정석 꼴로 다시 지었다. (vanilla.js 와 같은 셰이더, 같은 값)
- 그늘 램프: 빛을 받는 몫(반 램버트 기본)에 그림자를 곱해 램프에 대어 색을 고른다. 칸마다 자리, 선형 색, 부드러움, 경계는 fwidth 로 계단 없이. 그림자는 그늘 색으로 들어간다
- ToonLightSet::set_shade(ToonShade { step, feather, color, second_step, second_feather, second_color, is_half_lambert }), set_shade_ramp(자리, 색, 부드러움, 반 램버트), clear_shade_ramp, set_ramp_texture(Option
, 반 램버트) - set_band_count, set_band_ramp 는 같은 램프로 짓는다
- ToonLightSet::set_shade(ToonShade { step, feather, color, second_step, second_feather, second_color, is_half_lambert }), set_shade_ramp(자리, 색, 부드러움, 반 램버트), clear_shade_ramp, set_ramp_texture(Option
- 빛마다: 해는 램프 색을 통째로, 채움 빛, 점광, 스포트라이트는 램프의 밝기 단계를 받는다
- 하이라이트: set_specular(세기, 지수, 부드러움, 색), 해와 점광 모두. 림 빛: set_rim_light(색, 거듭제곱, 부드러움, 해 쪽 가림), 바탕색에 곱하지 않고 더한다
- 스포트라이트: ToonPointLight 의 direction (Some 이면 스포트라이트), inner_cone_angle, outer_cone_angle (기본 0 과 π/4)
- ToonDrawOptions: receives_shadow, shade_offset, specular_scale, rim_scale, matcap_texture, matcap_strength, matcap_blend (ToonMatcapBlend), outline_color, outline_width_scale
- 표면 조각에 shadeOffset, specularMask, rimMask, 빛 조각에 rim, sunLevel
- 노멀을 역행렬의 전치로 옮긴다. (늘이고 줄인 모형의 빛과 화면 공간 꺾임 선을 바로잡음)
- 기본 빛: 해 [0.84, 0.8, 0.74], 하늘 [0.3, 0.33, 0.42], 땅 [0.17, 0.16, 0.15]
- 그늘 램프: 빛을 받는 몫(반 램버트 기본)에 그림자를 곱해 램프에 대어 색을 고른다. 칸마다 자리, 선형 색, 부드러움, 경계는 fwidth 로 계단 없이. 그림자는 그늘 색으로 들어간다
- ToonRenderer: 껍데기 바깥선을 셰이더에서 민다. (바탕 자리와 미는 쪽, outline_color, outline_width_scale, set_outline_distance_scale, get_outline_distance_scale) read_view_rotation, read_outline_vertex_data 를 내보낸다
- ToonMatcapBlend: 매트캡을 섞는 방식. (Multiply, Add)
- ToonShade, ToonShadeRamp, ToonRimLight, ToonSpecular 를 크레이트 맨 위에서 내보낸다
- 툰 폴더 파일의 머리 주석을 채웠다. (모든 함수와 공개 칸)
- 툰을 유니티와 언리얼이 기본으로 갖춘 수준까지 채웠다. (vanilla.js 와 같은 셰이더, 같은 값)
- ShadowMap: 지을 때 앞의 텍스처와 프레임버퍼 묶음을 돌린다. (모형 뒤에 지으면 깊이 텍스처가 유닛에 남아 INVALID_OPERATION 이던 것) 빛이 거의 바로 아래나 위로 나아가면 위쪽을 z 축으로 잡는다. (광원 행렬이 깨지던 것)
- ShadowAtlas, ShadowAtlasLight, ShadowAtlasLightSource, ShadowAtlasTile, SHADOW_ATLAS_MAXIMUM_LIGHTS: 점광(큐브 여섯 면)과 스포트라이트(원근 한 칸)의 그림자를 깊이 텍스처 한 장에 칸으로. update_lights(&light_set.read_shadow_light_sources()). 받는 자리는 노멀 쪽으로 칸 텍셀 (1 + 3 x (1 - dot(N, L))) 개만큼 밀어 그림자 여드름을 막는다
- ToonRenderer: set_local_shadows(Option<&ShadowAtlas>, 세기), begin_shadow_atlas_pass, set_shadow_atlas_tile, set_outline_fade_distance, get_outline_fade_distance, set_light_color_usage, set_shade_rim_light. ToonDrawQueue::draw_local_shadows
- ToonPointLight: casts_shadow, shadow_near (기본 false, 0.05). 이름으로 지을 때는 ..ToonPointLight::default()
- ToonLightSet: set_light_color_usage(ToonLightColorUsage), set_shade_rim_light, get_shade_rim_light (ToonShadeRimLight), read_shadow_light_sources. 림, 매트캡, 껍데기 바깥선도 기본으로 해의 색을 곱한다. 지금까지 모습은 ToonLightColorUsage { rim: false, matcap: false, outline: false, ..Default }
- ToonDrawOptions: outline_offset_z, angel_ring_texture, angel_ring_color, angel_ring_offset_u, angel_ring_offset_v, is_angel_ring_alpha
- 2 번 UV: ToonGeometry.uvs1, ToonMeshArrays.uv1_data, add_triangles_with_uvs 의 마지막 인자 uvs1 (공개 API 를 바꿨다, 2 번 UV 가 없으면 None), read_glb_arrays 가 TEXCOORD_1 을 읽는다. read_uv_data
- 텍스처 유닛: 점광 그림자 0, 천사 고리 7, 머티리얼 8 ~ 15. TOON_MAXIMUM_MATERIAL_TEXTURES 9 → 8. 유닛 0 은 begin_frame 이 적어 두고 end_frame 이 돌린다
- ToonScreenOutline: 반 크기 판의 계단을 없앴다. 선의 판과 씨앗은 그리는 영역 해상도, 점프 플러딩만 줄인 판(모으기 패스로 씨앗을 모음), 씨앗 자리는 그리는 영역 화소 좌표. set_resolution_scale 은 선의 판과 넓히기 판의 몫(그리는 영역 x 몫)이다. ToonLineTarget: seed_framebuffer, seed_texture, jump_flood_framebuffers, jump_flood_textures, jump_flood_index, jump_flood_width, jump_flood_height. read_program_sources 가 다섯을 준다
- tools/apidoc(워크스페이스 크레이트 vanilla-engine-apidoc, syn 과 serde_json 만 쓴다): 문서 주석에서 API 문서 자료 docs/api/<판>.json 을 뽑는다. vanilla.js tools/apidoc.cjs 와 같은 자료 꼴에 클래스의 kind(struct, trait, type), traits, counterpart 를 더했다. --check(꼴 검사와 수 세기, 가이드 ko 와 en 대조), --missing(번역 표에 없는 ko 글), --gaps(문서가 빈 곳), --counterpart(vanilla.js 자료와 이름으로 짝 짓기). since 는 v0.3.2 태그의 소스와 대어 정한다. 쓰는 법은 tools/TOOLS.md
- docs/api/0.4.0.json(모듈 216, 클래스 496, 멤버 4930, 함수와 상수 354, 열거 89), 영어 번역 표 docs/api/translation.en.json, vanilla.js 와 같은 항목의 짝 표 docs/api/counterpart.0.4.0.json(vanilla.js 쪽 자료가 러스트 짝을 채울 때도 쓴다)
- 천사 고리: 카메라 기울임만큼 UV 를 되돌려 돌린다. (vanilla.js 와 같은 셈, read_camera_roll) 카메라를 기울여도 고리가 머리에 붙어 있다
- 빛 세기 막기: ToonLightSet::set_light_intensity_limited, is_light_intensity_limited (렌더러에도 set_light_intensity_limited). 유니티 툰 셰이더의 Limit Light Intensity 와 같은 셈, 기본 켬. 지금까지 모습은 set_light_intensity_limited(false). 옛 게임 셰이더(빛 세기를 막지 않던 것)를 옮길 때나 세기 1 을 넘는 점광, HDR 블룸을 쓸 때는 set_light_intensity_limited(false). 빛 색 쓰기를 끈 색의 세기와 껍데기 바깥선의 해 색도 유니티 툰 셰이더와 같게
- ShadowAtlas::new(gl, 해상도, 칸 해상도): 칸 크기를 유니티 URP 기본과 같게 칸마다 1024 를 바라고 다 들어가지 않으면 반씩 줄인다. DEFAULT_SHADOW_ATLAS_RESOLUTION (2048), DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION (1024), get_tile_resolution. (new 에 인자가 하나 늘었다)
- 뼈 행렬 유니폼 블록(원본 뼈 행렬 JointBlock 과 같게, 유니티 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). 툰 렌더러, 툰 바깥선, 스키닝 렌더러, 피부 렌더러가 모두 이 길을 쓰고, ShaderProgram 이 링크 뒤에 JointBlock 블록을 같은 자리로 묶는다. 모프 가중치 배열은 float 96 개(96 칸)에서 vec4 24 칸으로 줄였다. 정점 유니폼 칸 수는 tests/uniformlimit.rs 가 엔진이 짓는 프로그램마다 한도(정점 256, 조각 224)를 넘지 않는지 숨긴 창의 GL 에서 본다. 화면은 그대로다
성능
- 툰 프로그램 변형 미리 짓기(원본 5b8ae8c 와 같게, 정석: 유니티 ShaderVariantCollection.WarmUp, 언리얼 PSO 캐시처럼 첫 그리기 전에 지음, 화면 그대로): 몸 기능 변형은 처음 보는 조합을 그리는 첫 프레임에 프로그램을 지어 한 번 끊길 수 있었다. ToonRenderer::prewarm_draw_queue(gl, queue) 를 더했다. 그리기 줄에 담긴 것이 그릴 때 쓸 변형(머티리얼, 몸 기능 비트, 모서리 어둠 몸, 바깥선, 그림자 깊이)을 그리지 않고 그리기와 같은 열쇠로 미리 짓는다. GL_KHR_parallel_shader_compile 이 있으면(웹은 같은 확장) 컴파일만 맡기고 ToonProgramPrewarm::step 이 프레임마다 끝난 것을 한 걸음에 셋까지 나눠 끝내 주 스레드를 막지 않으며, 없으면 호출 안에서 짓는다. 돌려주는 ToonProgramPrewarm 의 is_ready(), wait(gl, renderer)(남은 것을 그 자리에서 모두 끝냄)로 끝을 안다. 끝나기 전에 그려도 되고 아직 안 지어진 변형은 지금처럼 그 자리에서 짓는다. ShaderProgram 은 ShaderProgram::create_deferred, is_deferred(), is_build_complete(gl), finish_build(gl), 정적 is_parallel_compile_supported(gl) 를 더했다(기본 동작 그대로). 그리기 줄이 인스턴스 버퍼를 담는 길이 들어오면 그 인스턴스 꼴의 변형도 같은 길로 미리 짓게 이어 붙일 자리를 남겼다. 시험: 미리 짓기 없이 첫 그리기 프레임이 프로그램 6 개를 짓고 미리 짓기 뒤에는 0 개, 화면은 바이트까지 같다. (맥 GL 은 병렬 컴파일 확장이 없어 맡기는 길은 시험 전용 스위치로 같이 돌림)
- 툰 미리 짓기(원본 jsprewarmwait 와 같게): 그리지 않고 프레임만 넘기며 미리 짓기가 끝나길 기다리는 불러오기 화면에서 미리 짓기가 나아가지 않을 수 있던 것을 고쳤다(원본에서 게임 세션이 맥 헤드리스 크롬에서 잰 값: 45 프레임을 기다려도 끝나지 않아 한꺼번에 끝내며 8,183 ms 프레임 하나). 맡긴 컴파일과 링크 명령은 그리기나 지우기가 없는 프레임에는 GPU 로 저절로 흘러가지 않을 수 있어(KHR_parallel_shader_compile 명세 원문에는 flush 얘기가 없다, 크로미엄 원문 확인은 못 했다) ToonRenderer::prewarm_draw_queue 와 prewarm_draw_queue_with_options 가 맡긴 뒤, 그리고 ToonProgramPrewarm::step 이 아직 남았으면 걸음마다 GlContext::flush 로 보낸다. ShaderProgram::is_build_complete 는 한 번 끝났다고 확인하면 다시 묻지 않는다. 화면은 그대로, 공개 API 는 그대로. 이 기계(맥 GL)에는 병렬 컴파일 확장이 없어 맡기는 길을 시험으로 강제해 flush 횟수(맡긴 뒤 1 번 이상, 남은 걸음마다 1 번)와 그리지 않고 0, 1, 2, 45 프레임 넘긴 뒤 그려도 화소가 나오는 것을 확인했다. 실제 병렬 확장이 있는 기계(윈도우, 리눅스)에서 돌려 본 것은 아니다.
- 툰 몸 셰이더의 점광 고리를 반지름 밖에서 건너뜀(원본과 같게): 점광 반지름 밖(lightRange > 0 이고 rangeExponent > 0 이고 lightDistance >= lightRange)은 감쇠 창이 정확히 0 이라 기여가 0 인데도, 몸 셰이더가 그 화소에서 pow 둘, 그림자 읽기, 칸 읽기까지 끝까지 셈했다. 이제 도함수(fwidth)는 갈래 밖에서 모든 화소가 함께 셈하고(갈래 안 도함수는 쿼드 이웃이 건너뛰면 정해지지 않는다), 반지름 밖이면 도함수 없는 무거운 셈(감쇠, 칸 읽기, 색 한계)을 건너뛴다. 점광 그림자 읽기는 칸 값에 들어가 갈래 밖에서 읽는다. 건너뛴 화소의 원래 기여는 감쇠가 0 이라 readLimitedLocalColor(0) 과 readLightColor(0) 이 0 이고 칸 값은 모두 clamp 된 유한한 수라 화면은 바이트까지 같다. 광부(아이패드 미니 6, 등불 하나 range 2.6)가 갈라 점광 하나가 프레임 약 4 ms 를 쓰는 것을 찾았다.
- 툰 프레임 블록 ToonFrame(원본 jsubo 와 같게, std140, 바인딩 2, float 172): 카메라, 빛, 그림자, 바깥선 거리, 점광 그림자, 모서리 어둠 원점과 직접 빛 몫을 프로그램마다 유니폼 자리로 올리던 것을 블록 하나로 바꿨다. 칸 차례와 셰이더 블록 선언은 원본과 글자까지 같다(시험이 원본 파일과 견준다). 몸, 바깥선, 깊이 프로그램이 같은 블록을 바인딩 2 로 읽고, 패스(frame_serial)마다 값을 한 번 쓴 뒤 같은 값이 든 버퍼가 있으면 그 버퍼를 묶고(올림 없음) 새 값은 begin_frame 여덟 번 동안 안 쓴 버퍼에 buffer_sub_data 로 쓴다(모자라면 새로 짓는다). 그림자나 점광 그림자가 없으면 빛 행렬과 그림자 세기 칸, 아틀라스 칸은 앞의 값 그대로다(원본과 같다). 방 구석, 모서리 어둠, 강조, 스타일, 쇼케이스, 후처리, 뷰 예제 화면은 고치기 전과 바이트가 같다.
- 툰 재질 블록, 자동 인스턴싱, 선의 판 묶음 자리(원본 f3f18e5, 5221c43, 1ffc38b, 90e3286, 3fd1a61 과 같게, 유니티 SRP Batcher 의 UnityPerMaterial 과 GPU 인스턴싱, 언리얼 auto-instancing 꼴): 몸 프로그램의 재질 값 열아홉(tintColor, tintAmount, alpha, glowScale, colorScale, emissiveColor, softEdge, alphaCutoff, premultipliedOutput, textureEnabled, uvTransform, decalUvTransform, decalColor, receivesShadow, shadeOffset, highlightScale, matcapSettings, angelRingSettings, angelRingColor)를 std140 유니폼 블록 ToonDrawMaterial(바인딩 0, float 44)로, 바깥선 껍데기 값 여섯(outlineColor, outlineLightColor, outlineWidthScale, outlineOffsetZ, alpha, premultipliedOutput)을 ToonDrawOutline(바인딩 1, float 12)으로 바꿨다. 칸 차례와 셰이더 블록 선언은 원본과 글자까지 같다. 값이 같은 블록은 하나(FNV-1a 해시와 비트 견줌), 그리기마다 bind_buffer_base 하나(같으면 건너뜀)이고, 갈래마다 1024 개에서 오래 안 쓴 블록 하나를 시계 꼴로 내보내 그 버퍼에 buffer_sub_data 로 새 값을 쓴다(버퍼를 지우거나 새로 짓지 않음). ToonDrawQueue 는 정렬 넷째 열쇠로 재질 블록을 쓰고, 정렬로 이어진 같은 모형, 같은 재질 블록, 같은 감기, 같은 그리기 꼴(선 번호, 묶음, 깊이 먼저, 그림자 드리우기, 거르기 말고 모두 같음, 뼈대 행렬이나 on_before_draw 가 있거나 비치는 것은 제외)인 불투명한 보통 모형을 인스턴스 그리기 한 번으로 묶는다(몸, 바깥선 껍데기, 그림자 깊이, 점광 그림자 칸마다). 묶음 자리(버퍼와 모형별 버텍스 어레이)는 프레임마다 같은 차례로 주고 행렬이 앞 프레임과 같으면 다시 올리지 않으며 몸과 껍데기가 같은 자리를 쓴다. ToonScreenOutline 도 선의 판 번호 그리기를 같은 모형과 선 꼴끼리 묶어(accept_mesh 로 거르고 초점 거리에 더한 뒤 draw_mesh_batch) 자기 묶음 자리를 두고 같으면 올리지 않는다(번호는 틴트 칸 x). 선의 판의 instanced, instanceLineIds, skinned, lineFlags 유니폼은 바뀔 때만 올린다. 화면은 바이트까지 같고(고치기 전 코드와 화면 해시가 같음), 같은 장면의 드로 콜이 28 에서 4 로 준다. 원본 toonautoinstancechrome 과 같은 장면의 인스턴스 수 목록이 같다([11, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2]).
- 툰 화면 바깥선 가는 선 길, 해상도 몫, 판 앞 비우기(원본 bf61a70, 2d1dad4, 1dce73d, 12f654c, 8ade0ed 와 같게, 유니티 URP 화면 공간 외곽선과 같은 꼴, 굵기 반지름 안 이웃을 한 번에 보기): ToonScreenOutline 이 굵기 약 3.24 픽셀(2 x sqrt(4.5) - 1)까지는 점프 플러딩(씨앗, 모으기, 넓히기 셋) 없이, 씨앗 고르기와 같은 차례로 화소마다 바깥 선과 꺾임 선의 첫 경계 쪽을 담은 판(R8UI 한 바이트)을 고르고, 섞기가 둘레 3 x 3 화소의 씨앗을 점프 플러딩 마지막 걸음과 같은 차례로 보아(아홉 번 읽기, 갈래 없는 고르기) 가장 가까운 것까지의 거리로 덮는 몫을 셈한다. 선의 판 뒤 화면 전체 패스가 여섯(씨앗, 모으기, 넓히기 셋, 섞기)에서 둘(가면, 섞기)이 되고, 화소마다 쓰는 판이 RGBA16UI 셋(24 바이트)에서 R8UI 하나(1 바이트)가 된다. 굵은 선과 선 색 표는 지금 길 그대로이고, 씨앗 판과 넓히기 판은 처음 굵은 선을 그을 때 짓는다. set_resolution_scale 은 섞기 앞의 모든 판(선의 판, 가면, 씨앗, 넓히기 판)을 그리는 영역 x 몫으로 줄인다(이전에는 넓히기 판만). 기본 1 은 화면이 바이트까지 그대로다. 몫이 1 보다 작으면 가는 선(굵기 x 몫이 약 3.24 선의 판 픽셀 이하)은 선의 판 해상도에서 덮는 몫(진하기와 번호 색을 곱한 RGBA8 판, get_line_target().coverage_texture)을 한 번 셈하고 마지막 섞기가 그것을 쌍선형으로 한 번만 읽는다(읽기 아홉에서 하나). 굵은 선은 선의 판 해상도에서 점프 플러딩을 하고 섞을 때 거리를 그리는 영역 픽셀로 곱해 잰다. 선 굵기(set_width)는 어느 몫이든 그리는 영역 픽셀이다. 판을 통째로 덮어쓰는 패스(가면, 씨앗, 모으기, 넓히기, 덮는 몫)는 앞에 판 비우기(clear_buffer_u32_slice, clear_buffer_f32_slice)를 불러 타일 GPU 가 옛 내용을 읽어 들이지 않게 한다(원본은 사파리에서 invalidateFramebuffer 가 프레임마다 10 ~ 25 ms 를 붙여 비우기로 바꿨고, 러스트에는 invalidate 가 없어 같은 자리의 비우기만 둔다). 셰이더 글은 원본과 글자까지 같다. 두 엔진이 같은 방 장면(640 x 360, 굵기 2, 2.62, 3, 6 x 배율 1, 0.75, 0.5, 번호 색 표 포함 열다섯 화면)에서 배율 1 은 화소 4 개(바깥선과 무관한 몸 밝기 띠), 배율 0.75 와 0.5 는 0 화소 다르다(고치기 전에는 배율 0.5 에서 5792 ~ 8176 화소, 가장 큰 차이 211). 원본의 선의 판 묶음 자리(3fd1a61)는 러스트 ToonDrawQueue 에 자동 인스턴싱 묶음이 아직 없어 옮기지 않았다.
- 하위 트리째 그리기 건너뛰기(원본 jssubtree 셋과 같게, 장면 그래프의 경계 더러움, OSG dirtyBound, Godot item_rect_changed 꼴): 노드마다 자기 그림과 켜지고 보이는 자식들 경계의 합(하위 트리 그리기 경계, 노드 내용 좌표)을 바뀐 때만 다시 셈해 두고, 그리기가 그 경계가 화면과 걸린 자르기 밖이면 노드와 자손의 그리기를 통째로 건너뛴다(tick 은 그대로). 부모가 셈하며 자식마다 부모 좌표 경계를 적어 두어 변환을 걸기 전에 먼저 거르고, 자식이 많으면 보이는 자식 범위를 이분 찾기로 좁힌다. 트랜스폼, 노드, 컴포넌트 세터는 값이 바뀔 때만 더러움을 알리고(같은 값이면 알리지 않는다) NodeTree 가 그리기 전에 조상으로 번진다. 경계를 알리지 않는 컴포넌트, 기즈모를 그리는 노드가 들면 그 조상은 건너뛰지 않는다. 그리지 않는 컴포넌트(draw 를 덮어쓰지 않은 것, ButtonMotion, UINode 같은)는 아무것도 그리지 않는 것으로 본다(반영 매크로가 Component::is_draw_overridden 을 짓는다). Graphic::set_subtree_culling_enabled(기본 켬), is_subtree_culling_enabled, get_last_frame_culled_subtree_count, add_culled_subtree_count, read_local_visible_bounds, NodeTree::read_subtree_draw_bounds, read_parent_draw_bounds, draw_children, WorldNode::mark_draw_bounds_dirty, mark_parent_draw_bounds_dirty, get_last_drawn_frame_number, ComponentBase::mark_drawn_rect_dirty, mark_all_drawn_rects_dirty(글꼴을 등록하면 엔진이 부른다), get_drawn_rect_generation, Component::mark_drawn_rect_dirty 를 더했다. 지난 프레임에 그리지 않은 노드는 글 굽기 배율이 처음 그리는 것처럼 정해진다. UILineChart 는 범위 밖 값의 선까지, UIBarChart 는 넘치는 막대까지, UISlider 는 손잡이 원까지 그리는 사각형을 알린다(고치기 전에는 내용 영역이 화면 밖인 선 그래프의 범위 밖 선이 화면에서 사라졌다). 예제 subtreecull(SUBTREECULL_CHECK=1)이 원본 시험과 재기 도구 장면을 켬, 끔, 모두 끔으로 찍어 화면 바이트와 프레임마다 그린 수를 견준다. 원본 재기 도구의 엔진 장면은 켬 건너뛴 하위 트리 231(원본 231), 변환 건 노드 끔 2164(원본 2164), 켬 멈춤 79, 스크롤 85(원본 노드 79, 85, 원본 셈에는 스크롤 칸 자르기 하나가 더 든다), 광부 설정 창 꼴(SUBTREECULL_SCENE=rimminer)은 켬 변환 건 노드 멈춤 59, 스크롤 55, 건너뛴 하위 트리 281(원본 59, 55, 281), 끔 1274(원본 1274). LayoutVariable::set_value_changed_event, get_value_changed_event(LayoutVariableEvent, 값이 달라질 때만 부른다, 원본 setValueChangedEvent)를 더했다. 러스트 UINode 는 푼 값을 노드 트랜스폼에 넣으므로 트랜스폼 세터가 더러움을 알린다. ShadowImage 는 굽기와 굽는 배율과 상관없이 번짐 두 배와 굽는 여유, 그림자 내림을 더한 넉넉한 사각형을 알린다(원본과 같게).
- Graphic 이 묶음과 2D 상태를 따로 기억하지 않고 그리기 앞에 GL 상태 캐시에 견준다(원본 db99208 과 같게, three.js WebGLState 꼴): 마지막으로 쓰게 한 프로그램, 0 번과 1 번 유닛, 묶음 유닛의 텍스처, 색 쓰기 마스크를 Graphic 이 따로 기억하던 것을 걷고, 상태 캐시에 견줘 다를 때만 건다. 그리기 바로 앞에서 섞기(켬, FUNC_ADD, 지금 블렌드 모드의 인자), 깊이 시험과 면 가리기 끔, 자르기 가위가 아니면 가위 끔, 드로잉 버퍼 전체 뷰포트를 상태 캐시에 견줘 맞추고(apply_draw_state), 낱장 길은 기본 버텍스 어레이와 정점 버퍼도 견줘 묶는다. 상태 캐시가 ARRAY_BUFFER 묶음을 기억하고(GlContext::bind_buffer, create_buffer, delete_buffer 를 더함, 검사 모드도 ARRAY_BUFFER_BINDING 을 견준다), GL 에 묻지 않는 견주기를 더했다. 그래서 게임이 run_external_pass 밖에서 get_gl 로 섞기, 깊이, 면 가리기, 가위, 뷰포트, 버텍스 어레이, 정점 버퍼, 활성 유닛을 바꿔 두고 돌아와도 다음 2D 그리기가 맞게 된다(전에는 묶어 그리기에서 섞기 인자와 식, 깊이, 면 가리기, 가위, 뷰포트, 낱장 그리기에서 그에 더해 버텍스 어레이와 정점 버퍼가 틀렸다). restore_render_state 는 원본처럼 스텐실 자르기를 건드리지 않고, run_external_pass 가 끝에 스텐실 자르기 상태를 되돌린다(셰이더 자르기가 없을 때도). 웹 판이 GL 컨텍스트를 잃거나 되살리면 상태 캐시를 잊는다.
- GameSceneBase 로딩 시각과 건너뛰기를 엔진 프레임 자리로(원본 df379ce 와 같은 꼴): 로딩 문(최소 노출 시간과 터치 건너뛰기, 첫 프레임 전에 불렀으면 첫 로딩 프레임의 시각부터 잼)을 SceneBase 가 들고, 엔진이 불러오는 중인 씬마다 프레임마다(시간을 올린 뒤, 로딩 화면 draw_on_load 앞) 엔진 시계와 엔진 입력으로 갱신한다. 지금까지는 GameSceneBase::draw_on_load 안에서만 갱신해, Scene 을 바로 구현하고 GameSceneBase 를 품은 씬이 바탕 draw_on_load 를 부르지 않으면 오류 없이 로딩 화면에 멈췄다(game_scene!, ui_scene! 은 바탕을 늘 불러 멈추지 않았다). 문이 그리기 앞에서 열려 initialize 가 전보다 한 프레임 이르게 불릴 수 있다. update_loading, begin_loading, get_loading_progress, is_load_touched_to_skip 은 그대로 쓴다.
- 그림자 다시 그리기 줄이기(원본 4dabf62, 2eefc5a 와 같게, 유니티 HDRP 의 빛마다 그림자 갱신 방식, 언리얼의 캐시된 그림자 맵 꼴): ShadowMap 과 ShadowAtlas 에 set_update_mode(ShadowUpdateMode, 프레임 수), get_update_mode, get_update_interval, request_update 를 더했다. ShadowUpdateMode 는 EveryFrame(매 프레임 전부, 지금까지의 동작), OnChange(기본), Interval(N 프레임마다 전부, 사이의 프레임은 앞의 그림자를 그대로 쓴다). OnChange 에서 ToonDrawQueue::draw_shadows 와 draw_local_shadows 는 드리우개를 담은 차례로 앞의 프레임과 견준다(모형, 재질, 모형 행렬과 인스턴스 행렬, 관절 행렬, 번호 버퍼의 범위, 화면 밖 거르기, 뒤집기, 빛 행렬과 아틀라스 칸). 30 프레임 그대로인 드리우개는 따로 구운 판에 굽고, 움직이는 것(과 정점 조각이 있는 재질)만 매 프레임 구운 판을 판에 옮긴(blit_framebuffer) 뒤 그 위에 덧그린다. 구운 것이 바뀌거나 빠지거나 새로 구울 것이 생기면 다시 굽고, 빛이 바뀐 프레임은 전부를 판에 바로 그린다. 다 그대로면 하나도 그리지 않는다. 깊이는 LEQUAL 로 가장 가까운 것이 남아 굽고 덧그린 판은 전부를 한 번에 그린 판과 비트까지 같다. 원본은 모형과 재질을 참조로 견주고 러스트 판은 모형 번호와 재질 번호로 견준다(지우고 다시 지은 것이 같은 주소에 와도 다르게 본다). 원본의 인스턴스 버퍼 견주기(addMeshInstanceBuffer 의 버퍼와 generation)는 러스트 ToonDrawQueue 에 인스턴스 버퍼를 담는 길이 아직 없어 넣지 않았다. 찍기 시험(tests/shadowcache.rs)이 원본 크롬 시험(tests/graphics3d/shadowcachechrome.test.mjs)과 같은 장면 110 프레임을 그려, EveryFrame 과 OnChange 의 화면이 프레임마다 같은지, 다 그대로인 프레임(45 ~ 59)은 그리지 않는지, 상자만 움직이는 프레임은 7 이하인지, Interval 4 는 네 프레임마다만 그리는지, request_update 프레임은 EveryFrame 과 같은 수를 그리는지 본다. OnChange 의 프레임마다 그림자 그리기 수는 110 프레임 모두 원본과 같고, 60 과 65 프레임 화면은 원본과 화소 4 개만 1 씩 다르다. (고치기 전 코드는 OnChange 도 매 프레임 12 ~ 16 을 그렸고 시험이 Interval 의 1 프레임에서 잡는다) 원본의 무거운 툰 장면(바닥, 모양 48, 뼈대 모형 여섯, 바위 인스턴스 400, 해와 점광 둘 그림자, 화면 공간 바깥선, 960 x 540)을 옮겨 맥미니 M2 Pro 에서 릴리스로 잰 프레임당 그림자 그리기는 다 멈춤 238 → 0, 뼈대 모형 여섯 움직임 238 → 39, CPU 프레임 시간 중앙값은 다 멈춤 1.48 → 0.79 ms, 움직임 1.51 → 1.32 ms 이고, 화면은 두 경우 모두 EveryFrame 과 비트까지 같다.
- UI 그리기 캐시와 올리기 줄이기(원본과 같은 꼴, 유니티 UGUI Canvas 가 바뀐 그래픽만 다시 짓는 것과 같은 사상): Graphic 이 컴포넌트마다 그린 정점을 캐시한다(Component::write_geometry_key 로 입력을 알리는 컴포넌트, Graphic::draw_component, set_geometry_caching_enabled, is_geometry_caching_enabled, get_last_frame_geometry_cache_hit_count, get_last_frame_geometry_rebuild_count, get_last_frame_retained_batch_count). 입력이 그대로면 draw 를 부르지 않고, 이동만 바뀌면 행렬만 다시 건다. 묶음은 프레임의 그리기 차례마다 GPU 버퍼에 남겨 바뀐 것이 없으면 정점을 올리지 않고 드로 콜만 내고, 바뀐 범위만 buffer_sub_data 로 고쳐 올린다. 캐시 없이 바로 쓴 정점이 껴도 묶음을 남기고 지난 프레임 같은 자리와 값을 견준다. 2D 묶음 CPU 배열은 사각형 512 개로 시작해 두 배씩 늘고, 프레임 끝 묶음 GPU 버퍼는 처음에 저장소를 잡지 않는다. RenderTarget::resolve 는 풀고 나서 다시 읽지 않는 첨부를 버리고(모바일 타일 GPU), 이어 그리려면 resolve_with_attachment_kept(gl, true)(원본 resolve(isAttachmentKept)). 글리프 잉크 여백은 채우기 2, 외곽선 ceil(두께 / 2) + 2 로 원본과 같고, ShadowText 의 그림자 내림은 사방 여백이 아니라 아래 높이에만 더한다.
- 할당 없는 읽기(원본 readXxx 와 같은 이름): WorldNode::read_content_size, read_pivot, read_local_position, read_local_scale, NodeTree::read_position, read_scale 이 값을 새로 만들지 않고 받을 자리(&mut Vector2)에 적는다. get_xxx 와 같은 값이다.
- 툰 그림자 캐시(ShadowUpdateMode::OnChange)가 바탕색 텍스처 같은 깊이에 닿지 않는 값에 다시 굽던 것 고침(원본 cee86b9 와 같게, 언리얼, HDRP 캐시 그림자처럼 드리우개를 물체마다 견줌): ToonDrawQueue::draw_shadows 와 draw_local_shadows 가 드리우개 기록을 불투명한 것의 정렬 차례(재질, 모형, 바탕색 텍스처)로 견주고 있었다. 한 모양의 바탕색 텍스처가 바뀌면 차례가 밀려, 바뀌지 않은 드리우개도 다르게 보여 구운 판을 통째로 다시 굽거나 아예 굽지 못하고 매 프레임 전부 덧그렸다. 이제 기록은 담은 차례로 견주고, 굽는 것과 덧그리는 것은 지금처럼 정렬 차례로 묶어 그린다. 견주는 값(모형, 재질, 행렬, 뼈대, 그리는 범위, 거르기, 뒤집기)은 그대로이고 틴트, 색, 바탕색 텍스처는 깊이에 닿지 않아 다시 굽지 않는다. 물체가 움직이면 지금처럼 그 프레임에 다시 굽는다. 찍기 시험 tests/shadowcasterorder.rs 가 텍스처만 바뀌는 프레임(40 ~ 79)에 그림자 깊이를 하나도 그리지 않는지(고치기 전 15 번씩 그림), 구운 상자가 움직인 프레임에 다시 굽고 그 뒤 그 상자만 덧그리는지, 화면이 EveryFrame 과 프레임마다 같은지 본다.
- 툰 그리기의 active_texture 줄이기(원본 cee86b9 와 같게): ToonRenderer 가 그리기마다 고른 텍스처 유닛을 0 으로 되돌려, 다음 그리기가 바탕색(유닛 4)만 바꿔도 active_texture(4) 와 active_texture(0) 을 다시 불렀다. 이제 그리기는 유닛을 되돌리지 않고(단계 콜백과 몸 그리기의 on_before_draw 에는 지금처럼 유닛 0 을 고른 채 넘기고, end_frame 이 앞서 고른 유닛을 돌린다), 상태 적어 두기는 이미 유닛 0 이면 유닛을 고르지 않으며, 돌리기는 상태 캐시가 같다고 기억하는 유닛 0 의 묶음과 고른 유닛을 다시 걸지 않는다. 바탕색 텍스처가 그리기마다 바뀌는 프레임의 active_texture 가 26 → 11 로 원본과 같다. 시험(graphics3d::toon::toondrawqueue 의 draw_does_not_reset_texture_unit_each_draw)이 호출 셈, 콜백이 유닛 0 을 고른 채 불리는지, 프레임 뒤 고른 유닛과 유닛 0 의 텍스처가 돌아오는지 본다.
- GL 상태 캐시(원본 WebGLStateCache 와 같은 기억 규칙, three.js WebGLState 와 크롬 GPU 명령 버퍼 클라이언트 꼴): Graphic 이 컨텍스트를 받자마자 컨텍스트마다 하나인 상태 캐시를 건다. glow 는 컨텍스트 함수를 가로챌 수 없어, 엔진의 상태 함수 호출(bind_framebuffer, viewport, scissor, enable, disable, clear_color, color_mask, blend_func, blend_func_separate, depth_mask, depth_func, front_face, cull_face, use_program, bind_vertex_array, active_texture, bind_texture, pixel_store_i32 와 만들기, 지우기, 링크)이 모두 이 캐시를 거쳐 GL 을 부르고 바뀐 값을 기억한다. 그리는 중 상태 읽기(엔진 2D 의 프레임 버퍼 되돌리기, 툰 3D 의 상태 적어 두기, ToonView3D 의 뷰포트, 프레임 버퍼, 비우기 색, 색 쓰기, 켜짐 다섯 같은 것)는 기억한 값으로 답해 GL 에 묻지 않는다. 바뀌지 않는 한도 값은 한 번만 묻고, 기억하지 않는 값은 그대로 묻고, 모르는 값(처음, 검사하지 못한 인자, 링크 결과를 모르는 프로그램, 지운 객체)은 다음에 읽을 때 한 번 묻는다. 엔진이 게임 코드에 GL 을 넘기는 자리(get_gl, run_external_pass 의 pass 끝, 툰 렌더러의 on_before_draw 뒤, 그리기 줄의 단계 콜백 뒤)에서는 잊지 않는다(원본과 같음, 넘기는 GlContext 의 상태 함수가 캐시를 거친다). 진짜 GL 시험(맥 CGL 로 창 없이 짓는 컨텍스트)이 틀린 인자, 지우기, 잊기를 섞어 600 번 마구 부르며 캐시 답과 견주기 함수가 진짜 GL 과 같은지 본다(다른 곳 0). 공개 함수 Graphic::get_current_framebuffer()(지금 그리는 프레임 버퍼, None 이면 창), get_current_viewport()(지금 뷰포트 Rect, 디바이스 픽셀, 왼쪽 아래 원점), reset_gl_state_cache()(기억을 다시 맞춤)를 더했다(원본 getCurrentFramebuffer, getCurrentViewport, resetGLStateCache).
- GL 상태 캐시 검사 모드(기본 꺼짐, 환경 변수 VANILLA_GL_STATE_CHECK=1): 엔진의 그리기 호출(draw_arrays, draw_elements 와 그 인스턴스 판) 바로 앞마다 상태 캐시가 기억한 값(프레임 버퍼 둘, 뷰포트, 가위, 비우기 색, 색 쓰기, 섞기 인자와 식, 깊이 쓰기와 견주기, 앞면과 가리는 면, 프로그램, 버텍스 어레이, 활성 유닛과 유닛마다 텍스처, 켜고 끄기, 픽셀 저장)을 진짜 GL 과 견주어, 어긋나면 그 갈래와 앞의 상태 호출 48 개를 표준 오류에 남기고 그 갈래를 잊는다. 견주는 읽기는 상태를 바꾸지 않는다(유닛마다 텍스처를 읽으려 활성 유닛을 잠깐 바꾸고 되돌린다). 찍기 모드면 찍는 프레임마다 그때까지 견준 그리기 수와 어긋남 수를 남긴다. 게임이 안의 glow::Context 를 꺼내 상태를 바꾼 곳을 찾는 데 쓴다. 진짜 GL 시험 하나를 더했다(GlContext 와 엔진 길로 400 번 마구 바꾸며 40 번 그려 어긋남 0, 날 glow 로 프로그램과 다른 유닛의 텍스처를 바꾸면 하나씩 잡고, 견주는 읽기 뒤 활성 유닛이 그대로인지).
- 툰 3D 그리기 상태 줄이기(원본과 같은 꼴, 유니티 SRP Batcher, three.js WebGLState 와 WebGLUniforms 꼴): ToonRenderer 가 그리기마다 프로그램, 텍스처 유닛 아홉, 앞면 감김과 가리는 면, 버텍스 어레이를 GL 상태 캐시에 물어 같으면 다시 걸지 않고, 유니폼은 프로그램마다 이름별로 마지막에 올린 값을 기억해 같은 값이면 올리지 않는다(본 행렬도 같다, 0 과 -0 은 가르고 NaN 은 늘 올린다, 프레임과 그림자 판의 시작, apply_frame_state(단계 콜백과 화면 공간 바깥선 뒤), 상태 되돌리기, 그 프로그램의 on_before_draw 뒤에는 잊고 다시 올린다). ShaderProgram::use_program 도 상태 캐시가 이미 그 프로그램을 쓴다고 기억하면 건너뛴다. ToonDrawQueue 는 불투명한 것(몸, 바깥선 껍데기, 해 그림자와 점광 그림자 깊이)을 재질, 모형, 바탕색 텍스처의 처음 본 차례로 정렬해 그린다(같은 것끼리는 담은 차례, 비치는 것은 그대로 먼 것부터). toonshowcase(모형 여럿, 인스턴스 바위, 뼈대 모형, 해 그림자, 바깥선 껍데기, 맥미니 M2 Pro 릴리스 빌드, 프레임 121 ~ 360)에서 프레임마다 GL 호출 878 → 396(useProgram 36 → 25, uniform 374 → 118, activeTexture 122 → 40, bindTexture 107 → 35, 상태 바꾸기 161 → 120, 상태 읽기 31 → 11, 그리기 35 그대로), toonview(ToonView3D 와 그리기 줄)에서 1328 → 615(상태 읽기 37 → 2). CPU 프레임 시간 중앙값은 toonshowcase 0.47 → 0.49 ms, toonview 0.43 → 0.45 ms 로 맥의 데스크탑 GL 은 호출이 싸서 거의 그대로다(웹 사파리와 모바일 드라이버처럼 호출이 비싼 곳에서 줄어든다). 화면은 두 예제 모두 바꾸기 전과 바이트까지 같다(두 예제는 실행마다 애셋 읽기와 시각에 따라 가끔 다른 그림이 나오고, 바꾸기 전에도 같다).
- 글자 그리기를 글리프 아틀라스로(원본과 같은 꼴, 스키아 글리프 캐시, 유니티 TextMeshPro 동적 아틀라스, 언리얼 폰트 캐시): 문자열마다 텍스처를 한 장씩 굽던 것을, 처음 보는 글리프만 아틀라스(1024 x 1024 장, 가장 나중에 연 장에 이어 놓고 차면 새 장, 8 장까지, 넘으면 가장 오래 안 쓴 장을 비운다)에 한 번만 굽고 문자열은 글리프 사각형으로 묶음에 넣어 그리도록 바꿨다. 새 문자열을 구워도 묶음을 끊지 않고, 같은 장의 글자는 드로 콜 하나로 묶인다. 장을 비우기 전에는 쌓아 둔 묶음을 먼저 그린다. 칸은 원본과 같은 글자 덩어리마다 하나다. 한글, 한자, 가나, 숫자, 문장 부호, 이모지는 글자 묶음마다, 라틴과 키릴 같은 글자는 낱말째 한 칸이고, 256px 넘는 글꼴과 오른쪽에서 왼쪽 글, 웹(브라우저 Canvas2D 로 굽는다)은 원본처럼 문자열째 칸 하나다. 칸 열쇠는 덩어리에 든 글리프마다 (얼굴, 글리프 번호, 크기, 스키아 서브픽셀 1/4 칸)과 정수 자리 차이, 방식과 선 굵기, 안티앨리어싱이다(원본의 1/8 자리 칸 열쇠가 가리는 래스터와 같다). 그래서 아는 글자로 된 새 문자열(바뀌는 숫자 같은)은 새로 굽지 않는다. 이웃 덩어리의 잉크가 닿는 자리는 칸마다 따로 그려 소수 자리의 선형 거르기와 겹친 잉크 섞기가 문자열째와 조금 다를 수 있다(원본과 같다, 스키아 글리프 캐시와 TextMeshPro 의 꼴). 칸 위아래에는 가장자리 줄을 한 줄씩 되풀이해 구워, 세로 소수 자리에서 칸 끝을 넘어 뽑아도 아틀라스의 다른 줄이 아니라 예전 문자열 텍스처의 CLAMP_TO_EDGE 처럼 가장자리 줄이 나온다. 잉크 없는 덩어리(공백)는 굽지 않는다. 엔트리 상한은 원본처럼 512 에서 1024 로. 글자 50 줄 드로 콜 51 에서 2(바탕 1 포함), 새 문자열 300 개 프레임 351 에서 2. 맥에서 잉크가 닿는 글리프만 묶던 것과 견주면 glyphparity 장면은 다른 화소 1(차이 1), 크롬 원본과의 차이는 그대로(구역마다 차이 8 넘는 화소 0)이고, 외곽선 네 굵기 장면은 이웃 덩어리의 띠가 겹치는 69 화소가 달라졌다(원본도 덩어리마다 긋는다). 새 문자열 300 개 굽기(릴리스) 23ms 에서 15ms, 아는 글자만 17ms 에서 8ms, 아는 숫자로 된 새 문자열 200 개의 올리기 200 번에서 0 번
- TextStringTextureCache::read_atlas_statistics 와 TextAtlasStatistics(atlas_page_count, glyph_count, baked_glyph_count, upload_count, entry_count, 원본 readAtlasStatistics)
- JPEG 해독 빠르기(데스크탑): 결과 비트는 그대로 두고 허프만(11 비트 미리 보기, AC 부호와 값을 한 번에 푸는 표, 0xFF 없는 8 바이트를 한꺼번에 넣는 비트 버퍼), 역 DCT(32 비트로 넘치지 않는 블록은 8 갈래 한꺼번에, 넘치면 64 비트 셈), 늘리기와 색 바꾸기(줄마다 묶어 바로 RGBA 로, 그림 크기의 성분 평면 셋을 두지 않음)를 고쳤다. 12MP 4:2:0 한 장이 스레드 CPU 시간 중앙값으로 124.6ms 에서 69.8ms 로, 옛 zune-jpeg(image 0.25.10, RGBA 까지) 69.4ms 와 같은 수준이다.
- 3D 자산 공유 캐시(SkinnedModelAsset): 같은 파일에서 지은 스킨드 모델 인스턴스들이 메시 버퍼와 버텍스 어레이, 머티리얼 원형과 그 텍스처, 모프 텍스처, 노드와 스킨 원형, 애니메이션 클립을 한 벌만 참조 수로 나눠 쓴다. (유니티의 메시와 sharedMaterial, three.js 복제본처럼, 원본과 같다) 받기 손잡이의 create_model 과 load_from_url_async, load_from_fbx_url_async 는 셰이더 프로그램과 정규화한 주소(SkinnedModelAsset::normalize_key)로 캐시를 찾아 있으면 풀지도 올리지도 않고 인스턴스를 돌려준다. async 받기는 캐시에 있으면 읽지도 않고, 같은 파일을 함께 받는 중이면 바이트를 한 번만 읽는다. (손잡이는 부탁할 때 렌더러를 몰라 바이트는 읽는다) 새로 create_instance(), create_from_asset(자산), get_asset(), get_material(번호)(유니티 Renderer.material, 처음 부르면 사본으로 갈라지고 텍스처는 빌려 씀), get_shared_material(번호), Material::create_instance(), set_base_color_factor, get_texture_byte_count, SkinnedModelAsset(find, register, clear_cache, get_cached_count, normalize_key, retain, release, get_reference_count, get_gpu_byte_count 들)과 SkinnedModelAssetContent 를 더했다. 인스턴스의 destroy 는 제 것(와이어프레임 버퍼, 갈라진 모프 텍스처와 머티리얼)만 지우고 자산을 놓으며, 마지막 인스턴스가 놓을 때 자산이 GPU 자원을 지우고 캐시에서 빠진다. 클립 목록은 인스턴스들이 나눠 쓰고 add_animations_from_fbx_* 로 같은 이름 클립을 더하면 그 자리를 바꾼다. add_morph_target 은 그 인스턴스의 타깃 목록과 모프 텍스처만 갈라 낸다. 잰 값(맥미니 M2 Pro, VANILLA_MEASURE_ASSET_CACHE=1 cargo run --release --example modelviewer, 같은 모형 20 개, 받아 둔 바이트로 짓기만 잼): fox.glb 186 ms, GPU 113.8 MB 에서 8.8 ms, 5.7 MB 로, mannequin_female.glb 45 ms, 32.0 MB 에서 2.0 ms, 1.6 MB 로. GPU 바이트는 원본 판과 바이트까지 같다. 원본과 같은 API, 같은 시험(skinnedmodel.rs 의 asset_cache_shares_resources_and_releases_by_reference_count)이다.
- Canvas2D(데스크탑): set_font 이 크롬처럼 CSS font 줄임 꼴로 읽어 틀린 글(크기나 이름 없음, inherit 같은 CSS 전역 낱말, 틀린 줄높이 등)은 무시하고, get_font 는 크롬이 직렬화한 글을 돌려준다(낱말 소문자, 상대 크기는 px, 줄높이와 너비 빠짐, 이름 따옴표, 시스템 글꼴 낱말). put_image_data 는 폭 x 높이 x 4 가 아닌 픽셀 묶음을 쓰지 않고, 더러운 사각형 꼴 put_image_data_region 을 더했다(두 판). get_image_data 의 프리멀티플라이 풀기가 크롬 CPU 캔버스와 같은 스키아 셈이 됐다(반이 딱 떨어지는 값에서 1 다르던 것). (블링크 base_rendering_context_2d.cc 의 font 게터와 putImageData, shorthands_custom.cc ConsumeFont, 스키아 SkSwizzler_opts.inc, 크롬 158 에서 잰 글 225 개와 65536 짝)
- DynamicFont::rebuild_atlas: 굽지 못하는 글자는 건너뛰고 나머지를 굽는다. 하나도 굽지 못하면 아틀라스를 그대로 둔다. (글자 하나에 묶음 전체가 안 구워지던 것)
- ToonRenderer: GPU 인스턴싱(draw_mesh_instanced, ToonInstance 마다 행렬과 틴트, 몸과 바깥선 모두, 뼈대 모형은 같은 자세), 화면 밖 거르기(모형의 경계 구를 절두체에 대고, 인스턴스는 하나씩 걸러 남은 것만 올린다, ToonDrawOptions.is_culled), 그림자(begin_shadow_pass, draw_mesh 가 깊이만 그리고 end_shadow_pass 가 프레임버퍼와 뷰포트를 돌린다, set_shadow(ToonShadowInput::from_shadow_map) 로 3x3 PCF 로 받는다), HDR 출력(set_hdr_output 이면 선형 색을 낸다), 한 프레임의 그린 수와 거른 수와 드로우콜(get_frame_statistics)
- AudioPlayer: set_playback_rate. 재생 빠르기(음 높이도 같이, 다음 play 부터). 데스크탑 kira playback_rate, 웹 AudioBufferSourceNode.playbackRate
- Color::from_cache(color_string): 색 문자열로 캐시한 색. (From<&str> 은 부를 때마다 소문자 글을 새로 만든다, 1024 개를 넘으면 비우고 다시 쌓는다)
- 폰트 문자열을 브라우저 Canvas2D 의 font 처럼 CSS font 줄임 꼴로 읽는다. (parse_font_string) 크기는 px 밖에 pt, pc, in, cm, mm, q, em, rem, %, larger, smaller, 이름 크기(xx-small ~ xxx-large)를 읽고(상대 크기는 원본 캔버스처럼 10px 에 댄다), "16px/1.5" 의 줄높이는 넘기고, small-caps, 늘이기 낱말, oblique 각도를 받는다. 쉼표로 이은 이름 목록은 글자마다 앞 이름의 얼굴부터 찾는다. (전에는 첫 이름만 썼다) 틀린 문자열은 캔버스 처음 값 "10px sans-serif" 로 본다. FontDescription.family_name_list 를 더했다. (구조체를 직접 짓는 코드는 고쳐야 한다) 크롬의 해석 값과 시험으로 대었다
고침
- 해 그림자 초점 칸(원본 0733926 과 같게, 카메라를 따라 초점이 움직이는 장면에서 OnChange 캐시가 프레임마다 다시 그리던 것을 줄임): ShadowMap 에 set_focus_step(월드 칸), get_focus_step 을 더했다. 칸을 주면 update_light_matrix 가 초점을 월드 x, y, z 각각 칸의 배수에 맞춰 옮겨 한 칸 안에서는 빛 행렬이 같고, 덮는 너비와 깊이에 칸만큼 여유를 더해 초점 둘레가 판 밖으로 나가지 않는다. 텍셀 맞춤은 그 위에 그대로 걸린다. 기본 0 은 지금까지와 같다(텍셀 맞춤만).
- 툰 몸 변형: 장면 중간에 처음 나타나는 조합(빛 묶음에 림, 음영 림, 램프 텍스처 같은 것이 켜져 몸 기능 비트가 바뀌는 때)이 그 프레임을 막던 것을 줄였다(원본 이슈 #2 와 같게). (가) ToonRenderer::prewarm_draw_queue_with_options(gl, queue, &options) 를 더했다(원본은 prewarmDrawQueue 의 선택 인자 options, 러스트는 선택 인자가 없어 짝 함수로). ToonProgramPrewarmOptions(기본값 Default)의 light_feature_list(조합마다 더 켜질 빛 기능 이름, 예 [["rim"], ["rim", "shadeRim"]], 이름은 rampTexture, shadeStops, rim, shadeRim, intensityLimit 이고 잘못된 이름은 Err), light_set_list(앞으로 쓸 빛 묶음), queue_list(나중에 나올 재질과 인스턴스 꼴을 담은 그리기 줄)로 게임이 쓸 조합 목록을 주면(유니티 ShaderVariantCollection 처럼) 그 조합을 미리 짓는다. (나) ToonRenderer::set_async_program_build(is_async), is_async_program_build() 를 더했다(기본 true). GL_KHR_parallel_shader_compile 이 있으면 장면 중간에 처음 보는 몸 변형은 컴파일만 맡기고, 다 지어질 때까지 전부 켠 기본 몸 프로그램으로 그려 프레임을 막지 않는다(화면은 바이트까지 같음). 확장이 없으면 예전처럼 그 자리에서 짓는다. 시험(빛이 네 번 바뀌는 장면): 프레임별 짓기 수 그 자리에서 짓기 [1, 1, 1, 1], 조합 목록 [0, 0, 0, 0], 빛 묶음 목록 [0, 0, 0, 0], 화면은 모두 바이트까지 같다. (맥 GL 은 병렬 컴파일 확장이 없어 맡기는 길은 시험 전용 스위치로 같은 코드를 돌림)
- 고침: 웹 예제가 모두 첫 프레임 전에 멈추던 것(전역 엔진 뒤, 캔버스를 지을 때 설정 제목을 빌린 것이 함수 끝까지 늘어나 attach_graphic 이 설정을 고칠 때 already borrowed 패닉).
- 고침(원본과 같게): 러스트 데스크탑이 시스템 글꼴 가족에서 보통(400)과 굵게(700) 얼굴 둘만 찾아 굵기 200, 300, 500 같은 값이 모두 400 으로 그려지던 것(크롬은 UltraLight, Light, Medium 처럼 가족이 가진 이름 붙은 굵기 얼굴을 고른다). 가족의 모든 굵기, 기울기 얼굴을 후보로 두고 CSS Fonts 의 굵기 고르기 규칙(청한 굵기가 400 ~ 500 이면 500 까지 위로, 그 아래, 그 위 차례, 400 아래면 아래 먼저, 500 위면 위 먼저)으로 고른다. 맥은 CoreText 의 가족 얼굴과 굵기 특성, 윈도우는 DirectWrite 의 가족 글꼴, 리눅스는 fontconfig 의 FC_WEIGHT 를 읽는다. platform::list_family_font_faces 를 더했다. 보통과 굵게는 전과 같다. 맥 크롬 158 의 CSS.getPlatformFontsForNode 와 Helvetica Neue, Apple SD Gothic Neo, Avenir Next, Helvetica 의 굵기 100 ~ 900(바른 꼴과 기울임)이 모두 같은 얼굴이다.
- 고침: 웹에서 CSS 크기가 없는 캔버스(auto_resize_on_window_resize 가 꺼진 예제, 예: batchclip)가 프레임마다 화소 배율만큼 자라 몇만 화소가 되던 것(화소 크기가 그대로 CSS 크기가 되어 캔버스 크기를 정할 때마다 다시 읽은 크기에 배율이 곱해졌다). 처음 읽은 CSS 크기로 고정한다. 웹에서 패닉이 나면 글을 브라우저 콘솔에 남긴다(전에는 unreachable 만 보였다). 스스로 끝나는 예제(batchclip, inputgallery, modelviewer, subtreecull, subtreecullinside, uigallery, uigallery2)가 웹에서도 exit_application 으로 window.close 를 불러 사파리 탭이 닫히던 것(원본도 같은 동작이라 엔진은 그대로, 웹에서는 끝내지 않고 계속 돌게 예제를 고쳤다). modelviewer 예제의 시계를 웹에서 도는 web_time 으로 바꿨다(std::time::Instant 는 wasm 에서 패닉).
- 고침(원본 eb4338b, 4e05c55, 61f4793 과 같게): 축에 맞는 자르기(셰이더 자르기) 안에서 바꿔 끼운 셰이더에 셰이더 섞기를 주면 덧그림 칸을 옮겨 섞을 때 자르기 밖을 덮던 것(덧그림 칸을 비운 뒤 셰이더 자르기 가위를 다시 건다). 투명도 층을 열 때 스텐실만 비워 지난 층의 깊이가 남아, 층 안의 깊이를 비우지 않는 3D 패스(run_external_pass 의 is_depth_cleared 거짓)가 가려지던 것(깊이를 1 로, 스텐실을 지금 자르기 깊이로 같이 비운다). ShadowMap::begin_render 가 가위 시험을 끄지 않아 2D 자르기 안의 바깥 패스에서 판 일부만 비우던 것(해 그림자 판과 점광 판이 같이 쓰는 판 묶기에서 끈다).
- UIDocument 그림과 노드 데이터 고침(원본과 같게): 같은 문서로 적고 읽은 복제본이 본의 그림을 그대로 쓴다. 쓰기(serialize_node, to_json_text)가 imagePath 를 적은 컴포넌트의 그림을 경로로 기억하고, 해석기와 load_images 애셋에서 못 찾으면 그 그림을 넣는다(유니티 Instantiate 처럼). 그래서 UIListView::set_template_node 로 복제한 항목에 그림이 나온다(전에는 해석기가 없으면 항목에 그림이 없었다). 전용 핸들러는 UIDocumentSaveContext::write_image_path(문서 값, 경로, 그림)로 경로를 적으면 같이 기억된다. bind_pending_images 는 그사이 게임이 그림을 넣었거나 경로를 바꾼 컴포넌트를 덮지 않는다. 그래서 UIDocumentLoadContext::bind_image 가 그 자리를 볼 함수 둘(지금 경로, 지금 그림)을 더 받는다. load_images 가 읽지 못한 그림은 다음 load_images 가 다시 요청한다. 노드 참조가 이름이 같은 앞 형제가 있는 노드를 가리키면 적을 때 경고한다(경로는 이름으로만 적어 다시 읽으면 앞 형제에 이어진다). 숨긴 노드(set_visible(false))는 노드 데이터에 visible: false 를 적고 되살린다(보이는 노드는 적지 않아 지금까지 적은 문서와 기대값은 그대로다. 보임을 active 로 쓰는 UIToast 는 지금처럼 active 로만 적는다).
- 고침: 뼈대 모형의 조인트 번호 정점 버퍼(SkinnedModel::bind_integer_attribute)가 u16 번호를 f32 로 바꿔 올리면서 포인터는 UNSIGNED_SHORT 로 읽어(로직 수를 f64 로 옮길 때 섞여 든 것), 셰이더가 깨진 번호로 jointMatrices 배열 밖을 읽었다(정의되지 않은 동작). 원본처럼 u16 그대로 올린다(원본 Uint16Array). 그 탓에 modelviewer 의 마네킹 둘이 T 자세로 서 있었고, 드라이버가 배열 밖에서 무엇을 읽느냐에 따라 팔의 삼각형이 길게 늘어지기도 했다(상태 캐시 경계의 잊기를 걷으면 늘어지고 GL 에 무엇이든 물으면 사라져, 상태 캐시 탓으로 보였던 것). 이제 마네킹이 클립대로 걷고, 툰 예제 넷(toonshowcase, toonview, toonfx, toonpost)과 modelviewer, blendmodes, batchclip 의 화면이 안전망을 두었을 때와 걷었을 때, 검사 모드일 때 모두 화소까지 같다(툰 넷과 modelviewer 는 프레임 60 ~ 590, blendmodes 는 60 ~ 240, 검사 모드에서 그리기 149,037 번을 견주어 어긋남 0).
- 데스크탑 질문 창, 문맥 메뉴, 터치 빠른 메뉴의 그림자: 겹친 둥근 사각형으로 갈음하던 것을 크롬과 같은 가우스 흐림으로 그린다. 문맥 메뉴는 원본 CSS box-shadow 0 4px 16px rgba(0, 0, 0, 0.18) 을 블링크처럼 시그마 8(흐림 반경의 반)로, 질문 창과 빠른 메뉴는 크롬 views BubbleBorder 의 두 겹(아래로 2, 흐림 8 과 12, #3C4043 알파 0x33 과 0x1A)을 ui/gfx 의 RadiusToSigma(blur / 2) 시그마로. 둥근 사각형을 CPU 로 구워(기기 배율, 같은 값이면 다시 쓰기) 그린다. 맥에서 문맥 메뉴 오른쪽 그림자 단면이 헤드리스 크롬의 원본 DOM 메뉴와 1/255 안에서 같다
- 데스크탑 창: GL 3.3 코어 컨텍스트를 청했는데 드라이버가 더 낮은 판(드라이버가 없는 윈도우의 GDI GL 1.1 같은)을 주면, 셰이더 함수가 없어 glow 안에서 패닉하던 것을 "OpenGL 3.3 코어가 없다: <판>" 오류로 알리고 끝낸다
- UIInputField::set_use_direct_touch 설명을 사실대로 고쳤다. 웹 전용이 아니고, 데스크탑은 원본에서 크롬이 그 DOM 입력에 하는 일(손가락 길게 누르기의 낱말 고르기와 터치 손잡이, 오른쪽 단추는 엔진 문맥 메뉴)을 한다
- Scene 터치: 원본 vanilla.js 의 Scene 도 씬 꼴과 상관없이 씬의 TouchRaycaster 로 노드에 터치를 넘기게 바꿔, 두 엔진이 같다. (러스트 판 SceneBase.tick 은 그대로, 문서의 "원본 기본 씬은 넘기지 않는다" 글을 고쳤다)
- Engine: 씬마다 그리기 앞(pre_draw, 로딩 중이면 draw_on_load 앞)에 뷰 좌표(view_manager.apply_view_rect)를 걸어 둔다. (원본과 같이 고쳤다) 지금까지는 pre_draw 에서 draw_scene_background 나 apply_view_rect 를 부르지 않는 씬이 그리기 버퍼의 물리 픽셀로 그려, 기기 픽셀 배율이 2 인 화면(레티나 맥, 웹 고밀도 화면)에서 캔버스 왼쪽 위 1/4 에만 그려졌다. 옮기는 법: 물리 픽셀로 그리던 씬은 pre_draw 에서 graphic.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0) 을 부른다
- format_compact_number: 반올림한 글이 1000 이 되면 다음 단위로 올린다. (999999 는 "1000K" 가 아니라 "1M", 원본도 같이 고쳤다)
- UIScrollBar: 자동 숨김이 노드를 끄지 않고 보이지 않게만 한다. (끄면 tick 이 멈춰 다시 나오지 않았다, 원본도 같이 고쳤다) is_auto_hidden() 추가
- Sprite: 뒤집기(set_horizontal_flip, set_vertical_flip)가 내용 영역 밖(음의 크기 쪽)에 그리던 것을 내용 영역 안에서 거울처럼 뒤집게 고쳤다. 조각, 나인 슬라이스, 타일 모두 뒤집힌다. 뒤집어도 is_drawn_inside_content 가 참이라 화면 밖 거르기를 받는다. (원본과 같게)
- 웹 오디오: 멈춘 AudioContext 를 깨우는 동안 stop 하거나 다시 play 하면 늦게 끝난 지난 요청이 소리를 내던 것을 고쳤다. (재생 요청 번호)
- ParticleSystem: 루프 이음매(되풀이 경계)의 버스트가 첫 주기에만 터지던 것을 고쳤다. 0 초 버스트와 경계 바로 앞 버스트도 주기마다 터지고, 한 프레임에 여러 주기를 건너면 그 수만큼 터진다. (원본과 같게)
- 웹 숨은 입력의 자리: 원본처럼 문서 스크롤을 더한다. (페이지를 스크롤하면 어긋나던 버그)
- VisualAsset: load 가 경로만 적고 바로 끝나던 것을 원본처럼 고침. load(엔진, 경로)가 바이트를 부탁하고, 바이트가 오면 비주얼 에디터 문서 꼴(JSON 객체, root 객체)을 보아 맞으면 읽힌 것이고 그 글을 든 Visual 을 담는다. create_visual_from_text, load_from_bytes, unload 추가. 옮기는 법: load(경로) 는 load(엔진, 경로) 로 바꾼다.
- HumanSkinRenderer: 텍스처 유닛 주석의 눈 홍채 차례를 바로잡음. (12 홍채 노멀, 13 홍채 색, 동작은 원래 맞았다)
- SkinnedModel: upload_meshes_and_materials 를 다시 부르면 예전 드로어블의 버텍스 어레이, 버퍼, 모프 텍스처, 머티리얼이 남아 새던 것을 원본과 같이 고침. (먼저 destroy) upload_wireframe_indices 도 이미 올린 선 버퍼를 지우고 새로 올린다.
- Material::create_from_description: 중간 이미지를 풀지 못하면 그때까지 지은 텍스처를 지우고 오류를 돌려준다. (원본도 같게 고쳤다)
- ShaderProgram::new, create_with_attribute_locations: 프래그먼트 셰이더나 프로그램을 짓지 못하면 먼저 지은 셰이더를 지운다. (원본도 같게 고쳤다)
- Localization::is_right_to_left: set_right_to_left 처럼 소문자로, 밑줄을 하이픈으로 읽는다. ("ar_EG" 를 오른쪽에서 왼쪽 언어로 못 잡던 것, 원본도 같게 고쳤다)
- UINode::add_constraint: 솔버가 받지 않은 제약(이미 더한 것, 모순)은 목록에 남기지 않는다. (다음 set_solver 가 같은 오류로 멈춰 뒤 제약이 안 걸리던 것, 원본도 같게 고쳤다)
- 소리 풀기(WebM, MP4 다듬기): 8 바이트를 넘는 EBML 부호 정수, 끝 값 클러스터 시각과 CodecDelay, 아주 큰 MP4 상자 크기와 편집 길이, 소리보다 긴 iTunSMPB priming 에서 넘침 패닉이 나던 것을 막았다. (망가진 파일도 패닉 없이 다듬는다)
- UISpinner::calculate_dot_opacity: 점이 없으면(dot_count 0) 0 나누기로 NaN 이 되지 않는다. (원본도 같게 고쳤다)
- UIListView::set_horizontal: 바뀌면 다음 tick 에 스크롤 영역을 다시 재고 보이는 항목을 새 축에 다시 놓는다. (원본도 같게 고쳤다)
- UIDocument 를 옮기다 찾은 원본 버그: Sprite 의 nineSlice 를 쓰기만 하고 읽지 않던 것. 러스트 판은 원본이 쓰는 꼴(Rect 의 left, top, right, bottom)을 거꾸로 풀어 읽는다
- ParticleSystem 의 바뀐 동작: 그림을 넣으면 늘 그림으로 그리던 것을 원본처럼 렌더 모양이 image 일 때만 그림으로 그린다. 서술의 edge 를 위로 퍼지는 납작한 사각형으로 읽던 것을 원본처럼 아래로 낸다. 입자마다 흔들림 위상을 뽑아 씨앗을 고정한 파티클(타임라인)의 입자 자리가 전과 다르다. circle 은 원본처럼 돌리지 않은 쿼드로, 크기는 0.1 아래로, 알파는 0 ~ 1 밖으로 가지 않는다
- SoundSystem: 원본 core/soundsystem.js 에서 빠졌던 것을 채웠다. set_autoplay_allowed_provider(첫 update 에서 한 번 허락을 묻고 누르기 전에 깨워 본다), 터치가 주된 기기에서 창이 포커스를 잃으면 음소거(누르거나 포커스를 얻거나 다시 보이면 풀림), 페이지가 가려지면 엔진의 페이지 이벤트로 그 자리에서 음소거, 음소거인 동안 AudioContext 멈춤(웹 suspend, 데스크탑은 메인 트랙 무음)과 풀린 뒤 0.5 초마다 다시 깨우기, 첫 누름 전이나 AudioContext 가 돌지 않을 때는 효과음을 내지 않기, play_effect 의 좌우(pan), 배경음악은 틀어 달라고 한 것을 기억했다가 받으면 틀기와 "" 로 끄기, fade_out_effects 의 ""(모두)와 0 초(바로 끊기), 받은 녹음만 고르기, 크기 다듬기(수가 아니면 0), get_music_scale, is_page_hidden, is_blur_mute_enabled, is_window_blurred, is_context_paused, is_context_running, get_last_context_resume_time. update 는 엔진을 받고(update(engine, time_delta)), play_effect 는 좌우를 받고, get_music_id 는 틀어 달라고 한 id(&str, 없으면 "")를 돌려준다. (공개 API 를 바꾸는 일이다) 이어 틀기가 늘 처음 자리(AudioPlayer.get_time 은 재생 중에 흐르지 않는다)에서 시작하던 것을 원본처럼 흐른 시간으로 셈한 자리로 고쳤다
- 효과, 3D, 애니메이션에서 원본 vanilla.js 와 다르던 것을 맞췄다. (꼴을 다르게 두었던 것을 원본 쓰임새로 되돌리고, 원본에만 있던 것을 옮기고, 두 엔진에 같이 있던 버그를 같이 고쳤다)
- 웹에서 툰 예제(toonview, toonfx)가 바로 멈추던 것을 고쳤다. glow 웹은 묶인 것이 없는 프레임버퍼나 텍스처를 읽으면 패닉해서 graphics3d::read_framebuffer_binding, read_texture_binding 으로 읽고(웹은 기본 것으로 본다), 빈 깊이 텍스처 바이트는 4 바이트로 맞춘 u32 에서 읽는다
- Animation: pause, resume 을 채웠다. (goto_and_stop 이 멈춘다) stop 은 멈춰 있어도 첫 프레임으로. (원본 버그를 같이 고침)
- Timeline: 무대 부모가 자기 자신이거나 고리면 무대 부모에 붙인다. 원본 이징이 틀린다던 머리 주석을 고쳤다. (원본 pow 는 이미 고쳐져 있어 두 엔진 이징 값이 같다)
- SoundSystem.get_music_bus, get_effect_bus(원본 getMusicBus, getEffectBus, 첫 누름 전에는 None): 음악과 효과음 크기를 플레이어마다 곱하던 것을 이 버스에 건다. 버스로 만든 플레이어도 설정 크기와 음소거를 따른다. 버스 크기는 셈한 값이 바뀔 때만 걸어, 버스의 set_volume, mute 로 건 값은 SoundSystem 이 크기를 다시 걸 때까지 간다 (원본도 같은 노드에 건다)
- 웹: 글꼴 바이트가 없을 때 브라우저로 굽는 글(platform/web/systemfont.rs)이 캔버스의 알파만 꺼내 흰색으로 올려 색 이모지가 흰 실루엣으로 나오던 것을 고쳤다. 원본처럼 RGBA 를 프리멀티플라이드로 올린다. 시스템 글꼴 조각(올린 글꼴에 없는 글자)은 흰 픽셀은 덮인 정도, 색 픽셀은 색 몫으로 나눈다. 안티앨리어싱을 끄면 알파로 가르고 곧은 색으로 채운다. (원본은 곧은 알파의 알파 칸을 가른다)
- 러스트 판에서 먼저 고쳤던 원본 버그(UIDocument 의 nineSlice 읽기, UIDropdown 의 머리 단추 틴트, UIInputField 의 붙여넣기 커서, LayoutSolver 의 인공 행)를 vanilla.js 에서도 고쳐 같아졌으므로 머리 주석의 "원본과 다른 것" 에서 뺐다. UILabel 배경 차례는 원본도 같았다
- vanilla.js 에서도 OBB.overlaps, NodeLayout.arrangeFan, SoundEffectPool 보이스 0 버그를 고치고 AudioAsset.getLoadError 를 넣어, 이 판의 머리 주석에서 그 '원본과 다른 점' 을 뺐다. (obb, nodelayout, soundeffectpool, audioasset)
- KeyCode::AUDIOPLAY 의 값을 W3C KeyboardEvent.code 표(2025-04-22 권고안)의 이름 "MediaPlayPause" 로 고쳤다. (원본과 같이 고침) "MediaPlay" 는 표에 없고 winit KeyCode 에도 없어 데스크탑에서는 늘 맞지 않았다. 크롬은 흔한 재생/멈춤 키(USB 0x0C00CD)에 "MediaPlayPause" 를 내고 "MediaPlay" 는 리눅스와 크롬OS 의 재생 키(USB 0x0C00B0)에만 낸다
- AssetLoader.get_in_flight_count 를 원본 getInFlightCount 정의대로 고쳤다. 집어 받기 시작했고 아직 끝나지 않은 것이다. (그림은 풀어 보기까지, 소리는 디코딩까지) add_load_handle 로 넣은 바깥 손잡이(원본 addTask 자리)도 끝나기 전까지 세고, 동시 수도 같은 셈이다. (원본 일꾼이 addTask 를 끝날 때까지 한 자리로 쓴다) 지금까지는 바깥 손잡이를 빼고 바이트가 오면 끝난 것으로 셌다
- 브라우저가 해 주던 것을 데스크탑에서도 같은 API 로 (원본은 크롬 위에서 돈다, 러스트 웹판은 같은 브라우저 기능을 쓰고 데스크탑은 엔진이 같은 일을 한다)
- Canvas2D, Path2D, CanvasGradient(곧은, 둥근, 원뿔), CanvasPattern, ImageData: 원본과 게임이 document.createElement("canvas") 와 getContext("2d") 로 쓰는 캔버스와 2D 컨텍스트. 웹은 문서에 붙이지 않은 브라우저 캔버스, 데스크탑은 tiny-skia(resvg 가 쓰는 같은 판)로 칠한다. 경로, 선과 점선, 자르기, 그림자, 합치기 26 가지, 그림, 글(엔진 글자 캐시), 픽셀 읽고 쓰기, to_image
- Engine::alert, confirm, prompt 와 alert_async, confirm_async, prompt_async: 원본 window.alert, confirm, prompt 자리. 웹과 데스크탑 모두 엔진이 그린 크롬 탭 모달 같은 창(제목 "이 페이지 내용:", 기본값을 모두 고른 입력 칸, 윈도우 [확인][취소] 맥과 리눅스 [취소][확인], 크로미엄 번역 82 로케일). 떠 있는 동안 씬과 async 작업이 멈춘다. DevTools 의 Local Storage 탭도 이것을 쓴다 (패널 안 입력 창을 뺐다)
- Document: html lang 과 head 의 meta. 웹은 브라우저 문서, 데스크탑은 엔진이 든 값(EngineConfiguration.document_language, document_meta_list). BuildInfo 는 데스크탑에서도 meta 의 build-version 을 먼저 읽고, LanguagePack 은 두 플랫폼 모두 문서 언어를 바꾼다
- Pane, PaneStyle: 데스크탑에서 엔진 노드로 짓는 분할 패널(같은 크기 셈과 끌기 셈, 테마 색, 리사이저 커서), PaneStyle 프리셋 노드(PaneElement, set_on_click). PointerCursor::request_element_cursor
- 입력 필드: 데스크탑 DOM 입력 필드의 되돌리기와 다시 하기(블링크 묶음 규칙, Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y, 윈도우 Alt+Backspace), 직접 누르는 필드의 크롬 편집 칸 문맥 메뉴(그림 이모티콘, 실행 취소, 다시 실행, 잘라내기, 복사, 붙여넣기, 일반 텍스트로 붙여넣기, 전체 선택, 쓰기 방향, 검사). 검사는 Engine::request_dev_tools_inspect 로 개발자 도구가 그 노드를 고른다
- LocalStorage, PersistedStore: 원본이 저장한 짝 없는 서로게이트(잘린 이모지, JSON.stringify 의 \ud83d)를 원래 UTF-16 단위로 지킨다. 전에는 그런 JSON 을 읽지 못해 PersistedStore 가 기본값으로 돌아가고 다음 쓰기에 원본 저장을 덮었다. get_item_code_units, set_item_code_units
- 고침(원본과 같게): 여러 줄 입력 필드(UIInputField)의 줄 끝 탭을 크롬 pre-wrap 처럼 공백과 같이 매달리게 했다(줄 나눔 때 줄 폭에서 뺌). 탭 폭보다 좁은 칸에서 "tab\there" 가 크롬은 [0, 4] 인데 엔진은 [0, 3, 4] 로 나뉘던 것이다(textarealayout 의 trim_hanging_spaces 에 탭 추가).
- 고침: UISpinner 점 위치가 리눅스에서 마지막 자리 하나 어긋나던 것(리눅스 glibc 의 cos 가 크롬 V8 과 끝자리가 달라 원본 값과 견주는 시험이 리눅스에서만 실패). cos, sin 을 fdlibm 계열 순수 러스트 libm 크레이트로 불러 맥, 리눅스, 웹이 V8 과 같은 값을 낸다. 새로 받는 의존은 없다(이미 다른 크레이트가 쓰던 판, 라이선스 표기에도 있음).
- 고침: 가려짐(Hidden)으로 AudioContext 를 멈춘 직후에도 소리 스레드가 한 퀀텀(128 프레임)을 더 그려 currentTime 이 나아가던 것(리눅스 CI 의 page_events_mute_and_unmute 가 가끔 실패). 크롬 audioContext.suspend() 는 약속이 풀린 뒤 시계가 서는 것처럼, 데스크탑 suspend_audio_context 가 소리 스레드가 멈춤을 받을 때까지(최대 200 ms) 기다린 뒤 돌아온다. 멈춘 뒤에는 시계가 나아가지 않는다.
도구, 문서, 예제
- 예제 toonshading(원본 examples/toonshading 과 같은 장면과 화면 꼴, 제목, 아래 VANILLAPUNCH.COM 링크, 왼쪽 아래 저작권 고지): VRM 1.0 캐릭터(VRM1 Constraint Twist Sample, pixiv Inc., VRM Public License 1.0)를 엔진 SkinnedModel 로 읽고 원본 셰이더 글 그대로 셀 셰이딩한다. 씬 MRT, 머리카락 깊이 패스(앞머리 그림자와 비침), 섀도우 맵, 블룸, 림 라이트와 ACES 합성, FXAA 순서도 같다. 표정 단추 여섯과 깜빡임, Quaternius 동작(CC0) 단추 여덟은 T 포즈 대비 월드 회전 변화를 VRM 뼈에 옮기고, VRMC_node_constraint 의 roll, aim 을 따른다. 끌기는 궤도, 휠은 줌, 오른쪽 끌기는 초점 높이. 자산은 원본 저장소의 것을 읽는다. 아직 없는 것: 스프링 본, 머리와 눈 따라보기, 옵션 패널과 슬라이더(값은 원본 기본값 고정), 와이어프레임, 렌더 정보 표시, 우클릭 메뉴.
- 예제 cameratour(원본 examples/cameratour 와 같은 화면과 동작): Camera2D 가 천천히 좌우로 돌며 대상을 따라가고 3 초마다 흔들린다(Shaker). 끌면 돌아간 방향 그대로 팬(pan_by_screen), 휠은 커서 아래를 고정한 채 줌(zoom_at). 왼쪽 위 노드는 Tween::create_node_tween 으로 배율이 오가고, 오른쪽 위에 Indicator 가 돈다.
- 예제 ancientmountain, neonhorizon 을 원본 vanilla.js 에서 옮겼다. ancientmountain 은 3인칭 산 오르기(절차 지형과 풀, 흙길, 절벽 3중 텍스처, 마네킹 달리기, 점프, 등반, 뛰어내리기, 여우 여섯, 정상 깃발, OFF, SIMPLE, REALTIME 그림자, 블룸, 모션 블러, 옵션 패널, 게임패드)이고, 애셋은 원본 저장소 것을 읽는다. neonhorizon 은 네온 그리드 지형 달리기(별, 유성, 함대, 부스트 빛살, 먼지, 블룸, 색수차, 필름 그레인, 옵션 패널)이고 모형 둘을 examples/assets/neonhorizon 에 둔다. 원본과 같은 셰이더와 같은 식을 엔진의 ShaderProgram, FullscreenPass, RenderTarget, ShadowMap, BloomEffect, SkinnedModelRenderer 위에서 돌린다. 애셋 라이선스는 THIRD_PARTY_LICENSES.md 에 적었다.
- 크레이트 라이선스 파일: vanilla-engine-macros, vanilla-engine-apidoc, vanilla-engine-licenses 에도 뿌리와 같은 LICENSE(저작권자 vanillapunch)를 두고 include 에 넣어 cargo package 꾸러미에 실린다. apidoc, licenses 에 authors 를 적고, licenses 는 SPDX 전문 texts 도 싣는다.
- 예제 자산 라이선스 정리: vanilla.js 저장소가 Mixamo 원본 파일을 Quaternius Universal Animation Library(CC0)로 바꾼 데 맞췄다. modelviewer 는 soldier.glb, Remy.fbx 대신 mannequin_female.glb(Idle, Walk, Run, Dance), mannequin.fbx, toonshowcase 는 mannequin_female.glb 를 읽는다. FBX 시험(walk_fbx_from_examples)은 블렌더가 쓴 7.4 형식과 pelvis 뼈를 본다. 가이드 15-3d 의 Remy.fbx 와 센티미터 배율 줄도 바꿨다. 문서 그림 model-viewer, toon-showcase 와 README 의 modelviewer.jpg, hero.jpg 왼쪽 위 칸을 새 장면으로 다시 찍었다(1280 x 720)
- 라이선스 고지: 다른 원문에서 옮긴 파일(mixer, decode/opus, decode/trim, textinput, canvas2d, textshaping, maskgamma, coretextglyph, systemfont, linuxplatform, browseruitext, colorglyph, component/text, format, autolayout, tween, matrix4, subsurfacescatteringeffect, 초안의 tilemap, physics2d, dynamictree) 머리 덩어리 바로 아래에 옮긴 원문과 라이선스 한 줄을 넣었다. THIRD_PARTY_LICENSES.md 의 실린 자료 절에 스키아의 maskgamma, coretextglyph, 크로미엄의 opus_audio_decoder, opus_constants.h, audio_file_reader, audio_discard_helper, 공개 도메인과 CC0 코드 절을 더했다
- cargo package: Cargo.toml 의 include 로 소스(그 안의 자료), LICENSE, THIRD_PARTY_LICENSES.md, README.md 만 싣는다. (문서, 예제, 시험과 시험 자산, 도구는 저장소에만)
- 라이선스: 엔진 저작권자를 vanillapunch 로 적었다. (LICENSE 의 "Copyright (c) 2026 vanillapunch", README 와 가이드 개요의 "© vanillapunch", MIT 그대로) 제3자 라이선스 고지는 THIRD_PARTY_LICENSES.md 한 파일에 모으고, 그것을 짓는 워크스페이스 도구 tools/licenses(vanilla-engine-licenses, serde_json 만 쓴다)를 더했다. 데스크탑 세 OS(x86_64, aarch64)와 wasm32 대상에서 엔진이 쓰는 크레이트(일반과 빌드 의존)의 라이선스 식, 고른 라이선스, 저작권 줄, 전문(같은 글은 한 번)을 담고, 표기 의무가 없는 라이선스로 쓰는 크레이트는 한 줄씩만 둔다. 크레이트가 아닌 실린 자료(HRTF 자료 Composite.flac 의 IRCAM 고지, fdlibm, 크로미엄과 블링크, 스키아, ICU4C 와 CLDR, font-rs, Kiwi, tween.js, gl-matrix, Separable SSS, 초안의 libtiled 와 Box2D 에서 옮긴 셈과 표)는 엔진 파일, 원본 파일, 고지 원문을 그 파일의 실린 자료 절에 적었다. 엔진과 매크로 크레이트의 Cargo.toml 에 authors = ["vanillapunch"] 를 넣었다. (라이선스 파일이 없는 매크로 크레이트 꾸러미의 고지에 쓰인다) 게임은 같은 도구로 자기 의존과 엔진이 실은 자료까지 모은 파일을 짓는다. (README 의 라이선스 절, tools/TOOLS.md 의 licenses)
- 시험: 데스크탑 플랫폼 시험 tests/desktopplatform.rs(#[ignore], 시스템 글꼴과 대체 글꼴 찾기, 대체 글꼴 글과 색 이모지 래스터, 같은 기계의 크롬 measureText 견주기, 클립보드 왕복)와 크롬 값을 찍는 tests/assets/systemfont/chromemeasure.cjs. 믹서의 크롬 견주기는 기대값을 찍은 운영체제와 CPU(chrome_mixer.json 의 platform, architecture)가 다르면 제곱합을 1e-5 (상대) 안으로 본다. (자동화의 exp, pow 가 운영체제 수학 라이브러리라 끝자리가 다르다)
- CI: .github/workflows/platforms.yml 이 윈도우, 리눅스(X11, 웨이랜드), 인텔 맥에서 cargo test, 데스크탑 플랫폼 시험, 예제 찍기(메사 llvmpipe 소프트웨어 GL), 가상 소리 장치의 audiotone, 소리 크롬 기대값을 그 기계의 크롬으로 다시 찍어 견주기, 원본 예제 페이지를 헤드리스 크롬으로 찍어 화소 견주기, wasm32 예제 빌드를 돌린다. (.github/scripts) 크롬은 러너에 깔린 것(기계마다 판이 달라 인텔 맥은 151 이었다) 대신 browser-actions/setup-chrome 으로 기대값을 찍은 판(Chrome for Testing 158.0.8127.88)을 세 기계에 같게 깔고 CHROME_PATH 로 넘긴다. 예제 찍기는 엔진이 찍기 모드에서 남기는 GL 렌더러 줄과 프레임마다의 진행 줄("Engine: 찍기 진행 프레임 N / 마지막, T 초")을 읽어, 180 초 동안 진행이 없으면 멈춤, 진행하며 제한 시간(기본 900 초, oldface 2700 초)을 넘기면 느림으로 가른다.
- 문서 글: 이름 바꾸기 때 snake_case 로 바뀐 원본 JS 이름(원본 playTone, audioContext, Graphic.drawNode 같은 것 105 곳)과 셰이더 유니폼 이름(modelMatrix, tintColor, globalAlpha), Canvas2D 이름을 원본 이름으로 되돌렸다
- 가이드: 13 장 Animator, 14 장 ScreenEffect 와 HeatHazeEffect 의 destroy(), 19 장 VisualAsset 과 Visual::create_node 를 바뀐 API 에 맞췄다
- 문서: InputManager.set_touch_pressed(Moved 는 누른 동안 켜짐), Engine 의 데스크탑 가려짐(최소화, 앱 멈춤, 웨이랜드 프레임 콜백도 Hidden), load_scene_async(같은 프레임 create 전에 내릴 때만 풀리지 않는다), Scene::initialize(맡긴 것이 없어도 create 뒤 0.3 초) 를 실제에 맞췄다.
- 문서 주석: LayoutTerm(원본의 변수 없는 항은 솔버가 건너뜀), UIView(원본 setBackgroundColor(null) 자리는 알파 0 색), NodeLayout(anchored_position 은 원본과 같게 build 때 건다), UIScrollBar(썸 색 차이 줄을 뺌, 원본을 (1, 1, 1, 0.6) 으로 맞춤)
- 시험: zero_value_terms_add_nothing, fast_short_drag_flings_one_page, snap_to_nearest_crosses_pages, line_chart_max_sample_count_trims_oldest, background_color_can_be_cleared, image_asset_gives_its_image, anchored_position_follows_call_order, language_list_without_aliases_is_accepted, frame_per_second_overlay_text_and_box
- 문서 글을 코드에 맞췄다: ShaderProgram(원본 이름 attributeLocationTable), Mask(NodeTree::draw_node 가 자른다), TweenProperty::get_name(첫 글자 소문자), ButtonMotion(tick 과 is_drawn_inside_content 머리, set_lit_handler), GraphicsQualityGovernor(데스크탑은 환경 변수
VANILLA_<이름>), FixedStepper::new, PointerCursor::is_coarse_pointer(윈도우 태블릿, 리눅스 터치), ViewManager 렌더 배율 상한(데스크탑도 쓴다), AudioBus::get_gain_node(데스크탑 Rc), UIWindow(as_any, dispose, set_dim_color, set_panel_color), UIContextMenu::show 의 좌표, ui 모듈 머리, README 애셋 로딩 예제 이름(C-CASE) - 예제: toonshowcase. 기본 도형 일곱과 soldier.glb 의 걷기를 툰으로 그린다. TOON_MODEL_PATH 에 GLB 경로를 주면 그 모형도 놓는다. (데스크탑)
- 예제 toonshowcase: 둘레에 바위 2 천 개를 인스턴싱 한 번으로 그리고 화면 밖은 거른다. (그린 것 690, 거른 것 1320, 드로우콜 20) 그림자, HDR 블룸과 톤매핑
- 예제: engineextras. 테, 진행 고리, 넓힌 누름 자리, 단추 반응과 토스트, 그림자 글과 그림자 그림, 부드러운 그늘, 마우스 커서, 카메라 손짓, 입력 상태를 한 화면에 놓는다. 입력을 흉내 내지 않아 데스크탑과 웹에서 직접 눌러 본다
- 예제: nodebasics. 노드를 만들고 Paint, Text, 직접 만든 컴포넌트(Spin)를 붙인다. (README '노드와 컴포넌트'의 코드)
- 예제: scenedocument. 원본 UIDocument 와 에디터 저장 꼴로 만든 씬 파일(examples/assets/scenedocument.scene.json)을 읽어 그리고, 다시 내보내 읽은 문서와 같은지 화면에 적는다
- 예제 effectgallery: 아래 오른쪽에 ParticleSystem 칸 여덟(circle 분수, rect 색종이, streak 불티, image 별, 끌개 소용돌이, 흔들림 물방울, edge 눈, 월드 공간 자국)을 두었다. 아래 트레일은 왼쪽만 오간다
- 예제 particleeffects, spriteeffects, uisample: 원본 예제와 같은 장면으로 옮겼다. particleeffects 는 파티클 이펙트 열여덟(목록, 사용 코드 패널과 COPY, 통계 패널), spriteeffects 는 스프라이트 셰이더, 화면 효과, 연출 스물다섯 목록, uisample 은 UIDocument 로 uiasset 을 읽어 단추와 진행 막대를 붙인다. 환경 변수 VANILLA_EXAMPLE_MODE 로 처음 모드를 고른다. spriteeffects 의 주인공 시트 애니메이션은 SpriteAnimator 가 ShaderSprite 안의 Sprite 를 찾지 못해 예제가 직접 돌린다
- 예제 uishowcase: 원본 VANILLA CONSOLE 과 같은 장면으로 옮겼다. UIDocument 가 uiasset 여섯을 읽고, 대시보드, 스토어, 설정, 컴포넌트 네 화면과 테마(Dim, Dark, Light, LocalStorage 에 저장), 팝업(PopupMotion, Typewriter), 토스트, 문맥 메뉴(오른쪽 단추나 길게 누름), 끌기 칩, 반응형 배치를 붙인다. 환경 변수 VANILLA_EXAMPLE_MODE 로 처음 화면(home, shop, settings, components)을 고른다. 테마 드롭다운은 자기 자신을 지우고 다시 만드는 일이라 다음 갱신에서 적용한다
- 예제 inputgallery: 오른쪽 아래에 입력 동작(누름, 반복 수, 이동 축), 손가락 목록과 단계, 마지막 장치를 흉내 낸 키, 손가락, 바깥 입력원으로 보인다. 예제 engineextras: 입력 상태 줄에 마지막 장치와 패드 종류
- 예제: toonview. 노드 사각형 안 툰(ToonView3D), Camera3D 로 3D 점 위에 얹은 2D 표시, 비치는 공 셋을 먼 것부터, combine 으로 이은 각진 돌덩이, 오른쪽 판은 ToonPostProcess 색 보정과 가장자리 어둡게
- 예제 loadingshowcase: AssetLoader 로 그림 일곱 장과 문서 하나를 셋씩 받고(없는 파일 하나는 실패 목록), 받은 뒤의 단계 열 개를 흉내 내 진행률이 차오르는 바꾼 로딩 화면(도는 점, 둥근 막대, 받은 수), 다 받은 뒤 FixedStepper 로 움직이는 공
- 예제: toonfx. 원근 카메라로 도형과 인스턴싱한 돌에 화면 공간 바깥선을 긋는다
- 예제 toonfx: 3 초마다 터짐(충격파, 불덩이, 그을음, 불꽃 줄기, 연기, 흙 알갱이), 연기 기둥, 흐르는 테 자국, 프레임마다 빔, 번개, 리본, 빛 점을 화면 공간 바깥선과 함께 그린다
- 예제: windowshowcase. 게임 영역 기준(세이프 에어리어 위 40, 아래 30 흉내), 기본 창과 긴 글 확인 창 쌓기, 바깥 누르기와 모두 닫기, 화면 페이드(손잡이로 0.6 초 붙잡기), UI 가 받지 않은 누름만 놀이로. 처음 몇 초는 저절로 둘러본다
- 예제: textnodeextras. 글자 칸 맞춤(Text, UILabel), 배율이 움직이는 글, 반투명 고리와 줄어드는 호와 선분 600 개, atlas.cjs 로 구운 아틀라스(examples/assets/atlas), 구운 그림을 나눠 쓰는 그림자 글, 돌아간 판 위의 마우스 자리(convert_view_to_local)
- 예제 oldface: 원본 OLD FACE 장면(그림자, 피부 MRT, 블렌드, AO, SSS, 블룸, ACES, FXAA, 표정 모프와 주름 맵, 깜빡임). 원본과 같은 시각에 찍어 평균 차이 0.8/255. 표정은 4 초마다 바뀌고 숫자 키로 고른다
- 예제 misctour: Camera2D 가 천천히 좌우로 돌고 begin, end 로 그린다
- 예제: panelayout. 파티클 에디터 꼴 창 구성(도구 막대, 왼쪽 고정 폭 세로 분할, 오른쪽 flex 패널에 엔진 캔버스). 웹 전용, 데스크탑은 안내만 찍는다
- 예제: devtoolsshowcase. 노드 몇 개를 놓고 개발자 도구를 열어 둔다. (VANILLA_DEVTOOLS_TAB 으로 처음 탭)
- 예제: uiscenelayout. UIScene 과 UINode 제약(세이프 에어리어 가이드, 약한 바람 너비와 범위, 여백 가이드, 같은 너비 단추, 자연 크기 글). VANILLA_EXAMPLE_DEVTOOLS=1 이면 개발자 도구를 연다. windowshowcase 는 GameScene 트레이트, 놀이 입력 처리기, fade_screen_with_hold 로 바꿨다
- 예제: textshaping. 아랍어 오른쪽에서 왼쪽 글(Rtl, Auto, RichText), 가짜 기울임과 굵게, 그림자 글의 기울임과 밑줄과 취소선, 한중일 낱말 줄바꿈, 글자 묶음 표시 수, DynamicFont
- 예제 textshaping: 색 이모지 줄(😀👍🏽 ❤️❤ 🇰🇷 👨👩👧 1️⃣), 그림자 글 이모지, 기울인 이모지, 글자 아틀라스의 ⭐
- 예제 blendmodes: 블렌드 모드 26 가지를 칸마다. 60 프레임마다 장면이 바뀐다(반투명 그림과 도형, 글자와 나인슬라이스와 자르기, 파티클 묶음과 낱장, 바꿔 끼운 셰이더와 기본 셰이더)
- 예제 toonpost: 세 판(ToonPostProcess 기본, 멀티샘플 4 와 깊이 24 와 다단 블룸 5 단, LDR 길의 밝기와 밝힌 자리와 채도)에 같은 장면, 물든 자국, 기름 윤, 깜빡이는 그을음, 발밑 그늘, 덮는 꼴 불덩이와 충격파와 리본, 빛 점 120(상한 160), 불덩이 사건을 열쇠와 나이로. 시간은 프레임 수 / 60 이라 찍을 때마다 같다
- 예제 toonmaterial: 머티리얼 표면 조각의 칠 획 숫자, 바탕색 텍스처와 데칼, 점광 셋과 정반사와 림과 채움 빛, 다른 빛 묶음의 반 램버트 4 단 띠, 더하기 홀로그램 둘(깊이 선패스 있고 없고), 바닥 평면 거울(불투명 앞 단계), 영구 인스턴스 버퍼 바위. 원본 시험 페이지와 같은 장면이다. (TOON_MATERIAL_FRAME 으로 멈춰 찍어 원본과 화소가 거의 같음) 시작할 때 애버런트 몸 셰이딩 식을 엔진 옵션으로 바꿔 실수 판에 그려 CPU 셈과 견준다 (최대 차이 4.5e-8)
- 문서를 지금 코드에 맞췄다. (코드는 그대로다)
- README: 장점과 예제 목록(새 예제 일곱), 애셋 형식(그림 gif, bmp, ico, svg, avif, 소리 flac, m4a), 기술 노트(글자 렌더링, 렌더 타겟 multiply, 로딩 0.3초), 기능 플래그 tls 와 윈도우, 리눅스 대상 검사, rav1d opt-level 권장, 검증용 화면 저장, 외부 의존성 표(Cargo.toml 과 Cargo.lock 대로, 윈도우와 리눅스 표를 더함), 셰이더 스프라이트 효과 수(none 을 빼면 49)
- ARCHITECTURE: 배치와 소유 구조, 프레임 루프, 블렌드와 글꼴과 애셋 형식, 9장 원본과의 대응(원본 200 파일 가운데 181 옮김, 일부러 안 옮긴 19 파일과 까닭), 10장 두 엔진의 차이(정말 맞출 수 없는 것과 일부러 정한 꼴)
- UPDATE.md 이 판 머리의 겹친 줄(찍기 모드 여섯 벌)을 하나로, math 줄의 옛 설명을 고쳤다
- 머리 주석: 원본에서도 고쳐 이제는 같은 것(묶어 그리기와 거르기 기본 켬, 프로그램과 텍스처 기억, Text 거르기, UIScene 의 use_dev_tools, 웹소켓 바이너리 JSON, Identifier.reset, Vector2 버그, pageshow 복구, DynamicFont 다시 놓기, 길이 0 트윈, set_playback_rate), UIImageView 의 그리는 차례(원본도 배경이 먼저), 그림 형식 목록(Material, GLB 그림, 쓰지 않는 avif-parse), 웹 글자 굽기, Scene 의 initialize 이름, lib.rs 의 웹 모듈 자리
- 예제 devtoolsshowcase: Spin 에 #[vanilla::reflect] 를 붙여 인스펙터에 degreesPerSecond 가 보인다
- 예제 toonstyle: 툰 셰이딩과 바깥선 견주기 장면. (TOON_STYLE_SCALE 로 선의 판 몫, TOON_STYLE_TOGGLES=1 로 모형마다의 꼴) vanilla.js examples/toonstyle 과 같은 장면이다. 숨긴 창으로 찍어 원본(헤드리스 크롬)과 견주면 2560x1440 에서 화소 차이 평균 0.005, 8 넘게 다른 화소 0.024% 다. (꺾임 각 문턱에 걸친 엷은 꺾임 선 몇 군데)
- 예제 toonfx: 새 set_crease, set_depth_threshold 로 바꿨다
- 예제 toonfx: 새 set_crease(60.0, 0.011, 0.8) (월드 단위), set_depth_threshold 로 바꿨다
- 예제 toonmaterial: 애버런트 몸 셰이딩 식 대조를 뺐다. (게임 하나의 식이고, 엔진 빛 꼴이 정석으로 바뀌어 같은 값이 나오지 않는다) 바위 정점 조각의 노멀 크기 맞춤을 뺐다
- 예제 toonstyle: 그늘 셋, 단단한 하이라이트, 해 쪽 림, 스포트라이트, 매트캡, TOON_STYLE_SHELL=1 로 껍데기 바깥선. 원본과 견주면 2560x1440 에서 화소 차이 평균 0.004, 8 넘게 다른 화소 0.018% (껍데기 장면은 0.279%, 기하 가장자리의 MSAA 차이)
- 예제 toonstyle: 점광과 스포트라이트 그림자, 그늘 쪽 림, 천사 고리, 껍데기 바깥선 사라지기와 카메라 쪽 밀기. 원본과 견주면 화소 차이 평균 0.005 (반 크기 판 0.008, 껍데기 0.163 은 MSAA 차이)
- 문서: 함수와 타입의 머리 주석(
//====두 줄 사이) 설명 줄을 rustdoc 문서 주석(///, 파일 머리는//!, 필드와 열거 값은 바로 위///)으로 바꾸고, 공개 API 모두에 설명,# 인자,# 돌려줌,# 예제를 채웠다. 머리 주석이 없던 함수에도 달았다. 예제 869 개(모듈 44, 구조체와 트레이트 377, 멤버 384, 함수 64)는cargo test --doc이 컴파일하고 돌린다. (창이나 GL 이 있어야 하는 것은 no_run 으로 컴파일만) 꼴은 ARCHITECTURE.md 8장 '코드 꼴'의 문서 주석. 입력 필드, Pane, Canvas2D, LocalStorage, PersistedStore, storagetext, 툰 3D 는 주석 꼴만 바뀌었고 인자, 돌려줌, 예제는 나중에 채운다 - 가이드 docs/guide/0.4.0/ko, en: 개요, 빠른 시작, 구조, 도구와 05 프로젝트 시작부터 19 저작 도구까지(원본 vanilla.js 가이드와 같은 장), 러스트 판만의 20 반사 매크로, 21 async/await, 22 원본에서 옮겨 오기. 코드 칸 216 개 가운데 rust 칸은 tools/apidoc 의 라이브러리 자리가 doctest 로 컴파일하고 돌린다. (장 목록 tools/apidoc/src/guide.rs 는 apidoc 이 장 파일마다 include_str 문서 속성으로 다시 쓴다) 업데이트 문서 docs/update/0.4.0.ko.md, .en.md
- 예제 toonstyle: TOON_STYLE_ROLL 로 카메라를 기울인다. 원본과 견주면 화소 차이 평균 0.005 (기울인 장면 0.005)
옮기는 법
- 3D 색 공간 칸: compose_toon_program_sources, ToonRenderer::read_material_program_sources 는 끝에 is_ambient_occlusion 과 color_space 를 받는다(지금과 같으려면 false, ColorSpace::Gamma). read_glb_arrays, read_glb_node_arrays 는 끝에 color_space: Option
를 받는다(None 이면 엔진의 값). ToonScreenOutline::read_program_sources 는 color_space 를 받고 (String, String) 다섯을 돌려준다. Graphic::new 는 셋째 인자로 색 공간을 받는다. ToonLineTarget::jump_flood_index 는 Option 다(아래 모서리 어둠). ToonTextureOptions, ToonPostProcessOptions 를 구조체 꼴로 다 적어 짓던 코드는 is_color_data, color_space 를 더하거나 ..Default::default() 를 쓴다. - 툰 모서리 어둠: ToonLineTarget::jump_flood_index 는 Option
다(넓히지 않았으면 None, 원본 -1). 굵기 0 인 바깥선(set_width(0) 와 꺾임 굵기 0)을 쓰던 게임은 그 화면이 바뀐다. - 툰 화면 바깥선 가는 선 길, 해상도 몫, 판 앞 비우기: ToonLineTarget 의 seed_framebuffer 와 seed_texture 는 Option, jump_flood_framebuffers 와 jump_flood_textures 는 Vec(굵은 선을 긋기 전에는 비어 있다)이 되었고, edge_mask_framebuffer, edge_mask_texture, coverage_framebuffer(Option), coverage_texture(Option), outline_path(ToonOutlinePath: None, Thin, ThinScaled, JumpFlood)를 더했다. read_program_sources 는 아홉을 돌려준다. get_line_target 의 line_texture 와 depth_texture 해상도는 set_resolution_scale 이 1 보다 작으면 그리는 영역보다 작다.
- 웹 그림 풀기를 브라우저로: 웹에서 Image::load_from_memory, load_from_memory_with_mime_type, Engine::load_image(data: 주소)는 Err 다. ImageAsset::load, load_from_bytes 를 await 하거나 AssetLoader 로 읽는다. (원본에도 그림 바이트를 그 자리에서 푸는 길이 없다)
- 하위 트리째 그리기 건너뛰기: WorldNode::set_last_drawn_maximum_scale 은 둘째 인자로 그리기 프레임 번호를 받는다(원본 setLastDrawnMaximumScale(maximumScale, frameNumber)). calculate_drawn_rect 를 덮어쓴 사용자 컴포넌트는 그 사각형을 바꾸는 세터에서 mark_drawn_rect_dirty 를 부른다. 부르지 않으면 넓어진 그림이 화면에 들어와도 안 그려질 수 있다. NodeTransform 을 통째로 갈아 끼우면(*get_transform_mut() = ...) 더러움이 알려지지 않으니 세터를 쓴다.
- 소리 스트리밍 읽기: SoundSystem 으로 틀던 배경음악은 load_type 이 없으면 스트리밍이 되므로, 그 애셋의 get_audio_buffer() 를 직접 쓰던 코드는 소리 줄의 load_type 을 Some(AudioLoadType::DecompressOnLoad) 로 준다. AudioAsset 을 직접 쓰는 코드는 기본이 그대로라 바꿀 것이 없고, 스트리밍을 쓰려면 set_load_type(AudioLoadType::Streaming) 을 건다. 스트리밍 애셋은 get_audio_buffer() 가 None 이다. SoundRow 를 구조체 꼴로 짓던 코드는 load_type: None 을 더한다. 데스크탑의 get_stream_url 은 파일에서 읽었으면 그 경로, 메모리에서 읽었으면 None 이다(웹은 원본처럼 주소나 blob: 주소).
- Graphic 이 묶음과 2D 상태를 따로 기억하지 않고 그리기 앞에 GL 상태 캐시에 견준다: Graphic::invalidate_render_state_cache 를 없앴다(원본 invalidateRenderStateCache 도 없앰). 부르던 곳은 지운다. 상태 캐시를 거치지 않고 안의 glow::Context 로 상태를 바꿨으면 전처럼 reset_gl_state_cache 를 부른다. restore_render_state 를 run_external_pass 밖에서 불러 스텐실 테스트를 다시 켜던 게임은 run_external_pass 를 쓴다.
- 뼈 자세 고리: write_skin_pose 를 부르는 곳은 끝에 None 을 더한다. (write_skin_pose(skeleton, name, time, &mut joint_matrices, blend, swing_scales, None))
- glTF 양자화 읽기: AccessorArray 를 match 로 모두 가르는 코드는 Byte, Short 갈래를 더한다. (그 밖은 새 기능)
- 툰 강조: ToonInstance 를 구조체 꼴로 짓는 코드는 ..ToonInstance::default() 를 붙인다. (엔진 예제는 이미 그 꼴) 인스턴스 행렬의 아래 줄에 0, 0, 0, 1 이 아닌 값을 넣던 것(사영 인스턴스 행렬)은 이제 아핀으로 읽는다. ToonScreenOutline 의 선의 판도 같다.
- 씬 훅 꼴을 원본과 같게: 씬의 fn create(&mut self, engine: &Engine) 는 fn load(&mut self, engine: &Engine) 로 바꾼다. 다른 훅은 engine 인자를 지우고, 몸에서 엔진을 쓰면 첫 줄에 let engine = Engine::get_engine().unwrap(); 을 둔다(같은 엔진). self.scene_base.tick(engine, time_delta) 는 self.scene_base.tick(time_delta), game_scene_base.create(engine) 은 game_scene_base.load(engine), game_scene_base.draw_on_load(engine, graphic) 은 game_scene_base.draw_on_load(graphic) 처럼 바탕 부르기에서도 engine 을 뺀다.
- 3D 렌더 스케일: ToonViewDrawCallback 의 다섯째 인자가 i32(드로잉 버퍼 높이)에서 ToonViewOutput 으로 바뀌었다. ToonPostProcess::end(gl, None, [x, 드로잉 버퍼 높이 - y - 높이, 너비, 높이]) 처럼 자리를 손으로 셈하던 것은 end(gl, output.output_framebuffer, output.output_viewport) 로 바꾼다. (배율 1 에서는 같은 자리고, 배율을 걸거나 투명도 층 안에서도 맞는 자리에 낸다)
- 엔진 GL 컨텍스트 GlContext: 콜백 인자에 형을 적은 코드(
|program: &ShaderProgram, gl: &glow::Context, kind: ToonProgramKind|, ToonView3D 그리기 함수의gl: &glow::Context)는gl: &GlContext로 바꾼다. 게임의 도움 함수가 받는gl: &glow::Context도gl: &GlContext로 바꾼다(그대로 두면 컴파일 오류로 알려 준다).use glow::HasContext;는 지운다(GlContext 의 고유 메서드라 없어도 돌고, 두면 쓰지 않는 가져오기 경고만 난다). get_gl 로 받아 엔진 함수에 넘기는 코드는 그대로 둔다. glow 의 형(glow::Texture 같은 것)과 상수는 그대로 쓴다. - 글자 그리기를 글리프 아틀라스로: TextEntry 의 texture 는 없다. glyph_textures, glyph_rects(문자열 사각형 왼쪽 위 기준 왼, 위, 오른, 아래, u0, v0, u1, v1)로 글리프마다 그린다. (엔진 안에서는 Graphic::draw_text_entry 가 한다) TextEntry 는 Copy 가 아니다. (clone)
- 그림자와 알림 인자 꼴: set_shadow(Color::create(0.0, 0.0, 0.0, 0.8), 3.0, 4.0) 은 set_shadow("#000000", 0.8, 3.0, 4.0) 으로 바꾼다. ToastMotion::new(옆) 은 ToastMotion::new() 와 set_enter_side(옆) 으로(attach_toast_motion 은 그대로). set_apply_text_handler 로 건 함수는 show 의 셋째 인자로 옮긴다: toast_motion.show(글, 초, move |context| { .. 글 넣기 .. }).
- 예약어 이름 없애기: cooldown.r#use() 는 cooldown.activate(), pass.r#use(gl) 는 pass.use_program(gl), pointer_gesture.r#move(x, y) 는 pointer_gesture.move_pointer(x, y), action.r#loop(..) 는 action.repeat_while(..), easing_function::quadratic::r#in 은 easing_function::quadratic::ease_in 으로 바꾼다(out, in_out 도 ease_out, ease_in_out).
- 글자 안티앨리어싱을 Graphic 메서드로: graphic.get_text_string_texture_cache().set_text_antialias_enabled(값) 은 graphic.set_text_antialias_enabled(값) 으로 바꾼다. (캐시 메서드도 그대로 돈다)
- 두 엔진 차이 맞추기: format_number, format_number_with_unit 은 Result<String, FormatError> 를 돌려준다(맞는 태그면 unwrap 이나 ?). to_json_text_mut, serialize_node_mut 는 없다. to_json_text, serialize_node 에 &mut NodeTree 를 넘긴다. 초안 Tilemap::get_tilesets 는 &[Rc
], get_tileset 은 Option<&Rc >, get_tileset_mut 은 다른 지도와 나눠 쓰는 중이면 None. add_tileset 은 Tileset 도 Rc 도 받는다 - 로직 수 f64: 게임 코드의 f32 를 f64 로 바꾼다. (tick 의 time_delta, Vector2::create 와 Color::create 의 인자, 컴포넌트 필드와 게터, 세터, std::f32::consts 는 std::f64::consts) Matrix4 의 elements, get_elements, write_to_array, write_to_slice 는 원본 Float32Array 처럼 f32 다. 칸으로 셈할 때는 새 read_elements(f64 배열)로 읽는다. TransformMatrix::write_to_float32_array 는 [f32; 9] 에 쓴다. Graphic::get_vertex_data, get_particle_vertex_data, ToonRenderer 의 인스턴스 자료(create_instance_buffer), ToonDrawOptions 와 ToonLineDrawOptions 의 joint_matrices, write_skin_pose 의 target 은 f32 라 f64 값은 as f32 로 넣는다. Canvas2D 와 Path2D 의 함수는 원본처럼 f64 를 받는다. 데스크탑은 크롬 블링크처럼 받자마자 f32 로 줄여 스키아처럼 float 로 셈하고(경로 함수 move_to, line_to, arc, rect 같은 것은 base::saturated_cast 라 f32 를 넘는 수는 무한이 되어 버리고, 나머지는 ClampTo
라 ±f32 끝값으로 자른다), 웹은 f64 를 브라우저에 그대로 넘긴다. 게터(get_line_width, get_shadow_blur, get_miter_limit, get_line_dash_offset 같은 것)는 f64 를 돌려주고, get_global_alpha 와 get_line_dash 는 크롬처럼 넣은 값 그대로다. CanvasRadius 는 f64 와 (f64, f64) 에서 짓는다. TextStringTextureCache 의 get_entry, find_entry, rasterize_text, rasterize_text_with_color 는 line_width 와 bake_scale 을 f64 로 받는다. (원본처럼 배율 곱과 구운 크기 나누기를 double 로 셈한다) CanvasMatrix 의 칸과 CanvasGradientKind 의 칸은 스키아의 float 행렬, 그라디언트라 f32 이고, CanvasMatrix::create 는 f64 를 받아 줄이며 transform_point 는 f64 로 셈해 돌려준다. 데스크탑 rotate 는 크롬처럼 각을 float 도로 줄여 스키아 setRotate 셈(float 라디안, sin 과 cos 이 1/65536 안이면 0)으로 돌린다. (90 도에서 cos 이 -4.4e-8 이 아니라 0) LayoutExpression 은 f32 대신 f64 와 i32 를 받는다. 게임 셰이더에 유니폼을 올릴 때는 glow 의 uniform_1_f32 들에 as f32 로 넘긴다. - 웹 질문 창과 웹 문맥 메뉴: Engine::alert, confirm, prompt 는 웹에서도 그 자리에서 끝나지 않는다. 손잡이의 is_finished, set_callback 이나 alert_async 들을 await 해 답을 받는다. (데스크탑과 같다) Engine::is_modal_dialog_open 은 웹에서도 참이 될 수 있다
- 반사를 빠뜨릴 수 없게: 게임 컴포넌트의 impl 블록과 impl Component 블록에 #[vanilla::reflect] 를 붙인다. 게터가 없는 타입은 빈 블록
#[vanilla::reflect] impl 타입 {}에 붙인다. Component::get_reflection, get_reflection_mut 은 없다(&dyn Component를&dyn Reflect로 올려 쓴다). collect_reflected_getters, collect_reflected_getters_in_tree, collect_reflected_getters_mut 은 Option 없이 Vec 을, UIDocument::serialize_component 는 Option 없이 Map 을 돌려준다. - GameScene 로딩과 터치 인식기: GameSceneBase::get_touch_recognizer, get_touch_recognizer_mut 이 Option 을 돌려준다. (initialize 전에는 None, 원본 undefined)
- 3D 자산 공유 캐시: destroy 가 다른 곳에서 Rc 로 쥐지 않은 머티리얼을 지우던 것을 원본처럼 바꿨다. set_material 로 넣은 머티리얼은 지우지 않으니 넣은 쪽이 destroy 한다. Drawable 의 mesh_description 은 Rc
, morph_target_list 는 Rc<Vec > 이고(읽기는 그대로, 고치려면 Rc::make_mut) 새 칸 is_morph_texture_shared 가 있다. 같은 주소를 여러 번 받아 모델마다 머티리얼 값을 다르게 바꾸던 코드는 get_material(번호) 로 사본을 받아 바꾼다. 받을 때마다 따로 풀린 자원이 필요하면 SkinnedModelAsset::clear_cache() 를 부르거나 load_from_bytes 를 쓴다. 손잡이의 create_model 을 끝난 뒤 다시 부르면 새로 짓지 않고 같은 자산의 인스턴스를 돌려준다. - JPEG 해독: EXIF 방향이 있는 JPEG 은 폭과 높이가 돌린 뒤의 값이다. 돌리지 않은 그림을 기대하던 코드는 그림을 방향 없이 다시 저장한다.
- 입력 필드 문맥 메뉴: UIInputFieldMenuAction 에 SelectAll 이 생기고 Undo, Redo, PasteAsPlainText, Emoji, WritingDirectionDefault, WritingDirectionLeftToRight, WritingDirectionRightToLeft, Inspect 는 없다. 되돌리기는 키(Ctrl+Z, Ctrl+Shift+Z)로 한다. UIInputFieldWritingDirection 과 UIInputField::set_writing_direction, get_writing_direction 은 지웠다(엔진이 그린 글에 영향이 없던 값이다)
- 컴포넌트 찾기: get_component::
() 가 ShaderSprite 도, get_component:: () 가 위젯의 품은 UIView 도 돌려준다. 정확히 그 타입만 찾던 코드는 as_any().downcast_ref 로 본다. remove_component:: () 는 Sprite 같은 하위 타입도 뗀다. - Action: start(&mut 대상) 은 start_with(&mut 대상), step(&mut 대상, 시간) 은 step_with(&mut 대상, 시간), start_on_node 는 start, step_on_node 는 step 으로 바꾼다.
- FloatingText: 밀린 만큼 좌표를 빼서 넘기던 코드는 원본처럼 부모 왼쪽 위 기준 좌표를 넘긴다.
- JSON 쓰기: 저장된 JSON 글을 "1.0" 같은 글로 견주던 코드는 원본과 같은 "1" 로 본다. 이미 저장된 글은 그대로 읽힌다.
- JSON 쓰기: 띄운 라벨 노드의 get_component::
() 는 get_component:: () 로 바꾼다. - 대체 글꼴 고르기: 바꿀 것 없다. 폰트 문자열에 이름을 준 글이 기본 글꼴 사슬의 글꼴(맥 Apple SD Gothic Neo, 윈도우 Segoe UI, 맑은 고딕)로 그려지던 글자는 이제 크롬처럼 운영체제 대체 글꼴로 그려진다. 사슬을 쓰려면 이름 목록 끝에 default 를 둔다.
- FBX 재질 여럿: FBX 모델의 드로어블 목록이 재질 수만큼 늘어난다. 드로어블 0 하나가 메시 전체라고 기대하던 코드는 material_name 이나 material_index 로 찾는다.
- SpriteAnimator.play: SpriteAnimator::play_on_node(node, ...) 는 SpriteAnimator::play(node, ...) 로, animator.play(...) 는 노드가 있으면 SpriteAnimator::play(node, ...), 완료 콜백 안이면 animator.play_clip(...) 으로 바꾼다.
- GamepadManager: 돌려받는 값이 참조(&Gamepad)가 아니라 사본(Gamepad)이다.
.into_iter().cloned().collect()나.cloned()로 사본을 들던 코드는 그것을 지운다. get_gamepad_manager() 로 빌려 읽어도 된다. - AudioPlayer 버리기: 플레이어를 버려 소리를 끄던 코드는 버리기 전에 stop() 을 부른다. 루프 소리는 stop 하지 않으면 원본처럼 계속 운다.
- 글꼴 이름: FontDescription.family_name_list 에서 따옴표 친 일반 이름은 ""monospace"" 처럼 따옴표째 온다. 이름을 견주던 코드는 따옴표를 떼고 본다. GenericFamily::from_family_name("-webkit-body") 는 Standard 를, find_family_font_file 은 큰따옴표로 감싼 이름을 글꼴 이름으로 찾는다
- Engine: 바뀌어 컴파일이 깨지는 공개 API 는 없다. 그리기에서 처음 그릴 때 GL 자원을 짓던 코드는 그대로 돈다. 원본처럼 create, initialize 에서 지으려면
if let Some(graphic) = engine.get_graphic() { ... graphic.get_gl() ... }로 옮긴다. 그리기 함수 안에서 engine.get_graphic() 을 부르면 None 이니 인자의 graphic 을 쓴다 - FbxLoader: 꼬리가 붙은 이름으로 play_animation 하거나 노드를 찾던 코드는 꼬리를 뗀 이름을 쓴다.
- ToonScreenOutline: (공개 API 를 바꿨다)
- set_crease(각, 진하기, 이어짐 픽셀) → set_crease(각, 굵기, 진하기). 굵기는 set_width 의 단위, 진하기는 0 ~ 1. 이어짐 픽셀은 없어졌다. 옛 set_crease(60.0, 0.5, 2.0) 과 비슷한 모습은 픽셀 단위면 set_crease(60.0, 1.0, 0.8), 월드 단위면 굵기를 바깥 선 굵기의 반쯤으로 (set_width(0.022, World) 면 set_crease(60.0, 0.011, 0.8)). 굵기가 set_width 의 단위라 월드 단위에 1 을 주면 1 미터 굵기가 된다
- set_depth_threshold(깊이 문턱, 맞닿음 문턱) → set_depth_threshold(깊이 문턱). 뜻이 접평면 거리로 바뀌었다. 맞닿음 문턱은 없어졌다
- set_width 의 뜻: 선 하나의 굵기를 경계 양쪽에 반씩. 기본 1.5 → 2 픽셀. 옛 모습의 바깥 두께를 맞추려면 두 배를 준다. 선 전체의 모습(덮는 몫의 합)을 맞추려면 두 배가 아니라 0.9 배쯤이다. (원본에서 옛 셰이더를 같은 선의 판에 돌려 견줌, 애버런트의 옛 값 0.022 m, 꺾임 60 도 .5 2 px 는 set_width(0.020, ToonOutlineWidthUnit::World), set_crease(60.0, 0.016, 0.5), set_depth_threshold(0.08) 가 가장 가깝다, toonstyle 장면 1280 x 720 에서 덮는 몫 합의 차이 1 %)
- set_sample_count, TOON_SCREEN_OUTLINE_MAXIMUM_SAMPLES, TOON_SCREEN_OUTLINE_MAXIMUM_CREASE_SAMPLES 는 없어졌다. 가벼운 길은 set_resolution_scale 만 낮춘다
- get_outline_radius(), read_outline_radius() → get_line_widths(), read_line_widths() ([바깥 선, 꺾임 선] 의 그리는 영역 픽셀)
- 선 번호 상한 65535 → TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID (16383)
- ToonLineTarget 의 mask_framebuffer, mask_texture 는 없어졌다. 대신 seed_framebuffers, seed_textures (RGBA16UI 둘), seed_index
- draw_outline 이 뷰포트를 begin_line_ids 때의 그리는 영역으로 스스로 건다
- 툰 셰이딩을 실시간 툰 렌더링의 정석 꼴로 다시 지었다.: (공개 API 를 바꿨다)
- 부드러운 램버트는 clear_shade_ramp() 나 set_band_count(0)
- ToonBandRamp, get_band_ramp, get_band_count, clear_band_ramp 는 없어졌다. ToonShadeRamp, get_shade_ramp, clear_shade_ramp
- set_specular(세기, 지수) → set_specular(세기, 지수, 부드러움, 색). 지금까지의 모습은 set_specular(세기, 지수, 1.0, [1.0; 3]). get_specular() 는 ToonSpecular
- set_rim_light(색, 거듭제곱) → set_rim_light(색, 거듭제곱, 부드러움, 해 쪽 가림). 지금까지와 같은 부드러운 테는 (색, 거듭제곱, 1.0, 0.0), 바탕색에 곱하지 않는다. get_rim_light() 는 ToonRimLight
- ToonPointLight 를 이름으로 지을 때는 ..ToonPointLight::default() 를 붙인다. (새 칸 direction, inner_cone_angle, outer_cone_angle)
- 뼈 행렬 유니폼 블록: 대체 정점 셰이더(SkinnedModelRenderer 에 주는 셰이더, 툰 쪽 바깥선 셰이더)는 uniform mat4 jointMatrices[96]; 대신 JOINT_BLOCK_GLSL 을 끼운다. (본문의 jointMatrices[번호] 는 그대로) 뼈 행렬을 직접 올리던 코드(유니폼 위치를 찾아 올리던 것)는 JointBlockBuffer::upload 로 바꾼다. 모프 가중치를 직접 올리던 곳은 uniform float morphWeights[96] 대신 uniform vec4 morphWeights[24] 와 vec4 배열 올리기로 바꾼다.
0.4.0
Summary
- Names: renamed to the Rust conventions (Rust API Guidelines C-CASE). Functions, methods, variables, fields and modules are snake_case, enum values UpperCamelCase and associated constants SCREAMING_SNAKE_CASE.
- Same as the original vanilla.js: ported the general-purpose features that came into the original 0.4.0 (features moved from games, window stacking, loading and saving, input actions, the standard form of toon 3D, the shadow atlas) and its bug fixes with the same API. The folders now match the original too. (module paths are unchanged)
- Engine: graphics are usable anywhere. Scenes build GL resources with engine.get_graphic() in create, initialize, tick and async tasks. async/await is used like the original as well.
- The desktop now does what the browser used to: sound output moved from kira to the engine mixer on cpal, AVIF and HE-AAC decode, and word segmentation, fonts and Canvas2D set_font and put_image_data match Chrome.
- Scene and Engine: the original now also passes touches to widgets on nodes whatever the scene type, like the Rust version, so the two engines match. Fixed it, together with the original, so the view transform is applied before each scene draws.
- Docs: tools/apidoc (crate vanilla-engine-apidoc), which extracts the API data from doc comments, docs/api/0.4.0.json and the guide docs/guide/0.4.0/ko, en.
- Migration: where the public API or usage changed is gathered in one place in the 'How to migrate' section at the bottom. A game only needs that section to see what to change. (naming conventions, SoundSystem::new and its functions, Image::get_pixels, ScreenEffect::destroy, JsonAsset.load, FbxLoader names, ToonScreenOutline, toon shading)
New features and changes
- GPU memory tracking (the same as the original afb9fc8 and 14586d0, for development): counts the bytes of textures, renderbuffers and buffers by kind and by owner. Bytes are nominal values computed from format and size (multisample renderbuffers multiply by the sample count; the canvas default framebuffer share is 4 bytes color + 4 bytes depth and stencil, times 4 plus one resolved color image when multisampled) and are counted only while tracking is on. It is off by default, so the creation and sizing calls of GlContext only look at one flag and nothing runs per frame. Added: EngineConfiguration::track_gpu_memory (default false), enable_gpu_memory_tracking, is_gpu_memory_tracking_enabled and read_gpu_memory_usage on Engine and Graphic (read turns tracking on if it is off and counts from then on), the enum GpuMemoryKind (Texture, Renderbuffer, Buffer) and GpuMemoryUsage, GpuMemoryKindUsage, GpuMemoryOwnerUsage (counterparts of the original { totalBytes, canvasBytes, kindTable, ownerList }). The owner is the top three frames of the creating call stack (desktop captures the frames at creation and resolves them when read; the web has no stack and uses the creating source location). Everything is cleared when the context is lost. Counted in GlContext: create_texture, create_buffer, create_renderbuffer, delete_*, tex_image_2d, tex_image_3d, tex_storage_2d, tex_storage_3d, generate_mipmap, renderbuffer_storage, renderbuffer_storage_multisample, buffer_data_size, buffer_data_u8_slice; the same calls the engine made directly on the glow context now go through GlContext. Web image-source uploads (tex_image_2d_with_*, tex_image_3d_with_*) are counted like the original, as width x height x format bytes (image, canvas, video, ImageBitmap, VideoFrame, ImageData). Named creation (create_named_*) is desktop-only and does not exist in the original (WebGL2), and partial buffer updates (buffer_sub_data) do not change the storage size and are not counted by the original either, so they are not counted.
- Graphic context loss handling and shader build failure notification (the same as the original afb9fc8 and its shader build failure notification; the web build receives webglcontextlost and webglcontextrestored the same way and desktop never loses the context): Engine gained add_graphic_context_event_listener, remove_graphic_context_event_listener, dispatch_graphic_context_event (the enum GraphicContextEvent with Lost and Restored, the listener type GraphicContextEventListener), Graphic::is_context_lost and GlContext::is_context_lost. On the web, when the context is lost the engine accepts the restore with preventDefault, does not draw while lost (it only updates scenes), drops the piled-up batch, reports once on standard error and passes Lost. When it comes back the engine rebuilds the base resources it made (the default shader program, vertex array, white texture, batching, particles, blend shaders, offscreen targets, the image texture and glyph caches), resumes drawing and passes Restored. GL objects the game made (toon renderers and meshes, shadow maps, its own shaders, render targets) cannot be rebuilt by the engine, so the game rebuilds them on Restored. When the engine cannot build a shader program (a toon renderer material, a screen effect pass, a Graphic::resolve_shader_program program, the ToonView3D renderer) it reports a GraphicError { kind, name, error } once to the graphic error listeners, in addition to standard error. Added: Engine::add_graphic_error_listener, remove_graphic_error_listener, dispatch_graphic_error, GraphicError, GraphicErrorKind::ShaderBuildFailed, GraphicErrorListener. A failure after the context was already lost is not the shader's fault, so it is neither reported nor remembered, and the program is rebuilt after the context comes back. The toon body shader's readShadeLevel now reads the last shade stop color with a constant index and a loop, letter for letter the same as the original (an iPhone SE2 A13 killed the GPU process on the dynamic index read).
- Capture mode (VANILLA_CAPTURE_*): the 0.3 s fade-in of a scene loaded before the first frame is counted from the first frame's time (same as the original). The desktop reads files at once, so the assets handed off finished before the first frame and the fade started at clock 0, while in the original fetch finishes after the first frame and the fade starts at the first frame time (1/60 s), so the scene's first tick was frame 19 in the original and 18 in Rust. Both are 19 now, and the toon showcase captured at the same frame number differs from the original in 36 pixels (5 above 8). Outside capture mode nothing changes.
- Canvas antialias advice for games using post processing (docs only, behavior unchanged, same as the original): 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 scene GPU throughput 6.89 to 6.49 ms, with the other build 6.81 to 5.22 ms).
- Toon body shader feature variants (same as the original a5e964c, 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, receiving shadows, 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 (original, 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). A variant is built the first time it is drawn (one frame may hitch then; ToonRenderer::prepare_material only prebuilds the default program) and the number of variants is the number of used bit combinations. The default program keeps every branch on. The only API change is a trailing parameter disabled_features of compose_toon_program_sources (&[&str], empty by default, an unknown name panics). The shader text is identical to the original down to the character, including not dropping the shadow branch when there is no shadow input (on the original's Mac Chrome the compiler folded the expression differently and 8 pixels changed by one step)
- Toon screen-outline batching of mirrored items (same as the original c69269c, ToonDrawQueue, the is_mirrored slot at the end of draw_mesh_batch of ToonScreenOutline, 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 is_mirrored) 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. The test (toonbatchtests) 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 instance buffer path (same as the original 293fe41, the path the miner game uses): ToonRenderer gained update_instance_buffer_range (updates only from the first instance with buffer_sub_data, Err when out of range), and ToonInstanceBuffer gained get_generation (+1 on every change), get_bounds (ToonInstanceBounds: center of the position box, distance to the farthest position, largest scale), get_data and get_id. Instance layouts gained instanceLineId (size 1, location 15, TOON_INSTANCE_LINE_ID_NAME, TOON_INSTANCE_LINE_ID_LOCATION, has_line_id; with it, at most two user attributes). ToonDrawQueue::add_mesh_instance_buffer and ToonScreenOutline::draw_mesh_instance_buffer let the body, the outline shell, the shadow and the line board share one uploaded GPU buffer without uploading again (the line board reads the instanceLineId slot as the line id). The shadow cache notices changes through the buffer id and generation. The existing draw_mesh_instance_buffer now culls the whole buffer by its bounds (same name and arguments, a buffer outside the screen has no pixels so the picture is the same; with is_culled false it does not cull). read_instance_buffer_sphere and is_sphere_in_frustum are public. The instance-layout shader text and the line board vertex shader are identical to the original down to the character (the test loads the original repository with node and compares). The test (tooninstancebuffertests) draws the miner mid scene for 75 frames on both the array and the buffer path and checks byte-identical pixels, fewer uploads (24 vs 6 on frame 0, then 13 vs 0), one buffer_sub_data on the frame where one rock changes, and the shadow cache re-baking
- A 3D color space setting (same as the original a803b71, in the style of Color Space: Gamma/Linear in Unity Player Settings): added EngineConfiguration::color_space and the enum ColorSpace (Gamma, Linear). The default is Gamma, and the screen is byte-identical to before. With Linear, toon 3D draws along the standard linear path. ToonRenderer::create_texture uploads color textures (base color, emission, 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, emissive color, decal color, outline color) are converted to linear with the standard sRGB curve (IEC 61966-2-1) before they are multiplied and mixed. Screen output, ToonPostProcess after tone mapping, the HDR shell outline and ToonScreenOutline line color, and the GLB base color (baseColorFactor into the vertex sRGB color) use the same curve. Data textures such as normals and masks are uploaded as plain RGBA8 with is_color_data: false in ToonTextureOptions (gamma does not distinguish them). With Linear, the 3D shaders the engine builds get #define VANILLA_COLOR_SPACE_LINEAR 1 (the shader text has the same two #ifdef paths as the original), and material chunks get toSurfaceColor(vec3), which converts an sRGB color into the space of ToonSurface.baseColor. ToonRenderer::new_with_options(ToonRendererOptions), ToonScreenOutline::new_with_options(ToonScreenOutlineOptions) and ToonPostProcessOptions::color_space take the color space (the default is the engine's value, Gamma without an engine, and new uses the engine's value) and report it with get_color_space. Added Engine::get_color_space and Graphic::get_color_space. Desktop GL does not enable GL_FRAMEBUFFER_SRGB on the default framebuffer (the shaders apply the curve themselves, as on the web canvas). 2D is composited in gamma space either way. Frames 5 and 40 of six toon examples (toonview, toonmaterial, toonpost, toonstyle, toonfx, toonshowcase) and the test scenes are byte-identical to before with Gamma. A capture test (tests/tooncolorspace.rs) runs the same checks as the original tooncolorspacechrome (texture encoding, the define line, the half mix at 127 for gamma and 188 for linear, the same values as the original, and engine defaults).
- Toon ambient occlusion (same as the original 61a68fa, screen-space AO, GTAO: Jimenez, Wu, Pesce, Jarabo 2016, applied only to indirect light like Unity URP SSAO): added ToonPostProcess::set_ambient_occlusion(is_enabled, intensity, radius, resolution_scale, direct_lighting_strength), get_ambient_occlusion (ToonAmbientOcclusion), is_ambient_occlusion_enabled, draw_ambient_occlusion(gl, line_target, view_matrix, projection_matrix), get_ambient_occlusion_texture, get_ambient_occlusion_prepass(gl) and draw_ambient_occlusion_with_prepass, ToonRenderer::set_ambient_occlusion_texture, get_ambient_occlusion_texture, ToonDrawQueue::set_post_process and has_post_process. The three shaders (GTAO, horizontal blur, vertical blur with upsampling) are the original text as is. 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 draw_outline draws nothing). ToonDrawQueue computes it after the line target and before bodies, sets it on the renderer and clears it after end_frame. The body shader switches to a body program with TOON_AMBIENT_OCCLUSION defined (sharing the default outline and shadow depth programs, falling back to the default when it cannot be built) and multiplies the visibility at the screen position into the ambient light. The texture unit is 16. The original uploads the origin in the ambientOcclusionOrigin field of the ToonFrame frame block; Rust has no frame block yet and uploads the same value in a uniform with the same name. With it off, bodies use the default body program, so the screen is byte-identical to before. A capture test (tests/toonambientocclusion.rs) draws the same scene as the original toonambientocclusionchrome (room corner, crate, robot) with the same checks, and the measured darkening (wall corner, left corner, beside the crate, under the robot's feet) equals the original to the first decimal. Between the two engines (640 x 360), 55 pixels differ when on in perspective, 6 in orthographic and 25 to 140 in the AO texture, by 1 to 2.
- Direct lighting strength for toon ambient occlusion (same as the original 50cb8de, in the form of Direct Lighting Strength in Unity URP SSAO and HDRP ScreenSpaceAmbientOcclusion.directLightingStrength): added the fifth argument direct_lighting_strength of set_ambient_occlusion (0 to 1, default 0 in the original), get_ambient_occlusion_direct_lighting_strength (post process and renderer), ToonAmbientOcclusion::direct_lighting_strength and the second argument of ToonRenderer::set_ambient_occlusion_texture. After the band 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) (the original text as is, multiplied at the same places, so strength 0 is byte-identical). Rim light, glow, matcap and angel ring stay as they are. The value is uploaded in the uniform ambientOcclusionDirectLightingStrength (the original uses the last field of the frame block). The capture test checks that with strength 0, 0.25, 0.5 and 1 the wall corner darkens 4.9, 5.9, 7.3, 9.8 and under the robot's feet 4.2, 6.0, 8.1, 12.1, the same as the original, and that open floor and the robot head stay byte-identical to off even at strength 1.
- Toon ambient occlusion vertical blur at half resolution and upsample as a four-tap depth and normal weighted bilinear (same as the original 394f5af, like Unity URP SSAO, which blurs in the reduced buffer): the vertical blur was moved out of the full-resolution upsample pass (7 x 2 = 14 taps) into the half-resolution pass with the same shader as the horizontal blur (direction uniform blurDirection), and the upsample now mixes the 2 x 2 nearest half-resolution cells with the bilinear weight multiplied by a weight chosen by the pixel's depth and normal (4 taps). No new buffer: the GTAO buffer and the blur buffer are used in turns (horizontal from the GTAO buffer to the blur buffer, vertical from the blur buffer back to the GTAO buffer). The shader text is identical to the original character by character (a test compares with the original file). On the same scene (room corner, crate, robot, 640 x 360, perspective, orthographic and outline) the picture differs from the original in Chrome by at most 2/255 (within 0.5% of the pixels).
- Does not use discarding attachments at the end of a pass (invalidate_framebuffer); passes that overwrite a whole target clear it first (clear_buffer) (same as the original f94e794): measured per site in the original 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 (51 ms on SE2 becomes 11 ms with it off, 90 ms becomes 25 ms on iPad). RenderTarget::resolve no longer discards attachments after resolving (is_attachment_kept of resolve_with_attachment_kept is no longer used and is kept), and the opacity layer (begin_opacity_layer) 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. The screen result is unchanged.
- Web image decoding through the browser (same as the original) and wasm size: on the web, 2D images are always decoded by the browser (HTMLImageElement), as in the original. Images of AssetLoader and ImageAsset::load are decoded by the browser by content without a type even if the response type and extension are not images (same as the original img.src), and ImageAsset::load_from_bytes stays loading until the browser decodes an untyped Blob, like the original loadFromBytes (if it cannot, it fails with "Load fail: path", same as the original). So the web wasm no longer ships the image crate decoders (including webp, gif, bmp, ico), the engine JPEG decoder or the color profile reading. On the web, color glyph PNG decoding and screen capture PNG writing use the png crate under image (desktop is unchanged). On the web the image crate remains only on the paths that decode 3D material and GLB images on the spot (Material, decode_glb_image), and is not shipped in games that do not use them. The wasm-bindgen command in the README and guides now has --remove-name-section --remove-producers-section (drops the function name section and the producers section). _bg.wasm size after wasm-bindgen (Mac, wasm-release, engine codegen-units 1, before is the old README command, after is the new one): uigallery 3,431,940 -> 2,945,625 bytes (gzip -9 1,196,670 -> 1,109,185), toonview 3,533,498 -> 3,047,917 (1,230,223 -> 1,142,121). loadingshowcase, which loads images, compared with sections removed on both sides: 5,356,171 -> 4,931,916 (2,195,165 -> 2,047,645). The pictures of the three examples captured in headless Chrome differ from before by 0 pixels.
- Streaming audio loading (same as the original AudioLoadType, the form of Unity's AudioClip Load Type and Unreal's sound wave streaming): AudioAsset gains the load type AudioLoadType (Automatic, DecompressOnLoad, Streaming) with set_load_type, get_load_type, is_streaming, get_stream_url, and the threshold AUTOMATIC_STREAMING_BYTE_THRESHOLD (1 MiB). Until now every sound was fully decoded to PCM, so one 3 minute stereo background track held about 61 MiB (f32). The default stays full decoding (DecompressOnLoad) as in the original, and only assets set to Automatic stream files larger than 1 MiB (the file size on desktop, the response Content-Length on the web). The engine SoundSystem sound row (SoundRow) gains a load_type field; when it is None, background music (is_music) uses Streaming and sound effects use DecompressOnLoad. Desktop: a streaming asset holds only the compressed source (a file path or bytes in memory) and the trim plan (opening demuxes the file once), and when played, a decoder thread per player decodes chunk by chunk into a ring buffer (16384 frames, 128 KiB for stereo) that the mixer's streaming source reads (nothing is decoded on the audio thread). Packet reading, Chrome's start and end trimming, the SincResampler and the speaker rules are the same code as full decoding, so the produced samples are bit-identical to the fully decoded buffer (27 test formats), and the streaming source computes like the buffer source, so playback, the end, the loop seam, a start position, stopping, playback rate and a different device sample rate produce bit-identical output. Looping reopens the decoder at the end and writes the next pass right after, without a gap, and a start position (set_time) decodes from the start and discards up to it. When the ring runs dry it outputs zeros meanwhile and the position follows the context clock. The duration (get_duration) is the length the container reports (the same as full decoding for the MP3, AAC, FLAC, WAV and Ogg test files; WebM, whose blocks carry no duration, can differ by about 4 milliseconds (-68 to +177 frames)) and becomes the decoded length once the sound has been decoded to the end. Web: as in the original, an HTMLAudioElement is connected to the player's GainNode through a MediaElementAudioSourceNode (one media element per player, the pitch follows the playback rate, other origins use CORS, sounds loaded from memory use a blob: URL). When the context is suspended the media element pauses and resumes with it, get_time is the media element's position, and background music faded out by SoundSystem stops when the fade ends. Measured (Mac mini M2 Pro, 3 minute stereo AAC of 2.92 MB, release optimization): full decoding loads in 107 ~ 125 ms and holds 63,504,000 bytes of PCM; streaming loads in 1.6 ~ 1.8 ms (demux only) and holds a 131,072 byte ring, playing from the start takes 0.7 ~ 1.0 ms (one ring fill), and playing from 150 seconds takes 0.03 ms (the decoder thread decodes from the start and discards up to that point, so the sound starts that much later; that delay was not measured). The original on a real device (iPhone SE2) loaded in 137 ms against 8,618 ms for full decoding.
- Drawn rects now match the original: Text follows the original calculateDrawnRect and calculateWrappedDrawnRect (a single line reserves 1.5 times the font size above and below the baseline, wrapped text reserves one font size around the line block, horizontally half the font size plus the stroke, and Start and End cover both sides). Before, the rect used the measured ascent and descent and was tighter, so Rust alone culled a row at the scroll edge that the original draws. ShadowText reports a generous rect regardless of baking (twice the blur, the bake padding and the shadow offset), RichText the summed width of its segments with the largest font size and stroke (append_segment and clear_segments mark it dirty), the rich mode of UILabel uses that rect, HeatHazeEffect the wobble amplitude plus 1, UIInputField the content area and the single line text area plus 2 (tick marks it dirty when the drawn values change), and the input field context menu its shadow margin. Before, all of these were unknown, so their ancestors were never skipped. The per node component culling (WorldNode::draw_components) now also widens the content area by one unit when a component draws inside the content, and ignores empty rects, like the original (before, it was one unit tighter and culled boxes at the scroll edge one frame earlier than the original).
- Subtree "fully inside" mark (same as the original): when the subtree draw bounds of a node lie fully inside the visible rect (shrunk by one device pixel), its descendants skip the subtree check, the component culling and the visible child range search while the node is drawn, and only look at the bounds size. A new clip starts checking again inside it (clip state serial). The check in parent coordinates uses the inner rect when the transform is axis aligned, and the check after the transform uses device coordinates. Added Graphic::is_inside_visible_bounds. The example subtreecullinside (SUBTREECULL_CHECK=1) renders the scene of the original subtreecullinsidechrome with culling on, off and all off, and compares the screen bytes, the draw count of each box and the count drawn as fully inside.
- Uploading images during the loading screen (same as the original prepareLoadedImages and prepareImage, the form of Unity's asyncUploadTimeSlice and Unreal's upload while loading): added Graphic::prepare_loaded_images(time_limit_milliseconds) and prepare_image(image). Images read and decoded by ImageAsset and AssetLoader (AssetLoadHandle::set_decoded_image) are stored as images not uploaded yet (weak references), and after the scene's tracked assets are read the engine uploads them to the GPU during the loading screen, 2 milliseconds per frame (counted together with the extra 0.3 seconds of display). It initializes only after all are uploaded. Capture mode uploads all at once. The Graphic held by the engine when ImageAsset::load is called is the owner, and a Graphic uploads only its own (if the owner is unknown, only when there is a single Graphic, same as the original). Until now uploads piled up on the first drawing frame.
- UIInputField IME, two fixes (same as the original; single line and multiline, including the desktop dialog input box): composing with text selected shows [text before the selection, composition, text after the selection] while composing (get_display_text, TextEditBuffer::build_display_text, drawing, cursor and underline positions; until now the composition was inserted at the cursor leaving the selection in place; committing replaces the selection as before). Added TextEditBuffer::get_composition_start, get_composition_end and get_display_text_before_cursor. set_text during composition clears the composition state and text (until now it stayed stuck in the composition state with the old composition text left in the visible text).
- Bone pose hook (the same place as the original, the same shape as Unreal AnimBP's Transform (Modify) Bone and bone overrides in Unity's LateUpdate): added a seventh argument pose_adjust: Option
to write_skin_pose. After the animation is sampled and blended, and before the skin matrices are built, it modifies each bone's local transform (translation, rotation, scale). ToonPoseAdjust::Hook(&mut hook) is called with (locals, skeleton) and the hook makes the changes (locals is a copy for that call only, so modifying it in place does not change the skeleton's rest pose), and ToonPoseAdjust::Bones(&[BoneModifier]) applies a per-bone modification table (node_index or name, translation, rotation, scale, mode, weight, Default changes nothing). Added adjust_bones(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. With None the result is bit-for-bit the same as before, and modifying one bone changes only that bone and the bones below it. The skin matrices of fox.glb (table, blend and table, hook) are bit-for-bit the same as the original run in Chrome 158. (tests/assets/skinposeadjust) - Quaternion normalization in pose computation (sampling animation channels, mixing two rotations) now uses the Math.hypot computation like the original (the engine's hypot_list). Before it was the square root of the sum of squares, so the last digit of the length could differ from the original. (34 % of a million random quaternions; skin matrices are f32 so the last digit rarely differed)
- 3D camera shake (the same place as the original, the shape of Unity Cinemachine Impulse and Unreal Camera Shake): added CameraShake. CameraShake::new(base seed) (Default is 1); each shake from add(CameraShakeOptions) takes the strength of 3 position axes and 3 rotation axes (pitch, yaw, roll) (amplitude, rotation_amplitude, per-axis shares position_axes, rotation_axes), frequency (frequency, default 10), duration (duration), attack (attack), decay ((1 - age / duration) to the power decay_exponent, 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: Option
). 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() (CameraShakeOffset { position, rotation } in camera local axes), is_shaking and clear. As places to apply it, added Camera3D::set_view_offset(position, rotation) (an offset in camera local axes applied last to the view matrix, on both the computed path and raw matrices, get_eye_position is the value before the offset) and create_offset_view_matrix(&view_matrix, position, rotation), which applies it to a view matrix the game computed. The seed drawing order and sine wave constants are the same as the original, so 852 read() values and the offset view matrices are bit-for-bit the same as the original run in Chrome 158. (tests/assets/camerashake) - glTF quantized mesh reading (KHR_mesh_quantization, same as the original): the toon GLB readers (read_glb_arrays, read_glb_node_arrays, read_glb_node_infos) 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, read_glb_node_infos gathers the bounds per name). The rebuilt outline thickness of a skinned mesh with integer positions is matched to rest pose model coordinates. If extensionsRequired lists an extension the reader cannot read (EXT_meshopt_compression, KHR_draco_mesh_compression and others) or an accessor points to a buffer outside the binary chunk (the meshopt fallback buffer), it returns Err with the same text as the original. Added read_float_accessor_array, AccessorArray::Byte and Short, COMPONENT_TYPE_BYTE and COMPONENT_TYPE_SHORT. The original test's synthetic GLB files and the values the original readers produce (tests/assets/glbquantization) check that both engines give the same values (tests/glbquantization.rs, difference 0 on macOS). For the mining ship, the mannequin and the fox with normals quantized with gltfpack, the arrays read by both engines are identical to the byte.
- Flat normals for glTF primitives without normals (same as the original 8cc37df, glTF 2.0 specification 'Using Primitive Data': without normals the primitive has flat normals and tangents are ignored): the toon GLB readers (read_glb_arrays, read_glb_node_arrays) split the vertices of a primitive without normals per triangle in index order, and give each triangle's (p1 - p0) x (p2 - p0) scaled to length 1 to its three corners (0 for a triangle with zero area). The outline shell rebuilt from the body does the same. Before, such primitives were not stored, so reading the example fox.glb with the toon reader gave an empty picture. 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 interpret_content splits the vertices with the same math and gives flat normals (rounded to 32-bit floats like the original Float32Array), and indices is None (positions, texture coordinates, joints, weights and morph deltas are split too). The toon and PBR arrays of eight real GLB files (the mining ship, the fox without and with normals, the mannequin and their quantized versions) read by both engines are byte-identical in all 110 files (108 before, the two PBR foxes differed). The body and shell arrays of a row of mesh builder shapes (box, rounded box, cylinder, sphere, lathe, capsule, torus, octahedron, faceted chunk, and quad and triangle shells of front and back faces whose normals cancel) are also byte-identical to the original in all 28473 values. (tests/glbquantization.rs, the fox and asset tests in skinnedmodel.rs)
- Toon highlight (same as the original e85d927): per-ID line color on ToonScreenOutline, set_line_color(line_id, color), remove_line_color(line_id), clear_line_colors(), get_line_color_count(). (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, and it is uploaded only when it changes. A line where two IDs touch takes the color of the nearer ID, and IDs not in the table keep the set_color color. With an empty table the composite is pixel-identical to before.
- ToonRenderer per-instance emission: emissive_color (Option<[f64; 3]> sRGB, default None) and emissive_intensity (linear multiplier, default 1) on ToonInstance. Added on top of that instance's shading and pattern so only that instance brightens. 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.
- Capture test of the same scene as the original Chrome test, tests/toonhighlight.rs (cargo test --test toonhighlight, GL of a hidden window): the five images (base, line color, after clearing, body, emission) are pixel-identical to the original in Chrome on the Mac. (0 different pixels out of 96000 at 480 x 200)
- Toon GLB accessor range: the toon GLB readers (read_glb_arrays, read_glb_node_arrays, read_glb_node_infos) return an Err for an accessor that reads outside the binary chunk instead of filling it with 0, and fill an accessor without a bufferView with 0 as the glTF specification says instead of reading bufferView 0. (The same meaning as the accessor reading of the original SkinnedModel. The original toon readers use the short array they read as it is and throw a TypeError without a bufferView, so the same check goes into them too)
- Sun shadow bias follows the shadow texel size (same as the original 025ea9d, 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 set_bias(depth_bias, normal_bias), get_depth_bias and get_normal_bias (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 capture test with the same scene as the original Chrome test, tests/shadowbias.rs (cargo test --test shadowbias, GL of a hidden window), checks both, and the measured values (face darkening 0.0 and 0.0, low wall shadow -1.505 ~ -1.53 with depth 98, tall wall -1.505 ~ -2.095) match the original in Chrome. The shader chunks match the original character for character, and the bias math matches the original readShadowBias bit for bit. Point and spot light shadows (ShadowAtlas) already use a normal bias scaled by texel size and slope and are unchanged.
- Capture mode determinism (same as the original): in capture mode (VANILLA_CAPTURE_*, web ?capture=), the 0.3 second loading screen wait after a scene loads is counted on the engine clock (1/60 second per frame) instead of real time. While a scene still has loading that takes real time, such as downloading assets (tracked assets and tasks other than the GameScene loading gate, which opens on the engine clock), 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. (.github/scripts/capturedeterminism.cjs captures quickstart and loadingshowcase twice each and compares them)
- Scene hook forms now match the original (since the global engine works anywhere, hook names and arguments are the same as the original Scene, GameScene and UIScene): the load order is create(), then load(engine), then initialize(engine), as in the original. The former create(engine) (the place of the original async load) is renamed load(engine), and a new create() hook without arguments is added (called once before load; the engine fits the root to the view size in between). Only the hooks that take the engine in the original (load, initialize, finalize, unload) receive engine: &Engine; the others receive only the original arguments: draw_on_load(graphic), destroy(), on_page_process_restored(), on_page_visibility_restored(), resize(canvas_native_size), tick(time_delta), pre_draw(graphic), draw(graphic), post_draw(graphic), draw_gizmos(graphic), touch_press, touch_move, touch_release, touch_cancel(view_input_position), touch_wheel(view_input_position, wheel_delta). load_assets() and layout() of GameScene and UIScene take no arguments, like the original loadAssets() and layout(). The public base functions match the original too: SceneBase::tick(time_delta), tick_touch(time_delta), draw_scene_background(graphic), and on GameSceneBase and UISceneBase load(engine) (formerly create), load_assets(), draw_on_load(graphic), resize(canvas_native_size), layout(), compute_safe_area_rect(), tick(time_delta), is_dev_tools_capturing_input(), pre_draw(graphic), post_draw(graphic), draw_screen_fade(graphic), apply_play_area_reference(). ScreenFadeDarkStarter::start(scene) no longer takes the engine.
- Global engine (the same place as the original static Engine.getEngine(), the form of Unreal's GEngine and Godot's Engine singleton): the engine is created once and never removed. Engine::new puts the engine in a place that lives until the program ends and returns &'static Engine, and Engine::get_engine() returns the same engine as Result<&'static Engine, EngineAccessError> anywhere right after creation (scene functions, draw, component tick and draw, widget callbacks, page event listeners, inside async tasks). All public engine functions are now &self (interior mutability), and the engine that scene hooks and task contexts (EngineContext::with, SceneContext::with) receive changed from &mut Engine to &Engine. Reading managers and the graphic gives Ref from get_x and RefMut from get_x_mut (get_all_loaded_scenes, get_canvas, get_engine_configuration and get_platform give Ref too), and borrowing the same field again while it is being changed panics with the function name and field name. Another thread gets Err(OtherThread), and if no engine was ever created it is Err(NotCreated). The original Scene.getEngine is SceneBase::get_engine and UIView.getEngine is UIView::get_engine, giving the same global engine. ComponentContext::get_engine gives an &Engine that outlives the context. (core/globalengine.rs)
- Anti-aliasing on and off (same field as the original): added EngineConfiguration.antialias (default true, same look as before). Turning it off stops using multisampling (MSAA) for the default framebuffer. Desktop picks the GL configuration with the fewest samples without asking for multisampling, and the web creates the WebGL context with antialias: false. It removes the per-frame resolve cost on high-resolution mobile devices. The web only chooses on or off and the browser picks the sample count. Desktop uses 4 samples when on.
- Render pixel ratio cap (ViewManager::set_max_render_pixel_ratio) in the same form as the original: the same value does nothing, and a change only stores the value and raises is_view_rect_pending. Both desktop and web fit the canvas and view area at the start of the next frame through the same path as a window resize (Engine::resize), and scenes receive the screen area change. calculate_view_rect lowers it once fitted. Added ViewManager::is_view_rect_pending().
- 3D render scale (ToonView3D::set_render_scale, get_render_scale, same range 0.05 ~ 4 as the original, 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 (depth 24, 4 samples when the default framebuffer is multisampled) to transparent and draws the 3D into it (stencil and scissor off, resolved when done), then 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. 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 set_depth_cleared(false) only works at scale 1. The target is deleted when detached from the node (detach) and when dropped. The fifth argument of the draw function changed from the drawing buffer height to ToonViewOutput (output_framebuffer, the framebuffer bound now, None for the default framebuffer, and output_viewport, the GL viewport inside it, integers, bottom-left origin; outputFramebuffer and outputViewport of the original rect). examples/toonview shows it with the environment variable VANILLA_RENDER_SCALE=0.5 (original ?renderScale=0.5). As in the original, the ToonRenderer translucent blend builds the alpha channel as premultiplied over (ToonBlendMode::Alpha is SRC_ALPHA, ONE_MINUS_SRC_ALPHA, ONE, ONE_MINUS_SRC_ALPHA) and additive leaves alpha unchanged (ONE, ONE, ZERO, ONE). On macOS, toonview at scale 0.5 against the original in headless Chrome has a mean difference of 0.10 and 0.33% of pixels over 8 (multisample patterns on edges). The UIDocument test data (the RenderScale field of ToonView3D) is the original files as is.
- Same names as the original: WorldNode::copy_content_size_to(&mut Vector2) (original copyContentSizeTo) and ShadowAtlas::get_light_count() (original getLightCount). The original made isComponentDrawCulled, refreshMatrices and readStorage, used only internally, private and removed UIButton.setStateEvent, which did nothing.
- Toon outline depth margin (same as original 836e59e, in the spirit of Unity and Unreal depth-normal edge detection that fits the threshold to the measured error): when ToonScreenOutline separates occluded silhouettes inside one id, it uses the distance of the occluding pixel from the tangent plane of the occluded pixel. It used the smaller of the two pixels' tangent plane distances, but when the occluder is the silhouette of a round surface its tangent plane contains the view ray and the distance shrank below one pixel, so a line could break into dots. The fixed margin added to the threshold (twice the pixel size at that depth) became a margin proportional to the measured error: the angle error of the 8-bit octahedral normal (0.0165 rad) x the distance between the two pixel positions, one pixel x the sine of the angle between the two normals for two pixels on either side of a crease, and one 24-bit depth step. Added the margin scale set_depth_margin, depth_margin (default 2) and depth_threshold. The seed shader text is the same as the original. In the toonao offOutline frame (640 x 360) the pixels that differ between the two engines went from 37 (largest difference 153) to 0.
- GPU throughput measurement (same as original 9af0e19, like the Unity profiler GPU module and Unreal stat gpu, to see the time the GPU takes to draw on its own): added Engine::measure_gpu_throughput(frame_count). It draws the current scene back to back without ticking scenes, through the same draw path as an engine frame (the scene drawing of the engine update split into the same function), waits for the GPU with a 1-pixel read, and returns the wall-clock time per frame as GpuThroughput { frame_count, chunk_frame_count, milliseconds_per_frame, chunk_milliseconds_per_frame } (Promise<Result<GpuThroughput, String>>). From the next engine update it draws 10 warm-up frames and then one chunk of 30 frames per update so it never blocks for long; engine time, input, frame number and capture stand still while measuring, and the engine loop resumes when done. Because it draws the same state repeatedly, caches such as shadow OnChange do not re-bake, and presenting happens only for the last frame of each chunk.
- Engine GL context GlContext (the same place as the context with intercepted state functions that the original Graphic.getWebGL2RenderingContext returns): Graphic::get_gl, the run_external_pass pass, the toon renderer's on_before_draw, ToonDrawQueue stage callbacks and the ToonView3D draw function now give GlContext instead of glow::Context. glow's HasContext is a sealed trait that cannot be implemented outside glow, so GlContext intercepts the state functions (bind_framebuffer, viewport, scissor, enable, disable, is_enabled, clear_color, color_mask, blend_func, blend_func_separate, blend_equation, blend_equation_separate, depth_mask, depth_func, front_face, cull_face, use_program, link_program, delete_program, bind_vertex_array, active_texture, bind_texture, pixel_store_i32, create and delete, get_parameter_* reads) as methods with the same names and signatures as glow and calls them through the state cache; every other function (all methods of HasContext and the inherent methods of the web glow::Context, 380 of which 44 are web only) is generated by machine as a method with the same name and signature (src/core/glcontext/generated.rs, the header comment says how it is generated) and calls the inner glow::Context as is. Deref is removed and there is no public way to take out the inner glow::Context, so passing a GlContext to a function taking
&glow::Contextis a compile error (game code has no way to skip the state cache, the same as the original intercepting the context and knowing every state call). Functions inside the engine that receive GL (public and private alike) also take&GlContextinstead of&glow::Context. The named creates of desktop GL 4.5 (create_named_framebuffer, create_named_texture, create_named_buffer, create_named_vertex_array), program_binary, pixel_store_bool and the web bind_external_framebuffer are also written by hand so that they go through the state cache or make it forget what it remembered. Desktop GL functions that the original WebGL2 does not have (per draw buffer enable_draw_buffer, color_mask_draw_buffer, blend_func_draw_buffer, blend_equation_draw_buffer and the like, plus viewport_f32_slice, scissor_slice, bind_texture_unit) make the state cache forget the affected value. So when game code changes state through GlContext and keeps calling engine drawing inside the same callback, the engine no longer skips wrongly. The state cache also tracks the blend equation (blend_equation, blend_equation_separate), like the original. Two real GL tests were added: 800 random calls mixing GlContext and the engine path, checking without any reset that read answers and skip comparisons match real GL (0 differences), and a pixel test that engine drawing is right right after GlContext changes the program, texture, active unit, blending and scissor (it also checks that changing them through raw glow goes wrong, so the test does catch the problem). Added a test that calls 44 kinds of state functions 2000 times at random through the game path (GlContext) only and compares in check mode after every call (0 mismatches), and five compile_fail doc tests checking that code taking out the raw glow::Context or passing it to a function taking&glow::Contextdoes not compile. The safety-net resets the engine did at the boundaries (get_gl, the end of a run_external_pass pass, after on_before_draw, after stage callbacks) are removed (same as the original). The examples modelviewer, blendmodes and batchclip render pixel-identical images to before (modelviewer compared with frames paired two apart, because its scene start depends on wall clock time). - 2D batching breaks less often (same screen result, the same scheme as the original): (1) Axis-aligned square clips whose edges lie on pixel boundaries (begin_clip_rect, Mask, UIScrollView) are discarded by the batch shader at pixel centers using a clip rectangle table index carried in the vertices instead of the stencil (the Unity RectMask2D and UI Toolkit scheme), so setting and releasing clips keeps the batch going. Rotated or rounded clips, and clips whose edges are not on pixel boundaries on a multisampled screen (desktop reads the sample count of the default framebuffer, the web reads the context attribute antialias like the original), still use the stencil (a multisampled stencil half-covers edge pixels, which differs from the pixel center rule). Unbatched draws (swapped-in shaders, shader blending, shader-blended particles) apply the same rectangle as a scissor, and run_external_pass writes the shader clips to the stencil for its duration. (2) One batch binds several textures (the smaller of the device MAX_TEXTURE_IMAGE_UNITS and 16), so the batch continues while images, shapes (white texture) and text textures alternate (the PixiJS scheme). (3) draw_colored_quads (particles, heat haze) also joins the same batch under fixed blending and computes with the same formula as the particle shader. (4) Off-screen culling (is_local_rect_visible) also checks the bounding box of the active clip, so components of rows outside a scroll view are not drawn (like Unity RectMask2D, automatic with no option). The DevTools inspector shows isDrawnInsideContent of UIView, UIButton, UIProgressView and UISlider in the same place as the original. The batch vertex limit is 6 x 8192, the same as the original. Measured (macOS desktop, hidden 1920 x 1080 window, example batchclip, every pixel identical to before): a settings-window-like scene (one window, a UIScrollView, 50 rows, each with text, a button and a shape) went from 45 draw calls to 1, and the same scene as the original tests/core/batchclipchrome.test.mjs from 51 to 14 (every pixel identical to the stencil path drawn with a 1e-9 radian rotation).
- Shadow and toast argument forms (same as the original): ShadowText::set_shadow and ShadowImage::set_shadow take the opacity separately like the original setShadow(color, opacity, offset, blur) (the color's alpha is ignored). ToastMotion::new() takes no arguments like the original new ToastMotion() (enters from the top, change it with set_enter_side), and show(text, stay seconds, apply function) takes a FnOnce(&mut ComponentContext) called when the toast starts to enter, like the original show(text, seconds, applyText). set_apply_text_handler and ToastApplyTextHandler are gone (now ToastApplyText).
- No reserved-word names (same names as the original): neither engine uses a reserved word (use, move, loop, in) as a name. Cooldown::r#use is removed in favour of activate (original activate), FullscreenPass::r#use and ShaderProgram::r#use are removed in favour of use_program (original useProgram), PointerGesture::r#move is move_pointer (original movePointer), Action::r#loop is repeat_while (original repeatWhile), and easing_function's r#in, out, in_out are ease_in, ease_out, ease_in_out (original easeIn, easeOut, easeInOut). Easing names in timeline data (such as "quadratic.in") are a data format and stay the same.
- Text antialiasing as a Graphic method (same place as the original Graphic.setTextAntialiasEnabled, isTextAntialiasEnabled): added Graphic::set_text_antialias_enabled(bool), is_text_antialias_enabled(). The original import.js now also exports AudioManager, DevTools (renamed from the original DEVTools), Pane, PaneStyle, PaneTheme and WebSocketClient, so both engines share the same top-level names.
- Matching the two engines (small Rust-side items): the soft disc texture (default particle sprite) is fully opaque up to radius 0.7 and fades out with smoothstep from 0.7 to 1 like the original (it was (1 - distance)^2, so particles were smaller and fainter). Node gizmos draw component gizmos first and then the border and pivot in '#00ff00' with a pivot radius of 4, like the original. BuildInfo quietly moves on when version.json cannot be fetched, like the original (the handle finishes with empty bytes, so it is not in the AssetLoader failed list). The statistics panel (use_statistics) writes engineVersion, platformName, browserName, canvasNativeSize, referenceResolutionSize, viewScaleMode, viewNativeRect, viewSize, input positions, time, framePerSecond, timeDelta, drawCalls, vertices, triangles and culledNodes at 1.4x in 16px DOSGothic, 16 per line, like the original drawStatistics (ViewScaleMode::get_name gives the original value text such as "stretchShort"). format_number and format_number_with_unit check the language tag in the same order as Chrome (V8 CanonicalizeLanguageTag, ECMA-402 IsStructurallyValidLanguageTag), and an invalid tag ("EN_gb", an empty string, "en-u" and so on) is Err(FormatError::InvalidLanguageTag) like the original RangeError (the error text matches Chrome too, 77 tags checked against node). Capture mode (VANILLA_CAPTURE_*, ?capture on the web) advances time by 1/60 s per frame for deterministic captures (the same arithmetic as the original ?capture, and the time at frame 30 is bit-identical to Chrome. The Chrome comparison also takes the same frame number through the original capture mode. The 0.3 s after scene loading is real time, like the original setTimeout). SpriteAnimator::find_sprite (the original findSprite, remembers the NodeId of the node holding the Sprite). UIDocument to_json_text and serialize_node are single functions like the original toJsonText and serializeNode and read &mut self getters too. UISceneBase::get_dev_tools and get_dev_tools_mut (the original UIScene.getDevTools). The draft tilemap shares tilesets like the original (Rc
, do not modify after adding) - Logic numbers are f64 (same as the original JavaScript number; like Unreal 5's large world coordinates, the CPU is f64 and the GPU is f32): all of the engine's logic arithmetic is f64. The components of Vector2, Vector3, Quaternion, TransformMatrix, Rect, OBB, Pivot and Color, base::math, tweens and easing, timelines, actions, animators, particles, node transforms and UI resolution, cameras, input coordinates, time (elapsed time, time_delta), sound volume and playback position, 3D transforms and skeleton arithmetic, reflection values and UIDocument numbers are f64. f32 stays only where the original uses Float32Array, Math.fround or WebAudio float: vertices, indices and uniform arrays going to the GPU (Graphic's vertex buffer, ToonMeshArrays, toon instance data, joint matrices, morph weights), the elements of Matrix4 (stored as f32 like the original, calculated per element in f64 and stored as f32), sound samples, the mixer and AudioParam values (Chrome WebAudio float), glyph raster and the inside of Canvas2D (Skia float), image decoders and color management. The drawing functions narrow to f32 when they put into a vertex buffer and when they upload uniforms. The last digits that differed from the original because of f32 arithmetic now match (a timeline color at 1 second is the same #80007fc0 as the original, 0.2 no longer becomes 0.20000000298023224 in a UIDocument round trip, the Gaussian sum of a blurred shadow is f64 like the original). The experimental physics world's advance now runs holding a FixedStepper like the original (before, the same arithmetic was kept separately inside the world). FixedStepper::get_alpha means the same as the original Math.max(0, Math.min(1, ratio)) (-0 becomes +0).
- Web dialogs and web context menu: matching the original, which moved to engine dialogs and engine menus, the Rust web build no longer uses the browser window.alert, confirm, prompt or the DOM context menu. It draws on the canvas the same engine dialog as the desktop (Chrome tab modal style; the scene and async tasks pause while it is open; Enter confirms, Escape cancels) and the engine context menu (UIInputFieldContextMenu). Text in the prompt field is received by a hidden DOM input, like the original (IME). Right-clicking a field or an engine menu blocks the browser menu. Browser UI text is chosen from the 82 Chromium translation locales by navigator.languages
- Reflection cannot be left out (every component is reflected, like the original): Reflect is now a supertrait of Component. The one way to make a component is #[vanilla::reflect], and leaving out either the impl block or the impl Component block gives a compile error that points at where to add it. Engine components that were missing it (the drafts RigidBody2D, Tilemap, AudioSource2D, AudioListener2D, Skeleton2DAnimator, plus UIInputFieldQuickMenu, the three web pane components, and the tree's placeholder) all have it now. The UI document writes every unregistered component by reflection like the original, and the developer tools inspector shows the getters of every component. (The "no reflection" line, the saved-key fallback, and the warning that dropped components without reflection are gone) The five enums of the draft Tilemap (orientation, stagger axis and index, render order and mode) are reflected as the original strings. The UI document output (keys, order, values) of the five draft types was compared and matches the original.
- GameScene loading and touch recognizer (the same in both engines): both engines measure the minimum loading time with the engine clock (get_realtime_since_startup), and if the engine clock has not started yet (before the first frame) they measure from the first loading screen frame. A press on the loading screen is read from engine input (is_touch_pressed) by draw_on_load. The TouchRecognizer is created in initialize like the original.
- Developer tools memory fields (desktop): the jsHeapSizeLimit field shows the upper bound the operating system allows for this process's heap. (platform::desktop::read_heap_size_limit: on macOS and Linux RLIMIT_DATA if set, otherwise physical memory; on Windows the smaller of physical memory and virtual address size from GlobalMemoryStatusEx) In both engines, all three fields are "(N/A)" if the heap cannot be read, and only that field if just the limit cannot be read.
- Desktop Pane canvas tag: where the original tools put the preview engine's canvas (the canvas element in uieditor and particleeditor), the render target's screen is drawn. Draw the preview scene into a render target and pass it with PaneElement::set_canvas_texture, and it is stretched over the element's inner box (calculate_canvas_box_size, where the original canvas has clientWidth, clientHeight). The same scene (a canvas in an rgb(16, 17, 20) box with vanilla at top left and red at bottom right) was captured in Chrome and on the desktop, and the position, orientation and colors matched. The original keeps its DOM canvas, so nothing changed there
- Opacity layer (group opacity like CSS opacity): Graphic's begin_opacity_layer and end_opacity_layer (the original beginOpacityLayer, endOpacityLayer) 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 set_opacity_layer(true) (the original setOpacityLayer) 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. Desktop Pane elements read CSS opacity and draw it with this layer. The same scene (red and blue boxes overlapping, grouped at opacity 0.5) was captured in Chrome and on the desktop, and the overlap color matched (19, 19, 146)
- Glyph raster (Windows and Linux desktop): painted like Chrome. Windows paints with DirectWrite using the same settings as Skia's SkScalerContext_DW (on a machine with ClearType on, Chrome keeps text as LCD so kGenA8FromLCD applies on the canvas, so it uses the average of the three channels of a ClearType 3x1 texture; with it off, grayscale A8; grid fitting, rendering mode chosen by the gasp table, size, bytecode hints and bitmap fonts; fake italics through the glyph matrix), and contrast and gamma are the DirectWrite rendering values only when the primary display has the Avalon.Graphics registry key like Chrome 158, otherwise contrast 1 and sRGB pre-correction. Linux follows Chrome 158, which draws system fonts and ordinary web fonts with Skia Fontations (skrifa) instead of FreeType: it applies the same hinting from fontconfig's hintstyle to skrifa outlines (Light with glyf auto-hinting for slight, Normal with auto-hinting fallback for medium, Strong for fonts that require hinting) and pre-corrects with gamma 1.2 and contrast 0.2. Both use 1/4 pixel subpixel positions like the Mac. CI compares a text scene (examples/glyphparity.rs) with Chrome 158 on the same machine.
- Audio thread priority (desktop): turned off cpal's realtime feature (audio_thread_priority, MPL-2.0) and, on the first call of the output callback thread, sets what Chrome's kRealtimeAudio does with operating system APIs (platform/audio/threadpriority.rs). Windows uses THREAD_PRIORITY_TIME_CRITICAL and MMCSS "Pro Audio" (AVRT_PRIORITY_CRITICAL, restored when the thread ends; was "Audio") like Chrome's wasapi_render_thread; Linux uses SCHED_RR priority 8 and nice -10 if that fails like Chrome's SetThreadTypeLinux (before, with no dbus feature, it did nothing); on the Mac the CoreAudio IO thread already has a time-constraint policy so it is left alone, and other threads get Chrome's SetPriorityRealtimeAudio three settings (timeshare 0, importance 63, time constraint of the buffer period). audio_thread_priority left the dependencies.
- Desktop Engine::new builds the graphics: like the original Engine constructor, get_graphic exists right after the engine is created. It builds the event loop on the main thread, creates the window hidden with that loop, builds the GL context and Graphic, and run shows the same window (hidden in capture mode) and draws as is. Textures, render targets and shaders built before run are used as they are. On machines that cannot build GL (CI without a display) and off the main thread (unit tests), it is built when run opens the window as before.
- JPEG decoding (desktop, and Image::load_from_memory on the web): decoded with a decoder written in the engine (core/jpegimage.rs) instead of the image crate (zune-jpeg). It follows the arithmetic Chrome 158's libjpeg-turbo 3.1.0 and Blink's JPEGImageDecoder choose (JDCT_ISLOW integer inverse DCT, smooth chroma upsampling h2v1, h1v2, h2v2, the 16-bit YCbCr tables of jdcolor.c, choosing the color space from component ids and the JFIF and Adobe markers), and matches Chrome WebGL texImage2D bit for bit on 51 test images (4:4:4, 4:2:2, 4:2:0, 4:4:0, 4:1:1, mixed ratios, progressive, restart, gray, RGB, CMYK, YCCK, ICC, EXIF orientation, lossless, small 1x1 to 33x18 images; before, up to 2 to 5 levels off). Lossless (SOF3) is newly decoded, and EXIF orientation is applied like Chrome (6 and 8 swap width and height). The CMYK ICC profile of a CMYK JPEG is converted like skcms. What Chrome cannot decode (12-bit, arithmetic coding, gray and YCbCr lossless, incomplete files with truncated data, no EOI or no remaining scan) is a transparent image with only the size read (Chrome fails to upload with INVALID_VALUE in WebGL texImage2D after onload; before, part was decoded or it failed). Chrome Canvas2D draws an incomplete file as far as it was received, which differs from that. JPEG inside SVG and in mouse pointer images use the same decoder. The jpeg feature of the image crate is off.
- Input field context menu: right-clicking a direct-touch field (set_use_direct_touch) now opens the same engine context menu as other fields. In both engines it has four items like the original: cut, copy, paste, plus select all (when there is text), and the original also blocks the browser edit-field menu on direct-touch fields. The Chrome edit-field menu that desktop drew separately (undo, redo, paste as plain text, emoji, writing direction, inspect) is gone. The long-press quick menu stays, and when there is nothing selected or to paste, and for "...", it opens the engine context menu
- Line breaking in multi-line input fields: desktop and the web canvas mode use the same algorithm. Like a Chrome textarea, it applies Blink's line breaking (the LazyLineBreakIterator fast table: ASCII pairs break only before opening brackets and after '-' and '?', a digit after '-' only when the character before is alphanumeric, Latin-1 pairs take the two-character ICU value) on top of the ICU4X LineSegmenter dictionary build at normal strictness (breaks before small kana and the prolonged sound mark). The break positions of 30 texts taken from a Chrome 158 textarea (English, URLs, punctuation, Korean, Japanese, Chinese, Thai, Russian, Latin-1) all match. (Until now desktop used plain strict UAX #14, which differed from Chrome after '/' and before small kana, and the web canvas mode approximated with word boundaries) icu_segmenter is now also a web dependency
- Component lookup: get_component, get_components, has_component, get_or_add_component, remove_component and NodeTree.with_component_mut also find embedded base types, like the original instanceof. Component::get_base_component(_mut) reports the embedded base (the original superclass), so ShaderSprite is found as Sprite and Paint, UIButton as UIControl and UIView, RichText as Text. (also Sprite, UIControl, UIDraggable, UISlider, UIToggleButton, UIScrollView, UISnapScrollView, UIImageView, UIProgressView, UILabel)
dyn Componentgets is_instance_of and as_instance_of(_mut). - DevTools: the tree Type column and the inspector type are the node type name (FloatingText, UIWindow and so on), like the original constructor.name. Adds UIDocument.get_node_type_name(node). The document DevTools holds at first calls register_editor_types.
- DevTools inspector: property values that point to a node (such as UIHitArea.targetNode) show that node's type name ([FloatingText], [UILabel] and so on) like the original constructor.name (always [WorldNode] until now). Document values of components without reflection also round numbers like the original toFixed (0.125 → 0.13).
- Action: the names now pair with the original. The form that holds the target is start(node_tree, Some(node_id)), step(node_tree, time_delta) and get_target() (the original start(target), step(timeDelta), getTarget), and start(node_tree, None) restarts with the previous target like the original start(). The form that passes the target every time without holding it is start_with(&mut target), step_with(&mut target, time_delta), and the original gained the same startWith(target), stepWith(target, timeDelta). The inner actions of repeat, forever and loop run in this form in both engines and do not hold the target.
- Animator.get_parameters(): returns the names and AnimatorParameter (Float, Int, Bool, Trigger) in first insertion order, like the original getParameters. AnimatorParameter is public.
- FloatingText: draws the label with UILabel like the original. (same settings: text, size, color, bold)
- FloatingText::create: like the original constructor, puts the FloatingText node's pivot and anchor at the top-left. spawn's world position is relative to the parent's top-left, so labels appear at the same place as the original (until now the anchor was the center, so they were pushed by half the parent size). Captured both engines with the same settings and saw a pixel difference of 0.
- JSON writing: every engine path that writes JSON (LocalStorage.set_json, PersistedStore, UIDocument.to_json_text, WebSocketClient.send, DevTools settings, the draft save) writes text identical to the original JSON.stringify down to the character through the single storagetext::stringify_json. Numbers use the original String(number) form (1.0 → 1, 1e21 → 1e+21, 1e16 → 10000000000000000), and object entries put array-index-like names first like an original JS object. The indented form is stringify_json_with_space (the original JSON.stringify(value, null, space)) and text quoting is quote_json_text. JSON reading turns on serde_json's float_roundtrip and reads the nearest number like the original JSON.parse (123456789012345680000 used to be off by one digit).
- TouchEffect: bakes the particle gradient with the engine Canvas2D radial gradient (create_radial_gradient, fill_rect) like the original. All 64x64 alpha values match the same canvas code in headless Chrome.
- PersistedStore: get_string_code_units(path) and set_string_code_units(path, code_units) read and write a string in the state as JS code units (UTF-16). A lone surrogate saved by the original comes back exactly as the original string. (the same form as LocalStorage *_code_units)
- Shader build failure: when ShaderSprite or ScreenEffect fails to build, the original now reports once and skips like the Rust engine. (the original used to stop the frame with an exception) Both engines are the same.
- Fallback font choice (desktop) like Chrome FontCache::PlatformFallbackFontForCharacter: the 217 measureText strings are identical on Mac Chrome 158 (arm64, Rosetta x86_64), Windows Chrome 158 and Linux Chrome 158. (Before, Mac 144, Windows 181, Linux 216)
- The default font chain (the original SYSTEM_FONT_STRING) follows only when the default font name default was asked for. With another name such as "16px Arial", it goes to the operating system fallback without the chain. (The original also uses that chain as the font string only for the default font)
- Fallback is asked separately per first font (the first face that has a space glyph) and per font string, and the fallback face draws only the characters the operating system chose that face for. When bold is asked for, the bold faces (Helvetica-Bold in Helvetica.ttc, GeezaPro-Bold, tahomabd.ttf on Windows) are read separately too, and on Mac and Windows the fallback faces are grouped by the family name in the font name table to pick the weight. (Tahoma, which has a different file per weight, also becomes Tahoma Bold for bold) Linux, like Chrome, asks fontconfig without weight and slant and uses the chosen file as is, drawing fake bold and fake italic, and for bold or italic it looks at the regular face of the first name first. (Bold Arabic is fake bold of DejaVuSans.ttf)
- Even when a face in the name list lacks the composed character (ï), if it has the canonically decomposed characters (i, U+0308), it draws with that face like HarfBuzz. (decompose_character was added to third_party/rustybuzz)
- Mac: asks CTFontCreateForString on the CTFont of the first font (an uploaded font is one built from bytes), and picks again from the same name when the traits or weight differ. (Until now it asked the system UI font, so Arabic was drawn with another font)
- Windows: for bold or italic, the regular face of the first name, then the Blink font_fallback_win.cc blocks and per-character tables (Thai Tahoma, monospace Arabic Courier New, Han characters by the UI language), the wide font list, and a DirectWrite order based on the first name. (Until now it asked only DirectWrite based on Segoe UI, so Thai was Leelawadee UI)
- Text whose characters are all U+00FF or below is shaped as Latin like Chrome (the 8-bit text path of HarfBuzzShaper). Words with only Common characters, such as digits, also use the font's latn features. (Linux Norasi has digit kerning only in DFLT, so 16px "0123456789" was 3.8px narrower)
- The web is the same: the original SYSTEM_FONT_STRING at the end of the font list handed to the browser is appended only when default was asked for.
- YUV to RGB conversion of AVIF (desktop) like Chrome 158 (CrabbyAvif crabby_avifImageYUVToRGB, libyuv, called by AVIFImageDecoder): the forms libyuv accepts (BT.601, unspecified, BT.709, BT.2020 NCL, chroma NCL matrices at 8, 10 and 12 bits) use libyuv's integer arithmetic (YuvPixel, YPixel, doubled chroma upsampling), and everything else uses libavif's float arithmetic (changed to divide per value and then mix chroma). High bit depths are stored as 16 bits like Chrome WebGL and decoded as half precision with the mantissa truncated like libyuv HalfFloatPlane. Alpha is decoded as straight alpha and multiplied with rounding. 19 test images match Chrome 158 WebGL texImage2D bit for bit (before, libavif's float arithmetic was 1 to 23 levels off). Picture pixels change by a level or two.
- FBX multiple materials: an FBX mesh with several materials (the Materials of LayerElementMaterial, MappingInformationType ByPolygon or AllSame) is split into partial meshes by each polygon's material index and drawn as one drawable per material. (three.js FBXLoader groups, Unity and Unreal submeshes) Until now the material index was looked up by polygon vertex order instead of polygon order, and each mesh was drawn with only the first material of its owning node, so the Quaternius mannequin (M_Main, M_Joints) was all orange. New SkinnedModel::split_fbx_corners_by_material and FbxCornerArrays; the FBX MeshDescription and the drawable's material_name are the FBX Material name (like glb), FbxMaterial.name. Same as the original. Unit tests multiple_materials_split_by_polygon and mannequin_fbx_materials_from_examples (the same triangle counts as the original, 5732 and 8012). The doc images model-viewer, and effect-gallery, shader-sprite and screen-effect after the shader hash change, were captured again (same size, cwebp -q 85).
- SceneBase.set_touch_dispatch_enabled(is_enabled), is_touch_dispatch_enabled(): turns off the scene's default touch passing, like the original Scene.setTouchRaycaster(null) (and the new setTouchDispatchEnabled). When off, tick_touch does not pass press, move, release or wheel to nodes (nor call the first touch callback), and only the scene's touch hooks are called, so the hooks can intercept and pass touches directly.
- SpriteAnimator.play: the default form takes the node and puts the first frame into the Sprite right away, like the original play: SpriteAnimator::play(&mut node, clip_name, options) (formerly play_on_node). The old play(&mut self, ...) that took only the animator is now play_clip, for when there is no node (inside the complete callback). After the complete callback the frame goes in during the same tick, so it changes right away.
- GamepadManager: get_all_connected_gamepads and get_connected_gamepad read in place when called, like the original navigator.getGamepads() (desktop drains the gilrs events for the current state and hands connects and disconnects to the next update, the web calls navigator.getGamepads()). Reading takes &self and returns copies read in place (Vec
, Option , a copy of that moment like the original). gilrs is created on the first call (update, vibration or list read), so vibrate before the first tick also rumbles on desktop. A manager fed with update_all_gamepads_with_list returns the list it was given. - Dropping an AudioPlayer: dropping the player no longer stops what it is playing. Like a WebAudio source node in the original, the sound plays to the end. On desktop the mixer keeps the player node (and the bus node it outputs to) until the source ends and then removes them. On the web, onended is replaced with a self-releasing callback, the source plays to the end and the GainNode is disconnected afterwards. A play that was waiting for the context to resume still starts after the resume, as in the original. (until now dropping stopped the sound)
- Sine, cosine, tangent: math::sin, cos and tan and the tween easings (sinusoidal, elastic) no longer use the system libm. They compute what Chrome's Math.sin, cos and tan compute (correctly rounded f64, src/base/trigonometry.rs: Payne-Hanek reduction with a 2/π bit table and a double-double series, no fma) and store the result in f32. Over 22,000 inputs sin, cos and tan matched Chrome 158 bit for bit. (The macOS system libm differed in 896 sin and 8,719 tan results) The system libm gave different last digits on macOS, Windows, Linux and wasm. math::tan now computes the tangent directly instead of sin / cos. It is slower than the standard functions (about 0.5 microseconds per call).
- Shader hash: hash21 (ScreenEffect, ShaderSprite) and hashPoint (toon VFX) became integer hashes that mix the float bits with the fmix32 finalizer of MurmurHash3 (Austin Appleby, public domain), same arithmetic as the original. The patterns of film grain, glitch, value noise and toon VFX noise change.
- Human skin environment BRDF: uses a formula the engine fitted by computing the split sum integral directly instead of the Karis approximation (same coefficients as the original, RMS error 0.071, 0.029 to 0.002, 0.006). Environment reflection changes.
- Images (desktop): embedded color profiles are converted to sRGB like Chrome. PNG cICP, iCCP, sRGB, gAMA and cHRM, JPEG APP2 ICC, WebP ICCP, AVIF colr (ICC, nclx primaries and transfer, PQ, HLG). ICC is read like Skia's Rust parser (para, curv, mft1, mft2, mAB, mBA, cicp), color space choice follows Chrome skia/ext/color_profile.cc and SkColorSpace, and conversion follows skcms and SkColorSpaceXformSteps (core/colorprofile.rs; the new direct dependency png 0.18 is the same version image already uses). 31 PNG and WebP test images match Chrome 158 WebGL texImage2D bit for bit. AVIF differs by a level or two because of the YUV to RGB arithmetic (Chrome uses libyuv), a few levels with a profile attached, and JPEG by a level or two because of decoder differences. 3D materials are not converted, like the original createImageBitmap (colorSpaceConversion "none"). (Until now no color profile was applied.)
- Animated AVIF (desktop): like Chrome (CrabbyAvif), the first frame of the track for the major brand avis and the primary image item for avif are decoded, and files with only a track are decoded too. Chrome always uses the first frame in drawImage and texImage2D (bitmap_image.cc ImageForDefaultFrame, image_extractor.cc) so it does not animate. (Until now an avis file decoded the primary image item, which could give a different frame from Chrome, and a file with only a track could not be decoded.) An AVIF with nclx transfer characteristics 9, 10, 11 or 12 cannot be decoded, like Chrome.
- Glyph positions (desktop): calculated at the 16.16 fixed point scale of the font size like Chrome HarfBuzz (Blink HarfBuzzFace::GetScaledFont, SkiaScalarToHarfBuzzPosition). Font unit values use em_scale, variable GPOS deltas em_scalef, rounded at that scale; axis values are normalized in 16.16 like HarfBuzz hb_ot_var_normalize_coords, avar is mapped in floating point and reduced to 2.14, and trak tracking is rounded with em_scalef_x. 222 of 228 strings (three texts at weights 300, 400, 700 and italic, Mac SFNS (system-ui) 8 to 128px) match Chrome 158 measureText to the last digit and the rest are within 6.1e-5px. (Before, "AVATAR Type Wolf" at weight 300 128px differed by up to 0.093px.)
- rustybuzz 0.20.1 has no scale, so a build with Face::set_scale and HarfBuzz-style axis normalization is in third_party/rustybuzz, and a corrected ttf-parser 0.25.1 (which read the device table of pair kerning, PairPos format 1, 2 bytes off) is in third_party/ttf-parser, both depended on by path. A game that fetches by git gets them too. There is no new crate.
- Font choice (desktop, Mac): italic system-ui and BlinkMacSystemFont use the SF italic font (SFNSItalic) like Chrome MatchSystemUIFont. (Until now it was fake italic on upright SFNS, 0.7px narrower at 13px and 7.4px at 48px.)
- Font names (desktop): like Chrome, a quoted generic name ('monospace', 'serif', 'system-ui') is not turned into the default font table; the font of that name and the uploaded face (FontFace) are looked up. The Mac has no font of that name so it is the next name or the standard font, and 'system-ui' is the system UI font like Mac Chrome FontCache. An unquoted generic name does not look up uploaded faces. -webkit-body is the standard font, and if the last generic name in the list is -webkit-body, even a name with no uploaded face is the standard font. The Mac finds BlinkMacSystemFont among the faces uploaded under the name system-ui. (Blink style_builder_converter.cc ConvertFontFamily, css_font_selector.cc GetFontData, font_selector.cc FamilyNameFromSettings, 24 strings measured on Mac Chrome 158.) The web also passes quoted generic names to the browser with their quotes. (Until now the quotes were stripped and they became generic names.)
- Desktop text ascent and descent (TextMetrics font_ascent, font_descent, and the top, middle and bottom baseline positions) like the Chrome canvas: like Blink FontMetrics::AscentDescentWithHacks, the operating system's vertical values (Linux typo if USE_TYPO_METRICS else hhea, Mac hhea, Windows OS/2 win values unless USE_TYPO_METRICS) are each rounded, and only small fonts (ascent under 3px or ascent + descent under 2px) are not rounded (the canvas's subpixel_ascent_descent). The Mac adds 15% to the ascent of Times, Helvetica and Courier (the same table as line height). Until now hhea values were not rounded, so they differed from Windows and Linux Chrome by up to 0.27px, and Windows Consolas by 3.1px. (Checked with CI's Windows and Linux Chrome 157 measureText.)
- Desktop font choice: when no face is found in the name list of a font string (an uninstalled name, or a generic name with no default font such as Linux cursive and fantasy), the first font is the screen language's standard font like Chrome (-webkit-standard; Times New Roman for Windows and Linux English). Until now the sans-serif of the default font chain (the original SYSTEM_FONT_STRING) came first, so widths differed from Windows and Linux Chrome. The name default is still the default font.
- Desktop bitmap color fonts (CBDT such as Noto Color Emoji): the advance is the integer advance in the glyph metrics of the strike converted to a ratio of the font size, like Linux Chrome (FreeType and Skia), and the actual bounding box (actual_bounding_box_*) is the picture box moved and widened to outer integers. Until now hmtx was converted directly so one 16px emoji was 0.04px narrower than Chrome and the box was 0. (colorglyph::read_bitmap_glyph_advance, read_bitmap_glyph_bounds, LoadedFont::is_bitmap_only_font)
- Desktop emoji face choice in Chrome FontFallbackIterator order: a face in the name list is used first if it has the glyph regardless of color (Linux Chrome 157 draws the 😀 of "16px DejaVu Sans" in black and white), a sequence with a variation selector (❤️) accepts only faces that fit that presentation, and a color glyph face is preferred only at the operating system fallback stage. Until now a color face was preferred anywhere in the list. FontFaceDescriptors gained is_system_fallback (whether it is a face of the operating system fallback font, default false).
- Linux touch detection: reading X11 input devices (XIQueryVersion) is serialized so one thread at a time does it. libXi builds its extension info table without locking, so when several threads created an InputManager (in tests) it crashed with SIGSEGV in libXext's XextAddDisplay. (Confirmed with gdb on CI Linux.)
- Desktop shape edges: asks for multisample 4 in the window's GL configuration. (Chrome paints the original WebGL context's default antialias with min(4, GL_MAX_SAMPLES) samples of MSAA, Blink DrawingBuffer.) Mac CGL gives only configurations without multisample unless asked, so the edges of circles, rounded rectangles and lines were stair-stepped. If there is no configuration of 4 or more it picks again without asking and uses the closest to 4. On the Mac the number of differing pixels at shape edges of the same scene dropped from 1894 to 897 (what remains is the share where the sample positions are flipped vertically, ARCHITECTURE chapter 10).
- Mac desktop glyph raster like Chrome: every non-color glyph is painted by CoreText in the same way as Chrome Mac Canvas2D (Blink FontPlatformData::CreateSkFont's kSubpixelAntiAlias and subpixel positions, kUnknown_SkPixelGeometry on a transparent canvas, Skia SkScalerContext_Mac's A8-from-LCD: paint on white RGB with font smoothing on, undo CoreGraphics gamma 2 and apply brightness through a gamma pre-correction table, the table being Chrome Mac's sRGB with contrast 0, and 1/2 of the text color when font smoothing is gray). Glyph positions add 1/8 to x and round down like Skia, and pass the rest to CoreText in 1/4 pixel units. Overlapping glyphs are layered on top like the canvas (they used to take the larger value). Fake italics are drawn with the slant of the CoreText text matrix. Fonts uploaded as bytes are also built with CoreText. On the Mac the differing pixels of text in the same scene (10 to 48px text, serif, bold, italic, Korean, emoji, fractional positions, white and dark backgrounds) went from 59438 to 0.
- TextStringTextureCache: rasterize_text_with_color (a raster told the text color, used by the original's ShadowText, which bakes the text color as is, and by 2D canvas fillText) and textshaping::rasterize_glyph_at (glyph raster at a subpixel position and text color).
- Engine: the graphic is usable anywhere. Engine holds Graphic instead of EngineRunner, and like the original getGraphic, GL resources (textures, render targets, shader programs, toon renderers and the like) are built with engine.get_graphic(), get_graphic_mut() in a scene's create, initialize and tick, a component's tick (context.get_engine()), and the first segment of an async task and the lines after an await. (Until now the graphic was received only as the graphic argument in draw functions) Draw functions take the graphic argument as before. It is the engine's graphic taken out for a moment with Option::take and passed in, so inside them engine.get_graphic() is None and the graphic argument is used. (Neither RefCell nor unsafe is used, so there is no way to blow up with a double borrow) To use the engine and the graphic together as &mut outside drawing, use the new engine.with_graphic(|engine, graphic| ...)
- EngineContext::with_graphic, SceneContext::with_graphic also give the graphic in the first segment at the spawn site. (Until now None) Only the first segment of a task spawned inside a draw function is None, because that is while the engine has lent the graphic to that function
- DevTools: forcing all gizmos visible (the original setForceGizmosVisible) is applied to the engine's graphic at the end of tick. Like the original, it shows from the drawing of the same frame in which F2 or the Settings checkbox was pressed. (Until now it was applied in the draw of post_draw, one frame late)
- Examples: toonstyle and toonmaterial build GL resources in create, like the original constructors, and oldface and modelviewer build them in initialize after all assets are received. The guide's DynamicFont example also bakes once in initialize, like the original
- ToonRenderer::create_mesh: if building a GL buffer or vertex array fails, deletes the buffers and vertex arrays built so far and returns None. (Until now the ones built earlier were left behind and leaked) For the vertex array bound together with the instance buffer too, if the outline side cannot be built, the body side is deleted. (In the original, Chrome's createBuffer, createVertexArray always return an object, so there is no path that fails midway)
- FbxLoader: strips the binary FBX type suffix ("\u{0}\u{1}Model", "\u{0}\u{1}AnimStack") from the name of nodes (Model) and animation stacks. Clip names are "Take 001", not "Take 001\u{0}\u{1}AnimStack", and bone names are "mixamorig:Hips". (three.js FBXLoader cuts at the first null byte in BinaryReader.getString, and Assimp changes it to "AnimStack::Take 001" and then FBXConverter strips "AnimStack::", "Model::"; the original was changed too) Bone name matching when adding FBX animations to a model read from glTF (add_animations_from_fbx_*) also matches with these names.
- tools/apidoc: grouping modules reachable from outside through a pub mod chain (modules that hold modules below them, such as vanilla::experimental, experimental::tilemap) keep their module description and examples in the data even without items. (In place of experimental/experimental in the original's data; the crate root lib.rs is left out, like the original) Grouping modules are not counted as modules without examples. Removed the Korean text from the draft example code (physics 2D, save slots, pannermath).
- Folders: moved the mature features the original vanilla.js had in src/experimental to their proper places, so the folders of the two engines are now the same. The Rust version already had them in these places, and module paths (such as vanilla::graphics3d) are unchanged. In the original, games that used import.js are unaffected, and games that imported by file path directly switch to the new paths. Fixed the original paths in the file header comments and ARCHITECTURE chapter 9 to the new paths. (Old path in the original → new path)
- src/experimental/graphics/.js (3D) → src/graphics3d/.js (Rust graphics3d/)
- src/experimental/graphics/toon/.js (toon 3D) → src/graphics3d/toon/.js (Rust graphics3d/toon/)
- src/experimental/graphics/fullscreenpass.js → src/core/fullscreenpass.js (Rust core/fullscreenpass.rs)
- src/experimental/animation/animator.js, timeline.js, src/experimental/action.js → src/animation/ (Rust animation/)
- src/experimental/indicator.js, visual/visual.js → src/misc/ (Rust misc/)
- src/experimental/bunchasset.js, visual/visualasset.js → src/resource/ (Rust resource/)
- src/experimental/collection/.js → src/base/collection/.js (not in Rust, since the standard Vec, HashMap and the like handle it)
- src/experimental/camera.js → src/deprecated/camera.js (deprecated in the original too; not in Rust, since Camera2D covers it)
- src/experimental/aabb.js, transform2d.js, graphics/gl2d.js, graphics/webgl2.js (dead code) → src/deprecated/ (not in Rust)
- UIInputField word movement and deletion: like the original, Ctrl on Windows and Linux and Option on Mac together with Left, Right (extending the selection when combined with Shift), Backspace, Delete move and delete by word. (On Mac also Option + Ctrl + Backspace, B, F from the key bindings) Positions follow Blink NextWordPosition, PreviousWordPosition: Right goes to the start of the next word only on Windows (the end of the current word on Mac and Linux), on Mac a selection being extended does not cross its anchor, and in multi-line fields, like Chrome textarea, it does not cross to the previous line at the start of a line that has characters. If there is a selection, only the selection is deleted as its own undo group, and word deletion opens a new group that following deletions and character insertions join. (Same as 2309 positions measured in a headless Chrome 158 textarea)
- Added WordLeft, WordRight, DeleteWordBackward, DeleteWordForward to TextInputKey. Added DeleteWordBackward, DeleteWordForward to TextEditKind. (Code that matches TextInputKey, TextEditKind exhaustively adds the new arms)
- Added collect_word_boundaries, find_next_word_position, find_previous_word_position to core::textinput. Word boundaries, like Chrome, join across a period only between digits and do not join across a colon. (Chromium ICU wordbrk.patch) Desktop double-click word selection also uses these boundaries. (Double-clicking "www.example.com" used to select it whole; now, like Chrome, only the clicked piece)
- Text line-wrap word splitting (desktop): splits at periods (except between digits) and colons, like Chrome's ICU. ("www.example.com" used to be one chunk that could not wrap; matches the values measured with the original splitWords in Chrome; on the web the browser splits)
- Platform::get_safe_area_rect: clamps width and height to 0 or more. area_size is a size in CSS pixels. (Same as the original getSafeAreaRect fixed to CSS pixels)
- UIDocument: reading an unregistered node type reads it as a WorldNode and emits a warning. (Like components, in the original too) The original gained registerEditorTypes and filling in what the constructor created when reading again, so document reading in the two engines is the same
- Color: to_rgba_string, to_hex_string clamp components to 0 ~ 255 and the rgba alpha to 0 ~ 1 when writing. (Same as the original toByteComponent; previously 1.5 became "17f") Stored components are not clamped, like the original. (HDR colors) create_from_rgba reads the same things as the regex of the original createFromRGBA. (Starts with rgb, integer r, g, b, alpha like parseFloat; also fixed a panic on text with reversed parentheses such as ")(")
- RenderTarget::new, resize: if a GL object cannot be created midway, deletes what was built so far and sets the size to 0. (It leaked)
- Graphic.draw_polyline, draw_line, draw_line_loop, draw_convex_polygon: when the vertex buffer fills up, draws what has accumulated and keeps writing. Previously segments from the 683rd on (triangles from the 1366th on for convex polygons) were dropped.
- AudioPlayer.get_time: while playing, advances with the audio context clock (web currentTime, desktop mixer clock). Multiplies by the playback rate, wraps around by the length when looping, and otherwise stops at the length. When stopped or finished, it is the start position from set_time. (Same as the original)
- Web: key, mouse, finger and page events no longer halt when they re-enter within a frame (dispatchEvent, focus() and the like in game code). Previously keydown, keyup, blur borrowed the RefCell again and wasm halted with unreachable, and mouse, finger and page events dropped that event (dropping mouseup left the button stuck pressed). If the borrow is available right away the event is handled on the spot; if not, it is queued and handled in arrival order at the end of the frame callback. (platform/eventqueue.rs)
- Web: if EngineConfiguration.title is not empty and is not the default ("바닐라엔진", the desktop window title), writes it to the document title (document.title) at startup, like the original.
- ParticleSystem.apply_description: reads imageDataUrl of the description (the data: URL of the image picked in the particle editor) and sets it as the particle image. Desktop decodes it on the spot, and the web draws it once the browser finishes decoding. (null or empty text removes the image)
- FontAsset.load(engine, asset_path): newly added. Like the original load, calls load_font with the file name minus its extension as the family name.
- JsonAsset.load: awaiting the returned handle now ends in failure when JSON parsing fails too. (The rejection of the original JsonAsset.load; a fetch failure was already a failure) How to migrate: code that assumed it ends with Ok even on a parse failure gets Err. Code that does not await and checks with is_finished and get_data (SpriteAtlas and others) is unchanged.
- UISnapScrollView: set_snap_to_nearest, set_velocity_threshold only held values and were not used in the snap calculation. (The original was the same) Now in one-page mode (the default), on release, if the drag velocity is at least set_velocity_threshold (default 200, offset pixels per second), it moves one page in the velocity direction regardless of the dragged distance, and otherwise decides by the set_page_change_threshold ratio as before. set_snap_to_nearest(true) does not clamp to the page range while dragging, and on release goes to the nearest page. Added get_drag_velocity(). (The original getDragVelocity; also added to the inspector expected values inspector_getters.json)
- UILineChart: lowering the cap with set_max_sample_count drops the samples already held, oldest first. (Fixed to match the original)
- DevTools: with Show FPS on in Settings, draws an "FPS
" box at the top left of the window even when the panel is closed. (Same as the original, canvas native coordinates, over the panel when the panel is visible) - UIInputField cursor and deletion: like the original, the Left and Right arrows and Delete work in grapheme clusters (extended grapheme clusters), and Backspace follows Blink BackspaceStateMachine (one code point, with emoji sequences and CR LF as a whole). With a selection, an arrow without Shift collapses to the front or back of the selection. The clicked position lands only on grapheme cluster boundaries. (find_previous_grapheme_boundary, find_next_grapheme_boundary, collect_grapheme_boundaries, find_backward_deletion_boundary, TextEditBuffer::delete_range in core/textinput.rs)
- UIInputField maximum length: insertion, like a Blink input field, inserts the text only up to the remaining UTF-16 length. (Previously the whole value was truncated)
- UIInputField multi-line and Pane line-height normal: instead of 1.2 times the font size, rounds and adds the ascent, descent and line gap of the first font, like Chrome SimpleFontData. (On Linux typo if USE_TYPO_METRICS, otherwise hhea; on Mac hhea with the 15% adjustment for Times, Helvetica, Courier; on Windows the DirectWrite win values. On the web, the line height the browser lays out) Added textstringtexturecache::measure_normal_line_height_without_graphic, LoadedFont::calculate_normal_line_height.
- Mac key bindings: Home, End, like Chrome on Mac, scroll to the start and end while leaving the cursor (to the start and end of the line if there is nothing to scroll), and with Shift select to the start and end of the text. PageUp, PageDown scroll by one screen while leaving the cursor (with Option they move it, with Shift they select), and Ctrl + Left, Right go to the start and end of the line. Added ScrollToDocumentStart, ScrollToDocumentEnd, ScrollPageUp, ScrollPageDown to TextInputKey. (Code that matches TextInputKey adds the new arms)
- UIInputField double and triple click: in fields that emulate DOM input (use_dom_input, multi-line), like Chrome, a mouse double click selects a word (on Windows including the trailing space), a triple click selects a paragraph, and dragging extends by that unit. Consecutive clicks count, like Chrome aura, within 500ms (NSEvent.doubleClickInterval on Mac) and within 2 DIP horizontally and vertically. On the web it is the detail of mousedown. (Added TextInput::set_pointer_click_count, get_pointer_click_count, systemfont::read_double_click_seconds)
- Pane (desktop): reads flex-wrap (wrap, wrap-reverse), flex-flow, align-content, row-gap, column-gap (the two values of gap), white-space and text-overflow: ellipsis. Wrapping collects lines per CSS Flexbox 9.3, 9.4 and stretches them with align-content: stretch. (Same positions as headless Chrome) A wrapping flex with height auto inside a block takes the height of the lines collected at that width.
- Scroll bars of Pane (desktop) and multi-line UIInputField: like Chrome, on Windows and Linux a Fluent bar that takes up space (thickness 15, thin 10, buttons 18, thumb 9); on Mac an overlay thumb if the system setting (NSScroller.preferredScrollerStyle) is overlay bars, or a bar that takes up space (thickness 15, thin 11) if classic. Reads scrollbar-width and the track color of scrollbar-color. (Added read_classic_scrollbar_metrics, calculate_classic_thumb_span in web/pane.rs, systemfont::is_overlay_scrollbar_preferred)
- Animator: completed as a standard state machine, like the original. AnimationState gets set_speed, get_speed, set_loop (Option, None follows the clip), is_loop, get_duration, get_normalized_time, get_frame_index. AnimationTransition gets set_exit_time, get_exit_time, set_duration, get_duration, set_can_transition_to_self, can_transition_to_self, add_condition (name, AnimationConditionMode, threshold), get_conditions, is_exit_time_reached, and a from of None means from any state (Any State). New AnimationConditionMode, AnimationCondition (also exported from lib.rs). Animator gets set_float, get_float, set_integer, get_integer, set_bool, get_bool, set_trigger, reset_trigger, get_trigger, play, find_transition, start_transition, is_condition_satisfied, get_current_state_index, get_current_normalized_time, get_current_frame, is_in_transition, get_next_state_index, get_next_normalized_time, get_next_frame, get_transition_weight. In the same scenario it produces the same state order, weights and frames as the original. How to migrate: set_property, get_property, get_properties (serde_json::Value) are gone. Replace them with set_float, set_integer, set_bool, set_trigger and their getters. get_animation, get_animation_mut (the inner Animation) are gone too. AnimationTransition holds a list of conditions and is no longer Copy.
- Visual: added set_document_text, get_document_text, create_node (UIDocument, node tree). Builds a new node tree from the document and sets the root's local position to location. (Ok(None) if there is no document, Err if the form is wrong)
- SkinnedModel: when an animation FBX has several stacks with channels, each stack becomes a "clip name/stack name" clip. (Fixed in the original too; previously they all had the same name, so play_animation played only the last one)
- Timeline: made public the handler type aliases TimelineEventHandler, TimelineMarkerHandler, TimelineCompleteHandler, TimelineTargetResolver used in public function arguments, and exported them from lib.rs. The name form in the TIMELINE_EASING_NAMES docs is now "
.<in|out|inOut>", matching the actual names. - ImageTextureCache::get_texture: images whose pixel length is not width x height x 4 are not passed to GL. An image whose pixels another cache released after uploading is read back from that texture and uploaded, and if it cannot be read back either, it is not uploaded and returns None. (An empty array was passed to tex_image_2d along with the width and height, so GL read outside the array)
- Image::create_from_premultiplied_pixels, Image::create_from_pixels: panic if the pixel length is not width x height x 4. (Same as the original ImageData throwing an exception when the length is wrong)
- BloomEffect: if new or set_use_float_color fails midway, deletes the passes and render targets built earlier. A set_use_float_color failure keeps the previous version as is. (GL objects leaked)
- NodeTree::add_component: like the original addComponent, if a dependency component (require) is not on the node, attaches it first through the same path (attach, attach_to_tree). Until now only WorldNode::add_component attached them
- TextStringTextureCache: unregister_font_face, set_font_face_order, get_font_face_count, watch_unresolved_family_characters, take_unresolved_family_characters also strip the surrounding quotes from the name before looking it up, like register_font_face. (Names given with their quotes could not be found)
- ScreenEffect::destroy, HeatHazeEffect::destroy: no longer take graphic. (Same as the original destroy()) They hold a weak handle to the context when first creating GL resources, and release the GL resources themselves on destroy and when dropped (Drop, when the node is removed or the scene is unloaded). How to migrate:
screen_effect.destroy(graphic)→screen_effect.destroy(); the resources are released even if it is not called when unloading the scene. (The public API changes) If ScreenEffect fails midway while building render targets, it deletes what it built earlier - Renamed to the Rust conventions (Rust API Guidelines C-CASE). Functions, methods, variables, fields and modules are snake_case, enum values are UpperCamelCase, associated constants are SCREAMING_SNAKE_CASE. (setFillColor → set_fill_color, Colors::white → Colors::WHITE, Pivot::topLeft → Pivot::TOP_LEFT, ButtonState::normal → ButtonState::Normal) Removed #![allow(non_snake_case)] and the like, which silenced naming warnings, from lib.rs and the examples. Code that uses the engine must be renamed by the same conventions. (This changes the public API) 11,071 places changed, behavior is the same. (cargo test 252 passed, 0 warnings in desktop and web builds, example screens same as before)
- README: noted that it was verified on macOS (Apple silicon) desktop
- Moves general-purpose features that Exoplanet Miner had built and used separately on the game side into the engine. (The same features added to vanilla.js first, the game's content implementations are not brought over)
- Outline: a component that draws only the border. Rounded rectangle border (set_round_size) or circle border (set_circle); the line stays inside the content size
- UIProgressRing: progress ring that fills clockwise from the top center following the node's shape. Perimeter points are computed only when the size changes
- SoftShade, SoftShadeShape: soft shade that bakes a band (Band) or floor (Bottom) gradient into a small image and draws it stretched to the content size
- FrameProbe: detects slow devices from frame intervals over the first few seconds. (25% or more of frames exceeding 1.4 times the target interval; skipping every other frame at 90 Hz is not counted as slow)
- InputManager: held state and this frame's press and release of the three mouse buttons (MouseButton::Left, Middle, Right) (is_mouse_button_down, is_mouse_button_just_pressed, is_mouse_button_just_released), the list of touching fingers (get_touch_points, TouchPoint), whether the last input was a finger (is_touch_input), whether the wheel was scrolled with Ctrl (is_wheel_with_ctrl)
- Web: feeds mouse (press, move, release, wheel) and fingers (touchstart, touchmove, touchend, touchcancel) into engine input. Until now the web build did not pass canvas presses to the engine, so widgets such as UIButton could not be pressed on the web. The left button and the first finger are passed as touch, and emulated mouse events the browser sends right after a finger is lifted are ignored. Prevents finger scrolling and zooming over the canvas, the right-click menu, and page scrolling by the wheel
- Desktop: feeds the middle and right buttons and fingers (winit Touch) into the input manager. Records Ctrl for the wheel
- CameraGestures: camera gestures. Right drag (horizontal rotates, the canvas 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). Read every frame with update(input_manager, view_manager) and taken out with take_pan, take_rotation, take_tilt, take_zoom
- PointerCursor, CursorValue: mouse cursor. The engine holds one (get_pointer_cursor_mut), and when enabled it sets the cursor at the end of every frame. Over a UIButton (including while pressed) it is the button's cursor, otherwise the cursor of set_screen_cursor. A winit cursor icon on desktop, the canvas cursor style on the web (including image cursors from register_image_cursor). When disabled (default), behaves as before
- Engine: is_coarse_pointer() (CSS pointer: coarse on the web, false on desktop at first, later Windows and Linux read the devices). Added set_cursor and is_coarse_pointer to the platform layer
- UIHitArea: hit area expansion. UIHitArea::attach(node_tree, button_id, minimum_size) places a transparent hit area as the sibling right behind the button, expanding its width and height to at least minimum_size. Clicks in the expanded area call the button's Clicked and Click notifications. Tracks the button's position, size and pivot every frame, and set_clip_node clips the expanded area to within a window or scroll area. (Clips after converting to node coordinates even if the parent is rotated)
- UIButton: fire_click_events(context). Calls only the click notifications (Clicked, Click) without pressing
- ToastMotion, ToastPhase, read_toast_seconds: enter and exit motion attached to a notification node. show(text, seconds) slides in from the outer side (top or bottom) while growing slightly and settling back, then after staying, floats up and disappears. 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. show only takes the request and moves on the next tick, and the text is put into the node by the function set with set_apply_text_handler. While hidden, the node is only made invisible
- ButtonMotion, ButtonMotionStyle, ButtonMotionArea, set_button_motion_area, shake_button: button feedback. 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 Paint and draws a white inner border. The style is set per button (set_style) or on an ancestor node with set_button_motion_area. Reads the pivot to scale around the center. Buttons inside scroll areas also shrink while pressed. Touch devices do not use hover. When there is no feedback, the node is left untouched. To make decorations light up in their own shape, set_lit_handler
- ShaderWarmer, ShaderWarmerSource: shader pre-linking. At startup, links the same sources in the background with KHR_parallel_shader_compile and leaves them in the program cache of the driver (the browser on the web), so it does not stall when ShaderProgram later builds the same sources. Does nothing if the extension is absent. update(gl) every frame, is_finished, is_supported
- ShaderProgram is exported from the crate root
- Toon 3D (graphics3d/toon): clay-like single-color material and outlines. (Only the general-purpose part of the board 3D of Exoplanet Miner)
- MeshBuilder, ToonGeometry, ToonPartOptions, ToonQuad, ToonMeshArrays: puts box, rounded box, cylinder and cone, sphere, lathe, capsule, torus and octahedron shapes (create_*_geometry) into one mesh, multiplied by position, rotation and scale (create_part_matrix). Vertices are position 3, normal 3, color 3 (sRGB), material 2 (emissive, unlit), pattern 4 (index and color, meaning defined by the shader). Outlines are a shell (inverted hull) pushed out with points at the same position moving together, so it does not stick out too far at corners, and faces that fold over and flip while pushing are removed. Winding is corrected using the normal so the outside is the front face. Terrain built from faces uses add_quad, add_quad_shell
- read_glb_arrays, read_glb_node_arrays, read_glb_node_infos, write_skin_pose, read_animation_swing, ToonOutlineOptions, ToonSkeleton: reads GLB painted with material colors without textures into arrays. Reads baseColorFactor as sRGB, emissiveFactor as emissive, and outline (shell) and basic (unlit) from material extras. Given outline settings, builds a new shell from the body of nodes that have a ".outline" pair (or added_parts). Reads the skeleton and motion (including loop "once" in extras) and computes bone matrices for a single moment. (Blending with the previous motion, sway scale) Separate from the engine's SkinnedModel (textured PBR)
- ToonRenderer, ToonMesh, ToonDrawOptions: draws with a sun and ambient light of sky and ground colors, cel shading with set_band_count, emissive and unlit, tint and opacity, and the outline shell as back faces. Up to 96 bones. (Same as SkinnedModelRenderer) begin_frame records the previous draw state and end_frame restores it, so it can be inserted between 2D drawing (after flush_batch, before restore_render_state). read_program_sources can be passed to ShaderWarmer
- ToonPostProcess: HDR finishing. Blooms bright areas with BloomEffect on the scene drawn into a half-float render target, and outputs to the screen with exposure, approximate ACES tonemapping and sRGB gamma. (begin, end, set_exposure, set_bloom)
- SoundSystem, SoundRow: background music and sound effects managed through a sound table. Picking a recording different from the previous one in a recording group, the interval before the same sound can play again, limits on simultaneous instances of the same sound and in total (the oldest is cut when exceeded), pitch variation, playing only the first few seconds and fading out, background music crossfade and resuming from where it stopped, music volume, music ratio and effect volume. Mute engages if any one of the user, the page being hidden (set_page_hidden), or an external source (set_external_mute_provider) holds. load_sounds(engine) loads from the asset folder, and add_sound_asset adds sounds in memory. update(time_delta) every frame
- Renamed the audio backend module alias audioBackend to audio_backend (naming conventions)
- Localization: matches language tags by stripping subtags one at a time from the end (zh-Hant-TW → zh-hant → zh, underscores become hyphens) and also checks aliases from set_language_aliases. Right-to-left languages (is_right_to_left, set_right_to_left, initially ar, fa, he, ur, ps, yi, dv), wrapping inserted values in direction isolation characters (isolate_text), filling named placeholders (text_named, values joined only by slashes are wrapped once as a whole). (Only the engine part of vanilla.js LanguagePack; reading the list file, the tab title and font hookup belong to the game framework and were not ported)
- ShadowText: single-line text with a shadow underneath. Bakes the text over the shadow into a single image, so the node's opacity applies to it as one layer. The shadow is spread with three box blurs, and on overflow the text shrinks down to set_fit_minimum_ratio. When baking with a system font without font bytes on the web, it draws as Graphic text without the shadow
- ShadowImage: image with a shadow underneath. Places the image (or an atlas piece) centered in the node preserving its aspect ratio, lays a shadow under the image's shape, and bakes them into one layer. set_image_color tints it a single color. Downscaling blends evenly by overlapping area
- blur_coverage, compose_shadow_image: blurring coverage and composing an image with the shape over the shadow (used by ShadowText, ShadowImage)
- TextStringTextureCache: rasterize_text(text, font_string, bake_scale, padding) → TextRaster. Gets only the shape of the text as a raster. (Does not upload it as a texture)
- README: rewrote it with a strengths-focused introduction, example screenshots (docs/images), usage (scene lifecycle, nodes and components, asset loading, web build), technical notes (generational handle node tree, component access, batching, culling, asset loading without async, text rendering, 2D and 3D, web Korean input, platform layer), and a performance table
- README: external dependencies section. Lists each crate's version, where it is used, what it does and its license in tables split into common, desktop and web
- UIDocument, UIDocumentSaveContext, UIDocumentLoadContext, UIDOCUMENT_VERSION: exports a node tree to the same JSON document as vanilla.js UIDocument (.scene.json, the format the visual editor saves) (to_json_text, serialize_node) and reads it back to build it (from_json_text, deserialize_node). Key order, tab indentation and even number formatting match the text produced by the original toJsonText. Instead of reflection, build, write and read functions are registered in a table per type name (register_component_type, register_widget_type for widgets), and Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView from the original table plus ShadowImage are registered in advance. Types the original saves by reflection are written with the same keys as the original reflection result. Children inside a widget's content (contentChildren), excluding components a widget attaches by itself, and node references ($nodeRef) also follow the original. Unregistered types emit a warning and are skipped. Image paths are resolved with the image resolver (set_image_resolver), or without a resolver, from the ImageAsset requested by load_images, and images loaded later are attached by bind_pending_images
- Sprite: set_image_path, get_image_path (original sprite.imagePath), set_round_size, get_round_size (the original used these by inheriting Paint). UIImageView: set_image_path, get_image_path. ShadowText: get_text_align, get_fit_minimum_ratio. ShadowImage: get_image_color, set_image_path, get_image_path
- Enabled preserve_order of serde_json. JSON object keys keep the order they were written in. (UIDocument writes in the same order as the original JSON.stringify; until now it was alphabetical)
- ParticleSystem: ported the original's render shapes (Circle, Rect, Streak, Image of ParticleRenderShape and set_render_shape), attractor (set_attractor, clear_attractor, position relative to the emission point), wobble (set_wobble), streak length (set_streak_scale), world space (set_world_space), and the edge emission shape (EmitterShape::Edge, set_edge_width). The description (apply_description) also reads renderShape, attractor, wobble, streakScale, worldSpace, edgeWidth by their original names. Drawing gathers quads per shape and draws them at once. (circle is a soft circle, rect and streak a white texture, image the image texture) Like the original, image fades only by start alpha x (1 - life ratio) without a color curve
- EmitterShape, ParticleRenderShape are exported from the crate root
- Format (base/format.rs, original base/format.js): format_number (locale thousands notation), format_number_with_unit, format_compact_number (1.2K, 5.6M, 1.3B), format_padded_number (range clamping and zero padding), format_minutes_seconds (minutes:seconds). It outputs the same text as the original through rounding, negatives and -0, unit boundaries, NaN and infinity, and the exponent form of String(number). Locales use a table extracted from node 25 (ICU 78.3) instead of Intl (121 lines: decimal point, thousands separator, negative prefix, digit shapes, Indian grouping, minimum grouping digits, NaN text), and a tag not in the table is en-US. (The original uses the browser's default locale and a wrong tag is a RangeError.) It matches 24,000 values from running the original format.js with node.
- Version: branch field and create_with_branch. With a branch, to_string produces "major.minor.patch-branch". (Original base/version.js) Since the branch is text, Version is no longer Copy
- Platform: is_desktop_web(). true if not mobile, and not an iPad presenting as a Mac with multiple touch inputs (navigator.maxTouchPoints > 1). Always true on desktop builds (original base/platform.js)
- Rect: the rest of the original base/rect.js. overlaps (touching edges count as overlapping), intersection, union, Rect::clamp, get_min / set_min, get_max / set_max, get_center / set_center, get_left / get_top / get_right / get_bottom and set_..., set_width, set_height
- Vector2: the rest of the original base/vector2.js. divide, divide_scalar, modulo, modulo_scalar, add_scalar, subtract_scalar, half, cross, length_squared, angle, get_x, get_y, minus_one, positive_infinity, negative_infinity, Vector2::lerp (original formula from * (1 - t) + to * t), Vector2::clamp. Fixed two original bugs: modulo doing division instead of remainder, and half returning double instead of half
- math: the rest of the original base/math.js. random_int (both ends inclusive), pick_random, shuffle, shuffle_with_random_function, approach, move_towards, min, max, round (halves toward +infinity, -2.5 → -2), POSITIVE_INFINITY, NEGATIVE_INFINITY. floor, ceil, sqrt, abs, trigonometric functions and pow with original names were added under the same names in the math line below. (Computed with f32 methods. The original's hand-rewritten sqrt, asin, acos, pow, which were wrong, were also fixed in the original to use built-in functions)
- NodeTree: sibling order and hierarchy checks. set_sibling_index (past the end goes last), get_sibling_index, get_child_index, get_sibling_ids, is_active_in_hierarchy, is_visible_in_hierarchy (active, visible flag, opacity > 0 up to the root). WorldNode: get_child_index. (Original base/node.js, core/node/transformnode.js)
- ViewManager: set_max_render_pixel_ratio / get_max_render_pixel_ratio (render pixel ratio cap; on the web the canvas is refit at the capped ratio at the start of the next frame; not used on desktop since the GL default framebuffer cannot be shrunk), limit_render_pixel_ratio, apply_aspect_view_scale_mode (StretchWidthExpandHeight if taller than the reference, StretchHeightExpandWidth if wider, recalculated immediately), get_css_pixel_scale, set_safe_area_override and get_safe_area_insets (override > URL ?safeArea=top,right,bottom,left > measured CSS env, view coordinates). (Original core/viewmanager.js) Added read_page_query_value (web URLSearchParams, desktop None) and read_safe_area_insets (web measured env, desktop 0) to the platform layer
- Engine: unload_scene(scene_id). Destroys and removes just one scene after this frame ends. (Original SceneManager.unloadScene) load_scene returns a SceneId, and a scene knows its own handle via get_scene_base().get_scene_id(). A scene loaded and unloaded in the same frame gets neither create nor destroy
- Scene: on_page_process_restored, on_page_visibility_restored. (Original core/scene.js) Called for each scene after the engine wakes sound again and clears input. On the web: visible of visibilitychange, document resume, pageshow (persisted); on desktop: when the window is no longer occluded (Mac and X11) and resumed after suspended. The original called an undefined function (dispatchPageProcessRestored) on pageshow and threw an exception; the Rust version fixes it with the same recovery as resume
- Engine: page events (PageEvent: Hidden, Visible, Blurred, Focused, PointerDown) and add_page_event_listener, is_page_hidden. When the platform reports one, the engine passes it to listeners on the spot. (The original attaches listeners to document and window in each module)
- Audio backend: suspend_audio_context (web AudioContext.suspend, desktop silences the kira main track and resume restores it), player pan (web StereoPannerNode, desktop kira panning)
- Graphic: batches tinted draws too. Like the original, adds a separate batch shader that carries color and tint per vertex. (Until now, tinted draws were not batched and were drawn one by one) The screen is the same as before. (uigallery draw calls 63 → 61, misctour 24 → 12)
- Graphic: remembers the last bound shader program and the texture of texture unit 0, and skips use_program and bind_texture that rebind the same ones. The call that returns to the default program after flushing a batch is also deferred to the next single draw. The memory is forgotten when GL is handed out via get_gl, on restore_render_state, and at frame start and end, so no wrong image appears after code that touches GL directly, such as toon, skinning, bloom, SSAO, ScreenEffect and ShaderSprite
- Graphic: set_image_mipmap_bias, get_image_mipmap_bias. (Original setImageMipmapBias) Sets the value added when choosing a mipmap level as textureLodBias in the default, batch and particle shaders. Swapped-in shaders receive it if they have that uniform. Until now it was hardcoded to 0
- Text: keeps the wrapped lines and re-measures only when the text, font string (name, size, bold, italic), wrap width or registered fonts change. (Until now it measured on every draw) The font string is also built only in setters. TextStringTextureCache: get_font_registration_count. Finds baked strings by a hash of the key instead of a key string, so no key is built on every draw. Graphic: push_state reuses the storage of a slot used once instead of cloning the font string. set_font_string leaves it as is if equal. NodeTree: reuses the empty placeholder put in place when tick and touch take out components, instead of allocating it every time
- Off-screen culling: text is culled too. Component gets calculate_drawn_rect (the rectangle actually drawn, None if unknown), and if all enabled components of a node give a rectangle, their union is checked with the Graphic transform at draw time. By default, as before, the content area if is_drawn_inside_content, otherwise unknown (not culled). Text and UILabel (when not rich text) give the text rectangle from the alignment, overflow and wrapping results, ShadowText the position of the last baked image (not culled if changed and not yet baked), ShadowImage the rectangle including the shadow margin. (ShadowText and ShadowImage were culled by the content area until now, so overflowing text and shadows could be cut at the screen edge) In scenes with overflowing text, text scaled 5x, children of culled parents, and multi-line text aligned to the bottom growing upward, the screen with culling on is the same as with culling off. (uigallery2 draw calls 83 → 81)
- Text decoration: set_underline, is_underline, set_strikethrough, is_strikethrough, set_wrap_mode, get_wrap_mode and TextWrapMode (Word, Character) on Text, RichText, UILabel. (Original setUnderline, setStrikethrough, setWrapMode "word" / "char") Underline and strikethrough draw a line in the text color (thickness max(1, size / 16)) like the original, and RichText segments use the Text values when they have no segment attribute. Italic (set_italic) only held the value until now; the glyph cache reads italic, oblique from the font string and emulates it by shifting the fontdue raster right above the baseline and left below it (0.2 times the height). Web system fonts put italic into the Canvas2D font. is_italic in FontDescription. ShadowText also gets set_italic, set_underline, set_strikethrough (not in the original; the lines are baked together so the shadow lies under them too. Since it is single-line text shrunk to fit, no wrap mode was added). Text decoration at the top right of example engineextras
- TextStringTextureCache: set_text_antialias_enabled, is_text_antialias_on. (Original setTextAntialiasEnabled, isTextAntialiasOn) When off, the alpha of baked glyphs is split into 0 and 255 at threshold 128 and textures are sampled with NEAREST. (For pixel fonts, on by default) Glyphs baked with web system fonts are the same. The original leaves already baked glyphs as they are, but here the on state is part of the cache key, so glyphs drawn after the change are baked that way. Pixel text that turns it off only while drawing in example engineextras
- Image: releases CPU pixels after uploading to the GPU to return memory. (Until now the same pixels as the texture were held on the CPU to the end) get_pixels returns Ref<[u8]> and may be empty after upload. (This changes the public API) Added has_pixels, set_pixels_retained, is_pixels_retained. Images whose pixels will be read again are kept with set_pixels_retained(true). ShadowImage keeps the images it receives by itself, and if one was already released by being drawn elsewhere first, it attaches the texture to a framebuffer and reads it back. (The read-back pixels are byte-identical to the original pixels) The engine has no path for restoring a GL context, so there is never a need to re-upload from released pixels
- Input: moves the input that the shipped games (Found You, Doomsday Survival, Space Creature, Aberrant, Exoplanet Miner) built and used separately on the game side into engine defaults. (The same features added to vanilla.js first)
- GamepadKind, read_gamepad_kind(gamepad_id): classifies the kind by pad name. PlayStation (054c, playstation, dualshock, dualsense, sony), Nintendo (057e, nintendo, joy-con, pro controller), Xbox (045e, xbox, xinput, microsoft), anything else Other
- GamepadManager.vibrate(strong_magnitude, weak_magnitude, seconds): vibrates all connected pads. gilrs force feedback on desktop (Linux, Windows), vibrationActuator dual-rumble on the web. Does nothing on macOS, where gilrs does not provide vibration. For this, gilrs is built with vibration enabled. (One gilrs vibration thread runs on desktop; until now it was off)
- GamepadManager.get_active_gamepad_id(): the name of the pad that pressed a button or tilted an axis more than 0.5 in the last update
- GamepadManager.set_input_log_enabled, is_input_log_enabled: turns off and on the log printed on every button and axis change. Changed default behavior: off by default, so button and axis logs are no longer printed. (Changed the same way as the original; moving a stick even slightly flooded the log every frame, and no game relies on the log) set_log_enabled remains the master switch for all logs, including connection and disconnection
- InputManager.is_key_just_pressed, is_key_just_released, is_mouse_button_just_pressed, is_mouse_button_just_released changed behavior: instead of comparing snapshots at frame end, accumulates and checks events (push_key, pop_key, set_mouse_button_down) that arrived since the end of the last frame. Fixed missing presses and releases between frames. (In that case the held state is false and press and release are both true) Same as the original
- Added phase (TouchPhase: Began, Moved, Stationary, Ended, Cancelled) and view_position to TouchPoint. (The struct gains fields, so code that builds TouchPoint directly must be fixed) InputManager.begin_touch_point, move_touch_point, end_touch_point receive each finger, and fingers lifted this frame stay in get_ended_touch_points for one frame. The desktop and web platforms feed through this path, and the web removes fingers missing from the event's touches as cancelled. get_touch_points is still only the fingers currently touching
- InputDevice, InputManager.get_last_input_device, get_last_gamepad_kind (set_last_input_device, set_last_gamepad_kind): the last used device (Keyboard, Mouse, Touch, Gamepad) and gamepad kind. The platform records it from keys, mouse (movement over 6 pixels on the web) and fingers, and gamepads are recorded in tick via get_active_gamepad_id. Initially Touch on finger devices, otherwise Keyboard
- InputManager.set_prevented_keys(keys), get_prevented_keys, is_key_prevented, is_typing_in_text_field: keys whose default browser behavior is prevented. Web keydown prevents them when not typing in a text field. (Desktop windows have no default behavior to prevent) A text field is the focus of an engine input field and, on the web, the document focus (text input, textarea, contenteditable, select). Added is_text_field_focused to the platform layer
- InputActions, InputActionSource (core/inputactions.rs): input actions. InputManager holds one (get_input_actions, get_input_actions_mut) and updates it in tick. bind_key, bind_gamepad_button, bind_axis(action, axis_index, direction), unbind_action, get_bound_keys, set_repeat(action, delay_seconds, interval_seconds), set_dead_zone (initially 0.2), set_axis_press_threshold (initially 0.5), set_keys_ignored_while_typing (initially true), add_source(Box
) → id, remove_source(id), is_pressed, is_just_pressed (including repeats), is_just_released, read_value, read_axis(negative_action, positive_action), read_gamepad_stick(x_axis_index, y_axis_index), read_move_axis (the longest of WASD and arrow keys, left stick, and external sources, length at most 1). Unlike the original, movement keys and pad axes read the values recorded at update in the same frame - Camera3D, ProjectedPoint: 3D camera. (Added together with vanilla.js) Perspective (set_perspective) and orthographic (set_orthographic), aspect ratio (set_aspect_ratio), look_at, and view and projection matrices cached and recomputed only when values change (get_view_projection_matrix, get_inverse_view_projection_matrix). project_to_view(x, y, z, view_rect) computes a world point's position inside the 3D drawing rectangle and whether it is in front of the camera, unproject_to_plane(view_position, plane_height, view_rect) computes the point where the ray from a position in the rectangle meets the horizontal plane, and read_view_depth computes view-space depth. The renderer and 2D overlays use the same camera. (Replaces Exoplanet Miner, Aberrant, Doomsday Survival rebuilding camera matrices per screen and computing projection by hand)
- ToonRenderer: set_screen_rect(x, y, width, height), clear_screen_rect, get_screen_rect. Draws only inside the node rectangle. begin_frame moves the clip space of view and projection into the rectangle and cuts off the outside with scissor, and end_frame releases the scissor. Off-screen culling uses the frustum before the move. begin_frame_with_camera(Camera3D), draw_mesh_outline (draws only the outline, not counted). Added casts_shadow (read by ToonDrawQueue) and is_body_drawn to ToonDrawOptions. (Default true; 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. add_mesh, add_mesh_instanced, draw_shadows, draw(gl, renderer, camera). Borrows the models it holds, so it has the lifetime 'a. (From the queued drawing of Doomsday Survival ModelRenderer3D)
- Graphic: run_external_pass(is_depth_cleared, pass), clear_depth_buffer. Inserts a GL pass between 2D draws. Flushes the preceding 2D batch, clears depth, then calls pass(gl) and calls restore_render_state. Clearing depth after setting a clip (stencil) once caused no 3D to be drawn at all on Galaxy Fold3 (Adreno 660) (original game), so nodes that draw 3D inside a clip call clear_depth_buffer before begin_clip_rect and pass is_depth_cleared as false
- ToonView3D, ToonViewDrawer, ToonViewPass: a component that draws toon 3D inside the node rectangle. Transforms the content area with the current transform into a drawing buffer rectangle, and inside run_external_pass sets the renderer's screen rectangle and calls the drawer (ToonViewDrawer::draw_toon). The renderer is created on first draw, and on devices where it cannot be created it is not retried and draw_fallback draws 2D instead. The aspect ratio of the camera (get_camera_mut) is matched to the rectangle on every draw. Holds the drawer as a type parameter instead of the original's draw function, and the original's setRenderer (renderer sharing) was not ported
- ToonPostProcess: set_color_grade(saturation, contrast, tint color, tint amount, haze color, haze amount), set_vignette (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 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. (From the color grading of Doomsday Survival SceneEffects3D)
- MeshBuilder::combine(&[ToonMeshPiece]) offsets multiple static pieces and joins them into one array. Outline shells, shell reference positions, and inner ranges are also offset and joined, skeletons are not joined. create_faceted_chunk_geometry(radius, vertex scale, axis scale) is a faceted rock made by stretching and shrinking each of the 12 icosahedron vertices. (Doomsday Survival combineMeshArrays, Exoplanet Miner meshbuilder.js)
- GraphicsQualityGovernor, GraphicsQuality (Auto, High, Low): decides the lite path (is_lite) in the order override (apply_search_text, ?light of the page URL via apply_page_query on the web, set_lite_override) → setting (low always, high never) → auto (set_auto_lite_default, or FrameProbe measures the device as slow). update(frame seconds, maximum frame) measures only in auto and returns true on the frame it changes. set_render_pixel_ratio_limits(normal, lite path) and apply_render_pixel_ratio(view_manager). What to reduce on the lite path is up to the game. (Exoplanet Miner readIsLite, Aberrant isLight)
- Loading, saving, and time features that shipped games built separately are added as engine defaults. (The same features added to vanilla.js; the games' screen looks and release platform code were not brought over, the only changed default behavior is LocalStorage reads)
- TimeManager: set_maximum_time_delta(seconds), get_maximum_time_delta(). Changes the cap on a single frame interval. (Previously hardcoded at 0.25 seconds, the default is unchanged) Below 0 or not finite gives 0.25
- Engine: set_maximum_frame_per_second(n), get_maximum_frame_per_second(). Changes the maximum FPS at runtime. (Until now it could only be set at startup via EngineConfiguration) Writes to the configuration, and the desktop and web platforms read that value every frame. Below 0 or not finite gives 0 (no limit)
- FixedStepper: fixed step. advance(time_delta, step_function) of FixedStepper::new(step_seconds, maximum_steps_per_frame) calls step_function(step_seconds) for the accumulated time and returns the remaining fraction (0 ~ 1). If steps remain after running up to the per-frame cap, the remaining time is discarded, and if step_function returns false, that frame stops there and the time stays accumulated. (The original stops only on false and need not return anything, but the Rust version always returns bool) get_alpha, get_last_step_count, reset
- LocalStorage: storage swapping with set_backend(Some(Box
)), has_backend. LocalStorageBackend is a trait with get_item, set_item, remove_item and (optional) get_keys, clear, and the original's exceptions are Err. If there is no storage (blocked localStorage on the web) or a write fails (capacity, the desktop folder cannot be created, Err from a swapped-in storage), values are kept in memory instead for this run. (is_memory_fallback) get_item, set_item (whether it was written to storage), remove_item, get_json(key, default_value), set_json(key, &value) - LocalStorage: reads (get_string, get_boolean, get_number) no longer write the default value for missing keys. (This changes default behavior, changed the same way as the original) Merely reading created the key, so after a default changed in a new version the old default remained as if it were a saved value, and contains_key was always true. None of the shipped games using the original rely on this behavior. (2026-11-25 grep of game code, details in vanilla.js UPDATE.md)
- PersistedStore: set_storage_backend(Option<Box
>), has_storage_backend. Places just one store elsewhere. Swapping re-reads from there and notifies subscribers - AssetLoader: concurrent asset loading. add_image, add_json, add_text, add_blob immediately return an asset with a load handle that is still empty, add_audio returns Rc
(finished only when decoding is done), add_font(engine, family, path, is_bold) a load handle, and add_load_handle adds an externally requested handle (in place of the original addTask). load(engine) requests set_concurrency (default 6) at a time, and calling update(engine) every frame requests the next ones as others finish. (On desktop they are read on the spot and finish in load) Handing get_completion_handle to the scene's track_load_handle defers initialize until everything is loaded. get_progress, get_loaded_count, get_finished_count, get_total_count, get_failed_list (AssetLoadFailure), is_finished, get_in_flight_count, set_progress_handler, set_complete_handler. It is a cheaply cloned handle - AssetBase: load_from_handle(load_handle). Attaches a load handle that someone else fills. Engine: request_asset_bytes_into(path, &load_handle). An asset bytes request that fills an already created handle (both used by AssetLoader)
- LoadingProgress: the shown value (get_shown_progress) smoothly follows the reported progress (set_progress, 0 ~ 1, never decreases). update(time_delta) every frame, set_follow_rate (default 6 times the remaining distance per second), is_finished, reset
- GameSceneBase: loading screen customization. set_loading_colors(background, gauge background, gauge), set_loading_outside_color (outside the view), and set_loading_drawer(Some(LoadingDrawer)) replaces the whole drawing over the background. (LoadingDrawer is a function receiving graphic, view size, shown progress and elapsed seconds) When progress is reported with set_loading_progress or track_asset_loader, the gauge smoothly follows that progress instead of elapsed time. (get_loading_progress_state, the original getLoadingProgress; named this way because the Rust version already has an elapsed-time ratio under the same name) For loaders handed over with track_asset_loader, draw_on_load calls update. If nothing is set, behavior is unchanged
- BuildInfo: build version reading. load(engine) of BuildInfo::new(env!("CARGO_PKG_VERSION")) first reads the page's on the web, and if absent requests version.json relative to the page without cache (cache: "no-cache" of fetch). On desktop it reads version.json in the asset folder. read_text() returns the meta text, "date time (hash)" from version.json (version if there is no hash), or the version embedded at build time if neither exists. is_finished, get_load_handle (handed to a scene or AssetLoader), read_version_data, set_meta_name, set_version_json_path, BuildInfo::compose_text. meta and disabling cache exist only in browsers, so desktop does not do them. Shows the version in example loadingshowcase
- ToonScreenOutline, ToonOutlineWidthUnit, ToonLineDrawOptions: toon screen-space outline. (Same features as vanilla.js ToonScreenOutline, the shader outlines that Exoplanet Miner and Aberrant wrote separately) Draws ToonRenderer models once more with the same matrices to write normals, line ids, and depth into a line buffer (begin_line_ids, draw_mesh, draw_mesh_instanced, end_line_ids), writes a mask, then blends with draw_outline. Part ids are given with index_start, index_count, and per-instance ids with line_id_list of draw_mesh_instanced. Width in world length or pixels (set_width, set_focus_distance), orthographic and perspective are told apart by the projection matrix, and depth is linearized to meters for perspective. set_depth_threshold, set_crease, set_resolution_scale, set_sample_count, set_color, set_hdr_output
- ToonMesh: get_body, get_instance_buffer, which read the body vertex array and instance buffer within the crate. (For when the screen-space outline draws the same model)
- ToonVfx and ToonParticleOptions, ToonFireballOptions, ToonShockwaveOptions, ToonDecalOptions, ToonPlumeOptions, ToonBeamOptions, ToonRibbonOptions, ToonLightningOptions, ToonGlintOptions, ToonVfxRange, ToonVfxSlot, ToonVfxLook, ToonVfxShape, ToonVfxDecalMode, ToonVfxCounts: base for toon 3D GPU effects. (Same features and shaders as vanilla.js ToonVfx, the general-purpose parts of Exoplanet Miner and Aberrant; effect recipes and ramp colors belong to the games) An atlas built in code, instanced GPU particles (emit_particles), fireballs (add_fireball), shockwaves (add_shockwave), floor marks (add_decal, queue_decal), smoke plumes (add_plume), lathe beams (queue_beam), ribbons (queue_ribbon) and lightning (queue_lightning), glints (queue_glint), an internal clock advanced by update, a particle cap (new, set_particle_capacity) and an emission count ratio (set_count_ratio), ramp colors (set_ramps, rows of [r, g, b] in 0 ~ 1), a floor height callback (set_floor_height_reader). Takes values through per-effect structs with defaults
- Window stacking and screen frames that shipped games (Exoplanet Miner, Aberrant, Doomsday Survival, Space Creature) built separately are moved into the engine. (The same features added to vanilla.js; panel looks, themes, presentation, and release platform code are not brought over)
- UIWindowLayer: window stacking component. UIWindowLayer::create(node_tree, parent_id) creates the layer node, and open_window(tree, window_id) stacks a window on top. Only the top window is visible. close_window removes it from the list immediately and deletes the window node after the PopupMotion close motion finishes (covered windows immediately). close_all_windows, close_top_window (back navigation, does not close windows with outside close disabled), get_top_window, find_window, has_open_window, get_window_count, set_window_change_event (notification receiving the number of open windows). The layer scales by UIScale::read (set_view_size takes the CSS pixel scale, set_ui_scale_options(None) for no scaling, get_ui_scale) and tells windows the area size divided by that and the safe area width (set_view_bleed). open_window_in_tree
- UIWindow, UIWindowBehavior, UIWindowDefaultBehavior, UIWindowParts, UIWindowEvent: a single window. Shows a panel (a single Paint) centered over a dim (which swallows presses) covering the area and the safe area. The panel widens to the area width but not beyond set_maximum_width (default 480), its height comes from layout_content (default set_panel_height), and if larger than the area the whole panel is scaled down. Pressing outside closes it (set_outside_close_enabled). close_in_tree, set_close_event, refresh_layout_in_tree. The methods that the original's subclasses override (build, layout_content, layout_panel, apply_motion, set_covered, handle_wheel, handle_closed, dispose) are the UIWindowBehavior trait and are taken out with get_behavior_mut. Games change the panel look by attaching decorations to the frame (get_frame_node) in build. The wheel goes first to the scroll view at that position, then to the window, which always swallows it
- UIConfirmWindow, UIConfirmWindowOptions: confirmation window (UIWindowBehavior). Title, message, and two buttons, cancel and confirm. When the text exceeds the area height, only the text area scrolls. The line count is known only after drawing, so it is first laid out as one line and laid out again on the next tick. With set_right_to_left(true), the button order is reversed. Confirm closes after set_confirm_event, and closing via the cancel button, an outside press or the window layer calls set_cancel_event. confirm_in_tree, set_title, set_message. (UIDialog is left as is)
- UIScale, UIScaleOptions: scale that enlarges only the UI layer when one view unit is smaller than minimum_css_scale (0.8) CSS pixels. (1 to maximum_scale 1.8, short screens are not enlarged below minimum_layer_height (not checked when it is 0, the default), portrait screens (width at most portrait_ratio 1.1 times the height) have no upper limit) UIScale::read(view_width, view_height, css_pixel_scale, &options), is_portrait
- Text: get_measured_line_count(). The line count from the last wrap after drawing, while the text, font and wrap width are unchanged. (For layouts without a Graphic to read the drawn result)
- GameSceneBase: fade_screen(on_dark), ScreenFadeHold, ScreenFadeEvent. Calls on_dark(tree, engine) when fully dark, and if it returns a ScreenFadeHold, stays dark until release (in place of the original Promise). false if already fading. set_screen_fade_color (default black), set_screen_fade_seconds (default 0.35), is_screen_fading, get_screen_fade_alpha. The overlay is drawn by post_draw (newly added, called from the scene's post_draw) over the whole canvas including the safe area, and moves with unscaled time. While the overlay is up, presses and wheel are blocked and only the move, release and cancel of fingers already pressing are passed
- GameSceneBase: is_user_interface_at(view_position), set_play_input_enabled, take_play_inputs, PlayInput (Press, Move, Release, Wheel), convert_view_to_play_area. Collects 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. (The original uses a handler object; the Rust version uses a queue because a handler cannot borrow the scene state)
- GameSceneBase: set_play_area_reference(fixed_length, is_landscape, engine), apply_play_area_reference(engine), calculate_play_area_reference_length. Extends the reference resolution so that the fixed-side length of the play area excluding the safe area is always fixed_length. initialize applies it by itself, and since resize cannot modify the engine, the scene calls apply_play_area_reference at the start of resize
- ViewManager: set_ignored_safe_area_sides(&[SafeAreaSide]), get_ignored_safe_area_sides, SafeAreaSide. get_safe_area_insets returns 0 for those sides
- TouchRecognizer: is_touching()
- GameSceneBase behavior change: when not set with set_safe_area_insets, compute_safe_area_rect reads ViewManager::get_safe_area_insets instead of measuring the platform env separately. Until now, set_safe_area_override, the URL's ?safeArea=, and (new) ignored sides did not reach the GameSceneBase safe area. Web env values are the same except that they are no longer truncated to integers, and desktop stays 0. read_platform_safe_area_insets and parse_leading_integer, which measured separately, are no longer used and were removed
- The text, node convenience, and drawing features and optimizations that the shipped games built and used separately are added to the engine defaults. (The same features added to vanilla.js together; the games' screen looks and presentation were not brought over)
- Text, UILabel: set_fit_width(width, minimum_ratio), get_fit_width, get_fit_minimum_ratio, get_fitted_font_size, calculate_fitted_font_size. 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 stays the same; if it still overflows at the minimum ratio, it is drawn overflowing, and the text rectangle for off-screen culling follows the width of the shrunk text. Wrapping text and rich text are not fitted. The shrunk size is measured when splitting lines, so a Graphic is needed to know it
- Text: set_letter_spacing, get_letter_spacing (same names on UILabel and RichText). 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, and wrapping, fit width, alignment and underline measure with that width. Positions are set by measuring the previous/next pair, so pair kerning is kept. Right-to-left text does not use the spacing. Same as the original's setLetterSpacing
- Engine::open_url(url): opens an outside URL. Desktop uses the OS default program (macOS open, Windows ShellExecuteW, Linux xdg-open); the web uses window.open(url, "_blank", "noopener") in a new tab. On the web it opens only when called inside user input (click, tap, key) handling (the browser's popup-blocking rule). Only http, https, mailto and tel are opened; other forms return false. Same as the original's Engine.openUrl
- Engine::read_local_time(minute_offset: f64) -> LocalTime: returns the calendar time of now plus a minute offset in this machine's time zone (LocalTime { year, month 1 to 12, day, hour, minute, second, weekday with 0 as Sunday }). It reads with Date on the web, localtime_r on Mac and Linux, and SystemTimeToTzSpecificLocalTime on Windows, and applies daylight saving time at the shifted moment (same as the original's new Date(Date.now() + offset)). Same as the original Engine.readLocalTime
- UIView: set_backdrop_blur(blur_radius), get_backdrop_blur. Backdrop blur (same meaning as CSS backdrop-filter: blur() and Unreal UMG BackgroundBlur, initially 0 meaning off). The argument is the standard deviation, the same as the N of CSS blur(Npx) (node coordinate units, device pixels on screen after the transform scale). It blurs with the new ScreenEffectType::GaussianBlur (separable Gaussian, up to 3 sigma, linear sampling, edges folded as a mirror). Pixel-identical to the original engine (standard deviations 3, 8, 20, 40, max difference 1) and equal to Chrome CSS. Off leaves the screen byte for byte
- UIView: set_backdrop_corner_radius(corner_radius), get_backdrop_corner_radius. Rounded corners of the backdrop blur and background color (CSS border-radius). Initially 0 (rectangle). Same as the original's setBackdropCornerRadius
- Screen capture: giving 0 to VANILLA_CAPTURE_FRAMES or the web capture query is treated as the first frame (1). (Frame numbers start at 1 so 0 never came, and the capture never finished)
- ScreenEffectType::GaussianBlur: standard-deviation Gaussian blur (parameters = [standard deviation in pixels], same meaning as CSS filter: blur()). The existing Blur stays as it is
- SpriteAnimator: also moves a ShaderSprite on the same node (in the original, ShaderSprite inherits Sprite so it also moves the ShaderSprite on the same node). play, tick and find_sprite use ShaderSprite when there is no Sprite
- Text, UILabel: measure_text(graphic, text, font_size). Graphic: measure_text_with_font_string(font_string, text)
- TextStringTextureCache: text measurement (measure_text) does not re-measure when the font string and text are the same. (2048 entries, the least recently used half is discarded when exceeded, cleared when a new font is registered) get_measure_count
- UILabel.set_text: skipped if the text is the same. (When not in rich text mode) Text.set_text already skipped the same text. Colors are Copy, so no separate same-color skip was added
- Graphic: set_text_bake_motion_scale_step, get_text_bake_motion_scale_step (default 0.25), set_text_bake_scale_moving, is_text_bake_scale_moving, update_text_bake_scale_moving. When the text bake scale step is 0 and the transform scale of the drawn node differs from the previous frame (ButtonMotion, PopupMotion, tweens), text is baked at a scale quantized to this step, and rebaked at the exact scale when it stops. A node drawn for the first time is treated as not moving. When the step is not 0 (default), nothing is computed. NodeTree decides it per node, and ShadowText and ShadowImage use the same scale too. WorldNode: set_last_drawn_maximum_scale, get_last_drawn_maximum_scale
- ShadowText, ShadowImage, SoftShade: baked images with the same shape are shared per key. (acquire_shared_bake, read_shared_bake_count in core/sharedbakecache.rs) The Rc held by each component serves as the reference count, and ones no longer used by anyone are kept up to 128 and evicted least recently used first when new ones are added. ShadowImage uses the image's instance identifier and piece as the key
- NodeTransform, WorldNode: set_local_position_xy, set_local_scale_xy, set_content_size_xy, set_rect(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 stays as is). NodeTree: convert_view_to_local(node_id, view_position) (same calculation as convert_view_position_to_node_position, original name)
- Localization: mirror_layout_x(x, width, parent_width), read_layout_text_align(text_align). For right-to-left languages, flips the horizontal layout position and the left and right of alignment
- Wheel: if the frontmost in draw order among those covering that position is a wheel receiver (Component::is_wheel_receiver, true for UIScrollView and UISnapScrollView), that receiver takes it. If the frontmost is a pressable node, it asks from that node toward its parents as before. (NodeTree::find_wheel_target_node, dispatch_wheel_at) Used by SceneBase.tick_touch and TouchRecognizer (GameSceneBase). Whether something took it is SceneBase::is_wheel_handled, TouchRecognizer::is_wheel_handled, GameSceneBase::is_wheel_handled (using the wheel for the game's map zoom etc. only when false does not conflict with window scrolling)
- Graphic: draw_ring(center, inner_radius, outer_radius, start_radian, end_radian) (set_fill_color), draw_arc(center, radius, start_radian, end_radian, line_width) (set_stroke_color), draw_ring_with_color. 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 draw_circle (16 to 64 per full turn), in proportion to the drawn angle. Angle 0 is right, clockwise
- Graphic: draw_line_segments(position_values, size). Draws multiple line segments at once from one number array (x0, y0, x1, y1 per segment). When the vertex buffer fills, draws up to there and continues filling
- SpriteAtlas: reads the JSON from tools/atlas.cjs (vanilla.js) and the { pagePaths, frames } form. load(engine, json_path), load_data, update (on the web, requests page images after the JSON arrives), is_loaded, track_json_asset, read_frame, has_frame, apply_frame, get_page_count, get_frame_names, and find_frame_in_order, apply_frame_in_order, which search multiple atlases in order. Names are also found with the extension removed. Sprite.set_frame(frame)
- GamepadManager.vibrate: also vibrates on macOS desktop. (gilrs's macOS force feedback is empty, so until now it did nothing) The platform layer platform/desktop/gamepadhaptics.rs builds CoreHaptics engines via GCController.haptics of GameController, and outputs continuous vibration with the heavy motor on the left handle engine and the light motor on the right handle engine. (Pads that do not provide both use one engine at the larger magnitude) gilrs pads are paired with controllers of the same name (vendorName) first, and the rest in order. Engines are built once per controller, restarted after stop and reset, and rebuilt on failure. On macOS, a length or magnitude of 0 stops the previous vibration. Added a pad vibration test (A, B, X, Y) to example inputgallery, and it does not end by itself when a real pad is connected. Dependencies: objc2-game-controller, objc2-core-haptics, objc2, objc2-foundation, block2 (macOS only)
- Made ParticleSystem the same as the original. Defaults (max 512 particles, speed 60, size 6, cone half-angle 0.5 radians, set_cone_angle is a half-angle like the original), cone emits within the radius, box emits upward only. Random number order and computation match the original, so the same seed gives the same particle positions as the original. (Difference below 0.0002 px across five shapes) The emission origin is the component coordinate origin (top-left of the content area) like the original, simulate(time_delta), emit(count, Option origin offset). Renamed EmitterShape to ParticleEmitterShape and Rectangle to Box. Like the original, it stays playing after duration passes, and is_finished reports the end. get_particle_position_list. Particles beyond the vertex limit are also all drawn in parts. (The public API changes)
- HeatHazeEffect: draws in parts without the row limit (1365). (The original is now the same effect component too)
- ScreenEffect.set_timeline_property takes &TimelineValue. (Numbers, strings and booleans like the original; booleans as numbers 1 and 0) TimelinePropertyTarget also passes values without converting them to text. (The public API changes)
- HumanSkinRenderer: ported the original humanskinrenderer.js. One shader split into shading modes for skin (wrinkle maps, micro normals, height detail, dual-lobe GGX, vellus hair), eyes (cornea refraction parallax, iris, limbus), hair (Kajiya-Kay anisotropy, sway, cutout and fringe 2 passes), occlusion, and fluids. The GLSL is the same as the original. Outputs irradiance, albedo, specular and normal to 4 MRT targets, and has a cutout depth pass. Wraps SkinnedModelRenderer and calls the base functions as is through Deref
- ToonView3D: like the original, takes a draw function and a fallback draw function (set_draw_callback, set_fallback_draw_callback, closures), and multiple nodes share one renderer with set_renderer, get_renderer. (Rc<RefCell
>) Taken out with get_component_mut:: () without a type parameter. Removed ToonViewDrawer, ToonViewPass. (The public API changes) - Graphic::run_external_pass: a drop guard restores the 2D state even if pass panics
- ToonRenderer, SkinnedModelRenderer, HumanSkinRenderer: bind a 1x1 comparison depth texture to the shadow unit when not receiving shadows. (This was the cause of the Mac driver's "UNSUPPORTED (log once) ... sampler type (Depth)" notice; the order of filling uniforms was not the cause) SkinnedModelRenderer::get_empty_shadow_texture
- ToonRenderer: set_shadow takes (ShadowMap or None, strength) like the original. destroy, get_solid_program, get_outline_program, get_depth_program, extract_frustum_planes
- ToonVfx: rim for light particles and light dots, glow bleed color for ribbons and lightning, set_rim_color, lightning that re-bends over its life add_lightning, screen flash add_flash (ToonFlashOptions), camera shake computed with the engine Shaker add_shake, read_shake, is_shaking. set_ramps takes both "#rrggbb" text and [r, g, b] (ToonRampColor). queue_lightning does not draw when count is 0. seed is Option. Shown in example toonfx
- SkinnedModel: reads default morph weights from glTF node weights. destroy of screen-space effects also deletes the fullscreen pass. ToonScreenOutline: get_line_target (ToonLineTarget), read_outline_radius
- Camera2D: rotation (set_rotation, get_rotation, degrees). apply_transform, screen_to_world, world_to_screen, pan_by_screen, fling, zoom_at follow the rotation, and the bounds clamp is measured with the box enclosing the rotated view (get_visible_half_extent). convert_screen_delta_to_world, begin, end
- Action: callbacks of condition steps are ActionConditionCallbacks. (updated receives only the target, like the original) repeat 0 times does not run
- Pane, PaneStyle, PaneTheme (original web/pane.js): DOM split panels. Exists only in web (wasm32) builds. Lays out child panels horizontally or vertically, resized by dragging the resizers between them. Size is PaneSize (Flex, Fixed pixels, Ratio), minimum and maximum size, whether resizable and which edges (PaneResizableEdges), set_visible (hiding also removes its space and the adjacent resizer), reset_layout, refresh, attach_to, set_callback. PaneStyle::create creates elements with the original presets (toolbar, panel, button, input, textarea, text), and style names are CSS names (background-color). PaneTheme is associated constants of the form PaneTheme::COLOR_BACKGROUND
- DevTools: ported the original F2 developer tools. A panel docked to the bottom right in logical coordinates inside the window, dragging to move and resizing by edges, corners and dividers, four tabs (Statistics, Node Hierarchy, Local Storage, Settings), tree (expand, active and gizmo columns, selection, scrolling), inspector, settings saving ("hierarchy.settings"), screen ratio guides, forcing all gizmos visible. The scene calls tick(engine, node_tree, time_delta) in tick and draw(engine, node_tree, graphic) in post_draw. Component properties in the inspector are the keys and values UIDocument saves, and local storage input on desktop is an input box inside the panel. (On the web, window.prompt, window.confirm like the original)
- UIDocument: serialize_component(node_tree, root_id, component). One registered component to document data (None without a warning for unregistered types)
- UI branch: removes UI feature differences with vanilla.js. (What was not in the original was also added to vanilla.js)
- Ported UINode (original ui/uinode.js), auto layout (ui/autolayout: LayoutSolver, LayoutVariable, LayoutExpression, LayoutConstraint, LayoutStrength, LayoutPriority, LayoutRelation, LayoutConstraintAxis, LayoutError, the original's Kiwi-based solver, 12 files), and UIScene (original ui/uiscene.js). UINode is a component attached to a node, and moves solver values into the node's position (relative to the top-left of the parent UINode) and content_size. The intrinsic content size gathers Component::get_intrinsic_content_size (Text, RichText, UILabel), and constraints are reapplied by itself when it changes. Where the solver throws exceptions, it is Result<(), LayoutError>
- UIScene trait, UISceneBase, and the ui_scene! macro: the solver, screen guide (screen_node), safe area guide (safe_area_layout_guide), and every tick it attaches the solver to the tree's UINodes, solves, and moves the results to the nodes. The common frame (loading, touch, developer tools) wraps GameSceneBase
- GameScene trait and game_scene! macro: the form of subclassing and overriding the original GameScene. Calls the base first, then the scene's functions of the same name (load_assets, initialize, layout, tick, pre_draw, draw, post_draw). layout is called by the base on resize and view size changes, and the fade overlay and developer tools of post_draw are drawn by the base. Calling GameSceneBase functions directly still works
- GameSceneBase: resize reapplies the play area reference (apply_play_area_reference) by itself. (The scene does not need to call it, resize takes &Engine) tick takes &Engine
- GameSceneBase: set_play_input_handler(Box<dyn FnMut(PlayInput)>) receives input not taken by the UI through a handler, like the original. (Can be used together with collection via set_play_input_enabled, take_play_inputs) fade_screen_with_hold(on_dark) is a callback form where on_dark receives the hold, keeps it and releases it later. (In place of the original Promise resolve) get_loading_drawer, draw_screen_fade, get_dev_tools, get_dev_tools_mut
- GameSceneBase: if EngineConfiguration::use_dev_tools (default true), creates DevTools in initialize, tick passes to it and post_draw draws it. Input over the panel is not passed to the UI or play. (is_dev_tools_capturing_input takes the engine)
- GameSceneBase: when the wheel points inside the window layer (UIWindowLayer), the top window takes it first like the original, and if not taken, the scroll view at that position takes it. (UIWindowLayer::scroll_window_at, find_scroll_view_at, find_window_layer_of) TouchRecognizer: split into tick_wheel, tick_pointer, mark_wheel_handled. (tick_touch is unchanged)
- UIWindowLayer: instead of deleting window nodes whose close motion has finished, detaches them from the layer, so the same window can be shown again with open_window like the original. (Attaches it if it is not a child of the layer)
- UIWindow: handle_wheel(node_tree, view_input_position, wheel_delta), UIWindowBehavior::handle_wheel receive the position like the original. get_panel_paint(_mut), get_dim_paint(_mut), get_view_width, get_view_height, get_margin, get_panel_height, get_panel_rect, get_panel_scale
- UIConfirmWindow: measures the line count of the message without Graphic, from the first layout. (textstringtexturecache::measure_text_without_graphic, which measures with registered fonts, Text::wrap_lines_without_graphic, wrap_text_to_lines_by) set_button_texts, refresh_if_open_in_tree, set_title_in_tree, set_message_in_tree
- Text: changing the font size, name, bold or italic also updates the font string used to draw single-line text right away. (Until now, without a fit width or underline, it drew at the initial 32px)
- UIListView: set_template_node(node_tree, template_id) serializes the template into a UIDocument and clones it, like the original. For game components, pass the UIDocument in which they are registered to set_template_node_with_document
- UILabel: set_visible_character_count, get_visible_character_count. UIProgressRing::get_perimeter_points. attach_button_motion, attach_toast_motion
- UIInputField: renamed set_use_dominput, is_using_dominput to set_use_dom_input, is_using_dom_input following Rust naming rules (original setUseDOMInput)
- Aligned text and fonts with the original (vanilla.js, browser Canvas2D):
- Text shaping (core/textshaping.rs): with bidirectional ordering (unicode-bidi) and glyph shaping (rustybuzz), draws right-to-left text (Arabic joining, Hebrew), mixed text, ligatures, kerning and combining marks like the browser. All text goes through this path
- Text direction: Graphic.set_text_direction, get_text_direction, resolve_text_direction, TextDirection(Inherit, Ltr, Rtl, Auto), detect_text_direction. resolve_text_align(text_align, text_direction) takes the direction like the original. (This changes the public API) The key of baked text includes the paragraph direction. set_text_direction, get_text_direction of Text, RichText, UILabel, ShadowText. RichText places segments from the right in a right-to-left paragraph
- Font faces: registers multiple faces with different weight, style and character range (unicode-range) under one name. (TextStringTextureCache.register_font_face, unregister_font_face, set_font_face_order, clear, FontFaceDescriptors, Engine.register_font_face_when_loaded, unregister_font_face, set_font_face_order, clear_text_cache, FontAsset.load_font_with_descriptors, unload) Selection follows CSS order (style, weight), and faces registered later come first. Reads numeric weights (500 etc.) in the font string
- Synthetic italic uses the same slant of 1/4 as Chromium (previously 0.2), and synthetic bold the same thickness as Skia (1/24 of the size at 9px or below, 1/32 at 36px or above), applied per glyph. Italic and bold faces are used when present. The web default_font_url font is registered only at normal weight, so bold text becomes synthetic bold. (Same as the original)
- Registering a face discards only the baked text within that name and character range. (original invalidateFontFaces) ShadowText also rebakes when a font is registered
- Fallback fonts: on desktop, when a character not in any registered font appears, loads and uses the system fonts in EngineConfiguration.fallback_font_paths from the front. (In place of the original browser's system font fallback) On the web, characters not in the registered fonts are drawn as browser system font pieces. Combining marks are drawn with a face that has the whole cluster
- On the web, ShadowText and DynamicFont bake with the browser system font even without font bytes. (Previously drew without the shadow)
- Added actual_bounding_box_left, right, ascent, descent to TextMetrics
- Line wrapping (Text.wrap_text_to_lines): splits at spaces, between words (CJK and Thai without spaces), then grapheme clusters, in the same order as the original. Words use ICU4X (icu_segmenter) on desktop and the browser Intl.Segmenter on the web like the original. A run of Hangul is its own word, as in the browser. split_graphemes, split_words, segment_words, count_graphemes, find_grapheme_prefix_length, wrap_text_to_lines_with (takes a measuring function)
- Visible character count (set_visible_character_count) and Typewriter count in grapheme clusters. (Emoji sequences and combining marks are not split) Typewriter's character reveal notification receives (&str, index). (This changes the public API) Added set_visible_character_count, get_visible_character_count to UILabel
- Text: measure_wrapped_size(TextWrappedSize), calculate_intrinsic_content_size, calculate_text_bounds (original measureWrappedSize, getIntrinsicContentSize, calculateTextBounds)
- ShadowText: get_font_family, get_font_size, is_bold
- DynamicFont, GlyphInfo (misc/dynamicfont.rs, original misc/dynamicfont.js): bakes characters together into a single atlas and draws them as cut-out pieces. build_atlas, rebuild_atlas, draw_text, measure_text, get_glyph, clear_atlas
- uifont (misc/uifont.rs, original misc/uifont.js): registers font subsets for multiple scripts under one name with their character ranges, places the selected language's group right before Latin, and downloads only the subsets for characters to be used. load_ui_font, update, apply_ui_font_group, load_ui_font_text, request_ui_font_text, is_ui_font_ready, read_ui_font_face, build_ui_font_string, configure_ui_font(UiFontOptions), read_ui_font_family
- languagepack (misc/languagepack.rs, original misc/languagepack.js): language list and language tables as asset JSON. load_language_list, load_language, apply_language_setting, update, is_loading, match_language_tag, resolve_language_code, translate, format_text, read_text_direction, isolate_text, mirror_layout_x, read_layout_text_align, read_all_texts, set_language_paths, set_document_title_key (tab title and html lang on the web, window title on desktop), set_language_loaded_handler, set_language_list_from_json, set_language_texts_from_json
- Color::from_cache: instead of clearing everything beyond 1024 entries, discards the least recently used first, like the original. get_cached_color_count
- Localization: treats the whitespace around the slash in named placeholder groups as any whitespace character, like the original
- New dependencies: rustybuzz, unicode-bidi, unicode-segmentation, icu_segmenter (desktop). The web wasm grew (uigallery after wasm-bindgen 1.14 MB → 1.93 MB, gzip 0.40 MB → 0.68 MB)
- Aligned core, platform and foundation with vanilla.js. (What the original had and the Rust version lacked, and what was ported differently. General-purpose features that existed only in the Rust version were also added to vanilla.js)
- Changed SoundSystem to the original usage. (This changes the public API) SoundSystem::new(engine, sound_table), update(), play_effect(sound_id, volume, pan), play_music(sound_id, fade_seconds, is_resumed) do not take the engine and time. Music and effect volumes follow with a 0.05 second time constant like the original, the same-sound interval and re-waking are counted on the wall clock, and fade-outs and the paused position of music on the AudioContext clock. Calling fade_out_effects again on effects that are fading out starts a new fade from the current volume and removes them from the list. (They are not counted by stop_effects or the voice limit) Background music is not played if its first file failed to load. Added load_sound, get_external_mute_provider, get_autoplay_allowed_provider (providers are Rc<dyn Fn() -> bool>), get_audio_manager, and the shared sound set_sound_system, read_sound_system. Removed set_page_hidden and fade_out_music, which existed only in the Rust version. (Same via engine page events and play_music("", seconds))
- AudioManager: Clone (a handle to the same AudioContext), get_context_time, get_audio_context, is_context_running made public. AudioPlayer: get_audio_context. get_audio_context_time in the audio backend
- math: original names floor, ceil, sqrt, abs, sin, cos, tan, asin, acos, pow. round leaves infinity as is like the original. (Previously NaN)
- Color: to_rgba_string, to_hex_string (appends alpha only when it is below 1 like the original, renamed the Rust version's to_hexstring to the original name), from_hex_cached. Version: get/set accessors, get_version_string. TransformMatrix: copy_from, renamed write_to_array to the original name write_to_float32_array
- The desktop render pixel ratio cap actually takes effect. Draws at the reduced size in the bottom left of the default framebuffer and stretches it to the window size at the end of the frame. (platform/desktop/renderscaler.rs) Changing the cap readjusts on the next frame
- EngineConfiguration: auto_resize_on_window_resize (web, when off the page's canvas size, on by default in the Rust version), preserve_drawing_buffer (web context), ignore_virtual_keyboard_resize (web on-screen keyboard), max_canvas_aspect_ratio (on the web shrinks the canvas and centers it like the original, on desktop draws in the center of the window and leaves the rest black). The web uses the visualViewport size
- Desktop page events: combines window occlusion, minimization (size 0, is_minimized) and app suspension to emit Hidden and Visible (+ on_page_visibility_restored). (Windows reports it as minimization) On waking from system sleep (the wall clock advanced more than 2 seconds beyond the monotonic clock), on_page_process_restored
- On desktop, page query values are environment variables in upper snake case after VANILLA_. (VANILLA_SAFE_AREA=44,0,34,0, VANILLA_QUALITY=lite) Input coordinates are converted with the window's scale factor. (Independent of the render size)
- ViewManager: convert_client_to_view, get_client_native_size. read_canvas_client_position, read_client_native_size, save_capture_file in the platform layer
- Input: like the original, any mouse button is touch at first, and set_touch_from_left_button_only limits it to the left, set_context_menu_prevented (web right-click menu), find_touch_point, is_touch_button. touch_moved is set on press and cleared on release like the original. (Previously cleared every frame) Scene and TouchRecognizer check the release first in the original tickTouch order, and do not pass Moved on the press frame. When the window loses focus, it is passed as a release. On desktop, leaving the window does not break a drag
- Scene: finalize, unload hooks (on unload, in the order finalize, unload, destroy), scene touch hooks touch_press, touch_move, touch_release, touch_cancel, touch_wheel (the engine calls them after tick in the original order). Engine.unload_scene also accepts &SceneBase
- Engine: the first frame number is 1 like the original, request_frame_capture (passes PNG bytes, FrameCaptureHandler), web screen capture set with the URL query capture, captureName, captureExit and saved as downloads like the original, remove_page_event_listener, resize, get_canvas, is_text_input_focused, request_asset_bytes_with_cache
- Nodes: from the original Node, set_parent, remove_child, remove_child_at, remove_children, remove_child_by_name (only detaches, does not destroy), find_child, find_child_recursive, find_child_recursive_by_name, is_root, is_leaf, has_parent, has_child, get_child. From the original TransformNode, global get/set_position, get/set_scale, get/set_rotation, get_opacity (NodeTree). get_or_add_component, get_components. Component.require (RequiredComponent, attached with default values if missing before attaching), detach (called by remove_component)
- AssetLoader: decodes downloaded images to check them like the original, and puts broken ones in the failure list. Decoded images are kept in the handle (AssetLoadHandle.get_decoded_image), so ImageAsset does not decode them again
- TextAsset, JsonAsset: set_no_cache, is_no_cache (cache: no-cache of web fetch). FontAsset: load_font_from_bytes, load_font_from_bytes_with_descriptors (original loadFontFromBytes, font face descriptors as is)
- SpriteAtlas: search atlas list add_search_atlas, remove_search_atlas, clear_search_atlases, find_frame, apply_search_frame (Rc<RefCell
>), get_page_images - BuildInfo: new() and set_version_json_path, is_loaded (false before load), read_meta_text is an instance function, the build-time version via set_package_version. (This changes BuildInfo::new(version))
- PointerCursor: get_button_cursor_name, get_default_cursor_name, is_coarse_pointer. FrameProbe: functions returning the settings. Platform: is_coarse_pointer, get_safe_area_rect, get_resouce_usage (original name as is). Identifier (original sequential number, reset goes back to the initial number, a bug where the original did nothing)
- Localization.text_named: accepts tabs and line breaks too as whitespace around the slash, like \s in the original regular expression. WebSocketClient.disconnect: only requests the close like the original and treats it as disconnected on the next tick
- Added finalize, unload, on_page_process_restored, on_page_visibility_restored and the scene touch hooks (touch_press, touch_move, touch_release, touch_cancel, touch_wheel) to the GameScene, UIScene traits, and game_scene!, ui_scene! forward them to the same functions of Scene. (What subclasses of the original GameScene, UIScene overrode)
- Callback getters (original names): UIButton.get_click_event, get_pressed_event, get_released_event, get_clicked_event, get_hover_event, UISlider.get_value_changed_event, UIToggleButton.get_toggled_event, ButtonMotion.get_lit_handler. The given callback is stored in an Rc
, and the getter returns that Rc. The caller borrows it with borrow_mut and calls it. (The set side still takes a Box) The engine also holds another clone of that Rc when calling, so a callback may set a new event, and calling the same event again while it is being called is skipped. GameSceneBase.get_loading_drawer (previously an uncallable &Box) and WebSocketClient.get_receive_event (previously a &mut from &mut self) were changed to the same form - AudioBus (added to the original in the same shape): AudioManager.create_audio_bus, AudioBus.create_audio_player (a player that plays through that bus), set_volume, get_volume, mute, unmute, is_muted, is_available, get_gain_node (web only). On desktop it is a sub-track under the kira main track (tracks of players created from the bus go under it), on the web a GainNode connected to the output. Volume and mute follow the same rules as AudioPlayer
- LocalStorage.get_backend, PersistedStore.get_storage_backend (original getBackend, getStorageBackend): return the swapped-in storage as Rc<RefCell<Box
>>. In exchange, has_backend, has_storage_backend above were removed. (Check with get_backend().is_some()) Calling LocalStorage while the retrieved storage is borrowed uses the default storage - SafeAreaInsets { top, right, bottom, left } (the original's insets object): ViewManager.set_safe_area_override, get_safe_area_insets, GameSceneBase.set_safe_area_insets, calculate_safe_area_rect take and return this instead of a [top, right, bottom, left] array. GameSceneBase.calculate_play_area_reference_length(fixed_length, is_landscape, canvas_native_size, safe_area_insets, inset_scale) takes insets in view coordinates and the canvas unit scale like the original. (Previously an inset array with the scale already multiplied in)
- Changed the default of EngineConfiguration.auto_resize_on_window_resize to off like the original. Turn it on to fit the canvas to the window on the web. (The examples and README turn it on, desktop always fits)
- Platform.get_resource_usage: added the correct name. The old name get_resouce_usage remains as an alias that calls the same function. (getResourceUsage was also added to the original)
- Color: From<&str> goes through from_cache like parseColorValue of the original Graphic. from_hex_cached, like from_cache, also discards the least recently used entries beyond 1024. (Previously cleared everything at 1024, the same rule was added to the original fromHEXCached) Both caches find the least recently used entry directly without scanning
- UIToggleButton.get_clicked_event: returns the toggle button's internal click handler like the original (getClickedEvent inherited from UIButton). Calling it flips the on state and calls the toggled event and the clicked event
- Web: toon 3D restores the previous GL state like the original. The glow web context panics when reading a binding while nothing is bound (null), so until now the web did not read the previous framebuffer and restored to the default framebuffer. The web platform layer also holds the WebGL2 context and checks for null first (platform::is_gl_binding_present), reading with glow only when something is bound. (read_framebuffer_binding, read_texture_binding, read_program_binding, read_vertex_array_binding of core::graphic, re-exported by graphics3d)
- end_shadow_pass of ToonRenderer and end_line_ids, draw_outline of ToonScreenOutline restore the previous framebuffer on the web too. The restriction that the shadow pass had to come before ToonPostProcess.begin on the web is gone. ToonScreenOutline also restores the previous texture after building the line buffer
- ToonRenderer, ToonScreenOutline, ToonVfx restore the previous shader program and vertex array like the original. (Until now even desktop left them unbound)
- Fixed the panic, for the same reason, when Graphic read back the pixels it placed from a texture (ShadowImage) while the default framebuffer was bound on the web
- Example toonshowcase: draws the shadow pass after binding the HDR target (ToonPostProcess.begin). Shows end_shadow_pass returning to the HDR target the same way on desktop and web
- ToonInstance.line_id: per-instance screen-space outline id. (original instances[i].lineId, None uses the common id, ToonRenderer does not read it) ToonInstance::default() (identity matrix, white tint, no id). Removed the line_id_list argument of ToonScreenOutline::draw_mesh_instanced. (This changes the public API, same usage as the original) Code that builds ToonInstance as a struct literal gives line_id or appends ..ToonInstance::default(). Updated the examples toonfx, toonshowcase, toonview
- Color emoji: bakes a font's color glyphs in their own colors. (core/colorglyph.rs, until now desktop showed them in black and white or blank because fontdue cannot draw color glyphs) Like the original (browser Canvas2D), bakes them in their own colors among white glyphs, and the text color is multiplied in when drawing
- Bitmaps: PNG and premultiplied BGRA from sbix (Apple Color Emoji) and CBDT/CBLC (Noto Color Emoji bitmap version). Among the strikes that have the glyph, picks the smallest one at or above the font size and downscales it with area averaging. (Apple Color Emoji has glyphs missing in some strikes)
- Outlines: COLR/CPAL v0 and v1. Receives them through ttf-parser's Painter and paints them directly with an area accumulation rasterizer, solid, linear, two-circle radial and sweep gradients (Pad, Repeat, Reflect), transforms, clips and 28 composite modes. Like Chrome, does not draw OT-SVG
- Same as Chrome: synthetic italic is applied to color glyphs too, synthetic bold is not. When baking as an outline (Stroke), color glyphs are placed in their colors without a border. ShadowText multiplies emoji only by the alpha of the text color, and the shadow follows the emoji shape too. The DynamicFont atlas also bakes color glyphs in their own colors. (Confirmed with Chrome Canvas2D on Mac)
- Face selection: emoji presentation sequences (VS16 FE0F, Emoji_Presentation, skin tones, flags, keycaps, tags, ZWJ sequences) prefer a face with color glyphs, and others (bare ❤, VS15) prefer a non-color face. Chrome too, when the specified font has a monochrome ❤, draws ❤️ with the color emoji font and bare ❤ with that font. On the web, if the registered font has no color glyphs, emoji presentation sequences are left to browser pieces (color emoji). (textshaping::is_emoji_presentation, enabled the emoji feature of unicode-properties)
- Fallback fonts: added C:/Windows/Fonts/seguiemj.ttf, /System/Library/Fonts/Apple Color Emoji.ttc, /usr/share/fonts/truetype/noto/NotoColorEmoji.ttf to the defaults of EngineConfiguration.fallback_font_paths. When a candidate is added, only the table directory in the file header is peeked to note whether color glyph tables (sbix, CBDT, COLR) are present, and emoji presentation characters load color candidates first, other characters non-color candidates first. (The roughly 190MB Apple Color Emoji is not loaded for CJK characters)
- GlyphRaster.color_pixels, TextRaster.color_pixels (the color glyph portion, premultiplied RGBA). coverage is the coverage of the text excluding color glyphs. The structs gained fields, so code that builds them directly must be updated
- Aligned the core and platform share of the final comparison with the original.
- Scenes: on load, right after create, fits the root to the view size like the original Scene.load. (Position 0, top-left pivot, content size is the view size) After the tracked assets have all finished, shows the loading screen (draw_on_load) for 0.3 seconds more like the original SceneManager.loadScene, then calls initialize.
- Made Engine.get_all_loaded_scenes (original SceneManager.getAllLoadedScenes, SceneId handles instead of scenes), SceneBase.has_ever_touched (original Scene.hasEverTouched), Engine.dispatch_page_event public.
- Tween: ends without callbacks like the original when the target node is detached from the node tree it first ran in (when the topmost node changes). (Previously ended only on destroy) Tween::find_root_node (original Tween.findRootNode)
- Web maximum FPS: sets the slot by the number of frames since counting started, like the original. (platform/framelimiter.rs, 60 FPS no longer becomes 45 at 90 Hz)
- Web exit_application: tries Capacitor's App.exitApp, or window.close if absent, like the original. (platform::exit_application)
- Web GL context: forgets the GL state cache on the canvas webglcontextlost, webglcontextrestored like the original WebGLStateCache. (reset_gl_state_cache)
- Desktop Engine.is_text_input_focused: was always false, now reflects the focus of engine input fields. (Same as InputManager.is_typing_in_text_field)
- Clipboard: Engine.read_clipboard_text_with_callback (in place of the then of the original readClipboard, after navigator.clipboard.readText on the web, immediately on desktop). Calling web UIInputField.paste from code also reads and pastes asynchronously like the original. (Previously did nothing on the web)
- Desktop image cursors: builds the images of PointerCursor.register_image_cursor into a winit CustomCursor. (1x image on Mac, on Windows and Linux scaled by the window scale factor, using the 2x image if present) CursorValue gained image_url, image_url_2x, hotspot_x, hotspot_y, and platform::set_cursor takes a CursorValue.
- Desktop keys: maps winit's SuperLeft, SuperRight to W3C MetaLeft, MetaRight, and winit's Meta to Super.
- KeyCode: added the original's punctuation (SEMICOLON etc.), SCROLLLOCK, META, COMMAND, PAUSE, 7 audio keys (AUDIOVOLUMEUP etc.), NUM_LOCK, 16 numpad keys (NUMPAD_DIVIDE etc., NUMPAD0 ~ NUMPAD9) and the original names ARROWLEFT, ARROWUP, ARROWRIGHT, ARROWDOWN. (LEFT and the like are kept)
- Fixed an original bug together: the mute key value "AudioMute" is not a name in the W3C code table, so pressing the key did not match. Fixed to "AudioVolumeMute".
- Gamepads: on the web, instead of gilrs, reads navigator.getGamepads() directly like the original and receives all buttons and axes the browser gives (previously cut to 17 and 4), with connection and disconnection via gamepadconnected / gamepaddisconnected. On desktop, after the standard 17 buttons and 4 axes, appends the buttons and axes that gilrs could not map to the standard layout, in the order they are first moved. (gilrs does not give the device's button list, so they appear only after first being moved) The state slots grow when the button or axis count grows. gilrs is now a desktop-only dependency.
- Steam Deck: on desktop Linux, the environment variable SteamDeck=1, or DMI board_vendor Valve with board_name Jupiter, Galileo, gives PlatformType::SteamDeck.
- Desktop Platform.get_resource_usage: was empty, now filled with files the engine read as assets (asset byte reads, Engine::load_image, audio files, image cursors). (Kind "file", transfer size and decoded size are the file byte count)
- Windows wake from sleep: instead of the clock difference check (on Windows the monotonic clock keeps running during sleep, so it did not work), subclasses the window to receive PBT_APMRESUMEAUTOMATIC of WM_POWERBROADCAST and calls on_page_process_restored. (platform/desktop/windowsplatform.rs, windows-sys 0.52 dependency on Windows only) Mac and Linux keep the clock difference check.
- Desktop is_coarse_pointer: on Windows, ported Chromium's (pointer: coarse) check. (True when in tablet mode or when there is only touch and no mouse) On Mac it is always false, as in Chromium, and on Linux it was false at first because the device list could not be read. (Fixed later, see the Linux entry below)
- FiniteStateMachine: a transition requested inside a handler with StateChangeRequester.change_state, obtained via get_state_change_requester, is carried out in order after that handler finishes. (Previously could not transition inside a handler)
- format: a locale not in the table uses the system language (web navigator.languages, desktop the first of LANGUAGE / LC_ALL / LC_MESSAGES / LANG), as the original uses the browser default locale, and en-US if that is not in the table either.
- Color: create_from_hex, like the original createFromHEX, requires #, reads #rgba, and reads each two digits the parseInt way. to_hex_string, to_rgba_string do not clamp components outside 0 ~ 1, like the original.
- TimeManager.set_time_scale: accepts negative values as is like the original. (Previously clamped to 0)
- EngineConfiguration.rebake_text_on_font_load (original rebakeTextOnFontLoad, off by default): only when on, registering a font face discards strings baked with that face's characters. (Previously always discarded)
- NodeTree.get_world_corners, get_world_bounds (original WorldNode.getWorldCorners, getWorldBounds)
- Cooldown.r#use, FullscreenPass.r#use, ShaderProgram.r#use: use the original name use as is with r#. activate, use_program remain as names that do the same thing.
- Aligned the UI, effect, animation and 3D share of the final comparison with the original:
- GameSceneBase: like the original, when the tracked assets excluding the loading gate have all finished (if progress has ever been reported), fills the progress to 1. (complete_loading_progress_if_assets_finished, previously 1 only when the tracked AssetLoader finished) SceneBase::are_tracked_assets_finished_except, AssetLoadHandle::is_same_load
- DevTools: writes clientNativeSize in Statistics from ViewManager::get_client_native_size, and web memory from Chrome's performance.memory like the original. ((N/A) on desktop and browsers without it) set_ui_document, get_ui_document_mut attach the UIDocument in which the game registered its components to the inspector
- UIDocument: writes and reads ShadowText including TextDirection, Italic, Underline, Strikethrough, like the original reflection-based save. create_component(tree, node, name), in place of the original getComponentType, builds and attaches the component of that name
- UIConfirmWindow: for right-to-left languages, sets the Rtl direction on the title and message like the original. (Otherwise Inherit, at the next layout) set_right_to_left_in_tree applies the text direction immediately like the original
- UIScrollView::set_shows_vertical_scroll_bar_in_tree, set_shows_horizontal_scroll_bar_in_tree: create the scroll bar node on the spot, turn it on or off, and return the handle, like the original
- UIInputField: counts character positions in public functions (get_cursor_index, get_selection_start, get_selection_range, move_cursor, measure_index_at_local_x) and max_length in UTF-16 units like the original. (The counting of the public API changes. Hangul is the same, and only characters such as emoji differ) Internally it holds positions per char and does not split surrogate pairs. The count now matches maxlength of the web DOM
- Timeline: handlers receive the timeline itself like the original. Event (target name, event name, key, &mut Timeline, &mut NodeTree), marker (marker name, marker, &mut Timeline, &mut NodeTree), complete (&mut Timeline, &mut NodeTree). pause, seek can be called inside handlers. (This changes the public API)
- Timeline: TimelineTarget::External holds an Rc<RefCell
>, and evaluate calls set_timeline_property on the spot like the original. Removed apply_external_properties. get_external_properties holds the values applied by the last evaluate. TimelineTarget is not Copy, Eq. (This changes the public API, the order of applying values on the final tick and of the complete handler also matches the original) The example timelineshowcase holds ScreenEffect in an Rc - Timeline: applies text properties (text, number, fontSize, visibleCharacters, color) to RichText nodes too, like the original. data: URLs of stage sprites first decode the percent-encoding in the body like the browser, and are read even without ;base64. emit events emit at the node position at that moment
- ParticleSystem::emit_in_tree(tree, node, count, offset), set_node_position: in world space, emits at the node position at the time of emitting, like the original. (Calling only emit uses the position read on the last tick)
- 3D URL functions on both desktop and web like the original: FbxLoader::load_from_url(engine, asset path) → FbxLoadHandle (get_scene_data), SkinnedModel::load_from_url, load_from_fbx_url → SkinnedModelLoadHandle (create_model(gl, renderer)), SkinnedModel::add_animations_from_fbx_url(engine, path, clip name, ignore translation) → FbxLoadHandle (adds the clips on the next update or play_animation once downloaded), Material::load_image_description(engine, path, options) → ImageDescriptionLoadHandle (get_image_description, mime_type from the extension via Material::find_image_mime_type). Uses the engine's asset download, from the asset folder candidates on desktop and from asset_base_url on the web. Download handles can be tracked with SceneBase::track_load_handle. Removed load_from_path, load_from_fbx_path, add_animations_from_fbx_path, which read relative to the current folder on desktop, and the path-taking load_image_description. (This changes the public API) The example modelviewer loads with the URL functions
- Desktop capture mode (VANILLA_CAPTURE_PATH) runs with the window hidden. No window appears on the user's screen when verification tools capture examples. A hidden window has no redraw requests or vertical sync, so it runs frames directly in about_to_wait, and without a maximum FPS matches the speed of a visible window at the monitor refresh rate (60 if unknown). Occlusion notifications are ignored. On Mac it also takes no Dock icon or focus (activation policy Accessory). To see the window, VANILLA_CAPTURE_SHOW_WINDOW=1. (Confirmed by capturing toonshowcase, uigallery, textshaping hidden on Mac)
- Desktop AudioContext suspension now works like the original suspend. When creating the context, places a root track (in place of the original destination) under the main track and hangs players, buses and beeps under it, and on suspend stops the root track with kira pause. Sounds stop where they are and continue when resumed, the context clock (get_context_time) also stops, and is_context_running is false. (Previously the main track was only muted, so sound and the clock kept running and it always reported running) AudioPlayer.play wakes a suspended context before playing, like the original
- Made AudioPlayer::new(audio_manager, output_node), AudioBus::new(audio_manager) public. (original new AudioPlayer(audioContext, outputNode), new AudioBus(audioContext)) The output (platform::audio::AudioOutputNode) is &AudioNode on the web and kira &mut TrackHandle on desktop. AudioBus::get_gain_node lends the bus track (RefMut
) on desktop too. (This changes the public API: the audio backend's create, is_audio_context_running, play_beep_tone take the manager state) - SoundSystem: picking from a group and pitch variation use math::random (seeded by time), in place of the original Math.random, instead of a fixed seed (SeededRandom 0x50f7). Changed SoundRow.maximum_voices to Option
. (This changes the public API) None allows up to the overall effect count, Some(0) plays only one like the original. (Previously 0 meant 12) - Desktop sound files: enabled kira's flac, isomp4, aac features to also read FLAC and M4A (AAC). (New crates: symphonia-bundle-flac, symphonia-format-isomp4, symphonia-codec-aac 0.6.1)
- BeepPlayer computes the desktop waveform the same way as Chrome WebAudio OscillatorNode (PeriodicWave). Band-limits by blending between two tables whose Fourier coefficients are trimmed every 1/3 octave, and normalizes the amplitude by the peak of the table with all harmonics. The maximum difference from oscillators rendered with headless Chrome OfflineAudioContext (square, sawtooth, triangle, sine, 150 / 440 / 1000 Hz, 2048 samples) is 0.0003. (Previously square and sawtooth waves without band limiting)
- WebSocketClient: opens wss:// on desktop. (ewebsock's tls feature, newly pulls in rustls 0.23 and ring 0.17. Sets the rustls crypto provider to ring when connecting) Made receive_message (original receiveMessage) public
- CameraGestures follows the original rules: going from two fingers to one continues the gesture until all are lifted (the movement is not used), and the reference is reset when the finger count changes. set_thresholds takes a fourth argument (milliseconds to ignore emulated mouse events, initially 800). (This changes the public API) Added is_touch_input (initially whether the device's primary input is fingers), is_coarse_pointer, is_last_wheel_ctrl. The initial value of InputManager.is_touch_input is also whether the device's primary input is fingers
- AssetLoader.add_font takes FontFaceDescriptors (weight, style, character range) instead of a weight and passes them to register_font_face_when_loaded. (original addFont descriptors, this changes the public API)
- JsonAsset: JSON that fails to parse is treated as not loaded, like the original. (is_loaded false, included in AssetLoader's failure list) Added get_text (text of the original TextAsset), and get_data is called with &self
- PersistedStore: read_stored_text made public. Merging like the original Object.assign: arrays (even when the stored state is an array) are merged by index keys, and key order puts integer-like keys first in ascending order, like JS objects. (Previously an array state gave the default)
- LocalStorage: converts numbers to text and reads text as numbers exactly like the original String(number), Number(text). Values of 1e21 or more and 1e-7 or less are written in exponent form like 1e+21, and 0x, 0o, 0b notation, "1.", ".5" and JS whitespace are read like the original. (Compared against values printed with node)
- Localization.detect_language, the device language of languagepack: on desktop reads the system preferred language order with sys-locale 0.3. (Windows and Mac too, like the original navigator.languages, previously only environment variables like LANG were read, so Windows always got the default language)
- GraphicsQualityGovernor.apply_search_text decodes + and %XX and skips empty pieces like the original URLSearchParams
- Added hooks push_transform, pop_transform to components, around the node's draw state. (Called wrapping its own components, children and gizmos, in place of the original nodes overriding pushTransform, popTransform) With these hooks TouchEffect draws its children too with additive blending, like the original. (Previously only its own particles)
- Graphic blend modes: correctly draws the 17 modes that were drawn as source-over instead. All 26 BlendMode modes now work (same behavior as the original, same shader source)
- SourceOut, SourceAtop, DestinationAtop, Xor are set with blend_func using the Porter-Duff coefficients of W3C Compositing and Blending Level 1 as is
- Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity copy only the area to be drawn (the bounding box of the vertices) from the current framebuffer with blit_framebuffer into a buffer of the same format at the same position 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). Since it copies to the same position, it also works on the multisampled default framebuffer on desktop. Darken, Lighten blend in the shader because blend_equation 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 (on M2 Pro with 1000 64x64 images, about 0.062 ms per draw on desktop and 0.061 ms on the web, mostly the cost of the copy breaking the render pass. Drawing source-over unbatched takes 0.002 ~ 0.004 ms)
- 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 each quad blends over the previous quads. Swapped-in shaders are first drawn into an overlay buffer (RGBA16F on desktop, on the web RGBA16F when EXT_color_buffer_float is available, otherwise RGBA8) and then blended while being transferred
- The path that used source-over for unknown modes and its warning are gone. (BlendMode is an enum, so there are no unknown values)
- 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. The web build matches the original engine down to the pixel, and desktop matches inside shapes and differs only in edge antialiasing. Canvas2D also clears outside the drawn shape for SourceIn, SourceOut, DestinationIn, DestinationAtop, Copy, whereas Graphic changes only the inside of the shape like the original
- Graphic: does not write alpha when drawing to the default framebuffer on desktop. In the original and on the web the canvas is alpha: false, so screen alpha is always 1, but the desktop default framebuffer has alpha, so after modes that lower alpha (SourceOut, Xor, DestinationOut and the like), modes using DST_ALPHA and shader blending came out differently from the web. (Drawing an image with SourceOut and then a rectangle in the same cell showed the rectangle only on desktop) Alpha is still written on render targets, and when handing GL out (get_gl, run_external_pass, end of frame) the mask is restored to write everything
- Extends toon post-processing, effects, and the camera so that Aberrant and Exoplanet Miner can use the engine as is. (Same API and same shader source as the original vanilla.js, with new options at their defaults the output is identical to the current screen down to the pixel, game recipes and color values are taken as parameters)
- RenderTarget: sample_count in RenderTargetOptions (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, on the web, the sample count each format accepts, without multisampling if unsupported or incomplete, desktop GL 3.3 has no per-format query so only MAX_SAMPLES) and depth_bits (16 or 24), get_sample_count, get_resolve_framebuffer, read_supported_sample_count. Places that built options as a struct literal append ..RenderTargetOptions::default(). read_renderbuffer_sample_counts (the WebGL2 SAMPLES list) in the web platform layer
- BloomEffect.set_use_float_color(gl, enabled): builds the ping-pong buffers as RGBA16F (default stays RGBA8)
- MultiLevelBloomEffect: multi-level bloom. (Same shaders as the original, half-size extraction with a soft knee, dual filter downsampling, tent filter upsampling, set_level_count, set_threshold)
- ToonPostProcess: new_with_options(gl, width, height, ToonPostProcessOptions { sample_count, use_float_color, depth_bits, use_depth_texture }) (new uses the default options), is_float_color_supported (devices that cannot use it take the RGBA8 LDR path), set_sample_count, set_resolution_scale, set_bloom_levels, set_bloom_float_color (these four take gl and return Result), set_brightness, set_lit_area and clear_lit_area, get_sample_count, get_use_float_color, get_resolution_scale, get_bloom_level_count. The color space convention in the header (the scene buffer is linear, porting gamma-encoded float buffer values is c^2.2, brightness multiplier k^2.2)
- Camera3D.set_matrices(view, projection): uses the raw matrices computed by the game as is. Extracts eye, target, up and whether it is orthographic from the matrices, and project_to_view, unproject_to_plane, read_view_depth and the renderer run on those matrices. has_raw_matrices, clear_raw_matrices. set_perspective, set_orthographic and look_at discard the raw matrices. One test
- ToonVfx: options age (an effect seen late starts from that age) and key (event key, a number or text in the original, u64 in the Rust version, clear forgets it, register_event_key) for particles, fireballs, shockwaves, marks, plumes, lightning and flashes, set_look_gain and get_look_gain, set_glint_capacity and get_glint_capacity (default 96), ToonVfxDecalMode::Stain, Sheen, Shade and mark flicker, queue_blob_shadow(ToonBlobShadowOptions), rim for fireballs, shockwaves, ribbons, lightning. Fields were added to the option structs, so build them with ..Default::default(). One default value test
- Getters that the original had and the Rust version lacked: ShadowImage.get_image, get_image_rect, get_bake_image (original getBakeCanvas), ShadowText.get_bake_image, SoftShade.get_color, get_fade_width, get_bake_unit, get_bake_maximum_size, get_bake_image
- slice_graphemes(text, count) (original sliceGraphemes, up to count grapheme clusters from the start, exported from the crate root)
- Graphic.set_image_smoothing_quality, get_image_smoothing_quality, ImageSmoothingQuality(Low, Medium, High, initially High. Only stored, like the original), get_vertex_array, get_vertex_buffer, get_vertex_data (vertex array, buffer and scratch array of the default drawing)
- create_guid() (createGUID of the original base/reflection.js, UUID-shaped text whose first 12 digits are the time in milliseconds and the rest random, exported from the crate root)
- Chains the desktop default font as a sequence of names like the original SYSTEM_FONT_STRING. (Previously only the first readable file among the candidate paths was used, so on Windows even Latin came out in Malgun Gothic) Finds -apple-system, Segoe UI, Roboto, Apple SD Gothic Neo, Malgun Gothic, sans-serif among the OS fonts, and draws characters missing from an earlier font with a later one. On Mac, Latin is SF (the system UI font) and Hangul is Apple SD Gothic Neo, and on Windows, Latin is Segoe UI and Hangul is Malgun Gothic. A face is loaded the first time text of that weight and style is used. (TextStringTextureCache.set_system_font_chain)
- Unregistered names in font strings are also looked up among the OS fonts. ("16px Menlo", "16px Helvetica" are drawn with system fonts, same as the browser) Generic names match Chrome's default fonts: on Mac sans-serif Helvetica, serif Times, monospace Courier, on Windows Arial, Times New Roman, Consolas, and on Linux fontconfig chooses
- Desktop fallback fonts: the OS chooses instead of 13 hardcoded files. Mac CoreText CTFontCreateForString (from the system UI font), Windows DirectWrite IDWriteFontFallback.MapCharacters (user language), Linux fontconfig (FcFontSort containing the character), the same APIs as Chrome, where the original runs. When bold is requested, a bold fallback face is queried separately. Emoji presentation characters check the color emoji font first. (platform/desktop/systemfont.rs: find_family_font_file, find_fallback_font_file, TextStringTextureCache.set_system_font_fallback_enabled)
- Changed the defaults of EngineConfiguration.default_font_paths, default_bold_font_paths, fallback_font_paths to empty lists. When empty the OS finds fonts as above, and when given those files are used as before. default_font_paths chains all readable files in order, and default_bold_font_paths holds the bold file for the same position. (Code that read the default path lists must be updated)
- Mac and Linux bold fonts and TTC: font collections (TTC) choose the face index by PostScript name or by weight and style. (textshaping::find_collection_face_index, the real Bold of Mac Apple SD Gothic Neo is used) Variable fonts (wght axis, Mac SF) produce the weight through axis values. (read_weight_variation) Outlines of variable fonts are obtained and drawn with skrifa. (fontdue cannot read axis values, and ttf-parser and fontdue cannot draw the outlines of Mac SFNS, which has more than 32 variations per glyph) LoadedFont.create_from_shared_bytes(bytes, face index, axis values), get_shaping_face, get_font_bytes, get_face_index, is_outline_raster, read_glyph_metrics, draw_glyph_outline. The LoadedFont.shaping_face field was replaced by get_shaping_face()
- Font unloading: LoadedFont holds the font bytes together with the rustybuzz face. (self_cell, previously held with Box::leak and not freed even when unregistered) Multiple faces from the same file share the bytes (Rc)
- Values compared against Mac Chrome Canvas2D measureText: Hangul "ganadara" (U+AC00 U+B098 U+B2E4 U+B77C) at 16px 55.360, "16px Helvetica" 113.508, "16px Menlo" 154.125 are the same. (Added as tests) SF Latin is 106.672, 2.2% narrower than Chrome's 109.072. (Did not fully match the optical size and letter spacing Chrome applies to the system UI font) (Fixed later: the gap came from font selection, since Chrome treats -apple-system as an unknown name. See the SF Latin entry below)
- New crates: self_cell 1, skrifa 0.50, Mac objc2-core-text 0.3 and objc2-core-foundation 0.3, Windows dwrote 0.11 and winapi 0.3, Linux yeslogic-fontconfig-sys 6 (dlopen, not linked at build time)
- Draws Mac color emoji with CoreText. (platform/desktop/coretextglyph.rs) Like Chrome on Mac, enlarges emoji at small font sizes and shifts them down. (20px image at 16px, the font size as is from 24px) The advance is the height of the image box drawn by CoreText rounded to an integer. Matches Chrome measureText at 23 sizes from 8 ~ 128px (8px 10, 13px 16, 16px 20, 21px 23), and the image box and alpha sum at 12, 16, 20, 32, 64px match Chrome canvas getImageData. (Color sum within 0.01%) CoreText enlarges emoji only for fonts registered with the system, so the font is built by PostScript name
- Mac: fonts whose outlines are not in glyf, CFF, CFF2 are also drawn with CoreText. The Chinese fallback font PingFangUI.ttc of macOS 26 keeps its outlines in the Apple-only hvgl table, so open parsers cannot draw it. (Previously Simplified Chinese characters were blank) LoadedFont.with_source_path, is_core_text_raster, read_advance_scale, is_integer_advance
- New crate: Mac objc2-core-graphics 0.3
- Aligned desktop word segmentation with Chrome Intl.Segmenter (ICU4C dictionary). Thai, Lao, Khmer and Burmese are split by dictionary instead of LSTM. (ICU4X WordSegmenter::new_dictionary) For CJK runs, ICU4X picks the longest word first while ICU4C picks the split with the smallest sum of word costs, so Japanese differed ("今日|はい|い"). Ported the computation of ICU4C CjkBreakEngine (cost 255 for characters not in the dictionary, length costs for runs of 1 ~ 8 katakana, NFKC before dictionary lookup) and re-splits with the same dictionary of ICU4X (cjdict). 22 sentences in Japanese, Chinese, Thai, Lao, Khmer and Burmese match Chrome. (Added as tests)
- New crates: icu_provider 2, icu_collections 2 (the versions icu_segmenter already uses), unicode-normalization 0.1 (desktop)
- UIFont: when characters not fetched in advance are measured or drawn with that font, update fetches the subsets for those characters. (In the original, the browser starts fetching a FontFace registered in document.fonts when the canvas draws characters within its character range. Previously only characters requested via load_ui_font_text, request_ui_font_text were fetched) Until fetched, they are drawn with another font like the original, and rebaked once fetched. The text cache collects characters, from text measured or baked with a watched name, that fall outside the character ranges of the registered faces. (textstringtexturecache::watch_unresolved_family_characters, take_unresolved_family_characters)
- Image formats: the original Image accepts every format the browser decodes. Desktop adds GIF (first frame), BMP, ICO from the image crate, and draws SVG with resvg at the image size (width, height, or viewBox if absent). (SVG with text loads the system fonts once the first time) On the web, when downloading an asset with an image extension (png, jpg, gif, webp, bmp, ico, svg, avif), decodes it with the browser (decode of HTMLImageElement) like the original and keeps it in the handle. ImageAsset and AssetLoader use that image as is. Added Image::create_from_premultiplied_pixels
- New crate: resvg 0.50 (desktop)
- Web rasterization uses browser Canvas2D like the original: even with font bytes, does not bake with fontdue and always bakes and measures with the canvas fillText, strokeText, measureText. Registered font bytes (FontAsset, default_font_bytes, default_font_url, UIFont subsets) are added to document.fonts like the original new FontFace(name, bytes, descriptors), and the browser chooses and draws. (Within the same name later faces come first, the default font is named VanillaEngineDefault and fallback fonts VanillaEngineFallback1, 2 …, placed after the font string names and before the system fonts) When registered fonts finish loading (loadingdone), baked text is discarded at the start of the frame. (TextStringTextureCache.is_browser_raster)
- Web ShadowText: like the original bakeText, sets the shadow (shadowColor, shadowBlur, shadowOffsetY) on the canvas and bakes with fillText in the text color, and underline and strikethrough with fillRect. The margin (2 + blur rounded up) and position calculation are the same as the original. Web ShadowImage: like the original readScaledImage, bakeImage, scales down with drawImage (imageSmoothingQuality high), paints the color with source-in, then lays the canvas shadow underneath. (Desktop still computes it directly)
- ToonRenderer extension points and light model: (same API and same shader source as the original vanilla.js) standard features come first so that Aberrant and Exoplanet Miner 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. (Drawing the same scene as the old renderer on the original side gives LDR pixel difference 0, and in the examples toonshowcase, toonview, toonfx the pixels of static things (floor, instanced rocks) are the same)
- ToonLightSet(toon/toonlightset.rs): one bundle of light values. The renderer holds a default set, and set_light, set_sun_direction, set_fill_light, set_rim_light, set_specular, set_point_lights, set_point_light_limit, set_band_count, set_band_ramp, clear_band_ramp, set_light_model modify it. create_light_set, get_light_set, get_light_set_mut, ToonDrawOptions.light_set per draw. ToonPointLight, ToonLightModel, ToonBandRamp, TOON_MAXIMUM_POINT_LIGHTS 8, TOON_MAXIMUM_BAND_STEPS 8. A clone gets a new version number
- Meaning of sun direction: the direction light travels (from the sun to the surface). The received share is max(dot(N, -sun_direction), 0). Code that used the direction from the surface toward the sun passes it with the sign flipped
- Point light attenuation = window (1 - (d / range)^range_exponent) clamped and squared x 1 / max(d^decay, 0.01), the received share is (dot + wrap) / (1 + wrap). Defaults decay 2, range_exponent 4. decay 0, range_exponent 1 gives (1 - d / range)^2
- Light model is_energy_normalized: ÷π and normalized Blinn-Phong (exponent + 8) / 8π
- ToonDrawOptions: added tint_amount, glow_scale, color_scale, emissive_color, emissive_intensity, base_color_texture, emissive_texture, uv_transform, decal_texture, decal_color, decal_emission, decal_uv_transform, alpha_cutoff, blend_mode(ToonBlendMode), soft_edge, is_mirrored(if None, decided automatically from the determinant), index_start, index_count, outline_index_start, outline_index_count, material, textures(&[(uniform name, texture)]), on_before_draw(&dyn Fn(&ShaderProgram, &glow::Context, ToonProgramKind)), light_set, group, is_depth_prepassed. Code that built it as a struct literal with every field written out appends ..ToonDrawOptions::default(). Debug is implemented by hand (callbacks show only whether they are present)
- ToonMaterial(toon/toonmaterial.rs): create_material(ToonMaterialChunks { name, uniform_chunk, surface_chunk, light_chunk, vertex_chunk }) (an options object in the original). prepare_material, delete_material, get_program(material, instance layout, ToonProgramKind). Passed to ShaderWarmer via read_material_program_sources(material, instance layout) and compose_toon_program_sources(ToonProgramSources, including attribute locations). (In place of the optional arguments of the original readProgramSources, read_program_sources stays the default program)
- Instance layout: create_instance_layout(&[(name, size)]) → ToonInstanceLayout, create_instance_buffer(gl, layout, count, ToonBufferUsage) → ToonInstanceBuffer, update_instance_buffer, delete_instance_buffer, draw_mesh_instance_buffer(gl, model, buffer, count, layout). TOON_MAXIMUM_INSTANCE_ATTRIBUTES 3, TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION 13
- Textures: create_texture(gl, width, height, RGBA bytes, ToonTextureOptions { is_mipmapped, is_repeated, is_filtered }), delete_texture. TOON_MAXIMUM_MATERIAL_TEXTURES 9
- Frame: begin_frame_with_matrices(gl, view, projection), get_frame_camera, read_frame_camera(ToonFrameCamera), apply_frame_state, create_reflection_matrix, read_matrix_determinant
- Performance: per program, frame values and the light set are uploaded only when changed
- vertexUv(12) was added to TOON_ATTRIBUTE_LOCATIONS, so its length is 13. ToonMesh::has_uv, get_index_counts, has_outline
- ToonDrawQueue: add_pass(ToonDrawStage::BeforeOpaque | AfterOpaque | AfterOutline | AfterTransparent, callback(gl, renderer)), options group and is_depth_prepassed (draws depth only first for a translucent group, then colors only at equal depth), blend_mode other than Alpha goes to the translucent order, draw_with_matrices(gl, renderer, view, projection). Stage callbacks are held in a RefCell, so draw(&self) calls them as is. clear also empties the callbacks
- MeshBuilder: added uv_data, material_ranges(ToonMaterialRange) to ToonMeshArrays and uvs to ToonGeometry. (Code that built them as struct literals with every field written out appends ..Default::default()) create_box_geometry, create_sphere_geometry build uvs and add_part stores them. add_triangles_with_uvs (the last optional argument of the original addTriangles), add_material_range, combine joins uv_data and material_ranges
- GLB reading: TEXCOORD_0, per-primitive material ranges (material name, extras, alpha_mode, alpha_cutoff, linear colors, texture image indices), read_glb_images(ToonGlbImage), decode_glb_image (RGBA via the image crate)
- Value conversion when porting Aberrant: same as the corresponding item in the original UPDATE.md. (sign of the sun and bounce light, ÷π, specular times 8 / 56, point lights with decay 0 and range_exponent 1, readjusting light intensity and exposure instead of min(lit, 1), linear values and multipliers to the power of 2.2 instead of HDR gamma values, material ranges and UV textures instead of color keys, face screens as surface chunks)
- Made NodeTree.get_position the same as the original WorldNode.getPosition. Offsets the local position relative to the parent pivot point (parent content size x parent pivot), then applies the parent's global rotation and scale, so it matches where the draw transform (calculate_world_matrix) places the pivot point. Until now, like the original TransformNode.getPosition, it did not subtract the parent pivot, so it differed when the parent's content size and pivot were nonzero. set_position is its inverse. (Fixed together with the bug where the original setPosition did not undo the parent pivot) Inside the engine only set_position calls get_position, and UI, layout, tweens and timelines compute with the local position and the world matrix, so the example screens are unchanged
- When drawing Multiply to a render target, the area under the draw region is copied and blended in a shader per the W3C formula (B(Cb, Cs) = Cb x Cs). (Fixed together with the original) Fixed blending drops the cs x (1 - αb) term when the backdrop is translucent and leaves the alpha as the backdrop alpha, differing from Chrome Canvas2D by up to 221. The default framebuffer keeps fixed blending and batching, so 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 scenes 6 and 7 to the blendmodes example (a translucent backdrop and scene 0 drawn into a render target cleared to transparent, then transferred over black and over white). On both desktop and web, within 1 level of the Chrome canvas inside shapes, and 0 for Multiply
- The system language Format uses in place of a language not in its table is the first entry of the shared function (localization::read_preferred_language_tags) that Localization.detect_language also uses. The "desktop LANGUAGE / LC_ALL / LC_MESSAGES / LANG" in the format line above applies to Linux. The desktop reads macOS CFLocaleCopyPreferredLanguages and Windows GetUserPreferredUILanguages through sys-locale. (On macOS, changing LANG to de_DE or fr_FR still follows the system preferred language ko-KR) Corrected the header comment of format.rs
- Aligned fonts more closely with Chrome 158 Canvas2D on macOS:
- macOS system UI font (system-ui, BlinkMacSystemFont, SFNS): like Chrome, sets the opsz axis to the font size (clamped to 17 ~ 96 for SFNS) and adds the tracking from the trak table. Weight is applied as the wght axis value as is (including weights like 300). 16px "Hello World Wifi" is 115.867, the same as Chrome. (Previously 106.7 with the initial opsz 28 and no tracking) Within 0.004 of Chrome across 19 sizes from 8 ~ 128px and weights 300, 400, 700. Chrome applies opsz to macOS system fonts and registered fonts (web fonts), and not to Windows or Linux system fonts. Follows that as is. (Chromium font_platform_data_mac.mm, font_custom_platform_data.cc)
- trak tracking is computed and added the way HarfBuzz 15 does, not rustybuzz. Interpolated linearly between sizes without rounding, end values outside the table, only for fonts with a STAT table, and added only to the advance of the first glyph of each cluster. (Chrome harfbuzz_face.cc gives the font size via ptem, and on macOS the advances of fonts with trak are computed by HarfBuzz) Apple Chancery, which has no STAT, matches Chrome without tracking
- LoadedFont: with_optical_sizing_auto, read_optical_size, read_horizontal_tracking, create_sized_shaping_face. draw_glyph_outline takes the font size. (This changes the public API, since axis values differ per size)
- The "SF Latin 106.672 vs Chrome 109.072" in the earlier entry was a value where Chrome skipped -apple-system as an unknown name and drew Latin with Apple SD Gothic Neo from the default chain. Like Chrome, -apple-system and ui-serif, ui-sans-serif, ui-monospace, ui-rounded are treated as unknown names. The Latin of the macOS desktop default font (the SYSTEM_FONT_STRING chain) changes from SF to Apple SD Gothic Neo. (Same as the screen of the original running in Chrome. Safari uses SF) BlinkMacSystemFont is the same as system-ui, like Chrome
- Generic family names (serif, sans-serif, monospace, cursive, fantasy, math) are resolved per Chrome's default font table. (platform/desktop/systemfont.rs: GenericFamily, resolve_generic_family_name, read_browser_locale) The table is IDS_*_FONT_FAMILY from Chromium locale_settings_mac.grd, _win.grd, _linux.grd and the UI language translations (platform_locale_settings/*.xtb). Chrome resolves a canvas without a document lang by the default locale (UI language), and does not register the per-script values for that script (prefs_tab_helper.cc), so it uses the Common values of the UI language. The canvases the original bakes into are not attached to the document, so changing the document lang has no effect. (Confirmed in Chrome) The Rust version takes as the UI language the first of the system preferred languages that has a Chrome translation. A value starting with a comma is the first installed font
- macOS Korean: standard and sans-serif Apple SD Gothic Neo, serif AppleMyungjo, monospace Menlo, cursive Apple Chancery, fantasy Papyrus, math STIX Two Math. 16px "Hello World Wifi" matches Chrome (serif 124.097, sans-serif 109.072, monospace 154.125, cursive 111.352, fantasy 109.156, math 115.472). Previously serif was Times 110.961 and monospace Courier 153.625. English is Times, Helvetica, Menlo
- Windows: like Chrome, monospace is Courier New, or Consolas when ClearType is on, and Korean is Batang, Malgun Gothic, Gulimche, Gungsuh. system-ui is the menu font (lfMenuFont of NONCLIENTMETRICS), like Chrome. Linux: names in the table such as Times New Roman, Arial, Monospace are looked up with fontconfig, but like Chrome (Skia SkFontConfigInterface_direct.cpp) a result is accepted only when the name matches, when it is a metric-compatible substitute (a table such as Liberation, Arimo), or when it is sans, serif, monospace. For Windows and Linux, only those branches were compiled for x86_64-pc-windows-msvc, x86_64-unknown-linux-gnu, and they were not run and compared against Chrome
- Characters for which the name list is exhausted are drawn, like Chrome, with the standard font of the UI language, then the OS fallback font, then the last resort font (Times on macOS). "é" (e + U+0301), whose combining mark is missing from the default font, is drawn in Times as in Chrome on macOS
- macOS: fixed font collections whose name table has only Mac records (such as Papyrus.ttc) drawing in Condensed because the face could not be selected by PostScript name. Puts normal width in the font descriptor
- Like the Chrome canvas (PlainTextNode in plain_text_node.cc), splits text into words and shapes them separately. No kerning or ligatures across spaces. Spaces, tabs and ZWSP are one each, and CJK characters and emoji are separate per character. (textshaping::find_chrome_word_end) The space and W kerning of STIX Two Math is gone, now matching Chrome. Canvas tabs, line feeds, form feeds and carriage returns are shaped as spaces. (Chrome IsNormalizedCanvasSpaceCharacter)
- Computes the font string size like the Chrome canvas. (parse_font_string) Matches values measured in Chrome on a canvas not attached to the document, as the original uses:
- ex, ch, cap, ic, lh are the x-height (top of the 'x' glyph), the advance of '0', the cap height, the advance of '水' (1em if missing), and line height normal of the parent font (Chrome's last resort font, Times on macOS) at 10px. rem, rex, rch, rcap, ric, rlh use the document root (the standard font of the UI language) at 16px. (Previously rem was computed as 10px) vw, vh, vi, vb, vmin, vmax with the sv, lv, dv prefixes, and cq units without a container, use the logical size of the window. (textstringtexturecache::set_font_viewport_size, the desktop reports it when the window size changes)
- When the name list is just an unquoted monospace, relative sizes are multiplied by 13 / 16 and keyword sizes use the monospace table (medium 13, large 16). Evaluates calc(), min(), max(), clamp(), abs(), sign(), round(), mod(), rem(), hypot(), sqrt(), pow(), exp(), log() and pi, e, infinity. Negative values inside functions become 0, values over 10000 become 10000, "+2px" ".5px" "1e1px" are accepted and "2.px" is invalid
- On the web, sizes other than absolute lengths are set into the font of a browser canvas not attached to the document, as the original does, and read back. (resolve_font_size in platform/web/systemfont.rs) The parent font metrics on Windows and Linux (choosing win or hhea values for line height) were ported following the Chrome source and not compared
- macOS-only Chrome comparison tests: system_ui_font_matches_chrome_on_macos (19 sizes x 3 weights), generic_families_match_chrome_korean_defaults_on_macos (when the UI language is Korean), font_size_units_match_chrome_on_macos (75 unit and calc cases, plus 12 root units when Korean). Comparing the textshaping example with the original JS of the same scene in Chrome on macOS, the horizontal extent of the text on each line is within 1 pixel on a 2x display. (Rust on the web differs from the original JS screen by at most 11 in pixel values)
- Remaining difference: rustybuzz holds positions as integers in font units and rounds GPOS variation deltas (such as the kerning between W and o in SFNS). HarfBuzz 15 holds them as fractions. "Hello World Wifi" in SFNS at 18, 20, 21, 24px differs from Chrome by 0.002 ~ 0.004px
- New crate: unicode-script 0.5 (the version rustybuzz and usvg already use). Enabled the general-category feature of unicode-properties and the Win32_Graphics_Gdi feature of windows-sys on Windows
- Moved desktop wss:// into a tls feature that is on by default. (tls of ewebsock and rustls) Default behavior is unchanged. The crypto provider ring builds C, so checking the Windows target on macOS was blocked by missing Windows C headers. Now the whole engine is checked against the Windows target with cargo check --target x86_64-pc-windows-msvc --no-default-features. (0 warnings, also fixed the naming warning for userProfilePath in LocalStorage, which compiles only on Windows) With default-features = false, the desktop opens only ws://. For the Linux target, alsa-sys of cpal and libudev-sys of gilrs call pkg-config, so on macOS it is checked by passing a pkg-config that prints empty flags via PKG_CONFIG, with PKG_CONFIG_ALLOW_CROSS=1
- AudioBus.get_gain_node returns AudioGainNode on both platforms. (GainNode on the web, on desktop an Rc<RefCell
> that shares the bus track) Its as_deref() is the output of AudioPlayer::new, so AudioPlayer::new(&audio_manager, audio_bus.get_gain_node().as_deref()) compiles as is on both platforms. (Previously split into as_deref on the web and as_deref_mut on desktop, this changes the public API) On desktop, other bus functions can now be called while the bus track is borrowed - The web platform, like the original engine.js, only keeps mouse events within 800 milliseconds after a finger out of the last device and last hand records, and passes the buttons, position and touch through as is. Until now the events were discarded entirely, so making the fourth argument of CameraGestures (the time to ignore emulated mouse events) shorter than 800 had no effect. (In headless Chrome, a right button 300 milliseconds after a finger is a gesture with threshold 100 and ignored with 800. Before the fix, both were ignored)
- Desktop PlayStation pads (Sony 054c DualShock 4 05c4, 09cc, 0ba0, DualSense 0ce6, 0df2, 0e5f) get 18 buttons like Chrome MapperDualshock4, MapperDualSense, with raw button 13 always at TOUCHPAD(17). (macOS IOKit button usage 14, Windows Windows.Gaming.Input button 13, Linux hid-generic BTN_GAMEPAD + 13) gilrs maps touchpad:b13 of the SDL mapping only to an unnamed button (Button::Unknown, same as misc1), so it is found by raw code. Other buttons (DualSense microphone) and axes are not mapped. Linux hid-sony (from 4.10) and hid-playstation (from 5.12) expose the touchpad as a separate device and add 0x8000 to bcdHID, so they have 17 buttons like Chrome MapperPs4Ps5. Until now, the first pressed button not in the mapping became 17. (Verified through mapping data and code paths without a real pad)
- is_coarse_pointer on Linux and other Unix systems: like Chromium on desktop Linux, true when there is a touchscreen and no enabled mouse, touchpad or pointing stick. (Previously always false) The device list is read from the display server, like Chromium. Wayland uses the pointer, touch capabilities of wl_seat, and X11 the device type from XListInputDevices and the use, enabled state, direct touch and Abs MT Position axes from XIQueryDevice. (Chromium's evdev classification is for ChromeOS) It is called every frame, so the read value is used for 2 seconds. x11-dl, wayland-client are the same versions glutin, winit already use
- The desktop also decodes AVIF. The engine reads HEIF boxes per libavif rules (joining grid tiles, both auxiliary alpha types, prem, colr nclx, clap only when the origin is (0, 0) like Chrome, irot, imir) and decodes AV1 with rav1d (a Rust port of dav1d, built with asm off, without nasm or a C compiler). The YUV to RGB conversion is libavif's reference computation. Maximum difference 1~4 from Chrome 158's decoding, and grid (1600 x 1200, 12 tiles) and alpha images made with macOS ImageIO also match. Color profile conversion and animated AVIF are not supported. rav1d is slow at opt-level 0. (1600 x 1200 takes 2.9 seconds in a dev build, 0.9 seconds with only rav1d at opt-level 3) Putting [profile.dev.package.rav1d] opt-level = 3 in the game's Cargo.toml makes it fast in dev builds too
- Added Image::load_from_memory_with_mime_type (bytes of a known type, SVG only for image/svg+xml like the browser, otherwise raster identified by content), sniff_image_mime_type (the image table of WHATWG MIME sniffing plus AVIF)
- Image type from the response content-type, like the original: load handles keep the response headers. (AssetLoadHandle.get_content_type) On the web, if the response is an image type or the URL has an image extension, the browser decodes it with that content-type as the type. Like the original HTMLImageElement, SVG is identified by type and raster by content. (image/svg+xml decodes even without an extension, and an .svg served as text/plain does not decode, like the original) Material's mime_type is the response content-type like the original loadImageDescription, and on desktop, which has no response, the type chosen from content. (Removed Material::find_image_mime_type, which decided by path extension)
- Timeline "data:" URL images: on the web the browser decodes them like the original (including SVG, AVIF), and once decoded they are set on the sprite and the frame of the description is selected. (applySpriteFrame in the original image.onload) On desktop, if the URL type is image/svg+xml it is drawn with resvg, otherwise it is raster identified by content. (Previously drew SVG by content regardless of type)
- Corrected the header comments of Platform.is_coarse_pointer, Engine.is_coarse_pointer to match actual behavior. (Windows and Linux use Chromium's detection)
- async/await is used like the original. (Until now load handles and callbacks stood in for it. The synchronous handle-based style and the callback APIs are kept)
- The engine contains a single-threaded executor. (core/task.rs, no external runtime, the same code on desktop and web, futures need not be Send) Engine::spawn_task (engine task) and spawn_scene_task (scene task) run up to the first await at the point of spawning, as when calling an async function in the original, and the rest is polled every frame after updating time and input, before the scenes' tick, in wake order until the queue is empty, like the original microtask queue. (When a task resolves a Promise or finishes, the waiting tasks continue in the same pass in the order they were resolved, and a future that wakes itself continues the next frame) Where only &Engine is available, spawn_deferred_task, spawn_deferred_scene_task
- Tasks borrow the scene and engine only inside with(|scene, engine| ...) of a context (EngineContext, SceneContext
). Pointers kept in a thread-local slot are taken out only while polling and put back, so no second &mut arises. Graphics via with_graphic. TaskHandle tells whether a task has finished, or is awaited - Promise, PromiseResolver: in place of the original new Promise((resolve, reject) => ...). Promise::create, Promise::resolved, reject(reason) of Promise<Result<T, E>>
- wait::seconds, wait::next_frame (the original base/wait.js, not ported until now). seconds is wall-clock seconds like the original setTimeout (time scale is not applied), yields once even for 0 seconds, and wraps milliseconds to a WebIDL long the same way. The original nextFrame finishing immediately because it did not await the Promise it created was fixed in the original too (vanilla.js dev 89847b7), so both wait until the next frame
- Scenes: in place of the original async load, a task spawned in create and handed to SceneBase::track_task defers initialize until it finishes. One handed over in unload keeps the scene in the list until it finishes, like the original await scene.unload (it still receives tick and draw). Even after a scene is unloaded, its tasks keep running like the original Promise chain, and the engine keeps the scene value alive until they finish (without tick and draw, with still gives that scene). A scene unloaded while loading still receives initialize once loading finishes, like the original loadScene. destroy is called when the scene value is dropped. Engine::load_scene_async, unload_scene_async, unload_all_scenes_async (the original await SceneManager.loadScene family, unloading resolves only after the unload tasks also finish)
- The loads that return a Promise in the original return awaitable handles that do not borrow the asset or scene. (The original await this.atlas.load(path) becomes the single line scene_context.with(|scene, engine| scene.atlas.load(engine, path)).await) ImageAsset (until decoded, fails if it cannot be decoded), TextAsset, JsonAsset, BlobAsset, BunchAsset, VisualAsset (only records the path and finishes immediately, like the original), the load_font family of FontAsset (FontLoadHandle, until added to the font list), load, load_from_bytes, load_from_asset of AudioAsset (AudioLoadHandle, until decoded. Immediate failures are seen through get_load_error of the handle instead of the Result it used to return), AssetLoader::load (failure list), load, load_data of SpriteAtlas (shared state that does not borrow the atlas), BuildInfo::load, SoundSystem::load_sounds, load_language_list, load_language, apply_language_setting of languagepack, load_ui_font, load_ui_font_text (UiFontTextLoadHandle) of uifont. Engine::register_font_face_when_loaded also returns a FontLoadHandle. A load already started can also be awaited with wait_for_load().await
- FbxLoadHandle, ImageDescriptionLoadHandle are IntoFuture. SkinnedModel::load_from_url_async, load_from_fbx_url_async (once fully downloaded, built with the GL of the engine polling the task). Timeline::load_from_url (the original loadFromUrl)
- SkinnedModel::add_animations_from_fbx_url returns an AnimationLoadHandle. When the await finishes, the clips have already been added, like the original. (The clip list is shared with the handle and clips are added in the order received) get_animation_list gives a borrowed value (Ref)
- languagepack::set_language_loaded_async_handler: an after-load function that returns a future. Like the original applyLanguageSetting, loading is in progress until that future finishes
- SpriteAtlas, like the original, keeps using the previous frames and page images while reloading, and finishes without frames if the JSON cannot be read or the format is unknown. (Until now it counted as loaded with empty frames)
- Engine::read_clipboard_text_async (the original readClipboardText, None if there is no text or access is denied), request_frame_capture_async (the original requestFrameCapture, PNG bytes)
- Screen fade: GameScene::fade_screen_async(on_dark), GameSceneBase::fade_screen_async::
. On the tick when it is fully dark, game_scene!, ui_scene! spawn on_dark as a scene task and run it up to the first await on the spot (where the original calls onDark), and it brightens when the future finishes. Scenes that implement Scene directly take it out with take_screen_fade_dark_starter after the base tick and start it - Added the SceneAny supertrait to the Scene trait (as_scene_any_mut, implemented automatically for every 'static scene). Used by SceneContext to downcast the scene to its own type
- Example asyncawait. 17 tests (executor and immediate first poll, waking, wake-order queue, waiting and setTimeout delay, asset and image handles, handles that borrow the engine, context access, panic on an escaped context, scene loading, keeping unloaded scenes alive, waiting for unload, scenes unloaded while loading, fade, language pack async functions, animation handles)
- README strengths and usage (scene lifecycle, original vs Rust table for asset loading, examples), technical notes, ARCHITECTURE layout, ownership structure and frame loop, chapter 9 (182 original files ported), chapter 10 (removed async from what truly cannot be matched, and put only with under deliberate design choices)
- Aligned the desktop more closely with the original running on Chrome. (Ported after confirming what Chrome does from the Chromium source, ARCHITECTURE chapter 10)
- Wayland page event Hidden: like Chrome on Linux Wayland, if a requested wl_surface.frame callback does not arrive for 3 seconds the window is treated as occluded and Hidden is emitted, and when callbacks resume, Visible and on_page_visibility_restored. Attaches wayland-client to the wl_display of the winit window as a guest connection and requests callbacks on its own queue. So that Mesa does not block inside eglSwapBuffers on an occluded window, Wayland sets the EGL swap interval to 0 like SDL and the engine waits up to 1/20 second for the previous frame callback. xdg_toplevel suspended is held by winit and cannot be received
- Windows touch keyboard: like Chrome on Windows, focusing or tapping a platform input field (use_dominput) with a finger or pen shows the touch keyboard through an InputPane bound to the window (debounced to 300 milliseconds), and hides it when focus leaves. The visualViewport shrinks by the height of the covered area, so the canvas shrinks with auto_resize_on_window_resize, and ignore_virtual_keyboard_resize prevents that on desktop too, like the original. macOS and Linux do not shrink the viewport, like Chrome
- preserve_drawing_buffer: like the original, when on, color is not cleared at the start of a frame. (The original applySettings clears only the stencil. Until now the Rust version always cleared on both web and desktop, so even when on, drawing did not accumulate over the previous frame) The desktop copies the finished frame and redraws it at the start of the next frame. Graphic::new takes preserve_drawing_buffer like the original constructor
- With auto_resize_on_window_resize off, the desktop also does not apply the canvas aspect ratio cap (max_canvas_aspect_ratio), like the original. (The original applies the ratio cap only when this setting is on. The desktop window is treated as a page whose canvas fills the window)
- Desktop Platform browser changed from Unknown to Chrome: the desktop version produces the same results as the original on Chrome, so browser branches in game code also take the Chrome path
- Developer tools memory fields: instead of (N/A), the desktop writes the system allocator heap (macOS malloc_zone_statistics, Windows process heap HeapSummary, Linux glibc mallinfo2) into the usedJSHeapSize, totalJSHeapSize fields. jsHeapSizeLimit stays (N/A) since there is no such limit
- Removed from the differences table: safe area insets 0 (also 0 on desktop Chrome, SetDisplayCutoutSafeArea exists only on Android), set_prevented_keys and right-click menu blocking (a desktop window has no default browser behavior to block, so it is the same as blocked), on-screen keyboard, Wayland Hidden, preserve_drawing_buffer, auto_resize_on_window_resize, browser name
- Reflection: does the same work as the original's runtime reflection (collectReflectedProperties, getReflectedProperties, saveByReflection, loadByReflection in uidocument.js, getComponentProperties in devtools.js) with code generated at compile time. A procedural macro does it, like Unreal UHT or Qt moc
- Made the repository a workspace and added the procedural macro crate macros/ (vanilla-engine-macros, syn, quote, proc-macro2). The engine re-exports it as vanilla::reflect, so games depend only on the engine. Generated code refers to the engine as ::vanilla, and inside the engine the same path works through extern crate self as vanilla in lib.rs
- #[vanilla::reflect] goes on the component's impl block and its impl Component block. Collects pub get_*, is_* getters without arguments and their matching set_* to generate the Reflect implementation. Keys are the original names (get_line_width → LineWidth), in definition order. If only one side has it, a compile error points to where to add it
- Getters of types that cannot be converted to a value are filtered out by autoref specialization, excluded from saving, and shown in the inspector as [type name]. #[reflect(skip)], #[reflect(transient)], #[reflect(name = "...")] on functions, #[reflect(base = field)] on blocks (chains to the field holding the original superclass part)
- core/reflection.rs: ReflectValue, Reflect, ToReflectValue, FromReflectValue, ReflectedProperty, ReflectedGetter, collect_reflected_properties, read_reflected_property, write_reflected_property, collect_reflected_getters. Component::get_reflection, get_reflection_mut (None by default). Enums that are strings in the original (TextAlign, TextBaseline, TextDirection, TextWrapMode, SpriteDrawMode, BlendMode, ScrollMode, ProgressDirection, ScrollBarAxis, SoftShadeShape, ButtonMotionStyle, ToastPhase, ParticleEmitterShape, ParticleRenderShape, ShaderSpriteEffect) convert to the same strings, and ButtonState to the original Enum number
- Applied to all 51 engine component types. Those with an original superclass (UIView for UIControl, UIScrollView, UIProgressView, UILabel, UIImageView, UIControl for UIButton, UISlider, UIDraggable, UIButton for UIToggleButton, UIScrollView for UISnapScrollView, Paint for Sprite, Sprite for ShaderSprite) chain with base, and their delegating functions were removed. TextAlign, isBold of ShadowText, the perimeter points of UIProgressRing, and isHorizontal of UIListView were moved to the original order
- UIDocument: like the original, types without write and read functions (propertyHandler) are written and read by reflection. (save_by_reflection, load_by_reflection, get_reflected_properties, the original REFLECTED_PROPERTY_EXCLUDE_NAMES) Removed the hand-written Outline, SoftShade, ShadowText, UIProgressRing serialization and switched them to reflection. The result matches the original saveByReflection down to keys, order and values. (Tested against JSON produced by running the original in node)
- Changed the public API: register_component_type(name, constructor function) is the original registerComponentType. (reflection) With write and read functions, register_component_type_with_handler, and widgets use register_widget_type(name, constructor function, content, self-attached types) and register_widget_type_with_handler
- Unregistered types that have reflection are also written by reflection, like the original. (type is the type name) Even for types with a write function, reflected properties that point to nodes are added and read separately, like the original saveNodeReferences, loadNodeReferences
- Components standing in for original node types (WorldNode subclasses): register_node_type, UIDocumentNode, UIDocumentNodeParts. A node with that component attached has that name as its type, the components and children the original node constructor created are written in the original document form, and on reading they are read as settings without being rebuilt
- register_editor_types: registers in one line the UIInputField, UIScrollBar (original node types) and UISnapScrollView found in documents saved by the original editor (tools/uieditor). Until now they were discarded on reading. UIInputField reads the background color, round size, placeholder and its color, font size, value and its color, and UIScrollBar reads the track and thumb colors
- ShadowImage is written in the reflection save form after imagePath
- UIScrollBar: get_track_color, get_thumb_color
- DevTools: the inspector calls and shows all get*, is* getters of a component, like the original getComponentProperties. (Names in the form of the original formatMethodName, values in the form of formatPropertyValue, numbers rounded the same as the original toFixed) Components without reflection show only the UIDocument save keys or the type name, as before
- README (how to use the reflection macro in nodes and components, technical notes, the macro crate table in external dependencies), ARCHITECTURE (layout, chapter 9, the reflection line in chapter 10 differences between the two engines)
- Made desktop audio decoding the same as the original (Chrome decodeAudioData). (platform/audio/decode)
- Chrome 158 decodes FLAC, MP3, PCM, Vorbis with symphonia 0.6, Opus with libopus, and AAC with FFmpeg. The engine also turns off kira's decoding features and calls symphonia 0.6.1 directly to use the same decoders (with the same features Chrome enables), and decodes Opus by registering opus-pure, a Rust port of libopus, in the symphonia codec registry. The webm (Opus) produced by webm.cjs now plays on desktop
- Containers are also handled by symphonia demuxers (wav, ogg, mkv(webm), isomp4(m4a), flac, mp3, adts), and the format is identified by content rather than extension or type
- Discards the same leading and trailing samples that Chrome discards based on FFmpeg timestamps and trim values. (Opus pre-skip, the portion caused by FFmpeg rounding the webm CodecDelay to ms, DiscardPadding, MP3 LAME delay, Ogg granules and single-page Vorbis, m4a edit lists and iTunSMPB, AAC last packet length)
- Integer samples are converted with Chrome's formula (positives divided by the maximum, negatives by the minimum, 16-bit FLAC as 16 bits), and MP3 is clamped to -1 ~ 1. Opus output gain and the Chromium channel order for 5.1 are also the same
- Ported Chromium SincResampler to resample to the original DECODE_SAMPLE_RATE (44100). (The same 32-tap kernel and length computation as Blink, with summation order matching the NEON, SSE, AVX2 paths Chrome selects)
- Downmixes to 1 or 2 channels by the WebAudio speaker rules. (Quad and 5.1 by the spec formulas, others by the first two channels. Files with 3 or more channels now play too)
- Compares 21 test sound files (tests/assets/audio, all a few KB) against Chrome 158's results (chrome_decode.json written by chromedecode.cjs). Lengths and channels all match, FLAC, MP3, PCM, Vorbis match down to the sample, and Opus, AAC are within about 1e-7
- Remaining difference: HE-AAC (SBR, PS) and AAC with 3 or more channels are not supported by symphonia 0.6.1, so they could not be decoded on desktop. (Chrome decodes them with FFmpeg) (Fixed later: they are now decoded with oxideav-aac, see the HE-AAC entry below)
- 7 crates added: opus-pure, symphonia-format-mkv, rustfft (enables opt-simd of symphonia like Chrome so the FFT matches) and its dependencies primal-check, strength_reduce, transpose, num-integer. None removed (the engine directly uses the symphonia kira was using)
- "data:" URLs: desktop Engine::load_audio_asset, request_asset_bytes, request_asset_bytes_into, load_image decode and read data: URLs. (data: sounds inserted by the timeline editor now play on desktop too) Moved base64 and percent-encoding decoding from the timeline to base/dataurl.rs. Fixed the web prepending the base URL to data: URLs too when asset_base_url was not empty, which made them fail to load
- Switched desktop audio output from kira to an engine mixer on top of cpal. (platform/audio/mixer.rs) The original sound API and the Rust API (AudioPlayer, AudioBus, get_gain_node, BeepPlayer) are unchanged
- Builds the same WebAudio graph the original builds. AudioBufferSourceNode → player GainNode → (once a nonzero pan is first set) StereoPannerNode → bus GainNode or output, beep oscillator → output. Renders in 128-frame quanta
- The computation is the same as Chrome. The source is ported from audio_buffer_source_handler.cc (start position rounded with 1024x oversampling, a straight copy at rate 1 and linear interpolation otherwise, linear extrapolation at the end, whole-buffer looping, playbackRate as f32 like AudioParam). Pan uses the formula from stereo_panner.cc (mono x = (pan + 1) / 2, stereo with pan <= 0 L += R cos, R *= sin), GainNode multiplies, mono goes to both sides by the speaker rules, and the output is clamped to -1 ~ 1. kira differed from Chrome with 4-point cubic interpolation and a sqrt pan law
- Pan and volume take effect from the next quantum. (Pan in the kira version applied from the next play) Beeps render at the context (device) sample rate
- The context clock is the rendered time. (The original currentTime, 128 / sample rate seconds per quantum) Nothing renders while suspended, so sound and clock stop in place
- A management thread holds the stream, and when the device is removed (or, except on macOS, when the default device changes) it reopens with the same mixer. (Same as kira did)
- AudioContext (desktop) belongs to the engine mixer and exposes sample_rate(), current_time() under the same names as the web AudioContext. AudioBuffer exposes duration(), length(), number_of_channels(), sample_rate(). (This changes the public API: until now they were kira's AudioManager, StaticSoundData)
- Players created from a bus and players given an output directly keep the bus node alive while connected, like the original WebAudio
- Added tests comparing five graphs (sources at the same and a different sample rate, rate with loop and start position, mono and stereo pan and 0, bus, mixing) against Chrome 158 OfflineAudioContext results (chrome_mixer.json written by tests/assets/mixer/chromemixer.cjs). They match within 1e-6
- 8 crates removed: kira, atomic-arena, crossbeam-utils, glam, mint, pastey, rtrb, triple_buffer. The only direct dependency is cpal (the same cpal 0.18 kira used, realtime feature)
- ToonScreenOutline: rebuilt the screen-space outline in the standard form of real-time toon rendering. (Same shaders and values as vanilla.js)
- Detection: in the line buffer (normal, line id, depth), each edge between a pixel and its four direct neighbors is tested once, and the line is placed at the middle of that edge. Until now crease lines were judged from the normal at a single point creaseRadius away, so both sides of a crease formed bands, and half-size buffers produced dotted lines, parallel second lines, and bands inside the silhouettes of curved surfaces
- Depth: reconstructs two neighboring pixels to view-space positions and detects occluded silhouettes by their distance from each other's tangent plane. Twice the pixel size at that depth is added to the threshold
- Widening: propagates the distance to edge segments with jump flooding. (log2 steps, outline and crease lines separately) The 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 edge. Lines do not break even with a reduced line buffer
- Per model: has_screen_outline of ToonLineDrawOptions (false only occludes), has_crease_line, is_mirrored (None uses the determinant)
- read_jump_flood_steps(distance): list of jump flooding steps
- ToonDrawOptions: line_id (None uses the order in the draw queue + 1), has_screen_outline, has_crease_line. (Per-model options for the screen-space outline, ToonRenderer does not read them)
- ToonDrawQueue: set_screen_outline(Option<&'a mut ToonScreenOutline>), has_screen_outline(). When set, draw and draw_with_matrices draw the opaque items into the line buffer before the bodies, and blend after the outline shells, before the AfterOutline stage. If there is a screen rectangle, that rectangle is used as the drawing area
- Fully aligned reflection with the original. (Tests compare against expected values extracted by running the original in node, and generate.mjs in src/ui/testdata/uidocument regenerates them)
- Reflection calls &mut self getters (get_reflected_value_mut, collect_reflected_getters_mut), getters that take the tree (collect_reflected_getters_in_tree), and setters that take the tree and a value (set_reflected_value_in_tree). When reading, UIDocument briefly takes the component out of the tree (NodeTree::with_component_at_mut) and calls tree-taking setters on the spot like the original, and to_json_text_mut, serialize_node_mut also write &mut self getters. The DevTools inspector reads &mut self getters in tick and calls tree-taking getters when drawing
- Macro: pairs are formed by key (baseName) like the original, and getting and setting are each looked up separately starting from the most derived type. Added #[reflect(unsaved)] (kept in the list but excluded from saving) and #[reflect(after = "...")] (places a getter from the impl Component block at its position in the original class body)
- The inspector getter list and the reflected property list match the original. Removed Rust-version overrides not in the original classes (such as isTickNeeded), and moved Text, RichText, UILabel, UIButton into the original definition order. They show under the original names, such as getTargetButton (tree) of UIHitArea, FontFace of ShadowText, and BakeCanvas of SoftShade, ShadowText, ShadowImage
- register_editor_types registers 35 engine component types and 12 node types (FloatingText, TouchEffect, UIConfirmWindow, UIContextMenu, UIDialog, UIDropdown, UIInputField, UIScrollBar, UISpinner, UIToast, UIWindow, UIWindowLayer), like the original editor. register_node_type_with_match distinguishes node types that use the same component (UIConfirmWindow is UIWindow plus a behavior)
- UIDocument reading: document values go into the components and children built when a node type or widget attaches, and into components attached together via require, without rebuilding them. The embedded Sprite of UIImageView is written and read as a following Sprite, like the original. A hidden UIToast is written and read as active false, like the original
- NodeTree::add_component, WorldNode::add_component reserve the component's slot first, like the original, and place components added during attach after it
- Fixed to match the original: the title and message of UIConfirmWindow are UILabel. UIWindow disables the node in create rather than on attach. FloatingText sets the pivot and anchor to the top left on attach. The UIDropdown arrows use the original characters (▴, ▾) and font size. The UIScrollBar thumb starts as an enabled zero-size rectangle like the original thumb node. UIInputField writes the text label size laid out by tick to the document. UIImageView holds the image path separately from the embedded Sprite. UISpinner dot positions are computed in f64 like the original
- DevTools: components with neither reflection nor registration show a "no reflection" line to flag the missing macro
- What the browser used to provide, part 2 (the remaining differences that could be closed)
- LocalStorage: keeps two keys that differ only in unpaired surrogates (different keys in the original) separate. Previously they became one key on the Rust side, so on desktop one of two such keys saved by the original was lost on reading and also removed from the file on the next write. Added get_keys_code_units, get_item_by_key_code_units, set_item_by_key_code_units, remove_item_by_key_code_units, contains_key_code_units, which also address keys in their original code units. A Rust string key refers to the key that is exactly that string if there is one, otherwise the first of the unpaired surrogate keys that appear as that string. get_keys yields keys that appear as the same string only once
- PaneStyle (desktop): reads the CSS that the original's tools use. Flex layout (flex-direction column, flex, flex-grow, flex-shrink, flex-basis following the length computation of CSS Flexbox, justify-content values such as space-between, align-items with stretch by default), min and max sizes, right and bottom, per-side padding, margin and border, line-height, text-align, overflow (clips overflowing children, auto and scroll can be scrolled with the wheel and by dragging the thumb, and hand the wheel to the parent once they reach the end, scrollbar-color). Elements with auto size are measured by adding up their children's sizes. PaneElement::get_scroll_offset, set_scroll_offset
- UIInputField::set_multiline: multi-line input like Chrome's textarea. Splits at newline characters and by width (pre-wrap, break-word, ICU4X Unicode line breaking on desktop), Enter inserts a line break, Up and Down (keeping the horizontal position), Home and End (visual line), Ctrl + Home, End (Cmd + Up, Down on Mac), PageUp, PageDown (Blink's 87.5% distance), tab stops, selection and dragging, composition underline, wheel and thumb drag scrolling, scrolling to follow the cursor. set_line_height, set_tab_size, get_scroll_top, set_scroll_top. The web DOM input is a hidden
- TextInputKey: Up, Down, PageUp, PageDown, DocumentStart, DocumentEnd. TextInputFieldState.is_multiline. Desktop single-line DOM input fields move Up and Down to the start and end of the text like Blink, and turn line breaks in inserted text into spaces (trailing line breaks are removed). Cmd + Left, Right on Mac go to the start and end of the line
- Canvas2D, Path2D: stores arc, ellipse, arcTo, roundRect as Skia conics, like Chrome. (Blink canvas_path.cc angle adjustment and degenerate ellipses, Skia SkPathBuilder::arcTo, SkConic::BuildUnitArc, SkRRect radius reduction and addRRect point order) On desktop, filling subdivides them into quadratic curves within 0.25 device pixels, like Skia's CPU raster. (Previously a cubic Bezier approximation)
- Canvas2D, Path2D: roundRect accepts elliptical corners. (CanvasRadius::Elliptical, (x, y), DOMPointInit in the original) The web Path2D calls functions of the browser Path2D such as arc and roundRect directly, like the original
- Canvas2D: also draws engine Images that released their CPU pixels when uploaded to the GPU. (Reads back the texture the image remembers, previously reported and skipped)
- Input fields (desktop, fields whose DOM input is pressed directly): like Chrome desktop touch, a 650ms long press with a finger (Chrome aura long press 500 + show press 150, movement tolerance 15 DIP) selects the word at that spot and shows touch selection handles (shaped like Chrome's vector icons, dragging them changes the selection) and the quick menu (Cut, Copy, Paste, "...", 100ms after release, centered above the selection). If nothing is selected and there is nothing to paste, it is the engine context menu. On Windows this is decided on release (Blink context_menu_on_mouse_up). Keys, mouse presses and the wheel dismiss the handles and menu. "..." shows the engine context menu at the top center of the selection
- The desktop now decodes HE-AAC v1 (SBR), v2 (PS) and AAC with three or more channels the way Chrome does. (platform/audio/decode/aac.rs)
- AAC-LC up to two channels is still decoded with symphonia (identical to Chrome down to PNS noise); what symphonia does not accept (SBR or PS written in the ASC, three or more channels) and streams that carry SBR only in the payload (such as HE-AAC in ADTS, detected by whether the first packet doubles the sample rate) are decoded with oxideav-aac
- oxideav-aac (MIT) is a pure Rust decoder written from the ISO/IEC 14496-3 and 13818-7 specifications. The commit history of its public repository (OxideAV/oxideav-aac) records it being written clause by clause from the specification, with no trace of porting LGPL code such as FFmpeg. The other candidate, rusty_aac (Apache-2.0), has no public repository or commit history for its decoder source (the crate's repository URL points to another repository that uses it), so its origin could not be verified and it was not used
- The floating-point output before integer rounding (set_float_pcm_capture) is not in the crates.io release 0.1.7, so the dependency is pinned to repository commit eac68f3. It will switch to crates.io when the next release is out
- Added six test sounds (HE-AAC v1 m4a and adts, v2 m4a, 5.1 AAC m4a and adts, stereo AAC using PNS), and 27 files are now compared with Chrome 158. Lengths and channels match and samples are within 1.5e-7
- Remaining difference: when PNS is used in AAC with three or more channels, the noise samples of that band differ from Chrome. (The specification does not define the random number generator; matching it would require porting FFmpeg's generator)
- Four more crates: oxideav-aac, oxideav-core, thiserror, thiserror-impl
- The x86_64 summation order of resampling (AVX2 with FMA, SSE) was written to match Chrome, but the expected values were generated on an Apple silicon Mac and it has not been run on real x86 hardware
- SoundSystem's effect fade-out, playing only the beginning, music crossfade and bus volume following now use AudioParam automation like the original. Until now both web and desktop computed the same formula on every update and set the volume
- Same calls as the original soundsystem.js: effects assign gain.value and then setValueAtTime, linearRampToValueAtTime(0), source.stop(when); fade-out is cancelScheduledValues, setValueAtTime, linearRampToValueAtTime(0), stop(when) from the current gain.value; music is setValueAtTime(0), linearRampToValueAtTime(volume) and fading down from the current value with stop(when); the bus is setTargetAtTime(volume, now, 0.05). Finished sounds are removed from the list by update, in place of the original onended
- On the web these go straight to WebAudio AudioParam and AudioBufferSourceNode.stop(when). (A stop received while the context is being resumed is applied at start)
- The desktop mixer's GainNode gain is now an AudioParam. (platform/audio/audioparam.rs, ports event insertion, removal of past events, pulling in new events, linear and exponential ramps, set target, ramps after a target and cancellation from Chromium audio_param_handler.cc; on x86_64 the same four-lane SSE grouping as Chrome) Quanta with automation are multiplied per sample, quanta without it by a single value, and automation advances even without a source. A source's stop(when) cuts at the frame that time rounds up to. The clock is rendered frames / sample rate
- Added apply_gain_automation, get_gain_value (reading the original gain.value) and stop_at_time, used inside the engine, to AudioPlayer and AudioBus. (The public API is unchanged)
- The Chrome 158 OfflineAudioContext graphs in the mixer tests went from five to nine. (Playing only the beginning with bus setTargetAtTime, fading out from the current gain.value after a suspend during rendering, music crossfade, exponential ramps with ramps after a target and cancellation) All match within 1e-6
- BeepPlayer's desktop tone is now computed in the mixer with exactly the graph of the original playTone. Until now the same envelope and waveform were drawn with formulas and the samples mixed
- Graph: OscillatorNode(type, frequency.setValueAtTime(frequency, start)) → GainNode(setValueAtTime(0.0001, start), linearRampToValueAtTime(peak, end of attack), setValueAtTime(peak, start of release), exponentialRampToValueAtTime(0.0001, end)) → output, start(start), stop(end + 0.01). Times are the context clock at the time of the call plus the delay (added in the same order as the original; the web version uses the same BeepSchedule)
- OscillatorNode ports Chromium oscillator_handler.cc, periodic_wave_handler.cc and the per-CPU kernels. (platform/audio/oscillator.rs) Band-limited tables (2048, 4096 or 16384 entries depending on the sample rate, one per third of an octave, normalized to the peak of the first table), start and stop frames (rounded up, starting between samples), a step per sample (a-rate) in quanta where frequency is automated and one per quantum (k-rate) otherwise, and two-point, three-point and five-point interpolation are computed in the same order and with the same f32 and f64 precision as Chrome. Four-sample groups use a NEON version on aarch64, an SSE2 version on x86 and a scalar version elsewhere
- Automation times are pulled in with the clock at the time of the call, like the original main thread, and pulled in once more to the current quantum before rendering. (AudioParam::apply_automation_at_call_time) Tables are built once per sample rate, like the context
- Added a test comparing, sample by sample, nine cases of the original playTone graph in Chrome 158 OfflineAudioContext (four waveforms, a preset sequence, starting between samples, calling during rendering, sample rates 22050 and 96000, three-point and five-point interpolation, close to Nyquist). (chrome_beep.json written by tests/assets/mixer/chromebeep.cjs) All are within 1.2e-7
- The x86 SSE2 version was written to match Chrome, but the expected values were generated on an Apple silicon Mac (arm64 Chrome) and have not been compared with x86 Chrome. (On a different CPU the test uses 1e-4)
- Rebuilt toon shading in the standard form of real-time toon rendering. (Same shaders and values as vanilla.js)
- Shade ramp: multiplies the received light share (half Lambert by default) by the shadow and looks it up in the ramp to pick the color. Each step has a position, linear color and softness, and boundaries are anti-aliased with fwidth so they have no stair steps. Shadows come in as the shade color
- ToonLightSet::set_shade(ToonShade { step, feather, color, second_step, second_feather, second_color, is_half_lambert }), set_shade_ramp(positions, colors, softness, half Lambert), clear_shade_ramp, set_ramp_texture(Option
, half Lambert) - set_band_count, set_band_ramp build the same ramp
- ToonLightSet::set_shade(ToonShade { step, feather, color, second_step, second_feather, second_color, is_half_lambert }), set_shade_ramp(positions, colors, softness, half Lambert), clear_shade_ramp, set_ramp_texture(Option
- Per light: the sun receives the full ramp color, and the fill light, point lights and spotlights receive the brightness step of the ramp
- Highlights: set_specular(intensity, exponent, softness, color), for both the sun and point lights. Rim light: set_rim_light(color, power, softness, sun-side mask), added rather than multiplied by the base color
- Spotlights: direction of ToonPointLight (a spotlight if Some), inner_cone_angle, outer_cone_angle (default 0 and π/4)
- ToonDrawOptions: receives_shadow, shade_offset, specular_scale, rim_scale, matcap_texture, matcap_strength, matcap_blend (ToonMatcapBlend), outline_color, outline_width_scale
- shadeOffset, specularMask, rimMask in the surface chunk, rim, sunLevel in the light chunk
- Transforms normals by the inverse transpose. (Corrects the lighting and screen-space crease lines of stretched and squashed models)
- Default lights: sun [0.84, 0.8, 0.74], sky [0.3, 0.33, 0.42], ground [0.17, 0.16, 0.15]
- Shade ramp: multiplies the received light share (half Lambert by default) by the shadow and looks it up in the ramp to pick the color. Each step has a position, linear color and softness, and boundaries are anti-aliased with fwidth so they have no stair steps. Shadows come in as the shade color
- ToonRenderer: pushes out the shell outline in the shader. (Base position and push direction, outline_color, outline_width_scale, set_outline_distance_scale, get_outline_distance_scale) Exports read_view_rotation, read_outline_vertex_data
- ToonMatcapBlend: how the matcap is blended. (Multiply, Add)
- Exports ToonShade, ToonShadeRamp, ToonRimLight, ToonSpecular at the crate root
- Filled in the header comments of the files in the toon folder. (All functions and public fields)
- Filled out toon rendering to the level Unity and Unreal provide by default. (Same shaders and values as vanilla.js)
- ShadowMap: restores the previous texture and framebuffer bindings when built. (Building it after models left the depth texture on a unit and caused INVALID_OPERATION) When the light travels almost straight down or up, the up direction becomes the z axis. (The light matrix used to break)
- ShadowAtlas, ShadowAtlasLight, ShadowAtlasLightSource, ShadowAtlasTile, SHADOW_ATLAS_MAXIMUM_LIGHTS: shadows of point lights (six cube faces) and spotlights (one perspective tile) as tiles in one depth texture. update_lights(&light_set.read_shadow_light_sources()). The receiving position is pushed toward the normal by (1 + 3 x (1 - dot(N, L))) tile texels to prevent shadow acne
- ToonRenderer: set_local_shadows(Option<&ShadowAtlas>, strength), begin_shadow_atlas_pass, set_shadow_atlas_tile, set_outline_fade_distance, get_outline_fade_distance, set_light_color_usage, set_shade_rim_light. ToonDrawQueue::draw_local_shadows
- ToonPointLight: casts_shadow, shadow_near (default false, 0.05). When building it with field names, add ..ToonPointLight::default()
- ToonLightSet: set_light_color_usage(ToonLightColorUsage), set_shade_rim_light, get_shade_rim_light (ToonShadeRimLight), read_shadow_light_sources. Rim, matcap and shell outlines now also multiply by the sun color by default. The previous look is ToonLightColorUsage { rim: false, matcap: false, outline: false, ..Default }
- ToonDrawOptions: outline_offset_z, angel_ring_texture, angel_ring_color, angel_ring_offset_u, angel_ring_offset_v, is_angel_ring_alpha
- Second UV: ToonGeometry.uvs1, ToonMeshArrays.uv1_data, the last argument uvs1 of add_triangles_with_uvs (changed the public API, None without a second UV), read_glb_arrays reads TEXCOORD_1. read_uv_data
- Texture units: point light shadows 0, angel ring 7, materials 8 ~ 15. TOON_MAXIMUM_MATERIAL_TEXTURES 9 → 8. begin_frame records unit 0 and end_frame restores it
- ToonScreenOutline: removed the stair steps of half-size buffers. The line buffer and seeds are at drawing area resolution, only the jump flooding runs on a reduced buffer (a gather pass collects the seeds), and seed positions are drawing area pixel coordinates. set_resolution_scale is the fraction (drawing area x fraction) for the line buffer and the widening buffers. ToonLineTarget: seed_framebuffer, seed_texture, jump_flood_framebuffers, jump_flood_textures, jump_flood_index, jump_flood_width, jump_flood_height. read_program_sources gives five
- tools/apidoc (workspace crate vanilla-engine-apidoc, uses only syn and serde_json): extracts the API documentation data docs/api/
.json from doc comments. Adds the class kind (struct, trait, type), traits and counterpart to the same data format as vanilla.js tools/apidoc.cjs. --check (format check and counts, comparing the ko and en guides), --missing (ko text not in the translation table), --gaps (places where documentation is empty), --counterpart (pairing with the vanilla.js data by name). since is decided by comparing against the source at the v0.3.2 tag. Usage is in tools/TOOLS.md - docs/api/0.4.0.json (216 modules, 496 classes, 4930 members, 354 functions and constants, 89 enums), the English translation table docs/api/translation.en.json, and docs/api/counterpart.0.4.0.json, the table pairing entries with the same items in vanilla.js (also used when the vanilla.js side data fills in its Rust counterparts)
- Angel ring: rotates the UV back by the camera roll. (Same computation as vanilla.js, read_camera_roll) The ring stays attached to the head even when the camera is tilted
- Light intensity limiting: ToonLightSet::set_light_intensity_limited, is_light_intensity_limited (set_light_intensity_limited on the renderer too). Same computation as Limit Light Intensity of the Unity toon shader, on by default. The previous look is set_light_intensity_limited(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 set_light_intensity_limited(false). The intensity of colors with light color usage turned off and the sun color of shell outlines also match the Unity toon shader
- ShadowAtlas::new(gl, resolution, tile resolution): like the Unity URP default, aims for 1024 per tile and halves the tile size if they do not all fit. DEFAULT_SHADOW_ATLAS_RESOLUTION (2048), DEFAULT_SHADOW_ATLAS_TILE_RESOLUTION (1024), get_tile_resolution. (new gained one argument)
- Bone matrix uniform block (same as the original's JointBlock; 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). 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/uniformlimit.rs checks in the hidden-window GL that every program the engine builds stays within the limits (256 vertex, 224 fragment). The screen is unchanged.
Performance
- Toon program variant prewarm (same as the original 5b8ae8c, 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. Added ToonRenderer::prewarm_draw_queue(gl, queue). It builds, without drawing and with the same keys the draw uses, the variants the items in a draw queue will use (material, body feature bits, ambient occlusion body, outline, shadow depth). With GL_KHR_parallel_shader_compile (the web uses the same extension) it only hands off compiling and ToonProgramPrewarm::step finishes the compiled ones up to three per step each frame so the main thread is not blocked; without it, it builds inside the call. The returned ToonProgramPrewarm tells the end with is_ready() and wait(gl, renderer) (finishes the rest on the spot). Drawing before it finishes is fine, and a variant not built yet is built on the spot as before. ShaderProgram gained ShaderProgram::create_deferred, is_deferred(), is_build_complete(gl), finish_build(gl) and the static is_parallel_compile_supported(gl) (default behavior unchanged). A place is left to attach the variants of the instance layout once the draw queue gets a way to add instance buffers. Test: without prewarm the first draw frame builds 6 programs and after prewarm 0, with a byte-identical picture. (Mac GL has no parallel compile extension, so the handed-off path is run too with a test-only switch)
- Toon prewarm (same as the original jsprewarmwait): fixed prewarm possibly not advancing on a loading screen that only skips frames while waiting for the prewarm to finish without drawing (in the original, 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). Handed-off compile and link commands may not flow to the GPU 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 ToonRenderer::prewarm_draw_queue and prewarm_draw_queue_with_options now call GlContext::flush after handing off, and ToonProgramPrewarm::step calls it every step while work remains. ShaderProgram::is_build_complete no longer asks again once it has seen completion. The picture and the public API are unchanged. This machine (Mac GL) has no parallel compile extension, so a test forces the hand-off path and checks the flush counts (at least 1 after hand-off, 1 per remaining step) and that drawing after skipping 0, 1, 2 and 45 frames without drawing still produces pixels. It was not run on a machine with the real parallel extension (Windows, Linux).
- Toon body shader skips the point-light loop body outside the light radius (same as the original): 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.
- Toon frame block ToonFrame (same as the original jsubo, std140, binding 2, 172 floats): camera, light, shadow, outline distance, point light shadow, and the ambient occlusion origin and direct lighting strength, which were uploaded per program as separate uniforms, now go in one block. The slot order and the shader block declaration are identical to the original character by character (a test compares with the original file). The solid, outline and depth programs read the same block at binding 2; once per pass (frame_serial) the values are written once, then if a buffer holds the same values it is bound (no upload), and new values are written with buffer_sub_data into a buffer not written for eight begin_frame calls (a new one is created if none is free). Without a shadow or point light shadow, the light matrix, shadow strength and atlas slots keep their previous values (same as the original). The pictures of the room corner, ambient occlusion, highlight, style, showcase, post process and view examples are byte-identical to before.
- Toon material block, automatic instancing and line pass batch slots (same as the original f3f18e5, 5221c43, 1ffc38b, 90e3286 and 3fd1a61, in the shape of Unity SRP Batcher UnityPerMaterial, GPU instancing and Unreal auto-instancing): 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) now live in one std140 uniform block ToonDrawMaterial (binding 0, 44 floats), and the six outline shell values (outlineColor, outlineLightColor, outlineWidthScale, outlineOffsetZ, alpha, premultipliedOutput) in ToonDrawOutline (binding 1, 12 floats). Field order and the shader block declarations are identical to the original down to the letter. Blocks with the same values are shared (FNV-1a hash and bit comparison), each draw does one bind_buffer_base (skipped when already bound), and at 1024 blocks per kind the least recently used block is evicted clock style and the new values are written into its buffer with buffer_sub_data (no buffer is deleted or created). ToonDrawQueue sorts with the material block as the fourth key and merges consecutive opaque plain meshes with the same mesh, material block, winding and draw options (everything equal except line id, group, depth prepass, shadow casting and culling; meshes with joint matrices or on_before_draw, and transparent ones, are excluded) into one instanced draw (body, outline shell, shadow depth, and each point light shadow tile). Batch slots (a buffer and per mesh vertex arrays) are handed out in the same order every frame, are not re-uploaded when the matrices equal the previous frame, and the body and the shell share a slot. ToonScreenOutline also batches the line id drawing by mesh and line options (accept_mesh culls and adds the focus distance, then draw_mesh_batch), keeps its own batch slots and skips the upload when equal (the id goes in tint x). The instanced, instanceLineIds, skinned and lineFlags uniforms of the line pass are uploaded only when they change. The screen is byte for byte the same (the screen hash equals the code before the change) and the draw calls of the same scene drop from 28 to 4. The instance count list of the same scene as the original toonautoinstancechrome is identical ([11, 6, 6, 6, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2]).
- Toon screen outline thin line path, resolution scale and clearing before buffers (same as the original bf61a70, 2d1dad4, 1dce73d, 12f654c and 8ade0ed, the same shape as the Unity URP screen-space outline, looking at the neighbors inside the radius at once): up to a width of about 3.24 pixels (2 x sqrt(4.5) - 1), ToonScreenOutline skips the jump flooding (seed, gather and three widening passes). It picks a buffer (R8UI, one byte) holding the first boundary side of the contour and crease lines per pixel in the same order as the seed pick, and the blend reads the seeds of the 3 x 3 pixels around in the same order as the last jump flooding step (nine reads, a branchless pick) to work out the coverage from the distance to the nearest one. The full-screen passes after the line buffer drop from six (seed, gather, three widening, blend) to two (mask, blend), and the buffers written per pixel drop from three RGBA16UI (24 bytes) to one R8UI (1 byte). Thick lines and the line color table keep the current path, and the seed buffer and widening buffers are created the first time a thick line is drawn. set_resolution_scale now shrinks every buffer before the blend (line buffer, mask, seed, widening buffers) to the drawing area x the scale (before, only the widening buffers). The default 1 leaves the picture byte for byte the same. Below 1, a thin line (width x scale at most about 3.24 line buffer pixels) works out the coverage (an RGBA8 buffer multiplied by intensity and the id color, get_line_target().coverage_texture) once at the line buffer resolution, and the last blend reads it bilinearly once (nine reads become one). Thick lines run the jump flooding at the line buffer resolution and measure the distance in drawing area pixels when blending. The line width (set_width) is in drawing area pixels at any scale. Passes that overwrite a whole buffer (mask, seed, gather, widening, coverage) clear the buffer first (clear_buffer_u32_slice, clear_buffer_f32_slice) so a tile GPU does not load the old contents (the original replaced invalidateFramebuffer, which added 10 to 25 ms per frame on Safari, with clearing, and Rust has no invalidate so only the clear at the same place is there). The shader text is the same as the original down to the letter. On the same room scene in both engines (640 x 360, widths 2, 2.62, 3, 6 x scales 1, 0.75, 0.5, with the id color table, fifteen pictures) scale 1 differs in 4 pixels (a body shading band unrelated to the outline) and scales 0.75 and 0.5 differ in 0 pixels (before the fix, 5792 to 8176 pixels at scale 0.5, largest difference 211). The original line buffer batch slots (3fd1a61) are not ported because the Rust ToonDrawQueue has no automatic instancing batches yet.
- Subtree draw skipping (same as the original jssubtree set, scene graph bound dirtying like OSG dirtyBound and Godot item_rect_changed): every node keeps the union of its own drawing and the bounds of its enabled, visible children (subtree draw bounds, in node content coordinates), recomputed only when something changed, and drawing skips the node and its descendants as a whole when those bounds are outside the screen and the active clip (tick still runs). While computing, a parent writes each child's bounds in parent coordinates so children are culled before their transform is applied, and with many children the visible child range is narrowed by binary search. Transform, node and component setters report dirtiness only when the value changes (not for the same value) and NodeTree spreads it to the ancestors before drawing. A component that does not report its bounds or a node that draws gizmos keeps its ancestors from being skipped. Components that draw nothing (draw not overridden, like ButtonMotion and UINode) count as drawing nothing (the reflect macro generates Component::is_draw_overridden). Added Graphic::set_subtree_culling_enabled (on by default), is_subtree_culling_enabled, get_last_frame_culled_subtree_count, add_culled_subtree_count, read_local_visible_bounds, NodeTree::read_subtree_draw_bounds, read_parent_draw_bounds, draw_children, WorldNode::mark_draw_bounds_dirty, mark_parent_draw_bounds_dirty, get_last_drawn_frame_number, ComponentBase::mark_drawn_rect_dirty, mark_all_drawn_rects_dirty (the engine calls it when a font is registered), get_drawn_rect_generation and Component::mark_drawn_rect_dirty. A node not drawn last frame gets its text bake scale as if drawn for the first time. UILineChart reports a drawn rect up to the lines of out-of-range values, UIBarChart up to overflowing bars, UISlider up to the thumb circle (before the fix, out-of-range lines of a line chart whose content area was off screen disappeared from the screen). The subtreecull example (SUBTREECULL_CHECK=1) captures the scenes of the original tests and benchmark with culling on, off and all off and compares screen bytes and per-frame draw counts. In the engine scene of the original benchmark: culled subtrees with culling on 231 (original 231), nodes with a transform applied with culling off 2164 (original 2164), on 79 static and 85 scrolling (original nodes 79 and 85, the original count also includes one clip of the scroll view); the Rimminer settings window scene (SUBTREECULL_SCENE=rimminer) applies a transform to 59 nodes static and 55 scrolling with 281 culled subtrees (original 59, 55, 281), and 1274 with culling off (original 1274). Added LayoutVariable::set_value_changed_event and get_value_changed_event (LayoutVariableEvent, called only when the value differs, original setValueChangedEvent). The Rust UINode writes the solved values into the node transform, so the transform setters report dirtiness. ShadowImage reports a generous rect with twice the blur, the bake padding and the shadow offset regardless of baking and bake scale (same as the original).
- Graphic no longer remembers bindings and 2D state separately and compares against the GL state cache before drawing (same as the original db99208, the three.js WebGLState form): removed the program last made current, the textures of units 0 and 1 and of the batch units, and the color write mask that Graphic remembered by itself; it now sets them only when the state cache differs. Right before a draw it matches blending (on, FUNC_ADD, the factors of the current blend mode), depth test and face culling off, scissor off unless it is the clip scissor, and a full drawing buffer viewport against the state cache (apply_draw_state), and the unbatched path also compares and binds the default vertex array and vertex buffer. The state cache remembers the ARRAY_BUFFER binding (added GlContext::bind_buffer, create_buffer, delete_buffer; the check mode also compares ARRAY_BUFFER_BINDING) and gains comparisons that do not ask GL. So when a game changes blending, depth, face culling, scissor, viewport, vertex array, vertex buffer, or the active unit through get_gl outside run_external_pass and comes back, the next 2D draw is right (before, batched drawing got the blend factors and equation, depth, face culling, scissor, and viewport wrong, and unbatched drawing also the vertex array and vertex buffer). restore_render_state no longer touches the stencil clip, like the original, and run_external_pass restores the stencil clip state at the end (also when there is no shader clip). The web build forgets the state cache when the GL context is lost or restored.
- GameSceneBase loading time and skipping moved to the engine's frame slot (same shape as the original df379ce): the loading gate (minimum display time and touch skipping, counted from the first loading frame if called before the first frame) is held by SceneBase and updated every frame for each loading scene by the engine (after time advances, before the loading screen's draw_on_load) with the engine clock and input. Until now it was updated only inside GameSceneBase::draw_on_load, so a scene that implements Scene directly and holds a GameSceneBase without calling the base draw_on_load stayed on the loading screen without an error (game_scene! and ui_scene! always call the base, so they did not stall). The gate opens before drawing, so initialize may be called one frame earlier than before. update_loading, begin_loading, get_loading_progress and is_load_touched_to_skip are used as before.
- Fewer shadow redraws (same as the original 4dabf62 and 2eefc5a, in the style of Unity HDRP's per-light shadow update mode and Unreal's cached shadow maps): ShadowMap and ShadowAtlas gain set_update_mode(ShadowUpdateMode, frame count), get_update_mode, get_update_interval and request_update. ShadowUpdateMode is EveryFrame (everything every frame, the behavior so far), OnChange (default) or Interval (everything every N frames, frames in between reuse the previous shadow). With OnChange, ToonDrawQueue::draw_shadows and draw_local_shadows 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 matrix 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 over the baked target copied into the target (blit_framebuffer). It rebakes when a baked caster changes or disappears or a new one is ready to bake, and a frame whose light changed draws everything straight into the target. When nothing changes it draws nothing. Depth keeps the nearest with LEQUAL, so the baked and overdrawn target is bit-identical to drawing everything at once. The original compares meshes and materials by reference; the Rust version compares mesh ids and material ids (a mesh rebuilt at the same address still counts as different). The original's instance buffer comparison (the buffer and generation of addMeshInstanceBuffer) is not included because the Rust ToonDrawQueue has no way to add an instance buffer yet. The capture test (tests/shadowcache.rs) draws the same 110-frame scene as the original Chrome test (tests/graphics3d/shadowcachechrome.test.mjs) and checks that EveryFrame and OnChange give the same screen every frame, that fully unchanged frames (45 to 59) draw nothing, that frames where only the box moves draw 7 or fewer, that Interval 4 draws only every fourth frame, and that a request_update frame draws as many as EveryFrame. The OnChange shadow draw count matches the original on all 110 frames, and the screens of frames 60 and 65 differ from the original in only 4 pixels by 1. (Before the change OnChange drew 12 to 16 every frame, and the test catches it at frame 1 of Interval) Measured on the original's heavy toon scene ported over (ground, 48 shapes, six skinned models, 400 rock instances, sun and two point light shadows, screen-space outline, 960 x 540), release build on a Mac mini M2 Pro: shadow draws per frame 238 → 0 with everything still and 238 → 39 with the six skinned models moving, median CPU frame time 1.48 → 0.79 ms still and 1.51 → 1.32 ms moving, and the screen is bit-identical to EveryFrame in both cases.
- UI draw cache and fewer uploads (same shape as the original, in the spirit of Unity UGUI Canvas rebuilding only changed graphics): Graphic caches the vertices each component drew (components that report inputs with Component::write_geometry_key, Graphic::draw_component, set_geometry_caching_enabled, is_geometry_caching_enabled, get_last_frame_geometry_cache_hit_count, get_last_frame_geometry_rebuild_count, get_last_frame_retained_batch_count). If the inputs are unchanged draw is not called, and if only the translation changed only the matrix is applied again. A batch is kept in a GPU buffer per draw order in the frame, so when nothing changed only the draw call is issued, and only changed ranges are updated with buffer_sub_data. Directly written vertices without a cache no longer stop a batch from being kept; their values are compared with the same place last frame. The 2D batch CPU array starts at 512 quads and doubles, and the frame-end batch GPU buffer allocates no storage at first. RenderTarget::resolve discards attachments that are not read again after resolving (mobile tile GPUs), and resolve_with_attachment_kept(gl, true) keeps them to continue drawing (original resolve(isAttachmentKept)). Glyph ink padding equals the original (fill 2, outline ceil(width / 2) + 2), and ShadowText adds the shadow offset only to the bottom height, not to the padding on every side.
- Reads without allocation (same names as the original readXxx): WorldNode::read_content_size, read_pivot, read_local_position, read_local_scale, NodeTree::read_position and read_scale write the value into a given place (&mut Vector2) without creating a new one. The value equals get_xxx.
- The toon shadow cache (ShadowUpdateMode::OnChange) no longer re-bakes on values that do not affect depth, such as the base color texture (same as original cee86b9; casters are compared per object, as in Unreal and HDRP cached shadows): ToonDrawQueue::draw_shadows and draw_local_shadows compared caster records in the sorted order of opaque items (material, mesh, base color texture). When the base color texture of one shape changed, the order shifted and unchanged casters looked changed, which either re-baked the whole cached map or never baked at all and redrew everything every frame. Records are now compared in submission order, while baked and overlaid casters are still drawn in sorted order. The compared values (mesh, material, matrices, joints, draw range, culling, mirroring) are unchanged; tint, color and base color texture do not affect depth and do not trigger a re-bake. A moving object still re-bakes in that frame. A capture test tests/shadowcasterorder.rs checks that frames where only the texture changes (40 to 79) draw no shadow depth (15 draws every frame before the fix), 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.
- Fewer active_texture calls in toon drawing (same as original cee86b9): ToonRenderer switched the active texture unit back to 0 after every draw, so the next draw called active_texture(4) and active_texture(0) again even when only the base color (unit 4) changed. Draws no longer switch back (stage callbacks and on_before_draw of body draws are still called with unit 0 active, and end_frame 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. For a frame whose base color texture changes on every draw, active_texture drops from 26 to 11, matching the original. A test (draw_does_not_reset_texture_unit_each_draw in graphics3d::toon::toondrawqueue) checks the call counts, that callbacks see unit 0 active, and that the active unit and unit 0's texture are restored after the frame.
- GL state cache (same remembering rules as the original WebGLStateCache, the pattern of three.js WebGLState and Chrome's GPU command buffer client): Graphic attaches one state cache per context as soon as it receives the context. glow cannot intercept context functions, so every engine state call (bind_framebuffer, viewport, scissor, enable, disable, clear_color, color_mask, blend_func, blend_func_separate, depth_mask, depth_func, front_face, cull_face, use_program, bind_vertex_array, active_texture, bind_texture, pixel_store_i32, and create, delete, link) goes through the cache, which calls GL and remembers the changed value. State reads during drawing (2D framebuffer restore, toon 3D state saving, ToonView3D's viewport, framebuffer, clear color, color mask and five enabled flags) are answered from the remembered values without asking GL. Constant limits are queried once, untracked values are queried as before, and unknown values (first read, unchecked arguments, programs with unknown link status, deleted objects) are queried once on the next read. Where the engine hands GL to game code (get_gl, the end of a run_external_pass pass, after the toon renderer's on_before_draw, after draw queue stage callbacks) the cache does not forget (same as the original; state functions of the GlContext handed over go through the cache). A real GL test (a windowless context made with macOS CGL) calls 600 random state functions mixed with invalid arguments, deletions and resets and checks that the cache answers and comparison functions match real GL (0 differences). New public functions Graphic::get_current_framebuffer() (the framebuffer being drawn to, None means the window), get_current_viewport() (current viewport Rect, device pixels, bottom-left origin) and reset_gl_state_cache() (resynchronizes the cache), matching the original getCurrentFramebuffer, getCurrentViewport and resetGLStateCache.
- GL state cache check mode (off by default, environment variable VANILLA_GL_STATE_CHECK=1): right before every engine draw call (draw_arrays, draw_elements and their instanced versions) the values the state cache remembers (both framebuffers, viewport, scissor, clear color, color mask, blend factors and equations, depth mask and function, front face and culled face, program, vertex array, active unit and the texture of each unit, enabled flags, pixel store) are compared with real GL; on a mismatch it prints that part and the previous 48 state calls to standard error and forgets that part. The comparing reads do not change state (to read each unit's texture it switches the active unit briefly and switches back). In capture mode it prints the number of compared draws and mismatches so far at every captured frame. It is meant for finding places where a game takes the inner glow::Context out and changes state. One real GL test was added (400 random changes through GlContext and the engine path with 40 draws give 0 mismatches, changing the program and another unit's texture through raw glow is caught once each, and the active unit is unchanged after the comparing reads).
- Fewer toon 3D draw state changes (same as the original, the pattern of Unity SRP Batcher, three.js WebGLState and WebGLUniforms): for each draw ToonRenderer asks the GL state cache about the program, the nine texture units, front face winding, culled face and vertex array, and does not set them again when they are the same. Uniforms remember the last uploaded value per program and name and are not uploaded again when the value is the same (joint matrices too; 0 and -0 are distinguished and NaN is always uploaded; the memory is forgotten at the start of a frame and shadow pass, in apply_frame_state (after stage callbacks and the screen space outline), when restoring state, and after that program's on_before_draw). ShaderProgram::use_program also skips when the state cache remembers that program is already in use. ToonDrawQueue sorts opaque items (bodies, outline shells, sun and point light shadow depth) by the first-seen order of material, mesh and base color texture (ties keep the queued order; transparent items stay far to near). In toonshowcase (several models, instanced rocks, skinned models, sun shadow, outline shells, Mac mini M2 Pro release build, frames 121 to 360) GL calls per frame went 878 → 396 (useProgram 36 → 25, uniform 374 → 118, activeTexture 122 → 40, bindTexture 107 → 35, state changes 161 → 120, state reads 31 → 11, draws 35 unchanged), and in toonview (ToonView3D and the draw queue) 1328 → 615 (state reads 37 → 2). The median CPU frame time stays about the same on macOS desktop GL, where calls are cheap: toonshowcase 0.47 → 0.49 ms, toonview 0.43 → 0.45 ms (it drops where calls are expensive, like Safari on the web and mobile drivers). Both examples render byte-identical images to before (both sometimes produce another image depending on asset loading and timing, also before the change).
- Text drawing moved to a glyph atlas (same shape as the original; like the Skia glyph cache, Unity TextMeshPro dynamic atlases and the Unreal font cache): instead of baking one texture per string, only glyphs seen for the first time are baked once into an atlas (1024 x 1024 pages, appended to the most recently opened page, a new page when it is full, up to 8 pages, and the least recently used page is cleared beyond that), and strings are drawn as glyph rectangles in the batch. Baking a new string no longer breaks the batch, and glyphs on the same page are drawn in one draw call. The pending batch is drawn before a page is cleared. There is one cell per text chunk, the same chunks as the original: Hangul, Han, kana, digits, punctuation and emoji get one cell per grapheme cluster, letters such as Latin and Cyrillic get one cell per word, and fonts above 256px, right-to-left text and the web (baked with the browser Canvas2D) get one cell for the whole string like the original. The cell key is, for every glyph in the chunk, (face, glyph index, size, Skia 1/4 subpixel slot) and its integer offset, plus mode and line width and antialiasing (it tells apart the same rasters as the original's 1/8 position slot key). So a new string made of known glyphs (such as a changing number) bakes nothing new. Where the ink of neighboring chunks touches, each cell is drawn separately, so linear filtering at fractional positions and blending of overlapping ink can differ slightly from the whole string (the same as the original, the shape of the Skia glyph cache and TextMeshPro). One row above and below each cell is baked as a repeat of the edge row, so sampling past the cell edge at a fractional vertical position returns the edge row like the old string texture's CLAMP_TO_EDGE instead of another row of the atlas. Chunks without ink (spaces) are not baked. The entry limit goes from 512 to 1024 like the original. 50 lines of text go from 51 draw calls to 2 (including 1 for the background), and a frame with 300 new strings from 351 to 2. On macOS, compared with grouping only glyphs whose ink touches, the glyphparity scene has 1 differing pixel (difference 1) and the difference from the original in Chrome is unchanged (0 pixels over 8 in every region), and the scene with strokes at four widths differs in 69 pixels where the stroke bands of neighboring chunks overlap (the original also strokes chunk by chunk). Baking 300 new strings (release) goes from 23ms to 15ms, known glyphs only from 17ms to 8ms, and 200 new strings made of known digits go from 200 uploads to 0
- TextStringTextureCache::read_atlas_statistics and TextAtlasStatistics (atlas_page_count, glyph_count, baked_glyph_count, upload_count, entry_count; the original readAtlasStatistics)
- JPEG decoding speed (desktop): the result bits are unchanged while Huffman decoding (11-bit lookahead, a table that decodes the AC code and value at once, a bit buffer that takes 8 bytes without 0xFF at a time), the inverse DCT (8 lanes at once for blocks that do not overflow 32 bits, 64-bit arithmetic when they do) and upsampling and color conversion (per row directly to RGBA, without three image-sized component planes) were reworked. One 12 MP 4:2:0 image went from 124.6 ms to 69.8 ms in median thread CPU time, on par with the old zune-jpeg (image 0.25.10, up to RGBA) at 69.4 ms.
- 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, same as the original) The load handle's create_model and load_from_url_async, load_from_fbx_url_async look the cache up by shader program and normalized path (SkinnedModelAsset::normalize_key) and on a hit return an instance without parsing or uploading. The async loads do not even read the file on a hit, and concurrent loads of the same file read the bytes once. (a handle reads the bytes because it does not know the renderer when the load is requested) Added create_instance(), create_from_asset(asset), get_asset(), get_material(index) (Unity Renderer.material: the first call forks a copy that borrows the textures), get_shared_material(index), Material::create_instance(), set_base_color_factor, get_texture_byte_count, SkinnedModelAsset (find, register, clear_cache, get_cached_count, normalize_key, retain, release, get_reference_count, get_gpu_byte_count and more) and SkinnedModelAssetContent. 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 add_animations_from_fbx_* replaces it in place. add_morph_target forks only that instance's target list and morph texture. Measured (Mac mini M2 Pro, VANILLA_MEASURE_ASSET_CACHE=1 cargo run --release --example modelviewer, 20 copies of one model, building from bytes already loaded): fox.glb from 186 ms and 113.8 MB of GPU memory to 8.8 ms and 5.7 MB, mannequin_female.glb from 45 ms and 32.0 MB to 2.0 ms and 1.6 MB. The GPU byte counts match the original edition exactly. Same API and same test as the original (asset_cache_shares_resources_and_releases_by_reference_count in skinnedmodel.rs).
- Canvas2D (desktop): set_font reads the CSS font shorthand form like Chrome and ignores invalid text (no size or family, CSS-wide keywords such as inherit, an invalid line height and so on), and get_font returns the text as Chrome serializes it (keywords lowercased, relative sizes in px, line height and font width dropped, family names quoted, system font keywords). put_image_data does not write pixel data that is not width x height x 4, and added put_image_data_region in the dirty rectangle form (both versions). Unpremultiplying in get_image_data now uses the same Skia computation as the Chrome CPU canvas (it was off by 1 at values falling exactly on a half). (Blink base_rendering_context_2d.cc font getter and putImageData, shorthands_custom.cc ConsumeFont, Skia SkSwizzler_opts.inc, 225 strings and 65536 pairs measured in Chrome 158)
- DynamicFont::rebuild_atlas: skips characters that cannot be baked and bakes the rest. If none can be baked, leaves the atlas as is. (A single character kept the whole batch from being baked)
- ToonRenderer: GPU instancing (draw_mesh_instanced, matrix and tint per ToonInstance, for both body and outline, skinned models share the same pose), off-screen culling (model bounding sphere against the frustum; instances are culled one by one and only the remaining ones are uploaded, ToonDrawOptions.is_culled), shadows (begin_shadow_pass, draw_mesh draws depth only, end_shadow_pass restores the framebuffer and viewport, received with 3x3 PCF via set_shadow(ToonShadowInput::from_shadow_map)), HDR output (set_hdr_output outputs linear color), drawn count, culled count and draw calls for one frame (get_frame_statistics)
- AudioPlayer: set_playback_rate. Playback speed (pitch changes too, from the next play). kira playback_rate on desktop, AudioBufferSourceNode.playbackRate on the web
- Color::from_cache(color_string): a color cached by color string. (From<&str> builds a new lowercase string on every call; beyond 1024 entries it is cleared and refilled)
- Reads font strings in the CSS font shorthand form, like font of browser Canvas2D. (parse_font_string) Sizes besides px include pt, pc, in, cm, mm, q, em, rem, %, larger, smaller and named sizes (xx-small ~ xxx-large) (relative sizes are based on 10px like the original canvas), the line height of "16px/1.5" is skipped, and small-caps, stretch keywords and oblique angles are accepted. A comma-separated family list looks for faces from the earlier names first for each character. (Previously only the first name was used) An invalid string is treated as the canvas initial value "10px sans-serif". Added FontDescription.family_name_list. (Code that builds the struct directly must be updated) Checked against Chrome's parsed values with tests
Fixes
- Sun shadow focus step (same as the original 0733926; reduces the OnChange cache redrawing every frame when the focus follows a camera): added ShadowMap::set_focus_step (world step) and get_focus_step. With a step, update_light_matrix snaps the focus to multiples of the step on world x, y and z so the light matrix is identical within a step, and widens the covered width and depth by the step so the area around the focus stays inside the map. Texel snapping still applies on top. The default 0 is unchanged (texel snapping only).
- 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) (same as original issue #2). (a) Added ToonRenderer::prewarm_draw_queue_with_options(gl, queue, &options) (the original takes an optional options argument on prewarmDrawQueue; Rust has no optional arguments, so it is a companion function). Pass the combinations the game will use, like Unity ShaderVariantCollection, with ToonProgramPrewarmOptions (Default): light_feature_list (per combination, the light feature names that turn on additionally, e.g. [["rim"], ["rim", "shadeRim"]]; the names are rampTexture, shadeStops, rim, shadeRim, intensityLimit, and a wrong name returns Err), light_set_list (the light sets to be used) and queue_list (draw queues holding materials and instance layouts that appear later), and those combinations are prewarmed. (b) Added ToonRenderer::set_async_program_build(is_async) and is_async_program_build() (default true). With GL_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 picture is byte-identical). Without the extension it is built on the spot as before. Test (a scene whose light changes four times): builds per frame built on the spot [1, 1, 1, 1], combination list [0, 0, 0, 0], light set list [0, 0, 0, 0], and the pictures are all byte-identical. (Mac GL has no parallel compile extension, so the handed-off path runs the same code with a test-only switch)
- Fix: every web example stopped before the first frame (after the global engine change, borrowing the configuration title while building the canvas was extended to the end of the function, so attach_graphic panicked with already borrowed when it modified the configuration).
- Fix (matches the original): the Rust desktop looked up only the regular (400) and bold (700) faces of a system font family, so weights such as 200, 300 and 500 were all drawn as 400 (Chrome picks the family's named weights such as UltraLight, Light and Medium). Every weight and slant face of the family is now a candidate, chosen by the CSS Fonts font-weight matching rule (a desired weight of 400 to 500 looks up to 500 first, then below, then above; below 400 looks down first; above 500 looks up first). macOS reads the family faces and weight trait from CoreText, Windows the family fonts from DirectWrite, Linux the FC_WEIGHT from fontconfig. Added platform::list_family_font_faces. Regular and bold are unchanged. Helvetica Neue, Apple SD Gothic Neo, Avenir Next and Helvetica pick the same face as macOS Chrome 158 (CSS.getPlatformFontsForNode) for every weight 100 to 900, upright and italic.
- Fix: on the web, a canvas without a CSS size (examples with auto_resize_on_window_resize off, such as batchclip) grew by the pixel ratio every frame to tens of thousands of pixels (the pixel size became the CSS size, so each resize multiplied the re-read size by the ratio). It is now pinned to the CSS size first read. A panic on the web now writes its message to the browser console (before, only unreachable showed). Self-exiting examples (batchclip, inputgallery, modelviewer, subtreecull, subtreecullinside, uigallery, uigallery2) also called exit_application on the web, which calls window.close and closed the Safari tab (the original does the same, so the engine is unchanged; the examples now keep running on the web). The modelviewer example clock now uses web_time, which works on the web (std::time::Instant panics on wasm).
- Fixes (same as the original eb4338b, 4e05c55, 61f4793): giving a shader blend to a swapped shader inside an axis aligned clip (shader clip) covered the area outside the clip when the overlay target was moved and blended (the shader clip scissor is set again after clearing the overlay target). Opening an opacity layer cleared only the stencil, so the depth of the previous layer remained and a 3D pass inside the layer that does not clear depth (is_depth_cleared false in run_external_pass) was hidden (depth is cleared to 1 together with the stencil to the current clip depth). ShadowMap::begin_render did not turn off the scissor test, so an outside pass inside a 2D clip cleared only part of the map (turned off in the map binding shared by the sun shadow map and the point light map).
- UIDocument image and node data fixes (same as the original): a copy written and read with the same document uses the original's image as is. Writing (serialize_node, to_json_text) remembers the image of a component that wrote imagePath by its path, and the resolver and load_images assets put that image in when they cannot find it (like Unity Instantiate). So an item cloned with UIListView::set_template_node shows its image (before, without a resolver the item had no image). A custom handler remembers it too when it writes the path with UIDocumentSaveContext::write_image_path(document value, path, image). bind_pending_images does not overwrite a component the game gave an image or changed the path of in the meantime, so UIDocumentLoadContext::bind_image takes two more functions that look at that place (current path, current image). An image that load_images could not read is requested again by the next load_images. Writing warns when a node reference points to a node that has an earlier sibling with the same name (the path is written by name only, so reading it back lands on the earlier sibling). A hidden node (set_visible(false)) writes and restores visible: false in the node data (a visible node writes nothing, so documents written so far and their expected values stay the same; UIToast, which uses active as visibility, writes only active as before).
- Fix: the joint index vertex buffer of skinned models (SkinnedModel::bind_integer_attribute) converted the u16 indices to f32 before uploading while the pointer reads UNSIGNED_SHORT (slipped in when logic numbers moved to f64), so the shader read outside the jointMatrices array with broken indices (undefined behavior). It now uploads u16 as is, like the original (Uint16Array). Because of this the two mannequins in modelviewer stood in a T pose, and depending on what the driver read outside the array the arm triangles sometimes stretched far (removing the state cache resets at the boundaries made them stretch and asking GL anything made it vanish, so it looked like a state cache problem). Now the mannequins walk with their clips, and the four toon examples (toonshowcase, toonview, toonfx, toonpost), modelviewer, blendmodes and batchclip render pixel-identical images with the safety net, without it and in check mode (frames 60 to 590 for the four toon examples and modelviewer, 60 to 240 for blendmodes, 149,037 draws compared in check mode with 0 mismatches).
- Shadows of the desktop dialog, context menu and touch quick menu: drawn with a Chrome-like Gaussian blur instead of overlapped rounded rectangles. The context menu uses the original CSS box-shadow 0 4px 16px rgba(0, 0, 0, 0.18) with sigma 8 (half the blur radius) like Blink; the dialog and quick menu use Chrome views BubbleBorder's two layers (down 2, blur 8 and 12, #3C4043 alpha 0x33 and 0x1A) with ui/gfx RadiusToSigma (blur / 2) as sigma. The rounded rectangle is baked on the CPU (device scale, reused for the same values). On the Mac the right-hand shadow cross section of the context menu matches the original DOM menu in headless Chrome within 1/255.
- Desktop window: when a GL 3.3 core context was requested and the driver gives a lower version (like the GDI GL 1.1 on Windows without a driver), the panic inside glow for missing shader functions is now reported as the error "OpenGL 3.3 core is not available:
" and ends. - Corrected the description of UIInputField::set_use_direct_touch to match the facts. It is not web-only; on desktop it does what Chrome does for that DOM input in the original (word selection by a long finger press and touch handles, while the right button opens the engine context menu)
- Scene touch: the original vanilla.js Scene was also changed to pass touches to nodes through the scene's TouchRaycaster regardless of the scene type, so the two engines are the same. (The Rust version's SceneBase.tick is unchanged; fixed the documentation text "the original default scene does not pass them")
- Engine: sets the view coordinates (view_manager.apply_view_rect) before drawing for each scene (before pre_draw, or before draw_on_load while loading). (Fixed in the original too) Until now a scene that did not call draw_scene_background or apply_view_rect in pre_draw drew in the physical pixels of the drawing buffer, so on screens with a device pixel ratio of 2 (Retina Macs, high-density screens on the web) it drew only in the top-left 1/4 of the canvas. How to migrate: a scene that drew in physical pixels calls graphic.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0) in pre_draw
- format_compact_number: when the rounded text reaches 1000, moves up to the next unit. (999999 is "1M", not "1000K"; fixed in the original too)
- UIScrollBar: auto-hide no longer disables the node, it only makes it invisible. (Disabling it stopped tick, so it never came back; fixed in the original too) Added is_auto_hidden()
- Sprite: flipping (set_horizontal_flip, set_vertical_flip) used to draw outside the content area (on the negative size side); fixed to mirror within the content area. Atlas pieces, nine-slice and tiles all flip. Even when flipped, is_drawn_inside_content is true, so it gets off-screen culling. (Same as the original)
- Web audio: fixed an earlier request that finished late making sound when stop or play again was called while a suspended AudioContext was being resumed. (Playback request numbers)
- ParticleSystem: fixed bursts at the loop seam (the repeat boundary) firing only in the first cycle. Bursts at 0 seconds and right before the boundary also fire every cycle, and when one frame skips over several cycles they fire that many times. (Same as the original)
- Position of the web hidden input: adds the document scroll, like the original. (A bug where it was misplaced when the page was scrolled)
- VisualAsset: fixed load, which only recorded the path and finished immediately, to work like the original. load(engine, path) requests the bytes, and when the bytes arrive it checks for the visual editor document form (JSON object, root object); if it matches, it is loaded and holds a Visual with that text. Added create_visual_from_text, load_from_bytes, unload. How to migrate: change load(path) to load(engine, path).
- HumanSkinRenderer: corrected the eye iris order in the texture unit comments. (12 iris normal, 13 iris color; the behavior was already correct)
- SkinnedModel: fixed, in the original too, the vertex arrays, buffers, morph textures and materials of the old drawables being left behind and leaking when upload_meshes_and_materials is called again. (destroy first) upload_wireframe_indices also deletes the line buffer already uploaded and uploads anew.
- Material::create_from_description: if an image partway through cannot be decoded, deletes the textures built so far and returns an error. (The original was fixed the same way)
- ShaderProgram::new, create_with_attribute_locations: if the fragment shader or the program cannot be built, deletes the shader built earlier. (The original was fixed the same way)
- Localization::is_right_to_left: reads in lowercase with underscores as hyphens, like set_right_to_left. ("ar_EG" was not detected as a right-to-left language; the original was fixed the same way)
- UINode::add_constraint: constraints the solver did not accept (already added, contradictory) are not kept in the list. (The next set_solver stopped at the same error and later constraints were not applied; the original was fixed the same way)
- Sound decoding (WebM, MP4 trimming): prevented overflow panics from EBML signed integers longer than 8 bytes, extreme-value cluster timestamps and CodecDelay, very large MP4 box sizes and edit lengths, and iTunSMPB priming longer than the sound. (Even broken files are trimmed without panicking)
- UISpinner::calculate_dot_opacity: with no dots (dot_count 0) it no longer becomes NaN from dividing by 0. (The original was fixed the same way)
- UIListView::set_horizontal: when changed, re-measures the scroll area on the next tick and lays out the visible items again along the new axis. (The original was fixed the same way)
- Original bug found while porting UIDocument: Sprite's nineSlice was written but never read. The Rust version reads it by decoding the form the original writes (left, top, right, bottom of a Rect)
- ParticleSystem changed behavior: instead of always drawing with the image once an image is set, draws with the image only when the render shape is image, like the original. The description's edge, which was read as a flat rectangle spreading upward, now emits downward like the original. Because a wobble phase is drawn per particle, particle positions of particle systems with a fixed seed (timelines) differ from before. Like the original, circle uses unrotated quads, size does not go below 0.1 and alpha does not go outside 0 ~ 1
- SoundSystem: filled in what was missing from the original core/soundsystem.js. set_autoplay_allowed_provider (asks for permission once on the first update and tries waking before a press), muting when the window loses focus on touch-primary devices (released on a press, on regaining focus, or on becoming visible again), muting on the spot via the engine's page events when the page is hidden, pausing the AudioContext while muted (web suspend, desktop silences the main track) and waking it again every 0.5 seconds after unmuting, not playing sound effects before the first press or while the AudioContext is not running, left-right pan of play_effect, remembering requested background music and playing it once loaded and stopping it with "", "" (all) and 0 seconds (cut immediately) for fade_out_effects, picking only loaded recordings, volume sanitizing (0 if not a number), get_music_scale, is_page_hidden, is_blur_mute_enabled, is_window_blurred, is_context_paused, is_context_running, get_last_context_resume_time. update takes the engine (update(engine, time_delta)), play_effect takes pan, and get_music_id returns the requested id (&str, "" if none). (This changes the public API) Fixed resumed playback always starting from the initial position (AudioPlayer.get_time does not advance during playback) to start from the position computed from elapsed time, like the original
- Aligned what differed from the original vanilla.js in effects, 3D and animation. (Reverted forms that had been made different back to the original's usage, ported what existed only in the original, and fixed bugs present in both engines in both)
- Fixed the toon examples (toonview, toonfx) stopping immediately on the web. On the web, glow panics when reading the binding while no framebuffer or texture is bound, so they are read with graphics3d::read_framebuffer_binding, read_texture_binding (treated as the default on the web), and empty depth texture bytes are read from a u32 aligned to 4 bytes
- Animation: filled in pause and resume. (goto_and_stop stops) stop returns to the first frame even when stopped. (Fixed the original bug too)
- Timeline: attaches to the stage parent if the parent is itself or a cycle. Fixed the header comment saying the original easing was wrong. (The original pow was already fixed, so the easing values of the two engines are the same)
- SoundSystem.get_music_bus, get_effect_bus (original getMusicBus, getEffectBus, None before the first press): music and effect volumes, previously multiplied per player, are applied to these buses. Players created from a bus also follow the settings volume and mute. The bus volume is applied only when the computed value changes, so a value set with the bus's set_volume, mute lasts until SoundSystem applies the volume again (the original also applies to the same node)
- Web: fixed text baked by the browser when there are no font bytes (platform/web/systemfont.rs) taking only the canvas alpha and uploading it as white, which made color emoji appear as white silhouettes. Uploads RGBA as premultiplied like the original. System font pieces (characters not in the registered fonts) are split into coverage for white pixels and the color portion for colored pixels. With antialiasing off, thresholds by alpha and fills with straight color. (The original thresholds the alpha channel of straight alpha)
- The original bugs fixed first in the Rust version (UIDocument nineSlice reading, UIDropdown header button tint, UIInputField paste cursor, LayoutSolver artificial rows) were also fixed in vanilla.js and now match, so they were removed from "differences from the original" in the header comments. The UILabel background order was already the same in the original
- The OBB.overlaps, NodeLayout.arrangeFan and SoundEffectPool voice count 0 bugs were fixed in vanilla.js too and AudioAsset.getLoadError was added, so those 'differences from the original' were removed from the header comments of this version. (obb, nodelayout, soundeffectpool, audioasset)
- Changed the value of KeyCode::AUDIOPLAY to "MediaPlayPause", the name in the W3C KeyboardEvent.code table (2025-04-22 Recommendation). (Fixed together with the original) "MediaPlay" is neither in the table nor in winit KeyCode, so it never matched on desktop. Chrome emits "MediaPlayPause" for the common play/pause key (USB 0x0C00CD) and "MediaPlay" only for the play key on Linux and ChromeOS (USB 0x0C00B0)
- Fixed AssetLoader.get_in_flight_count to follow the definition of the original getInFlightCount: items picked up and started but not yet finished. (Images through decoding, sounds through audio decoding) External handles added with add_load_handle (in place of the original addTask) are also counted until they finish, and the concurrency count uses the same count. (An original worker occupies one slot with an addTask until it finishes) Until now external handles were excluded and an item counted as finished when its bytes arrived
- What the browser used to provide, now with the same API on desktop too (the original runs on Chrome, the Rust web version uses the same browser features, and on desktop the engine does the same work)
- Canvas2D, Path2D, CanvasGradient (linear, radial, conic), CanvasPattern, ImageData: the canvas and 2D context the original and games use through document.createElement("canvas") and getContext("2d"). The web uses a browser canvas not attached to the document, and the desktop paints with tiny-skia (the same version resvg uses). Paths, strokes and dashes, clipping, shadows, 26 compositing modes, images, text (engine text cache), pixel read and write, to_image
- Engine::alert, confirm, prompt and alert_async, confirm_async, prompt_async: in place of the original window.alert, confirm, prompt. Both the web and the desktop use a dialog drawn by the engine like a Chrome tab-modal dialog (title "This page says", an input field with the default value fully selected, [OK][Cancel] on Windows and [Cancel][OK] on macOS and Linux, Chromium translations for 82 locales). While it is up, scenes and async tasks pause. The Local Storage tab of DevTools also uses it (removed the in-panel input window)
- Document: html lang and the meta in head. The web uses the browser document, and the desktop values held by the engine (EngineConfiguration.document_language, document_meta_list). BuildInfo reads build-version from meta first on desktop too, and LanguagePack changes the document language on both platforms
- Pane, PaneStyle: split panels built from engine nodes on desktop (the same size and drag computations, theme colors, resizer cursors), PaneStyle preset nodes (PaneElement, set_on_click). PointerCursor::request_element_cursor
- Input fields: undo and redo for desktop DOM input fields (Blink grouping rules, Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y, Alt+Backspace on Windows), and the Chrome editable field context menu for direct-touch fields (Emoji, Undo, Redo, Cut, Copy, Paste, Paste as plain text, Select all, Writing Direction, Inspect). Inspect makes the developer tools select that node via Engine::request_dev_tools_inspect
- LocalStorage, PersistedStore: preserve unpaired surrogates saved by the original (truncated emoji, \ud83d from JSON.stringify) as the original UTF-16 units. Previously such JSON could not be read, so PersistedStore fell back to defaults and overwrote the original's save on the next write. get_item_code_units, set_item_code_units
- Fix (matches the original): a tab at the end of a line in the multi-line input field (UIInputField) now hangs like a space, as in Chrome pre-wrap (removed from the line width when breaking lines). In a column narrower than the tab width, "tab\there" broke at [0, 4] in Chrome but [0, 3, 4] in the engine (added the tab to trim_hanging_spaces in textarealayout).
- Fix: UISpinner dot positions were off by one in the last digit on Linux (glibc cos differs from Chrome V8 in the last digit, so the test comparing with the original values failed only on Linux). cos and sin now come from the pure Rust libm crate (fdlibm family), so macOS, Linux and web give the same values as V8. No new dependency (a version other crates already used, already in the license notices).
- Fix: the audio thread could render one more quantum (128 frames) right after the AudioContext was suspended by Hidden, so currentTime still advanced (the Linux CI test page_events_mute_and_unmute failed now and then). Like Chrome audioContext.suspend(), whose promise resolves after the clock has stopped, the desktop suspend_audio_context now waits (up to 200 ms) until the audio thread has received the suspend. The clock does not advance after it returns.
Tools, docs and examples
- Example toonshading (same scene and screen layout as the original examples/toonshading: title, VANILLAPUNCH.COM link below, copyright notice at the bottom left): reads a VRM 1.0 character (VRM1 Constraint Twist Sample, pixiv Inc., VRM Public License 1.0) with the engine SkinnedModel and cel-shades it with the original shader source. The scene MRT, hair depth pass (bangs shadow and see-through), shadow map, bloom, rim light and ACES composite, and FXAA run in the same order. Six expression buttons with blinking and eight Quaternius animation (CC0) buttons retarget world rotation changes against the T pose onto the VRM bones, and the roll and aim of VRMC_node_constraint are followed. Drag orbits, the wheel zooms, right-drag moves the focus height. Assets are read from the original repository. Not there yet: spring bones, head and eye following, the options panel and sliders (values fixed to the original defaults), wireframe, the rendering info display, the context menu.
- Example cameratour (same screen and behavior as the original examples/cameratour): Camera2D slowly turns left and right while following a target and shakes every 3 seconds (Shaker). Dragging pans in the rotated direction (pan_by_screen), the wheel zooms keeping the point under the cursor fixed (zoom_at). The node at the top left has its scale moved by Tween::create_node_tween, and an Indicator spins at the top right.
- Examples ancientmountain and neonhorizon were ported from the original vanilla.js. ancientmountain is a third-person mountain climb (procedural terrain with grass, a dirt path and three-way cliff textures, mannequin run, jump, climb, drop down, six foxes, summit flag, OFF, SIMPLE and REALTIME shadows, bloom, motion blur, option panel, gamepad) and reads its assets from the original repository. neonhorizon is a neon-grid terrain run (stars, meteors, a fleet, boost light streaks, dust, bloom, chromatic aberration, film grain, option panel) and keeps two models in examples/assets/neonhorizon. It runs the original's shaders and formulas on the engine's ShaderProgram, FullscreenPass, RenderTarget, ShadowMap, BloomEffect and SkinnedModelRenderer. Asset licenses are written in THIRD_PARTY_LICENSES.md.
- Crate license files: vanilla-engine-macros, vanilla-engine-apidoc and vanilla-engine-licenses also get the same LICENSE as the root (copyright holder vanillapunch), listed in include so it ships in the cargo package. authors are written for apidoc and licenses, and licenses also carries the SPDX full texts.
- Example asset license cleanup: matches the original vanilla.js repository replacing the Mixamo original files with the Quaternius Universal Animation Library (CC0). modelviewer reads mannequin_female.glb (Idle, Walk, Run, Dance) and mannequin.fbx instead of soldier.glb and Remy.fbx, and toonshowcase reads mannequin_female.glb. The FBX test (walk_fbx_from_examples) checks the Blender-written 7.4 format and the pelvis bone. The Remy.fbx and centimeter scale lines of the 15-3d guide changed too. The doc images model-viewer and toon-showcase and the upper left cell of README's modelviewer.jpg and hero.jpg were retaken with the new scene (1280 x 720).
- License notices: files ported from other sources (mixer, decode/opus, decode/trim, textinput, canvas2d, textshaping, maskgamma, coretextglyph, systemfont, linuxplatform, browseruitext, colorglyph, component/text, format, autolayout, tween, matrix4, subsurfacescatteringeffect, and the experimental tilemap, physics2d, dynamictree) got the source and a one-line license right under the header block. THIRD_PARTY_LICENSES.md gained Skia's maskgamma and coretextglyph, Chromium's opus_audio_decoder, opus_constants.h, audio_file_reader and audio_discard_helper in the bundled materials section, and a public domain and CC0 code section.
- cargo package: Cargo.toml's include ships only the source (and its data), LICENSE, THIRD_PARTY_LICENSES.md and README.md. (docs, examples, tests and test assets, and tools stay in the repository only)
- 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, and a workspace tool that builds it, tools/licenses (vanilla-engine-licenses, uses only serde_json), was added. It holds the license expression, the license used, the copyright lines and the full texts (each identical text once) of the crates the engine uses (normal and build dependencies) on the three desktop OSes (x86_64, aarch64) and wasm32, and lists crates used under licenses that require no notice on one line each. Bundled materials that are not crates (the IRCAM notice of the HRTF data Composite.flac, and code and tables ported from fdlibm, Chromium and Blink, Skia, ICU4C and CLDR, font-rs, Kiwi, tween.js, gl-matrix, Separable SSS, and libtiled and Box2D in the drafts) are written in the file's bundled materials section with the engine files, the original files and the original notices. The Cargo.toml of the engine and macro crates now has authors = ["vanillapunch"]. (Used in the notice of the macro crate package, which has no license file) Games build their own file with the same tool, covering their dependencies and the materials the engine bundles. (The license section of the README, licenses in tools/TOOLS.md)
- Tests: the desktop platform test tests/desktopplatform.rs (#[ignore]; system font and fallback font lookup, fallback font text and color emoji raster, comparison with the same machine's Chrome measureText, clipboard round trip) and tests/assets/systemfont/chromemeasure.cjs, which records Chrome values. The mixer's Chrome comparison accepts a sum of squares within 1e-5 (relative) when the operating system and CPU the expected values were recorded on (platform and architecture in chrome_mixer.json) differ (automation's exp and pow are the operating system math library, so the last digits differ).
- CI: .github/workflows/platforms.yml runs cargo test, the desktop platform test, example capture (Mesa llvmpipe software GL), audiotone on a virtual sound device, re-recording the sound Chrome expected values with that machine's Chrome and comparing, capturing the original example pages with headless Chrome for pixel comparison, and the wasm32 example build on Windows, Linux (X11, Wayland) and Intel Mac (.github/scripts). Instead of the Chrome installed on the runner (versions differ by machine; the Intel Mac had 151), browser-actions/setup-chrome installs the version the expected values were recorded with (Chrome for Testing 158.0.8127.88) on all three machines and hands it over through CHROME_PATH. Example capture reads the GL renderer line and the per-frame progress line ("Engine: capture progress frame N / last, T seconds") that the engine leaves in capture mode, and classifies no progress for 180 seconds as stuck and exceeding the time limit while progressing (default 900 seconds, oldface 2700 seconds) as slow.
- Doc text: restored to the original names the original JS names that were changed to snake_case during the renaming (original playTone, audioContext, Graphic.drawNode and the like, 105 places), shader uniform names (modelMatrix, tintColor, globalAlpha) and Canvas2D names
- Guide: updated chapter 13 Animator, the destroy() of ScreenEffect and HeatHazeEffect in chapter 14, and VisualAsset and Visual::create_node in chapter 19 to the changed APIs
- Docs: corrected InputManager.set_touch_pressed (Moved stays on while pressed), Engine's desktop occlusion (minimization, app suspension and Wayland frame callbacks are also Hidden), load_scene_async (it fails to resolve only when unloaded before create in the same frame), and Scene::initialize (0.3 seconds after create even when nothing is entrusted) to match actual behavior.
- Doc comments: LayoutTerm (the solver skips the original's terms without a variable), UIView (the original's setBackgroundColor(null) corresponds to a color with alpha 0), NodeLayout (anchored_position is applied at build, same as the original), UIScrollBar (removed the line about the thumb color difference; the original was aligned to (1, 1, 1, 0.6))
- Tests: zero_value_terms_add_nothing, fast_short_drag_flings_one_page, snap_to_nearest_crosses_pages, line_chart_max_sample_count_trims_oldest, background_color_can_be_cleared, image_asset_gives_its_image, anchored_position_follows_call_order, language_list_without_aliases_is_accepted, frame_per_second_overlay_text_and_box
- Matched doc text to the code: ShaderProgram (original name attributeLocationTable), Mask (NodeTree::draw_node clips), TweenProperty::get_name (first letter lowercase), ButtonMotion (the tick and is_drawn_inside_content headers, set_lit_handler), GraphicsQualityGovernor (environment variables
VANILLA_<name>on desktop), FixedStepper::new, PointerCursor::is_coarse_pointer (Windows tablets, Linux touch), ViewManager render scale cap (desktop uses it too), AudioBus::get_gain_node (desktop Rc), UIWindow (as_any, dispose, set_dim_color, set_panel_color), the coordinates of UIContextMenu::show, the ui module header, README asset loading example names (C-CASE) - Example: toonshowcase. Draws seven basic shapes and the walk of soldier.glb in toon style. Giving a GLB path in TOON_MODEL_PATH places that model too. (Desktop)
- Example toonshowcase: draws 2,000 rocks around the edge with a single instanced draw and culls off-screen ones. (690 drawn, 1320 culled, 20 draw calls) Shadows, HDR bloom and tonemapping
- Example: engineextras. Places borders, progress rings, expanded hit areas, button feedback and toasts, shadow text and shadow images, soft shades, the mouse cursor, camera gestures and input state on one screen. Input is not emulated, so press them directly on desktop and web
- Example: nodebasics. Creates nodes and attaches Paint, Text and a custom component (Spin). (The code from the README section 'Nodes and components')
- Example: scenedocument. Reads and draws a scene file made in the original UIDocument and editor save format (examples/assets/scenedocument.scene.json), exports it again and shows on screen whether it matches the document read
- Example effectgallery: placed eight ParticleSystem cells at the bottom right (circle fountain, rect confetti, streak sparks, image stars, attractor vortex, wobble droplets, edge snow, world space trail). The trail below moves only on the left
- Examples particleeffects, spriteeffects, uisample: ported with the same scenes as the originals. particleeffects has eighteen particle effects (list, usage code panel with COPY, stats panel), spriteeffects has a list of sprite shaders, screen effects and twenty-five staging scenes, uisample loads a uiasset with UIDocument and wires buttons and a progress bar. The environment variable VANILLA_EXAMPLE_MODE picks the first mode. The hero sheet animation in spriteeffects is stepped by the example because SpriteAnimator cannot find the Sprite inside a ShaderSprite
- Example uishowcase: ported with the same scene as the original VANILLA CONSOLE. UIDocument reads six uiassets and the code adds four screens (dashboard, store, settings, components), themes (Dim, Dark, Light, saved in LocalStorage), popups (PopupMotion, Typewriter), toasts, a context menu (right button or long press), drag chips and responsive layout. The environment variable VANILLA_EXAMPLE_MODE picks the first screen (home, shop, settings, components). The theme dropdown deletes and rebuilds itself, so the theme applies on the next update
- Example inputgallery: shows input actions (press, repeat count, move axis), the finger list and phases, and the last device at the bottom right, using emulated keys, fingers and external sources. Example engineextras: last device and gamepad kind in the input state line
- Example: toonview. Toon inside a node rectangle (ToonView3D), 2D labels placed over 3D points with Camera3D, three translucent balls drawn farthest first, faceted rocks joined with combine, and ToonPostProcess color grading and vignette on the right panel
- Example loadingshowcase: loads seven images and one document three at a time with AssetLoader (one missing file goes to the failure list), a customized loading screen (spinning dots, rounded bar, loaded count) whose progress fills while emulating ten post-load steps, and after loading, a ball moved with FixedStepper
- Example: toonfx. Draws screen-space outlines on shapes and instanced rocks with a perspective camera
- Example toonfx: every 3 seconds an explosion (shockwave, fireball, scorch, spark streaks, smoke, dirt grains), smoke plumes, flowing ring marks, and every frame beams, lightning, ribbons and glints, drawn together with screen-space outlines
- Example: windowshowcase. Play area reference (emulating safe areas of 40 at the top and 30 at the bottom), stacking a basic window and a long-text confirmation window, outside press and close all, screen fade (held for 0.6 seconds with a hold handle), only presses not taken by the UI go to play. For the first few seconds it tours by itself
- Example: textnodeextras. Text box fitting (Text, UILabel), text with moving scale, translucent rings, a shrinking arc and 600 line segments, an atlas baked with atlas.cjs (examples/assets/atlas), shadow text sharing baked images, the mouse position over a rotated panel (convert_view_to_local)
- Example oldface: the original OLD FACE scene (shadows, skin MRT, blending, AO, SSS, bloom, ACES, FXAA, expression morphs and wrinkle maps, blinking). Captured at the same time as the original, mean difference 0.8/255. The expression changes every 4 seconds and is chosen with number keys
- Example misctour: Camera2D rotates slowly left and right and draws with begin, end
- Example: panelayout. A particle editor style window layout (toolbar, fixed-width vertical split on the left, engine canvas in a flex panel on the right). Web only, desktop only prints a notice
- Example: devtoolsshowcase. Places a few nodes and leaves the developer tools open. (Initial tab via VANILLA_DEVTOOLS_TAB)
- Example: uiscenelayout. UIScene and UINode constraints (safe area guide, weak preferred width and range, margin guide, equal-width buttons, natural-size text). Opens the developer tools when VANILLA_EXAMPLE_DEVTOOLS=1. windowshowcase was changed to the GameScene trait, the play input handler, and fade_screen_with_hold
- Example: textshaping. Arabic right-to-left text (Rtl, Auto, RichText), synthetic italic and bold, italic, underline and strikethrough on shadow text, CJK word wrapping, visible count in grapheme clusters, DynamicFont
- Example textshaping: a color emoji line (😀👍🏽 ❤️❤ 🇰🇷 👨👩👧 1️⃣), emoji in shadow text, italic emoji, ⭐ in the glyph atlas
- Example blendmodes: the 26 blend modes, one per cell. The scene changes every 60 frames (translucent images and shapes, text with nine-slice and clipping, batched and single particles, swapped-in and default shaders)
- Example toonpost: the same scene in three setups (ToonPostProcess default, multisample 4 with depth 24 and 5-level bloom, brightness, lit area and saturation on the LDR path), stain marks, oil sheen, flickering scorch, shadow under the feet, covering-style fireballs, shockwaves and ribbons, 120 light dots (cap 160), fireball events with key and age. Time is frame count / 60, so every capture is the same
- Example toonmaterial: seven-segment digits from a material surface chunk, base color texture and decal, three point lights with specular, rim and fill light, a 4-step half Lambert band from a different light set, two additive holograms (with and without a depth prepass), a planar floor mirror (before-opaque stage), and rocks in a persistent instance buffer. The same scene as the original test page. (Frozen and captured with TOON_MATERIAL_FRAME, the pixels are nearly identical to the original) At startup, converts the Aberrant body shading formula to engine options, draws it into a float buffer and compares it against CPU computation (maximum difference 4.5e-8)
- Updated the documentation to match the current code. (the code is unchanged)
- README: strengths and example list (seven new examples), asset formats (images gif, bmp, ico, svg, avif, sounds flac, m4a), technical notes (text rendering, render target multiply, 0.3 second loading), the tls feature flag and Windows, Linux target checks, recommended rav1d opt-level, frame capture for verification, external dependency tables (per Cargo.toml and Cargo.lock, added Windows and Linux tables), ShaderSprite effect count (49 excluding none)
- ARCHITECTURE: layout and ownership structure, frame loop, blending, fonts and asset formats, chapter 9 correspondence with the original (181 of the original 200 files ported, the 19 files deliberately not ported and why), chapter 10 differences between the two engines (what truly cannot be matched and deliberate design choices)
- In the header of this version in UPDATE.md, merged the duplicated lines (six copies of the capture mode) into one, and corrected the old description in the math line
- Header comments: things now the same because they were fixed in the original too (batching and culling on by default, program and texture caching, Text culling, use_dev_tools of UIScene, WebSocket binary JSON, Identifier.reset, Vector2 bugs, pageshow restoration, DynamicFont re-placement, zero-duration tweens, set_playback_rate), UIImageView draw order (the original also draws the background first), image format lists (Material, GLB images, the unused avif-parse), web text baking, the initialize name of Scene, the place of the web module in lib.rs
- Example devtoolsshowcase: Spin has #[vanilla::reflect], so degreesPerSecond shows in the inspector
- Example toonstyle: a scene comparing toon shading and outlines. (TOON_STYLE_SCALE sets the line buffer scale, TOON_STYLE_TOGGLES=1 the per-model options) The same scene as vanilla.js examples/toonstyle. Captured in a hidden window and compared with the original (headless Chrome) at 2560x1440, the average pixel difference is 0.005 and 0.024% of pixels differ by more than 8. (A few faint crease lines at the crease angle threshold)
- Example toonfx: switched to the new set_crease, set_depth_threshold
- Example toonfx: switched to the new set_crease(60.0, 0.011, 0.8) (world units), set_depth_threshold
- Example toonmaterial: removed the comparison against the Aberrant body shading formula. (It is one game's formula, and since the engine light model changed to the standard form it no longer gives the same values) Removed the normal length correction in the rock vertex chunk
- Example toonstyle: three shade tones, hard highlights, sun-side rim, spotlights, matcap, shell outlines with TOON_STYLE_SHELL=1. Compared with the original at 2560x1440, the average pixel difference is 0.004 and 0.018% of pixels differ by more than 8 (0.279% for the shell scene, MSAA differences at geometry edges)
- Example toonstyle: point light and spotlight shadows, shade-side rim, angel ring, shell outlines fading out and pushed along the camera direction. Compared with the original, the average pixel difference is 0.005 (0.008 with the half-size buffer, 0.163 for the shell due to MSAA differences)
- Docs: changed the description lines of function and type header comments (between two
//====lines) into rustdoc doc comments (///,//!for file headers,///directly above fields and enum values), and filled in a description and the# Arguments,# Returns,# Examplessections (headings written in Korean in the source) for the entire public API. Also added them to functions that had no header comment. The 869 examples (44 modules, 377 structs and traits, 384 members, 64 functions) are compiled and run bycargo test --doc. (Those that need a window or GL are only compiled, with no_run) The format is the doc comments part of chapter 8 'Code style' in ARCHITECTURE.md. Input fields, Pane, Canvas2D, LocalStorage, PersistedStore, storagetext and toon 3D only had their comment format changed, and their arguments, returns and examples will be filled in later - Guide docs/guide/0.4.0/ko, en: overview, getting started, architecture, tools, and 05 project setup through 19 authoring tools (the same chapters as the original vanilla.js guide), plus the Rust-only 20 reflection macro, 21 async/await, 22 porting from the original. Of the 216 code blocks, the rust blocks are compiled and run as doctests by the library target of tools/apidoc. (apidoc rewrites the chapter list tools/apidoc/src/guide.rs with an include_str doc attribute for each chapter file) Update notes docs/update/0.4.0.ko.md, .en.md
- Example toonstyle: tilts the camera with TOON_STYLE_ROLL. Compared with the original, the average pixel difference is 0.005 (0.005 for the tilted scene)
How to migrate
- A 3D color space setting: compose_toon_program_sources and ToonRenderer::read_material_program_sources take is_ambient_occlusion and color_space at the end (false and ColorSpace::Gamma to keep the old result). read_glb_arrays and read_glb_node_arrays take color_space: Option
at the end (None means the engine's value). ToonScreenOutline::read_program_sources takes color_space and returns five (String, String). Graphic::new takes the color space as its third argument. ToonLineTarget::jump_flood_index is Option (see ambient occlusion below). Code that builds ToonTextureOptions or ToonPostProcessOptions by listing every field adds is_color_data or color_space, or uses ..Default::default(). - Toon ambient occlusion: ToonLineTarget::jump_flood_index is Option
(None when nothing was flooded, the original uses -1). Games that used a zero-width outline (set_width(0) and crease width 0) will see that screen change. - Toon screen outline thin line path, resolution scale and clearing before buffers: ToonLineTarget seed_framebuffer and seed_texture are Option, jump_flood_framebuffers and jump_flood_textures are Vec (empty until a thick line is drawn), and edge_mask_framebuffer, edge_mask_texture, coverage_framebuffer (Option), coverage_texture (Option) and outline_path (ToonOutlinePath: None, Thin, ThinScaled, JumpFlood) are added. read_program_sources returns nine. The line_texture and depth_texture resolution of get_line_target is smaller than the drawing area when set_resolution_scale is below 1.
- Web image decoding through the browser: on the web, Image::load_from_memory, load_from_memory_with_mime_type and Engine::load_image (data: URL) return Err. Await ImageAsset::load or load_from_bytes, or load with AssetLoader. (the original has no path that decodes image bytes on the spot either)
- Subtree draw skipping: WorldNode::set_last_drawn_maximum_scale takes the draw frame number as its second argument (original setLastDrawnMaximumScale(maximumScale, frameNumber)). A user component that overrides calculate_drawn_rect calls mark_drawn_rect_dirty from setters that change that rect. Without it a drawing that grew into the screen may not be drawn. Replacing a NodeTransform as a whole (*get_transform_mut() = ...) does not report dirtiness, so use the setters.
- Streaming audio loading: background music played through SoundSystem streams when load_type is absent, so code that used that asset's get_audio_buffer() directly sets the sound row's load_type to Some(AudioLoadType::DecompressOnLoad). Code using AudioAsset directly keeps the same default and needs no change; to stream, call set_load_type(AudioLoadType::Streaming). A streaming asset's get_audio_buffer() is None. Code that builds SoundRow as a struct literal adds load_type: None. On desktop get_stream_url is the file path when loaded from a file and None when loaded from memory (on the web it is the URL or a blob: URL as in the original).
- Graphic no longer remembers bindings and 2D state separately and compares agains: removed Graphic::invalidate_render_state_cache (the original invalidateRenderStateCache was also removed). Delete the calls. If you changed state through the inner glow::Context without going through the state cache, call reset_gl_state_cache as before. Games that called restore_render_state outside run_external_pass to turn the stencil test back on use run_external_pass.
- Bone pose hook: callers of write_skin_pose add None at the end. (write_skin_pose(skeleton, name, time, &mut joint_matrices, blend, swing_scales, None))
- glTF quantized mesh reading: code that matches every AccessorArray variant adds the Byte and Short arms. (Otherwise a new feature)
- Toon highlight: code that builds ToonInstance as a struct literal appends ..ToonInstance::default(). (The engine examples already do) 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.
- Scene hook forms now match the original: change a scene's fn create(&mut self, engine: &Engine) to fn load(&mut self, engine: &Engine). Remove the engine argument from the other hooks, and if the body uses the engine, put let engine = Engine::get_engine().unwrap(); on the first line (the same engine). Remove engine from base calls as well: self.scene_base.tick(engine, time_delta) becomes self.scene_base.tick(time_delta), game_scene_base.create(engine) becomes game_scene_base.load(engine), and game_scene_base.draw_on_load(engine, graphic) becomes game_scene_base.draw_on_load(graphic).
- 3D render scale: the fifth argument of ToonViewDrawCallback changed from i32 (drawing buffer height) to ToonViewOutput. Replace hand-computed positions such as ToonPostProcess::end(gl, None, [x, drawing buffer height - y - height, width, height]) with end(gl, output.output_framebuffer, output.output_viewport). (same place at scale 1, and the right place with a render scale or inside an opacity layer)
- Engine GL context GlContext: code that writes the type of a callback argument (
|program: &ShaderProgram, gl: &glow::Context, kind: ToonProgramKind|,gl: &glow::Contextof a ToonView3D draw function) changes it togl: &GlContext. Changegl: &glow::Contexttaken by game helper functions togl: &GlContexttoo (if left as is, a compile error points it out). Removeuse glow::HasContext;(the methods are inherent methods of GlContext, so it works without it; keeping it only gives an unused import warning). Code that passes get_gl to engine functions stays as it is. glow types (glow::Texture and the like) and constants are used as they are. - Text drawing moved to a glyph atlas: TextEntry has no texture. Draw each glyph with glyph_textures and glyph_rects (left, top, right, bottom, u0, v0, u1, v1 relative to the top-left of the string rectangle). (Inside the engine Graphic::draw_text_entry does this) TextEntry is not Copy. (clone)
- Shadow and toast argument forms: set_shadow(Color::create(0.0, 0.0, 0.0, 0.8), 3.0, 4.0) becomes set_shadow("#000000", 0.8, 3.0, 4.0). ToastMotion::new(side) becomes ToastMotion::new() plus set_enter_side(side) (attach_toast_motion is unchanged). Move the function given to set_apply_text_handler to the third argument of show: toast_motion.show(text, seconds, move |context| { .. set the text .. }).
- No reserved-word names: cooldown.r#use() becomes cooldown.activate(), pass.r#use(gl) becomes pass.use_program(gl), pointer_gesture.r#move(x, y) becomes pointer_gesture.move_pointer(x, y), action.r#loop(..) becomes action.repeat_while(..), and easing_function::quadratic::r#in becomes easing_function::quadratic::ease_in (out and in_out become ease_out and ease_in_out).
- Text antialiasing as a Graphic method: replace graphic.get_text_string_texture_cache().set_text_antialias_enabled(value) with graphic.set_text_antialias_enabled(value). (The cache method still works)
- Matching the two engines: format_number and format_number_with_unit return Result<String, FormatError> (unwrap or ? for a valid tag). to_json_text_mut and serialize_node_mut are gone; pass &mut NodeTree to to_json_text and serialize_node. The draft Tilemap::get_tilesets returns &[Rc
], get_tileset returns Option<&Rc >, and get_tileset_mut is None while the tileset is shared with another map. add_tileset takes either a Tileset or an Rc - Logic numbers are f64: change f32 to f64 in game code (tick's time_delta, the arguments of Vector2::create and Color::create, component fields, getters and setters; std::f32::consts becomes std::f64::consts). Matrix4's elements, get_elements, write_to_array and write_to_slice are f32 like the original Float32Array; read them with the new read_elements (f64 array) when calculating per element. TransformMatrix::write_to_float32_array writes into [f32; 9]. Graphic::get_vertex_data, get_particle_vertex_data, ToonRenderer's instance data (create_instance_buffer), and the joint_matrices of ToonDrawOptions and ToonLineDrawOptions and the target of write_skin_pose are f32, so put f64 values in with as f32. The functions of Canvas2D and Path2D take f64 like the original. The desktop, like Chrome Blink, narrows to f32 as soon as it receives a value and calculates in float like Skia (path functions such as move_to, line_to, arc and rect use base::saturated_cast, so a number beyond f32 becomes infinity, and the others use ClampTo
, which clamps to the f32 limits with the sign); the web hands the f64 to the browser as is. Getters (such as get_line_width, get_shadow_blur, get_miter_limit, get_line_dash_offset) return f64, and get_global_alpha and get_line_dash return the stored value as is, like Chrome. CanvasRadius is built from f64 and (f64, f64). get_entry, find_entry, rasterize_text and rasterize_text_with_color of TextStringTextureCache take line_width and bake_scale as f64. (Like the original, the scale multiplication and the division by the baked size are computed in double) The fields of CanvasMatrix and CanvasGradientKind are f32 because they are Skia's float matrix and gradient; CanvasMatrix::create takes f64 and narrows it, and transform_point calculates in f64 and returns the result. The desktop rotate, like Chrome, narrows the angle to float and rotates with the Skia setRotate calculation (float radians, with sin and cos treated as 0 when within 1/65536). (At 90 degrees cos is 0, not -4.4e-8) LayoutExpression takes f64 and i32 instead of f32. When uploading uniforms to a game shader, pass them to glow's uniform_1_f32 functions with as f32. - Web dialogs and web context menu: Engine::alert, confirm, prompt no longer finish immediately on the web either. Get the answer from the handle's is_finished or set_callback, or await alert_async and the others (same as the desktop). Engine::is_modal_dialog_open can be true on the web too
- Reflection cannot be left out: put #[vanilla::reflect] on the impl block and the impl Component block of game components. A type without getters takes it on an empty block,
#[vanilla::reflect] impl Type {}. Component::get_reflection and get_reflection_mut are gone (upcast&dyn Componentto&dyn Reflect). collect_reflected_getters, collect_reflected_getters_in_tree and collect_reflected_getters_mut return a Vec without Option, and UIDocument::serialize_component returns a Map without Option. - GameScene loading and touch recognizer: GameSceneBase::get_touch_recognizer and get_touch_recognizer_mut return an Option. (None before initialize, undefined in the original)
- Shared 3D asset cache: destroy used to delete materials that nothing else held by Rc; it now matches the original and does not delete materials put in with set_material, so their owner destroys them. Drawable's mesh_description is Rc
and morph_target_list is Rc<Vec > (reading is unchanged, use Rc::make_mut to change them), and there is a new field is_morph_texture_shared. Code that loaded the same path several times and changed material values per model should take a copy with get_material(index). If each load needs its own parsed resources, call SkinnedModelAsset::clear_cache() or use load_from_bytes. Calling a handle's create_model again after it finished returns another instance of the same asset instead of building a new model. - JPEG decoding: a JPEG with EXIF orientation has the width and height after rotation. Code that expected the unrotated image saves the image again without orientation.
- Input field context menu: UIInputFieldMenuAction gains SelectAll and loses Undo, Redo, PasteAsPlainText, Emoji, WritingDirectionDefault, WritingDirectionLeftToRight, WritingDirectionRightToLeft and Inspect. Undo and redo are done with the keys (Ctrl+Z, Ctrl+Shift+Z). UIInputFieldWritingDirection and UIInputField::set_writing_direction and get_writing_direction are removed (the value never affected the text the engine draws)
- Component lookup: get_component::
() also returns a ShaderSprite, and get_component:: () returns the UIView embedded in a widget. Code that wanted only that exact type checks as_any().downcast_ref. remove_component:: () also removes subtypes such as Sprite. - Action: change start(&mut target) to start_with(&mut target), step(&mut target, time) to step_with(&mut target, time), start_on_node to start and step_on_node to step.
- FloatingText: code that subtracted that offset should pass coordinates relative to the parent's top-left like the original.
- JSON writing: code that compared stored JSON text against text like "1.0" should expect "1" like the original. Text already stored is still read as before.
- JSON writing: change get_component::
() on a spawned label node to get_component:: (). - Fallback font choice: no code changes. Text whose font string gives a name and used to draw with the default font chain (Mac Apple SD Gothic Neo, Windows Segoe UI, Malgun Gothic) now draws with the operating system fallback font like Chrome. To use the chain, put default at the end of the name list.
- FBX multiple materials: the drawable list of an FBX model grows by the number of materials. Code that expected drawable 0 to be the whole mesh looks up by material_name or material_index.
- SpriteAnimator.play: SpriteAnimator::play_on_node(node, ...) becomes SpriteAnimator::play(node, ...), and animator.play(...) becomes SpriteAnimator::play(node, ...) when a node is at hand or animator.play_clip(...) inside the complete callback.
- GamepadManager: the returned values are copies (Gamepad), not references (&Gamepad). Remove
.into_iter().cloned().collect()or.cloned()used to keep copies. Reading through get_gamepad_manager() also works. - Dropping an AudioPlayer: code that dropped a player to silence it calls stop() before dropping it. A looping sound keeps playing until stopped, as in the original.
- Font names: a quoted generic name in FontDescription.family_name_list comes with its quotes, like ""monospace"". Code that compared names strips the quotes first. GenericFamily::from_family_name("-webkit-body") is Standard, and find_family_font_file looks up a double-quoted name as a font name.
- Engine: no public API changed in a way that breaks compilation. Code that built GL resources when first drawing in a draw function keeps working as is. To build them in create, initialize like the original, move it into
if let Some(graphic) = engine.get_graphic() { ... graphic.get_gl() ... }. Calling engine.get_graphic() inside a draw function gives None, so use the graphic argument - FbxLoader: code that called play_animation or looked up nodes with names carrying the suffix uses the names without the suffix.
- ToonScreenOutline: (the public API changed)
- set_crease(angle, intensity, continuation pixels) → set_crease(angle, width, intensity). Width is in the units of set_width, intensity is 0 ~ 1. Continuation pixels are gone. A look similar to the old set_crease(60.0, 0.5, 2.0) is set_crease(60.0, 1.0, 0.8) in pixel units, and in world units a width of about half the outline width (set_crease(60.0, 0.011, 0.8) for set_width(0.022, World)). Since the width is in the units of set_width, giving 1 in world units makes the line 1 meter wide
- set_depth_threshold(depth threshold, contact threshold) → set_depth_threshold(depth threshold). Its meaning changed to tangent plane distance. The contact threshold is gone
- Meaning of set_width: the width of one line, half on each side of the edge. 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. (Measured in the original 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 set_width(0.020, ToonOutlineWidthUnit::World), set_crease(60.0, 0.016, 0.5), set_depth_threshold(0.08); the coverage sums differ by 1 % in the toonstyle scene at 1280 x 720)
- set_sample_count, TOON_SCREEN_OUTLINE_MAXIMUM_SAMPLES, TOON_SCREEN_OUTLINE_MAXIMUM_CREASE_SAMPLES are gone. Lightweight paths lower only set_resolution_scale
- get_outline_radius(), read_outline_radius() → get_line_widths(), read_line_widths() ([outline, crease line] in drawing area pixels)
- Line id limit 65535 → TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID (16383)
- mask_framebuffer, mask_texture of ToonLineTarget are gone. Instead seed_framebuffers, seed_textures (two RGBA16UI), seed_index
- draw_outline sets the viewport to the drawing area from begin_line_ids by itself
- Rebuilt toon shading in the standard form of real-time toon rendering.: (the public API changed)
- For smooth Lambert, clear_shade_ramp() or set_band_count(0)
- ToonBandRamp, get_band_ramp, get_band_count, clear_band_ramp are gone. ToonShadeRamp, get_shade_ramp, clear_shade_ramp
- set_specular(intensity, exponent) → set_specular(intensity, exponent, softness, color). The previous look is set_specular(intensity, exponent, 1.0, [1.0; 3]). get_specular() returns ToonSpecular
- set_rim_light(color, power) → set_rim_light(color, power, softness, sun-side mask). The same soft rim as before is (color, power, 1.0, 0.0), and it is not multiplied by the base color. get_rim_light() returns ToonRimLight
- When building ToonPointLight with field names, add ..ToonPointLight::default(). (New fields direction, inner_cone_angle, outer_cone_angle)
- 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 (finding the uniform location and uploading) changes to JointBlockBuffer::upload. Where morph weights were uploaded directly, use uniform vec4 morphWeights[24] and a vec4 array upload in place of uniform float morphWeights[96].