From fbf8a32404ebecc65ac42433f41182d8a0764471 Mon Sep 17 00:00:00 2001
From: Chris Xiong <chirs241097@gmail.com>
Date: Fri, 7 Sep 2018 10:54:11 +0800
Subject: Load texture from 3dxml archive if failed to load from the provided
 texture directory. Enable smooth rendering and auto smoothing by default.

---
 Virtools/3dxml.py | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/Virtools/3dxml.py b/Virtools/3dxml.py
index e54f794..5846497 100644
--- a/Virtools/3dxml.py
+++ b/Virtools/3dxml.py
@@ -9,9 +9,9 @@ bl_info={
 	"category":"Import-Export",
 	"support":"TESTING"
 }
-import bpy,bmesh,bpy_extras,mathutils,zipfile,struct,time
+import bpy,bmesh,bpy_extras,mathutils
 import xml.etree.ElementTree as etree
-import pathlib
+import pathlib,zipfile,time,os,tempfile
 
 NS="{http://www.3ds.com/xsd/3DXML}"
 
@@ -19,6 +19,7 @@ meshes=dict()
 meshmat=dict()
 materials=dict()
 textures=dict()
+texturefiles=dict()
 
 unitfactor=0.01292
 texdir="/Ballance/Textures/"
@@ -27,7 +28,11 @@ def load_textures(tree):
 	txd=pathlib.Path(texdir)
 	for tex in tree.findall(f".//{NS}Image"):
 		txname=tex.attrib["name"]
-		txp=[i for i in txd.iterdir() if i.stem.lower()==txname.lower()]
+		txp=[]
+		if txd.is_dir():
+			txp=[i for i in txd.iterdir() if i.stem.lower()==txname.lower()]
+		if len(txp)<1 and tex.attrib["href"] is not None:
+			txp=[texturefiles[tex.attrib["href"]]]
 		tx=bpy.data.textures.new(txname,'IMAGE')
 		try:
 			tx.image=bpy.data.images.load(str(txp[0]),True)
@@ -102,6 +107,7 @@ def load_objects(tree):
 		scn.objects.link(obj)
 		scn.objects.active=obj
 		obj.select=True
+		bpy.ops.object.shade_smooth()
 
 def create_mesh(verts,faces,facemat,uvs,objidx):
 	if len(uvs)>len(verts):
@@ -125,6 +131,7 @@ def create_mesh(verts,faces,facemat,uvs,objidx):
 			lp[uv].uv=mathutils.Vector(uvs[lp.vert.index])
 	msh=bpy.data.meshes.new(objname)
 	mesh.to_mesh(msh)
+	msh.use_auto_smooth=True
 	meshes[objidx]=msh
 	mesh.free()
 
@@ -144,11 +151,22 @@ def read(filename):
 		except ValueError:
 			print("not a 3DXML 3.0 file!")
 		filename=zf.open("Root.3dxml")
+		for im in zf.namelist():
+			if im.endswith(".tga"):
+				tf=tempfile.NamedTemporaryFile(suffix=".tga",delete=False)
+				tf.write(zf.open(im).read())
+				tf.flush()
+				texturefiles[im]=tf.name
+				tf.close()
 	tree=etree.parse(filename)
 	load_textures(tree)
 	load_materials(tree)
 	load_meshes(tree)
 	load_objects(tree)
+	bpy.ops.file.pack_all()
+	for fn,tfn in texturefiles.items():
+		os.remove(tfn)
+	texturefiles.clear()
 	time2=time.time()
 	print("Total import time is: %.2f seconds."%(time2-time1))
 
-- 
cgit v1.2.3