cleaning up viewer code (#101)

This commit is contained in:
Ethan Weber authored and GitHub committed 2022-07-07 16:00:30 -07:00
1 parent b40ec1e863
commit 74ec84117e
30 files changed
+826 -11359

No files matched your search

+4 -1
View File
@@ -1,5 +1,4 @@
{ {
// "python.pythonPath": "/path/to/bin/python",
"files.watcherExclude": { "files.watcherExclude": {
"**/__pycache__/": true, "**/__pycache__/": true,
"**/.ipynb_checkpoints": true, "**/.ipynb_checkpoints": true,
@@ -8,6 +7,10 @@
"**/runs*": true, "**/runs*": true,
"**/temp*": true, "**/temp*": true,
}, },
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[python]": {
"editor.defaultFormatter": "ms-python.python"
},
"editor.formatOnSave": true, "editor.formatOnSave": true,
"python.envFile": "${workspaceFolder}/.env", "python.envFile": "${workspaceFolder}/.env",
"python.formatting.provider": "black", "python.formatting.provider": "black",
+6 -3
View File
@@ -9,8 +9,11 @@ The viewer is built using [ThreeJS](https://threejs.org/) and packaged into a [R
## Quick start ## Quick start
``` ```
# run training script with the viewer # Run bridge server in the background.
python scripts/run_viewer_bridge_server.py
# Run training script with viewer enabled.
python scripts/run_train.py viewer.enable=True
``` ```
<hr> <hr>
@@ -63,8 +66,8 @@ yarn start
# forward port and open in your local browser # forward port and open in your local browser
# the URL takes the following form # the URL takes the following form
# http://localhost:<forwarded_react_port>/localhost:<forwarded_backend_tcp_port> # http://localhost:<forwarded_react_port>?localhost:<forwarded_backend_tcp_port>
http://localhost:4000/localhost:8051 http://localhost:4000?localhost:8051
``` ```
Possibly edit the port in `app/.env.development` file with the following: Possibly edit the port in `app/.env.development` file with the following:
+26 -19
View File
@@ -10,7 +10,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 1, "execution_count": null,
"id": "8501e01d-f932-4a75-8259-2def67a546d7", "id": "8501e01d-f932-4a75-8259-2def67a546d7",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -23,7 +23,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 2, "execution_count": null,
"id": "b15dfdc1-5054-40bc-9631-4c7426eecfd9", "id": "b15dfdc1-5054-40bc-9631-4c7426eecfd9",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -52,7 +52,7 @@
"from pyrad.utils.config import Config, setup_config\n", "from pyrad.utils.config import Config, setup_config\n",
"\n", "\n",
"# the new import\n", "# the new import\n",
"from pyrad.viewer.server import vis_utils\n", "from pyrad.viewer.server import viewer_utils\n",
"\n", "\n",
"\n", "\n",
"from hydra import compose, initialize\n", "from hydra import compose, initialize\n",
@@ -71,7 +71,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 3, "execution_count": null,
"id": "7fe7478d", "id": "7fe7478d",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -90,7 +90,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 4, "execution_count": null,
"id": "26d6da3c-e28a-4c55-9592-d90dccb86051", "id": "26d6da3c-e28a-4c55-9592-d90dccb86051",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -100,7 +100,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 5, "execution_count": null,
"id": "642b0a25-0e88-4eac-b661-a57a74fb10fc", "id": "642b0a25-0e88-4eac-b661-a57a74fb10fc",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -110,7 +110,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 6, "execution_count": null,
"id": "938f090b-3b28-4fd6-82dc-d4b5c5917134", "id": "938f090b-3b28-4fd6-82dc-d4b5c5917134",
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
@@ -121,19 +121,10 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 9, "execution_count": null,
"id": "fd04703a-aa50-45e4-95fd-4d881ff18d61", "id": "fd04703a-aa50-45e4-95fd-4d881ff18d61",
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [],
{
"name": "stdout",
"output_type": "stream",
"text": [
"estimated_time: 3.3333333333333335\n",
"time_elapsed: 3.510408878326416\n"
]
}
],
"source": [ "source": [
"# move a camera around\n", "# move a camera around\n",
"num_cameras = len(dataset_inputs.intrinsics)\n", "num_cameras = len(dataset_inputs.intrinsics)\n",
@@ -153,7 +144,7 @@
"\n", "\n",
"start = time.time()\n", "start = time.time()\n",
"for camera in cameras:\n", "for camera in cameras:\n",
" vis_utils.set_camera(vis, camera)\n", " viewer_utils.set_camera(vis, camera)\n",
"\n", "\n",
" # render an image\n", " # render an image\n",
" # outputs = trainer.render_image_in_viewer()\n", " # outputs = trainer.render_image_in_viewer()\n",
@@ -171,6 +162,22 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [] "source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "fd32ba39-fdfe-4689-8ed0-4531d8f2ff04",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "ae52a7e6-2a1d-46db-9cc1-7c96b6433a33",
"metadata": {},
"outputs": [],
"source": []
} }
], ],
"metadata": { "metadata": {
+2 -2
View File
@@ -32,7 +32,7 @@ from pyrad.utils import profiler, writer
from pyrad.utils.config import Config from pyrad.utils.config import Config
from pyrad.utils.decorators import check_main_thread from pyrad.utils.decorators import check_main_thread
from pyrad.utils.writer import EventName, TimeWriter from pyrad.utils.writer import EventName, TimeWriter
from pyrad.viewer.server import vis_utils from pyrad.viewer.server import viewer_utils
logging.getLogger("PIL").setLevel(logging.WARNING) logging.getLogger("PIL").setLevel(logging.WARNING)
@@ -63,7 +63,7 @@ class Trainer:
writer.setup_event_writers(config.logging, max_iter=config.trainer.max_num_iterations) writer.setup_event_writers(config.logging, max_iter=config.trainer.max_num_iterations)
profiler.setup_profiler(config.logging) profiler.setup_profiler(config.logging)
# visualizer variable # visualizer variable
self.visualizer_state = vis_utils.VisualizerState(config.viewer) self.visualizer_state = viewer_utils.VisualizerState(config.viewer)
def setup(self, test_mode=False): def setup(self, test_mode=False):
"""Setup the Trainer by calling other setup functions.""" """Setup the Trainer by calling other setup functions."""
+1 -1
View File
@@ -34,7 +34,7 @@ from pyrad.graphs.modules.ray_generator import RayGenerator
from pyrad.utils import profiler from pyrad.utils import profiler
from pyrad.utils.config import GraphConfig from pyrad.utils.config import GraphConfig
from pyrad.utils.misc import get_masked_dict, instantiate_from_dict_config, is_not_none from pyrad.utils.misc import get_masked_dict, instantiate_from_dict_config, is_not_none
from pyrad.viewer.server.vis_utils import CameraChangeException from pyrad.viewer.server.viewer_utils import CameraChangeException
@profiler.time_function @profiler.time_function
+3 -1
View File
@@ -15,7 +15,9 @@
"react-scripts": "^5.0.1", "react-scripts": "^5.0.1",
"socket.io-client": "^4.5.1", "socket.io-client": "^4.5.1",
"three": "^0.142.0", "three": "^0.142.0",
"websocket": "^1.0.34" "websocket": "^1.0.34",
"three-wtm": "^1.0",
"wwobjloader2": "^4.0"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "start": "react-scripts start",
-234
View File
@@ -1,234 +0,0 @@
import * as THREE from 'three';
import CCapture from 'ccapture.js'; //TODO(ethan): check if this is correct
const dat = require('dat.gui');
function remove_folders(gui) {
for (let name of Object.keys(gui.__folders)) {
let folder = gui.__folders[name];
remove_folders(folder);
dat.dom.dom.unbind(window, 'resize', folder.__resizeHandler);
gui.removeFolder(folder);
}
}
export class Animator {
constructor(viewer) {
this.viewer = viewer;
this.folder = this.viewer.gui.addFolder("Animations");
this.mixer = new THREE.AnimationMixer();
this.loader = new THREE.ObjectLoader();
this.clock = new THREE.Clock();
this.actions = [];
this.playing = false;
this.time = 0;
this.time_scrubber = null;
this.setup_capturer("png");
this.duration = 0;
}
setup_capturer(format) {
this.capturer = new CCapture({
format: format,
name: "pyrad_" + String(Date.now())
});
this.capturer.format = format;
}
play() {
this.clock.start();
// this.mixer.timeScale = 1;
for (let action of this.actions) {
action.play();
}
this.playing = true;
}
record() {
this.reset();
this.play();
this.recording = true;
this.capturer.start();
}
pause() {
// this.mixer.timeScale = 0;
this.clock.stop();
this.playing = false;
if (this.recording) {
this.stop_capture();
this.save_capture();
}
}
stop_capture() {
this.recording = false;
this.capturer.stop();
this.viewer.animate(); // restore the animation loop which gets disabled by capturer.stop()
}
save_capture() {
this.capturer.save();
if (this.capturer.format === "png") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
} else if (this.capturer.format === "jpg") {
alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.jpg \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4");
}
}
display_progress(time) {
this.time = time;
if (this.time_scrubber !== null) {
this.time_scrubber.updateDisplay();
}
}
seek(time) {
this.actions.forEach((action) => {
action.time = Math.max(0, Math.min(action._clip.duration, time));
});
this.mixer.update(0);
this.viewer.set_dirty();
}
reset() {
for (let action of this.actions) {
action.reset();
}
this.display_progress(0);
this.mixer.update(0);
this.setup_capturer(this.capturer.format);
this.viewer.set_dirty();
}
clear() {
remove_folders(this.folder);
this.mixer.stopAllAction();
this.actions = [];
this.duration = 0;
this.display_progress(0);
this.mixer = new THREE.AnimationMixer();
}
load(animations, options) {
this.clear();
this.folder.open();
let folder = this.folder.addFolder("default");
folder.open();
folder.add(this, "play");
folder.add(this, "pause");
folder.add(this, "reset");
// Note, for some reason when you call `.max()` on a slider controller it does
// correctly change how the slider behaves but does not change the range of values
// that can be entered into the text box attached to the slider. Oh well. We work
// around this by creating the slider with an unreasonably huge range and then calling
// `.min()` and `.max()` on it later.
this.time_scrubber = folder.add(this, "time", 0, 1e9, 0.001);
this.time_scrubber.onChange((value) => this.seek(value));
folder.add(this.mixer, "timeScale").step(0.01).min(0);
let recording_folder = folder.addFolder("Recording");
recording_folder.add(this, "record");
recording_folder.add({format: "png"}, "format", ["png", "jpg"]).onChange(value => {
this.setup_capturer(value);
});
if (options.play === undefined) {
options.play = true
}
if (options.loopMode === undefined) {
options.loopMode = THREE.LoopRepeat
}
if (options.repetitions === undefined) {
options.repetitions = 1
}
if (options.clampWhenFinished === undefined) {
options.clampWhenFinished = true
}
this.duration = 0;
this.progress = 0;
for (let animation of animations) {
let target = this.viewer.scene_tree.find(animation.path).object;
let clip = this.loader.parseAnimations([animation.clip])[0];
let action = this.mixer.clipAction(clip, target);
action.clampWhenFinished = options.clampWhenFinished;
action.setLoop(options.loopMode, options.repetitions);
this.actions.push(action);
this.duration = Math.max(this.duration, clip.duration);
}
this.time_scrubber.min(0);
this.time_scrubber.max(this.duration);
this.reset();
if (options.play) {
this.play();
}
}
update() {
if (this.playing) {
this.mixer.update(this.clock.getDelta());
this.viewer.set_dirty();
if (this.duration != 0) {
let current_time = this.actions.reduce((acc, action) => {
return Math.max(acc, action.time);
}, 0);
this.display_progress(current_time);
} else {
this.display_progress(0);
}
if (this.actions.every((action) => action.paused)) {
this.pause();
for (let action of this.actions) {
action.reset();
}
}
}
}
after_render() {
if (this.recording) {
this.capturer.capture(this.viewer.renderer.domElement);
}
}
}
// Generates a gradient texture without filling up
// an entire canvas. We simply create a 2x1 image
// containing only the two colored pixels and then
// set up the appropriate magnification and wrapping
// modes to generate the gradient automatically
function gradient_texture(top_color, bottom_color) {
let colors = [bottom_color, top_color];
let width = 1;
let height = 2;
let size = width * height;
var data = new Uint8Array(3 * size);
for (let row = 0; row < height; row++) {
let color = colors[row];
for (let col = 0; col < width; col++) {
let i = 3 * (row * width + col);
for (let j = 0; j < 3; j++) {
data[i + j] = color[j];
}
}
}
var texture = new THREE.DataTexture(data, width, height, THREE.RGBFormat);
texture.magFilter = THREE.LinearFilter;
texture.encoding = THREE.LinearEncoding;
// By default, the points in our texture map to the center of
// the pixels, which means that the gradient only occupies
// the middle half of the screen. To get around that, we just have
// to tweak the UV transform matrix
texture.matrixAutoUpdate = false;
texture.matrix.set(0.5, 0, 0.25,
0, 0.5, 0.25,
0, 0, 1);
texture.needsUpdate = true
return texture;
}
-19
View File
@@ -1,19 +0,0 @@
import React, { Component } from "react";
export class BackgroundDiv extends Component {
componentDidMount() {
document.getElementById("BackgroundDiv-video").play();
}
render() {
return (
<div className="BackgroundDiv">
<video id="BackgroundDiv-video" autoPlay muted loop>
<source
src="https://www.w3schools.com/html/mov_bbb.mp4"
type="video/mp4"
></source>
</video>{" "}
</div>
);
}
}
@@ -2,7 +2,7 @@ import * as THREE from "three";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js"; import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader.js"; import { ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js"; import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";
// import {MtlObjBridge} from 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.js'; import { MtlObjBridge } from "wwobjloader2";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js"; import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader.js"; import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader.js";
import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js"; import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js";
@@ -193,11 +193,10 @@ export class ExtensibleObjectLoader extends THREE.ObjectLoader {
if (json.mtl_library) { if (json.mtl_library) {
let mtl_loader = new MTLLoader(manager); let mtl_loader = new MTLLoader(manager);
let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", ""); let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", "");
console.log(mtl_parse_result); let materials =
// let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result); MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result);
// console.log(materials); loader.setMaterials(materials);
// loader.addMaterials(materials); this.onTextureLoad();
// this.onTextureLoad();
} }
let obj = loader.parse(json.data + "\n", path); let obj = loader.parse(json.data + "\n", path);
geometry = merge_geometries(obj, true); geometry = merge_geometries(obj, true);
+119 -119
View File
@@ -3,142 +3,142 @@ import * as THREE from "three";
const dat = require("dat.gui"); const dat = require("dat.gui");
function remove_folders(gui) { function remove_folders(gui) {
for (let name of Object.keys(gui.__folders)) { for (let name of Object.keys(gui.__folders)) {
let folder = gui.__folders[name]; let folder = gui.__folders[name];
remove_folders(folder); remove_folders(folder);
dat.dom.dom.unbind(window, "resize", folder.__resizeHandler); dat.dom.dom.unbind(window, "resize", folder.__resizeHandler);
gui.removeFolder(folder); gui.removeFolder(folder);
} }
} }
function dispose(object) { function dispose(object) {
if (!object) { if (!object) {
return; return;
} }
if (object.geometry) { if (object.geometry) {
object.geometry.dispose(); object.geometry.dispose();
} }
if (object.material) { if (object.material) {
if (Array.isArray(object.material)) { if (Array.isArray(object.material)) {
for (let material of object.material) { for (let material of object.material) {
if (material.map) { if (material.map) {
material.map.dispose(); material.map.dispose();
}
material.dispose();
}
} else {
if (object.material.map) {
object.material.map.dispose();
}
object.material.dispose();
} }
material.dispose();
}
} else {
if (object.material.map) {
object.material.map.dispose();
}
object.material.dispose();
} }
}
} }
export class SceneNode { export class SceneNode {
constructor(object, folder) { constructor(object, folder) {
this.object = object; this.object = object;
this.folder = folder; this.folder = folder;
this.children = {}; this.children = {};
this.create_controls(); this.create_controls();
for (let c of this.object.children) { for (let c of this.object.children) {
this.add_child(c); this.add_child(c);
}
} }
}
add_child(object) { add_child(object) {
let f = this.folder.addFolder(object.name); let f = this.folder.addFolder(object.name);
let node = new SceneNode(object, f); let node = new SceneNode(object, f);
this.children[object.name] = node; this.children[object.name] = node;
return node; return node;
}
create_child(name) {
let obj = new THREE.Group();
obj.name = name;
this.object.add(obj);
return this.add_child(obj);
}
find(path) {
if (path.length == 0) {
return this;
} else {
let name = path[0];
let child = this.children[name];
if (child === undefined) {
child = this.create_child(name);
}
return child.find(path.slice(1));
} }
}
create_controls() { create_child(name) {
if (this.vis_controller !== undefined) { let obj = new THREE.Group();
this.folder.domElement.removeChild(this.vis_controller.domElement); obj.name = name;
this.object.add(obj);
return this.add_child(obj);
} }
this.vis_controller = new dat.controllers.BooleanController(
this.object,
"visible"
);
this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
this.vis_controller.domElement.style.float = "right";
}
set_property(property, value) { find(path) {
if (property === "position") { if (path.length == 0) {
this.object.position.set(value[0], value[1], value[2]); return this;
} else if (property === "quaternion") { } else {
this.object.quaternion.set(value[0], value[1], value[2], value[3]); let name = path[0];
} else if (property === "scale") { let child = this.children[name];
this.object.scale.set(value[0], value[1], value[2]); if (child === undefined) {
} else { child = this.create_child(name);
this.object[property] = value; }
return child.find(path.slice(1));
}
} }
this.vis_controller.updateDisplay();
}
set_transform(matrix) { create_controls() {
let mat = new THREE.Matrix4(); if (this.vis_controller !== undefined) {
mat.fromArray(matrix); this.folder.domElement.removeChild(this.vis_controller.domElement);
mat.decompose( }
this.object.position, this.vis_controller = new dat.controllers.BooleanController(
this.object.quaternion, this.object,
this.object.scale "visible"
); );
} this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
set_object(object) { this.vis_controller.domElement.style.float = "right";
let parent = this.object.parent;
this.dispose_recursive();
this.object.parent.remove(this.object);
this.object = object;
parent.add(object);
this.create_controls();
}
dispose_recursive() {
for (let name of Object.keys(this.children)) {
this.children[name].dispose_recursive();
} }
dispose(this.object);
}
delete(path) { set_property(property, value) {
if (path.length == 0) { if (property === "position") {
console.error("Can't delete an empty path"); this.object.position.set(value[0], value[1], value[2]);
} else { } else if (property === "quaternion") {
let parent = this.find(path.slice(0, path.length - 1)); this.object.quaternion.set(value[0], value[1], value[2], value[3]);
let name = path[path.length - 1]; } else if (property === "scale") {
let child = parent.children[name]; this.object.scale.set(value[0], value[1], value[2]);
if (child !== undefined) { } else {
child.dispose_recursive(); this.object[property] = value;
parent.object.remove(child.object); }
remove_folders(child.folder); this.vis_controller.updateDisplay();
parent.folder.removeFolder(child.folder); }
delete parent.children[name];
} set_transform(matrix) {
let mat = new THREE.Matrix4();
mat.fromArray(matrix);
mat.decompose(
this.object.position,
this.object.quaternion,
this.object.scale
);
}
set_object(object) {
let parent = this.object.parent;
this.dispose_recursive();
this.object.parent.remove(this.object);
this.object = object;
parent.add(object);
this.create_controls();
}
dispose_recursive() {
for (let name of Object.keys(this.children)) {
this.children[name].dispose_recursive();
}
dispose(this.object);
}
delete(path) {
if (path.length == 0) {
console.error("Can't delete an empty path");
} else {
let parent = this.find(path.slice(0, path.length - 1));
let name = path[path.length - 1];
let child = parent.children[name];
if (child !== undefined) {
child.dispose_recursive();
parent.object.remove(child.object);
remove_folders(child.folder);
parent.folder.removeFolder(child.folder);
delete parent.children[name];
}
}
} }
}
} }
-374
View File
@@ -1,374 +0,0 @@
import React, { Component } from "react";
import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
import Stats from "three/examples/jsm/libs/stats.module.js";
import { GUI } from "dat.gui";
import { split_path } from "./utils";
import { SceneNode } from "./SceneNode";
import { ExtensibleObjectLoader } from "./ExtensibleObjectLoader";
function websocket_endpoint_from_url(url) {
let endpoint = url.split("?").pop();
if (endpoint == "") {
let message =
"Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051";
window.alert(message);
return null;
}
return endpoint;
}
function findCameraObjectUnderObject3D(object) {
// seach the tree for the camera
if (object instanceof THREE.Camera) {
return object;
}
for (let name of Object.keys(object.children)) {
return findCameraObjectUnderObject3D(object.children[name]);
}
return null;
}
var msgpack = require("msgpack-lite");
export class Viewer extends Component {
constructor(props) {
super(props);
this.state = {
scene: null,
controls: null,
renderer: null,
gui: null,
scene_tree: null,
viewport_width: null,
viewport_height: null,
};
this.update = this.update.bind(this);
this.set_object = this.set_object.bind(this);
this.handle_command = this.handle_command.bind(this);
this.threejs_ref = React.createRef();
}
handleResize() {
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
this.state.camera_main.aspect =
this.state.viewport_width / this.state.viewport_height;
this.state.camera_main.updateProjectionMatrix();
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
}
update() {
requestAnimationFrame(this.update);
this.handleResize();
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
camera_main.updateProjectionMatrix();
if (this.state.controls_main != null) {
this.state.controls_main.update();
}
this.state.renderer_main.render(this.state.scene, camera_main);
this.send_camera_over_websocket();
}
send_camera_over_websocket() {
/* update the camera information in the python server
if the websocket is connected */
console.log("send_camera_over_websocket");
if (this.state.websocket.readyState === WebSocket.OPEN) {
// update the camera information in the python server
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
console.log(camera_main.toJSON());
let cmd = "set_object";
let path = "Cameras/Main Camera";
let data = {
type: cmd,
path: path,
object: camera_main.toJSON(),
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
set_object(path, object) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
// add controls if object is a camera
if (object instanceof THREE.Camera) {
this.state.controls_main = new TrackballControls(
object,
this.state.renderer_main.domElement
);
this.state.controls_main.rotateSpeed = 2.0;
this.state.controls_main.zoomSpeed = 0.3;
this.state.controls_main.panSpeed = 0.2;
this.state.controls_main.staticMoving = false; // false is default
this.state.controls_main.target.set(0, 0, 0); // focus point of the controls
this.state.controls_main.autoRotate = false;
this.state.controls_main.dynamicDampingFactor = 1.0;
this.state.controls_main.update();
// this.send_camera_over_websocket();
// this.state.controls_main.addEventListener("change", () => {
// this.send_camera_over_websocket();
// });
}
}
set_object_from_json(path, object_json) {
let loader = new ExtensibleObjectLoader();
loader.parse(object_json, (obj) => {
if (
obj.geometry !== undefined &&
obj.geometry.type === "BufferGeometry"
) {
if (
obj.geometry.attributes.normal === undefined ||
obj.geometry.attributes.normal.count === 0
) {
obj.geometry.computeVertexNormals();
}
}
obj.castShadow = true;
obj.receiveShadow = true;
this.set_object(path, obj);
});
}
set_transform(path, matrix) {
this.state.scene_tree.find(path).set_transform(matrix);
}
delete_path(path) {
if (path.length === 0) {
console.error("Deleting the entire scene is not implemented.");
} else {
this.state.scene_tree.delete(path);
}
}
set_property(path, property, value) {
this.state.scene_tree.find(path).set_property(property, value);
// TODO(ethan): handle this issue
if (path[0] === "Background") {
// The background is not an Object3d, so needs a little help.
this.state.scene_tree.find(path).on_update();
}
}
handle_command(cmd) {
// convert binary serialization format back to JSON
cmd = msgpack.decode(new Uint8Array(cmd));
console.log(cmd);
// three js scene commands
if (cmd.type === "set_object") {
let path = split_path(cmd.path);
this.set_object_from_json(path, cmd.object);
} else if (cmd.type === "set_transform") {
let path = split_path(cmd.path);
this.set_transform(path, cmd.matrix);
} else if (cmd.type === "delete") {
let path = split_path(cmd.path);
this.delete_path(path);
} else if (cmd.type === "set_property") {
let path = split_path(cmd.path);
this.set_property(path, cmd.property, cmd.value);
}
// web rtc commands
else if (cmd.type === "answer") {
let answer = cmd.data;
this.state.pc.setRemoteDescription(answer);
}
// possibly update the camera information in the python server
// this.send_camera_over_websocket();
}
getViewportWidth() {
return window.innerWidth - (window.innerWidth % 2);
}
getViewportHeight() {
return window.innerHeight;
}
setupWebRTC() {
console.log("setting up WebRTC");
// The iceServers config comes from the following URL:
// https://www.metered.ca/tools/openrelay/
this.state.pc = new RTCPeerConnection({
iceServers: [{
urls: "stun:openrelay.metered.ca:80",
},
{
urls: "turn:openrelay.metered.ca:80",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443?transport=tcp",
username: "openrelayproject",
credential: "openrelayproject",
},
],
});
// connect video
this.state.pc.addEventListener("track", function(evt) {
if (evt.track.kind == "video") {
console.log("setting event stream");
document.getElementById("WebRTCVideo-video").srcObject = evt.streams[0];
}
});
this.state.pc.addTransceiver("video", { direction: "recvonly" });
this.state.pc
.createOffer()
.then((offer) => {
return this.state.pc.setLocalDescription(offer);
})
.then(() => {
// wait for ICE gathering to complete
return new Promise((resolve) => {
if (this.state.pc.iceGatheringState === "complete") {
resolve();
} else {
var checkState = () => {
if (this.state.pc.iceGatheringState === "complete") {
this.state.pc.removeEventListener(
"icegatheringstatechange",
checkState
);
resolve();
}
};
this.state.pc.addEventListener(
"icegatheringstatechange",
checkState
);
}
});
})
.then(() => {
var offer = this.state.pc.localDescription;
console.log("sending the offer");
let cmd = "offer";
let path = "";
let data = {
type: cmd,
path: path,
data: {
sdp: offer.sdp,
type: offer.type,
},
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
});
}
componentDidMount() {
// Open the websocket
let endpoint = websocket_endpoint_from_url(window.location.href);
this.state.websocket = new WebSocket("ws://" + endpoint + "/");
this.state.websocket.onopen = () => {
console.log("websocket connected");
this.setupWebRTC();
};
this.state.websocket.binaryType = "arraybuffer";
// 'command' for updates to Viewer
this.state.websocket.onmessage = (cmd) => this.handle_command(cmd.data);
this.state.websocket.onclose = function(evt) {
console.log("onclose:", evt);
};
// Get size of screen
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
// Scene
this.state.scene = new THREE.Scene();
// GUI
this.state.gui = new GUI();
let scene_folder = this.state.gui.addFolder("Scene");
scene_folder.open();
this.state.scene_tree = new SceneNode(this.state.scene, scene_folder);
// Renderer main
this.state.renderer_main = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
this.state.renderer_main.setPixelRatio(window.devicePixelRatio);
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
this.state.renderer_main.domElement.style.border = "1px solid black";
let domElement = document.getElementById("canvas-container-main");
domElement.append(this.state.renderer_main.domElement);
// Camera main
this.state.camera_main = new THREE.PerspectiveCamera(
120,
this.state.viewport_width / this.state.viewport_height,
0.01,
100
);
this.state.camera_main.position.x = 5;
this.state.camera_main.position.y = -5;
this.state.camera_main.position.z = 5;
this.state.camera_main.up = new THREE.Vector3(0, 0, 1);
this.set_object(["Cameras", "Main Camera"], this.state.camera_main);
// Axes display
let axes = new THREE.AxesHelper(5);
this.set_object(["Axes"], axes);
// Grid
let grid = new THREE.GridHelper(20, 20);
this.set_object(["Grid"], grid);
// Lights
let color = 0xffffff;
let intensity = 1;
let light = new THREE.AmbientLight(color, intensity);
this.set_object(["Light"], light);
// Stats
var stats = new Stats();
let domElement_stats = document.getElementById("canvas-container-main");
domElement_stats.append(stats.dom);
this.update();
}
render() {
return ( <
div >
<
div className = "WebRTCVideo" >
<
video id = "WebRTCVideo-video"
autoPlay playsInline muted > { " " } <
/video>{" "} <
/div>{" "} <
div id = "canvas-container-main" > < /div>{" "} <
div id = "stats-container" > < /div>{" "} <
/div>
);
}
}
+373
View File
@@ -0,0 +1,373 @@
import React, { Component } from "react";
import * as THREE from "three";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
import Stats from "three/examples/jsm/libs/stats.module.js";
import { GUI } from "dat.gui";
import { split_path } from "./utils";
import { SceneNode } from "./SceneNode";
import { ExtensibleObjectLoader } from "./ExtensibleObjectLoader";
function websocket_endpoint_from_url(url) {
let endpoint = url.split("?").pop();
if (endpoint == "") {
let message =
"Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051";
window.alert(message);
return null;
}
return endpoint;
}
function findCameraObjectUnderObject3D(object) {
// seach the tree for the camera
if (object instanceof THREE.Camera) {
return object;
}
for (let name of Object.keys(object.children)) {
return findCameraObjectUnderObject3D(object.children[name]);
}
return null;
}
var msgpack = require("msgpack-lite");
export class Viewer extends Component {
constructor(props) {
super(props);
this.state = {
scene: null,
controls: null,
renderer: null,
gui: null,
scene_tree: null,
viewport_width: null,
viewport_height: null,
};
this.update = this.update.bind(this);
this.set_object = this.set_object.bind(this);
this.handle_command = this.handle_command.bind(this);
this.threejs_ref = React.createRef();
}
handleResize() {
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
this.state.camera_main.aspect =
this.state.viewport_width / this.state.viewport_height;
this.state.camera_main.updateProjectionMatrix();
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
}
update() {
requestAnimationFrame(this.update);
this.handleResize();
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
camera_main.updateProjectionMatrix();
if (this.state.controls_main != null) {
this.state.controls_main.update();
}
this.state.renderer_main.render(this.state.scene, camera_main);
this.send_camera_over_websocket();
}
send_camera_over_websocket() {
/* update the camera information in the python server
if the websocket is connected */
// console.log("send_camera_over_websocket");
if (this.state.websocket.readyState === WebSocket.OPEN) {
// update the camera information in the python server
let camera_main = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera"]).object
);
// console.log(camera_main.toJSON());
let cmd = "set_object";
let path = "Cameras/Main Camera";
let data = {
type: cmd,
path: path,
object: camera_main.toJSON(),
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
}
}
set_object(path, object) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
// add controls if object is a camera
if (object instanceof THREE.Camera) {
this.state.controls_main = new TrackballControls(
object,
this.state.renderer_main.domElement
);
this.state.controls_main.rotateSpeed = 2.0;
this.state.controls_main.zoomSpeed = 0.3;
this.state.controls_main.panSpeed = 0.2;
this.state.controls_main.staticMoving = false; // false is default
this.state.controls_main.target.set(0, 0, 0); // focus point of the controls
this.state.controls_main.autoRotate = false;
this.state.controls_main.dynamicDampingFactor = 1.0;
this.state.controls_main.update();
// this.send_camera_over_websocket();
// this.state.controls_main.addEventListener("change", () => {
// this.send_camera_over_websocket();
// });
}
}
set_object_from_json(path, object_json) {
let loader = new ExtensibleObjectLoader();
loader.parse(object_json, (obj) => {
if (
obj.geometry !== undefined &&
obj.geometry.type === "BufferGeometry"
) {
if (
obj.geometry.attributes.normal === undefined ||
obj.geometry.attributes.normal.count === 0
) {
obj.geometry.computeVertexNormals();
}
}
obj.castShadow = true;
obj.receiveShadow = true;
this.set_object(path, obj);
});
}
set_transform(path, matrix) {
this.state.scene_tree.find(path).set_transform(matrix);
}
delete_path(path) {
if (path.length === 0) {
console.error("Deleting the entire scene is not implemented.");
} else {
this.state.scene_tree.delete(path);
}
}
set_property(path, property, value) {
this.state.scene_tree.find(path).set_property(property, value);
// TODO(ethan): handle this issue
if (path[0] === "Background") {
// The background is not an Object3d, so needs a little help.
this.state.scene_tree.find(path).on_update();
}
}
handle_command(cmd) {
// convert binary serialization format back to JSON
cmd = msgpack.decode(new Uint8Array(cmd));
// console.log(cmd);
// three js scene commands
if (cmd.type === "set_object") {
let path = split_path(cmd.path);
this.set_object_from_json(path, cmd.object);
} else if (cmd.type === "set_transform") {
let path = split_path(cmd.path);
this.set_transform(path, cmd.matrix);
} else if (cmd.type === "delete") {
let path = split_path(cmd.path);
this.delete_path(path);
} else if (cmd.type === "set_property") {
let path = split_path(cmd.path);
this.set_property(path, cmd.property, cmd.value);
}
// web rtc commands
else if (cmd.type === "answer") {
let answer = cmd.data;
this.state.pc.setRemoteDescription(answer);
}
// possibly update the camera information in the python server
// this.send_camera_over_websocket();
}
getViewportWidth() {
return window.innerWidth - (window.innerWidth % 2);
}
getViewportHeight() {
return window.innerHeight;
}
setupWebRTC() {
console.log("setting up WebRTC");
// The iceServers config comes from the following URL:
// https://www.metered.ca/tools/openrelay/
this.state.pc = new RTCPeerConnection({
iceServers: [
{
urls: "stun:openrelay.metered.ca:80",
},
{
urls: "turn:openrelay.metered.ca:80",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443",
username: "openrelayproject",
credential: "openrelayproject",
},
{
urls: "turn:openrelay.metered.ca:443?transport=tcp",
username: "openrelayproject",
credential: "openrelayproject",
},
],
});
// connect video
this.state.pc.addEventListener("track", function (evt) {
if (evt.track.kind == "video") {
console.log("setting event stream");
document.getElementById("WebRTCVideo-video").srcObject = evt.streams[0];
}
});
this.state.pc.addTransceiver("video", { direction: "recvonly" });
this.state.pc
.createOffer()
.then((offer) => {
return this.state.pc.setLocalDescription(offer);
})
.then(() => {
// wait for ICE gathering to complete
return new Promise((resolve) => {
if (this.state.pc.iceGatheringState === "complete") {
resolve();
} else {
var checkState = () => {
if (this.state.pc.iceGatheringState === "complete") {
this.state.pc.removeEventListener(
"icegatheringstatechange",
checkState
);
resolve();
}
};
this.state.pc.addEventListener(
"icegatheringstatechange",
checkState
);
}
});
})
.then(() => {
var offer = this.state.pc.localDescription;
console.log("sending the offer");
let cmd = "offer";
let path = "";
let data = {
type: cmd,
path: path,
data: {
sdp: offer.sdp,
type: offer.type,
},
};
let message = msgpack.encode(data);
this.state.websocket.send(message);
});
}
componentDidMount() {
// Open the websocket
let endpoint = websocket_endpoint_from_url(window.location.href);
this.state.websocket = new WebSocket("ws://" + endpoint + "/");
this.state.websocket.onopen = () => {
console.log("websocket connected");
this.setupWebRTC();
};
this.state.websocket.binaryType = "arraybuffer";
// 'command' for updates to Viewer
this.state.websocket.onmessage = (cmd) => this.handle_command(cmd.data);
this.state.websocket.onclose = function (evt) {
console.log("onclose:", evt);
};
// Get size of screen
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
// Scene
this.state.scene = new THREE.Scene();
// GUI
this.state.gui = new GUI();
let scene_folder = this.state.gui.addFolder("Scene");
scene_folder.open();
this.state.scene_tree = new SceneNode(this.state.scene, scene_folder);
// Renderer main
this.state.renderer_main = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
});
this.state.renderer_main.setPixelRatio(window.devicePixelRatio);
this.state.renderer_main.setSize(
this.state.viewport_width,
this.state.viewport_height
);
this.state.renderer_main.domElement.style.border = "1px solid black";
let domElement = document.getElementById("canvas-container-main");
domElement.append(this.state.renderer_main.domElement);
// Camera main
this.state.camera_main = new THREE.PerspectiveCamera(
120,
this.state.viewport_width / this.state.viewport_height,
0.01,
100
);
this.state.camera_main.position.x = 5;
this.state.camera_main.position.y = -5;
this.state.camera_main.position.z = 5;
this.state.camera_main.up = new THREE.Vector3(0, 0, 1);
this.set_object(["Cameras", "Main Camera"], this.state.camera_main);
// Axes display
let axes = new THREE.AxesHelper(5);
this.set_object(["Axes"], axes);
// Grid
let grid = new THREE.GridHelper(20, 20);
grid.rotateX(Math.PI / 2); // now on xy plane
this.set_object(["Grid"], grid);
// Lights
let color = 0xffffff;
let intensity = 1;
let light = new THREE.AmbientLight(color, intensity);
this.set_object(["Light"], light);
// Stats
var stats = new Stats();
let domElement_stats = document.getElementById("canvas-container-main");
domElement_stats.append(stats.dom);
this.update();
}
render() {
return (
<div>
<div className="WebRTCVideo">
<video id="WebRTCVideo-video" autoPlay playsInline muted>
</video>
</div>
<div id="canvas-container-main"> </div>
<div id="stats-container"> </div>
</div>
);
}
}
+21 -24
View File
@@ -1,43 +1,40 @@
body { body {
margin: 0; margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", -webkit-font-smoothing: antialiased;
sans-serif; -moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
} }
code { code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
monospace;
} }
.BackgroundDiv, .BackgroundDiv,
.WebRTCVideo { .WebRTCVideo {
position: absolute; position: absolute;
top: 0px; top: 0px;
right: 0px; right: 0px;
bottom: 0px; bottom: 0px;
left: 0px; left: 0px;
} }
#BackgroundDiv-video, #BackgroundDiv-video,
#WebRTCVideo-video { #WebRTCVideo-video {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: fill; object-fit: fill;
} }
#canvas-container-main { #canvas-container-main {
position: absolute; position: absolute;
top: 0px; top: 0px;
right: 0px; right: 0px;
bottom: 0px; bottom: 0px;
left: 0px; left: 0px;
} }
#canvas-container-main canvas { #canvas-container-main canvas {
position: relative; position: relative;
height: 100%; height: 100%;
width: 100%; width: 100%;
} }
+104 -104
View File
@@ -11,131 +11,131 @@
// opt-in, read https://bit.ly/CRA-PWA // opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean( const isLocalhost = Boolean(
window.location.hostname === 'localhost' || window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address. // [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' || window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4. // 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match( window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
) )
); );
export function register(config) { export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW. // The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) { if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin // Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to // from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374 // serve assets; see https://github.com/facebook/create-react-app/issues/2374
return; return;
} }
window.addEventListener('load', () => { window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) { if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not. // This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config); checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the // Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation. // service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => { navigator.serviceWorker.ready.then(() => {
console.log( console.log(
'This web app is being served cache-first by a service ' + "This web app is being served cache-first by a service " +
'worker. To learn more, visit https://bit.ly/CRA-PWA' "worker. To learn more, visit https://bit.ly/CRA-PWA"
); );
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
}); });
} else { }
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
} }
function registerValidSW(swUrl, config) { function registerValidSW(swUrl, config) {
navigator.serviceWorker navigator.serviceWorker
.register(swUrl) .register(swUrl)
.then(registration => { .then((registration) => {
registration.onupdatefound = () => { registration.onupdatefound = () => {
const installingWorker = registration.installing; const installingWorker = registration.installing;
if (installingWorker == null) { if (installingWorker == null) {
return; return;
} }
installingWorker.onstatechange = () => { installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') { if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) { if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched, // At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older // but the previous service worker will still serve the older
// content until all client tabs are closed. // content until all client tabs are closed.
console.log( console.log(
'New content is available and will be used when all ' + "New content is available and will be used when all " +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.' "tabs for this page are closed. See https://bit.ly/CRA-PWA."
); );
// Execute callback // Execute callback
if (config && config.onUpdate) { if (config && config.onUpdate) {
config.onUpdate(registration); config.onUpdate(registration);
} }
} else { } else {
// At this point, everything has been precached. // At this point, everything has been precached.
// It's the perfect time to display a // It's the perfect time to display a
// "Content is cached for offline use." message. // "Content is cached for offline use." message.
console.log('Content is cached for offline use.'); console.log("Content is cached for offline use.");
// Execute callback // Execute callback
if (config && config.onSuccess) { if (config && config.onSuccess) {
config.onSuccess(registration); config.onSuccess(registration);
} }
} }
} }
}; };
}; };
}) })
.catch(error => { .catch((error) => {
console.error('Error during service worker registration:', error); console.error("Error during service worker registration:", error);
}); });
} }
function checkValidServiceWorker(swUrl, config) { function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page. // Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, { fetch(swUrl, {
headers: { 'Service-Worker': 'script' }, headers: { "Service-Worker": "script" },
}) })
.then(response => { .then((response) => {
// Ensure service worker exists, and that we really are getting a JS file. // Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type'); const contentType = response.headers.get("content-type");
if ( if (
response.status === 404 || response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1) (contentType != null && contentType.indexOf("javascript") === -1)
) { ) {
// No service worker found. Probably a different app. Reload the page. // No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => { navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => { registration.unregister().then(() => {
window.location.reload(); window.location.reload();
}); });
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
"No internet connection found. App is running in offline mode."
);
}); });
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
} }
export function unregister() { export function unregister() {
if ('serviceWorker' in navigator) { if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready navigator.serviceWorker.ready
.then(registration => { .then((registration) => {
registration.unregister(); registration.unregister();
}) })
.catch(error => { .catch((error) => {
console.error(error.message); console.error(error.message);
}); });
} }
} }
+1 -1
View File
@@ -2,4 +2,4 @@
// allows you to do things like: // allows you to do things like:
// expect(element).toHaveTextContent(/react/i) // expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom // learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect'; import "@testing-library/jest-dom/extend-expect";
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,3 +1,3 @@
export function split_path(path_str) { export function split_path(path_str) {
return path_str.split("/").filter(x => x.length > 0); return path_str.split("/").filter((x) => x.length > 0);
} }
-48
View File
@@ -1,48 +0,0 @@
function createPeerConnection() {
var config = {
sdpSemantics: "unified-plan",
};
// if (document.getElementById('use-stun').checked) {
// config.iceServers = [{urls: ['stun:stun.l.google.com:19302']}];
// }
let pc = new RTCPeerConnection(config);
// register some listeners to help debugging
pc.addEventListener(
"icegatheringstatechange",
function () {
iceGatheringLog.textContent += " -> " + pc.iceGatheringState;
},
false
);
iceGatheringLog.textContent = pc.iceGatheringState;
pc.addEventListener(
"iceconnectionstatechange",
function () {
iceConnectionLog.textContent += " -> " + pc.iceConnectionState;
},
false
);
iceConnectionLog.textContent = pc.iceConnectionState;
pc.addEventListener(
"signalingstatechange",
function () {
signalingLog.textContent += " -> " + pc.signalingState;
},
false
);
signalingLog.textContent = pc.signalingState;
// connect audio / video
pc.addEventListener("track", function (evt) {
if (evt.track.kind == "video")
document.getElementById("video").srcObject = evt.streams[0];
else document.getElementById("audio").srcObject = evt.streams[0];
});
return pc;
}
+19
View File
@@ -8745,6 +8745,18 @@ text-table@^0.2.0:
resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"
integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw== integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==
three-wtm@^1.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/three-wtm/-/three-wtm-1.0.2.tgz#f923ba885fc14ec15808670f67f82a0a7139bd64"
integrity sha512-gsjjF9XYHeqsKxCHqN+hhGAKuTqcV9ouw0Ad7SRTdZ65cDjjZkSR5KYcbW7tgwBu16jFagOG9VVjuBbGd40Kbw==
dependencies:
three "^0.133.1"
three@^0.133.1:
version "0.133.1"
resolved "https://registry.yarnpkg.com/three/-/three-0.133.1.tgz#5606f4817d67a09d9212d4ccbd6826564774f8f4"
integrity sha512-WydohO8ll949B0FTD6MGz59Yv2Lwj8hvObg/0Heh2r42S6+tQC1WByfCNRdmG4D7+odfGod+n8JPV1I2xrboWw==
three@^0.142.0: three@^0.142.0:
version "0.142.0" version "0.142.0"
resolved "https://registry.yarnpkg.com/three/-/three-0.142.0.tgz#89e226a16221f212eb1d40f0786604b711f28aed" resolved "https://registry.yarnpkg.com/three/-/three-0.142.0.tgz#89e226a16221f212eb1d40f0786604b711f28aed"
@@ -9527,6 +9539,13 @@ ws@~8.2.3:
resolved "https://registry.yarnpkg.com/ws/-/ws-8.2.3.tgz#63a56456db1b04367d0b721a0b80cae6d8becbba" resolved "https://registry.yarnpkg.com/ws/-/ws-8.2.3.tgz#63a56456db1b04367d0b721a0b80cae6d8becbba"
integrity sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA== integrity sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==
wwobjloader2@^4.0:
version "4.0.1"
resolved "https://registry.yarnpkg.com/wwobjloader2/-/wwobjloader2-4.0.1.tgz#8846325f313b100e6762d09e382398a9ac5a556b"
integrity sha512-+i8jex37jeIcWfTaHLioAvKMcKC/T6yvODVu09FkvKkRsOb843JNjoPxWj5oehedpx2Fj59kK0b7mvO/g4/FXg==
dependencies:
three "^0.133.1"
xml-name-validator@^3.0.0: xml-name-validator@^3.0.0:
version "3.0.0" version "3.0.0"
resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a"
-25
View File
@@ -1,25 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# 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.
import os
from . import commands
from . import geometry
from . import visualizer
from . import transformations
from .visualizer import ViewerWindow, Viewer
def viewer_assets_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "viewer"))
+4 -11
View File
@@ -12,24 +12,17 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import absolute_import, division, print_function
import sys from pyrad.viewer.server.geometry import (
if sys.version_info >= (3, 0):
unicode = str
from .geometry import (
Geometry,
Object,
Mesh, Mesh,
MeshPhongMaterial, MeshPhongMaterial,
Object,
OrthographicCamera, OrthographicCamera,
PerspectiveCamera, PerspectiveCamera,
PointsMaterial,
Points, Points,
PointsMaterial,
) )
from .path import Path from pyrad.viewer.server.path import Path
class SetObject: class SetObject:
+1 -3
View File
@@ -29,15 +29,13 @@ else:
import umsgpack import umsgpack
import numpy as np import numpy as np
from . import transformations as tf
class SceneElement(object): class SceneElement(object):
def __init__(self): def __init__(self):
self.uuid = unicode(uuid.uuid1()) self.uuid = unicode(uuid.uuid1())
def intrinsic_transform(self): def intrinsic_transform(self):
return tf.identity_matrix() return np.identity(4)
class ReferenceSceneElement(SceneElement): class ReferenceSceneElement(SceneElement):
-2
View File
@@ -29,7 +29,6 @@ import zmq.eventloop.ioloop
from aiortc import RTCPeerConnection, RTCSessionDescription from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcrtpsender import RTCRtpSender from aiortc.rtcrtpsender import RTCRtpSender
from zmq.eventloop.zmqstream import ZMQStream from zmq.eventloop.zmqstream import ZMQStream
from pyrad.viewer.server.socket import SerializingContext
from pyrad.viewer.server.tree import SceneTree, find_node, walk from pyrad.viewer.server.tree import SceneTree, find_node, walk
from pyrad.viewer.server.video_stream import SingleFrameStreamTrack from pyrad.viewer.server.video_stream import SingleFrameStreamTrack
@@ -126,7 +125,6 @@ class WebSocketHandler(tornado.websocket.WebSocketHandler):
class ZMQWebSocketBridge(object): class ZMQWebSocketBridge(object):
context = zmq.Context() context = zmq.Context()
# context = SerializingContext()
def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None): def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None):
self.host = host self.host = host
-141
View File
@@ -1,141 +0,0 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# 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.
# https://gist.github.com/jeffbass/ebf877e964c9a0b84272
# zmqimage.py -- classes to send, receive and display cv2 images via zmq
# based on serialization in pyzmq docs and pyzmq/examples/serialization
"""
PURPOSE:
These classes allow a headless (no display) computer running OpenCV code
to display OpenCV images on another computer with a display.
For example, a headless Raspberry Pi with no display can run OpenCV code
and can display OpenCV images on a Mac with a display.
USAGE:
First, start this "display server" program on the computer with a display:
# imageShowServer.py
import zmqimage
zmq = zmqimage.zmqImageShowServer()
print "Starting zmqImageShow Server..."
print " press Ctrl-C to stop"
while True: # Until Ctrl-C is pressed, will repeatedly
zmq.imshow() # display images sent from the headless computer
Run the above program by:
python imageShowServer.py
Leave the above program running in its own terminal window.
Then, run a program like the one below on the headless computer.
In most cases, it will be run using ssh into the headless computer
from another terminal window on the computer with a display.
The python lines below represent a program fragment as an example.
Use zmq.imshow("Image Display Name", image) instead of
cv2.imshow("Image Display Name", image) and the images will
display on the computer running the program above:
import numpy as np
import cv2
import zmqimage
print "Connecting to zmqShowImage Server ... "
zmq = zmqimage.zmqConnect()
image = np.zeros((500, 500), dtype="uint8")
zmq.imshow("Zero Image 500 x 500", image)
# build a rectangular mask & display it
mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(mask, (0, 90), (300, 450), 255, -1)
zmq.imshow("Rectangular Mask", mask)
CAVEATS:
There is no error checking and only Ctrl-C stops the display server.
While zmq.imshow() works like cv2.imshow(), no other
cv2 display functions are implemented.
Uses tcp style sockets; sockets and tcp addresses have
defaults in the classes but may be overridden.
AUTHOR:
Jeff Bass, https://github.com/jeffbass, jeff@yin-yang-ranch.com
"""
import zmq
import numpy as np
import cv2
class SerializingSocket(zmq.Socket):
"""A class with some extra serialization methods
send_array sends numpy arrays with metadata necessary
for reconstructing the array on the other side (dtype,shape).
Also sends array name for display with cv2.show(image).
recv_array receives dict(arrayname,dtype,shape) and an array
and reconstructs the array with the correct shape and array name.
"""
def send_array(self, A, arrayname="NoName", flags=0, copy=True, track=False):
"""send a numpy array with metadata and array name"""
md = dict(
arrayname=arrayname,
dtype=str(A.dtype),
shape=A.shape,
)
self.send_json(md, flags | zmq.SNDMORE)
return self.send(A, flags, copy=copy, track=track)
def recv_array(self, flags=0, copy=True, track=False):
"""recv a numpy array, including arrayname, dtype and shape"""
md = self.recv_json(flags=flags)
msg = self.recv(flags=flags, copy=copy, track=track)
A = np.frombuffer(msg, dtype=md["dtype"])
return (md["arrayname"], A.reshape(md["shape"]))
class SerializingContext(zmq.Context):
_socket_class = SerializingSocket
class zmqConnect:
"""A class that opens a zmq REQ socket on the headless computer"""
def __init__(self, connect_to="tcp://jeff-mac:5555"):
"""initialize zmq socket for sending images to display on remote computer"""
"""connect_to is the tcp address:port of the display computer"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REQ)
self.zmq_socket.connect(connect_to)
def imshow(self, arrayname, array):
"""send image to display on remote server"""
if array.flags["C_CONTIGUOUS"]:
# if array is already contiguous in memory just send it
self.zmq_socket.send_array(array, arrayname, copy=False)
else:
# else make it contiguous before sending
array = np.ascontiguousarray(array)
self.zmq_socket.send_array(array, arrayname, copy=False)
message = self.zmq_socket.recv()
class zmqImageShowServer:
"""A class that opens a zmq REP socket on the display computer to receive images"""
def __init__(self, open_port="tcp://*:5555"):
"""initialize zmq socket on viewing computer that will display images"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REP)
self.zmq_socket.bind(open_port)
def imshow(self, copy=False):
"""receive and show image on viewing computer display"""
arrayname, image = self.zmq_socket.recv_array(copy=False)
# print "Received Array Named: ", arrayname
# print "Array size: ", image.shape
cv2.imshow(arrayname, image)
cv2.waitKey(0)
self.zmq_socket.send(b"OK")
File diff suppressed because it is too large. Load diff
@@ -27,13 +27,13 @@ import torch
import pyrad.viewer.server.cameras as c import pyrad.viewer.server.cameras as c
import pyrad.viewer.server.geometry as g import pyrad.viewer.server.geometry as g
import pyrad.viewer.server.transformations as tf
from pyrad.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix from pyrad.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix
from pyrad.cameras.rays import RayBundle from pyrad.cameras.rays import RayBundle
from pyrad.utils import profiler from pyrad.utils import profiler
from pyrad.utils.config import ViewerConfig from pyrad.utils.config import ViewerConfig
from pyrad.viewer.server import Viewer from pyrad.viewer.server.visualizer import Viewer
from pyrad.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h from pyrad.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h
from pyrad.viewer.server.transformations import get_translation_matrix
class CameraChangeException(Exception): class CameraChangeException(Exception):
@@ -64,7 +64,6 @@ class VisualizerState:
if self.config.enable: if self.config.enable:
zmq_url = self.config.zmq_url zmq_url = self.config.zmq_url
self.vis = Viewer(zmq_url=zmq_url) self.vis = Viewer(zmq_url=zmq_url)
logging.info("Connected to viewer at %s", zmq_url)
self.vis.delete() self.vis.delete()
else: else:
logging.info("Continuing without viewer.") logging.info("Continuing without viewer.")
@@ -120,6 +119,10 @@ class VisualizerState:
aabb = dataset_inputs.scene_bounds.aabb aabb = dataset_inputs.scene_bounds.aabb
draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb") draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb")
# set the main camera intrinsics to one from the dataset
K = camera.get_intrinsics_matrix()
set_persp_intrinsics_matrix(self.vis, K.double().numpy())
def _async_check_camera_update(self): def _async_check_camera_update(self):
"""Async function to check whether camera has been updated in visualizer""" """Async function to check whether camera has been updated in visualizer"""
with self.lock: with self.lock:
@@ -231,7 +234,7 @@ def show_obj(vis, obj_path, name="obj", color=None):
def draw_camera_frustum( def draw_camera_frustum(
vis, vis,
image=np.random.rand(100, 100, 3) * 255.0, image=np.random.rand(100, 100, 3) * 255.0,
pose=tf.translation_matrix([0, 0, 0]), pose=get_translation_matrix([0, 0, 0]),
K=None, K=None,
name="0000000", name="0000000",
displayed_focal_length=None, displayed_focal_length=None,
@@ -270,17 +273,17 @@ def draw_camera_frustum(
g_frustum = c.frustum(scale=1.0, focal_length=displayed_focal_length, width=width, height=height) g_frustum = c.frustum(scale=1.0, focal_length=displayed_focal_length, width=width, height=height)
vis[name + "/frustum"].set_object(g_frustum) vis[name + "/frustum"].set_object(g_frustum)
if not realistic: if not realistic:
vis[name + "/frustum"].set_transform(tf.translation_matrix([0, 0, displayed_focal_length])) vis[name + "/frustum"].set_transform(get_translation_matrix([0, 0, displayed_focal_length]))
# draw the image plane # draw the image plane
g_image_plane = c.ImagePlane(image, width=width, height=height) g_image_plane = c.ImagePlane(image, width=width, height=height)
vis[name + "/image_plane"].set_object(g_image_plane) vis[name + "/image_plane"].set_object(g_image_plane)
if realistic: if realistic:
vis[name + "/image_plane"].set_transform(tf.translation_matrix([0, 0, -displayed_focal_length])) vis[name + "/image_plane"].set_transform(get_translation_matrix([0, 0, -displayed_focal_length]))
if shift_forward: if shift_forward:
matrix = tf.translation_matrix([0, 0, displayed_focal_length]) matrix = get_translation_matrix([0, 0, displayed_focal_length])
matrix2 = tf.translation_matrix([0, 0, -shift_forward]) matrix2 = get_translation_matrix([0, 0, -shift_forward])
vis[name + "/frustum"].set_transform(matrix2 @ matrix) vis[name + "/frustum"].set_transform(matrix2 @ matrix)
vis[name + "/image_plane"].set_transform(matrix2) vis[name + "/image_plane"].set_transform(matrix2)
@@ -288,14 +291,7 @@ def draw_camera_frustum(
vis[name].set_transform(pose) vis[name].set_transform(pose)
def set_persp_camera(vis, pose, K, colmap=True): def set_persp_intrinsics_matrix(vis, K):
"""Assumes simple pinhole model for intrinsics.
Args:
colmap: whether to use the colmap camera coordinate convention or not
"""
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
pp_w = K[0, 2] pp_w = K[0, 2]
pp_h = K[1, 2] pp_h = K[1, 2]
assert K[0, 0] == K[1, 1] assert K[0, 0] == K[1, 1]
@@ -304,9 +300,24 @@ def set_persp_camera(vis, pose, K, colmap=True):
fov = 2.0 * np.arctan(x) * (180.0 / np.pi) fov = 2.0 * np.arctan(x) * (180.0 / np.pi)
vis["/Cameras/Main Camera/<object>"].set_property("fov", fov) vis["/Cameras/Main Camera/<object>"].set_property("fov", fov)
vis["/Cameras/Main Camera/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height vis["/Cameras/Main Camera/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height
def set_persp_pose(vis, pose, colmap=True):
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
vis["/Cameras/Main Camera/<object>"].set_transform(pose_processed) vis["/Cameras/Main Camera/<object>"].set_transform(pose_processed)
def set_persp_camera(vis, pose, K, colmap=True):
"""Assumes simple pinhole model for intrinsics.
Args:
colmap: whether to use the colmap camera coordinate convention or not
"""
set_persp_intrinsics_matrix(vis, K)
set_persp_pose(vis, pose, colmap=colmap)
def set_camera(vis, camera: Camera): def set_camera(vis, camera: Camera):
pose = camera.get_camera_to_world_h() pose = camera.get_camera_to_world_h()
K = camera.get_intrinsics_matrix() K = camera.get_intrinsics_matrix()
@@ -318,4 +329,4 @@ def draw_aabb(vis, aabb, name="aabb"):
lengths = aabb[1] - aabb[0] lengths = aabb[1] - aabb[0]
vis[name].set_object(g.Box(lengths.tolist()), material=g.MeshPhongMaterial(color=0xFF0000, opacity=0.1)) vis[name].set_object(g.Box(lengths.tolist()), material=g.MeshPhongMaterial(color=0xFF0000, opacity=0.1))
center = aabb[0] + lengths / 2.0 center = aabb[0] + lengths / 2.0
vis[name].set_transform(tf.translation_matrix(center.tolist())) vis[name].set_transform(get_translation_matrix(center.tolist()))
+49 -7
View File
@@ -12,28 +12,28 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import absolute_import, division, print_function import logging
import signal
import sys
import numpy as np
import msgpack import msgpack
import msgpack_numpy import msgpack_numpy
import numpy as np
import umsgpack import umsgpack
import zmq import zmq
from pyrad.viewer.server.socket import SerializingContext from pyrad.viewer.server.commands import Delete, GetObject, SetObject, SetProperty, SetTransform
from pyrad.viewer.server.path import Path
from .commands import Delete, SetObject, GetObject, SetProperty, SetTransform
from .path import Path
class ViewerWindow(object): class ViewerWindow(object):
context = zmq.Context() context = zmq.Context()
# context = SerializingContext()
def __init__(self, zmq_url): def __init__(self, zmq_url):
self.zmq_url = zmq_url self.zmq_url = zmq_url
self.client = self.context.socket(zmq.REQ) self.client = self.context.socket(zmq.REQ)
self.client.connect(self.zmq_url) self.client.connect(self.zmq_url)
self.assert_connected()
def send(self, command): def send(self, command):
cmd_data = command.lower() cmd_data = command.lower()
@@ -46,11 +46,53 @@ class ViewerWindow(object):
) )
return self.client.recv() return self.client.recv()
def send_ping(self):
"""Tries to contact the viewer bridge server."""
type_ = "ping"
path = ""
data = umsgpack.packb({"type": type_, "path": path})
self.client.send_multipart(
[
type_.encode("utf-8"),
path.encode("utf-8"),
data,
]
)
return self.client.recv()
def assert_connected(self, timeout_in_sec: int = 5):
"""Check if the connection was established properly within some time.
Args:
timeout_in_sec (int): The maximum time to wait for the connection to be established.
"""
def timeout_handler(signum, frame):
raise Exception(f"Couldn't connect to the viewer Bridge Server in {timeout_in_sec} seconds. Exiting.")
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout_in_sec)
try:
logging.info("Sending ping to the viewer Bridge Server...")
response = self.send_ping()
logging.info("Successfully connected.")
signal.alarm(0) # cancel the alarm
except Exception as e:
logging.info(e)
sys.exit()
class Viewer(object): class Viewer(object):
"""Visualizer class for connecting to the bridge server.""" """Visualizer class for connecting to the bridge server."""
def __init__(self, zmq_url: str = None, window: ViewerWindow = None): def __init__(self, zmq_url: str = None, window: ViewerWindow = None):
"""_summary_
Args:
zmq_url (str, optional): _description_. Defaults to None.
window (ViewerWindow, optional): _description_. Defaults to None.
timeout (str, optional): _description_. Defaults to None.
"""
if zmq_url is None and window is None: if zmq_url is None and window is None:
raise ValueError("Must specify either zmq_url or window.") raise ValueError("Must specify either zmq_url or window.")
if window is None: if window is None:
File renamed without changes.
-325
View File
@@ -1,325 +0,0 @@
from __future__ import absolute_import, division, print_function
import unittest
import subprocess
import sys
import tempfile
import os
if sys.version_info >= (3, 0):
from io import StringIO, BytesIO
else:
from StringIO import StringIO
BytesIO = StringIO
import io
import numpy as np
import meshcat
import meshcat.geometry as g
import meshcat.cameras as c
import meshcat.transformations as tf
class VisualizerTest(unittest.TestCase):
def setUp(self):
self.vis = meshcat.Visualizer()
if "CI" in os.environ:
port = self.vis.url().split(":")[-1].split("/")[0]
self.dummy_proc = subprocess.Popen(
[sys.executable, "-m", "meshcat.tests.dummy_websocket_client", str(port)]
)
else:
self.vis.open()
self.dummy_proc = None
self.vis.wait()
def tearDown(self):
if self.dummy_proc is not None:
self.dummy_proc.kill()
class TestDrawing(VisualizerTest):
def runTest(self):
self.vis.delete()
v = self.vis["shapes"]
v.set_transform(tf.translation_matrix([1.0, 0, 0]))
v["box"].set_object(g.Box([1.0, 0.2, 0.3]))
v["box"].delete()
v["box"].set_object(g.Box([0.1, 0.2, 0.3]))
v["box"].set_transform(tf.translation_matrix([0.05, 0.1, 0.15]))
v["cylinder"].set_object(g.Cylinder(0.2, 0.1), g.MeshLambertMaterial(color=0x22DD22))
v["cylinder"].set_transform(tf.translation_matrix([0, 0.5, 0.1]).dot(tf.rotation_matrix(-np.pi / 2, [1, 0, 0])))
v["sphere"].set_object(g.Mesh(g.Sphere(0.15), g.MeshLambertMaterial(color=0xFF11DD)))
v["sphere"].set_transform(tf.translation_matrix([0, 1, 0.15]))
v["ellipsoid"].set_object(g.Ellipsoid([0.3, 0.1, 0.1]))
v["ellipsoid"].set_transform(tf.translation_matrix([0, 1.5, 0.1]))
v["transparent_ellipsoid"].set_object(
g.Mesh(g.Ellipsoid([0.3, 0.1, 0.1]), g.MeshLambertMaterial(color=0xFFFFFF, opacity=0.5))
)
v["transparent_ellipsoid"].set_transform(tf.translation_matrix([0, 2.0, 0.1]))
v = self.vis["meshes/valkyrie/head"]
v.set_object(
g.Mesh(
g.ObjMeshGeometry.from_file(os.path.join(meshcat.viewer_assets_path(), "data/head_multisense.obj")),
g.MeshLambertMaterial(
map=g.ImageTexture(
image=g.PngImage.from_file(
os.path.join(meshcat.viewer_assets_path(), "data/HeadTextureMultisense.png")
)
)
),
)
)
v.set_transform(tf.translation_matrix([0, 0.5, 0.5]))
v = self.vis["meshes/convex"]
v["obj"].set_object(
g.Mesh(
g.ObjMeshGeometry.from_file(
os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.obj")
)
)
)
v["stl_ascii"].set_object(
g.Mesh(
g.StlMeshGeometry.from_file(
os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.stl_ascii")
)
)
)
v["stl_ascii"].set_transform(tf.translation_matrix([0, -0.5, 0]))
v["stl_binary"].set_object(
g.Mesh(
g.StlMeshGeometry.from_file(
os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.stl_binary")
)
)
)
v["stl_binary"].set_transform(tf.translation_matrix([0, -1, 0]))
v["dae"].set_object(
g.Mesh(
g.DaeMeshGeometry.from_file(
os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.dae")
)
)
)
v["dae"].set_transform(tf.translation_matrix([0, -1.5, 0]))
v = self.vis["points"]
v.set_transform(tf.translation_matrix([0, 2, 0]))
verts = np.random.rand(3, 1000000)
colors = verts
v["random"].set_object(g.PointCloud(verts, colors))
v["random"].set_transform(tf.translation_matrix([-0.5, -0.5, 0]))
v = self.vis["lines"]
v.set_transform(tf.translation_matrix(([-2, -3, 0])))
vertices = np.random.random((3, 10)).astype(np.float32)
v["line_segments"].set_object(g.LineSegments(g.PointsGeometry(vertices)))
v["line"].set_object(g.Line(g.PointsGeometry(vertices)))
v["line"].set_transform(tf.translation_matrix([0, 1, 0]))
v["line_loop"].set_object(g.LineLoop(g.PointsGeometry(vertices)))
v["line_loop"].set_transform(tf.translation_matrix([0, 2, 0]))
v["line_loop_with_material"].set_object(
g.LineLoop(g.PointsGeometry(vertices), g.LineBasicMaterial(color=0xFF0000))
)
v["line_loop_with_material"].set_transform(tf.translation_matrix([0, 3, 0]))
colors = vertices # Color each line by treating its xyz coordinates as RGB colors
v["line_with_vertex_colors"].set_object(
g.Line(g.PointsGeometry(vertices, colors), g.LineBasicMaterial(vertexColors=True))
)
v["line_with_vertex_colors"].set_transform(tf.translation_matrix([0, 4, 0]))
v["triad"].set_object(
g.LineSegments(
g.PointsGeometry(
position=np.array([[0, 0, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]])
.astype(np.float32)
.T,
color=np.array([[1, 0, 0], [1, 0.6, 0], [0, 1, 0], [0.6, 1, 0], [0, 0, 1], [0, 0.6, 1]])
.astype(np.float32)
.T,
),
g.LineBasicMaterial(vertexColors=True),
)
)
v["triad"].set_transform(tf.translation_matrix(([0, 5, 0])))
v["triad_function"].set_object(g.triad(0.5))
v["triad_function"].set_transform(tf.translation_matrix([0, 6, 0]))
class TestMeshStreams(VisualizerTest):
def runTest(self):
"""Applications using meshcat may already have meshes loaded in memory. It is
more efficient to load these meshes with streams rather than going to and then
from a file on disk. To test this we are importing meshes from disk and
converting them into streams so it kind of defeats the intended purpose! But at
least it tests the functionality.
"""
self.vis.delete()
v = self.vis["meshes/convex"]
# Obj file
filename = os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.obj")
with open(filename, "r") as f:
fio = StringIO(f.read())
v["stream_obj"].set_object(g.Mesh(g.ObjMeshGeometry.from_stream(fio)))
v["stream_stl_ascii"].set_transform(tf.translation_matrix([0, 0.0, 0]))
# STL ASCII
filename = os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.stl_ascii")
with open(filename, "r") as f:
fio = StringIO(f.read())
v["stream_stl_ascii"].set_object(g.Mesh(g.StlMeshGeometry.from_stream(fio)))
v["stream_stl_ascii"].set_transform(tf.translation_matrix([0, -0.5, 0]))
# STL Binary
filename = os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.stl_binary")
with open(filename, "rb") as f:
fio = BytesIO(f.read())
v["stream_stl_binary"].set_object(g.Mesh(g.StlMeshGeometry.from_stream(fio)))
v["stream_stl_binary"].set_transform(tf.translation_matrix([0, -1.0, 0]))
# DAE
filename = os.path.join(meshcat.viewer_assets_path(), "../tests/data/mesh_0_convex_piece_0.dae")
with open(filename, "r") as f:
fio = StringIO(f.read())
v["stream_dae"].set_object(g.Mesh(g.DaeMeshGeometry.from_stream(fio)))
v["stream_dae"].set_transform(tf.translation_matrix([0, -1.5, 0]))
class TestStandaloneServer(unittest.TestCase):
def setUp(self):
self.zmq_url = "tcp://127.0.0.1:5560"
args = ["meshcat-server", "--zmq-url", self.zmq_url]
if "CI" not in os.environ:
args.append("--open")
self.server_proc = subprocess.Popen(args)
self.vis = meshcat.Visualizer(self.zmq_url)
# self.vis = meshcat.Visualizer()
# self.vis.open()
if "CI" in os.environ:
port = self.vis.url().split(":")[-1].split("/")[0]
self.dummy_proc = subprocess.Popen(
[sys.executable, "-m", "meshcat.tests.dummy_websocket_client", str(port)]
)
else:
# self.vis.open()
self.dummy_proc = None
self.vis.wait()
def runTest(self):
v = self.vis["shapes"]
v["cube"].set_object(g.Box([0.1, 0.2, 0.3]))
v.set_transform(tf.translation_matrix([1.0, 0, 0]))
v.set_transform(tf.translation_matrix([1.0, 1.0, 0]))
def tearDown(self):
if self.dummy_proc is not None:
self.dummy_proc.kill()
self.server_proc.kill()
class TestAnimation(VisualizerTest):
def runTest(self):
v = self.vis["shapes"]
v.set_transform(tf.translation_matrix([1.0, 0, 0]))
v["cube"].set_object(g.Box([0.1, 0.2, 0.3]))
animation = meshcat.animation.Animation()
with animation.at_frame(v, 0) as frame_vis:
frame_vis.set_transform(tf.translation_matrix([0, 0, 0]))
with animation.at_frame(v, 30) as frame_vis:
frame_vis.set_transform(tf.translation_matrix([2, 0, 0]).dot(tf.rotation_matrix(np.pi / 2, [0, 0, 1])))
v.set_animation(animation)
class TestCameraAnimation(VisualizerTest):
def runTest(self):
v = self.vis["shapes"]
v.set_transform(tf.translation_matrix([1.0, 0, 0]))
v["cube"].set_object(g.Box([0.1, 0.2, 0.3]))
animation = meshcat.animation.Animation()
with animation.at_frame(v, 0) as frame_vis:
frame_vis.set_transform(tf.translation_matrix([0, 0, 0]))
with animation.at_frame(v, 30) as frame_vis:
frame_vis.set_transform(tf.translation_matrix([2, 0, 0]).dot(tf.rotation_matrix(np.pi / 2, [0, 0, 1])))
with animation.at_frame(v, 0) as frame_vis:
frame_vis["/Cameras/default/rotated/<object>"].set_property("zoom", "number", 1)
with animation.at_frame(v, 30) as frame_vis:
frame_vis["/Cameras/default/rotated/<object>"].set_property("zoom", "number", 0.5)
v.set_animation(animation)
class TestStaticHTML(TestDrawing):
def runTest(self):
"""Test that we can generate a static HTML file from the Drawing test case and view it."""
super(TestStaticHTML, self).runTest()
res = self.vis.static_html()
# save to a file
temp = tempfile.mkstemp(suffix=".html")
with open(temp[1], "w") as f:
f.write(res)
class TestSetProperty(VisualizerTest):
def runTest(self):
self.vis["/Background"].set_property("top_color", [255, 0, 0])
class TestTriangularMesh(VisualizerTest):
def runTest(self):
"""
Test that we can render meshes from raw vertices and faces as
numpy arrays
"""
v = self.vis["triangular_mesh"]
v.set_transform(tf.rotation_matrix(np.pi / 2, [0.0, 0, 1]))
vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]])
faces = np.array([[0, 1, 2], [3, 0, 2]])
v.set_object(g.TriangularMeshGeometry(vertices, faces), g.MeshLambertMaterial(color=0xEEDD22, wireframe=True))
class TestOrthographicCamera(VisualizerTest):
def runTest(self):
"""
Test that we can set_object with an OrthographicCamera.
"""
self.vis.set_object(g.Box([0.5, 0.5, 0.5]))
camera = c.OrthographicCamera(left=-1, right=1, bottom=-1, top=1, near=-1000, far=1000)
self.vis["/Cameras/default/rotated"].set_object(camera)
self.vis["/Cameras/default"].set_transform(tf.translation_matrix([0, -1, 0]))
self.vis["/Cameras/default/rotated/<object>"].set_property("position", [0, 0, 0])
self.vis["/Grid"].set_property("visible", False)
class TestPerspectiveCamera(VisualizerTest):
def runTest(self):
"""
Test that we can set_object with a PerspectiveCamera.
"""
self.vis.set_object(g.Box([0.5, 0.5, 0.5]))
camera = g.PerspectiveCamera(fov=90)
self.vis["/Cameras/default/rotated"].set_object(camera)
self.vis["/Cameras/default"].set_transform(tf.translation_matrix([1, -1, 0.5]))
self.vis["/Cameras/default/rotated/<object>"].set_property("position", [0, 0, 0])
@@ -12,35 +12,35 @@ import umsgpack
from tqdm import tqdm from tqdm import tqdm
import pyrad.viewer.server.geometry as g import pyrad.viewer.server.geometry as g
import pyrad.viewer.server.transformations as tf
from pyrad.cameras.camera_paths import InterpolatedCameraPath from pyrad.cameras.camera_paths import InterpolatedCameraPath
from pyrad.cameras.cameras import get_camera from pyrad.cameras.cameras import get_camera
from pyrad.data.utils import get_dataset_inputs from pyrad.data.utils import get_dataset_inputs
from pyrad.utils.io import get_absolute_path from pyrad.utils.io import get_absolute_path
from pyrad.viewer.server.vis_utils import get_vis, set_camera from pyrad.viewer.server.viewer_utils import get_default_vis, set_camera
from pyrad.viewer.server.transformations import get_rotation_matrix, get_translation_matrix
def test_drawing(): def test_drawing():
vis = get_vis() vis = get_default_vis()
vis.delete() vis.delete()
v = vis["shapes"] v = vis["shapes"]
v.set_transform(tf.translation_matrix([1.0, 0, 0])) v.set_transform(get_translation_matrix([1.0, 0, 0]))
v["box"].set_object(g.Box([1.0, 0.2, 0.3])) v["box"].set_object(g.Box([1.0, 0.2, 0.3]))
v["box"].delete() v["box"].delete()
v["box"].set_object(g.Box([0.1, 0.2, 0.3])) v["box"].set_object(g.Box([0.1, 0.2, 0.3]))
v["box"].set_transform(tf.translation_matrix([0.05, 0.1, 0.15])) v["box"].set_transform(get_translation_matrix([0.05, 0.1, 0.15]))
v["cylinder"].set_object(g.Cylinder(0.2, 0.1), g.MeshLambertMaterial(color=0x22DD22)) v["cylinder"].set_object(g.Cylinder(0.2, 0.1), g.MeshLambertMaterial(color=0x22DD22))
v["cylinder"].set_transform(tf.translation_matrix([0, 0.5, 0.1]).dot(tf.rotation_matrix(-np.pi / 2, [1, 0, 0]))) v["cylinder"].set_transform(get_translation_matrix([0, 0.5, 0.1]).dot(get_rotation_matrix(-np.pi / 2, [1, 0, 0])))
v["sphere"].set_object(g.Mesh(g.Sphere(0.15), g.MeshLambertMaterial(color=0xFF11DD))) v["sphere"].set_object(g.Mesh(g.Sphere(0.15), g.MeshLambertMaterial(color=0xFF11DD)))
v["sphere"].set_transform(tf.translation_matrix([0, 1, 0.15])) v["sphere"].set_transform(get_translation_matrix([0, 1, 0.15]))
v["ellipsoid"].set_object(g.Ellipsoid([0.3, 0.1, 0.1])) v["ellipsoid"].set_object(g.Ellipsoid([0.3, 0.1, 0.1]))
v["ellipsoid"].set_transform(tf.translation_matrix([0, 1.5, 0.1])) v["ellipsoid"].set_transform(get_translation_matrix([0, 1.5, 0.1]))
v["transparent_ellipsoid"].set_object( v["transparent_ellipsoid"].set_object(
g.Mesh(g.Ellipsoid([0.3, 0.1, 0.1]), g.MeshLambertMaterial(color=0xFFFFFF, opacity=0.5)) g.Mesh(g.Ellipsoid([0.3, 0.1, 0.1]), g.MeshLambertMaterial(color=0xFFFFFF, opacity=0.5))
) )
v["transparent_ellipsoid"].set_transform(tf.translation_matrix([0, 2.0, 0.1])) v["transparent_ellipsoid"].set_transform(get_translation_matrix([0, 2.0, 0.1]))
v = vis["meshes/convex"] v = vis["meshes/convex"]
v["obj"].set_object( v["obj"].set_object(
@@ -49,43 +49,43 @@ def test_drawing():
v["stl_ascii"].set_object( v["stl_ascii"].set_object(
g.Mesh(g.StlMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.stl_ascii"))) g.Mesh(g.StlMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.stl_ascii")))
) )
v["stl_ascii"].set_transform(tf.translation_matrix([0, -0.5, 0])) v["stl_ascii"].set_transform(get_translation_matrix([0, -0.5, 0]))
v["stl_binary"].set_object( v["stl_binary"].set_object(
g.Mesh(g.StlMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.stl_binary"))) g.Mesh(g.StlMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.stl_binary")))
) )
v["stl_binary"].set_transform(tf.translation_matrix([0, -1, 0])) v["stl_binary"].set_transform(get_translation_matrix([0, -1, 0]))
v["dae"].set_object( v["dae"].set_object(
g.Mesh(g.DaeMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.dae"))) g.Mesh(g.DaeMeshGeometry.from_file(get_absolute_path("tests/viewer/data/mesh_0_convex_piece_0.dae")))
) )
v["dae"].set_transform(tf.translation_matrix([0, -1.5, 0])) v["dae"].set_transform(get_translation_matrix([0, -1.5, 0]))
v = vis["points"] v = vis["points"]
v.set_transform(tf.translation_matrix([0, 2, 0])) v.set_transform(get_translation_matrix([0, 2, 0]))
verts = np.random.rand(3, 1000000) verts = np.random.rand(3, 1000000)
colors = verts colors = verts
v["random"].set_object(g.PointCloud(verts, colors)) v["random"].set_object(g.PointCloud(verts, colors))
v["random"].set_transform(tf.translation_matrix([-0.5, -0.5, 0])) v["random"].set_transform(get_translation_matrix([-0.5, -0.5, 0]))
v = vis["lines"] v = vis["lines"]
v.set_transform(tf.translation_matrix(([-2, -3, 0]))) v.set_transform(get_translation_matrix(([-2, -3, 0])))
vertices = np.random.random((3, 10)).astype(np.float32) vertices = np.random.random((3, 10)).astype(np.float32)
v["line_segments"].set_object(g.LineSegments(g.PointsGeometry(vertices))) v["line_segments"].set_object(g.LineSegments(g.PointsGeometry(vertices)))
v["line"].set_object(g.Line(g.PointsGeometry(vertices))) v["line"].set_object(g.Line(g.PointsGeometry(vertices)))
v["line"].set_transform(tf.translation_matrix([0, 1, 0])) v["line"].set_transform(get_translation_matrix([0, 1, 0]))
v["line_loop"].set_object(g.LineLoop(g.PointsGeometry(vertices))) v["line_loop"].set_object(g.LineLoop(g.PointsGeometry(vertices)))
v["line_loop"].set_transform(tf.translation_matrix([0, 2, 0])) v["line_loop"].set_transform(get_translation_matrix([0, 2, 0]))
v["line_loop_with_material"].set_object(g.LineLoop(g.PointsGeometry(vertices), g.LineBasicMaterial(color=0xFF0000))) v["line_loop_with_material"].set_object(g.LineLoop(g.PointsGeometry(vertices), g.LineBasicMaterial(color=0xFF0000)))
v["line_loop_with_material"].set_transform(tf.translation_matrix([0, 3, 0])) v["line_loop_with_material"].set_transform(get_translation_matrix([0, 3, 0]))
colors = vertices # Color each line by treating its xyz coordinates as RGB colors colors = vertices # Color each line by treating its xyz coordinates as RGB colors
v["line_with_vertex_colors"].set_object( v["line_with_vertex_colors"].set_object(
g.Line(g.PointsGeometry(vertices, colors), g.LineBasicMaterial(vertexColors=True)) g.Line(g.PointsGeometry(vertices, colors), g.LineBasicMaterial(vertexColors=True))
) )
v["line_with_vertex_colors"].set_transform(tf.translation_matrix([0, 4, 0])) v["line_with_vertex_colors"].set_transform(get_translation_matrix([0, 4, 0]))
v["triad"].set_object( v["triad"].set_object(
g.LineSegments( g.LineSegments(
@@ -100,10 +100,10 @@ def test_drawing():
g.LineBasicMaterial(vertexColors=True), g.LineBasicMaterial(vertexColors=True),
) )
) )
v["triad"].set_transform(tf.translation_matrix(([0, 5, 0]))) v["triad"].set_transform(get_translation_matrix(([0, 5, 0])))
v["triad_function"].set_object(g.triad(0.5)) v["triad_function"].set_object(g.triad(0.5))
v["triad_function"].set_transform(tf.translation_matrix([0, 6, 0])) v["triad_function"].set_transform(get_translation_matrix([0, 6, 0]))
def test_streaming(): def test_streaming():
@@ -116,7 +116,7 @@ def test_rendering():
def test_camera_trajectory(): def test_camera_trajectory():
print("test_camera_trajectory") print("test_camera_trajectory")
vis = get_vis() vis = get_default_vis()
# vis.delete() # vis.delete()
# sample poses from a dataset # sample poses from a dataset
@@ -145,7 +145,7 @@ def test_camera_trajectory():
def test_send_image_stream(): def test_send_image_stream():
vis = get_vis() vis = get_default_vis()
vis_Background = vis["/Background"] vis_Background = vis["/Background"]
video_filename = get_absolute_path("data/instant_ngp/bear/bear.MOV") video_filename = get_absolute_path("data/instant_ngp/bear/bear.MOV")
@@ -169,11 +169,11 @@ def test_send_image_stream():
def test_perspective_camera(): def test_perspective_camera():
vis = get_vis() vis = get_default_vis()
vis.set_object(g.Box([0.5, 0.5, 0.5])) vis.set_object(g.Box([0.5, 0.5, 0.5]))
camera = g.PerspectiveCamera(fov=90) camera = g.PerspectiveCamera(fov=90)
vis["/Cameras/default/rotated"].set_object(camera) vis["/Cameras/default/rotated"].set_object(camera)
vis["/Cameras/default"].set_transform(tf.translation_matrix([1, -1, 0.5])) vis["/Cameras/default"].set_transform(get_translation_matrix([1, -1, 0.5]))
vis["/Cameras/default/rotated/<object>"].set_property("position", [0, 0, 0]) vis["/Cameras/default/rotated/<object>"].set_property("position", [0, 0, 0])