Ejemplo n.º 1
0
def axes(max_dist, axis_rad=0.25, axis_color='yellow'):
    """
    Generate X, Y, Z axes of length max_width in the form of a pythreejs
    Line object.

    Parameters
    ----------
    max_dist : float
                maximum extent of grid from origin in each dimension
    axis_rad : float
                radius of cylinder representing each axis (default: 0.25)
    axis_color : color
                color the axes are drawn in (default: 'yellow')

    Returns
    -------
    Xaxis, Yaxis, Zaxis : pythreejs.Mesh*3
            Three pythreejs Mesh objects representing the x, y, and z axes.
    """
    Xaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, 
                                                height=max_dist, 
                                                radiusSegments=12, 
                                                heightSegments=1, 
                                                openEnded=False, 
                                                thetaStart=0, thetaLength=2*np.pi), 
                material=p3j.MeshBasicMaterial(color=axis_color),
                position=[max_dist/2, 0, 0])
    Xaxis.rotateZ(np.pi/2)
    
    Yaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, 
                                                height=max_dist, 
                                                radiusSegments=12, 
                                                heightSegments=1, 
                                                openEnded=False, 
                                                thetaStart=0, thetaLength=2*np.pi), 
                material=p3j.MeshBasicMaterial(color=axis_color),
                position=[0, max_dist/2, 0])
    
    Zaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, 
                                                height=max_dist, 
                                                radiusSegments=12, 
                                                heightSegments=1, 
                                                openEnded=False, 
                                                thetaStart=0, thetaLength=2*np.pi), 
                material=p3j.MeshBasicMaterial(color=axis_color),
                position=[0, 0, max_dist/2])
    Zaxis.rotateX(np.pi/2)

    return Xaxis, Yaxis, Zaxis
Ejemplo n.º 2
0
        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)
Ejemplo n.º 3
0
    def _ipython_display_(self):
        # This needs to actually display, which is not the same as returning a display.
        cam = pythreejs.PerspectiveCamera(
            position=[25, 35, 100],
            fov=20,
            children=[pythreejs.AmbientLight()],
        )
        children = [cam, pythreejs.AmbientLight(color="#dddddd")]
        material = pythreejs.MeshBasicMaterial(color="#ff0000",
                                               vertexColors="VertexColors",
                                               side="DoubleSide")
        for model in self.components:
            mesh = pythreejs.Mesh(geometry=model.geometry,
                                  material=material,
                                  position=[0, 0, 0])
            children.append(mesh)

        scene = pythreejs.Scene(children=children)

        rendererCube = pythreejs.Renderer(
            camera=cam,
            background="white",
            background_opacity=1,
            scene=scene,
            controls=[pythreejs.OrbitControls(controlling=cam)],
            width=800,
            height=800,
        )

        return rendererCube
Ejemplo n.º 4
0
    def _make_threejs_primitive(self):
        geometry = pythreejs.BufferGeometry()
        material = pythreejs.MeshStandardMaterial(
            vertexColors=pythreejs.enums.Colors.VertexColors, metalness=0.05, roughness=.9)
        result = pythreejs.Mesh(geometry, material)

        return result
Ejemplo n.º 5
0
    def __init__(self, trimesh, uvs, width=512, height=512, duration=5, textureMap = None):
        self.viewer = TriMeshViewer(trimesh, width, height, textureMap)

        flatPosArray = None
        if (uvs.shape[1] == 2): flatPosArray = np.array(np.pad(uvs, [(0, 0), (0, 1)], 'constant'), dtype=np.float32)
        else:                   flatPosArray = np.array(uvs, dtype=np.float32)
        flatPos     = pythreejs.BufferAttribute(array=flatPosArray, normalized=False)
        flatNormals = pythreejs.BufferAttribute(array=np.repeat(np.array([[0, 0, 1]], dtype=np.float32), uvs.shape[0], axis=0), normalized=False)

        geom = self.viewer.currMesh.geometry
        mat  = self.viewer.currMesh.material
        geom.morphAttributes = {'position': [flatPos,], 'normal': [flatNormals,]}

        # Both of these material settings are needed or else our target positions/normals are ignored!
        mat.morphTargets, mat.morphNormals = True, True

        flatteningMesh = pythreejs.Mesh(geometry=geom, material=mat)

        amplitude = np.linspace(-1, 1, 20, dtype=np.float32)
        times = (np.arcsin(amplitude) / np.pi + 0.5) * duration
        blendWeights = 0.5 * (amplitude + 1)
        track = pythreejs.NumberKeyframeTrack('name=.morphTargetInfluences[0]', times = times, values = blendWeights, interpolation='InterpolateSmooth')

        self.action = pythreejs.AnimationAction(pythreejs.AnimationMixer(flatteningMesh),
                                                pythreejs.AnimationClip(tracks=[track]),
                                                flatteningMesh, loop='LoopPingPong')

        self.viewer.meshes.children = [flatteningMesh]

        self.layout = ipywidgets.VBox()
        self.layout.children = [self.viewer.renderer, self.action]
Ejemplo n.º 6
0
    def getArrows(self, visVertices, visTris, vmin = None, vmax = None, alpha = 1.0, material=None, existingMesh=None):
        vectors, colors, mask = self.arrowData(vmin, vmax, alpha)
        V, N, F = self.arrowGeometry()
        pos = None
        if (self.domainType == DomainType.PER_VTX): pos = visVertices
        if (self.domainType == DomainType.PER_TRI): pos = np.mean(visVertices[visTris], axis=1) # triangle barycenters
        pos = pos[mask]

        if (pos is None): raise Exception('Unhandled domainType')

        if (material is None): material = vis.shaders.loadShaderMaterial('vector_field')

        rawInstancedAttr = {'arrowColor': np.array(colors,  dtype=np.float32),
                            'arrowVec':   np.array(vectors, dtype=np.float32),
                            'arrowPos':   np.array(pos,     dtype=np.float32)}
        rawAttr = {'position': V,
                   'index':    F.ravel(),
                   'normal':   N}

        arrowMesh = None
        if (existingMesh is None):
            attr =      {k: pythreejs.InstancedBufferAttribute(v) for k, v in rawInstancedAttr.items()}
            attr.update({k: pythreejs.         BufferAttribute(v) for k, v in         rawAttr.items()})
            ibg = pythreejs.InstancedBufferGeometry(attributes=attr)
            arrowMesh = pythreejs.Mesh(geometry=ibg, material=material, frustumCulled=False) # disable frustum culling since our vertex shader moves arrows around.
        else:
            for k, v in rawInstancedAttr.items(): # position/index/normal should be constant...
                existingMesh.geometry.attributes[k].array = v
            arrowMesh = existingMesh
            existingMesh.geometry.maxInstancedCount = pos.shape[0] # threejs does not automatically update maxInstancedCount after it is initialized to the full count of the original arrays by the renderer

        return arrowMesh
Ejemplo n.º 7
0
def xyplane(max_dist, grid_space):
    """
    Generates and returns two pythreejs items: a mesh of a flat surface and a
    SurfaceGrid object, both representing the xy plane.

    NOTE: max_dist will be rounded UP to next grid_space position (e.g. if
       yoru submit a max_width of 38 but a grid_space of 5, the max_width will
       be silently rounded up to 40 to allow an integer number of grids).

    Keyword arguments:
    max_dist (float): Maximum extent of grid from origin in each dimension
    grid_space (float): The grid spacing in system units.


    Parameters
    ----------
    max_dist : float
                maximum extent of grid from origin in each dimension
    grid_space : float
            the grid spacing in system units.

    Returns
    -------
    surface : pythreejs.Mesh
                a  pythreejs Mesh object representing the xy plane.
    surf_grid : pythreejs.SurfaceGrid
                a  pythreejs SurfaceGrid object for the grid on the xy plane.
    """

    # Determine the gridsize to use, adding one additional step if necessary
    x_steps = int(np.ceil(max_dist / grid_space))
    xmax = x_steps * grid_space

    # Number of vertices (subtract one for number of boxes shown)
    nx, ny = (2 * x_steps + 1, 2 * x_steps + 1)
    x = np.linspace(-xmax, xmax, nx)
    y = np.linspace(-xmax, xmax, ny)
    xx, yy = np.meshgrid(x, y)
    z = 0 * xx + 0 * yy

    # Generate the 3D surface and surface grid to return
    surf_g = p3j.SurfaceGeometry(z=list(z[::-1].flat),
                                 width=2 * xmax,
                                 height=2 * xmax,
                                 width_segments=nx - 1,
                                 height_segments=ny - 1)
    surface_material = p3j.MeshBasicMaterial(color='darkslategrey',
                                             transparent=True,
                                             opacity=0.5)
    surf = p3j.Mesh(geometry=surf_g, material=surface_material)
    grid_material = p3j.LineBasicMaterial(color='grey')

    # To avoid overlap, lift grid slightly above the plane scaling
    # by size of grid
    surfgrid = p3j.SurfaceGrid(geometry=surf_g,
                               material=grid_material,
                               position=[0, 0, 1e-2 * max_dist])

    return surf, surfgrid
Ejemplo n.º 8
0
def draw_mesh(mesh, color=None):
    vertices, faces = mesh.to_vertices_and_faces()
    hexcolor = rgb_to_hex(color[:3]) if color else '#cccccc'
    vertexcolors = [hexcolor] * len(vertices)
    faces = [f + [None, [vertexcolors[i] for i in f], None] for f in faces]
    geo = p3js.Geometry(vertices=vertices, faces=faces)
    geo.exec_three_obj_method('computeFaceNormals')
    return p3js.Mesh(geometry=geo, material=p3js.MeshLambertMaterial(vertexColors='VertexColors'), position=[0, 0, 0])
Ejemplo n.º 9
0
    def mesh(self):
        import numpy as np
        import pythreejs as js

        wireframe = self.view_data.get('wireframe', False)

        def triangles(polygon):
            points = polygon.points
            return [(points[0], points[ix], points[ix + 1])
                    for ix in range(1, len(polygon.points) - 1)]

        def _ba(vs):
            points = np.array(vs, dtype=np.float32)
            return js.BufferAttribute(array=points, normalized=False)

        vertices = [
            list(p.xyz) for polygon in self.polygons
            for t in triangles(polygon)
            for p in t
        ]
        normals = [
            list(polygon.plane.normal.xyz) for polygon in self.polygons
            for t in triangles(polygon)
            for p in t
        ]

        geometry = js.BufferGeometry(
            attributes={
                'position': _ba(vertices),
                'normal': _ba(normals)
            },
        )

        if not wireframe:
            color = self.view_data.get('color', 'white')
            material = material=js.MeshLambertMaterial(color=color)
            opacity = self.view_data.get('opacity')
            if opacity is not None:
                material.opacity = opacity
                material.transparent = True
            return js.Mesh(geometry, material)
        else:
            color = self.view_data.get('color', '#00ff00')
            material = js.MeshBasicMaterial(color=color, wireframe=True)
            return js.Mesh(geometry, material)
Ejemplo n.º 10
0
def OldStarMesh(temp=Te_Sun, rad=1,  scale=(1, 1, 1), pos=[0, 0, 0]):
    """
    This function creates a pythreejs object that represents a star using
    a texture based on public domain STEREO Heliographic map made with
    images taken of the Sun on Dec. 30, 2011.  Image downloaded from
       https://stereo.gsfc.nasa.gov/360blog/
    and had its brightness and resolution rescaled.

    Parameters
    ----------
    temp : float
            temperature of star in Kelvin (default 5777)
    rad : float
            radius of the star in system units (default 1)
    scale : tuple
             pythreejs scale in each dimension as tuple (default (1, 1, 1) )
    pos : list
           three-dimensional position as list (default [0, 0, 0] )

    Returns
    -------
    star : pythreejs.Mesh
              a spherical pythreejs Mesh object representing a star
    """

    # Check is position is a list
    if isinstance(pos, list):
        # Check if this is a list of 3 items
        if (len(pos) != 3):
            raise TypeError('pos passed to StarMesh must be list of 3 numbers')
        # Check that all the items in the list are numbers
        for this_pos in pos:
            try:
                i = float(this_pos)
            except ValueError:
                raise TypeError('ValueError: pos contains list item that is not a number.')
    else:
        raise TypeError('pos passed to StarMesh must be list of 3 numbers')

    # Check is scale is a tuple
    if isinstance(scale, tuple):
        if (len(scale) != 3):
            raise TypeError('scale passed to StarMesh must be tuple of 3 numbers')
    else:
        raise TypeError('scale must be a tuple')

    # Define color and texture of star surface
    hexcolor = tc.rgb2hex(tc.temp2rgb(float(temp)))[0]
    StarTexture = p3j.ImageTexture(imageUri='images/sun_surface.jpg')

    # Create sphere using MeshBasicMaterial (which is unaffected by lighting)
    StarSurface = p3j.MeshBasicMaterial(color=hexcolor, map=StarTexture)

    StarGeom = p3j.SphereBufferGeometry(radius=rad, widthSegments=32,
                                        heightSegments=16)
    return p3j.Mesh(geometry=StarGeom, material=StarSurface,
                    position=pos, scale=scale)
Ejemplo n.º 11
0
def test_cylinder():

    cylinder = Cylinder(10.0,
                        5.0,
                        name='cylinder',
                        color='blue',
                        material="METAL")
    assert cylinder.name == 'cylinder'
    assert cylinder.__str__() == \
        'Cylinder cylinder color:blue material:METAL length:10.0 radius:5.0'
    assert cylinder.__repr__() == 'Cylinder'
    assert cylinder.length == 10.0
    assert cylinder.radius == 5.0
    assert cylinder.color == 'blue'

    if p3js is not None:
        mesh = cylinder._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.CylinderBufferGeometry(radiusTop=5.0,
                                                              radiusBottom=5.0,
                                                              height=10.0),
                                  p3js.MeshStandardMaterial(color='blue'),
                                  name='cylinder')
        assert repr(mesh) == repr(expected_mesh)

    cylinder.name = 'cylinder1'
    assert cylinder.name == 'cylinder1'

    cylinder.length = 14.0
    assert cylinder.length == 14.0

    cylinder.radius = 7.0
    assert cylinder.radius == 7.0

    cylinder.color = 'cyan'
    assert cylinder.color == 'cyan'

    cylinder.material = 'FOIL'
    assert cylinder.material == 'FOIL'
    assert cylinder.generate_dict() == {
        "color": "cyan",
        "type": "Cylinder",
        "name": "cylinder1",
        "length": 14.0,
        "radius": 7.0,
        "material": "FOIL"
    }

    assert isinstance(cylinder, Shape)

    cylinder_ = Cylinder(10.0, 5.0, color='blue')
    assert cylinder_.name == 'unnamed'
    assert cylinder_.__str__() == \
        'Cylinder unnamed color:blue material:default length:10.0 radius:5.0'

    assert cylinder_.__repr__() == 'Cylinder'
Ejemplo n.º 12
0
 def showWireframe(self, shouldShow = True):
     if shouldShow:
         if self.wireframeMesh is None:
             # The wireframe shares geometry with the current mesh, and should automatically be updated when the current mesh is...
             self.wireframeMesh = pythreejs.Mesh(geometry=self.currMesh.geometry, material=self.wireframeMaterial())
         if self.wireframeMesh not in self.meshes.children:
             self.meshes.add(self.wireframeMesh)
     else: # hide
         if self.wireframeMesh in self.meshes.children:
             self.meshes.remove(self.wireframeMesh)
     self.shouldShowWireframe = shouldShow
Ejemplo n.º 13
0
def draw_cylinder(cylinder, color=None, radius_segments=8):
    geo = p3js.CylinderBufferGeometry(radiusTop=cylinder.circle.radius,
                                      radiusBottom=cylinder.circle.radius,
                                      height=cylinder.height,
                                      radiusSegments=radius_segments)
    mat = material_from_color(color)
    mesh = p3js.Mesh(geometry=geo, material=mat)
    mesh.position = list(cylinder.circle.plane.point)
    mesh.quaternion = list(
        Frame.from_plane(cylinder.circle.plane).quaternion.xyzw)
    return mesh
Ejemplo n.º 14
0
def draw_mesh(mesh, hexcolor):
    mesh_quads_to_triangles(mesh)
    vertices, faces = mesh.to_vertices_and_faces()
    vertexcolors = [hexcolor] * len(vertices)
    faces = [f + [None, [vertexcolors[i] for i in f], None] for f in faces]
    geo = p3js.Geometry(vertices=vertices, faces=faces)
    geo.exec_three_obj_method('computeFaceNormals')
    return p3js.Mesh(
        geometry=geo,
        material=p3js.MeshLambertMaterial(vertexColors='VertexColors'),
        position=[0, 0, 0])
Ejemplo n.º 15
0
def _create_mesh(geometry, color, wireframe, position):
    if wireframe:
        edges = p3.EdgesGeometry(geometry)
        mesh = p3.LineSegments(geometry=edges,
                               material=p3.LineBasicMaterial(color=color))

    else:
        material = p3.MeshBasicMaterial(color=color)
        mesh = p3.Mesh(geometry=geometry, material=material)
    mesh.position = tuple(position.value)
    return mesh
Ejemplo n.º 16
0
def get_voxelgrid_pythreejs(xyz, colors):
    vertices = np.array(np.meshgrid([-0.5, 0.5], [-0.5, 0.5], [-0.5, 0.5]),
                        dtype=np.float32).T.reshape(-1, 3)
    faces = np.array(
        [
            [0, 3, 2],
            [0, 1, 3],  # front
            [1, 7, 3],
            [1, 5, 7],  # right
            [5, 6, 7],
            [5, 4, 6],  # back
            [4, 2, 6],
            [4, 0, 2],  # left
            [2, 7, 6],
            [2, 3, 7],  # top
            [4, 1, 0],
            [4, 5, 1]
        ],  # bottom
        dtype=np.uint32)
    colors = pythreejs.InstancedBufferAttribute(array=colors,
                                                meshPerAttribute=3)
    offsets = pythreejs.InstancedBufferAttribute(array=xyz, meshPerAttribute=3)

    instanced_geometry = pythreejs.InstancedBufferGeometry(
        attributes={
            "position": pythreejs.BufferAttribute(array=vertices),
            "index": pythreejs.BufferAttribute(array=faces.ravel()),
            "offset": offsets,
            "color": colors,
        })

    material = pythreejs.ShaderMaterial(vertexShader='''
    precision highp float;
    attribute vec3 offset;
    varying vec3 vPosition;
    varying vec4 vColor;
    void main(){

        vPosition = position + offset;
        vColor = vec4( color, 1 );
        gl_Position = projectionMatrix * modelViewMatrix * vec4( vPosition, 1.0 );
    }
    ''',
                                        fragmentShader='''
    precision highp float;
    varying vec4 vColor;
    void main() {
        gl_FragColor = vec4( vColor );
    }
    ''',
                                        vertexColors='VertexColors',
                                        transparent=False)

    return pythreejs.Mesh(instanced_geometry, material, frustumCulled=False)
Ejemplo n.º 17
0
def test_cone():

    cone = Cone(10.0,
                5.0,
                name='cone',
                color='darkblue',
                material="CHECKERBOARD")
    assert cone.name == 'cone'
    assert cone.__str__() == \
        'Cone cone color:darkblue material:CHECKERBOARD length:10.0 radius:5.0'
    assert cone.__repr__() == 'Cone'
    assert cone.length == 10.0
    assert cone.radius == 5.0
    assert cone.color == 'darkblue'

    if p3js is not None:
        mesh = cone._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.CylinderBufferGeometry(radiusTop=0.0,
                                                              radiusBottom=5.0,
                                                              height=10.0),
                                  p3js.MeshStandardMaterial(color='darkblue'),
                                  name='cone')
        assert repr(mesh) == repr(expected_mesh)

    cone.name = 'cone1'
    assert cone.name == 'cone1'

    cone.length = 16.0
    assert cone.length == 16.0

    cone.radius = 3.0
    assert cone.radius == 3.0

    cone.color = 'darkcyan'
    assert cone.color == 'darkcyan'

    assert cone.generate_dict() == {
        "color": "darkcyan",
        "type": "Cone",
        "name": "cone1",
        "length": 16.0,
        "radius": 3.0,
        "material": "CHECKERBOARD"
    }
    assert isinstance(cone, Shape)

    cone_ = Cone(10.0, 5.0, color='darkblue')
    assert cone_.name == 'unnamed'
    assert cone_.__str__() == \
        'Cone unnamed color:darkblue material:default length:10.0 radius:5.0'
    assert cone_.__repr__() == 'Cone'
Ejemplo n.º 18
0
def test_torus_knot():

    torus_knot = TorusKnot(10.0, 2.0, name='torus_knot', color='red')

    assert torus_knot.name == 'torus_knot'
    assert torus_knot.__str__() == ('TorusKnot torus_knot color:red '
                                    'material:default radius:10.0 '
                                    'tube_radius:2.0')
    assert torus_knot.__repr__() == 'TorusKnot'
    assert torus_knot.radius == 10.0
    assert torus_knot.tube_radius == 2.0
    assert torus_knot.color == 'red'

    if p3js is not None:
        mesh = torus_knot._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.TorusKnotBufferGeometry(radius=10.0,
                                                               tube=2.0),
                                  p3js.MeshStandardMaterial(color='red'),
                                  name='torus_knot')
        assert repr(mesh) == repr(expected_mesh)

    torus_knot.name = 'torus_knot1'
    assert torus_knot.name == 'torus_knot1'

    torus_knot.radius = 12.0
    assert torus_knot.radius == 12.0

    torus_knot.tube_radius = 1.0
    assert torus_knot.tube_radius == 1.0

    torus_knot.color = 'blue'
    assert torus_knot.color == 'blue'

    assert torus_knot.generate_dict() == {
        "color": "blue",
        "type": "TorusKnot",
        "name": "torus_knot1",
        "radius": 12.0,
        "tube_radius": 1,
        "material": "default"
    }

    assert isinstance(torus_knot, Shape)

    torus_knot_ = TorusKnot(10.0, 2.0, color='red')
    assert torus_knot_.name == 'unnamed'
    assert torus_knot_.__str__() == ('TorusKnot unnamed color:red material:'
                                     'default radius:10.0 tube_radius:2.0')
    assert torus_knot_.__repr__() == 'TorusKnot'
Ejemplo n.º 19
0
 def draw_box(self, box, color=None):
     geo = p3js.BoxBufferGeometry(width=box.xsize, 
                                  height=box.zsize, 
                                  depth=box.ysize,
                                  widthSegments=box.xsize, 
                                  heightSegments=box.zsize,
                                  depthSegments=box.ysize)
     mat = material_from_color(color)
     mesh = p3js.Mesh(geometry=geo, material=mat)
     Tinit = Translation([box.xsize/2, box.ysize/2, box.zsize/2])
     Sc, Sh, R, T, P = (Transformation.from_frame(box.frame) * Tinit).decompose()
     mesh.quaternion = R.quaternion.xyzw
     mesh.position = list(T.translation)
     self.geometry.append(mesh)
     return mesh
Ejemplo n.º 20
0
 def __init__(self):
     # TODO: arguments for width/height
     self._width = 600
     self._height = 400
     self._ball = _three.Mesh(
         geometry=_three.SphereGeometry(
             radius=1,
             widthSegments=30,
             heightSegments=20,
         ),
         material=_three.MeshLambertMaterial(color='lightgray'),
     )
     self._axes = _three.AxesHelper(size=1.2)
     self._ambient_light = _three.AmbientLight(
         intensity=0.5,
     )
     self._directional_light1 = _three.DirectionalLight(
         position=[0, 0, 1],
         intensity=0.6,
     )
     self._directional_light2 = _three.DirectionalLight(
         position=[0, 0, -1],
         intensity=0.6,
     )
     self._scene = _three.Scene(
         children=[
             self._ball,
             self._axes,
             self._ambient_light,
             self._directional_light1,
             self._directional_light2,
         ],
     )
     self._camera = _three.PerspectiveCamera(
         position=[0, 0, 2.4],
         up=[0, 0, 1],
         aspect=self._width/self._height,
     )
     self._controls = _three.OrbitControls(controlling=self._camera)
     self._renderer = _three.Renderer(
         camera=self._camera,
         scene=self._scene,
         controls=[self._controls],
         width=self._width,
         height=self._height,
         #alpha=True,
         #clearOpacity=0.5,
     )
Ejemplo n.º 21
0
def test_plane():

    plane = Plane(10.0, 20.0, name='plane', color='lightcyan')
    assert plane.name == 'plane'
    assert plane.__str__() == \
        'Plane plane color:lightcyan material:default length:10.0 width:20.0'
    assert plane.__repr__() == 'Plane'
    assert plane.length == 10.0
    assert plane.width == 20.0
    assert plane.color == 'lightcyan'

    if p3js is not None:
        mesh = plane._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.PlaneBufferGeometry(height=10.0,
                                                           width=20.0),
                                  p3js.MeshStandardMaterial(color='lightcyan',
                                                            side='DoubleSide'),
                                  name='plane')
        assert repr(mesh) == repr(expected_mesh)

    plane.name = 'plane1'
    assert plane.name == 'plane1'

    plane.length = 30.0
    assert plane.length == 30.0

    plane.width = 10.0
    assert plane.width == 10.0

    plane.color = 'lavender'
    assert plane.color == 'lavender'

    assert plane.generate_dict() == {
        "color": "lavender",
        "type": "Plane",
        "name": "plane1",
        "width": 10.0,
        "length": 30.0,
        "material": "default"
    }

    assert isinstance(plane, Shape)

    plane_ = Plane(10.0, 20.0, color='indigo')
    assert plane_.name == 'unnamed'
    assert plane_.__str__() == \
        'Plane unnamed color:indigo material:default length:10.0 width:20.0'
    assert plane_.__repr__() == 'Plane'
Ejemplo n.º 22
0
def test_torus():
    torus = Torus(10.0, 2.0, name='torus', color='red')

    assert torus.name == 'torus'
    assert torus.__str__() == \
        'Torus torus color:red material:default radius:10.0 tube_radius:2.0'
    assert torus.__repr__() == 'Torus'
    assert torus.radius == 10.0
    assert torus.tube_radius == 2.0
    assert torus.color == 'red'

    if p3js is not None:
        mesh = torus._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.TorusBufferGeometry(radius=10.0,
                                                           tube=2.0),
                                  p3js.MeshStandardMaterial(color='red'),
                                  name='torus')
        assert repr(mesh) == repr(expected_mesh)

    torus.name = 'torus1'
    assert torus.name == 'torus1'

    torus.radius = 15.0
    assert torus.radius == 15.0

    torus.tube_radius = 4.0
    assert torus.tube_radius == 4.0

    torus.color = 'tan'
    assert torus.color == 'tan'

    assert torus.generate_dict() == {
        "color": "tan",
        "type": "Torus",
        "name": "torus1",
        "radius": 15.0,
        "tube_radius": 4.0,
        "material": "default"
    }

    assert isinstance(torus, Shape)

    torus_ = Torus(10.0, 2.0, color='red')
    assert torus_.name == 'unnamed'
    assert torus_.__str__() == \
        'Torus unnamed color:red material:default radius:10.0 tube_radius:2.0'
    assert torus_.__repr__() == 'Torus'
Ejemplo n.º 23
0
 def __initialize_mesh(self):
     drawable_geometry = self.__get_drawable_from_boundary()
     material = three.MeshLambertMaterial(
         polygonOffset=True,
         polygonOffsetFactor=1,
         polygonOffsetUnits=1,
         flatShading=True,
         color="white",
         opacity=1.,
         transparent=False,
         side='DoubleSide',
         wireframe=False,
         vertexColors='FaceColors',
     )
     return three.Mesh(geometry=drawable_geometry,
                       material=material,
                       position=[0, 0, 0])
Ejemplo n.º 24
0
 def _get_mesh(self, u):
     if self.codim == 2:
         u = u[self.entity_map]
     elif self.grid.reference_element == triangle:
         u = np.repeat(u, 3)
     else:
         u = np.tile(np.repeat(u, 3), 2)
     data = p3js.BufferAttribute(_normalize(u, self.vmin, self.vmax),
                                 normalized=True)
     geo = p3js.BufferGeometry(
         index=self.buffer_faces,
         attributes=dict(position=self.buffer_vertices, data=data))
     mesh = p3js.Mesh(geometry=geo, material=self.material)
     mesh.visible = False
     # translate to origin where the camera is looking by default, avoids camera not updating in nbconvert run
     mesh.position = tuple(p - i
                           for p, i in zip(mesh.position, self.mesh_center))
     return mesh
Ejemplo n.º 25
0
def display_portal(th_scene, portal):
    """Display portal."""
    def portal_vertices(portal):
        p1 = np.array(portal[0])
        p2 = np.array(portal[1])
        p4 = np.array(portal[2])
        p3 = p1 + (p2 - p1) + (p4 - p1)
        return [p1, p2, p3, p1, p3, p4]

    ps_attr = three.BufferAttribute(array=portal_vertices(portal),
                                    normalized=False)
    geom = three.BufferGeometry(attributes={'position': ps_attr})
    mat = three.MeshBasicMaterial(color='#ff0000',
                                  transparent=True,
                                  opacity=0.1,
                                  side='DoubleSide')
    mesh = three.Mesh(geometry=geom, material=mat)
    th_scene.add(mesh)
Ejemplo n.º 26
0
    def _p3js_mesh(self, constant_map={}):
        """Returns a PyThreeJS mesh object that corresponds to this shape."""

        if p3js is None:
            raise ImportError('pythreejs is not installed.')

        data = self.generate_dict(constant_map=constant_map)

        attrs = dict()

        for k, v in self._p3js_attribute_map.items():
            try:
                attrs[k] = data[v]
            except KeyError:
                attrs[k] = v

        try:
            geom_attr = '{}BufferGeometry'.format(self._p3js_geometry_type)
            Geometry = getattr(p3js, geom_attr)
        except AttributeError:
            geom_attr = '{}Geometry'.format(self._p3js_geometry_type)
            Geometry = getattr(p3js, geom_attr)

        geometry = Geometry(**attrs)

        # NOTE : For some reason traitlets doesn't think 'grey' is a valid HTML
        # color. This workaround should be removed, but deprecation will likely
        # be needed.
        if data['color'] == 'grey':
            color = 'gray'
        else:
            color = data['color']

        material = p3js.MeshStandardMaterial(color=color,
                                             **self._p3js_material_attributes)

        mesh = p3js.Mesh(name=data['name'],
                         geometry=geometry,
                         material=material)

        self._mesh = mesh

        return mesh
Ejemplo n.º 27
0
def test_circle():

    circle = Circle(10.0, name='circle', color='gold')

    assert circle.name == 'circle'
    assert circle.__str__() == \
        'Circle circle color:gold material:default radius:10.0'
    assert circle.__repr__() == 'Circle'
    assert circle.radius == 10.0
    assert circle.color == 'gold'

    if p3js is not None:
        mesh = circle._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.CircleBufferGeometry(radius=10.0),
                                  p3js.MeshStandardMaterial(color='gold'),
                                  name='circle')
        assert repr(mesh) == repr(expected_mesh)

    circle.name = 'circle1'
    assert circle.name == 'circle1'

    circle.radius = 12.0
    assert circle.radius == 12.0

    circle.color = 'black'
    assert circle.color == 'black'

    assert circle.generate_dict() == {
        "color": "black",
        "type": "Circle",
        "name": "circle1",
        "radius": 12.0,
        "material": "default"
    }

    assert isinstance(circle, Shape)

    circle = Circle(10.0, color='gold')
    assert circle.name == 'unnamed'
    assert circle.__str__() == \
        'Circle unnamed color:gold material:default radius:10.0'
    assert circle.__repr__() == 'Circle'
Ejemplo n.º 28
0
def test_tetrahedron():
    # Tetrahedron, Octahedron and Icosahedron geometry is defined by the
    # radius of the circumscribed sphere. It would be mentioned explicitly
    # in the docstrings
    tetrahedron = Tetrahedron(5.0, name='tetrahedron', color='maroon')
    assert tetrahedron.name == 'tetrahedron'
    assert tetrahedron.__str__() == \
        'Tetrahedron tetrahedron color:maroon material:default radius:5.0'
    assert tetrahedron.__repr__() == 'Tetrahedron'
    assert tetrahedron.radius == 5.0
    assert tetrahedron.color == 'maroon'

    if p3js is not None:
        mesh = tetrahedron._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.TetrahedronGeometry(radius=5.0),
                                  p3js.MeshStandardMaterial(color='maroon'),
                                  name='tetrahedron')
        assert repr(mesh) == repr(expected_mesh)

    tetrahedron.name = 'tetrahedron1'
    assert tetrahedron.name == 'tetrahedron1'

    tetrahedron.radius = 7.0
    assert tetrahedron.radius == 7.0

    tetrahedron.color = 'orange'
    assert tetrahedron.color == 'orange'

    assert tetrahedron.generate_dict() == {
        "color": "orange",
        "type": "Tetrahedron",
        "name": "tetrahedron1",
        "radius": 7.0,
        "material": "default"
    }
    assert isinstance(tetrahedron, Shape)

    tetrahedron_ = Tetrahedron(5.0, color='maroon')
    assert tetrahedron_.name == 'unnamed'
    assert tetrahedron_.__str__() == \
        'Tetrahedron unnamed color:maroon material:default radius:5.0'
    assert tetrahedron_.__repr__() == 'Tetrahedron'
Ejemplo n.º 29
0
def test_box():

    box = Box(10.0, 20.0, 30.0, name='box', color='blue', material="WATER")

    assert box.name == 'box'
    assert box.__str__() == 'Box box color:blue material:WATER depth:30.0 height:20.0 width:10.0'
    assert box.__repr__() == 'Box'
    assert box.width == 10.0
    assert box.height == 20.0
    assert box.depth == 30.0
    assert box.color == 'blue'

    if p3js is not None:
        mesh = box._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.BoxBufferGeometry(width=10.0,
                                                         height=20.0,
                                                         depth=30.0),
                                  p3js.MeshStandardMaterial(color='blue'),
                                  name='box')
        assert repr(mesh) == repr(expected_mesh)
Ejemplo n.º 30
0
def test_icosahedron():

    icosahedron = Icosahedron(11.0, name='icosahedron', color='blue')
    assert icosahedron.name == 'icosahedron'
    assert icosahedron.__str__() == \
        'Icosahedron icosahedron color:blue material:default radius:11.0'
    assert icosahedron.__repr__() == 'Icosahedron'
    assert icosahedron.radius == 11.0
    assert icosahedron.color == 'blue'

    if p3js is not None:
        mesh = icosahedron._p3js_mesh()
        expected_mesh = p3js.Mesh(p3js.IcosahedronGeometry(radius=11.0),
                                  p3js.MeshStandardMaterial(color='blue'),
                                  name='icosahedron')
        assert repr(mesh) == repr(expected_mesh)

    icosahedron.name = 'icosahedron1'
    assert icosahedron.name == 'icosahedron1'

    icosahedron.radius = 3.0
    assert icosahedron.radius == 3.0

    icosahedron.color = 'blue'
    assert icosahedron.color == 'blue'

    assert icosahedron.generate_dict() == {
        "color": "blue",
        "type": "Icosahedron",
        "name": "icosahedron1",
        "radius": 3.0,
        "material": "default"
    }

    assert isinstance(icosahedron, Shape)

    icosahedron_ = Icosahedron(11.0, color='blue')
    assert icosahedron_.name == 'unnamed'
    assert icosahedron_.__str__() == \
        'Icosahedron unnamed color:blue material:default radius:11.0'
    assert icosahedron_.__repr__() == 'Icosahedron'