def plot_with_pythreejs(cloud, **kwargs): if ipywidgets is None: raise ImportError( "ipywidgets is needed for plotting with pythreejs backend.") if pythreejs is None: raise ImportError( "pythreejs is needed for plotting with pythreejs backend.") if display is None: raise ImportError( "IPython is needed for plotting with pythreejs backend.") colors = get_colors(cloud, kwargs["use_as_color"], kwargs["cmap"]) ptp = cloud.xyz.ptp() children = [] widgets = [] if kwargs["mesh"]: raise NotImplementedError( "Plotting mesh geometry with pythreejs backend is not supported yet." ) if kwargs["polylines"]: lines = get_polylines_pythreejs(kwargs["polylines"]) children.extend(lines) points = get_pointcloud_pythreejs(cloud.xyz, colors) children.append(points) initial_point_size = kwargs["initial_point_size"] or ptp / 10 size = ipywidgets.FloatSlider(value=initial_point_size, min=0.0, max=initial_point_size * 10, step=initial_point_size / 100) ipywidgets.jslink((size, 'value'), (points.material, 'size')) widgets.append(ipywidgets.Label('Point size:')) widgets.append(size) if kwargs["scene"]: kwargs["scene"].children = [points] + list(kwargs["scene"].children) else: camera = get_camera_pythreejs(cloud.centroid, cloud.xyz, kwargs["width"], kwargs["height"]) children.append(camera) controls = [get_orbit_controls(camera, cloud.centroid)] scene = pythreejs.Scene(children=children) renderer = pythreejs.Renderer(scene=scene, camera=camera, controls=controls, width=kwargs["width"], height=kwargs["height"]) display(renderer) color = ipywidgets.ColorPicker(value=kwargs["background"]) ipywidgets.jslink((color, 'value'), (scene, 'background')) widgets.append(ipywidgets.Label('Background color:')) widgets.append(color) display(ipywidgets.HBox(children=widgets)) return scene if kwargs["return_scene"] else None
def visualise(mesh, geometric_field, number_of_dimensions, xi_interpolation, dependent_field=None, variable=None, mechanics_animation=False, colour_map_dependent_component_number=None, cmap='gist_rainbow', resolution=1, node_labels=False): if number_of_dimensions != 3: print( 'Warning: Only visualisation of 3D meshes is currently supported.') return if xi_interpolation != [1, 1, 1]: print( 'Warning: Only visualisation of 3D elements with linear Lagrange \ interpolation along all coordinate directions is currently \ supported.') return view_width = 600 view_height = 600 debug = False if debug: vertices = [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]] faces = [[0, 1, 3], [0, 3, 2], [0, 2, 4], [2, 6, 4], [0, 4, 1], [1, 4, 5], [2, 3, 6], [3, 7, 6], [1, 5, 3], [3, 5, 7], [4, 6, 5], [5, 6, 7]] vertexcolors = [ '#000000', '#0000ff', '#00ff00', '#ff0000', '#00ffff', '#ff00ff', '#ffff00', '#ffffff' ] else: # Get mesh topology information. num_nodes = mesh_tools.num_nodes_get(mesh, mesh_component=1) node_nums = list(range(1, num_nodes + 1)) num_elements, element_nums = mesh_tools.num_element_get( mesh, mesh_component=1) # Convert geometric field to a morphic mesh and export to json mesh = mesh_tools.OpenCMISS_to_morphic(mesh, geometric_field, element_nums, node_nums, dimension=3, interpolation='linear') vertices, faces, _, xi_element_nums, xis = get_faces( mesh, res=resolution, exterior_only=True, include_xi=True) vertices = vertices.tolist() faces = faces.tolist() centroid = np.mean(vertices, axis=0) max_positions = np.max(vertices, axis=0) min_positions = np.min(vertices, axis=0) range_positions = max_positions - min_positions if (dependent_field is not None) and (colour_map_dependent_component_number is not None): solution = np.zeros(xis.shape[0]) for idx, (xi, xi_element_num) in enumerate(zip(xis, xi_element_nums)): solution[idx] = mesh_tools.interpolate_opencmiss_field_xi( dependent_field, xi, element_ids=[xi_element_num], dimension=3, deriv=1)[colour_map_dependent_component_number - 1] minima = min(solution) maxima = max(solution) import matplotlib norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True) mapper = cm.ScalarMappable(norm=norm, cmap=cm.get_cmap(name=cmap)) vertex_colors = np.zeros((len(vertices), 3), dtype='float32') for idx, v in enumerate(solution): vertex_colors[idx, :] = mapper.to_rgba(v, alpha=None)[:3] # else: # raise ValueError('Visualisation not supported.') else: vertex_colors = np.tile(np.array([0.5, 0.5, 0.5], dtype='float32'), (len(vertices), 1)) geometry = pjs.BufferGeometry(attributes=dict( position=pjs.BufferAttribute(vertices, normalized=False), index=pjs.BufferAttribute( np.array(faces).astype(dtype='uint16').ravel(), normalized=False), color=pjs.BufferAttribute(vertex_colors), )) if mechanics_animation: deformed_vertices = np.zeros((xis.shape[0], 3), dtype='float32') for idx, (xi, xi_element_num) in enumerate(zip(xis, xi_element_nums)): deformed_vertices[idx, :] = \ mesh_tools.interpolate_opencmiss_field_xi( dependent_field, xi, element_ids=[xi_element_num], dimension=3, deriv=1)[0][:3] geometry.morphAttributes = { 'position': [ pjs.BufferAttribute(deformed_vertices), ] } geometry.exec_three_obj_method('computeFaceNormals') geometry.exec_three_obj_method('computeVertexNormals') surf1 = pjs.Mesh(geometry, pjs.MeshPhongMaterial(color='#ff3333', shininess=150, morphTargets=True, side='FrontSide'), name='A') surf2 = pjs.Mesh(geometry, pjs.MeshPhongMaterial(color='#ff3333', shininess=150, morphTargets=True, side='BackSide'), name='B') surf = pjs.Group(children=[surf1, surf2]) # camera = pjs.PerspectiveCamera( # fov=20, position=[range_positions[0] * 10, # range_positions[1] * 10, # range_positions[2] * 10], # width=view_width, # height=view_height, near=1, # far=max(range_positions) * 10) camera = pjs.PerspectiveCamera(position=[ range_positions[0] * 3, range_positions[1] * 3, range_positions[2] * 3 ], aspect=view_width / view_height) camera.up = [0, 0, 1] camera.lookAt(centroid.tolist()) scene3 = pjs.Scene(children=[ surf1, surf2, camera, pjs.DirectionalLight(position=[3, 5, 1], intensity=0.6), pjs.AmbientLight(intensity=0.5) ]) axes = pjs.AxesHelper(size=range_positions[0] * 2) scene3.add(axes) A_track = pjs.NumberKeyframeTrack( name='scene/A.morphTargetInfluences[0]', times=[0, 3], values=[0, 1]) B_track = pjs.NumberKeyframeTrack( name='scene/B.morphTargetInfluences[0]', times=[0, 3], values=[0, 1]) pill_clip = pjs.AnimationClip(tracks=[A_track, B_track]) pill_action = pjs.AnimationAction(pjs.AnimationMixer(scene3), pill_clip, scene3) renderer3 = pjs.Renderer( camera=camera, scene=scene3, controls=[pjs.OrbitControls(controlling=camera)], width=view_width, height=view_height) display(renderer3, pill_action) else: geometry.exec_three_obj_method('computeFaceNormals') geometry.exec_three_obj_method('computeVertexNormals') surf1 = pjs.Mesh(geometry=geometry, material=pjs.MeshLambertMaterial( vertexColors='VertexColors', side='FrontSide')) # Center the cube. surf2 = pjs.Mesh(geometry=geometry, material=pjs.MeshLambertMaterial( vertexColors='VertexColors', side='BackSide')) # Center the cube. surf = pjs.Group(children=[surf1, surf2]) camera = pjs.PerspectiveCamera(position=[ range_positions[0] * 3, range_positions[1] * 3, range_positions[2] * 3 ], aspect=view_width / view_height) camera.up = [0, 0, 1] camera.lookAt(centroid.tolist()) # if perspective: # camera.mode = 'perspective' # else: # camera.mode = 'orthographic' lights = [ pjs.DirectionalLight(position=[ range_positions[0] * 16, range_positions[1] * 12, range_positions[2] * 17 ], intensity=0.5), pjs.AmbientLight(intensity=0.8), ] orbit = pjs.OrbitControls(controlling=camera, screenSpacePanning=True, target=centroid.tolist()) scene = pjs.Scene() axes = pjs.AxesHelper(size=max(range_positions) * 2) scene.add(axes) scene.add(surf1) scene.add(surf2) scene.add(lights) if node_labels: # Add text labels for each mesh node. v, ids = mesh.get_node_ids(group='_default') for idx, v in enumerate(v): text = make_text(str(ids[idx]), position=(v[0], v[1], v[2])) scene.add(text) # Add text for axes labels. x_axis_label = make_text('x', position=(max(range_positions) * 2, 0, 0)) y_axis_label = make_text('y', position=(0, max(range_positions) * 2, 0)) z_axis_label = make_text('z', position=(0, 0, max(range_positions) * 2)) scene.add(x_axis_label) scene.add(y_axis_label) scene.add(z_axis_label) renderer = pjs.Renderer(scene=scene, camera=camera, controls=[orbit], width=view_width, height=view_height) camera.zoom = 1 display(renderer) return vertices, faces
def Plot3D(S, size=(800, 200), center=(0, 0, 0), rot=[(pi / 3., pi / 6., 0)], scale=1): """Function to create 3D interactive visualization widgets in a jupyter notebook Args: S: (:class:`~pyoptools.raytrace.system.System`, :class:`~pyoptools.raytrace.component.Component` or :class:`~pyoptools.raytrace.component.Component`) Object to plot size: (Tuple(float,float)) Field of view in X and Y for the window shown in the notebook. center: (Tuple(float,float,float) Coordinate of the center of the visualization window given in the coordinate system of the object to plot. rot: List of tuples. Each tuple describe an (Rx, Ry, Rz) rotation and are applied in order to generate the first view of the window. scale: (float) Scale factor applied to the rendered window Returns: pyjs renderer needed to show the image in the jupiter notebook. """ width, height = size light = py3js.DirectionalLight(color='#ffffff', intensity=.7, position=[0, 1000, 0]) alight = py3js.AmbientLight(color='#777777', ) # Set up a scene and render it: #cam = py3js.PerspectiveCamera(position=[0, 0, 500], fov=70, children=[light], aspect=width / height) pos = array((0, 0, 500)) for r in rot: pos = dot(rot_z(r[2]), pos) pos = dot(rot_y(r[1]), pos) pos = dot(rot_x(r[0]), pos) cam = py3js.OrthographicCamera(-width / 2 * scale, width / 2 * scale, height / 2 * scale, -height / 2 * scale, children=[light], position=list(pos), zoom=scale) if isinstance(S, System): c = sys2mesh(S) elif isinstance(S, Component): c = comp2mesh(S, (0, 0, 0), (0, 0, 0)) else: c = surf2mesh(S, (0, 0, 0), (0, 0, 0)) scene = py3js.Scene(children=[c, alight, cam], background="#000000") oc = py3js.OrbitControls(controlling=cam) oc.target = center renderer = py3js.Renderer(camera=cam, background='black', background_opacity=1, scene=scene, controls=[oc], width=width * scale, height=height * scale) return (renderer)
def __init__(self, obj, width=512, height=512, textureMap=None, scalarField=None, vectorField=None, superView=None, transparent=False): # Note: subclass's constructor should define # self.MeshConstructor and self.isLineMesh, which will # determine how the geometry is interpreted. if (not hasattr(self, "isLineMesh")): self.isLineMesh = False if (not hasattr(self, "isPointCloud")): self.isPointCloud = False if (self.MeshConstructor is None): self.MeshConstructor = pythreejs.Mesh light = pythreejs.PointLight(color='white', position=[0, 0, 5]) light.intensity = 0.6 self.cam = pythreejs.PerspectiveCamera(position=[0, 0, 5], up=[0, 1, 0], aspect=width / height, children=[light]) self.avoidRedrawFlicker = False self.objects = pythreejs.Group() self.meshes = pythreejs.Group() self.ghostMeshes = pythreejs.Group( ) # Translucent meshes kept around by preserveExisting self.ghostColor = 'red' self.materialLibrary = MaterialLibrary(self.isLineMesh, self.isPointCloud) # Sometimes we do not use a particular attribute buffer, e.g. the index buffer when displaying # per-face scalar fields. But to avoid reallocating these buffers when # switching away from these cases, we need to preserve the buffers # that may have previously been allocated. This is done with the bufferAttributeStash. # A buffer attribute, if it exists, must always be attached to the # current BufferGeometry or in this stash (but not both!). self.bufferAttributeStash = {} self.currMesh = None # The main mesh being viewed self.wireframeMesh = None # Wireframe for the main visualization mesh self.pointsMesh = None # Points for the main visualization mesh self.vectorFieldMesh = None self.cachedWireframeMaterial = None self.cachedPointsMaterial = None self.shouldShowWireframe = False self.scalarField = None self.vectorField = None self.superView = superView if (superView is None): self.objects.add([self.meshes, self.ghostMeshes]) else: superView.objects.add([self.meshes, self.ghostMeshes]) self.subviews = [] self._arrowMaterial = None # Will hold this viewer's instance of the special vector field shader (shared/overridden by superView) self._arrowSize = 60 # Camera needs to be part of the scene because the scene light is its child # (so that it follows the camera). self.scene = pythreejs.Scene(children=[ self.objects, self.cam, pythreejs.AmbientLight(intensity=0.5) ]) if (superView is None): # Sane trackball controls. self.controls = pythreejs.TrackballControls(controlling=self.cam) self.controls.staticMoving = True self.controls.rotateSpeed = 2.0 self.controls.zoomSpeed = 2.0 self.controls.panSpeed = 1.0 self.renderer = pythreejs.Renderer(camera=self.cam, scene=self.scene, controls=[self.controls], width=width, height=height) else: self.controls = superView.controls self.renderer = superView.renderer self.update(True, obj, updateModelMatrix=True, textureMap=textureMap, scalarField=scalarField, vectorField=vectorField, transparent=transparent)
def create_jsrenderer(scene, height=400, width=400, background='gray', orthographic=False, camera_position=(0, 0, -10), view=(10, -10, -10, 10), fov=50): """ Properties ---------- orthographic : bool use orthographic camera (True) or perspective (False) camera_position : tuple position of camera in scene view : tuple view extents: (top, bottom, left, right) (orthographic only) fov : float camera field of view (perspective only) Returns ------- camera : pythreejs.Camera renderer : pythreejs.Renderer Examples -------- >>> import pythreejs as js >>> scene = js.Scene(children=[js.AmbientLight(color='#777777')]) >>> camera, renderer = create_jsrenderer(scene,200,200, 'gray', (1,-1,-1,1)) >>> type(renderer) <class 'pythreejs.pythreejs.Renderer'> >>> type(camera) <class 'pythreejs.pythreejs.OrthographicCamera'> """ if orthographic: top, bottom, left, right = view camera = js.OrthographicCamera(position=camera_position, up=[0, 0, 1], top=top, bottom=bottom, left=left, right=right, near=.1, far=2000) else: camera = js.PerspectiveCamera(position=camera_position, up=[0, 0, 1], far=2000, near=.1, fov=fov, aspect=width / float(height)) camera.children = [ js.DirectionalLight(color='white', position=[3, 5, 1], intensity=0.5) ] control = js.OrbitControls(controlling=camera) renderer = js.Renderer(camera=camera, background=background, background_opacity=.1, height=str(height), width=str(width), scene=scene, controls=[control]) return camera, renderer
def __init__(self, scipp_obj_dict=None, positions=None, axes=None, masks=None, cmap=None, log=None, vmin=None, vmax=None, color=None, aspect=None, background=None, nan_color=None, pixel_size=None, tick_size=None, show_outline=True): super().__init__(scipp_obj_dict=scipp_obj_dict, positions=positions, axes=axes, masks=masks, cmap=cmap, log=log, vmin=vmin, vmax=vmax, color=color, aspect=aspect, button_options=['X', 'Y', 'Z']) self.vslice = None self.current_cut_surface_value = None self.cut_slider_steps = 10. self.cbar_image = widgets.Image() self.cut_options = { "Xplane": 0, "Yplane": 1, "Zplane": 2, "Xcylinder": 3, "Ycylinder": 4, "Zcylinder": 5, "Sphere": 6, "Value": 7 } # Prepare colormaps self.cmap = copy(cm.get_cmap(self.params["values"][self.name]["cmap"])) self.cmap.set_bad(color=nan_color) self.scalar_map = cm.ScalarMappable( norm=self.params["values"][self.name]["norm"], cmap=self.cmap) self.masks_scalar_map = None if self.params["masks"][self.name]["show"]: self.masks_cmap = copy( cm.get_cmap(self.params["masks"][self.name]["cmap"])) self.masks_cmap.set_bad(color=nan_color) self.masks_scalar_map = cm.ScalarMappable( norm=self.params["values"][self.name]["norm"], cmap=self.masks_cmap) # Generate the colorbar image self.create_colorbar() # Useful variables self.permutations = {"x": ["y", "z"], "y": ["x", "z"], "z": ["x", "y"]} self.remaining_inds = [0, 1] # Search the coordinates to see if one contains vectors. If so, it will # be used as position vectors. self.axlabels = {"x": "", "y": "", "z": ""} self.positions = None self.pixel_size = pixel_size self.tick_size = tick_size if positions is not None: coord = self.data_array.coords[positions] self.positions = np.array(coord.values, dtype=np.float32) self.axlabels.update({ "x": name_with_unit(coord, name="X"), "y": name_with_unit(coord, name="Y"), "z": name_with_unit(coord, name="Z") }) else: # If no positions are supplied, create a meshgrid from coordinate # axes. coords = [] labels = [] for dim, val in self.slider.items(): if val.disabled: arr = self.slider_coord[self.name][dim] if self.histograms[self.name][dim][dim]: arr = to_bin_centers(arr, dim) coords.append(arr.values) labels.append( name_with_unit(self.slider_coord[self.name][dim])) z, y, x = np.meshgrid(*coords, indexing='ij') self.positions = np.array( [x.ravel(), y.ravel(), z.ravel()], dtype=np.float32).T if self.pixel_size is None: self.pixel_size = coords[0][1] - coords[0][0] self.axlabels.update({ "z": labels[0], "y": labels[1], "x": labels[2] }) # Find spatial and value limits self.xminmax, self.center_of_mass = self.get_spatial_extents() self.vminmax = [ sc.min(self.data_array.data).value, sc.max(self.data_array.data).value ] # Create the point cloud with pythreejs self.points_geometry, self.points_material, self.points = \ self.create_points_geometry() # Create outline around point positions self.outline, self.axticks = self.create_outline() # Save the size of the outline box for later self.box_size = np.diff(list(self.xminmax.values()), axis=1).ravel() # Define camera: look at the centre of mass of the points camera_lookat = self.center_of_mass camera_pos = np.array(self.center_of_mass) + 1.2 * self.box_size self.camera = p3.PerspectiveCamera(position=list(camera_pos), aspect=config.plot.width / config.plot.height) # Add red/green/blue axes helper self.axes_3d = p3.AxesHelper(10.0 * np.linalg.norm(camera_pos)) # Create the pythreejs scene self.scene = p3.Scene(children=[ self.camera, self.axes_3d, self.points, self.outline, self.axticks ], background=background) # Add camera controller self.controller = p3.OrbitControls(controlling=self.camera, target=camera_lookat) self.camera.lookAt(camera_lookat) # Render the scene into a widget self.renderer = p3.Renderer(camera=self.camera, scene=self.scene, controls=[self.controller], width=config.plot.width, height=config.plot.height) # Update visibility of outline according to keyword arg self.outline.visible = show_outline self.axticks.visible = show_outline # Opacity slider: top value controls opacity if no cut surface is # active. If a cut curface is present, the upper slider is the opacity # of the slice, while the lower slider value is the opacity of the # data not in the cut surface. self.opacity_slider = widgets.FloatRangeSlider( min=0.0, max=1.0, value=[0.1, 1], step=0.01, description="Opacity slider: When no cut surface is active, the " "max value of the range slider controls the overall opacity, " "and the lower value has no effect. When a cut surface is " "present, the max value is the opacity of the slice, while the " "min value is the opacity of the background.", continuous_update=True, style={'description_width': '60px'}) self.opacity_slider.observe(self.update_opacity, names="value") self.opacity_checkbox = widgets.Checkbox( value=self.opacity_slider.continuous_update, description="Continuous update", indent=False, layout={"width": "20px"}) self.opacity_checkbox_link = widgets.jslink( (self.opacity_checkbox, 'value'), (self.opacity_slider, 'continuous_update')) self.toggle_outline_button = widgets.ToggleButton(value=show_outline, description='', button_style='') self.toggle_outline_button.observe(self.toggle_outline, names="value") # Run a trigger to update button text self.toggle_outline({"new": show_outline}) # Add buttons to provide a choice of different cut surfaces: # - Cartesian X, Y, Z # - Cylindrical X, Y, Z (cylinder major axis) # - Sperical R # - Value-based iso-surface # Note additional spaces required in cylindrical names because # options must be unique. self.cut_surface_buttons = widgets.ToggleButtons( options=[('X ', self.cut_options["Xplane"]), ('Y ', self.cut_options["Yplane"]), ('Z ', self.cut_options["Zplane"]), ('R ', self.cut_options["Sphere"]), (' X ', self.cut_options["Xcylinder"]), (' Y ', self.cut_options["Ycylinder"]), (' Z ', self.cut_options["Zcylinder"]), ('', self.cut_options["Value"])], value=None, description='Cut surface:', button_style='', tooltips=[ 'X-plane', 'Y-plane', 'Z-plane', 'Sphere', 'Cylinder-X', 'Cylinder-Y', 'Cylinder-Z', 'Value' ], icons=(['cube'] * 3) + ['circle-o'] + (['toggle-on'] * 3) + ['magic'], style={"button_width": "55px"}, layout={'width': '350px'}) self.cut_surface_buttons.observe(self.update_cut_surface_buttons, names="value") # Add a capture for a click event: if the active button is clicked, # this resets the togglebuttons value to None and deletes the cut # surface. self.cut_surface_buttons.on_msg(self.check_if_reset_needed) # Add slider to control position of cut surface self.cut_slider = widgets.FloatSlider(min=0, max=1, description="Position:", disabled=True, value=0.5, layout={"width": "350px"}) self.cut_checkbox = widgets.Checkbox(value=True, description="Continuous update", indent=False, layout={"width": "20px"}, disabled=True) self.cut_checkbox_link = widgets.jslink( (self.cut_checkbox, 'value'), (self.cut_slider, 'continuous_update')) self.cut_slider.observe(self.update_cut_surface, names="value") # Allow to change the thickness of the cut surface self.cut_surface_thickness = widgets.BoundedFloatText( value=0.05 * self.box_size.max(), min=0, layout={"width": "150px"}, disabled=True, description="Thickness:", style={'description_width': 'initial'}) self.cut_surface_thickness.observe(self.update_cut_surface, names="value") self.cut_thickness_link = widgets.jslink( (self.cut_slider, 'step'), (self.cut_surface_thickness, 'value')) self.cut_slider.observe(self.update_cut_surface, names="value") # Put widgets into boxes self.cut_surface_controls = widgets.HBox([ self.cut_surface_buttons, widgets.VBox([ widgets.HBox([self.cut_slider, self.cut_checkbox]), self.cut_surface_thickness ]) ]) self.box = widgets.VBox([ widgets.HBox([self.renderer, self.cbar_image]), widgets.VBox(self.vbox), widgets.HBox([ self.opacity_slider, self.opacity_checkbox, self.toggle_outline_button ]), self.cut_surface_controls ]) # Update list of members to be returned in the SciPlot object self.members.update({ "camera": self.camera, "scene": self.scene, "renderer": self.renderer }) return
def display_scene(lm_scene): """Display Lightmetrica scene.""" # Scene scene = three.Scene() # Camera # Get lm camera information lm_main_camera = lm_scene.camera() lm_camera_params = lm_main_camera.underlying_value() camera = three.PerspectiveCamera(fov=lm_camera_params['vfov'], aspect=lm_camera_params['aspect'], near=0.1, far=10000) camera.position = lm_camera_params['eye'] camera.up = lm_camera_params['up'] scene.add(camera) # Mesh def add_lm_scene_mesh(): # Default material mat_default = three.MeshBasicMaterial(color='#000000', wireframe=True, transparent=True, opacity=0.2, depthTest=False) # Convert lm mesh def traverse_func(node, trans): # Underlying mesh mesh = node.primitive.mesh if mesh is None: return # Iterate through all triangles vs = [] def process_triangle(face_index, tri): vs.append(list(tri.p1.p)) vs.append(list(tri.p2.p)) vs.append(list(tri.p3.p)) mesh.foreach_triangle(process_triangle) # Create geometry ps_attr = three.BufferAttribute(array=vs, normalized=False) geom = three.BufferGeometry(attributes={'position': ps_attr}) # Create mesh mesh = three.Mesh(geometry=geom, material=mat_default) mesh.matrixAutoUpdate = False mesh.matrix = trans.T.flatten().tolist() scene.add(mesh) lm_scene.traverse_primitive_nodes(traverse_func) add_lm_scene_mesh() # View frustum def add_view_frustum(): position = np.array(lm_camera_params['eye']) center = np.array(lm_camera_params['center']) up = np.array(lm_camera_params['up']) aspect = lm_camera_params['aspect'] fov = math.radians(lm_camera_params['vfov']) M = lookat_matrix(position, center, up) z = 5 half_fov = fov * .5 y = math.tan(half_fov) * z x = aspect * y p = list(position) p1 = list(position + np.dot(M, [-x, -y, -z])) p2 = list(position + np.dot(M, [x, -y, -z])) p3 = list(position + np.dot(M, [x, y, -z])) p4 = list(position + np.dot(M, [-x, y, -z])) # Add mesh geom = three.Geometry( vertices=[p, p1, p2, p, p2, p3, p, p3, p4, p, p4, p1]) mat = three.MeshBasicMaterial(color='#00ff00', wireframe=True, side='DoubleSide') mesh = three.Line(geometry=geom, material=mat) scene.add(mesh) add_view_frustum() # Axis axes = three.AxesHelper(size=1) scene.add(axes) # Renderer controls = three.OrbitControls(controlling=camera) # Rendered image size w = 1000 h = w / lm_camera_params['aspect'] # We need to set both target and lookAt in this order. # Otherwise the initial target position becomes wrong. # cf. https://github.com/jupyter-widgets/pythreejs/issues/200 controls.target = lm_camera_params['center'] camera.lookAt(lm_camera_params['center']) renderer = three.Renderer(camera=camera, scene=scene, width=w, height=h, controls=[controls]) # Button to reset camera configuration # Note that we need to press the button twice to reset the control # to the correct target possibly due to the bug of pythreejs. reset_camera_button = widgets.Button(description="Reset Camera") @reset_camera_button.on_click def reset_camera_button_on_click(b): controls.reset() controls.target = lm_camera_params['center'] camera.lookAt(lm_camera_params['center']) # Display all display(reset_camera_button) display(renderer) return scene, camera, renderer
def generate_3js_render( element_groups, canvas_size, zoom, camera_fov=30, background_color="white", background_opacity=1.0, reuse_objects=False, use_atom_arrays=False, use_label_arrays=False, ): """Create a pythreejs scene of the elements. Regarding initialisation performance, see: https://github.com/jupyter-widgets/pythreejs/issues/154 """ import pythreejs as pjs key_elements = {} group_elements = pjs.Group() key_elements["group_elements"] = group_elements unique_atom_sets = {} for el in element_groups["atoms"]: element_hash = ( ("radius", el.sradius), ("color", el.color), ("fill_opacity", el.fill_opacity), ("stroke_color", el.get("stroke_color", "black")), ("ghost", el.ghost), ) unique_atom_sets.setdefault(element_hash, []).append(el) group_atoms = pjs.Group() group_ghosts = pjs.Group() atom_geometries = {} atom_materials = {} outline_materials = {} for el_hash, els in unique_atom_sets.items(): el = els[0] data = dict(el_hash) if reuse_objects: atom_geometry = atom_geometries.setdefault( el.sradius, pjs.SphereBufferGeometry(radius=el.sradius, widthSegments=30, heightSegments=30), ) else: atom_geometry = pjs.SphereBufferGeometry(radius=el.sradius, widthSegments=30, heightSegments=30) if reuse_objects: atom_material = atom_materials.setdefault( (el.color, el.fill_opacity), pjs.MeshLambertMaterial(color=el.color, transparent=True, opacity=el.fill_opacity), ) else: atom_material = pjs.MeshLambertMaterial(color=el.color, transparent=True, opacity=el.fill_opacity) if use_atom_arrays: atom_mesh = pjs.Mesh(geometry=atom_geometry, material=atom_material) atom_array = pjs.CloneArray( original=atom_mesh, positions=[e.position.tolist() for e in els], merge=False, ) else: atom_array = [ pjs.Mesh( geometry=atom_geometry, material=atom_material, position=e.position.tolist(), name=e.info_string, ) for e in els ] data["geometry"] = atom_geometry data["material_body"] = atom_material if el.ghost: key_elements["group_ghosts"] = group_ghosts group_ghosts.add(atom_array) else: key_elements["group_atoms"] = group_atoms group_atoms.add(atom_array) if el.get("stroke_width", 1) > 0: if reuse_objects: outline_material = outline_materials.setdefault( el.get("stroke_color", "black"), pjs.MeshBasicMaterial( color=el.get("stroke_color", "black"), side="BackSide", transparent=True, opacity=el.get("stroke_opacity", 1.0), ), ) else: outline_material = pjs.MeshBasicMaterial( color=el.get("stroke_color", "black"), side="BackSide", transparent=True, opacity=el.get("stroke_opacity", 1.0), ) # TODO use stroke width to dictate scale if use_atom_arrays: outline_mesh = pjs.Mesh( geometry=atom_geometry, material=outline_material, scale=(1.05, 1.05, 1.05), ) outline_array = pjs.CloneArray( original=outline_mesh, positions=[e.position.tolist() for e in els], merge=False, ) else: outline_array = [ pjs.Mesh( geometry=atom_geometry, material=outline_material, position=e.position.tolist(), scale=(1.05, 1.05, 1.05), ) for e in els ] data["material_outline"] = outline_material if el.ghost: group_ghosts.add(outline_array) else: group_atoms.add(outline_array) key_elements.setdefault("atom_arrays", []).append(data) group_elements.add(group_atoms) group_elements.add(group_ghosts) group_labels = add_labels(element_groups, key_elements, use_label_arrays) group_elements.add(group_labels) if len(element_groups["cell_lines"]) > 0: cell_line_mat = pjs.LineMaterial( linewidth=1, color=element_groups["cell_lines"].group_properties["color"]) cell_line_geo = pjs.LineSegmentsGeometry(positions=[ el.position.tolist() for el in element_groups["cell_lines"] ]) cell_lines = pjs.LineSegments2(geometry=cell_line_geo, material=cell_line_mat) key_elements["cell_lines"] = cell_lines group_elements.add(cell_lines) if len(element_groups["bond_lines"]) > 0: bond_line_mat = pjs.LineMaterial( linewidth=element_groups["bond_lines"]. group_properties["stroke_width"], vertexColors="VertexColors", ) bond_line_geo = pjs.LineSegmentsGeometry( positions=[ el.position.tolist() for el in element_groups["bond_lines"] ], colors=[[Color(c).rgb for c in el.color] for el in element_groups["bond_lines"]], ) bond_lines = pjs.LineSegments2(geometry=bond_line_geo, material=bond_line_mat) key_elements["bond_lines"] = bond_lines group_elements.add(bond_lines) group_millers = pjs.Group() if len(element_groups["miller_lines"]) or len( element_groups["miller_planes"]): key_elements["group_millers"] = group_millers if len(element_groups["miller_lines"]) > 0: miller_line_mat = pjs.LineMaterial( linewidth=3, vertexColors="VertexColors" # TODO use stroke_width ) miller_line_geo = pjs.LineSegmentsGeometry( positions=[ el.position.tolist() for el in element_groups["miller_lines"] ], colors=[[Color(el.stroke_color).rgb] * 2 for el in element_groups["miller_lines"]], ) miller_lines = pjs.LineSegments2(geometry=miller_line_geo, material=miller_line_mat) group_millers.add(miller_lines) for el in element_groups["miller_planes"]: vertices = el.position.tolist() faces = [( 0, 1, 2, triangle_normal(vertices[0], vertices[1], vertices[2]), "black", 0, )] if len(vertices) == 4: faces.append(( 2, 3, 0, triangle_normal(vertices[2], vertices[3], vertices[0]), "black", 0, )) elif len(vertices) != 3: raise NotImplementedError("polygons with more than 4 points") plane_geom = pjs.Geometry(vertices=vertices, faces=faces) plane_mat = pjs.MeshBasicMaterial( color=el.fill_color, transparent=True, opacity=el.fill_opacity, side="DoubleSide", ) plane_mesh = pjs.Mesh(geometry=plane_geom, material=plane_mat) group_millers.add(plane_mesh) group_elements.add(group_millers) scene = pjs.Scene(background=None) scene.add([group_elements]) view_width, view_height = canvas_size minp, maxp = element_groups.get_position_range() # compute a minimum camera distance, that is guaranteed to encapsulate all elements camera_dist = maxp[2] + sqrt(maxp[0]**2 + maxp[1]**2) / tan( radians(camera_fov / 2)) camera = pjs.PerspectiveCamera( fov=camera_fov, position=[0, 0, camera_dist], aspect=view_width / view_height, zoom=zoom, ) scene.add([camera]) ambient_light = pjs.AmbientLight(color="lightgray") key_elements["ambient_light"] = ambient_light direct_light = pjs.DirectionalLight(position=(maxp * 2).tolist()) key_elements["direct_light"] = direct_light scene.add([camera, ambient_light, direct_light]) camera_control = pjs.OrbitControls(controlling=camera, screenSpacePanning=True) atom_picker = pjs.Picker(controlling=group_atoms, event="dblclick") key_elements["atom_picker"] = atom_picker material = pjs.SpriteMaterial( map=create_arrow_texture(right=False), transparent=True, depthWrite=False, depthTest=False, ) atom_pointer = pjs.Sprite(material=material, scale=(4, 3, 1), visible=False) scene.add(atom_pointer) key_elements["atom_pointer"] = atom_pointer renderer = pjs.Renderer( camera=camera, scene=scene, controls=[camera_control, atom_picker], width=view_width, height=view_height, alpha=True, clearOpacity=background_opacity, clearColor=background_color, ) return renderer, key_elements
def create_world_axes(camera, controls, initial_rotation=np.eye(3), length=30, width=3, camera_fov=10): """Create a renderer, containing an axes and camera that is synced to another camera. adapted from http://jsfiddle.net/aqnL1mx9/ Parameters ---------- camera : pythreejs.PerspectiveCamera controls : pythreejs.OrbitControls initial_rotation : list or numpy.array initial rotation of the axes length : int length of axes lines width : int line width of axes Returns ------- pythreejs.Renderer """ import pythreejs as pjs canvas_width = length * 2 canvas_height = length * 2 ax_scene = pjs.Scene() group_ax = pjs.Group() # NOTE: could use AxesHelper, but this does not allow for linewidth seletion # TODO: add arrow heads (ArrowHelper doesn't seem to work) ax_line_mat = pjs.LineMaterial(linewidth=width, vertexColors="VertexColors") ax_line_geo = pjs.LineSegmentsGeometry( positions=[[[0, 0, 0], length * r / np.linalg.norm(r)] for r in initial_rotation], colors=[[Color(c).rgb] * 2 for c in ("red", "green", "blue")], ) ax_lines = pjs.LineSegments2(geometry=ax_line_geo, material=ax_line_mat) group_ax.add(ax_lines) ax_scene.add([group_ax]) camera_dist = length / tan(radians(camera_fov / 2)) ax_camera = pjs.PerspectiveCamera(fov=camera_fov, aspect=canvas_width / canvas_height, near=1, far=1000) ax_camera.up = camera.up ax_renderer = pjs.Renderer( scene=ax_scene, camera=ax_camera, width=canvas_width, height=canvas_height, alpha=True, clearOpacity=0.0, clearColor="white", ) def align_axes(change=None): """Align axes to world.""" # TODO: this is not working correctly for TrackballControls, when rotated upside-down # (OrbitControls enforces the camera up direction, # so does not allow the camera to rotate upside-down). # TODO how could this be implemented on the client (js) side? new_position = np.array(camera.position) - np.array(controls.target) new_position = camera_dist * new_position / np.linalg.norm( new_position) ax_camera.position = new_position.tolist() ax_camera.lookAt(ax_scene.position) align_axes() camera.observe(align_axes, names="position") controls.observe(align_axes, names="target") ax_scene.observe(align_axes, names="position") return ax_renderer