修改场景材质光照

This commit is contained in:
2026-10-30 18:40:29 +08:00
parent 1c837766cd
commit 738095c60d
12 changed files with 873 additions and 23 deletions
+2
View File
@@ -2,6 +2,8 @@
主站使用静态页面,仿真运行器需要先构建。three.js、urdf-loader、marked、DOMPurify 和字体都放在 vendor/(`node scripts/vendor.mjs` 下载),不依赖外部 CDN;3D 引擎只在需要的页面按需加载。
项目详情页统一采用 Robot Viewer 的光照和高光风格:白色主光 + 补光、半球光、Phong 高光材质、无色调映射和 PCF 柔和阴影,保留模型原色与已有 PBR 材质。原始 URDF 和压缩 GLB 使用相同规则;背景和地面保持原样。Phong 使用中性反射环境,已有 PBR 材质继续使用本地 `assets/environments/monochrome_studio_02_1k.hdr`(PMREM 过滤,加载失败时回退到程序棚拍环境)。移植来源与许可证见 `vendor/robot-viewer/NOTICE`。
## 本地运行
详情页的「行走演示」使用 `sandbox/` 中的运动运行器,首次启动先运行:
Binary file not shown.
+36 -9
View File
@@ -10,23 +10,41 @@ const PRESETS = {
rubber: { roughness: 0.86, metalness: 0, clearcoat: 0, clearcoatRoughness: 0.1 },
};
function hasAuthoredPbr(src) {
if (!src?.isMeshStandardMaterial) return false;
const hasTexture = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap', 'bumpMap', 'alphaMap'].some((key) => src[key]);
return src.isMeshPhysicalMaterial || hasTexture || src.roughness !== 1 || src.metalness !== 0;
}
// Phong enhancement adapted from fan-ziqi/robot_viewer, Copyright 2025 Ziqi Fan, Apache-2.0.
// Modified to preserve authored PBR materials, imported texture channels and named overrides.
// See vendor/robot-viewer/LICENSE and vendor/robot-viewer/NOTICE.
function enhancePhongMaterial(mat, envMap) {
mat.shininess = Math.max(mat.shininess, 50);
if (Math.min(mat.specular.r, mat.specular.g, mat.specular.b) < 0.2) mat.specular.setRGB(0.3, 0.3, 0.3);
mat.envMap = envMap || mat.envMap;
mat.reflectivity = 0.3;
}
// PBR 模型保留贴图、物理参数和多材质分组;只有 URDF / STL 的简单材质需要补齐。
export function prepareRobotMaterial(original, paint = {}) {
if (Array.isArray(original)) return original.map((mat) => prepareRobotMaterial(mat, paint));
export function prepareRobotMaterial(original, paint = {}, options = {}) {
if (Array.isArray(original)) return original.map((mat) => prepareRobotMaterial(mat, paint, options));
const src = original;
const usePhong = options.renderPreset === 'studio' && !hasAuthoredPbr(src);
let mat;
if (src?.isMeshStandardMaterial) {
if (usePhong && src?.isMeshPhongMaterial) {
mat = src.clone();
} else if (!usePhong && src?.isMeshStandardMaterial) {
mat = src.clone();
const hasTexture = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap', 'bumpMap', 'alphaMap'].some((key) => src[key]);
const hasAuthoredPbr = src.isMeshPhysicalMaterial || hasTexture || src.roughness !== 1 || src.metalness !== 0;
// STL-to-GLB conversion creates a default white StandardMaterial; treat that placeholder like URDF/STL fallback.
if (!hasAuthoredPbr) Object.assign(mat, PRESETS.showcase);
if (!hasAuthoredPbr(src)) Object.assign(mat, PRESETS.showcase);
} else {
const hasColor = src?.color && !(src.color.r === 1 && src.color.g === 1 && src.color.b === 1 && src.isMeshPhongMaterial && !src.name);
mat = new THREE.MeshPhysicalMaterial({
const Material = usePhong ? THREE.MeshPhongMaterial : THREE.MeshPhysicalMaterial;
mat = new Material({
name: src?.name || '',
color: hasColor ? src.color : DEFAULT_COLOR,
...PRESETS.showcase,
...(usePhong ? {} : PRESETS.showcase),
});
// 贴图共享原资源,颜色 / 向量独立复制,避免悬停高亮影响别的零件。
for (const key of ['map', 'normalMap', 'normalMapType', 'bumpMap', 'bumpScale', 'alphaMap', 'aoMap', 'aoMapIntensity', 'lightMap', 'lightMapIntensity', 'emissiveMap', 'emissiveIntensity', 'displacementMap', 'displacementScale', 'displacementBias', 'transparent', 'opacity', 'alphaTest', 'side', 'depthWrite', 'depthTest', 'vertexColors', 'flatShading']) {
@@ -35,13 +53,22 @@ export function prepareRobotMaterial(original, paint = {}) {
if (src?.normalScale) mat.normalScale.copy(src.normalScale);
if (src?.emissive) mat.emissive.copy(src.emissive);
}
if (usePhong) enhancePhongMaterial(mat, options.envMap);
for (const [name, value] of Object.entries(paint)) {
if (!mat.name.includes(name)) continue;
const override = typeof value === 'string' ? { color: value } : value;
if (PRESETS[override.preset]) Object.assign(mat, PRESETS[override.preset]);
const finish = { ...PRESETS[override.preset], ...override };
if (override.color !== undefined) mat.color.set(override.color);
if (override.emissive !== undefined) mat.emissive.set(override.emissive);
if (mat.isMeshPhongMaterial) {
// Existing roughness overrides still control highlight width in the legacy shader.
if (finish.roughness !== undefined) mat.shininess = THREE.MathUtils.clamp(2 / Math.max(finish.roughness, 0.04) ** 2 - 2, 1, 1000);
if (finish.metalness !== undefined) mat.specular.setScalar(THREE.MathUtils.lerp(0.05, 0.3, finish.metalness));
if (finish.emissiveIntensity !== undefined) mat.emissiveIntensity = finish.emissiveIntensity;
continue;
}
if (PRESETS[override.preset]) Object.assign(mat, PRESETS[override.preset]);
for (const key of ['roughness', 'metalness', 'envMapIntensity', 'emissiveIntensity', 'clearcoat', 'clearcoatRoughness']) {
if (override[key] !== undefined) mat[key] = override[key];
}
+35
View File
@@ -0,0 +1,35 @@
// Adapted from fan-ziqi/robot_viewer (Copyright 2025 Ziqi Fan), Apache-2.0.
// Modified for vibemake's normalized robot scale and existing stage.
// See vendor/robot-viewer/LICENSE and vendor/robot-viewer/NOTICE.
import * as THREE from 'three';
export function configureRobotViewerRenderer(renderer) {
renderer.toneMapping = THREE.NoToneMapping;
renderer.toneMappingExposure = 1;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
}
export function createRobotViewerLights(scene) {
const ambient = new THREE.HemisphereLight(0xffffff, 0x444444, 0.5);
ambient.position.set(0, 1, 0);
const key = new THREE.DirectionalLight(0xffffff, Math.PI);
// Directional light keeps the original angle; distance fits our unit-sized robots.
const keyOffset = new THREE.Vector3(4, 10, 1).normalize().multiplyScalar(4);
key.position.copy(keyOffset);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
Object.assign(key.shadow.camera, { left: -1.4, right: 1.4, top: 1.4, bottom: -1.4, near: 0.1, far: 8 });
key.shadow.normalBias = 0.001;
const fill = new THREE.DirectionalLight(0xffffff, Math.PI * 0.3);
fill.position.set(-2, 2, -2);
scene.add(ambient, key, key.target, fill);
return { key, keyOffset };
}
export function createRobotViewerReflectionMap() {
// The reference viewer uses a uniform white cube for Phong reflections.
const face = new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1);
const texture = new THREE.CubeTexture(Array(6).fill(face));
texture.needsUpdate = true;
return texture;
}
+9 -1
View File
@@ -1,6 +1,14 @@
import * as THREE from 'three';
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
// 只用于 IBL:柔光板形成宽高光,暗区保留反射层次,不增加逐帧的灯光开销。
const STUDIO_HDR_URL = new URL('../assets/environments/monochrome_studio_02_1k.hdr', import.meta.url).href;
// HDR 只参与照明和金属反射;场景背景由页面样式独立控制。
export function loadStudioHDR() {
return new RGBELoader().loadAsync(STUDIO_HDR_URL);
}
// HDR 加载失败时的本地备用环境。
export function createStudioEnvironment() {
const scene = new THREE.Scene();
const room = new THREE.Mesh(
+41 -11
View File
@@ -11,9 +11,10 @@ import URDFLoader from 'urdf-loader';
import { URDFDragControls } from 'urdf-loader/src/URDFDragControls.js';
import { MotionController } from './motion.js';
import { prepareRobotMaterial } from './robot-materials.js';
import { createStudioEnvironment } from './studio-environment.js';
import { createStudioEnvironment, loadStudioHDR } from './studio-environment.js';
import { RenderBudget, RenderLoop } from './render-budget.js';
import { fetchResource, queueModelResource } from './resource-loading.js';
import { configureRobotViewerRenderer, createRobotViewerLights, createRobotViewerReflectionMap } from './robot-viewer-lighting.js';
export const ACCENT = '#c8ff3e';
const GRID_SPACING = 0.075;
@@ -64,6 +65,7 @@ export class RobotViewer extends EventTarget {
r.shadowMap.enabled = this.budget.shadows;
// PCFShadowMap 的 radius 才能控制采样范围;PCFSoftShadowMap 会忽略它。
r.shadowMap.type = this.studioLighting ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
if (this.studioLighting) configureRobotViewerRenderer(r);
r.domElement.classList.add('vm-canvas');
// 第一帧画出来之前隐藏,避免刷新时闪白。
// 用 visibility 而不是 opacity 渐变:Chrome 对 WebGL 画布做透明度动画时偶尔会合成出一块白
@@ -97,6 +99,7 @@ export class RobotViewer extends EventTarget {
this.scene = new THREE.Scene();
this.createEnvironment();
this.phongEnvironment = this.studioLighting ? createRobotViewerReflectionMap() : null;
this.camera = new THREE.PerspectiveCamera(32, 1, 0.01, 100);
this.camera.position.set(1.8, 0.9, 2.0);
@@ -153,27 +156,50 @@ export class RobotViewer extends EventTarget {
this.scene.environment = this.environment.texture;
disposeObject(room);
pmrem.dispose();
this.environmentReady = this.studioLighting ? this.loadStudioEnvironment() : Promise.resolve();
}
async loadStudioEnvironment() {
let hdr, pmrem;
try {
hdr = await loadStudioHDR();
if (this.disposed) return;
pmrem = new THREE.PMREMGenerator(this.renderer);
const target = pmrem.fromEquirectangular(hdr);
const previous = this.environment;
this.environment = target;
this.scene.environment = target.texture;
previous.dispose();
} catch (error) {
if (!this.disposed) console.warn('[vibemake] HDR 环境加载失败,使用备用棚拍环境', error);
} finally {
hdr?.dispose();
pmrem?.dispose();
}
}
addLights() {
const s = this.scene;
const studio = this.studioLighting;
s.add(new THREE.HemisphereLight(studio ? 0xffffff : 0xdfe4ea, 0x0b0c0e, studio ? 0.16 : 0.9));
const key = new THREE.DirectionalLight(0xffffff, studio ? 3 : 2.4);
this.keyOffset = new THREE.Vector3(...(studio ? [2.5, 3, 3.5] : [1.6, 3.2, 1.4]));
if (this.studioLighting) {
Object.assign(this, createRobotViewerLights(s));
return;
}
s.add(new THREE.HemisphereLight(0xdfe4ea, 0x0b0c0e, 0.9));
const key = new THREE.DirectionalLight(0xffffff, 2.4);
this.keyOffset = new THREE.Vector3(1.6, 3.2, 1.4);
key.position.copy(this.keyOffset);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
Object.assign(key.shadow.camera, { left: -1.4, right: 1.4, top: 1.4, bottom: -1.4, near: 0.1, far: 8 });
key.shadow.bias = studio ? -0.00015 : -0.0004;
key.shadow.normalBias = studio ? 0.003 : 0.02;
key.shadow.radius = studio ? 4 : 6;
key.shadow.bias = -0.0004;
key.shadow.normalBias = 0.02;
key.shadow.radius = 6;
this.key = key;
s.add(key, key.target);
const rim = new THREE.DirectionalLight(studio ? 0xffffff : new THREE.Color(ACCENT), studio ? 0.55 : 1.1);
const rim = new THREE.DirectionalLight(new THREE.Color(ACCENT), 1.1);
rim.position.set(-2.2, 1.4, -2.4);
s.add(rim);
const fill = new THREE.DirectionalLight(studio ? 0xffffff : 0x9fb4ff, studio ? 0.18 : 0.35);
const fill = new THREE.DirectionalLight(0x9fb4ff, 0.35);
fill.position.set(-2, 0.6, 2);
s.add(fill);
}
@@ -423,9 +449,11 @@ export class RobotViewer extends EventTarget {
if (!o.isMesh) return;
o.castShadow = true;
o.receiveShadow = true;
o.material = prepareRobotMaterial(o.material, config.paint);
o.material = prepareRobotMaterial(o.material, config.paint, { renderPreset: this.opts.renderPreset, envMap: this.phongEnvironment });
});
this.addExtras(robot, config.extras);
// 第一帧直接使用 HDR,避免模型出现后反射、亮度突然变化。
await this.environmentReady;
return robot;
}
@@ -707,6 +735,7 @@ export class RobotViewer extends EventTarget {
}
dispose() {
this.disposed = true;
this.loadToken++;
this.loadController?.abort();
for (const controller of this.pendingBuilds) controller.abort();
@@ -718,6 +747,7 @@ export class RobotViewer extends EventTarget {
this.clearRobot();
this.controls.dispose();
this.environment.dispose();
this.phongEnvironment?.dispose();
disposeObject(this.scene);
this.scene.traverse((object) => object.shadow?.dispose());
this.renderer.domElement.remove();
+7 -2
View File
@@ -16,6 +16,7 @@ const ENTRIES = [
['three', 'examples/jsm/environments/RoomEnvironment.js'],
['three', 'examples/jsm/loaders/GLTFLoader.js'],
['three', 'examples/jsm/loaders/DRACOLoader.js'],
['three', 'examples/jsm/loaders/RGBELoader.js'],
['three', 'examples/jsm/loaders/OBJLoader.js'],
['three', 'examples/jsm/loaders/STLLoader.js'],
['three', 'examples/jsm/loaders/ColladaLoader.js'],
@@ -25,7 +26,10 @@ const ENTRIES = [
['dompurify', 'dist/purify.es.mjs'],
];
// Draco 解码器(GLB 模型压缩用),不是 import 进来的,单独列出
const EXTRA = ['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js'].map((f) => ['three', `examples/jsm/libs/draco/gltf/${f}`]);
const EXTRA = [
...['draco_decoder.js', 'draco_decoder.wasm', 'draco_wasm_wrapper.js'].map((f) => ['three', `examples/jsm/libs/draco/gltf/${f}`]),
['three', 'LICENSE'],
];
const done = new Set();
async function get(pkg, path) {
@@ -71,7 +75,8 @@ async function fonts() {
return n;
}
rmSync(OUT, { recursive: true, force: true });
// Only replace downloaded packages; retain notices for locally adapted code.
for (const pkg of [...Object.keys(PKGS), 'fonts']) rmSync(join(OUT, pkg), { recursive: true, force: true });
for (const [pkg, path] of [...ENTRIES, ...EXTRA]) await get(pkg, path);
const n = await fonts();
console.log(`已下载 ${done.size} 个库文件、${n} 个字体文件到 vendor/`);
+52
View File
@@ -102,3 +102,55 @@ test('keeps transparent legacy material settings and accepts a material preset w
assert.equal(material.normalScale.x, 0.5);
assert.equal(material.normalScale.y, 0.7);
});
test('detail preset keeps the same color and Phong highlights for URDF and compressed GLB placeholders', () => {
const envMap = new THREE.CubeTexture();
const options = { renderPreset: 'studio', envMap };
const urdf = new THREE.MeshPhongMaterial({ name: 'shell', color: '#9b7600', transparent: true, opacity: 0.6 });
const glb = new THREE.MeshStandardMaterial({ name: 'shell', color: '#9b7600', transparent: true, opacity: 0.6 });
const materials = [urdf, glb].map((source) => prepareRobotMaterial(source, {}, options));
for (const material of materials) {
assert.equal(material.isMeshPhongMaterial, true);
assert.equal(material.color.getHexString(), '9b7600');
assert.equal(material.shininess, 50);
assert.deepEqual(material.specular.toArray(), [0.3, 0.3, 0.3]);
assert.equal(material.envMap, envMap);
assert.equal(material.reflectivity, 0.3);
assert.equal(material.opacity, 0.6);
assert.equal(material.transparent, true);
}
assert.equal(urdf.shininess, 30);
assert.equal(glb.envMap, null);
});
test('detail preset preserves authored PBR texture channels and metallic parameters', () => {
const options = { renderPreset: 'studio', envMap: new THREE.CubeTexture() };
const source = new THREE.MeshStandardMaterial({
color: '#315cb0', roughness: 0.62, metalness: 0.2, normalMap: new THREE.Texture(),
});
const material = prepareRobotMaterial(source, {}, options);
assert.equal(material.isMeshStandardMaterial, true);
assert.equal(material.isMeshPhongMaterial, undefined);
assert.equal(material.roughness, source.roughness);
assert.equal(material.metalness, source.metalness);
assert.equal(material.normalMap, source.normalMap);
assert.equal(material.envMap, source.envMap);
assert.equal(material.color.getHex(), source.color.getHex());
});
test('detail preset keeps material slots, texture settings and hover emission independent', () => {
const source = new THREE.MeshLambertMaterial({ name: 'cover', color: '#335577', map: new THREE.Texture(), opacity: 0.4, transparent: true });
const led = new THREE.MeshPhongMaterial({ name: 'led', emissive: '#00ff00', emissiveIntensity: 0.4, shininess: 90 });
const [cover, light] = prepareRobotMaterial([source, led], { cover: { roughness: 0.45 } }, { renderPreset: 'studio' });
assert.equal(cover.isMeshPhongMaterial, true);
assert.equal(cover.map, source.map);
assert.equal(cover.opacity, source.opacity);
assert.equal(cover.transparent, source.transparent);
assert.equal(cover.color.getHex(), source.color.getHex());
assert.ok(cover.shininess < light.shininess);
assert.equal(light.shininess, 90);
light.emissive.set('#ffffff');
assert.equal(light.userData.baseEmissive.color.getHexString(), '00ff00');
assert.equal(light.userData.baseEmissive.intensity, 0.4);
assert.equal(led.emissive.getHexString(), '00ff00');
});
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Ziqi Fan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+19
View File
@@ -0,0 +1,19 @@
Robot Viewer
https://github.com/fan-ziqi/robot_viewer
Copyright 2025 Ziqi Fan
Licensed under the Apache License, Version 2.0. See LICENSE.
vibemake adapts lighting, renderer defaults and Phong material enhancement from:
src/renderer/EnvironmentManager.js
src/renderer/SceneManager.js
src/adapters/URDFAdapter.js
src/utils/MeshLoader.js
Modified files:
js/robot-viewer-lighting.js
js/robot-materials.js
Changes: normalized light distances for unit-sized robots; retained vibemake's
background and ground; applied the same Phong finish to URDF and compressed
GLB placeholders; preserved authored PBR materials, textures, colors and
material slots; retained the local HDR environment for authored PBR materials.
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright © 2010-2023 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+450
View File
@@ -0,0 +1,450 @@
import {
DataTextureLoader,
DataUtils,
FloatType,
HalfFloatType,
LinearFilter,
LinearSRGBColorSpace
} from 'three';
// https://github.com/mrdoob/three.js/issues/5552
// http://en.wikipedia.org/wiki/RGBE_image_format
class RGBELoader extends DataTextureLoader {
constructor( manager ) {
super( manager );
this.type = HalfFloatType;
}
// adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html
parse( buffer ) {
const
/* default error routine. change this to change error handling */
rgbe_read_error = 1,
rgbe_write_error = 2,
rgbe_format_error = 3,
rgbe_memory_error = 4,
rgbe_error = function ( rgbe_error_code, msg ) {
switch ( rgbe_error_code ) {
case rgbe_read_error: throw new Error( 'THREE.RGBELoader: Read Error: ' + ( msg || '' ) );
case rgbe_write_error: throw new Error( 'THREE.RGBELoader: Write Error: ' + ( msg || '' ) );
case rgbe_format_error: throw new Error( 'THREE.RGBELoader: Bad File Format: ' + ( msg || '' ) );
default:
case rgbe_memory_error: throw new Error( 'THREE.RGBELoader: Memory Error: ' + ( msg || '' ) );
}
},
/* offsets to red, green, and blue components in a data (float) pixel */
//RGBE_DATA_RED = 0,
//RGBE_DATA_GREEN = 1,
//RGBE_DATA_BLUE = 2,
/* number of floats per pixel, use 4 since stored in rgba image format */
//RGBE_DATA_SIZE = 4,
/* flags indicating which fields in an rgbe_header_info are valid */
RGBE_VALID_PROGRAMTYPE = 1,
RGBE_VALID_FORMAT = 2,
RGBE_VALID_DIMENSIONS = 4,
NEWLINE = '\n',
fgets = function ( buffer, lineLimit, consume ) {
const chunkSize = 128;
lineLimit = ! lineLimit ? 1024 : lineLimit;
let p = buffer.pos,
i = - 1, len = 0, s = '',
chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
while ( ( 0 > ( i = chunk.indexOf( NEWLINE ) ) ) && ( len < lineLimit ) && ( p < buffer.byteLength ) ) {
s += chunk; len += chunk.length;
p += chunkSize;
chunk += String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
}
if ( - 1 < i ) {
/*for (i=l-1; i>=0; i--) {
byteCode = m.charCodeAt(i);
if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++;
else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2;
if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate
}*/
if ( false !== consume ) buffer.pos += len + i + 1;
return s + chunk.slice( 0, i );
}
return false;
},
/* minimal header reading. modify if you want to parse more information */
RGBE_ReadHeader = function ( buffer ) {
// regexes to parse header info fields
const magic_token_re = /^#\?(\S+)/,
gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,
exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,
format_re = /^\s*FORMAT=(\S+)\s*$/,
dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,
// RGBE format header struct
header = {
valid: 0, /* indicate which fields are valid */
string: '', /* the actual header string */
comments: '', /* comments found in header */
programtype: 'RGBE', /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */
format: '', /* RGBE format, default 32-bit_rle_rgbe */
gamma: 1.0, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */
exposure: 1.0, /* a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0 */
width: 0, height: 0 /* image dimensions, width/height */
};
let line, match;
if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) {
rgbe_error( rgbe_read_error, 'no header found' );
}
/* if you want to require the magic token then uncomment the next line */
if ( ! ( match = line.match( magic_token_re ) ) ) {
rgbe_error( rgbe_format_error, 'bad initial token' );
}
header.valid |= RGBE_VALID_PROGRAMTYPE;
header.programtype = match[ 1 ];
header.string += line + '\n';
while ( true ) {
line = fgets( buffer );
if ( false === line ) break;
header.string += line + '\n';
if ( '#' === line.charAt( 0 ) ) {
header.comments += line + '\n';
continue; // comment line
}
if ( match = line.match( gamma_re ) ) {
header.gamma = parseFloat( match[ 1 ] );
}
if ( match = line.match( exposure_re ) ) {
header.exposure = parseFloat( match[ 1 ] );
}
if ( match = line.match( format_re ) ) {
header.valid |= RGBE_VALID_FORMAT;
header.format = match[ 1 ];//'32-bit_rle_rgbe';
}
if ( match = line.match( dimensions_re ) ) {
header.valid |= RGBE_VALID_DIMENSIONS;
header.height = parseInt( match[ 1 ], 10 );
header.width = parseInt( match[ 2 ], 10 );
}
if ( ( header.valid & RGBE_VALID_FORMAT ) && ( header.valid & RGBE_VALID_DIMENSIONS ) ) break;
}
if ( ! ( header.valid & RGBE_VALID_FORMAT ) ) {
rgbe_error( rgbe_format_error, 'missing format specifier' );
}
if ( ! ( header.valid & RGBE_VALID_DIMENSIONS ) ) {
rgbe_error( rgbe_format_error, 'missing image size specifier' );
}
return header;
},
RGBE_ReadPixels_RLE = function ( buffer, w, h ) {
const scanline_width = w;
if (
// run length encoding is not allowed so read flat
( ( scanline_width < 8 ) || ( scanline_width > 0x7fff ) ) ||
// this file is not run length encoded
( ( 2 !== buffer[ 0 ] ) || ( 2 !== buffer[ 1 ] ) || ( buffer[ 2 ] & 0x80 ) )
) {
// return the flat buffer
return new Uint8Array( buffer );
}
if ( scanline_width !== ( ( buffer[ 2 ] << 8 ) | buffer[ 3 ] ) ) {
rgbe_error( rgbe_format_error, 'wrong scanline width' );
}
const data_rgba = new Uint8Array( 4 * w * h );
if ( ! data_rgba.length ) {
rgbe_error( rgbe_memory_error, 'unable to allocate buffer space' );
}
let offset = 0, pos = 0;
const ptr_end = 4 * scanline_width;
const rgbeStart = new Uint8Array( 4 );
const scanline_buffer = new Uint8Array( ptr_end );
let num_scanlines = h;
// read in each successive scanline
while ( ( num_scanlines > 0 ) && ( pos < buffer.byteLength ) ) {
if ( pos + 4 > buffer.byteLength ) {
rgbe_error( rgbe_read_error );
}
rgbeStart[ 0 ] = buffer[ pos ++ ];
rgbeStart[ 1 ] = buffer[ pos ++ ];
rgbeStart[ 2 ] = buffer[ pos ++ ];
rgbeStart[ 3 ] = buffer[ pos ++ ];
if ( ( 2 != rgbeStart[ 0 ] ) || ( 2 != rgbeStart[ 1 ] ) || ( ( ( rgbeStart[ 2 ] << 8 ) | rgbeStart[ 3 ] ) != scanline_width ) ) {
rgbe_error( rgbe_format_error, 'bad rgbe scanline format' );
}
// read each of the four channels for the scanline into the buffer
// first red, then green, then blue, then exponent
let ptr = 0, count;
while ( ( ptr < ptr_end ) && ( pos < buffer.byteLength ) ) {
count = buffer[ pos ++ ];
const isEncodedRun = count > 128;
if ( isEncodedRun ) count -= 128;
if ( ( 0 === count ) || ( ptr + count > ptr_end ) ) {
rgbe_error( rgbe_format_error, 'bad scanline data' );
}
if ( isEncodedRun ) {
// a (encoded) run of the same value
const byteValue = buffer[ pos ++ ];
for ( let i = 0; i < count; i ++ ) {
scanline_buffer[ ptr ++ ] = byteValue;
}
//ptr += count;
} else {
// a literal-run
scanline_buffer.set( buffer.subarray( pos, pos + count ), ptr );
ptr += count; pos += count;
}
}
// now convert data from buffer into rgba
// first red, then green, then blue, then exponent (alpha)
const l = scanline_width; //scanline_buffer.byteLength;
for ( let i = 0; i < l; i ++ ) {
let off = 0;
data_rgba[ offset ] = scanline_buffer[ i + off ];
off += scanline_width; //1;
data_rgba[ offset + 1 ] = scanline_buffer[ i + off ];
off += scanline_width; //1;
data_rgba[ offset + 2 ] = scanline_buffer[ i + off ];
off += scanline_width; //1;
data_rgba[ offset + 3 ] = scanline_buffer[ i + off ];
offset += 4;
}
num_scanlines --;
}
return data_rgba;
};
const RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) {
const e = sourceArray[ sourceOffset + 3 ];
const scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
destArray[ destOffset + 3 ] = 1;
};
const RGBEByteToRGBHalf = function ( sourceArray, sourceOffset, destArray, destOffset ) {
const e = sourceArray[ sourceOffset + 3 ];
const scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
// clamping to 65504, the maximum representable value in float16
destArray[ destOffset + 0 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 0 ] * scale, 65504 ) );
destArray[ destOffset + 1 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 1 ] * scale, 65504 ) );
destArray[ destOffset + 2 ] = DataUtils.toHalfFloat( Math.min( sourceArray[ sourceOffset + 2 ] * scale, 65504 ) );
destArray[ destOffset + 3 ] = DataUtils.toHalfFloat( 1 );
};
const byteArray = new Uint8Array( buffer );
byteArray.pos = 0;
const rgbe_header_info = RGBE_ReadHeader( byteArray );
const w = rgbe_header_info.width,
h = rgbe_header_info.height,
image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h );
let data, type;
let numElements;
switch ( this.type ) {
case FloatType:
numElements = image_rgba_data.length / 4;
const floatArray = new Float32Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 4 );
}
data = floatArray;
type = FloatType;
break;
case HalfFloatType:
numElements = image_rgba_data.length / 4;
const halfArray = new Uint16Array( numElements * 4 );
for ( let j = 0; j < numElements; j ++ ) {
RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 4 );
}
data = halfArray;
type = HalfFloatType;
break;
default:
throw new Error( 'THREE.RGBELoader: Unsupported type: ' + this.type );
break;
}
return {
width: w, height: h,
data: data,
header: rgbe_header_info.string,
gamma: rgbe_header_info.gamma,
exposure: rgbe_header_info.exposure,
type: type
};
}
setDataType( value ) {
this.type = value;
return this;
}
load( url, onLoad, onProgress, onError ) {
function onLoadCallback( texture, texData ) {
switch ( texture.type ) {
case FloatType:
case HalfFloatType:
texture.colorSpace = LinearSRGBColorSpace;
texture.minFilter = LinearFilter;
texture.magFilter = LinearFilter;
texture.generateMipmaps = false;
texture.flipY = true;
break;
}
if ( onLoad ) onLoad( texture, texData );
}
return super.load( url, onLoadCallback, onProgress, onError );
}
}
export { RGBELoader };