working on 3d cards

This commit is contained in:
2025-08-06 16:26:26 +02:00
parent 7c24d9a7c5
commit 6872056901
3 changed files with 267 additions and 27 deletions

View File

@ -13,6 +13,13 @@ from typing import List, Dict, Any
import pandas as pd
import re
from enum import Enum
from solid import *
from solid.utils import *
import numpy as np
import trimesh
import cairosvg
MAX_ALBUM_IMG_SIZE = 512
@ -238,6 +245,165 @@ class HipsterfyPlaylistItem(object):
</div>
"""
def create_text_mesh_svg(self, text, font_size=100, extrude_height=1.0, font_family="Arial"):
# Define a rough bounding box size (oversized is OK, it will crop to path later)
svg_width = font_size * len(text) * 0.6 # heuristic width
svg_height = font_size * 1.5 # little padding below
# 1. Create SVG with size attributes!
svg_template = f'''<?xml version="1.0" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" width="{svg_width}px" height="{svg_height}px" viewBox="0 0 {svg_width} {svg_height}">
<text x="0" y="{font_size}" font-family="{font_family}" font-size="{font_size}px">{text}</text>
</svg>'''
# 2. Use CairoSVG to convert to SVG with <path> outlines (in-memory)
outlined_svg = BytesIO()
cairosvg.svg2svg(bytestring=svg_template.encode('utf-8'), write_to=outlined_svg)
outlined_svg.seek(0)
# 3. Load the SVG Path into Trimesh
path = trimesh.load_path(outlined_svg, "svg")
# 4. Get closed polygons
polygons = path.polygons_full
if len(polygons) == 0:
raise ValueError("No polygons found in SVG. Make sure the font is available.")
# 5. Extrude into 3D meshes
meshes = []
for p in polygons:
mesh = trimesh.creation.extrude_polygon(p, height=extrude_height)
# Fix potential non-watertight edges
mesh = mesh.copy().process(validate=True)
if not mesh.is_watertight:
print("Warning: Mesh is not watertight. Trying to fix...")
mesh = mesh.convex_hull # Hack: force watertight by convex hull
meshes.append(mesh)
text_mesh = trimesh.util.concatenate(meshes)
text_mesh.apply_translation(-text_mesh.centroid)
# Final safety net
if not text_mesh.is_watertight:
print("Final Warning: Text mesh still not watertight after fix.")
return text_mesh
def generate_3d_qr_card(
self,
primary_property,
secondary_property,
additional_properties: List[str] = None,
card_size=60,
card_thickness=3,
qr_relief_depth=0.5, # Tiefe der Vertiefung
qr_margin=8
):
"""
Generates a 3D card (STL as bytes) with a sunken QR code (engraved).
Returns: STL file as bytes.
"""
qr = qrcode.QRCode(box_size=1, border=0)
qr.add_data(self.link)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white").convert("1")
arr = np.array(img)
h, w = arr.shape
pixel_size = (card_size - 2 * qr_margin) / w
# Grundplatte
base = trimesh.creation.box(extents=(card_size, card_size, card_thickness))
base.apply_translation((card_size/2, card_size/2, card_thickness/2))
# QR-Vertiefung (nur die weißen Felder bleiben stehen, schwarze werden "eingesunken")
cutouts_xa_ya = []
cutouts_xa_yb = []
cutouts_xb_ya = []
cutouts_xb_yb = []
for y in range(h):
for x in range(w):
if arr[y, x] == 0: # Schwarzes Pixel → wird vertieft
px = qr_margin + x * pixel_size + pixel_size/2
py = qr_margin + (h - y - 1) * pixel_size + pixel_size/2
cube = trimesh.creation.box(extents=(pixel_size * 1.00001, pixel_size * 1.00001, qr_relief_depth))
cube.apply_translation((px, py, card_thickness - qr_relief_depth/2))
if y % 2 == 0:
if x % 2 == 0:
cutouts_xa_ya.append(cube)
else:
cutouts_xa_yb.append(cube)
else:
if x % 2 == 0:
cutouts_xb_ya.append(cube)
else:
cutouts_xb_yb.append(cube)
card = base
if cutouts_xa_ya:
cutout_xa_ya = trimesh.util.concatenate(cutouts_xa_ya)
card = card.difference(cutout_xa_ya)
if cutouts_xa_yb:
cutout_xa_yb = trimesh.util.concatenate(cutouts_xa_yb)
card = card.difference(cutout_xa_yb)
if cutouts_xb_ya:
cutout_xb_ya = trimesh.util.concatenate(cutouts_xb_ya)
card = card.difference(cutout_xb_ya)
if cutouts_xb_yb:
cutout_xb_yb = trimesh.util.concatenate(cutouts_xb_yb)
card = card.difference(cutout_xb_yb)
# engrave the text to the lower card side
lines = []
if primary_property:
lines.append(str(getattr(self, primary_property, "")))
if secondary_property:
lines.append(str(getattr(self, secondary_property, "")))
if additional_properties:
for prop in additional_properties:
value = getattr(self, prop, "")
if value:
lines.append(f"{prop.replace('_', ' ').title()}: {value}")
text_depth = qr_relief_depth
text_size = card_size * 0.09 # Schriftgröße relativ zur Karte
# Combine into one mesh
text_mesh = self.create_text_mesh_svg("\n".join(lines), font_size=text_size, extrude_height=text_depth, font_family="Arial")
# Center the text mesh
text_mesh.apply_translation((-text_mesh.centroid[0], -text_mesh.centroid[1], 0))
# Position the text mesh on the card
text_mesh.apply_translation((card_size / 2, card_size / 2, card_thickness - text_depth / 2))
# Text von der Karte abziehen (gravieren)
card = card.difference(text_mesh, check_volume=True)
## round corners
radius = 5
corners = [
(radius, radius, 0),
(card_size - radius, radius, 0),
(card_size - radius, card_size - radius, 0),
(radius, card_size - radius, 0)
]
plate_offsets = [
(radius / 2, radius / 2, 0),
(card_size - radius / 2, radius / 2, 0),
(card_size - radius / 2, card_size - radius / 2, 0),
(radius / 2, card_size - radius / 2, 0)
]
for i, corner in enumerate(corners ):
plate = trimesh.creation.box(extents=(radius, radius, card_thickness))
plate.apply_translation((plate_offsets[i][0], plate_offsets[i][1], card_thickness / 2))
cylinder = trimesh.creation.cylinder(radius=radius, height=card_thickness, sections=64)
cylinder.apply_translation((corner[0], corner[1], corner[2] + card_thickness / 2))
inverse_corner = plate.difference(cylinder)
card = card.difference(inverse_corner, check_volume=True)
return card.export(file_type='stl')
@staticmethod
def get_available_properties() -> List[str]:
"""
@ -416,3 +582,4 @@ class HipsterfyPlaylist(object):
"""Returns the list of HipsterfyPlaylistItem objects representing the tracks in the playlist.
"""
return self._tracks_data