vpython / vpython-jupyter

3D visualization made easy
MIT License
133 stars 65 forks source link

3mf Support - Script for loading 3mf #228

Closed docdann closed 1 year ago

docdann commented 1 year ago

from datetime import datetime from zipfile import ZipFile import xml.etree.ElementTree as ET import os from vpython import * import numpy as np from tkinter import filedialog as fd

now = datetime.now()

def select_3mf(): filename = fd.askopenfilename() return filename

def load_3mf(filename): with ZipFile(filename, 'r') as zipObj:

Extract all the contents of 3mf file in new directory specified by os.path.splitext(filename)[0]

    # os.path.splitext(filename)[0] is the file name without the extension
    zipObj.extractall(os.path.splitext(filename)[0])

tree = ET.parse(os.path.splitext(filename)[0] + "/3D/3dmodel.model")

root = tree.getroot()
ET.dump(tree)
# registering core 3mf schema namespace
ET.register_namespace("", "http://schemas.microsoft.com/3dmanufacturing/core/2015/02")
ns = {"": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"}
print("****************************************************************")

trianglearray = []
for t in root.findall('.//triangle', ns):
    trianglearray.extend([t.attrib])
# print(trianglearray)
nptri = np.array(trianglearray)

print("****************************************************************")
vertexarray = []
for v in root.findall('.//vertex', ns):
    vertexarray.extend([v.attrib])
npvert = np.array(vertexarray)

print("****************************************************************")

# getting colorgroup
# registering material 3mf schema namespace

ET.register_namespace("", "http://schemas.microsoft.com/3dmanufacturing/material/2015/02")
# The namespace variable is updated to match the newly registered namespace
ns = {"": "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"}

colorarray = []
c_hex_array = []
c_rgb_array = []
c_rgb_norm = []
try:
    # xml search for color
    for c in root.findall('.//color', ns):
        colorarray.extend([c.attrib])
    npcolor = np.array(colorarray)
    print(npcolor)
    for c in range(len(npcolor)):
        col = (npcolor[c])
        c_hex_array.append(str(col['color']).lstrip("#").removesuffix('FF'))
    print(c_hex_array)
    # converting hex values in c_hex_array to an array of rgb tuples
    for j in range(len(c_hex_array)):
        if c_hex_array[j] != "A0A0A0":
            c_rgb_array.append(tuple(int(c_hex_array[j][i:i + 2], 16) / 255 for i in (0, 2, 4)))
            r, g, b = c_rgb_array[j]
            c_rgb_norm.append([r, g, b])
        else:
            pass

    print(c_rgb_norm)
except Exception:
    pass
# color vectors
# default color values
a0_color, a1_color, a2_color = 0, 0, 0
b0_color, b1_color, b2_color = 0, 0, 0
c0_color, c1_color, c2_color = 0, 0, 0

if len(c_rgb_norm) == 1:
    a0_color, a1_color, a2_color = c_rgb_norm[0][0], c_rgb_norm[0][1], c_rgb_norm[0][2]
    b0_color, b1_color, b2_color, c0_color, c1_color, c2_color = a0_color, a1_color, a2_color, a0_color, a1_color, a2_color
elif len(c_rgb_norm) == 2:
    a0_color, a1_color, a2_color = c_rgb_norm[0][0], c_rgb_norm[0][1], c_rgb_norm[0][2]
    b0_color, b1_color, b2_color = c_rgb_norm[1][0], c_rgb_norm[1][1], c_rgb_norm[1][2]
    c0_color, c1_color, c2_color = (a0_color + b0_color) / 2, (a1_color + b1_color) / 2, (a2_color + b2_color) / 2

elif len(c_rgb_norm) == 3:
    a0_color = c_rgb_norm[0][0]
    a1_color = c_rgb_norm[0][1]
    a2_color = c_rgb_norm[0][2]
    b0_color = c_rgb_norm[1][0]
    b1_color = c_rgb_norm[1][1]
    b2_color = c_rgb_norm[1][2]
    c0_color = c_rgb_norm[2][0]
    c1_color = c_rgb_norm[2][1]
    c2_color = c_rgb_norm[2][2]
else:
    pass

print("****************************************************************")

model = []
for t in range(len(nptri)):
    tri = nptri[t]
    # v1, v2, v3 are the vertecies of each triangle

    v1 = [float(npvert[int(tri['v1'])]['x']), float(npvert[int(tri['v1'])]['y']),
          float(npvert[int(tri['v1'])]['z'])]
    v2 = [float(npvert[int(tri['v2'])]['x']), float(npvert[int(tri['v2'])]['y']),
          float(npvert[int(tri['v2'])]['z'])]
    v3 = [float(npvert[int(tri['v3'])]['x']), float(npvert[int(tri['v3'])]['y']),
          float(npvert[int(tri['v3'])]['z'])]

    a = vertex(pos=vec(v1[0], v1[1], v1[2]), color=vector(a0_color, a1_color, a2_color))
    b = vertex(pos=vec(v2[0], v2[1], v2[2]), color=vector(b0_color, b1_color, b2_color))
    c = vertex(pos=vec(v3[0], v3[1], v3[2]), color=vector(c0_color, c1_color, c2_color))
    # triangles are appended to the array model to be combined into a compound object after all triangles defined
    model.append(triangle(vs=[a, b, c]))

combined = compound(model)
return combined
BruceSherwood commented 1 year ago

What exactly is the problem? You need to reduce your program to a very short test program that shows the problem, and also state what the problem is. Otherwise we have no way to deal with your post.