Skip to content

Commit

Permalink
PLY: code cleanup and PEP8
Browse files Browse the repository at this point in the history
Unused imports, move rare imports inside functions, comment out unused codeblocks instead of docstring, use bl_description.
  • Loading branch information
mrachinskiy committed Oct 15, 2019
1 parent 5e7df9f commit 376fa84
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 83 deletions.
14 changes: 5 additions & 9 deletions io_mesh_ply/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@
bl_info = {
"name": "Stanford PLY format",
"author": "Bruce Merry, Campbell Barton",
"version": (1, 0, 0),
"blender": (2, 81, 6),
"version": (1, 1, 0),
"blender": (2, 82, 0),
"location": "File > Import-Export",
"description": "Import-Export PLY mesh data with UV's and vertex colors",
"warning": "",
"wiki_url": "https://docs.blender.org/manual/en/latest/addons/io_mesh_ply.html",
"support": 'OFFICIAL',
"category": "Import-Export",
Expand All @@ -34,8 +33,6 @@
# Copyright (C) 2004, 2005: Bruce Merry, [email protected]
# Contributors: Bruce Merry, Campbell Barton

# To support reload properly, try to access a package var,
# if it's there, reload everything
if "bpy" in locals():
import importlib
if "export_ply" in locals():
Expand All @@ -44,13 +41,11 @@
importlib.reload(import_ply)


import os
import bpy
from bpy.props import (
CollectionProperty,
StringProperty,
BoolProperty,
EnumProperty,
FloatProperty,
)
from bpy_extras.io_utils import (
Expand Down Expand Up @@ -81,6 +76,8 @@ class ImportPLY(bpy.types.Operator, ImportHelper):
filter_glob: StringProperty(default="*.ply", options={'HIDDEN'})

def execute(self, context):
import os

paths = [os.path.join(self.directory, name.name)
for name in self.files]
if not paths:
Expand All @@ -96,10 +93,9 @@ def execute(self, context):

@orientation_helper(axis_forward='Y', axis_up='Z')
class ExportPLY(bpy.types.Operator, ExportHelper):
"""Export a single object as a Stanford PLY with normals, """ \
"""colors and texture coordinates"""
bl_idname = "export_mesh.ply"
bl_label = "Export PLY"
bl_description = "Export as a Stanford PLY with normals, vertex colors and texture coordinates"

filename_ext = ".ply"
filter_glob: StringProperty(default="*.ply", options={'HIDDEN'})
Expand Down
33 changes: 13 additions & 20 deletions io_mesh_ply/export_ply.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,12 @@
"""
This script exports Stanford PLY files from Blender. It supports normals,
colors, and texture coordinates per face or per vertex.
Only one mesh can be exported at a time.
"""

import bpy
import os


def save_mesh(
filepath,
mesh,
use_normals=True,
use_uv_coords=True,
use_colors=True,
):
def save_mesh(filepath, mesh, use_normals=True, use_uv_coords=True, use_colors=True):
import os
import bpy

def rvec3d(v):
return round(v[0], 6), round(v[1], 6), round(v[2], 6)
Expand Down Expand Up @@ -186,16 +178,17 @@ def rvec2d(v):


def save(
operator,
context,
filepath="",
use_selection=False,
use_mesh_modifiers=True,
use_normals=True,
use_uv_coords=True,
use_colors=True,
global_matrix=None
operator,
context,
filepath="",
use_selection=False,
use_mesh_modifiers=True,
use_normals=True,
use_uv_coords=True,
use_colors=True,
global_matrix=None
):
import bpy
import bmesh

if bpy.ops.object.mode_set.poll():
Expand Down
106 changes: 52 additions & 54 deletions io_mesh_ply/import_ply.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@

# <pep8 compliant>

import re
import struct


class element_spec(object):
__slots__ = (
Expand Down Expand Up @@ -59,14 +56,16 @@ def __init__(self, name, list_type, numeric_type):
self.numeric_type = numeric_type

def read_format(self, format, count, num_type, stream):
import struct

if format == b'ascii':
if num_type == 's':
ans = []
for i in range(count):
s = stream[i]
if not (len(s) >= 2 and s.startswith(b'"') and s.endswith(b'"')):
print('Invalid string', s)
print('Note: ply_import.py does not handle whitespace in strings')
print("Invalid string", s)
print("Note: ply_import.py does not handle whitespace in strings")
return None
ans.append(s[1:-1])
stream[:count] = []
Expand Down Expand Up @@ -104,29 +103,30 @@ def load(self, format, stream):


class object_spec(object):
__slots__ = ("specs",
)
'A list of element_specs'
__slots__ = ("specs",)

def __init__(self):
# A list of element_specs
self.specs = []

def load(self, format, stream):
return dict([(i.name, [i.load(format, stream) for j in range(i.count)]) for i in self.specs])

'''
# Longhand for above LC
answer = {}
for i in self.specs:
answer[i.name] = []
for j in range(i.count):
if not j % 100 and meshtools.show_progress:
Blender.Window.DrawProgressBar(float(j) / i.count, 'Loading ' + i.name)
answer[i.name].append(i.load(format, stream))
return answer
'''

# answer = {}
# for i in self.specs:
# answer[i.name] = []
# for j in range(i.count):
# if not j % 100 and meshtools.show_progress:
# Blender.Window.DrawProgressBar(float(j) / i.count, 'Loading ' + i.name)
# answer[i.name].append(i.load(format, stream))
# return answer


def read(filepath):
import re

format = b''
texture = b''
version = b'1.0'
Expand Down Expand Up @@ -161,7 +161,7 @@ def read(filepath):
signature = plyf.readline()

if not signature.startswith(b'ply'):
print('Signature line was invalid')
print("Signature line was invalid")
return invalid_ply

valid_header = False
Expand All @@ -178,7 +178,7 @@ def read(filepath):
continue
elif tokens[1] == b'TextureFile':
if len(tokens) < 4:
print('Invalid texture line')
print("Invalid texture line")
else:
texture = tokens[2]
continue
Expand All @@ -187,29 +187,29 @@ def read(filepath):
continue
elif tokens[0] == b'format':
if len(tokens) < 3:
print('Invalid format line')
print("Invalid format line")
return invalid_ply
if tokens[1] not in format_specs:
print('Unknown format', tokens[1])
print("Unknown format", tokens[1])
return invalid_ply
try:
version_test = float(tokens[2])
except Exception as ex:
print('Unknown version', ex)
print("Unknown version", ex)
version_test = None
if version_test != float(version):
print('Unknown version', tokens[2])
print("Unknown version", tokens[2])
return invalid_ply
del version_test
format = tokens[1]
elif tokens[0] == b'element':
if len(tokens) < 3:
print(b'Invalid element line')
print("Invalid element line")
return invalid_ply
obj_spec.specs.append(element_spec(tokens[1], int(tokens[2])))
elif tokens[0] == b'property':
if not len(obj_spec.specs):
print('Property without element')
print("Property without element")
return invalid_ply
if tokens[1] == b'list':
obj_spec.specs[-1].properties.append(property_spec(tokens[4], type_specs[tokens[2]], type_specs[tokens[3]]))
Expand All @@ -224,22 +224,20 @@ def read(filepath):
return obj_spec, obj, texture


import bpy


def load_ply_mesh(filepath, ply_name):
from bpy_extras.io_utils import unpack_face_list
import bpy

obj_spec, obj, texture = read(filepath)
# XXX28: use texture
if obj is None:
print('Invalid file')
print("Invalid file")
return

uvindices = colindices = None
colmultiply = None

# noindices = None # Ignore normals
# TODO import normals
# noindices = None

for el in obj_spec.specs:
if el.name == b'vertex':
Expand Down Expand Up @@ -376,38 +374,38 @@ def add_face(vertices, indices, uvindices, colindices):
if texture and uvindices:
pass
# XXX28: add support for using texture.
'''
import os
import sys
from bpy_extras.image_utils import load_image

encoding = sys.getfilesystemencoding()
encoded_texture = texture.decode(encoding=encoding)
name = bpy.path.display_name_from_filepath(texture)
image = load_image(encoded_texture, os.path.dirname(filepath), recursive=True, place_holder=True)
# import os
# import sys
# from bpy_extras.image_utils import load_image

# encoding = sys.getfilesystemencoding()
# encoded_texture = texture.decode(encoding=encoding)
# name = bpy.path.display_name_from_filepath(texture)
# image = load_image(encoded_texture, os.path.dirname(filepath), recursive=True, place_holder=True)

if image:
texture = bpy.data.textures.new(name=name, type='IMAGE')
texture.image = image
# if image:
# texture = bpy.data.textures.new(name=name, type='IMAGE')
# texture.image = image

material = bpy.data.materials.new(name=name)
material.use_shadeless = True
# material = bpy.data.materials.new(name=name)
# material.use_shadeless = True

mtex = material.texture_slots.add()
mtex.texture = texture
mtex.texture_coords = 'UV'
mtex.use_map_color_diffuse = True
# mtex = material.texture_slots.add()
# mtex.texture = texture
# mtex.texture_coords = 'UV'
# mtex.use_map_color_diffuse = True

mesh.materials.append(material)
for face in mesh.uv_textures[0].data:
face.image = image
'''
# mesh.materials.append(material)
# for face in mesh.uv_textures[0].data:
# face.image = image

return mesh


def load_ply(filepath):
import time
import bpy

t = time.time()
ply_name = bpy.path.display_name_from_filepath(filepath)
Expand All @@ -421,7 +419,7 @@ def load_ply(filepath):
bpy.context.view_layer.objects.active = obj
obj.select_set(True)

print('\nSuccessfully imported %r in %.3f sec' % (filepath, time.time() - t))
print("\nSuccessfully imported %r in %.3f sec" % (filepath, time.time() - t))
return {'FINISHED'}


Expand Down

0 comments on commit 376fa84

Please sign in to comment.