File size: 13,963 Bytes
5a5f252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1baefa4
5a5f252
 
 
 
 
 
 
1baefa4
 
5a5f252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1baefa4
5a5f252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1baefa4
5a5f252
 
 
 
 
 
 
 
 
 
 
1baefa4
5a5f252
 
 
1baefa4
5a5f252
 
 
 
 
 
 
 
 
 
 
 
1baefa4
 
 
 
5a5f252
 
 
1baefa4
5a5f252
1baefa4
 
5a5f252
 
1baefa4
 
 
 
 
 
5a5f252
 
1baefa4
5a5f252
 
 
1baefa4
 
 
 
 
 
 
 
 
 
 
 
 
5a5f252
 
1baefa4
 
5a5f252
 
1baefa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a5f252
 
1baefa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a5f252
 
 
 
 
 
 
1baefa4
58b1e11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""
relief_workshop.py
Image → 3D relief tile — versione workshop Fabrication Topologies
"""

import argparse
import struct
import sys
from pathlib import Path

import cv2
import numpy as np
from PIL import Image


def load_and_prepare(image_path: str, max_px: int) -> np.ndarray:
    img = Image.open(image_path).convert("RGB")
    ratio = min(max_px / img.width, max_px / img.height)
    new_w = max(2, int(img.width * ratio))
    new_h = max(2, int(img.height * ratio))
    img = img.resize((new_w, new_h), Image.LANCZOS)
    return np.array(img.convert("L"), dtype=np.float32)


def smooth_heightmap(gray: np.ndarray, blur: float) -> np.ndarray:
    if blur <= 0:
        return gray
    result = cv2.bilateralFilter(
        gray.astype(np.uint8), d=9,
        sigmaColor=min(60, blur * 15),
        sigmaSpace=min(10, blur * 3)
    ).astype(np.float32)
    return result


def quantize_heightmap(gray: np.ndarray, levels: int) -> np.ndarray:
    if levels < 2:
        return gray
    normalized = gray / 255.0
    quantized = np.floor(normalized * levels) / levels
    return (quantized * 255.0).astype(np.float32)


def make_tileable(gray: np.ndarray, fade_px: int) -> np.ndarray:
    if fade_px <= 0:
        return gray
    h, w = gray.shape
    mean_val = float(np.mean(gray))
    result = gray.copy()
    fade = min(fade_px, w // 4, h // 4)
    for i in range(fade):
        alpha = i / fade
        result[i, :] = alpha * gray[i, :] + (1 - alpha) * mean_val
        result[h - 1 - i, :] = alpha * gray[h - 1 - i, :] + (1 - alpha) * mean_val
        result[:, i] = alpha * result[:, i] + (1 - alpha) * mean_val
        result[:, w - 1 - i] = alpha * result[:, w - 1 - i] + (1 - alpha) * mean_val
    return result


def build_heightmap(
    image_path: str,
    max_px: int = 500,
    invert: bool = False,
    blur: float = 0.5,
    gamma: float = 1.1,
    quantize: int = 0,
    tileable: bool = False,
    fade_px: int = 8,
):
    gray = load_and_prepare(image_path, max_px)
    h, w = gray.shape
    gray = smooth_heightmap(gray, blur)
    gray = np.power(gray / 255.0, gamma) * 255.0
    if quantize >= 2:
        gray = quantize_heightmap(gray, quantize)
    if tileable:
        gray = make_tileable(gray, fade_px)
    if invert:
        gray = 255.0 - gray
    gray = np.clip(gray, 0, 255)
    return gray / 255.0, w, h


def _pack_triangle(normal, v1, v2, v3) -> bytes:
    return struct.pack("<ffffffffffffH", *normal, *v1, *v2, *v3, 0)


def heightmap_to_stl(
    height_map: np.ndarray,
    px_w: int,
    px_h: int,
    tile_w_mm: float,
    tile_h_mm: float,
    relief_mm: float,
    base_mm: float,
) -> bytes:
    """
    Genera STL da heightmap [0,1].
    Se base_mm == 0: mesh aperta sotto (solo superficie + pareti che scendono
    fino al punto più basso del rilievo, nessun piano inferiore).
    Se base_mm > 0: solido chiuso con base piatta.
    """
    pixel_x = tile_w_mm / (px_w - 1)
    pixel_y = tile_h_mm / (px_h - 1)
    no_base = (base_mm <= 0)

    def z_surf(row, col):
        # z della superficie di rilievo
        return base_mm + height_map[row, col] * relief_mm

    def z_bottom(row, col):
        # z del bordo inferiore: 0 se c'è la base, minimo locale se no
        if no_base:
            return height_map[row, col] * relief_mm  # inizia dal rilievo stesso (min=0)
        return 0.0

    triangles = []

    # ── Superficie superiore ──
    for row in range(px_h - 1):
        for col in range(px_w - 1):
            x0, x1 = col * pixel_x, (col + 1) * pixel_x
            y0 = (px_h - 1 - row) * pixel_y
            y1 = (px_h - 2 - row) * pixel_y

            z00 = z_surf(row, col)
            z10 = z_surf(row, col + 1)
            z01 = z_surf(row + 1, col)
            z11 = z_surf(row + 1, col + 1)

            v00, v10 = (x0, y0, z00), (x1, y0, z10)
            v01, v11 = (x0, y1, z01), (x1, y1, z11)

            e1 = np.subtract(v10, v00); e2 = np.subtract(v01, v00)
            n = np.cross(e1, e2); nn = n / (np.linalg.norm(n) + 1e-12)
            triangles.append(_pack_triangle(nn, v00, v10, v01))

            e1 = np.subtract(v01, v11); e2 = np.subtract(v10, v11)
            n = np.cross(e1, e2); nn = n / (np.linalg.norm(n) + 1e-12)
            triangles.append(_pack_triangle(nn, v11, v01, v10))

    # ── Base inferiore (solo se base_mm > 0) ──
    if not no_base:
        for row in range(px_h - 1):
            for col in range(px_w - 1):
                x0, x1 = col * pixel_x, (col + 1) * pixel_x
                y0 = (px_h - 1 - row) * pixel_y
                y1 = (px_h - 2 - row) * pixel_y
                n = (0.0, 0.0, -1.0)
                triangles.append(_pack_triangle(n, (x0,y0,0),(x0,y1,0),(x1,y0,0)))
                triangles.append(_pack_triangle(n, (x1,y1,0),(x1,y0,0),(x0,y1,0)))

    W, H = tile_w_mm, tile_h_mm

    if no_base:
        # Senza base: le pareti laterali collegano la superficie al suo stesso
        # bordo inferiore (z = height_map * relief_mm, cioè parte da 0 al minimo)
        # Fronte (y=0, row = px_h-1)
        for col in range(px_w - 1):
            x0, x1 = col * pixel_x, (col + 1) * pixel_x
            zt0 = z_surf(px_h - 1, col);     zt1 = z_surf(px_h - 1, col + 1)
            zb0 = height_map[px_h-1, col] * relief_mm
            zb1 = height_map[px_h-1, col+1] * relief_mm
            n = (0.0, -1.0, 0.0)
            triangles.append(_pack_triangle(n, (x0,0,zb0),(x1,0,zt1),(x0,0,zt0)))
            triangles.append(_pack_triangle(n, (x0,0,zb0),(x1,0,zb1),(x1,0,zt1)))

        # Retro (y=H, row = 0)
        for col in range(px_w - 1):
            x0, x1 = col * pixel_x, (col + 1) * pixel_x
            zt0 = z_surf(0, col);     zt1 = z_surf(0, col + 1)
            zb0 = height_map[0, col] * relief_mm
            zb1 = height_map[0, col+1] * relief_mm
            n = (0.0, 1.0, 0.0)
            triangles.append(_pack_triangle(n, (x0,H,zt0),(x1,H,zt1),(x0,H,zb0)))
            triangles.append(_pack_triangle(n, (x1,H,zt1),(x1,H,zb1),(x0,H,zb0)))

        # Sinistra (x=0, col=0)
        for row in range(px_h - 1):
            y0 = (px_h - 1 - row) * pixel_y
            y1 = (px_h - 2 - row) * pixel_y
            zt0 = z_surf(row, 0);       zt1 = z_surf(row + 1, 0)
            zb0 = height_map[row, 0] * relief_mm
            zb1 = height_map[row+1, 0] * relief_mm
            n = (-1.0, 0.0, 0.0)
            triangles.append(_pack_triangle(n, (0,y0,zt0),(0,y1,zt1),(0,y0,zb0)))
            triangles.append(_pack_triangle(n, (0,y1,zt1),(0,y1,zb1),(0,y0,zb0)))

        # Destra (x=W, col=px_w-1)
        for row in range(px_h - 1):
            y0 = (px_h - 1 - row) * pixel_y
            y1 = (px_h - 2 - row) * pixel_y
            zt0 = z_surf(row, px_w-1);   zt1 = z_surf(row+1, px_w-1)
            zb0 = height_map[row, px_w-1] * relief_mm
            zb1 = height_map[row+1, px_w-1] * relief_mm
            n = (1.0, 0.0, 0.0)
            triangles.append(_pack_triangle(n, (W,y0,zb0),(W,y1,zt1),(W,y0,zt0)))
            triangles.append(_pack_triangle(n, (W,y0,zb0),(W,y1,zb1),(W,y1,zt1)))

    else:
        # Con base: pareti vanno da z=0 alla superficie
        # Fronte
        for col in range(px_w - 1):
            x0, x1 = col * pixel_x, (col + 1) * pixel_x
            zt0 = z_surf(px_h-1, col); zt1 = z_surf(px_h-1, col+1)
            n = (0.0, -1.0, 0.0)
            triangles.append(_pack_triangle(n,(x0,0,0),(x1,0,zt1),(x0,0,zt0)))
            triangles.append(_pack_triangle(n,(x0,0,0),(x1,0,0),(x1,0,zt1)))

        # Retro
        for col in range(px_w - 1):
            x0, x1 = col * pixel_x, (col + 1) * pixel_x
            zt0 = z_surf(0, col); zt1 = z_surf(0, col+1)
            n = (0.0, 1.0, 0.0)
            triangles.append(_pack_triangle(n,(x0,H,zt0),(x1,H,zt1),(x0,H,0)))
            triangles.append(_pack_triangle(n,(x1,H,zt1),(x1,H,0),(x0,H,0)))

        # Sinistra
        for row in range(px_h - 1):
            y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_y
            zt0 = z_surf(row,0); zt1 = z_surf(row+1,0)
            n = (-1.0, 0.0, 0.0)
            triangles.append(_pack_triangle(n,(0,y0,zt0),(0,y1,zt1),(0,y0,0)))
            triangles.append(_pack_triangle(n,(0,y1,0),(0,y0,0),(0,y1,zt1)))

        # Destra
        for row in range(px_h - 1):
            y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_y
            zt0 = z_surf(row,px_w-1); zt1 = z_surf(row+1,px_w-1)
            n = (1.0, 0.0, 0.0)
            triangles.append(_pack_triangle(n,(W,y0,0),(W,y1,zt1),(W,y0,zt0)))
            triangles.append(_pack_triangle(n,(W,y0,0),(W,y1,0),(W,y1,zt1)))

    header = b"\x00" * 80
    count = struct.pack("<I", len(triangles))
    return header + count + b"".join(triangles)


def save_depth_preview(height_map: np.ndarray, out_path: str):
    Image.fromarray((height_map * 255).astype(np.uint8)).save(out_path)


# ─────────────────────────────────────────────
# BLOB PIPELINE (pezzi separati)
# ─────────────────────────────────────────────

def _contour_to_stl(contour, height_mm: float) -> bytes:
    """
    Converte un singolo contorno OpenCV in un solido STL chiuso
    (cilindretto: cappello superiore + base piatta + pareti laterali).
    Il contorno è in coordinate pixel; scaliamo dopo.
    """
    import struct
    pts = contour.reshape(-1, 2).astype(float)
    n = len(pts)
    if n < 3:
        return b""

    # Centra e normalizza — scala 1 px = 1 unità, poi il chiamante ri-scala
    # Triangolazione fan dalla centroide per cappello e base
    cx, cy = pts[:, 0].mean(), pts[:, 1].mean()

    def pack_tri(normal, v1, v2, v3):
        return struct.pack("<ffffffffffffH", *normal, *v1, *v2, *v3, 0)

    tris = []
    # Cappello superiore (z = height_mm) — fan dalla centroide
    for i in range(n):
        a = pts[i]
        b = pts[(i + 1) % n]
        v0 = (cx,    cy,    height_mm)
        v1 = (a[0],  a[1],  height_mm)
        v2 = (b[0],  b[1],  height_mm)
        e1 = (v1[0]-v0[0], v1[1]-v0[1], 0)
        e2 = (v2[0]-v0[0], v2[1]-v0[1], 0)
        nx = e1[1]*e2[2] - e1[2]*e2[1]
        ny = e1[2]*e2[0] - e1[0]*e2[2]
        nz = e1[0]*e2[1] - e1[1]*e2[0]
        ln = (nx**2+ny**2+nz**2)**0.5 + 1e-12
        tris.append(pack_tri((nx/ln, ny/ln, nz/ln), v0, v1, v2))

    # Base inferiore (z = 0) — fan inverso
    for i in range(n):
        a = pts[i]
        b = pts[(i + 1) % n]
        v0 = (cx,    cy,    0)
        v1 = (b[0],  b[1],  0)
        v2 = (a[0],  a[1],  0)
        tris.append(pack_tri((0, 0, -1), v0, v1, v2))

    # Pareti laterali
    for i in range(n):
        a = pts[i]
        b = pts[(i + 1) % n]
        # due triangoli per ogni segmento
        v00 = (a[0], a[1], 0)
        v10 = (b[0], b[1], 0)
        v01 = (a[0], a[1], height_mm)
        v11 = (b[0], b[1], height_mm)
        # normale laterale approssimata
        dx, dy = b[0]-a[0], b[1]-a[1]
        ln = (dx**2+dy**2)**0.5 + 1e-12
        nx, ny = dy/ln, -dx/ln
        tris.append(pack_tri((nx, ny, 0), v00, v10, v01))
        tris.append(pack_tri((nx, ny, 0), v10, v11, v01))

    header = b"\x00" * 80
    count = struct.pack("<I", len(tris))
    return header + count + b"".join(tris)


def blobs_to_stl(
    image_path: str,
    tile_w_mm: float,
    tile_h_mm: float,
    height_mm: float,
    threshold: int = 127,
    min_area_px: int = 20,
) -> tuple[bytes, int]:
    """
    Pipeline blob: soglia binaria → findContours → un cilindretto per blob.
    Restituisce (stl_bytes, n_blobs).
    Tutti i cilindretti sono nella stessa mesh (un solo file STL).
    """
    img = Image.open(image_path).convert("L")
    arr = np.array(img, dtype=np.uint8)

    # Scala pixel → mm
    scale_x = tile_w_mm / arr.shape[1]
    scale_y = tile_h_mm / arr.shape[0]

    # Soglia binaria
    _, binary = cv2.threshold(arr, threshold, 255, cv2.THRESH_BINARY)

    # Trova contorni esterni
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    all_tris = []
    n_blobs = 0

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area < min_area_px:
            continue

        # Semplifica il contorno per ridurre la mesh
        eps = 0.01 * cv2.arcLength(cnt, True)
        cnt = cv2.approxPolyDP(cnt, eps, True)
        pts = cnt.reshape(-1, 2).astype(float)
        if len(pts) < 3:
            continue

        # Converti pixel → mm (y invertita: OpenCV ha y verso il basso)
        pts[:, 0] *= scale_x
        pts[:, 1] = tile_h_mm - pts[:, 1] * scale_y

        # Genera STL del singolo blob
        blob_bytes = _contour_to_stl(pts.reshape(-1, 1, 2), height_mm)
        if blob_bytes:
            # Estrai solo i triangoli (salta header 84 byte)
            n_tri = (len(blob_bytes) - 84) // 50
            all_tris.append(blob_bytes[84:])
            n_blobs += 1

    if not all_tris:
        raise ValueError("Nessun blob trovato. Prova ad abbassare la soglia o caricare un'immagine con forme bianche su sfondo nero.")

    import struct
    total_tris = sum(len(t) // 50 for t in all_tris)
    header = b"\x00" * 80
    count = struct.pack("<I", total_tris)
    return header + count + b"".join(all_tris), n_blobs


def blob_preview(image_path: str, threshold: int = 127, min_area_px: int = 20) -> np.ndarray:
    """Restituisce un'immagine con i contorni trovati disegnati sopra l'originale."""
    img = Image.open(image_path).convert("L")
    arr = np.array(img, dtype=np.uint8)
    _, binary = cv2.threshold(arr, threshold, 255, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    preview = cv2.cvtColor(arr, cv2.COLOR_GRAY2RGB)
    valid = [c for c in contours if cv2.contourArea(c) >= min_area_px]
    cv2.drawContours(preview, valid, -1, (212, 169, 18), 2)
    return preview, len(valid)