How to use trimesh - 10 common examples

To help you get started, we’ve selected a few trimesh examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mikedh / trimesh / examples / widget.py View on Github external
def callback(self, dt):
        # change camera location
        self.scene_widget1._angles[2] += np.deg2rad(1)
        self.scene_widget1.scene.set_camera(self.scene_widget1._angles)

        # change scene
        if len(self.scene_widget2.scene.graph.nodes) < 100:
            geom = trimesh.creation.icosphere(radius=0.01)
            geom.visual.face_colors = np.random.uniform(0, 1, (3,))
            geom.apply_translation(np.random.uniform(-0.3, 0.3, (3,)))
            self.scene_widget2.scene.add_geometry(geom)
            self.scene_widget2._draw()

        # change image
        image = np.random.randint(0,
                                  255,
                                  (self.height - 10, self.width // 3 - 10, 3),
                                  dtype=np.uint8)
        with io.BytesIO() as f:
            PIL.Image.fromarray(image).save(f, format='JPEG')
            self.image_widget.image = pyglet.image.load(filename=None, file=f)
github mikedh / trimesh / tests / generic.py View on Github external
If True raise a ValueError if a mesh
      that should be loadable returns a non- Trimesh object.

    Returns
    ----------
    meshes : list
      Trimesh objects from models folder
    """
    # use deterministic file name order
    file_names = sorted(os.listdir(dir_models))

    meshes = []
    for file_name in file_names:
        extension = trimesh.util.split_extension(file_name).lower()
        if extension in trimesh.available_formats():
            loaded = trimesh.util.make_sequence(get_mesh(file_name))
            for m in loaded:
                # is the loaded mesh a Geometry object or a subclass:
                # Trimesh, PointCloud, Scene
                type_ok = isinstance(m, trimesh.parent.Geometry)
                if raise_error and not type_ok:
                    raise ValueError('%s returned a non- Trimesh object!',
                                     file_name)
                if not isinstance(m, trimesh.Trimesh) or (
                        only_watertight and not m.is_watertight):
                    continue
                meshes.append(m)
                yield m
        else:
            log.warning('%s has no loader, not running test on!',
                        file_name)
github cselab / Mirheo / tests / rigids / create_from_mesh.py View on Github external
def create_from_mesh_file(density, fname, niter):
    import trimesh
    m = trimesh.load(fname);
    # TODO diagonalize
    inertia = [row[i] for i, row in enumerate(m.moment_inertia)]
    return create_from_mesh(density, m.vertices.tolist(), m.faces.tolist(), inertia, niter)
github mmatl / pyrender / tests / unit / test_offscreen.py View on Github external
def test_offscreen_renderer(tmpdir):

    # Fuze trimesh
    fuze_trimesh = trimesh.load('examples/models/fuze.obj')
    fuze_mesh = Mesh.from_trimesh(fuze_trimesh)

    # Drill trimesh
    drill_trimesh = trimesh.load('examples/models/drill.obj')
    drill_mesh = Mesh.from_trimesh(drill_trimesh)
    drill_pose = np.eye(4)
    drill_pose[0,3] = 0.1
    drill_pose[2,3] = -np.min(drill_trimesh.vertices[:,2])

    # Wood trimesh
    wood_trimesh = trimesh.load('examples/models/wood.obj')
    wood_mesh = Mesh.from_trimesh(wood_trimesh)

    # Water bottle trimesh
    bottle_gltf = trimesh.load('examples/models/WaterBottle.glb')
    bottle_trimesh = bottle_gltf.geometry[list(bottle_gltf.geometry.keys())[0]]
github mikedh / pypocketing / tests / test_basic.py View on Github external
def test_contour(self):
        path = get_model('wrench.dxf')
        poly = path.polygons_full[0]
        # generate tool paths
        toolpaths = pocketing.contour.contour_parallel(poly, .05)

        assert all(trimesh.util.is_shape(i, (-1, 2))
                   for i in toolpaths)
github mikedh / pypocketing / tests / test_basic.py View on Github external
def check_arcs(arcs):
    # arcs should be 2D or 2D 3-point arcs
    assert trimesh.util.is_shape(arcs, (-1, 3, (3, 2)))
    # make sure arcs start where previous arc begins
    for a, b in zip(arcs[:-1], arcs[1:]):
        assert np.allclose(a[2], b[0])
github cselab / Mirheo / tests / restart / rigid_vector.py View on Github external
parser = argparse.ArgumentParser()
parser.add_argument("--restart", action='store_true', default=False)
parser.add_argument("--ranks", type=int, nargs=3)
args = parser.parse_args()

ranks  = args.ranks
domain = (16, 16, 16)
dt = 0.0

u = mir.Mirheo(ranks, domain, dt, debug_level=9,
              log_filename='log', no_splash=True,
              checkpoint_every = (0 if args.restart else 5))

    
mesh = trimesh.creation.icosphere(subdivisions=1, radius = 0.1)

coords = [[-0.01, 0., 0.],
          [ 0.01, 0., 0.],
          [0., -0.01, 0.],
          [0.,  0.01, 0.],
          [0., 0., -0.01],
          [0., 0.,  0.01]]

udx_mesh = mir.ParticleVectors.Mesh(mesh.vertices.tolist(), mesh.faces.tolist())
pv       = mir.ParticleVectors.RigidObjectVector("pv", mass=1.0, inertia=[0.1, 0.1, 0.1], object_size=len(coords), mesh=udx_mesh)

nobjs = 10
pos = [ np.array(domain) * t for t in np.linspace(0, 1.0, nobjs) ]
Q = [ np.array([1.0, 0., 0., 0.])  for i in range(nobjs) ]
pos_q = np.concatenate((pos, Q), axis=1)
github mmatl / pyrender / tests / unit / test_meshes.py View on Github external
x.texcoord_1 = np.zeros(10)
    with pytest.raises(TypeError):
        x.material = np.zeros(10)
    assert x.targets is None
    assert np.allclose(x.bounds, np.array([
        [-0.5, -0.5, -0.5],
        [0.5, 0.5, 0.5]
    ]))
    assert np.allclose(x.centroid, np.zeros(3))
    assert np.allclose(x.extents, np.ones(3))
    assert np.allclose(x.scale, np.sqrt(3))
    x.material.baseColorFactor = np.array([0.0, 0.0, 0.0, 0.0])
    assert x.is_transparent

    # From two trimeshes
    x = Mesh.from_trimesh([trimesh.creation.box(),
                          trimesh.creation.cylinder(radius=0.1, height=2.0)],
                          smooth=False)
    assert isinstance(x, Mesh)
    assert len(x.primitives) == 2
    assert x.is_visible
    assert np.allclose(x.bounds, np.array([
        [-0.5, -0.5, -1.0],
        [0.5, 0.5, 1.0]
    ]))
    assert np.allclose(x.centroid, np.zeros(3))
    assert np.allclose(x.extents, [1.0, 1.0, 2.0])
    assert np.allclose(x.scale, np.sqrt(6))
    assert not x.is_transparent

    # From bad data
    with pytest.raises(TypeError):
github cselab / Mirheo / tests / restart / object_vector.py View on Github external
parser = argparse.ArgumentParser()
parser.add_argument("--restart", action='store_true', default=False)
parser.add_argument("--ranks", type=int, nargs=3)
args = parser.parse_args()

comm   = MPI.COMM_WORLD
ranks  = args.ranks
domain = (16, 16, 16)
dt = 0

u = mir.Mirheo(ranks, domain, dt, comm_ptr=MPI._addressof(comm),
              debug_level=3, log_filename='log', no_splash=True,
              checkpoint_every = (0 if args.restart else 5))
    
mesh = trimesh.creation.icosphere(subdivisions=1, radius = 0.1)
    
udx_mesh = mir.ParticleVectors.MembraneMesh(mesh.vertices.tolist(), mesh.faces.tolist())
pv       = mir.ParticleVectors.MembraneVector("pv", mass=1.0, mesh=udx_mesh)

if args.restart:
    ic   = mir.InitialConditions.Restart("restart/")
else:
    nobjs = 10
    pos = [ np.array(domain) * t for t in np.linspace(0, 1.0, nobjs) ]
    Q = [ np.array([1.0, 0., 0., 0.])  for i in range(nobjs) ]
    pos_q = np.concatenate((pos, Q), axis=1)

    ic = mir.InitialConditions.Membrane(pos_q.tolist())

u.registerParticleVector(pv, ic)
github cselab / Mirheo / tests / bindings / obj_rod.py View on Github external
pv_rod = mir.ParticleVectors.RodVector('rod', mass, num_segments)
ic_rod = mir.InitialConditions.Rod(com_q_rod, center_line, torsion, a0)


# ellipsoid

axes = tuple(args.axes)
com_q_ell = [[0.5 * domain[0],
              0.5 * domain[1],
              0.5 * domain[2] + axes[2],
              1., 0, 0, 0]]
coords = np.loadtxt(args.coords).tolist()

if args.vis:
    import trimesh
    ell = trimesh.creation.icosphere(subdivisions=2, radius = 1.0)
    for i in range(3):
        ell.vertices[:,i] *= axes[i]
    mesh = mir.ParticleVectors.Mesh(ell.vertices.tolist(), ell.faces.tolist())
    pv_ell = mir.ParticleVectors.RigidEllipsoidVector('ellipsoid', mass, object_size=len(coords), semi_axes=axes, mesh=mesh)
else:
    pv_ell = mir.ParticleVectors.RigidEllipsoidVector('ellipsoid', mass, object_size=len(coords), semi_axes=axes)

ic_ell = mir.InitialConditions.Rigid(com_q_ell, coords)
vv_ell = mir.Integrators.RigidVelocityVerlet("vv_ell")

u.registerParticleVector(pv_ell, ic_ell)
u.registerParticleVector(pv_rod, ic_rod)

u.registerIntegrator(vv_ell)
u.setIntegrator(vv_ell, pv_ell)