javascript/3d/demo_3d.js · 2502 字节 · 下载原文
// demo_3d.js —— 第 5 层:**3D 视口**(`ui_3d_*`,独立库 vml3d)
// demo_3d.js — Layer 5: **3D viewport** (`ui_3d_*`, the separate vml3d library)
//
// 这一层画在 2D 画布之上:视口自带相机 / 视场角 / 背景色 / 一盏方向光,
// 模型从同目录的 `box.glb`(CC0,glTF 2.0)装载;2D 那层只负责清屏。
// This layer draws on top of the 2D canvas: the viewport owns a camera, field of view,
// background colour and one directional light; the model comes from `box.glb` (CC0,
// glTF 2.0) next to this file, while the 2D layer only clears the canvas.
//
// 跑法 / How to run:
// 手机 vml run examples/javascript/3d/demo_3d.js
// 桌面 vmlcli Examples/javascript/3d/demo_3d.js --screen 640x480 --frames /tmp/f3d
//
// ⚠ 3D 是**透过** 2D 层显示的 ⇒ 必须 `ui_2d_clear(0)`;`box.glb` 走相对路径
// (宿主沙箱根 = 源文件所在目录)。
// ⚠ The 3D output shows **through** the 2D layer, so `ui_2d_clear(0)` is mandatory;
// `box.glb` is relative (the host sandbox root is the source-file directory).
#include <vml_ui.js>
#include <vml3d.js>
var frames = 20; // 20 帧 × 40ms ≈ 0.8 秒 / 20 frames x 40ms ~ 0.8s
// ① 开窗:宽高传 0 = 交给宿主用真实可用区
// ① Open the window: size 0 = the host picks the real usable area
ui_win_open_ex("demo_3d (JavaScript)", 0, 0, 0, 0);
var w = ui_scr_get_w();
var h = ui_scr_get_h();
// ② 建视口 + 相机 / 视场 / 背景 / 灯光
// ② Create the viewport plus camera / FOV / background / light
var vp = ui_3d_viewport_create(0, 0, w, h, 0);
ui_3d_viewport_set_camera(vp, 0.0, 1.5, 4.0, 0.0, 0.0, 0.0);
ui_3d_viewport_set_fov(vp, 50.0, 0.1, 100.0);
ui_3d_viewport_set_bg(vp, 0xFF14202F);
ui_3d_viewport_set_light(vp, 0.4, 0.9, 0.6, 0xFFFFFFFF, 0.3);
// ③ 2D 层清成透明,让 3D 透出来 / Clear the 2D layer to transparent so the 3D shows through
ui_2d_clear(0);
// ④ 装载模型(返回场景句柄)/ Load the model (returns a scene handle)
var scene = ui_3d_gltf_load(vp, "box.glb");
// ⑤ 有界渲染循环:交帧 + 等一条消息 / Bounded render loop: present + wait for one message
var i = 0;
while (i < frames) {
ui_2d_present();
ui_msg_fetch_wait(40);
i = i + 1;
}
// ⑥ 收尾:释放场景 / 视口,再关窗
// ⑥ Wrap-up: free the scene/viewport, then close the window
ui_3d_gltf_free(scene);
ui_3d_viewport_free(vp);
ui_win_close();
console.log("demo_3d done (JavaScript)");