Documenting viewer and faster image sending (#86)

* updated three.js version. only send camera information when it moves

* changing code back to updating camera constantly because packets seem to be lost

* name change

* starting viewer docs

* new workflow

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* ga

* homepage

* homepage

* / to ?

* more documentation

* fixed none error

* instant ngp fix

* faster image sending over tcp. instant ngp bin fix. lowest res when moving

* black

* requirements
This commit is contained in:
Ethan Weber authored and GitHub committed 2022-07-07 00:03:45 -07:00
1 parent d0f0f8da2d
commit 44c5e3264c
28 files changed
+28943 -609

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Copyright 2022 The Plenoptix Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from . import commands
from . import geometry
from . import visualizer
from . import transformations
from .visualizer import ViewerWindow, Viewer
def viewer_assets_path():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "viewer"))
+90
View File
@@ -0,0 +1,90 @@
# 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
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
+101
View File
@@ -0,0 +1,101 @@
# 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 .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 GetObject:
__slots__ = ["path"]
def __init__(self, path):
self.path = path
def lower(self):
return {"type": "get_object", "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}
+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
+240
View File
@@ -0,0 +1,240 @@
# 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 numpy as np
import tornado.gen
import tornado.ioloop
import tornado.web
import tornado.websocket
import msgpack
import msgpack_numpy
import umsgpack
import zmq
import zmq.eventloop.ioloop
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcrtpsender import RTCRtpSender
from zmq.eventloop.zmqstream import ZMQStream
from pyrad.viewer.server.socket import SerializingContext
from pyrad.viewer.server.tree import SceneTree, find_node, walk
from pyrad.viewer.server.video_stream import SingleFrameStreamTrack
MAX_ATTEMPTS = 1000
DEFAULT_ZMQ_METHOD = "tcp"
DEFAULT_ZMQ_PORT = 6000
DEFAULT_WEBSOCKET_PORT = 8051
WEBSOCKET_COMMANDS = ["set_transform", "set_object", "get_object", "set_property", "delete"]
WEBRTC_COMMANDS = ["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 (OSError, 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
)
)
)
def force_codec(pc, sender, forced_codec):
kind = forced_codec.split("/")[0]
codecs = RTCRtpSender.getCapabilities(kind).codecs
transceiver = next(t for t in pc.getTransceivers() if t.sender == sender)
transceiver.setCodecPreferences([codec for codec in codecs if codec.mimeType == forced_codec])
class WebSocketHandler(tornado.websocket.WebSocketHandler):
"""Tornado websocket handler for receiving and sending commands from/to the viewer."""
def __init__(self, *args, **kwargs):
self.bridge = kwargs.pop("bridge")
super(WebSocketHandler, self).__init__(*args, **kwargs)
def check_origin(self, origin):
"""This disables CORS."""
return True
def open(self):
self.bridge.websocket_pool.add(self)
print("opened:", self, file=sys.stderr)
self.bridge.send_scene(self)
async def on_message(self, message):
data = message
m = umsgpack.unpackb(message)
type_ = m["type"]
path = list(filter(lambda x: len(x) > 0, m["path"].split("/")))
if type_ == "set_transform":
find_node(self.bridge.tree, path).transform = data
elif type_ == "set_object":
find_node(self.bridge.tree, path).object = data
find_node(self.bridge.tree, path).properties = []
elif type_ == "offer":
offer = RTCSessionDescription(m["data"]["sdp"], m["data"]["type"])
pc = RTCPeerConnection()
self.bridge.pcs.add(pc)
video = SingleFrameStreamTrack()
self.bridge.video_tracks.add(video)
video_sender = pc.addTrack(video)
# force_codec(pc, video_sender, video_codec)
await pc.setRemoteDescription(offer)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
cmd_data = {
"type": "answer",
"path": "",
"data": {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type},
}
data = umsgpack.packb(cmd_data)
self.write_message(data, binary=True)
def on_close(self):
self.bridge.websocket_pool.remove(self)
print("closed:", self, file=sys.stderr)
class ZMQWebSocketBridge(object):
context = zmq.Context()
# context = SerializingContext()
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()
self.pcs = set()
self.video_tracks = set()
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):
"""Create a tornado application for the websocket server."""
return tornado.web.Application([(r"/", WebSocketHandler, {"bridge": self})])
def handle_zmq(self, frames):
cmd = frames[0].decode("utf-8")
print(cmd)
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]
if cmd in WEBSOCKET_COMMANDS:
if cmd != "get_object":
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 == "get_object":
data = find_node(self.tree, path).object
if isinstance(data, type(None)):
data = umsgpack.packb("error: object not found")
self.zmq_socket.send(data)
return
elif cmd == "set_property":
find_node(self.tree, path).properties.append(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()
elif cmd in WEBRTC_COMMANDS:
if cmd == "set_image":
image = msgpack.unpackb(
data, object_hook=msgpack_numpy.decode, use_list=False, max_bin_len=50000000, raw=False
)
for video_track in self.video_tracks:
video_track.put_frame(image)
else:
self.zmq_socket.send(b"error: unknown command")
return
self.zmq_socket.send(b"ok")
return
def forward_to_websockets(self, frames):
"""Forward a zmq message to all websockets."""
_, _, data = frames # cmd, path, data
for websocket in self.websocket_pool:
websocket.write_message(data, binary=True)
def setup_zmq(self, url):
"""Setup a zmq socket and connect it to the given 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)
def run(self):
self.ioloop.start()
def start_server_as_subprocess(zmq_url=None):
"""Starts the ZMQWebSocketBridge server as a subprocess."""
raise NotImplementedError()
+127
View File
@@ -0,0 +1,127 @@
# https://gist.github.com/jeffbass/ebf877e964c9a0b84272
# zmqimage.py -- classes to send, receive and display cv2 images via zmq
# based on serialization in pyzmq docs and pyzmq/examples/serialization
"""
PURPOSE:
These classes allow a headless (no display) computer running OpenCV code
to display OpenCV images on another computer with a display.
For example, a headless Raspberry Pi with no display can run OpenCV code
and can display OpenCV images on a Mac with a display.
USAGE:
First, start this "display server" program on the computer with a display:
# imageShowServer.py
import zmqimage
zmq = zmqimage.zmqImageShowServer()
print "Starting zmqImageShow Server..."
print " press Ctrl-C to stop"
while True: # Until Ctrl-C is pressed, will repeatedly
zmq.imshow() # display images sent from the headless computer
Run the above program by:
python imageShowServer.py
Leave the above program running in its own terminal window.
Then, run a program like the one below on the headless computer.
In most cases, it will be run using ssh into the headless computer
from another terminal window on the computer with a display.
The python lines below represent a program fragment as an example.
Use zmq.imshow("Image Display Name", image) instead of
cv2.imshow("Image Display Name", image) and the images will
display on the computer running the program above:
import numpy as np
import cv2
import zmqimage
print "Connecting to zmqShowImage Server ... "
zmq = zmqimage.zmqConnect()
image = np.zeros((500, 500), dtype="uint8")
zmq.imshow("Zero Image 500 x 500", image)
# build a rectangular mask & display it
mask = np.zeros(image.shape[:2], dtype="uint8")
cv2.rectangle(mask, (0, 90), (300, 450), 255, -1)
zmq.imshow("Rectangular Mask", mask)
CAVEATS:
There is no error checking and only Ctrl-C stops the display server.
While zmq.imshow() works like cv2.imshow(), no other
cv2 display functions are implemented.
Uses tcp style sockets; sockets and tcp addresses have
defaults in the classes but may be overridden.
AUTHOR:
Jeff Bass, https://github.com/jeffbass, jeff@yin-yang-ranch.com
"""
import zmq
import numpy as np
import cv2
class SerializingSocket(zmq.Socket):
"""A class with some extra serialization methods
send_array sends numpy arrays with metadata necessary
for reconstructing the array on the other side (dtype,shape).
Also sends array name for display with cv2.show(image).
recv_array receives dict(arrayname,dtype,shape) and an array
and reconstructs the array with the correct shape and array name.
"""
def send_array(self, A, arrayname="NoName", flags=0, copy=True, track=False):
"""send a numpy array with metadata and array name"""
md = dict(
arrayname=arrayname,
dtype=str(A.dtype),
shape=A.shape,
)
self.send_json(md, flags | zmq.SNDMORE)
return self.send(A, flags, copy=copy, track=track)
def recv_array(self, flags=0, copy=True, track=False):
"""recv a numpy array, including arrayname, dtype and shape"""
md = self.recv_json(flags=flags)
msg = self.recv(flags=flags, copy=copy, track=track)
A = np.frombuffer(msg, dtype=md["dtype"])
return (md["arrayname"], A.reshape(md["shape"]))
class SerializingContext(zmq.Context):
_socket_class = SerializingSocket
class zmqConnect:
"""A class that opens a zmq REQ socket on the headless computer"""
def __init__(self, connect_to="tcp://jeff-mac:5555"):
"""initialize zmq socket for sending images to display on remote computer"""
"""connect_to is the tcp address:port of the display computer"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REQ)
self.zmq_socket.connect(connect_to)
def imshow(self, arrayname, array):
"""send image to display on remote server"""
if array.flags["C_CONTIGUOUS"]:
# if array is already contiguous in memory just send it
self.zmq_socket.send_array(array, arrayname, copy=False)
else:
# else make it contiguous before sending
array = np.ascontiguousarray(array)
self.zmq_socket.send_array(array, arrayname, copy=False)
message = self.zmq_socket.recv()
class zmqImageShowServer:
"""A class that opens a zmq REP socket on the display computer to receive images"""
def __init__(self, open_port="tcp://*:5555"):
"""initialize zmq socket on viewing computer that will display images"""
self.zmq_context = SerializingContext()
self.zmq_socket = self.zmq_context.socket(zmq.REP)
self.zmq_socket.bind(open_port)
def imshow(self, copy=False):
"""receive and show image on viewing computer display"""
arrayname, image = self.zmq_socket.recv_array(copy=False)
# print "Received Array Named: ", arrayname
# print "Array size: ", image.shape
cv2.imshow(arrayname, image)
cv2.waitKey(0)
self.zmq_socket.send(b"OK")
File diff suppressed because it is too large. Load diff
+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:])
+51
View File
@@ -0,0 +1,51 @@
# 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 numpy as np
import torch
def get_chunks(lst, num_chunks=None, size_of_chunk=None):
"""Returns list of n elements, constaining a sublist."""
if num_chunks:
assert not size_of_chunk
size = len(lst) // num_chunks
if size_of_chunk:
assert not num_chunks
size = size_of_chunk
chunks = []
for i in range(0, len(lst), size):
chunks.append(lst[i : i + size])
return chunks
def get_intrinsics_matrix_and_camera_to_world_h(camera_object, image_height):
"""Returns the camera intrinsics matrix and the camera to world homogeneous matrix.
Args:
camera_object: a Camera object.
image_size: the size of the image (height, width)
"""
# intrinsics
fov = camera_object["fov"]
aspect = camera_object["aspect"]
image_width = aspect * image_height
pp_w = image_width / 2.0
pp_h = image_height / 2.0
focal_length = pp_h / np.tan(fov * (np.pi / 180.0) / 2.0)
intrinsics_matrix = torch.tensor([[focal_length, 0, pp_w], [0, focal_length, pp_h], [0, 0, 1]]).float()
# extrinsics
camera_to_world_h = torch.tensor(get_chunks(camera_object["matrix"], size_of_chunk=4)).T.float()
return intrinsics_matrix, camera_to_world_h
+93
View File
@@ -0,0 +1,93 @@
# 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 asyncio
import queue
import math
import cv2
import numpy
from aiortc import VideoStreamTrack
from av import VideoFrame
class FlagVideoStreamTrack(VideoStreamTrack):
"""
A video track that returns an animated flag.
"""
def __init__(self):
super().__init__() # don't forget this!
self.counter = 0
height, width = 480, 640
# generate flag
data_bgr = numpy.hstack(
[
self._create_rectangle(width=213, height=480, color=(255, 0, 0)), # blue
self._create_rectangle(width=214, height=480, color=(255, 255, 255)), # white
self._create_rectangle(width=213, height=480, color=(0, 0, 255)), # red
]
)
# shrink and center it
M = numpy.float32([[0.5, 0, width / 4], [0, 0.5, height / 4]])
data_bgr = cv2.warpAffine(data_bgr, M, (width, height))
# compute animation
omega = 2 * math.pi / height
id_x = numpy.tile(numpy.array(range(width), dtype=numpy.float32), (height, 1))
id_y = numpy.tile(numpy.array(range(height), dtype=numpy.float32), (width, 1)).transpose()
self.frames = []
for k in range(30):
phase = 2 * k * math.pi / 30
map_x = id_x + 10 * numpy.cos(omega * id_x + phase)
map_y = id_y + 10 * numpy.sin(omega * id_x + phase)
frame = cv2.remap(data_bgr, map_x, map_y, cv2.INTER_LINEAR)
self.frames.append(VideoFrame.from_ndarray(frame, format="bgr24"))
async def recv(self):
pts, time_base = await self.next_timestamp()
frame = self.frames[self.counter % 30]
frame.pts = pts
frame.time_base = time_base
self.counter += 1
return frame
def _create_rectangle(self, width, height, color):
data_bgr = numpy.zeros((height, width, 3), numpy.uint8)
data_bgr[:, :] = color
return data_bgr
class SingleFrameStreamTrack(VideoStreamTrack):
def __init__(self):
super().__init__()
self.background_frame = numpy.zeros((480, 640, 3), dtype="uint8") * 255
self.frame = None
self.put_frame(self.background_frame)
def put_frame(self, frame):
self.frame = VideoFrame.from_ndarray(frame)
async def recv(self):
pts, time_base = await self.next_timestamp()
frame = self.frame
frame.pts = pts
frame.time_base = time_base
return frame
+321
View File
@@ -0,0 +1,321 @@
# 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 logging
import random
import sys
import threading
import time
import numpy as np
import torch
import pyrad.viewer.server.cameras as c
import pyrad.viewer.server.geometry as g
import pyrad.viewer.server.transformations as tf
from pyrad.cameras.cameras import Camera, get_camera, get_intrinsics_from_intrinsics_matrix
from pyrad.cameras.rays import RayBundle
from pyrad.utils import profiler
from pyrad.utils.config import ViewerConfig
from pyrad.viewer.server import Viewer
from pyrad.viewer.server.utils import get_intrinsics_matrix_and_camera_to_world_h
class CameraChangeException(Exception):
"""Basic camera exception to interrupt visualizer"""
class SetTrace:
"""Basic trace function"""
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
class VisualizerState:
"""Class to hold state for"""
def __init__(self, config: ViewerConfig):
self.config = config
self.vis = None
if self.config.enable:
zmq_url = self.config.zmq_url
self.vis = Viewer(zmq_url=zmq_url)
logging.info("Connected to viewer at %s", zmq_url)
self.vis.delete()
else:
logging.info("Continuing without viewer.")
# visualizer specific variables
self.prev_camera_matrix = None
self.res_upscale_factor = 1
self.lock = threading.Lock()
self.check_interrupt_vis = False
self.check_done_render = True
def init_scene(self, image_dataset, dataset_inputs):
"""initializes the scene with the datasets"""
if self.vis:
self._draw_scene_in_viewer(image_dataset, dataset_inputs)
def update_scene(self, step, graph):
"""updates the scene based on the graph weights"""
if self._is_render_step(step):
self._render_image_in_viewer(graph)
def _check_interrupt(self, frame, event, arg):
if event == "line":
if self.check_interrupt_vis and self.res_upscale_factor > 1:
raise CameraChangeException
return self._check_interrupt
def _is_render_step(self, step, default_steps=10):
"""dynamically calculate when to render grapic based on resolution of image"""
if self.vis and step != 0:
steps_per_render_image = min(default_steps * self.res_upscale_factor, 100)
return step % steps_per_render_image == 0
return False
def _draw_scene_in_viewer(self, image_dataset, dataset_inputs):
"""Draw some images and the scene aabb in the viewer."""
indices = random.sample(range(len(image_dataset)), k=10)
for idx in indices:
image = image_dataset[idx]["image"]
camera = get_camera(dataset_inputs.intrinsics[idx], dataset_inputs.camera_to_world[idx], None)
pose = camera.get_camera_to_world().double().numpy()
K = camera.get_intrinsics_matrix().double().numpy()
draw_camera_frustum(
self.vis,
image=(image.double().numpy() * 255.0),
pose=pose,
K=K,
height=1.0,
name=f"image_dataset/{idx:06d}",
displayed_focal_length=0.5,
realistic=False,
)
aabb = dataset_inputs.scene_bounds.aabb
draw_aabb(self.vis, aabb, name="dataset_inputs_train/scene_bounds/aabb")
def _async_check_camera_update(self):
"""Async function to check whether camera has been updated in visualizer"""
with self.lock:
self.check_done_render = False
while not self.check_done_render:
data = self.vis["/Cameras/Main Camera"].get_object()
if data is None:
return
camera_object = data["object"]["object"]
if self.prev_camera_matrix is None or not np.array_equal(camera_object["matrix"], self.prev_camera_matrix):
with self.lock:
self.check_interrupt_vis = True
self.prev_camera_matrix = camera_object["matrix"]
self.res_upscale_factor = 1
time.sleep(0.001)
@torch.no_grad()
def _async_get_visualizer_outputs(self, graph, camera_ray_bundle: RayBundle):
"""async getter function for visualizer without returning"""
with SetTrace(self._check_interrupt):
graph.get_outputs_for_camera_ray_bundle(camera_ray_bundle)
with self.lock:
self.check_done_render = True
self.check_interrupt_vis = False
@profiler.time_function
def _render_image_in_viewer(self, graph):
"""
Draw an image using the current camera pose from the viewer.
The image is sent of a TCP connection and then uses WebRTC to send it to the viewer.
"""
data = self.vis["/Cameras/Main Camera"].get_object()
if data is None:
return
camera_object = data["object"]["object"]
# hacky way to prevent overflow check to see if < 100; TODO(make less hacky)
if self.prev_camera_matrix is not None and np.array_equal(camera_object["matrix"], self.prev_camera_matrix):
self.res_upscale_factor = min(self.res_upscale_factor * 2, 100)
else:
self.prev_camera_matrix = camera_object["matrix"]
self.res_upscale_factor = 1
image_height = min(
self.config.min_render_image_height * self.res_upscale_factor,
self.config.max_render_image_height,
)
intrinsics_matrix, camera_to_world_h = get_intrinsics_matrix_and_camera_to_world_h(
camera_object, image_height=image_height
)
camera_to_world = camera_to_world_h[:3, :]
intrinsics = get_intrinsics_from_intrinsics_matrix(intrinsics_matrix)
camera = get_camera(intrinsics, camera_to_world)
camera_ray_bundle = camera.get_camera_ray_bundle(device=graph.get_device())
camera_ray_bundle.num_rays_per_chunk = self.config.num_rays_per_chunk
graph.eval()
try:
check_thread = threading.Thread(target=self._async_check_camera_update)
render_thread = threading.Thread(target=self._async_get_visualizer_outputs, args=(graph, camera_ray_bundle))
check_thread.start()
render_thread.start()
check_thread.join()
render_thread.join()
except Exception as e: # pylint: disable=broad-except
print(e)
graph.train()
outputs = graph.vis_outputs
if outputs is not None:
# gross hack to get the image key, depending on which keys the graph uses
rgb_key = "rgb" if "rgb" in outputs else "rgb_fine"
image = (outputs[rgb_key].cpu().numpy() * 255).astype("uint8")
self.vis["/Cameras/Main Camera"].set_image(image)
return outputs
def get_default_vis():
"""Returns the default Visualizer."""
zmq_url = "tcp://0.0.0.0:6000"
viewer = Viewer(zmq_url=zmq_url)
return viewer
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 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_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/<object>"].set_property("fov", fov)
vis["/Cameras/Main Camera/<object>"].set_property("aspect", float(pp_w / pp_h)) # three.js expects width/height
vis["/Cameras/Main Camera/<object>"].set_transform(pose_processed)
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())
def draw_aabb(vis, aabb, name="aabb"):
"""Draw the axis-aligned bounding box."""
lengths = aabb[1] - aabb[0]
vis[name].set_object(g.Box(lengths.tolist()), material=g.MeshPhongMaterial(color=0xFF0000, opacity=0.1))
center = aabb[0] + lengths / 2.0
vis[name].set_transform(tf.translation_matrix(center.tolist()))
+109
View File
@@ -0,0 +1,109 @@
# 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 numpy as np
import msgpack
import msgpack_numpy
import umsgpack
import zmq
from pyrad.viewer.server.socket import SerializingContext
from .commands import Delete, SetObject, GetObject, SetProperty, SetTransform
from .path import Path
class ViewerWindow(object):
context = zmq.Context()
# context = SerializingContext()
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),
]
)
return self.client.recv()
class Viewer(object):
"""Visualizer class for connecting to the bridge server."""
def __init__(self, zmq_url: str = None, window: ViewerWindow = None):
if zmq_url is None and window is None:
raise ValueError("Must specify either zmq_url or window.")
if window is None:
self.window = ViewerWindow(zmq_url=zmq_url)
else:
self.window = window
self.path = Path(("pyrad",))
@staticmethod
def view_into(window: ViewerWindow, path: Path):
"""Returns a new Viewer but keeping the same ViewerWindow."""
vis = Viewer(window=window)
vis.path = path
return vis
def __getitem__(self, path):
return Viewer.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 get_object(self):
"""Get the object at the current path."""
data = self.window.send(GetObject(self.path))
data = umsgpack.unpackb(data)
if isinstance(data, str) and data.find("error") == 0:
# some error meaning that the object does not exist
return None
return data
def set_image(self, image):
"""Set the image"""
type_ = "set_image"
path = self.path.lower()
data = msgpack.packb(image, default=msgpack_numpy.encode, use_bin_type=True)
self.window.client.send_multipart(
[
type_.encode("utf-8"),
path.encode("utf-8"),
data,
]
)
return self.window.client.recv()
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 delete(self):
return self.window.send(Delete(self.path))
def __repr__(self):
return "<Viewer using: {window} at path: {path}>".format(window=self.window, path=self.path)