Skip to content

Commit

Permalink
basic working- ish texture support to viewer
Browse files Browse the repository at this point in the history
  • Loading branch information
mikedh committed Jan 1, 2019
1 parent 4790232 commit d3fa122
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 10 deletions.
16 changes: 10 additions & 6 deletions trimesh/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1943,15 +1943,19 @@ def remove_unreferenced_vertices(self):

def unmerge_vertices(self):
"""
Removes all face references so that every face contains three
unique vertex indices and no faces are adjacent.
Removes all face references so that every face contains
three unique vertex indices and no faces are adjacent.
"""
vertices = self.vertices[self.faces].reshape((-1, 3))
faces = np.arange(len(vertices),
dtype=np.int64).reshape((-1, 3))
#vertices = self.vertices[self.faces].reshape((-1, 3))
faces = np.arange(len(self.faces) * 3,
dtype=np.int64).reshape((-1, 3))

# use update_vertices to apply mask to
# all properties that are per-vertex
self.update_vertices(self.faces.reshape(-1))
# set faces to incrementing indexes
self.faces = faces
self.vertices = vertices
# keep face normals as the haven't changed
self._cache.clear(exclude=['face_normals'])

def apply_translation(self, translation):
Expand Down
5 changes: 4 additions & 1 deletion trimesh/exchange/ply.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,23 @@ def elements_to_kwargs(elements, textures=None):
if len(face_blob.dtype.names) == 1:
name = face_blob.dtype.names[0]
elif len(face_blob.dtype.names) > 1:
# loop through options
for i in face_blob.dtype.names:
if i in index_names:
name = i
break
# get faces
faces = face_blob[name]['f1']

try:
td = face_blob['texcoord']['f1']
uv = np.zeros((len(vertices), 2), dtype=np.float64)
uv[faces.reshape(-1)] = td.reshape((-1, 2))

kwargs['visual'] = visual.texture.TextureVisuals(
uv=uv,
image=next(iter(textures.values())))

except (ValueError, KeyError):
# accessing numpy arrays with named fields
# incorrectly is a valueerror
Expand Down
3 changes: 1 addition & 2 deletions trimesh/exchange/wavefront.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def append_mesh():
for usemtl in current['usemtl']:
try:
findices = usemtl_to_findices[usemtl]
uv = texture[findices]
uv = texture[findices][:, :2]
# what is the file name of the texture image
file_name = mtllibs[usemtl]['map_Kd']
# get the texture image as a PIL image
Expand All @@ -187,7 +187,6 @@ def append_mesh():
loaded['visual'] = visual.texture.TextureVisuals(
uv=uv, image=image)
except BaseException:

log.error('failed to load texture: {}'.format(
usemtl), exc_info=True)

Expand Down
26 changes: 25 additions & 1 deletion trimesh/rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,14 @@ def mesh_to_vertexlist(mesh,
args : (7,) tuple
Args for vertex list constructor
"""
if smooth and len(mesh.faces) < smooth_threshold:

if hasattr(mesh.visual, 'uv'):
vertex_count = len(mesh.vertices)
normals = mesh.vertex_normals.reshape(-1).tolist()
faces = mesh.faces.reshape(-1).tolist()
vertices = mesh.vertices.reshape(-1).tolist()
color_gl = uv_to_gl(mesh.visual.uv)
elif smooth and len(mesh.faces) < smooth_threshold:
# if we have a small number of faces smooth the mesh
mesh = mesh.smoothed()
vertex_count = len(mesh.vertices)
Expand Down Expand Up @@ -221,6 +228,23 @@ def colors_to_gl(colors, count):

return colors_type, colors

def uv_to_gl(uv):
return 't2f/static', uv.astype(np.float64).reshape(-1).tolist()

def material_to_texture(material):
if hasattr(material, 'image'):
img = material.image
else:
img = material.baseColorTexture

with util.BytesIO() as f:
# export PIL image as PNG
img.save(f, format='png'); f.seek(0)
# filename used for format guess
gl_image = pyglet.image.load(filename='.png', file=f)
texture = gl_image.get_texture()

return texture

def matrix_to_gl(matrix):
"""
Expand Down
22 changes: 22 additions & 0 deletions trimesh/scene/viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ def __init__(self,
# store geometry rendering mode
self.vertex_list_mode = {}

# name : texture
self.textures = {}

if scene.camera is not None:
if resolution is not None:
if not np.allclose(resolution, scene.camera.resolution,
Expand Down Expand Up @@ -114,6 +117,8 @@ def __init__(self,
self.add_geometry(name=name,
geometry=mesh,
smooth=bool(smooth))

# call after geometry is added
self.init_gl()
self.set_size(*resolution)
self.update_flags()
Expand Down Expand Up @@ -164,6 +169,12 @@ def add_geometry(self, name, geometry, **kwargs):
# save the rendering mode from the constructor args
self.vertex_list_mode[name] = args[1]

if hasattr(geometry, 'visual') and hasattr(geometry.visual, 'material'):
self.textures[name] = rendering.material_to_texture(geometry.visual.material)

print(self.textures)


def reset_view(self, flags=None):
"""
Set view to the default view.
Expand Down Expand Up @@ -260,6 +271,7 @@ def init_gl(self):
gl.glLineWidth(1.5)
gl.glPointSize(4)


def toggle_culling(self):
"""
Toggle backface culling on or off. It is on by default
Expand Down Expand Up @@ -456,13 +468,23 @@ def on_draw(self):
# come back to this mesh later
continue

#
texture = None
if geometry_name in self.textures:
texture = self.textures[geometry_name]
gl.glEnable(texture.target)
gl.glBindTexture(texture.target, texture.id)

# get the mode of the current geometry
mode = self.vertex_list_mode[geometry_name]
# draw the mesh with its transform applied
self.vertex_list[geometry_name].draw(mode=mode)
# pop the matrix stack as we drew what we needed to draw
gl.glPopMatrix()

if texture is not None:
gl.glDisable(texture.target)

def save_image(self, file_obj):
"""
Save the current color buffer to a file object
Expand Down

0 comments on commit d3fa122

Please sign in to comment.