347 lines
12 KiB
Python
347 lines
12 KiB
Python
import math
|
|
import re
|
|
import struct
|
|
import zlib
|
|
from io import BytesIO
|
|
from itertools import islice
|
|
from pathlib import PurePosixPath
|
|
from xml.etree import ElementTree
|
|
from zipfile import ZIP_DEFLATED, ZIP_STORED, BadZipFile, ZipFile
|
|
|
|
SIZE = 128
|
|
MAX_TRIANGLES = 40_000
|
|
MAX_MODEL_BYTES = 12 * 1024 * 1024
|
|
MAX_IMAGE_BYTES = 512 * 1024
|
|
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
|
STL_TRIANGLE = struct.Struct("<12fH")
|
|
STL_VERTEX = re.compile(rb"^[ \t]*vertex[ \t]+([^\s]+)[ \t]+([^\s]+)[ \t]+([^\s]+)", re.M)
|
|
|
|
|
|
def create_preview(file, extension):
|
|
try:
|
|
if extension == ".stl":
|
|
return _render_stl(file)
|
|
if extension in {".3mf", ".zip"}:
|
|
with ZipFile(_ArchiveReader(file)) as archive:
|
|
return _render_3mf(archive) if extension == ".3mf" else _render_zip(archive)
|
|
except (
|
|
BadZipFile,
|
|
ElementTree.ParseError,
|
|
ValueError,
|
|
OverflowError,
|
|
OSError,
|
|
RuntimeError,
|
|
EOFError,
|
|
LookupError,
|
|
zlib.error,
|
|
):
|
|
# The original upload is still downloadable when a preview cannot be built.
|
|
return b""
|
|
return b""
|
|
|
|
|
|
def image_type(data):
|
|
return "image/png" if data.startswith(PNG_SIGNATURE) else "image/jpeg"
|
|
|
|
|
|
class _ArchiveReader:
|
|
"""Bound the ZIP directory read before zipfile allocates its entry list."""
|
|
|
|
def __init__(self, file):
|
|
self.file = file
|
|
|
|
def seek(self, *args):
|
|
return self.file.seek(*args)
|
|
|
|
def tell(self):
|
|
return self.file.tell()
|
|
|
|
def seekable(self):
|
|
return self.file.seekable()
|
|
|
|
def read(self, size=-1):
|
|
limit = 2 * 1024 * 1024
|
|
if size > limit:
|
|
raise BadZipFile("Oversized ZIP directory")
|
|
if size < 0:
|
|
data = self.file.read(limit + 1)
|
|
if len(data) > limit:
|
|
raise BadZipFile("Oversized ZIP metadata")
|
|
return data
|
|
return self.file.read(size)
|
|
|
|
|
|
def _read_member(archive, name, limit):
|
|
entry = archive.NameToInfo.get(name)
|
|
if (
|
|
entry is None
|
|
or entry.is_dir()
|
|
or entry.file_size > limit
|
|
or entry.flag_bits & 1
|
|
or entry.compress_type not in {ZIP_STORED, ZIP_DEFLATED}
|
|
):
|
|
return b""
|
|
with archive.open(entry) as member:
|
|
return member.read(limit)
|
|
|
|
|
|
class _NoDoctype(ElementTree.TreeBuilder):
|
|
def doctype(self, *_):
|
|
raise ValueError("DTD in model metadata")
|
|
|
|
|
|
def _read_xml(archive, name, limit):
|
|
data = _read_member(archive, name, limit)
|
|
if not data:
|
|
return None
|
|
return ElementTree.fromstring(data, parser=ElementTree.XMLParser(target=_NoDoctype()))
|
|
|
|
|
|
def _render_3mf(archive):
|
|
paths = {name.lower(): name for name in archive.namelist()}
|
|
preview_paths = []
|
|
model_path = paths.get("3d/3dmodel.model")
|
|
try:
|
|
relationships = _read_xml(archive, "_rels/.rels", 64 * 1024)
|
|
except (ElementTree.ParseError, ValueError):
|
|
relationships = None
|
|
if relationships is not None:
|
|
for relationship in relationships:
|
|
if relationship.get("TargetMode") == "External":
|
|
continue
|
|
target = relationship.get("Target", "").lstrip("/")
|
|
kind = relationship.get("Type", "").rsplit("/", 1)[-1]
|
|
if kind == "thumbnail":
|
|
preview_paths.append(target)
|
|
elif kind == "3dmodel" and target in archive.NameToInfo:
|
|
model_path = target
|
|
preview_paths.extend(
|
|
paths[path]
|
|
for path in (
|
|
"metadata/plate_1.png",
|
|
"auxiliaries/.thumbnails/thumbnail_3mf.png",
|
|
"metadata/thumbnail.png",
|
|
"metadata/thumbnail.jpg",
|
|
)
|
|
if path in paths
|
|
)
|
|
for name in list(dict.fromkeys(preview_paths))[:8]:
|
|
data = _read_member(archive, name, MAX_IMAGE_BYTES)
|
|
width, height = _image_dimensions(data)
|
|
if 0 < width <= 1024 and 0 < height <= 1024:
|
|
return data
|
|
if model_path:
|
|
root = _read_xml(archive, model_path, MAX_MODEL_BYTES)
|
|
if root is not None:
|
|
return _render(_3mf_triangles(root))
|
|
return b""
|
|
|
|
|
|
def _render_zip(archive):
|
|
# Open a few candidates in archive order, without extracting entries to disk.
|
|
names = [
|
|
entry.filename
|
|
for entry in archive.infolist()
|
|
if not entry.is_dir()
|
|
and not entry.filename.startswith("__MACOSX/")
|
|
and PurePosixPath(entry.filename).suffix.lower() in {".stl", ".3mf"}
|
|
]
|
|
for name in names[:6]:
|
|
data = _read_member(archive, name, MAX_MODEL_BYTES)
|
|
if data:
|
|
preview = create_preview(BytesIO(data), PurePosixPath(name).suffix.lower())
|
|
if preview:
|
|
return preview
|
|
return b""
|
|
|
|
|
|
def _image_dimensions(data):
|
|
if data.startswith(PNG_SIGNATURE) and len(data) >= 33 and data[12:16] == b"IHDR":
|
|
return struct.unpack_from(">II", data, 16)
|
|
if data.startswith(b"\xff\xd8"):
|
|
offset = 2
|
|
while offset + 4 <= len(data) and data[offset] == 255:
|
|
marker = data[offset + 1]
|
|
if marker == 255:
|
|
offset += 1
|
|
continue
|
|
length = int.from_bytes(data[offset + 2 : offset + 4], "big")
|
|
if marker in {0xC0, 0xC1, 0xC2} and length >= 8 and offset + 9 <= len(data):
|
|
height, width = struct.unpack_from(">HH", data, offset + 5)
|
|
return width, height
|
|
if marker in {0xD9, 0xDA} or length < 2:
|
|
break
|
|
offset += 2 + length
|
|
return 0, 0
|
|
|
|
|
|
def _render_stl(file):
|
|
header = file.read(84)
|
|
if len(header) == 84:
|
|
count = int.from_bytes(header[80:84], "little")
|
|
if count and file.seek(0, 2) == 84 + count * STL_TRIANGLE.size:
|
|
file.seek(84)
|
|
return _render(_binary_triangles(file, count))
|
|
file.seek(0)
|
|
data = file.read(MAX_MODEL_BYTES + 1)
|
|
if len(data) > MAX_MODEL_BYTES or not data.lstrip().lower().startswith(b"solid"):
|
|
return b""
|
|
vertices = (tuple(map(float, match.groups())) for match in STL_VERTEX.finditer(data))
|
|
return _render(zip(vertices, vertices, vertices, strict=False))
|
|
|
|
|
|
def _binary_triangles(file, count):
|
|
step = max(1, math.ceil(count / MAX_TRIANGLES))
|
|
for _ in range(0, count, step):
|
|
values = STL_TRIANGLE.unpack(file.read(STL_TRIANGLE.size))
|
|
yield values[3:6], values[6:9], values[9:12]
|
|
if step > 1:
|
|
file.seek((step - 1) * STL_TRIANGLE.size, 1)
|
|
|
|
|
|
def _3mf_triangles(root):
|
|
objects = {item.get("id"): item for item in root.findall("./{*}resources/{*}object")}
|
|
builds = root.findall("./{*}build/{*}item")
|
|
identity = (1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)
|
|
visits = 0
|
|
meshes = {}
|
|
|
|
def emit(object_id, transforms, parents):
|
|
nonlocal visits
|
|
visits += 1
|
|
item = objects.get(object_id)
|
|
if item is None or object_id in parents or len(parents) >= 12 or visits > 256:
|
|
return
|
|
mesh = item.find("{*}mesh")
|
|
if mesh is not None:
|
|
if object_id not in meshes:
|
|
meshes[object_id] = _mesh_faces(mesh)
|
|
for face in meshes[object_id]:
|
|
for transform in transforms:
|
|
face = tuple(_transform(vertex, transform) for vertex in face)
|
|
yield face
|
|
for component in item.findall("./{*}components/{*}component"):
|
|
if "path" not in component.attrib and not any(
|
|
key.endswith("}path") for key in component.attrib
|
|
):
|
|
matrix = tuple(map(float, component.get("transform", "").split())) or identity
|
|
if len(matrix) == 12:
|
|
component_transforms = (
|
|
transforms if matrix == identity else (matrix, *transforms)
|
|
)
|
|
yield from emit(
|
|
component.get("objectid"), component_transforms, (*parents, object_id)
|
|
)
|
|
|
|
if builds:
|
|
for item in builds[:256]:
|
|
matrix = tuple(map(float, item.get("transform", "").split())) or identity
|
|
if len(matrix) == 12:
|
|
yield from emit(item.get("objectid"), () if matrix == identity else (matrix,), ())
|
|
else:
|
|
for object_id in list(objects)[:256]:
|
|
yield from emit(object_id, (), ())
|
|
|
|
|
|
def _mesh_faces(mesh):
|
|
vertices = [
|
|
tuple(float(vertex.attrib.get(axis, "nan")) for axis in ("x", "y", "z"))
|
|
for vertex in mesh.findall("./{*}vertices/{*}vertex")
|
|
]
|
|
triangles = mesh.findall("./{*}triangles/{*}triangle")
|
|
step = max(1, math.ceil(len(triangles) / MAX_TRIANGLES))
|
|
faces = []
|
|
for triangle in triangles[::step]:
|
|
try:
|
|
indexes = tuple(int(triangle.attrib[key]) for key in ("v1", "v2", "v3"))
|
|
if min(indexes) >= 0:
|
|
faces.append(tuple(vertices[index] for index in indexes))
|
|
except (IndexError, KeyError, ValueError):
|
|
continue
|
|
return faces
|
|
|
|
|
|
def _transform(vertex, matrix):
|
|
x, y, z = vertex
|
|
return tuple(
|
|
x * matrix[i] + y * matrix[i + 3] + z * matrix[i + 6] + matrix[i + 9] for i in range(3)
|
|
)
|
|
|
|
|
|
def _project(vertex):
|
|
x, y, z = vertex
|
|
return 0.83 * x - 0.56 * y, 0.29 * x + 0.43 * y - 0.85 * z, 0.48 * x + 0.71 * y + 0.52 * z
|
|
|
|
|
|
def _render(triangles):
|
|
faces = []
|
|
for triangle in islice(triangles, MAX_TRIANGLES):
|
|
if not all(
|
|
math.isfinite(value) and abs(value) < 1e12 for vertex in triangle for value in vertex
|
|
):
|
|
continue
|
|
a, b, c = triangle
|
|
u = tuple(b[i] - a[i] for i in range(3))
|
|
v = tuple(c[i] - a[i] for i in range(3))
|
|
nx, ny, nz = (
|
|
u[1] * v[2] - u[2] * v[1],
|
|
u[2] * v[0] - u[0] * v[2],
|
|
u[0] * v[1] - u[1] * v[0],
|
|
)
|
|
length = math.hypot(nx, ny, nz)
|
|
if not length:
|
|
continue
|
|
projected = tuple(map(_project, triangle))
|
|
shade = abs(0.27 * nx + 0.49 * ny + 0.83 * nz) / length
|
|
color = bytes(
|
|
round(base + shade * light) for base, light in ((21, 99), (92, 132), (85, 131))
|
|
)
|
|
faces.append((sum(point[2] for point in projected), projected, color))
|
|
if not faces:
|
|
return b""
|
|
xs, ys = zip(*((x, y) for _, points, _ in faces for x, y, _ in points), strict=True)
|
|
width, height = max(xs) - min(xs), max(ys) - min(ys)
|
|
extent = max(width, height)
|
|
if not extent:
|
|
return b""
|
|
scale = (SIZE - 20) / extent
|
|
left, top = min(xs) + width / 2, min(ys) + height / 2
|
|
pixels = bytearray(bytes((230, 244, 242)) * (SIZE * SIZE))
|
|
for _, points, color in sorted(faces, key=lambda face: face[0]):
|
|
points = [
|
|
((x - left) * scale + SIZE / 2, (y - top) * scale + SIZE / 2) for x, y, _ in points
|
|
]
|
|
_fill_triangle(pixels, points, color)
|
|
return _encode_png(pixels)
|
|
|
|
|
|
def _fill_triangle(pixels, points, color):
|
|
edges = list(zip(points, points[1:] + points[:1], strict=True))
|
|
rows = [point[1] for point in points]
|
|
for y in range(math.ceil(min(rows) - 0.5), math.ceil(max(rows) - 0.5)):
|
|
intersections = [
|
|
x1 + (y + 0.5 - y1) * (x2 - x1) / (y2 - y1)
|
|
for (x1, y1), (x2, y2) in edges
|
|
if min(y1, y2) <= y + 0.5 < max(y1, y2)
|
|
]
|
|
if len(intersections) == 2:
|
|
left, right = sorted(math.ceil(x - 0.5) for x in intersections)
|
|
start = (y * SIZE + left) * 3
|
|
pixels[start : start + (right - left) * 3] = color * (right - left)
|
|
|
|
|
|
def _encode_png(pixels):
|
|
def chunk(kind, data):
|
|
return (
|
|
struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
|
)
|
|
|
|
scanlines = b"".join(b"\0" + pixels[i : i + SIZE * 3] for i in range(0, len(pixels), SIZE * 3))
|
|
header = struct.pack(">IIBBBBB", SIZE, SIZE, 8, 2, 0, 0, 0)
|
|
return (
|
|
PNG_SIGNATURE
|
|
+ chunk(b"IHDR", header)
|
|
+ chunk(b"IDAT", zlib.compress(scanlines))
|
|
+ chunk(b"IEND", b"")
|
|
)
|