platform/web
웹 플랫폼. (wasm32)
- 원본처럼 캔버스를 창 안쪽에 꽉 채우고, 원본과 같은 옵션으로 WebGL2 컨텍스트를 얻는다.
- request_animation_frame 콜백마다 엔진 프레임 하나. (브라우저가 수직 동기에 맞춰 부르고, 콜백이 끝나면 화면을 넘긴다)
- 키보드, 마우스, 손가락을 받는다. 입력 필드의 글 입력(숨긴 DOM <input>, IME 조합, 문맥 메뉴)과 클립보드는 web/textinput.rs 가 맡는다.
- 키를 누르면 입력 매니저의 막을 키(set_prevented_keys)면 글자 입력칸에 쓰는 중이 아닐 때 기본 동작을 막는다. 마지막으로 쓴 장치를 키, 마우스, 손가락 사건마다 적는다.
- 오디오: 원본 engine.js 처럼 click / touchstart / keydown(설정하면 touchend / pointerup 도)은 user gesture 로 보고 engine.resume_on_user_gesture(), focus 와 페이지가 다시 보일 때는 engine.resume() 을 부른다.
- 페이지: visibilitychange, blur, focus, pointerdown 을 엔진의 페이지 이벤트로 넘기고, 다시 보이면 on_page_visibility_restored, 문서 resume 과 pageshow(persisted) 면 on_page_process_restored 를 부른다. (원본 setupAllDocumentEvents)
- 최대 FPS 는 원본처럼 세기 시작한 뒤 처리한 프레임 수로 차례를 정한다. (platform/framelimiter.rs, 90 Hz 에서 60 FPS 도 평균 60)
- 캔버스의 webglcontextlost, webglcontextrestored 에서 원본 WebGLStateCache 처럼 GL 상태 기억을 잊는다.
- 키, 마우스, 손가락, 페이지 사건은 프레임 콜백 안에서 다시 들어와도(게임 코드의 dispatchEvent, focus() 같은 것) 겹쳐 빌리지 않는다. 바로 빌릴 수 있으면 그 자리에서 처리하고, 못 빌리면 줄에 쌓았다가 프레임 콜백 끝에 온 차례대로 처리한다. (platform/eventqueue.rs)
- exit_application: 원본처럼 Capacitor 의 App.exitApp, 없으면 window.close 를 시도한다.
Web platform. (wasm32)
- As in the original, fills the window's inside with the canvas and gets a WebGL2 context with the same options as the original.
- One engine frame per request_animation_frame callback. (the browser calls it in step with vertical sync, and the screen is presented when the callback finishes)
- Receives keyboard, mouse and fingers. Text input for input fields (a hidden DOM <input>, IME composition, context menu) and the clipboard are handled by web/textinput.rs.
- When a key is pressed, if it is one of the input manager's keys to prevent (set_prevented_keys), the default action is prevented unless typing in a text input. The last used device is recorded on every key, mouse and finger event.
- Audio: as in the original engine.js, click / touchstart / keydown (and touchend / pointerup if set) count as a user gesture and call engine.resume_on_user_gesture(), and on focus and when the page becomes visible again engine.resume() is called.
- Page: passes visibilitychange, blur, focus, pointerdown as engine page events, calls on_page_visibility_restored when visible again, and on_page_process_restored on document resume and pageshow (persisted). (the original setupAllDocumentEvents)
- Max FPS decides turns by the number of frames processed since counting started, as in the original. (platform/framelimiter.rs, at 90 Hz 60 FPS also averages 60)
- On the canvas's webglcontextlost, webglcontextrestored, forgets the GL state cache like the original WebGLStateCache.
- Key, mouse, finger and page events do not borrow twice even when they re-enter inside the frame callback (like dispatchEvent or focus() in game code). If they can borrow right away they are handled on the spot, otherwise they are queued and handled in arrival order at the end of the frame callback. (platform/eventqueue.rs)
- exit_application: as in the original, tries Capacitor's App.exitApp, or window.close if missing.
use vanilla::platform;
let quality = platform::read_page_query_value("quality").unwrap_or_else(|| String::from("high"));
let safe_area_insets = platform::read_safe_area_insets();
let is_touch_first = platform::is_coarse_pointer();
println!("{} {:?} {}", quality, safe_area_insets, is_touch_first);PlatformWindowtype
엔진이 들고 있는 창 손잡이. (커서를 바꿀 때)
Window handle held by the engine. (for changing the cursor)
pub type PlatformWindow = web_sys::HtmlCanvasElement함수Functions
커서 보이기 설정.
- 캔버스의 cursor 스타일을 감출 때 none, 보일 때 빈 값(브라우저 기본)으로 쓴다.
Sets cursor visibility.
- Writes none to the canvas's cursor style when hiding, and an empty value (browser default) when showing.
- platform_windowOption<&PlatformWindow>
- 엔진 캔버스. (None 이면 아무것도 하지 않는다)Engine canvas. (does nothing if None)
- is_visiblebool
- 보이려면 true.true to show it.
커서 모양 설정. (캔버스의 cursor 스타일에 CSS 값을 쓴다, 빈 값이면 브라우저의 기본, 그림 커서는 CSS 값에 그림이 든다)
Sets the cursor shape. (writes the CSS value to the canvas's cursor style, an empty value is the browser default, for an image cursor the CSS value contains the image)
- platform_windowOption<&PlatformWindow>
- 엔진 캔버스. (None 이면 아무것도 하지 않는다)Engine canvas. (does nothing if None)
- cursor_value&CursorValue
- 커서 값. (css_value 를 그대로 쓴다)Cursor value. (css_value is written as is)
주된 손이 손가락인지. (CSS 의 pointer: coarse)
Whether the primary pointer is a finger. (CSS pointer: coarse)
반환Returnsbool matchMedia("(pointer: coarse)") 가 맞으면 true. window 가 없거나 읽지 못하면 false.true if matchMedia("(pointer: coarse)") matches. false if there is no window or it cannot be read.
문서의 초점이 글자 입력칸에 있는지. (글자 종류의 input, textarea, contenteditable, select)
Whether the document's focus is on a text input. (text-type input, textarea, contenteditable, select)
반환Returnsbool document.activeElement 가 글자 입력칸이면 true. (button, checkbox 같은 input 은 false, 초점이 없으면 false)true if document.activeElement is a text input. (inputs like button, checkbox are false, false if nothing is focused)
페이지 주소의 쿼리 값. (원본처럼 location.search 를 URLSearchParams 로 읽어 처음 값, 없으면 None)
Query value of the page address. (as in the original, reads location.search with URLSearchParams and takes the first value, None if missing)
- name&str
- 쿼리 이름. (safeArea 같은)Query name. (such as safeArea)
반환ReturnsOption<String> 그 이름의 첫 값. 쿼리에 없거나 window, location, URLSearchParams 를 읽지 못하면 None.First value with that name. None if not in the query or window, location, URLSearchParams cannot be read.
화면(client) 좌표에서 캔버스의 왼쪽 위. (원본 canvas.getBoundingClientRect() 의 left, top, 캔버스가 없으면 0)
Top-left of the canvas in screen (client) coordinates. (left, top of the original canvas.getBoundingClientRect(), 0 if there is no canvas)
반환ReturnsVector2 캔버스의 왼쪽 위 자리. (CSS 픽셀, 엔진 캔버스가 아직 없으면 0, 0)Top-left position of the canvas. (CSS pixels, 0, 0 if the engine canvas does not exist yet)
검증용 화면 저장. (원본처럼 내려받기, PNG 를 Blob 주소로 만들어 a 요소의 download 로 누른다)
Saves the screen for verification. (downloads it as in the original, makes the PNG a Blob URL and clicks it with the download of an a element)
- file_name&str
- 내려받을 파일 이름. (a 요소의 download 값)File name to download. (the download value of the a element)
- png_bytes&[u8]
- PNG 파일 바이트.PNG file bytes.
반환ReturnsResult<(), String> 내려받기를 눌렀으면 Ok. window, document, body, Blob, URL.createObjectURL 이 없거나 DOM 호출이 실패하면 Err(까닭 글).Ok if the download was clicked. Err(reason text) if window, document, body, Blob, URL.createObjectURL are missing or a DOM call fails.
페이지 전체 크기. (원본 window.innerWidth, innerHeight)
Full page size. (the original window.innerWidth, innerHeight)
반환ReturnsOption<Vector2> 창 안쪽 크기. (CSS 픽셀) window 가 없거나 값을 읽지 못하면 None.Inner size of the window. (CSS pixels) None if there is no window or the values cannot be read.
CSS env(safe-area-inset-*) 세이프 에어리어 인셋. (원본 viewManager.readSafeAreaFromEnvironment, CSS 픽셀 [위, 오른쪽, 아래, 왼쪽])
- 숨은 요소의 padding 에 env() 를 걸고 계산된 값을 parseFloat 로 읽는다. 문서나 body 가 없으면 0.
CSS env(safe-area-inset-*) safe area insets. (the original viewManager.readSafeAreaFromEnvironment, CSS pixels [top, right, bottom, left])
- Sets env() on the padding of a hidden element and reads the computed values with parseFloat. 0 if there is no document or body.
반환Returns[f64; 4] [위, 오른쪽, 아래, 왼쪽] 인셋. (CSS 픽셀, 읽지 못한 칸은 0)[top, right, bottom, left] insets. (CSS pixels, entries that could not be read are 0)
창 제목 설정. (문서 제목)
Sets the window title. (the document title)
- _platform_windowOption<&PlatformWindow>
- 엔진 캔버스. (쓰지 않는다, 데스크탑과 같은 꼴을 맞춘 것)Engine canvas. (not used, kept to match the desktop form)
- title&str
- 제목 글. (document.title)Title text. (document.title)
pub fn request_asset_bytes(asset_location: String, load_handle: AssetLoadHandle, is_no_cache: bool)#애셋 바이트 읽기. (fetch 로 받고, 받으면 끝낸다. 그 사이 프레임은 계속 돈다)
- 응답의 content-type 을 손잡이에 적는다. (원본 Material.loadImageDescription 의 response.headers.get("content-type"))
- 응답이 그림 형(image/...)이거나 주소가 그림 확장자(png, jpg, gif, webp, bmp, ico, svg, avif 등)면 끝내기 전에 원본처럼 브라우저가 풀게 해 손잡이에 둔다. (ImageAsset, AssetLoader 가 그대로 쓴다) 원본 HTMLImageElement 처럼 응답의 content-type 을 그대로 형으로 넘겨, 브라우저가 SVG 는 그 형(image/svg+xml)으로, 그 밖의 그림은 내용으로 가린다. 머리가 없는 응답만 확장자의 형을 쓴다. data: 주소는 fetch 가 주소의 형을 content-type 으로 준다.
- 그림으로 풀어야 하는 손잡이(ImageAsset, AssetLoader 의 그림)는 형과 확장자가 그림이 아니어도 형 없이 브라우저가 내용으로 가려 푼다. (원본 img.src 와 같다, 웹에는 엔진 해독기가 없다)
Reads asset bytes. (receives with fetch and finishes once received. Frames keep running in the meantime)
- Records the response's content-type on the handle. (response.headers.get("content-type") of the original Material.loadImageDescription)
- If the response is an image type (image/...) or the URL has an image extension (png, jpg, gif, webp, bmp, ico, svg, avif, etc.), lets the browser decode it as in the original before finishing and keeps it on the handle. (ImageAsset, AssetLoader use it as is) Like the original HTMLImageElement, passes the response's content-type as the type as is, so the browser treats SVG by that type (image/svg+xml) and other images by their content. Only responses without the header use the extension's type. For data: URLs, fetch gives the URL's type as content-type.
- Handles that must be decoded as images (images of ImageAsset and AssetLoader) are decoded by the browser by content without a type, even if the type and extension are not images. (same as the original img.src; the web has no engine decoder)
- asset_locationString
- 받을 주소. (엔진이 애셋 경로로 만든 것, data: 주소도 된다)URL to receive. (made from the asset path by the engine, data: URLs work too)
- load_handleAssetLoadHandle
- 다 받으면 바이트나 오류 글로 끝낼 손잡이.Handle to finish with the bytes or error text once received.
- is_no_cachebool
- true 면 fetch 에 cache: "no-cache" 를 붙인다. (원본 TextAsset)If true, adds cache: "no-cache" to fetch. (the original TextAsset)
시작. (캔버스와 WebGL2 를 잡고 request_animation_frame 을 걸어 둔 뒤 바로 돌아온다)
Starts. (grabs the canvas and WebGL2, sets up request_animation_frame and returns right away)
- engine_runnerEngineRunner
- 엔진 실행자. (Engine::run 이 엔진과 첫 씬으로 만들어 넘긴다)Engine runner. (Engine::run makes it with the engine and the first scene and passes it)
반환ReturnsResult<(), String> 프레임 콜백을 걸었으면 Ok. 캔버스나 WebGL2 컨텍스트를 얻지 못했거나 사건 리스너를 달지 못했으면 Err(까닭 글).Ok if the frame callback was set. Err(reason text) if the canvas or WebGL2 context could not be obtained or event listeners could not be attached.
응용 프로그램 종료. (원본 exitApplication: Capacitor 네이티브면 App 플러그인으로 끝내고, 아니면 창 닫기를 시도한다)
- 둘 다 환경에 따라 거부될 수 있으며 실패해도 오류를 내지 않는다. 엔진은 종료 요청을 적어 다음 프레임부터 돌지 않는다.
Exits the application. (the original exitApplication: exits with the App plugin if Capacitor native, otherwise tries to close the window)
- Either can be refused depending on the environment, and no error is raised on failure. The engine records the exit request and stops running from the next frame.
바깥 주소 열기. (원본 Engine.openUrl, window.open(주소, "_blank", "noopener") 로 새 탭에 연다)
- 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열린다. 브라우저의 팝업 차단 규칙이다.
- 열 수 있는 것은 http, https, mailto, tel 뿐이다. (is_openable_url) 그 밖의 꼴은 열지 않고 false.
Opens an outside URL. (original Engine.openUrl, opens a new tab with window.open(url, "_blank", "noopener"))
- It opens only when called inside user input (click, tap, key) handling. This is the browser's popup-blocking rule.
- Only http, https, mailto and tel can be opened. (is_openable_url) Other forms are not opened and return false.
- url&str
- 열 주소. (http, https, mailto, tel 꼴)URL to open. (http, https, mailto or tel)
반환Returnsbool 브라우저에 열기를 넘겼으면 true.True if the open was handed to the browser.
현지 시각 읽기. (원본 Engine.readLocalTime, new Date(Date.now() + 오프셋 분) 의 현지 달력 시각)
Read the local time. (same as the original Engine.readLocalTime, the local calendar time of new Date(Date.now() + offset minutes))
- minute_offsetf64
- 지금에 더할 분. (음수는 과거, 0 이면 지금)Minutes to add to now. (negative is the past, 0 is now)
반환Returnscrate::platform::LocalTime 더한 때를 브라우저 시간대로 본 달력 시각.The calendar time of the shifted moment in the browser's time zone.