Initial viewer (visualizer) code (#52)

* some initial code for viewer. copying from other repos

* adding electron support

* moving some test files around. need to rewrite these

* camera traj. test cases. starting to transmit images

* still working on vis

* reorganized viewer and figured out websocket sending from client. need to do with camera pose

* black

* temporarily ignore pylinting for viewer

* ignore viewer

* fixed array

* license and fixed ignore in pyproject.toml

* improved syntax
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-06-16 12:11:40 -07:00
1 parent 91ef54963c
commit 1e22984d87
50 files changed
+16946 -919

No files matched your search

+61 -5
View File
@@ -1,10 +1,66 @@
# Viewer
The backend viewer code (python, websockets, ...).
#### Backend (backend/)
# References
The backend faciliates communication between Python code and the ReactJS client application.
```
https://github.com/lp-research/openvslam/tree/main/viewer
https://github.com/rdeits/meshcat
```
cd backend
python run_zmq_server.py
It should print out something of the form:
"ZMQWebSocketBridge using zmq_url=tcp://127.0.0.1:6000 and websocket_port=8051"
```
#### Client (app/)
The ReactJS client code is in the `app` folder. First, install the most recent version of node.
```
cd app
# install yarn and package.json dependencies
npm install --global yarn
yarn install
# start the application
yarn start
# forward port and open in your local browser
# the URL takes the following form
# http://localhost:<forwarded_react_port>/localhost:<forwarded_backend_tcp_port>
http://localhost:4000/localhost:8051
```
Possibly edit the port in `app/.env.development` file with the following:
```
BROWSER=none
FAST_REFRESH=false
HOST=localhost
PORT=4000
```
#### Establishing the connection from Python
See `notebooks/visualize_viewer.ipynb` for a quick overview of how to interact with the viewer.
<hr>
#### How to use with VNC
> This section is more experimental and shouldn't be used right now. Eventually it would be nice to support an Electron app for local use instead of using a web browser (e.g., Chrome).
```
https://tigervnc.org/doc/Xvnc.html
# start vnc server
/opt/TurboVNC/bin/Xvnc :5017 -rfbport 5017 -SecurityTypes none -localsts
# run the application. TODO: get electron to work!
alias wgui='vglrun -d :0.0'
export DISPLAY=:5017
wgui chromium-browser http://localhost:3000/localhost:8051
```
The server communication code is in the `comms` folder.
+4
View File
@@ -0,0 +1,4 @@
BROWSER=none
FAST_REFRESH=false
HOST=localhost
PORT=4000
+14
View File
@@ -0,0 +1,14 @@
.idea/
.vscode/
node_modules/
build/
.DS_Store
*.tgz
my-app*
template/src/__tests__/__snapshots__/
lerna-debug.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/.changelog
.npm/
+52
View File
@@ -0,0 +1,52 @@
{
"name": "viewer",
"version": "0.0.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.2.0",
"ccapture.js": "github:aceslowman/ccapture.js#npm-fix",
"dat.gui": "^0.7.9",
"msgpack-lite": "^0.1.26",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "^5.0.1",
"socket.io-client": "^4.5.1",
"three": "^0.141.0",
"websocket": "^1.0.34"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"electron": "electron ."
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"main": "public/electron.js",
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"concurrently": "^7.2.1",
"electron": "^19.0.4",
"electron-is-dev": "^2.0.0",
"typescript": "^4.7.3",
"wait-on": "^6.0.1"
}
}
+47
View File
@@ -0,0 +1,47 @@
const path = require("path");
const { app, BrowserWindow } = require("electron");
const isDev = require("electron-is-dev");
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: "detach" });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>visualizer</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

+25
View File
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

+234
View File
@@ -0,0 +1,234 @@
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;
}
+38
View File
@@ -0,0 +1,38 @@
.App {
/*text-align: center;*/
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
+45
View File
@@ -0,0 +1,45 @@
import React, { Component } from "react";
import "./App.css";
import { Viewer } from "./Viewer";
class Image extends Component {
constructor(props) {
super(props);
this.state = {};
}
}
class ColorGUIHelper {
constructor(object, prop) {
this.object = object;
this.prop = prop;
}
get value() {
return `#${this.object[this.prop].getHexString()}`;
}
set value(hexString) {
this.object[this.prop].set(hexString);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
client: null,
};
this.viewer_ref = React.createRef();
}
render() {
return (
<div className="App">
<Viewer ref={this.viewer_ref} />
</div>
);
}
}
export default App;
+9
View File
@@ -0,0 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
@@ -0,0 +1,283 @@
import * as THREE from "three";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader.js";
import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js";
// import {MtlObjBridge} from 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.js';
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader.js";
import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js";
// Merges a hierarchy of collada mesh geometries into a single
// `BufferGeometry` object:
// * A new merged `BufferGeometry` if the input contains meshes
// * empty `BufferGeometry` otherwise
function merge_geometries(object, preserve_materials = false) {
let materials = [];
let geometries = [];
let root_transform = object.matrix.clone();
function collectGeometries(node, parent_transform) {
let transform = parent_transform.clone().multiply(node.matrix);
if (node.type === "Mesh") {
node.geometry.applyMatrix(transform);
geometries.push(node.geometry);
materials.push(node.material);
}
for (let child of node.children) {
collectGeometries(child, transform);
}
}
collectGeometries(object, root_transform);
let result = null;
if (geometries.length === 1) {
result = geometries[0];
if (preserve_materials) {
result.material = materials[0];
}
} else if (geometries.length > 1) {
result = BufferGeometryUtils.mergeBufferGeometries(geometries, true);
if (preserve_materials) {
result.material = materials;
}
} else {
result = new THREE.BufferGeometry();
}
return result;
}
// Handler for special texture types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single texture, and should
// return either:
// * A new `THREE.Texture` if that json represents a special texture
// * `null` otherwise
function handle_special_texture(json) {
if (json.type === "_text") {
let canvas = document.createElement("canvas");
// canvas width and height should be in the power of 2; otherwise although
// the page usually loads successfully, WebGL does complain/warn
canvas.width = 256;
canvas.height = 256;
let ctx = canvas.getContext("2d");
ctx.textAlign = "center";
let font_size = json.font_size;
// auto-resing the font_size to fit in the canvas
ctx.font = font_size + "px " + json.font_face;
while (ctx.measureText(json.text).width > canvas.width) {
font_size--;
ctx.font = font_size + "px " + json.font_face;
}
ctx.fillText(json.text, canvas.width / 2, canvas.height / 2);
let canvas_texture = new THREE.CanvasTexture(canvas);
canvas_texture.uuid = json.uuid;
return canvas_texture;
} else {
return null;
}
}
// Handler for special geometry types that we want to support
// in addition to whatever three.js supports. This function
// takes a json object representing a single geometry, and should
// return either:
// * A new `THREE.Mesh` if that json represents a special geometry
// * `null` otherwise
function handle_special_geometry(geom) {
if (geom.type === "_meshfile") {
console.warn(
"_meshfile is deprecated. Please use _meshfile_geometry for geometries and _meshfile_object for objects with geometry and material"
);
geom.type = "_meshfile_geometry";
}
if (geom.type === "_meshfile_geometry") {
if (geom.format === "obj") {
let loader = new OBJLoader();
let obj = loader.parse(geom.data + "\n");
let loaded_geom = merge_geometries(obj);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else if (geom.format === "dae") {
let loader = new ColladaLoader();
let obj = loader.parse(geom.data);
let result = merge_geometries(obj.scene);
result.uuid = geom.uuid;
return result;
} else if (geom.format === "stl") {
let loader = new STLLoader();
let loaded_geom = loader.parse(geom.data.buffer);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else if (geom.format === "ply") {
let loader = new PLYLoader();
let loaded_geom = loader.parse(geom.data.buffer);
loaded_geom.uuid = geom.uuid;
return loaded_geom;
} else {
console.error("Unsupported mesh type:", geom);
return null;
}
}
return null;
}
// The ExtensibleObjectLoader extends the THREE.ObjectLoader
// interface, while providing some hooks for us to perform some
// custom loading for things other than three.js native JSON.
//
// We currently use this class to support some extensions to
// three.js JSON for objects which are easy to construct in
// javascript but hard to construct in Python and/or Julia.
// For example, we perform the following transformations:
//
// * Converting "_meshfile" geometries into actual meshes
// using the THREE.js native mesh loaders
// * Converting "_text" textures into text by drawing the
// requested text onto a canvas.
export class ExtensibleObjectLoader extends THREE.ObjectLoader {
delegate(special_handler, base_handler, json, additional_objects) {
let result = {};
if (json === undefined) {
return result;
}
let remaining_json = [];
for (let data of json) {
let x = special_handler(data);
if (x !== null) {
result[x.uuid] = x;
} else {
remaining_json.push(data);
}
}
return Object.assign(
result,
base_handler(remaining_json, additional_objects)
);
}
parseTextures(json, images) {
return this.delegate(
handle_special_texture,
super.parseTextures,
json,
images
);
}
parseGeometries(json, shapes) {
return this.delegate(
handle_special_geometry,
super.parseGeometries,
json,
shapes
);
}
parseObject(json, geometries, materials) {
if (json.type === "_meshfile_object") {
let geometry;
let material;
let manager = new THREE.LoadingManager();
let path =
json.url === undefined ?
undefined :
THREE.LoaderUtils.extractUrlBase(json.url);
manager.setURLModifier((url) => {
if (json.resources[url] !== undefined) {
return json.resources[url];
}
return url;
});
if (json.format === "obj") {
let loader = new OBJLoader(manager);
if (json.mtl_library) {
let mtl_loader = new MTLLoader(manager);
let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", "");
console.log(mtl_parse_result);
// let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result);
// console.log(materials);
// loader.addMaterials(materials);
// this.onTextureLoad();
}
let obj = loader.parse(json.data + "\n", path);
geometry = merge_geometries(obj, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format === "dae") {
let loader = new ColladaLoader(manager);
loader.onTextureLoad = this.onTextureLoad;
let obj = loader.parse(json.data, path);
geometry = merge_geometries(obj.scene, true);
geometry.uuid = json.uuid;
material = geometry.material;
} else if (json.format === "stl") {
let loader = new STLLoader();
geometry = loader.parse(json.data.buffer, path);
geometry.uuid = json.uuid;
material = geometry.material;
} else {
console.error("Unsupported mesh type:", json);
return null;
}
let object = new THREE.Mesh(geometry, material);
// Copied from ObjectLoader
object.uuid = json.uuid;
if (json.name !== undefined) object.name = json.name;
if (json.matrix !== undefined) {
object.matrix.fromArray(json.matrix);
if (json.matrixAutoUpdate !== undefined)
object.matrixAutoUpdate = json.matrixAutoUpdate;
if (object.matrixAutoUpdate)
object.matrix.decompose(
object.position,
object.quaternion,
object.scale
);
} else {
if (json.position !== undefined)
object.position.fromArray(json.position);
if (json.rotation !== undefined)
object.rotation.fromArray(json.rotation);
if (json.quaternion !== undefined)
object.quaternion.fromArray(json.quaternion);
if (json.scale !== undefined) object.scale.fromArray(json.scale);
}
if (json.castShadow !== undefined) object.castShadow = json.castShadow;
if (json.receiveShadow !== undefined)
object.receiveShadow = json.receiveShadow;
if (json.shadow) {
if (json.shadow.bias !== undefined)
object.shadow.bias = json.shadow.bias;
if (json.shadow.radius !== undefined)
object.shadow.radius = json.shadow.radius;
if (json.shadow.mapSize !== undefined)
object.shadow.mapSize.fromArray(json.shadow.mapSize);
if (json.shadow.camera !== undefined)
object.shadow.camera = this.parseObject(json.shadow.camera);
}
if (json.visible !== undefined) object.visible = json.visible;
if (json.frustumCulled !== undefined)
object.frustumCulled = json.frustumCulled;
if (json.renderOrder !== undefined) object.renderOrder = json.renderOrder;
if (json.userjson !== undefined) object.userjson = json.userData;
if (json.layers !== undefined) object.layers.mask = json.layers;
return object;
} else if (json.type === "CameraHelper") {
console.log("processing CameraHelper");
console.log(json);
console.log(geometries);
console.log(materials);
return super.parseObject(json, geometries, materials);
} else {
return super.parseObject(json, geometries, materials);
}
}
}
+157
View File
@@ -0,0 +1,157 @@
import * as THREE from 'three';
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);
}
}
function dispose(object) {
if (!object) {
return;
}
if (object.geometry) {
object.geometry.dispose();
}
if (object.material) {
if (Array.isArray(object.material)) {
for (let material of object.material) {
if (material.map) {
material.map.dispose();
}
material.dispose();
}
} else {
if (object.material.map) {
object.material.map.dispose();
}
object.material.dispose();
}
}
}
export class SceneNode {
constructor(object, folder, on_update) {
this.object = object;
this.folder = folder;
this.children = {};
this.on_update = on_update;
this.create_controls();
for (let c of this.object.children) {
this.add_child(c);
}
}
add_child(object) {
let f = this.folder.addFolder(object.name);
let node = new SceneNode(object, f, this.on_update);
this.children[object.name] = 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() {
if (this.vis_controller !== undefined) {
this.folder.domElement.removeChild(this.vis_controller.domElement);
}
this.vis_controller = new dat.controllers.BooleanController(this.object, "visible");
this.vis_controller.onChange(() => this.on_update());
this.folder.domElement.prepend(this.vis_controller.domElement);
this.vis_controller.domElement.style.height = "0";
this.vis_controller.domElement.style.float = "right";
// // add on hover controls and clickable functionality
// // hover
// this.folder.domElement.addEventListener("mouseenter", function (event) {
// event.target.style.color = "purple";
// }, false);
// this.folder.domElement.addEventListener("mouseleave", function (event) {
// event.target.style.color = "";
// }, false);
// // click
// this.folder.domElement.addEventListener("dblclick", () => this.printValue(), false);
}
printValue() {
console.log("calling print value");
console.log(this.object);
console.log(this);
}
set_property(property, value) {
if (property === "position") {
this.object.position.set(value[0], value[1], value[2]);
} else if (property === "quaternion") {
this.object.quaternion.set(value[0], value[1], value[2], value[3]);
} else if (property === "scale") {
this.object.scale.set(value[0], value[1], value[2]);
} else {
this.object[property] = value;
}
this.vis_controller.updateDisplay();
}
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];
}
}
}
}
+542
View File
@@ -0,0 +1,542 @@
import React, { Component } from "react";
import "./App.css";
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 a websocket endpoint. For example, a correct URL may look like the following: http://localhost:3000/visiongpu10.csail.mit.edu:8051";
window.alert(message);
return null;
}
return endpoint;
}
function removeAllChildNodes(parent) {
// https://www.javascripttutorial.net/dom/manipulating/remove-all-child-nodes/
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
function findCameraObjectUnderObject3D(object) {
// seach the tree for the camera
if (object instanceof THREE.Camera) {
return object;
} else if (object instanceof THREE.CameraHelper) {
return object.camera;
}
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,
needs_render: true,
viewport_width: null,
viewport_height: null,
images: [],
image_index: 0,
};
this.animate = this.animate.bind(this);
this.set_object = this.set_object.bind(this);
this.handle_command = this.handle_command.bind(this);
// window.addEventListener('resize', this.handleResize.bind(this));
}
set_dirty() {
this.setState({ needs_render: true });
}
handleResize() {
this.state.viewport_width = this.getViewportWidth();
this.state.viewport_height = this.getViewportHeight();
this.state.camera_l.aspect =
this.state.viewport_width / this.state.viewport_height;
this.state.camera_l.updateProjectionMatrix();
this.state.camera_r.updateProjectionMatrix();
this.state.camera_orth.updateProjectionMatrix();
this.state.renderer_l.setSize(
this.state.viewport_width,
(this.state.viewport_height * 2) / 3
);
this.state.renderer_r.setSize(
this.state.viewport_width / 2,
(this.state.viewport_height * 1) / 3
);
this.state.renderer_orth.setSize(
this.state.viewport_width / 2,
(this.state.viewport_height * 1) / 3
);
}
animate() {
requestAnimationFrame(this.animate);
if (this.state.needs_render) {
this.handleResize();
let camera_l = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera L"]).object
);
let camera_r = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera R"]).object
);
let camera_orth = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera Orth"]).object
);
camera_l.updateProjectionMatrix();
camera_r.updateProjectionMatrix();
camera_orth.updateProjectionMatrix();
if (this.state.controls_l != null) {
this.state.controls_l.update();
}
if (this.state.controls_r != null) {
this.state.controls_r.update();
}
if (this.state.controls_orth != null) {
this.state.controls_orth.update();
}
this.state.renderer_l.render(this.state.scene, camera_l);
this.state.renderer_r.render(this.state.scene, camera_r);
// NOTE(ethan): trying to add background image
// console.log("ethan is here");
if (this.state.websocket_is_opened) {
this.state.websocket.send("TODO: put camera pose here");
}
this.state.renderer_orth.render(
this.backgroundScene,
this.backgroundCamera
);
// this.state.renderer_orth.render(this.state.scene, camera_orth);
this.state.needs_render = false;
this.set_dirty(); // TODO(ethan): remove this but make sure to include it everywhere
}
}
save_image(image) {
let url = "https://friends.ethanweber.me/save_image";
let data = {
index: this.state.image_index,
image: image,
};
fetch(url, {
method: "POST", // The method
mode: "no-cors", // It can be no-cors, cors, same-origin
headers: {
"Content-Type": "application/json", // Your headers
},
body: JSON.stringify(data),
}).then((returned) => {
console.log(returned);
});
this.state.image_index += 1;
}
set_object(path, object) {
this.state.scene_tree.find(path.concat(["<object>"])).set_object(object);
}
set_object_from_json(path, object_json) {
let loader = new ExtensibleObjectLoader();
loader.onTextureLoad = () => {
this.set_dirty();
};
loader.parse(object_json, (obj) => {
// console.log("ethan.");
// console.log(obj.type);
if (
obj.geometry !== undefined &&
obj.geometry.type === "BufferGeometry"
) {
if (
obj.geometry.attributes.normal === undefined ||
obj.geometry.attributes.normal.count === 0
) {
obj.geometry.computeVertexNormals();
}
} else if (obj.type.includes("Camera")) {
console.log("uses camera !!");
// this.set_camera(obj);
// this.set_3d_pane_size();
}
obj.castShadow = true;
obj.receiveShadow = true;
this.set_object(path, obj);
this.set_dirty();
});
}
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) {
console.log(cmd);
// convert binary serialization format back to JSON
cmd = msgpack.decode(new Uint8Array(cmd));
console.log(cmd);
// TODO(ethan): ignore these or remove status. maybe incorporate into a clean view
if (cmd.type === "status") {
return;
}
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);
} else if (cmd.type === "set_animation") {
// TODO(ethan): implement animations
console.error("Animations not implemented yet.");
} else if (cmd.type === "set_image") {
console.log("ethan: setting camera");
// var url = URL.createObjectURL(
// new Blob([cmd["image"].buffer], { type: "image/png" } /* (1) */)
// );
// console.log(url);
// document.getElementById("my-img").src = url;
var height = 300;
var width = 200;
// console.log(cmd["image"]);
var texture = new THREE.DataTexture(
cmd["image"],
width,
height,
THREE.RGBFormat
);
// var texture = new THREE.TextureLoader().load("texture2.jpeg");
// var texture = new THREE.TextureLoader().load(url);
// console.log(texture);
// console.log(this.backgroundMesh);
this.backgroundMesh.material.map = texture;
this.backgroundMesh.material.map.needsUpdate = true;
this.backgroundMesh.material.needsUpdate = true;
}
this.set_dirty();
if (cmd.type === "set_transform" && cmd.path === "/Cameras/Main Camera R") {
let camera_r = findCameraObjectUnderObject3D(
this.state.scene_tree.find(["Cameras", "Main Camera R"]).object
);
camera_r.updateProjectionMatrix();
this.state.renderer_save.render(this.state.scene, camera_r);
let imgData = this.state.renderer_save.domElement.toDataURL();
this.state.images.push(imgData.toString());
// this.save_image(imgData);
}
}
save_scene() {}
load_scene() {}
// save_image() {}
add_camera_helper(path, camera) {
let camera_copy = camera.clone();
camera_copy.far = 1; // so it doesn't show so far away
this.set_object(path, new THREE.CameraHelper(camera_copy));
}
getViewportWidth() {
return window.innerWidth - (window.innerWidth % 2);
}
getViewportHeight() {
return window.innerHeight;
}
componentDidMount() {
// Open the websocket
let endpoint = websocket_endpoint_from_url(window.location.href);
this.state.websocket_is_opened = false;
this.state.websocket = new WebSocket("ws://" + endpoint + "/");
this.state.websocket.onopen = () => {
console.log("connected");
this.state.websocket_is_opened = true;
};
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(); // notice that this is half width
this.state.viewport_height = this.getViewportHeight();
// Scene
this.state.scene = new THREE.Scene();
this.state.scene.background = new THREE.Color(0xffffff);
// 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, () =>
this.set_dirty()
);
// let save_folder = this.state.gui.addFolder("Save / Load / Capture");
// save_folder.add(this, 'save_scene');
// save_folder.add(this, 'load_scene');
// save_folder.add(this, 'save_image');
// this.state.gui.open();
// console.log(this.mount);
// Renderer Left
this.state.renderer_l = new THREE.WebGLRenderer({ antialias: true });
this.state.renderer_l.setPixelRatio(window.devicePixelRatio);
this.state.renderer_l.setSize(
this.state.viewport_width,
(this.state.viewport_height * 2) / 3
);
this.state.renderer_l.domElement.style.border = "1px solid black";
this.mount.appendChild(this.state.renderer_l.domElement);
// Renderer Right
let div = document.createElement("div");
this.state.renderer_r = new THREE.WebGLRenderer({ antialias: true });
this.state.renderer_r.setPixelRatio(window.devicePixelRatio);
this.state.renderer_r.setSize(
this.state.viewport_width / 2,
(this.state.viewport_height * 1) / 3
);
this.state.renderer_r.domElement.style.border = "1px solid black";
this.state.renderer_r.domElement.style = "inline-block";
div.appendChild(this.state.renderer_r.domElement);
this.state.renderer_orth = new THREE.WebGLRenderer({ antialias: true });
this.state.renderer_orth.setPixelRatio(window.devicePixelRatio);
this.state.renderer_orth.setSize(
this.state.viewport_width / 2,
(this.state.viewport_height * 1) / 3
);
this.state.renderer_orth.domElement.style.border = "1px solid black";
this.state.renderer_orth.domElement.style = "inline-block";
div.appendChild(this.state.renderer_orth.domElement);
// div.display.style = "relative";
// NOTE(ethan): not sure if this is needed anymore?
this.state.renderer_save = new THREE.WebGLRenderer({
antialias: true,
preserveDrawingBuffer: true,
});
this.state.renderer_save.setPixelRatio(1.0);
this.state.renderer_save.setSize(960, 540);
this.state.renderer_save.domElement.style.border = "1px solid black";
this.state.renderer_save.domElement.style.display = "none";
// div.appendChild(this.state.renderer_save.domElement);
this.mount.appendChild(div);
// console.log(this.mount);
this.mount.style.display = "block";
// Camera settings at https://stackoverflow.com/questions/46182845/field-of-view-aspect-ratio-view-matrix-from-projection-matrix-hmd-ost-calib/46195462
// Camera left
this.state.camera_l = new THREE.PerspectiveCamera(
120,
this.state.viewport_width / this.state.viewport_height,
0.01,
100
);
this.state.camera_l.position.x = 5;
this.state.camera_l.position.y = -5;
this.state.camera_l.position.z = -5;
this.state.camera_l.up = new THREE.Vector3(0, -1, 0);
// Controls left
this.state.controls_l = new TrackballControls(
this.state.camera_l,
this.state.renderer_l.domElement
);
this.state.controls_l.rotateSpeed = 2.0;
this.state.controls_l.zoomSpeed = 0.3;
this.state.controls_l.panSpeed = 0.2;
this.state.controls_l.staticMoving = false; // false is default
this.state.controls_l.target.set(0, 0, 0); // focus point of the controls
this.state.controls_l.autoRotate = false;
this.state.controls_l.update();
// Camera right
this.state.camera_r = new THREE.PerspectiveCamera(
120,
this.state.viewport_width / (this.state.viewport_height / 2),
0.01,
100
);
this.state.camera_orth = new THREE.OrthographicCamera(
-2,
2,
-2,
2,
0.01,
100
);
// this.state.camera_r.position.x = 0;
// this.state.camera_r.position.y = 0;
// this.state.camera_r.position.z = 0;
// this.state.camera_r.up = new THREE.Vector3(0, -1, 0);
var texture = new THREE.TextureLoader().load("texture.jpeg");
this.backgroundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2),
new THREE.MeshBasicMaterial({
map: texture,
})
// material
);
// const geometry = new THREE.PlaneGeometry(1, 1);
// const material = new THREE.MeshBasicMaterial({
// color: 0xffff00,
// side: THREE.DoubleSide,
// });
// const plane = new THREE.Mesh(geometry, material);
this.backgroundMesh.material.depthTest = false;
this.backgroundMesh.material.depthWrite = false;
// Create your background scene
this.backgroundScene = new THREE.Scene();
this.backgroundCamera = new THREE.Camera();
this.backgroundScene.add(this.backgroundCamera);
this.backgroundScene.add(this.backgroundMesh);
this.set_object(["Cameras", "Main Camera L"], this.state.camera_l);
this.set_object(["Cameras", "Main Camera R"], this.state.camera_r);
this.set_object(["Cameras", "Main Camera Orth"], this.state.camera_orth);
// rotate the cameras to match the COLMAP format
let rotY = new THREE.Matrix4();
rotY.makeRotationY(Math.PI);
let rotZ = new THREE.Matrix4();
rotZ.makeRotationZ(Math.PI);
let rot = rotY.multiply(rotZ);
this.set_transform(["Cameras", "Main Camera R", "<object>"], rot.toArray());
// this.state.scene_tree.find(["Cameras", "Main Camera L"]).set_property("position", [5, -5, -5]);
this.state.scene_tree
.find(["Cameras", "Main Camera R"])
.set_property("position", [-2, -2, -2]);
// Controls right
// this.state.controls_r = new TrackballControls(this.state.scene_tree.find(["Cameras", "Main Camera R"]).object, this.state.renderer_r.domElement);
// this.state.controls_r.rotateSpeed = 2.0;
// this.state.controls_r.zoomSpeed = 0.3;
// this.state.controls_r.panSpeed = 0.2;
// this.state.controls_r.staticMoving = false; // false is default
// this.state.controls_r.target.set(0, 0, 0); // focus point of the controls
// this.state.controls_r.autoRotate = false;
// this.state.controls_r.update();
this.set_transform(
["Cameras", "Main Camera Orth", "<object>"],
rot.toArray()
);
this.state.scene_tree
.find(["Cameras", "Main Camera Orth"])
.set_property("position", [-1, -1, -1]);
let camera_axes_l = new THREE.AxesHelper(1);
let camera_axes_r = new THREE.AxesHelper(1);
let camera_axes_orth = new THREE.AxesHelper(1);
this.set_object(["Cameras", "Main Camera L", "Axes"], camera_axes_l);
this.set_object(["Cameras", "Main Camera R", "Axes"], camera_axes_r);
this.set_object(["Cameras", "Main Camera Orth", "Axes"], camera_axes_orth);
// Axes display
let axes = new THREE.AxesHelper(5);
this.set_object(["Axes"], axes);
// var arrowPos = new THREE.Vector3(0, 0, 0);
// var arrow = new THREE.ArrowHelper(new THREE.Vector3(1, 0, 0), arrowPos, 60, 0xFF0000, 20, 10)
// this.set_object(["arrow"], arrow);
// 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();
this.mount.appendChild(stats.dom);
// let camera = new THREE.PerspectiveCamera(75, this.state.width / this.state.height, 0.1, 1000);
// let helper = new THREE.CameraHelper(camera);
// // scene.add( helper );
// // console.log(helper);
// console.log(helper);
// // this.set_object(["Helper"], helper);
// // console.log(this.state.scene);
// Cube
// var geometry = new THREE.BoxGeometry(1, 1, 1);
// var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
// var cube = new THREE.Mesh(geometry, material);
// this.state.scene.add(cube);
this.animate();
}
componentWillUnmount() {
// this.mount.removeChild(this.state.renderer_l.domElement);
// this.mount.removeChild(this.state.renderer_r.domElement);
removeAllChildNodes(this.mount);
}
render() {
return <div ref={(ref) => (this.mount = ref)} />;
}
}
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from "react-dom/client";
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+141
View File
@@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.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
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
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.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
+3
View File
@@ -0,0 +1,3 @@
export function split_path(path_str) {
return path_str.split("/").filter(x => x.length > 0);
}
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
# 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 . import animation
from .visualizer import ViewerWindow, Visualizer
def viewer_assets_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "viewer"))
+184
View File
@@ -0,0 +1,184 @@
# 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.
from __future__ import absolute_import, division, print_function
import tempfile
import tarfile
import sys
import os.path
import subprocess
if sys.version_info >= (3, 0):
unicode = str
import bisect
from . import transformations as tf
class AnimationTrack(object):
__slots__ = ["name", "jstype", "frames", "values"]
def __init__(self, name, jstype, frames=None, values=None):
self.name = name
self.jstype = jstype
if frames is None:
self.frames = []
else:
self.frames = frames
if values is None:
self.values = []
else:
self.values = values
def set_property(self, frame, value):
i = bisect.bisect(self.frames, frame)
self.frames.insert(i, frame)
self.values.insert(i, value)
def lower(self):
return {
"name": unicode("." + self.name),
"type": unicode(self.jstype),
"keys": [{"time": self.frames[i], "value": self.values[i]} for i in range(len(self.frames))],
}
class AnimationClip(object):
__slots__ = ["tracks", "fps", "name"]
def __init__(self, tracks=None, fps=30, name="default"):
if tracks is None:
self.tracks = {}
else:
self.tracks = tracks
self.fps = fps
self.name = name
def set_property(self, frame, property, jstype, value):
if property not in self.tracks:
self.tracks[property] = AnimationTrack(property, jstype)
track = self.tracks[property]
track.set_property(frame, value)
def lower(self):
return {"fps": self.fps, "name": unicode(self.name), "tracks": [t.lower() for t in self.tracks.values()]}
class Animation(object):
__slots__ = ["clips", "default_framerate"]
def __init__(self, clips=None, default_framerate=30):
if clips is None:
self.clips = {}
else:
self.clips = clips
self.default_framerate = default_framerate
def lower(self):
return [{"path": path.lower(), "clip": clip.lower()} for (path, clip) in self.clips.items()]
def at_frame(self, visualizer, frame):
return AnimationFrameVisualizer(self, visualizer.path, frame)
def js_position(matrix):
return list(matrix[:3, 3])
def js_quaternion(matrix):
quat = tf.quaternion_from_matrix(matrix)
return [quat[1], quat[2], quat[3], quat[0]]
class AnimationFrameVisualizer(object):
__slots__ = ["animation", "path", "current_frame"]
def __init__(self, animation, path, current_frame):
self.animation = animation
self.path = path
self.current_frame = current_frame
def get_clip(self):
if self.path not in self.animation.clips:
self.animation.clips[self.path] = AnimationClip(fps=self.animation.default_framerate)
return self.animation.clips[self.path]
def set_transform(self, matrix):
assert matrix.shape == (4, 4)
clip = self.get_clip()
clip.set_property(self.current_frame, "position", "vector3", js_position(matrix))
clip.set_property(self.current_frame, "quaternion", "quaternion", js_quaternion(matrix))
def set_property(self, prop, jstype, value):
clip = self.get_clip()
clip.set_property(self.current_frame, prop, jstype, value)
def __getitem__(self, path):
return AnimationFrameVisualizer(self.animation, self.path.append(path), self.current_frame)
def __enter__(self):
return self
def __exit__(self, *arg):
pass
def convert_frames_to_video(tar_file_path, output_path="output.mp4", framerate=60, overwrite=False):
"""
Try to convert a tar file containing a sequence of frames saved by the
pyrad viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
"""
output_path = os.path.abspath(output_path)
if os.path.isfile(output_path) and not overwrite:
raise ValueError(
"The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.".format(
output_path
)
)
with tempfile.TemporaryDirectory() as tmp_dir:
with tarfile.open(tar_file_path) as tar:
tar.extractall(tmp_dir)
args = [
"ffmpeg",
"-r",
str(framerate),
"-i",
r"%07d.png",
"-vcodec",
"libx264",
"-preset",
"slow",
"-crf",
"18",
]
if overwrite:
args.append("-y")
args.append(output_path)
try:
subprocess.check_call(args, cwd=tmp_dir)
except subprocess.CalledProcessError as e:
print(
"""
Could not call `ffmpeg` to convert your frames into a video.
If you want to convert the frames manually, you can extract the
.tar archive into a directory, cd to that directory, and run:
ffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4
"""
)
raise
print("Saved output as {:s}".format(output_path))
return output_path
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python
import os
import sys
import subprocess
import time
def file_filter(name):
return (not name.startswith(".")) and (not name.endswith(".swp"))
def file_times(path):
for top_level in filter(file_filter, os.listdir(path)):
for root, dirs, files in os.walk(top_level):
for file in filter(file_filter, files):
yield os.stat(os.path.join(root, file)).st_mtime
def print_stdout(process):
stdout = process.stdout
if stdout != None:
print(stdout)
# We concatenate all of the arguments together, and treat that as the command to run
command = " ".join(sys.argv[1:])
# The path to watch
path = "."
# How often we check the filesystem for changes (in seconds)
wait = 1
# The process to autoreload
process = subprocess.Popen(command, shell=True)
# The current maximum file modified time under the watched directory
last_mtime = max(file_times(path))
while True:
max_mtime = max(file_times(path))
print_stdout(process)
if max_mtime > last_mtime:
last_mtime = max_mtime
process.kill()
print("Restarting process.")
process = subprocess.Popen(command, shell=True)
time.sleep(wait)
+167
View File
@@ -0,0 +1,167 @@
# 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.
from .geometry import SceneElement, Geometry, Object, LineSegments, PointsGeometry, LineBasicMaterial
# import geometry as g
from . import geometry as g
import numpy as np
import cv2
"""
TODO(ethan): add some notes about the coordinate conventions of the cameras
"""
class Camera(SceneElement):
def __init__(self):
super().__init__()
class OrthographicCamera(Camera):
def __init__(self, left, right, top, bottom, near, far, zoom=1):
super().__init__()
self.left = left
self.right = right
self.top = top
self.bottom = bottom
self.near = near
self.far = far
self.zoom = zoom
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "OrthographicCamera",
"left": self.left,
"right": self.right,
"top": self.top,
"bottom": self.bottom,
"near": self.near,
"far": self.far,
"zoom": self.zoom,
}
}
return data
class PerspectiveCamera(Camera):
def __init__(self, aspect, fov, near, far, zoom=1):
super().__init__()
self.aspect = aspect
self.fov = fov
self.near = near
self.far = far
@staticmethod
def from_intrinsics(focal_length, aspect_ratio):
"""TODO(ethan): finish this"""
# convert the intrinsics matrix into three.js compatible format
return PerspectiveCamera(aspect, fov, near, far)
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"fov": self.fov,
"near": self.near,
"far": self.far,
}
}
return data
class CameraHelper(Camera):
"""NOTE(ethan): Camera parent class might not make sense here?"""
def __init__(self, camera):
super().__init__()
self.camera = camera
def lower(self):
data = {"object": {"uuid": self.uuid, "type": "CameraHelper", "camera": self.camera.lower()}}
return data
class ImagePlane(g.Mesh):
def __init__(self, image, height=1, width=1):
"""TODO(ethan): decide how to deal with the height and width"""
self.image = image
geometry = g.PlaneGeometry([width, height])
material = g.MeshBasicMaterial(
map=g.ImageTexture(image=g.PngImage(cv2.imencode(".png", self.image[:, :, ::-1])[1].tobytes()))
)
super().__init__(geometry, material)
def get_camera_wireframe(scale: float = 0.3, f=4, w=1.5, h=2):
"""
Returns a wireframe of a 3D line-plot of a camera symbol.
At https://github.com/hangg7/mvs_visual/blob/275d382a824733a3187a8e3147be184dd6f14795/mvs_visual.py#L54.
Args:
f (focal length): this is the focal length
"""
ul = np.array([-w, h, -f])
ur = np.array([w, h, -f])
ll = np.array([-w, -h, -f])
lr = np.array([w, -h, -f])
C = np.zeros(3)
camera_points = [C, ul, C, ur, C, ll, C, lr, C]
lines = np.stack([x for x in camera_points]) * scale
return lines
def get_plane_pts(focal_length=(1.0, 1.0), image_size=(10, 10), camera_scale=1, scale_factor=1 / 4):
Z = -(focal_length[0] + focal_length[1]) / 2 * camera_scale
X0, Y0, X1, Y1 = (
-image_size[0] / 2 * camera_scale,
image_size[1] / 2 * camera_scale,
image_size[0] / 2 * camera_scale,
-image_size[1] / 2 * camera_scale,
)
# scale image to plane such that it can go outside of the x0x1 range.
W, H = X1 - X0, Y0 - Y1
w, h = image_size
ratio = min(w / W, h / H)
oW, oH = w / ratio, h / ratio
X0, Y0, X1, Y1 = -oW / 2, oH / 2, oW / 2, -oH / 2
wsteps, hsteps = int(w * scale_factor), int(h * scale_factor)
Ys, Xs = np.meshgrid(
np.linspace(Y0, Y1, num=hsteps),
np.linspace(X0, X1, num=wsteps),
indexing="ij",
)
Zs = np.ones_like(Xs) * Z
plane_pts = np.stack([Xs, Ys, Zs], axis=-1)
return plane_pts
def frustum(scale=1.0, color=[0, 0, 0], focal_length=4, width=1.5, height=2):
"""TODO(ethan): make the scale adjustable depending on the camera size
color - color of lines using R, G, B. default is black
"""
# print("linewidth")
camera_wireframe_lines = get_camera_wireframe(scale=scale, f=focal_length, w=width / 2.0, h=height / 2.0)
N = len(camera_wireframe_lines)
colors = np.array([color for _ in range(N)])
line_segments = LineSegments(
PointsGeometry(position=camera_wireframe_lines.astype(np.float32).T, color=colors.astype(np.float32).T),
LineBasicMaterial(vertexColors=True, linewidth=10.0),
)
return line_segments
+120
View File
@@ -0,0 +1,120 @@
# 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.
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info >= (3, 0):
unicode = str
from .geometry import (
Geometry,
Object,
Mesh,
MeshPhongMaterial,
OrthographicCamera,
PerspectiveCamera,
PointsMaterial,
Points,
)
from .cameras import Camera, CameraHelper
from .path import Path
class SetObject:
__slots__ = ["object", "path"]
def __init__(self, geometry_or_object, material=None, path=None):
if isinstance(geometry_or_object, Object):
if material is not None:
raise (ValueError("Please supply either an Object OR a Geometry and a Material"))
self.object = geometry_or_object
elif isinstance(geometry_or_object, (OrthographicCamera, PerspectiveCamera)):
self.object = geometry_or_object
else:
if material is None:
material = MeshPhongMaterial()
if isinstance(material, PointsMaterial):
self.object = Points(geometry_or_object, material)
else:
self.object = Mesh(geometry_or_object, material)
if path is not None:
self.path = path
else:
self.path = Path()
def lower(self):
return {"type": "set_object", "object": self.object.lower(), "path": self.path.lower()}
class SetTransform:
__slots__ = ["matrix", "path"]
def __init__(self, matrix, path):
self.matrix = matrix
self.path = path
def lower(self):
return {"type": "set_transform", "path": self.path.lower(), "matrix": list(self.matrix.T.flatten())}
class Delete:
__slots__ = ["path"]
def __init__(self, path):
self.path = path
def lower(self):
return {"type": "delete", "path": self.path.lower()}
class SetProperty:
__slots__ = ["path", "key", "value"]
def __init__(self, key, value, path):
self.key = key
self.value = value
self.path = path
def lower(self):
return {"type": "set_property", "path": self.path.lower(), "property": self.key.lower(), "value": self.value}
class SetAnimation:
__slots__ = ["animation", "play", "repetitions"]
def __init__(self, animation, play=True, repetitions=1):
self.animation = animation
self.play = play
self.repetitions = repetitions
def lower(self):
return {
"type": "set_animation",
"animations": self.animation.lower(),
"options": {"play": self.play, "repetitions": self.repetitions},
"path": "",
}
class SetImage:
__slots__ = ["image", "path"]
def __init__(self, image, path):
self.image = image
self.path = path
def lower(self):
return {"type": "set_image", "image": self.image, "path": self.path.lower()}
+658
View File
@@ -0,0 +1,658 @@
# 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.
from __future__ import absolute_import, division, print_function
import sys
import base64
import uuid
if sys.version_info >= (3, 0):
unicode = str
from io import StringIO, BytesIO
else:
from StringIO import StringIO
BytesIO = StringIO
import umsgpack
import numpy as np
from . import transformations as tf
class SceneElement(object):
def __init__(self):
self.uuid = unicode(uuid.uuid1())
def intrinsic_transform(self):
return tf.identity_matrix()
class ReferenceSceneElement(SceneElement):
def lower_in_object(self, object_data):
object_data.setdefault(self.field, []).append(self.lower(object_data))
return self.uuid
class Geometry(ReferenceSceneElement):
field = "geometries"
class Material(ReferenceSceneElement):
field = "materials"
class Texture(ReferenceSceneElement):
field = "textures"
class Image(ReferenceSceneElement):
field = "images"
class Box(Geometry):
def __init__(self, lengths):
super().__init__()
self.lengths = lengths
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "BoxGeometry",
"width": self.lengths[0],
"height": self.lengths[1],
"depth": self.lengths[2],
}
class Sphere(Geometry):
def __init__(self, radius):
super().__init__()
self.radius = radius
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "SphereGeometry",
"radius": self.radius,
"widthSegments": 20,
"heightSegments": 20,
}
class Ellipsoid(Sphere):
"""
An Ellipsoid is treated as a Sphere of unit radius, with an affine
transformation applied to distort it into the ellipsoidal shape
"""
def __init__(self, radii):
super().__init__(1.0)
self.radii = radii
def intrinsic_transform(self):
return np.diag(np.hstack((self.radii, 1.0)))
class PlaneGeometry(Geometry):
def __init__(self, lengths):
super().__init__()
self.lengths = lengths
def lower(self, object_data):
return {"uuid": self.uuid, "type": "PlaneGeometry", "width": self.lengths[0], "height": self.lengths[1]}
"""
A cylinder of the given height and radius. By Three.js convention, the axis of
rotational symmetry is aligned with the y-axis.
"""
class Cylinder(Geometry):
def __init__(self, height, radius=1.0, radiusTop=None, radiusBottom=None):
super().__init__()
if radiusTop is not None and radiusBottom is not None:
self.radiusTop = radiusTop
self.radiusBottom = radiusBottom
else:
self.radiusTop = radius
self.radiusBottom = radius
self.height = height
self.radialSegments = 50
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "CylinderGeometry",
"radiusTop": self.radiusTop,
"radiusBottom": self.radiusBottom,
"height": self.height,
"radialSegments": self.radialSegments,
}
class GenericMaterial(Material):
def __init__(
self,
color=0xFFFFFF,
reflectivity=0.5,
map=None,
side=2,
transparent=None,
opacity=1.0,
linewidth=1.0,
wireframe=False,
wireframeLinewidth=1.0,
vertexColors=False,
**kwargs
):
super().__init__()
self.color = color
self.reflectivity = reflectivity
self.map = map
self.side = side
self.transparent = transparent
self.opacity = opacity
self.linewidth = linewidth
self.wireframe = wireframe
self.wireframeLinewidth = wireframeLinewidth
self.vertexColors = vertexColors
self.properties = kwargs
def lower(self, object_data):
# Three.js allows a material to have an opacity which is != 1,
# but to still be non-transparent, in which case the opacity only
# serves to desaturate the material's color. That's a pretty odd
# combination of things to want, so by default we just use the
# opacity value to decide whether to set transparent to True or
# False.
if self.transparent is None:
transparent = bool(self.opacity != 1)
else:
transparent = self.transparent
data = {
"uuid": self.uuid,
"type": self._type,
"color": self.color,
"reflectivity": self.reflectivity,
"side": self.side,
"transparent": transparent,
"opacity": self.opacity,
"linewidth": self.linewidth,
"wireframe": bool(self.wireframe),
"wireframeLinewidth": self.wireframeLinewidth,
"vertexColors": (2 if self.vertexColors else 0), # three.js wants an enum
}
data.update(self.properties)
if self.map is not None:
data["map"] = self.map.lower_in_object(object_data)
return data
class MeshBasicMaterial(GenericMaterial):
_type = "MeshBasicMaterial"
class MeshPhongMaterial(GenericMaterial):
_type = "MeshPhongMaterial"
class MeshLambertMaterial(GenericMaterial):
_type = "MeshLambertMaterial"
class MeshToonMaterial(GenericMaterial):
_type = "MeshToonMaterial"
class LineBasicMaterial(GenericMaterial):
_type = "LineBasicMaterial"
class PngImage(Image):
def __init__(self, data):
super().__init__()
self.data = data
@staticmethod
def from_file(fname):
with open(fname, "rb") as f:
return PngImage(f.read())
def lower(self, object_data):
return {
"uuid": self.uuid,
"url": unicode("data:image/png;base64," + base64.b64encode(self.data).decode("ascii")),
}
class GenericTexture(Texture):
def __init__(self, properties):
super().__init__()
self.properties = properties
def lower(self, object_data):
data = {"uuid": self.uuid}
data.update(self.properties)
if "image" in data:
image = data["image"]
data["image"] = image.lower_in_object(object_data)
return data
class ImageTexture(Texture):
def __init__(self, image, wrap=[1001, 1001], repeat=[1, 1], **kwargs):
super().__init__()
self.image = image
self.wrap = wrap
self.repeat = repeat
self.properties = kwargs
def lower(self, object_data):
data = {
"uuid": self.uuid,
"wrap": self.wrap,
"repeat": self.repeat,
"image": self.image.lower_in_object(object_data),
}
data.update(self.properties)
return data
class Object(SceneElement):
def __init__(self, geometry, material=MeshPhongMaterial()):
super().__init__()
self.geometry = geometry
self.material = material
def lower(self):
data = {
"metadata": {
"version": 4.5,
"type": "Object",
},
"geometries": [],
"materials": [],
"object": {
"uuid": self.uuid,
"type": self._type,
"geometry": self.geometry.uuid,
"material": self.material.uuid,
"matrix": list(self.geometry.intrinsic_transform().flatten()),
},
}
self.geometry.lower_in_object(data)
self.material.lower_in_object(data)
return data
class Mesh(Object):
_type = "Mesh"
class OrthographicCamera(SceneElement):
def __init__(self, left, right, top, bottom, near, far, zoom=1):
super(OrthographicCamera, self).__init__()
self.left = left
self.right = right
self.top = top
self.bottom = bottom
self.near = near
self.far = far
self.zoom = zoom
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "OrthographicCamera",
"left": self.left,
"right": self.right,
"top": self.top,
"bottom": self.bottom,
"near": self.near,
"far": self.far,
"zoom": self.zoom,
}
}
return data
class PerspectiveCamera(SceneElement):
"""
The PerspectiveCamera is the default camera used by the pyrad viewer. See
https://threejs.org/docs/#api/en/cameras/PerspectiveCamera for more
information.
"""
def __init__(self, fov=50, aspect=1, near=0.1, far=2000, zoom=1, filmGauge=35, filmOffset=0, focus=10):
"""
fov : Camera frustum vertical field of view, from bottom to top of view, in degrees. Default is 50.
aspect: Camera frustum aspect ratio, usually the canvas width / canvas height. Default is 1 (square canvas).
near : Camera frustum near plane. Default is 0.1. The valid range is greater than 0 and less than the current
value of the far plane. Note that, unlike for the OrthographicCamera, 0 is not a valid value for a
PerspectiveCamera's near plane.
far : Camera frustum far plane. Default is 2000.
zoom : Gets or sets the zoom factor of the camera. Default is 1.
filmGauge: Film size used for the larger axis. Default is 35 (millimeters). This parameter does not influence
the projection matrix unless .filmOffset is set to a nonzero value.
filmOffset: Horizontal off-center offset in the same unit as .filmGauge. Default is 0.
focus: Object distance used for stereoscopy and depth-of-field effects. This parameter does not influence
the projection matrix unless a StereoCamera is being used. Default is 10.
"""
super(PerspectiveCamera, self).__init__()
self.fov = fov
self.aspect = aspect
self.far = far
self.near = near
self.zoom = zoom
self.filmGauge = filmGauge
self.filmOffset = filmOffset
self.focus = focus
def lower(self):
data = {
"object": {
"uuid": self.uuid,
"type": "PerspectiveCamera",
"aspect": self.aspect,
"far": self.far,
"filmGauge": self.filmGauge,
"filmOffset": self.filmOffset,
"focus": self.focus,
"fov": self.fov,
"near": self.near,
"zoom": self.zoom,
}
}
return data
def item_size(array):
if array.ndim == 1:
return 1
elif array.ndim == 2:
return array.shape[0]
else:
raise ValueError(
"I can only pack 1- or 2-dimensional numpy arrays, but this one has {:d} dimensions".format(array.ndim)
)
def threejs_type(dtype):
if dtype == np.uint8:
return "Uint8Array", 0x12
elif dtype == np.int32:
return "Int32Array", 0x15
elif dtype == np.uint32:
return "Uint32Array", 0x16
elif dtype == np.float32:
return "Float32Array", 0x17
else:
raise ValueError("Unsupported datatype: " + str(dtype))
def pack_numpy_array(x):
if x.dtype == np.float64:
x = x.astype(np.float32)
typename, extcode = threejs_type(x.dtype)
return {
"itemSize": item_size(x),
"type": typename,
"array": umsgpack.Ext(extcode, x.tobytes("F")),
"normalized": False,
}
def data_from_stream(stream):
if sys.version_info >= (3, 0):
if isinstance(stream, BytesIO):
data = stream.read().decode(encoding="utf-8")
elif isinstance(stream, StringIO):
data = stream.read()
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(stream)))
else:
data = stream.read()
return data
class MeshGeometry(Geometry):
def __init__(self, contents, mesh_format):
super().__init__()
self.contents = contents
self.mesh_format = mesh_format
def lower(self, object_data):
return {"type": "_meshfile", "uuid": self.uuid, "format": self.mesh_format, "data": self.contents}
class ObjMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "obj")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), "obj")
@staticmethod
def from_stream(f):
return MeshGeometry(data_from_stream(f), "obj")
class DaeMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "dae")
@staticmethod
def from_file(fname):
with open(fname, "r") as f:
return MeshGeometry(f.read(), "dae")
@staticmethod
def from_stream(f):
return MeshGeometry(data_from_stream(f), "dae")
class StlMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "stl")
@staticmethod
def from_file(fname):
with open(fname, "rb") as f:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
@staticmethod
def from_stream(f):
if sys.version_info >= (3, 0):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(f)))
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
class PlyMeshGeometry(MeshGeometry):
def __init__(self, contents):
super().__init__(contents, "ply")
@staticmethod
def from_file(fname):
with open(fname, "rb") as f:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "ply")
@staticmethod
def from_stream(f):
if sys.version_info >= (3, 0):
if isinstance(f, BytesIO):
arr = np.frombuffer(f.read(), dtype=np.uint8)
elif isinstance(f, StringIO):
arr = np.frombuffer(bytes(f.read(), "utf-8"), dtype=np.uint8)
else:
raise ValueError("Stream must be instance of StringIO or BytesIO, not {}".format(type(f)))
else:
arr = np.frombuffer(f.read(), dtype=np.uint8)
_, extcode = threejs_type(np.uint8)
encoded = umsgpack.Ext(extcode, arr.tobytes())
return MeshGeometry(encoded, "stl")
class TriangularMeshGeometry(Geometry):
"""
A mesh consisting of an arbitrary collection of triangular faces.
To construct one, you need to pass in a collection of vertices as an Nx3 array
and a collection of faces as an Mx3 array. Each element of `faces`
should be a collection of 3 indices into the `vertices` array.
For example, to create a square made out of two adjacent triangles, we could do:
vertices = np.array([
[0, 0, 0], # the first vertex is at [0, 0, 0]
[1, 0, 0],
[1, 0, 1],
[0, 0, 1]
])
faces = np.array([
[0, 1, 2], # The first face consists of vertices 0, 1, and 2
[3, 0, 2]
])
mesh = TriangularMeshGeometry(vertices, faces)
"""
__slots__ = ["vertices", "faces"]
def __init__(self, vertices, faces):
super().__init__()
vertices = np.asarray(vertices, dtype=np.float32)
faces = np.asarray(faces, dtype=np.uint32)
assert vertices.shape[1] == 3, "`vertices` must be an Nx3 array"
assert faces.shape[1] == 3, "`faces` must be an Mx3 array"
self.vertices = vertices
self.faces = faces
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "BufferGeometry",
"data": {
"attributes": {"position": pack_numpy_array(self.vertices.T)},
"index": pack_numpy_array(self.faces.T),
},
}
class PointsGeometry(Geometry):
def __init__(self, position, color=None):
super().__init__()
self.position = position
self.color = color
def lower(self, object_data):
attrs = {"position": pack_numpy_array(self.position)}
if self.color is not None:
attrs["color"] = pack_numpy_array(self.color)
return {"uuid": self.uuid, "type": "BufferGeometry", "data": {"attributes": attrs}}
class PointsMaterial(Material):
def __init__(self, size=0.001, color=0xFFFFFF, sizeAttenuation=True):
super().__init__()
self.size = size
self.color = color
self.sizeAttenuation = sizeAttenuation
def lower(self, object_data):
return {
"uuid": self.uuid,
"type": "PointsMaterial",
"color": self.color,
"size": self.size,
"sizeAttenuation": bool(self.sizeAttenuation),
"vertexColors": 2,
}
class Points(Object):
_type = "Points"
def PointCloud(position, color, **kwargs):
return Points(PointsGeometry(position, color), PointsMaterial(**kwargs))
class Line(Object):
_type = "Line"
class LineSegments(Object):
_type = "LineSegments"
class LineLoop(Object):
_type = "LineLoop"
def triad(scale=1.0):
"""
A visual representation of the origin of a coordinate system, drawn as three
lines in red, green, and blue along the x, y, and z axes. The `scale` parameter
controls the length of the three lines.
Returns an `Object` which can be passed to `set_object()`
"""
return LineSegments(
PointsGeometry(
position=np.array([[0, 0, 0], [scale, 0, 0], [0, 0, 0], [0, scale, 0], [0, 0, 0], [0, 0, scale]])
.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,
),
LineBasicMaterial(vertexColors=True),
)
def camera(scale=1.0):
"""
A visual representation of the origin of a coordinate system, drawn as three
lines in red, green, and blue along the x, y, and z axes. The `scale` parameter
controls the length of the three lines.
Returns an `Object` which can be passed to `set_object()`
"""
return LineSegments(
PointsGeometry(
position=np.array([[0, 0, 0], [scale, 0, 0], [0, 0, 0], [0, scale, 0], [0, 0, 0], [0, 0, scale]])
.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,
),
LineBasicMaterial(vertexColors=True),
)
+45
View File
@@ -0,0 +1,45 @@
# 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.
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info >= (3, 0):
unicode = str
class Path(object):
__slots__ = ["entries"]
def __init__(self, entries=tuple()):
self.entries = entries
def append(self, other):
new_path = self.entries
for element in other.split("/"):
if len(element) == 0:
new_path = tuple()
else:
new_path = new_path + (element,)
return Path(new_path)
def lower(self):
return unicode("/" + "/".join(self.entries))
def __hash__(self):
return hash(self.entries)
def __eq__(self, other):
return self.entries == other.entries
+233
View File
@@ -0,0 +1,233 @@
# 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.
from __future__ import absolute_import, division, print_function
import base64
import re
import sys
if sys.version_info >= (3, 0):
ADDRESS_IN_USE_ERROR = OSError
else:
import socket
ADDRESS_IN_USE_ERROR = socket.error
import tornado.gen
import tornado.ioloop
import tornado.web
import tornado.websocket
import zmq
import zmq.eventloop.ioloop
from pyrad.viewer.backend.tree import SceneTree, find_node, walk
from zmq.eventloop.zmqstream import ZMQStream
def capture(pattern, s):
match = re.match(pattern, s)
if not match:
raise ValueError("Could not match {:s} with pattern {:s}".format(s, pattern))
else:
return match.groups()[0]
def match_zmq_url(line):
return capture(r"^zmq_url=(.*)$", line)
def _zmq_install_ioloop():
# For pyzmq<17, install ioloop instead of a tornado ioloop
# http://zeromq.github.com/pyzmq/eventloop.html
try:
pyzmq_major = int(zmq.__version__.split(".")[0])
except ValueError:
# Development version?
return
if pyzmq_major < 17:
zmq.eventloop.ioloop.install()
_zmq_install_ioloop()
MAX_ATTEMPTS = 1000
DEFAULT_ZMQ_METHOD = "tcp"
DEFAULT_ZMQ_PORT = 6000
DEFAULT_WEBSOCKET_PORT = 8051
MESHCAT_COMMANDS = ["set_transform", "set_object", "delete", "set_property", "set_animation", "set_image"]
def find_available_port(func, default_port, max_attempts=MAX_ATTEMPTS, **kwargs):
for i in range(max_attempts):
port = default_port + i
try:
return func(port, **kwargs), port
except (ADDRESS_IN_USE_ERROR, zmq.error.ZMQError):
print("Port: {:d} in use, trying another...".format(port), file=sys.stderr)
except Exception as e:
print(type(e))
raise
else:
raise (
Exception(
"Could not find an available port in the range: [{:d}, {:d})".format(
default_port, max_attempts + default_port
)
)
)
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
self.bridge = kwargs.pop("bridge")
super(WebSocketHandler, self).__init__(*args, **kwargs)
# this disables CORS
def check_origin(self, origin):
return True
def open(self):
self.bridge.websocket_pool.add(self)
print("opened:", self, file=sys.stderr)
self.bridge.send_scene(self)
def on_message(self, message):
print(message)
def on_close(self):
self.bridge.websocket_pool.remove(self)
print("closed:", self, file=sys.stderr)
def create_command(data):
"""Encode the drawing command into a Javascript fetch() command for display."""
return """
fetch("data:application/octet-binary;base64,{}")
.then(res => res.arrayBuffer())
.then(buffer => viewer.handle_command_bytearray(new Uint8Array(buffer)));
""".format(
base64.b64encode(data).decode("utf-8")
)
class ZMQWebSocketBridge(object):
context = zmq.Context()
def __init__(self, zmq_url=None, host="127.0.0.1", websocket_port=None):
self.host = host
self.websocket_pool = set()
self.app = self.make_app()
self.ioloop = tornado.ioloop.IOLoop.current()
if zmq_url is None:
def f(port):
return self.setup_zmq("{:s}://{:s}:{:d}".format(DEFAULT_ZMQ_METHOD, self.host, port))
(self.zmq_socket, self.zmq_stream, self.zmq_url), _ = find_available_port(f, DEFAULT_ZMQ_PORT)
else:
self.zmq_socket, self.zmq_stream, self.zmq_url = self.setup_zmq(zmq_url)
listen_kwargs = {}
if websocket_port is None:
_, self.websocket_port = find_available_port(self.app.listen, DEFAULT_WEBSOCKET_PORT, **listen_kwargs)
else:
self.app.listen(websocket_port, **listen_kwargs)
self.websocket_port = websocket_port
self.tree = SceneTree()
def __str__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name} using zmq_url={self.zmq_url} and websocket_port={self.websocket_port}"
def make_app(self):
return tornado.web.Application([(r"/", WebSocketHandler, {"bridge": self})])
def handle_zmq(self, frames):
cmd = frames[0].decode("utf-8")
if cmd not in MESHCAT_COMMANDS:
print(f"{cmd} not in MESHCAT_COMMANDS! Proceeding anyways.")
# self.zmq_socket.send(b"error: unrecognized comand")
if len(frames) != 3:
self.zmq_socket.send(b"error: expected 3 frames")
return
path = list(filter(lambda x: len(x) > 0, frames[1].decode("utf-8").split("/")))
data = frames[2]
self.forward_to_websockets(frames)
if cmd == "set_transform":
find_node(self.tree, path).transform = data
elif cmd == "set_object":
find_node(self.tree, path).object = data
find_node(self.tree, path).properties = []
elif cmd == "set_property":
find_node(self.tree, path).properties.append(data)
elif cmd == "set_animation":
find_node(self.tree, path).animation = data
elif cmd == "delete":
if len(path) > 0:
parent = find_node(self.tree, path[:-1])
child = path[-1]
if child in parent:
del parent[child]
else:
self.tree = SceneTree()
self.zmq_socket.send(b"ok")
def forward_to_websockets(self, frames):
cmd, path, data = frames
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
def setup_zmq(self, url):
zmq_socket = self.context.socket(zmq.REP)
zmq_socket.bind(url)
zmq_stream = ZMQStream(zmq_socket)
zmq_stream.on_recv(self.handle_zmq)
return zmq_socket, zmq_stream, url
def send_scene(self, websocket):
for node in walk(self.tree):
if node.object is not None:
websocket.write_message(node.object, binary=True)
for p in node.properties:
websocket.write_message(p, binary=True)
if node.transform is not None:
websocket.write_message(node.transform, binary=True)
if node.animation is not None:
websocket.write_message(node.animation, binary=True)
def run(self):
self.ioloop.start()
def main():
import argparse
parser = argparse.ArgumentParser(description="Serve the MeshCat HTML files and listen for ZeroMQ commands")
parser.add_argument("--zmq-url", "-z", type=str, nargs="?", default=None)
parser.add_argument("--websocket-port", "-wp", type=str, nargs="?", default=None)
args = parser.parse_args()
bridge = ZMQWebSocketBridge(zmq_url=args.zmq_url, websocket_port=args.websocket_port)
print(bridge)
try:
bridge.run()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
File diff suppressed because it is too large. Load diff
+45
View File
@@ -0,0 +1,45 @@
# 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.
from __future__ import absolute_import, division, print_function
from collections import defaultdict
class TreeNode(defaultdict):
__slots__ = ["object", "transform", "properties", "animation"]
def __init__(self, *args, **kwargs):
super(TreeNode, self).__init__(*args, **kwargs)
self.object = None
self.properties = []
self.transform = None
self.animation = None
SceneTree = lambda: TreeNode(SceneTree)
def walk(tree):
yield tree
for v in tree.values():
for t in walk(v): # could use `yield from` if we didn't need python2
yield t
def find_node(tree, path):
if len(path) == 0:
return tree
else:
return find_node(tree[path[0]], path[1:])
+219
View File
@@ -0,0 +1,219 @@
# 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.
"""Code to interface with the `vis/` (the JS visualizer).
"""
import copy
import random
import cv2
import matplotlib.pyplot as plt
import numpy as np
from pyrad.cameras.cameras import Camera
import pyrad.viewer.backend.cameras as c
import pyrad.viewer.backend.geometry as g
import pyrad.viewer.backend.transformations as tf
from pyrad.viewer.backend import ViewerWindow, Visualizer
def get_vis(zmq_url="tcp://0.0.0.0:6000"):
"""Returns the vis object."""
window = ViewerWindow(zmq_url)
vis = Visualizer(window=window)
return vis
def show_box_test(vis):
"""Simple test to draw a box and make sure everything is working."""
vis["box"].set_object(g.Box([1.0, 1.0, 1.0]), material=g.MeshPhongMaterial(color=0xFF0000))
def get_random_color():
color = np.random.rand(3) * 255.0
color = tuple([int(x) for x in color])
return color
def plot_correspondences(pair, plot=True):
"""Draw what the pair looks like, with the correspondences as lines."""
image0 = (pair["data0"]["image"] * 255).astype("uint8").transpose((1, 2, 0))
image1 = (pair["data1"]["image"] * 255).astype("uint8").transpose((1, 2, 0))
original_image = np.hstack([image0, image1])
h, w, _ = image0.shape
matches_image = original_image.copy()
# draw lines
correspondences = list(pair["correspondences"])
num = min(20, len(correspondences))
for x0, y0, x1, y1 in np.array(random.sample(correspondences, k=num)).astype("uint64"):
color = get_random_color()
thickness = 2
matches_image = cv2.line(matches_image, (x0, y0), (int(w + x1), y1), color, thickness)
# show image
if plot:
print("Correspondences:")
plt.figure(figsize=(20, 10))
plt.imshow(matches_image)
plt.show()
# ----------
# example training data
equal_distances_image = original_image.copy()
for i in range(num):
c0, c1 = np.array(random.sample(correspondences, k=2)).astype("uint64")
color = get_random_color()
thickness = 2
p0, p1 = c0[:2], c1[:2]
equal_distances_image = cv2.line(equal_distances_image, tuple(p0), tuple(p1), color, thickness)
p0, p1 = c0[2:], c1[2:]
p0[0] += w
p1[0] += w
equal_distances_image = cv2.line(equal_distances_image, tuple(p0), tuple(p1), color, thickness)
if plot:
print("Example training data:")
plt.figure(figsize=(20, 10))
plt.imshow(equal_distances_image)
plt.show()
return matches_image, equal_distances_image
def show_ply(vis, ply_path, name="ply", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
assert ply_path.endswith(".ply")
if color:
material = g.MeshPhongMaterial(color=color)
else:
material = g.MeshPhongMaterial(vertexColors=True)
vis[name].set_object(g.PlyMeshGeometry.from_file(ply_path), material)
def show_obj(vis, obj_path, name="obj", color=None):
"""Show the PLY file in the 3D viewer. Specify the full filename as input."""
assert obj_path.endswith(".obj")
if color:
material = g.MeshPhongMaterial(color=color)
else:
material = g.MeshPhongMaterial(vertexColors=True)
vis[name].set_object(g.ObjMeshGeometry.from_file(obj_path), material)
def draw_camera_frustum(
vis,
image=np.random.rand(100, 100, 3) * 255.0,
pose=tf.translation_matrix([0, 0, 0]),
K=None,
name="0000000",
displayed_focal_length=None,
shift_forward=None,
height=None,
realistic=True,
):
"""Draw the camera in the scene."""
assert K[0, 0] == K[1, 1]
focal_length = K[0, 0]
pp_w = K[0, 2]
pp_h = K[1, 2]
if displayed_focal_length:
assert height is None or not realistic
if height:
assert displayed_focal_length is None or not realistic
if height:
dfl = height / (2.0 * (pp_h / focal_length))
width = 2.0 * (pp_w / focal_length) * dfl
if displayed_focal_length is None:
displayed_focal_length = dfl
elif displayed_focal_length:
width = 2.0 * (pp_w / focal_length) * displayed_focal_length
height = 2.0 * (pp_h / focal_length) * displayed_focal_length
else:
assert not realistic
if pose.shape == (3, 4):
pose = np.concatenate([pose, np.zeros_like(pose[:1])], axis=0)
pose[3, 3] = 1.0
# draw the frustum
g_frustum = c.frustum(scale=1.0, focal_length=displayed_focal_length, width=width, height=height)
vis[name + "/frustum"].set_object(g_frustum)
if not realistic:
vis[name + "/frustum"].set_transform(tf.translation_matrix([0, 0, displayed_focal_length]))
# draw the image plane
g_image_plane = c.ImagePlane(image, width=width, height=height)
vis[name + "/image_plane"].set_object(g_image_plane)
if realistic:
vis[name + "/image_plane"].set_transform(tf.translation_matrix([0, 0, -displayed_focal_length]))
if shift_forward:
matrix = tf.translation_matrix([0, 0, displayed_focal_length])
matrix2 = tf.translation_matrix([0, 0, -shift_forward])
vis[name + "/frustum"].set_transform(matrix2 @ matrix)
vis[name + "/image_plane"].set_transform(matrix2)
# set the transform of the camera
vis[name].set_transform(pose)
def set_camera_render(vis, intrinsics=None, pose=None, name="renderer"):
"""Place a three.js camera in the scene.
This can be used to render an image from.
"""
full_name_str = f"/Cameras/{name}/rotated"
g_camera = c.PerspectiveCamera(fov=120, aspect=1.0, near=0.01, far=1000)
g_camera_helper = c.CameraHelper(g_camera)
# vis[full_name_str].set_object(g_camera)
vis[full_name_str].set_object(g_camera_helper)
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
"""
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
pp_w = K[0, 2]
pp_h = K[1, 2]
assert K[0, 0] == K[1, 1]
focal_length = K[0, 0]
x = pp_h / (focal_length)
fov = 2.0 * np.arctan(x) * (180.0 / np.pi)
vis["/Cameras/Main Camera R/<object>"].set_property("fov", fov)
vis["/Cameras/Main Camera R/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height
vis["/Cameras/Main Camera R"].set_transform(pose_processed)
def set_orth_camera(vis, pose, width, height, colmap=True):
""" """
pose_processed = copy.deepcopy(pose)
if colmap:
pose_processed[:, 1:3] *= -1
vis["/Cameras/Main Camera Orth"].set_transform(pose_processed)
vis["/Cameras/Main Camera Orth/<object>"].set_property("left", -width / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("right", width / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("top", height / 2.0)
vis["/Cameras/Main Camera Orth/<object>"].set_property("bottom", -height / 2.0)
def set_camera(vis, camera: Camera):
pose = camera.get_camera_to_world_h()
K = camera.get_intrinsics_matrix()
set_persp_camera(vis, pose=pose.double().numpy(), K=K.double().numpy())
+84
View File
@@ -0,0 +1,84 @@
# 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.
from __future__ import absolute_import, division, print_function
import sys
import time
import numpy as np
import umsgpack
import zmq
from .commands import Delete, SetAnimation, SetImage, SetObject, SetProperty, SetTransform
from .path import Path
class ViewerWindow(object):
context = zmq.Context()
def __init__(self, zmq_url):
self.zmq_url = zmq_url
self.client = self.context.socket(zmq.REQ)
self.client.connect(self.zmq_url)
def send(self, command):
cmd_data = command.lower()
self.client.send_multipart(
[
cmd_data["type"].encode("utf-8"),
cmd_data["path"].encode("utf-8"),
umsgpack.packb(cmd_data),
]
)
self.client.recv()
class Visualizer(object):
__slots__ = ["window", "path"]
def __init__(self, window):
self.window = window
self.path = Path(("pyrad",)) # TODO(ethan): change this
@staticmethod
def view_into(window, path):
vis = Visualizer(window=window)
vis.path = path
return vis
def __getitem__(self, path):
return Visualizer.view_into(self.window, self.path.append(path))
def set_object(self, geometry, material=None):
return self.window.send(SetObject(geometry, material, self.path))
def set_transform(self, matrix=np.eye(4)):
assert matrix.shape == (4, 4)
return self.window.send(SetTransform(matrix, self.path))
def set_property(self, key, value):
return self.window.send(SetProperty(key, value, self.path))
def set_animation(self, animation, play=True, repetitions=1):
return self.window.send(SetAnimation(animation, play=play, repetitions=repetitions))
def set_image(self, image):
return self.window.send(SetImage(image, self.path))
def delete(self):
return self.window.send(Delete(self.path))
def __repr__(self):
return "<Visualizer using: {window} at path: {path}>".format(window=self.window, path=self.path)
-127
View File
@@ -1,127 +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.
"""
Visualization code for plotly.
"""
import numpy as np
import plotly.graph_objects as go
import torch
from pyrad.cameras.rays import RayBundle
def color_str(color):
"""Plotly color string.
Args:
color: list [r, g, b] in [0, 1] range
Returns:
str: plotly-formatted color string
"""
color = list((np.array(color) * 255.0).astype("int"))
return f"""rgb({color[0]}, {color[1]}, {color[2]})"""
def get_line_segments_from_lines(
lines,
color=color_str((1, 0, 0)),
marker_color=color_str((1, 0, 0)),
colors=None,
draw_marker=True,
draw_line=True,
marker_size=4,
line_width=10,
):
"""Returns a list of Scatter3D objects for creating lines with plotly.
# TODO(ethan): make this function more efficient instead of having a list of objects.
Args:
lines (_type_): list of [np.array(2, 3), ...], line is defined by a (2, 3) array
color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
marker_color (_type_, optional): _description_. Defaults to color_str((1, 0, 0)).
colors (_type_, optional): _description_. Defaults to None.
draw_marker (bool, optional): _description_. Defaults to True.
draw_line (bool, optional): _description_. Defaults to True.
marker_size (int, optional): _description_. Defaults to 4.
line_width (int, optional): _description_. Defaults to 10.
Returns:
_type_: _description_
"""
data = []
for idx, line in enumerate(lines):
thiscolor = color if draw_line else "rgba(0, 0, 0, 0)"
if colors is not None:
marker_color = colors[idx]
thiscolor = colors[idx]
data.append(
go.Scatter3d(
x=line[:, 0],
y=line[:, 1],
z=line[:, 2],
showlegend=False,
marker=dict(
size=marker_size,
color=marker_color,
colorscale="Viridis",
)
if draw_marker
else dict(color="rgba(0, 0, 0, 0)"),
line=dict(color=thiscolor, width=line_width),
)
)
return data
def visualize_dataset(camera_origins, ray_bundle: RayBundle):
"""Visualize a dataset with plotly using our cameras and generated rays."""
skip = 1
size = 8
assert len(ray_bundle) < 500, "Let's not break plotly by plotting too many rays!"
data = []
data += [
go.Scatter3d(
x=camera_origins[::skip, 0],
y=camera_origins[::skip, 1],
z=camera_origins[::skip, 2],
mode="markers",
name="camera origins",
marker=dict(color="rgba(0, 0, 0, 1)", size=size),
)
]
length = 2.0
lines = torch.stack(
[ray_bundle.origins, ray_bundle.origins + ray_bundle.directions * length], dim=1
) # (num_rays, 2, 3)
data += get_line_segments_from_lines(lines)
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
margin=go.layout.Margin(l=50, r=50, b=100, t=100, pad=4),
scene=go.layout.Scene(
aspectmode="data",
camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=1.25, y=1.25, z=1.25)),
),
)
fig = go.Figure(data=data, layout=layout)
return fig