import hashlib import json from pathlib import Path import bpy from mathutils import Vector from mathutils.bvhtree import BVHTree ROOT = Path(__file__).resolve().parent MILK_DIR = ROOT / "milk_2l" ORANGE_DIR = ROOT / "orange_juice_2l" MILK_SOURCE = MILK_DIR / "PerfectCoffee_milk_2l.blend" ORANGE_SOURCE = ORANGE_DIR / "PerfectCoffee_orange_juice_2l_MilkJug.blend" MILK_BLEND = MILK_DIR / "PerfectCoffee_milk_2l_Empty.blend" MILK_GLB = MILK_BLEND.with_suffix(".glb") ORANGE_BLEND = ORANGE_DIR / "PerfectCoffee_orange_juice_2l_MilkJug_LabelTest.blend" ORANGE_GLB = ORANGE_BLEND.with_suffix(".glb") TEXTURE = ROOT / "labels" / "orange_juice" / "orange_juice_wrap_wide.png" ALPHA = 0.15 LABEL_Z_MIN = 0.025 LABEL_Z_MAX = 0.115 LABEL_OFFSET = 0.00006 HANDLE_BOTTOM = 0.122 def sha256(path): return hashlib.sha256(path.read_bytes()).hexdigest() def mesh_objects(): return [obj for obj in bpy.context.scene.objects if obj.type == "MESH" and not obj.name.startswith("Studio_")] def triangle_count(objects): total = 0 for obj in objects: obj.data.calc_loop_triangles() total += len(obj.data.loop_triangles) return total def export_collection(path): collection = bpy.data.collections["Model"] bpy.ops.object.select_all(action="DESELECT") for obj in collection.all_objects: obj.select_set(True) bpy.context.view_layer.objects.active = next(obj for obj in collection.all_objects if obj.type == "MESH") bpy.ops.export_scene.gltf( filepath=str(path), export_format="GLB", use_selection=True, export_yup=True, export_apply=True, export_texcoords=True, export_cameras=False, export_lights=False, ) def remove_liquid(): removed = [] for obj in mesh_objects(): if any(token in obj.name.lower() for token in ("liquid", "_fill", "contents")): removed.append(obj.name) bpy.data.objects.remove(obj, do_unlink=True) return removed def set_opacity(body, name): material = body.data.materials[0].copy() material.name = name material.diffuse_color = (*material.diffuse_color[:3], ALPHA) material.use_nodes = True material.surface_render_method = "DITHERED" material.use_backface_culling = False material.node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value = ALPHA body.data.materials.clear() body.data.materials.append(material) for polygon in body.data.polygons: polygon.material_index = 0 def render_views(views, cap_pivot=None): scene = bpy.context.scene camera = scene.camera camera_matrix = camera.matrix_world.copy() camera_scale = camera.data.ortho_scale resolution = scene.render.resolution_x, scene.render.resolution_y bpy.ops.render.render(write_still=True) if cap_pivot: location = cap_pivot.location.copy() cap_pivot.location += Vector((0.045, 0, 0.055)) scene.render.filepath = views["cap_removed"] bpy.ops.render.render(write_still=True) cap_pivot.location = location for name, position, target, scale in views["details"]: camera.location = position target = Vector(target) camera.rotation_euler = (target - camera.location).to_track_quat("-Z", "Y").to_euler() camera.data.ortho_scale = scale scene.render.resolution_x = 900 scene.render.resolution_y = 900 scene.render.filepath = name bpy.ops.render.render(write_still=True) camera.matrix_world = camera_matrix camera.data.ortho_scale = camera_scale scene.render.resolution_x, scene.render.resolution_y = resolution scene.render.filepath = views["main"] def clip_polygon(points, threshold, keep_above): result = [] for first, second in zip(points, points[1:] + points[:1]): first_inside = first.z >= threshold if keep_above else first.z <= threshold second_inside = second.z >= threshold if keep_above else second.z <= threshold if first_inside: result.append(first.copy()) if first_inside != second_inside: amount = (threshold - first.z) / (second.z - first.z) result.append(first.lerp(second, amount)) return result def cross_2d(origin, first, second): return (first[0] - origin[0]) * (second[1] - origin[1]) - (first[1] - origin[1]) * (second[0] - origin[0]) def convex_hull(points): points = sorted(set((round(point[0], 7), round(point[1], 7)) for point in points)) lower = [] for point in points: while len(lower) >= 2 and cross_2d(lower[-2], lower[-1], point) <= 0: lower.pop() lower.append(point) upper = [] for point in reversed(points): while len(upper) >= 2 and cross_2d(upper[-2], upper[-1], point) <= 0: upper.pop() upper.append(point) return lower[:-1] + upper[:-1] def perimeter_mapping(points): hull = convex_hull(points) back_index = max(range(len(hull)), key=lambda i: (hull[i][1] + hull[(i + 1) % len(hull)][1]) / 2) first = Vector(hull[back_index]) second = Vector(hull[(back_index + 1) % len(hull)]) start = (first + second) / 2 outline = [start] + [Vector(hull[i]) for i in range(back_index + 1, len(hull))] outline += [Vector(hull[i]) for i in range(back_index + 1)] + [start] lengths = [(second - first).length for first, second in zip(outline[:-1], outline[1:])] total = sum(lengths) def map_point(point): point = Vector(point) best_distance = None best_length = 0.0 accumulated = 0.0 for first, second, length in zip(outline[:-1], outline[1:], lengths): edge = second - first amount = max(0.0, min(1.0, (point - first).dot(edge) / edge.length_squared)) nearest = first + amount * edge distance = (point - nearest).length_squared if best_distance is None or distance < best_distance: best_distance = distance best_length = accumulated + amount * length accumulated += length return best_length / total return map_point, total def create_label(body, root): polygons = [] for polygon in body.data.polygons: if abs(polygon.normal.z) > 0.1: continue if polygon.center.x * polygon.normal.x + polygon.center.y * polygon.normal.y <= 0: continue points = [body.data.vertices[index].co.copy() for index in polygon.vertices] if max(point.z for point in points) < LABEL_Z_MIN or min(point.z for point in points) > LABEL_Z_MAX: continue clipped = clip_polygon(clip_polygon(points, LABEL_Z_MIN, True), LABEL_Z_MAX, False) if len(clipped) >= 3: polygons.append(clipped) vertices = [] faces = [] vertex_map = {} for polygon in polygons: face = [] for point in polygon: key = tuple(round(value, 7) for value in point) if key not in vertex_map: vertex_map[key] = len(vertices) vertices.append(tuple(point)) face.append(vertex_map[key]) faces.append(tuple(face)) assert len(faces) >= 8, f"Unexpected label surface face count: {len(faces)}" mesh = bpy.data.meshes.new("OrangeJuice_Label_Surface_Mesh") mesh.from_pydata(vertices, [], faces) mesh.update() label = bpy.data.objects.new("OrangeJuice_Label_Surface", mesh) bpy.data.collections["Model"].objects.link(label) label.parent = root map_point, perimeter = perimeter_mapping(vertices) uv = mesh.uv_layers.new(name="UVMap_TightLabel") for polygon in mesh.polygons: values = [] for loop_index in polygon.loop_indices: vertex = mesh.vertices[mesh.loops[loop_index].vertex_index].co u = map_point((vertex.x, vertex.y)) v = (vertex.z - LABEL_Z_MIN) / (LABEL_Z_MAX - LABEL_Z_MIN) values.append((loop_index, u, v)) if max(value[1] for value in values) - min(value[1] for value in values) > 0.5: values = [(index, u + 1 if u < 0.5 else u, v) for index, u, v in values] for loop_index, u, v in values: uv.data[loop_index].uv = (u, v) image = bpy.data.images.load(str(TEXTURE), check_existing=True) image.name = "OrangeJuice_Wrap_Tight" image.use_fake_user = True image.pack() material = bpy.data.materials.new("OrangeJuice_Label_Tight") material.use_nodes = True material.use_backface_culling = False output = material.node_tree.nodes.get("Material Output") shader = material.node_tree.nodes.get("Principled BSDF") texture = material.node_tree.nodes.new("ShaderNodeTexImage") texture.image = image texture.extension = "REPEAT" texture.interpolation = "Linear" shader.inputs["Roughness"].default_value = 0.62 material.node_tree.links.new(texture.outputs["Color"], shader.inputs["Base Color"]) material.node_tree.links.new(shader.outputs["BSDF"], output.inputs["Surface"]) mesh.materials.append(material) modifier = label.modifiers.new("Tight_To_Bottle", "SHRINKWRAP") modifier.target = body modifier.wrap_method = "NEAREST_SURFACEPOINT" modifier.wrap_mode = "OUTSIDE_SURFACE" modifier.offset = LABEL_OFFSET label["label_surface_offset_m"] = LABEL_OFFSET label["label_z_range_m"] = [LABEL_Z_MIN, LABEL_Z_MAX] label["below_handle"] = True label["texture_contains_percentage_claim"] = False root["label_fit_method"] = "Surface-cut geometry with shrinkwrap to the actual bottle exterior" return label, perimeter, len(polygons) def surface_gaps(body, label): bpy.context.view_layer.update() depsgraph = bpy.context.evaluated_depsgraph_get() tree = BVHTree.FromObject(body, depsgraph) evaluated = label.evaluated_get(depsgraph) mesh = evaluated.to_mesh() inverse = body.matrix_world.inverted() gaps = [] for vertex in mesh.vertices: point = inverse @ (label.matrix_world @ vertex.co) nearest, normal, _, distance = tree.find_nearest(point) signed = (point - nearest).dot(normal) gaps.append(signed) evaluated.to_mesh_clear() return [min(gaps) * 1000, max(gaps) * 1000] def make_milk(): bpy.ops.wm.open_mainfile(filepath=str(MILK_SOURCE)) bpy.context.preferences.filepaths.save_version = 0 removed = remove_liquid() assert {obj.name for obj in mesh_objects()} == {"Milk_Bottle_Body", "Milk_Cap"} body = bpy.data.objects["Milk_Bottle_Body"] set_opacity(body, "Milk_HDPE_Observe15") root = bpy.data.objects["Milk2L_Root"] root.name = "Milk2L_Empty_Root" root["interior_empty"] = True root["modeled_liquid_ml"] = 0.0 root["body_opacity"] = ALPHA export_collection(MILK_GLB) scene = bpy.context.scene scene.render.filepath = str(MILK_DIR / "preview_empty15.png") render_views({ "main": str(MILK_DIR / "preview_empty15.png"), "cap_removed": str(MILK_DIR / "preview_empty15_cap_removed.png"), "details": [], }, bpy.data.objects["Milk_Cap_Pivot"]) assert sha256(MILK_SOURCE) == SOURCE_HASHES[MILK_SOURCE] bpy.ops.wm.save_as_mainfile(filepath=str(MILK_BLEND), compress=True) return removed def make_orange(): bpy.ops.wm.open_mainfile(filepath=str(ORANGE_SOURCE)) bpy.context.preferences.filepaths.save_version = 0 removed = remove_liquid() assert {obj.name for obj in mesh_objects()} == {"OrangeJuice_Bottle_Body", "OrangeJuice_Cap"} body = bpy.data.objects["OrangeJuice_Bottle_Body"] set_opacity(body, "OrangeJuice_PET_Observe15") root = bpy.data.objects["OrangeJuice2L_MilkJug_Root"] root.name = "OrangeJuice2L_MilkJug_LabelTest_Root" root["interior_empty"] = True root["modeled_liquid_ml"] = 0.0 root["body_opacity"] = ALPHA label, perimeter, source_face_count = create_label(body, root) export_collection(ORANGE_GLB) scene = bpy.context.scene scene.render.filepath = str(ORANGE_DIR / "preview_label_test.png") render_views({ "main": str(ORANGE_DIR / "preview_label_test.png"), "cap_removed": None, "details": [ (str(ORANGE_DIR / "preview_label_test_front.png"), (0, -0.55, 0.18), (0, 0, 0.14), 0.325), (str(ORANGE_DIR / "preview_label_test_back.png"), (0, 0.55, 0.18), (0, 0, 0.14), 0.325), (str(ORANGE_DIR / "preview_label_fit.png"), (0.20, -0.28, 0.16), (0, 0, 0.075), 0.205), ], }) assert sha256(ORANGE_SOURCE) == SOURCE_HASHES[ORANGE_SOURCE] bpy.ops.wm.save_as_mainfile(filepath=str(ORANGE_BLEND), compress=True) return { "removed_liquid_objects": removed, "label_source_face_count": source_face_count, "label_perimeter_m": perimeter, "label_surface_gap_mm": surface_gaps(body, label), } def validate_milk(removed): bpy.ops.wm.open_mainfile(filepath=str(MILK_BLEND)) native_triangles = triangle_count(mesh_objects()) native_alpha = bpy.data.materials["Milk_HDPE_Observe15"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value native_ok = ( native_triangles == 906 and abs(native_alpha - ALPHA) < 0.00001 and bpy.data.objects.get("OrangeJuice_Juice_Fill") is None and len(mesh_objects()) == 2 ) bpy.ops.wm.read_factory_settings(use_empty=True) bpy.ops.import_scene.gltf(filepath=str(MILK_GLB)) glb_triangles = triangle_count(mesh_objects()) glb_alpha = bpy.data.materials["Milk_HDPE_Observe15"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value glb_ok = glb_triangles == 906 and abs(glb_alpha - ALPHA) < 0.00001 and len(mesh_objects()) == 2 assert native_ok and glb_ok report = { "asset": "Milk2L_Empty_Root", "source_model": "model_assets/milk_2l/PerfectCoffee_milk_2l.blend", "source_unchanged": True, "body_opacity": ALPHA, "interior_empty": True, "removed_liquid_objects": removed, "native_triangles": native_triangles, "glb_triangles": glb_triangles, "native_reopen_passed": native_ok, "glb_reimport_passed": glb_ok, "technical_validation_passed": True, "visual_review_passed": False, "passed": False, "blend": MILK_BLEND.name, "glb": MILK_GLB.name, "preview": "preview_empty15.png", "preview_cap_removed": "preview_empty15_cap_removed.png", } (MILK_DIR / "validation_empty15.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") return report def validate_orange(fit_data): bpy.ops.wm.open_mainfile(filepath=str(ORANGE_BLEND)) body = bpy.data.objects["OrangeJuice_Bottle_Body"] label = bpy.data.objects["OrangeJuice_Label_Surface"] native_triangles = triangle_count(mesh_objects()) native_alpha = bpy.data.materials["OrangeJuice_PET_Observe15"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value native_gaps = surface_gaps(body, label) texture = bpy.data.materials["OrangeJuice_Label_Tight"].node_tree.nodes.get("Image Texture") native_ok = ( native_triangles <= 1000 and len(mesh_objects()) == 3 and abs(native_alpha - ALPHA) < 0.00001 and label.modifiers["Tight_To_Bottle"].target == body and bool(label.data.uv_layers) and texture is not None and list(texture.image.size) == [3584, 768] and texture.image.packed_file is not None and max(native_gaps) <= 0.061 and min(native_gaps) > 0 and LABEL_Z_MAX < HANDLE_BOTTOM ) bpy.ops.wm.read_factory_settings(use_empty=True) bpy.ops.import_scene.gltf(filepath=str(ORANGE_GLB)) imported_objects = mesh_objects() body = bpy.data.objects["OrangeJuice_Bottle_Body"] label = bpy.data.objects["OrangeJuice_Label_Surface"] glb_triangles = triangle_count(imported_objects) glb_alpha = bpy.data.materials["OrangeJuice_PET_Observe15"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value glb_gaps = surface_gaps(body, label) glb_texture = bpy.data.materials["OrangeJuice_Label_Tight"].node_tree.nodes.get("Image Texture") glb_ok = ( glb_triangles == native_triangles and len(imported_objects) == 3 and abs(glb_alpha - ALPHA) < 0.00001 and bool(label.data.uv_layers) and glb_texture is not None and list(glb_texture.image.size) == [3584, 768] and max(glb_gaps) <= 0.061 and min(glb_gaps) > 0 ) assert native_ok and glb_ok, "Tight label or empty bottle validation failed" report = { "asset": "OrangeJuice2L_MilkJug_LabelTest_Root", "source_model": "model_assets/orange_juice_2l/PerfectCoffee_orange_juice_2l_MilkJug.blend", "source_unchanged": True, "body_opacity": ALPHA, "interior_empty": True, "removed_liquid_objects": fit_data["removed_liquid_objects"], "native_triangles": native_triangles, "glb_triangles": glb_triangles, "triangle_limit": 1000, "cap_color": "orange", "cap_independent": True, "label_method": "Clipped bottle-surface mesh with shrinkwrap", "label_z_range_m": [LABEL_Z_MIN, LABEL_Z_MAX], "handle_bottom_z_m": HANDLE_BOTTOM, "label_below_handle": True, "label_nominal_offset_mm": LABEL_OFFSET * 1000, "native_surface_gap_mm": native_gaps, "glb_surface_gap_mm": glb_gaps, "label_source_face_count": fit_data["label_source_face_count"], "label_perimeter_m": fit_data["label_perimeter_m"], "texture_dimensions": [3584, 768], "percentage_purity_claims_present": False, "native_reopen_passed": native_ok, "glb_reimport_passed": glb_ok, "technical_validation_passed": True, "visual_review_passed": False, "passed": False, "blend": ORANGE_BLEND.name, "glb": ORANGE_GLB.name, "preview": "preview_label_test.png", "preview_front": "preview_label_test_front.png", "preview_back": "preview_label_test_back.png", "preview_fit": "preview_label_fit.png", } (ORANGE_DIR / "validation_milk_jug_label_test.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") return report SOURCE_HASHES = {path: sha256(path) for path in (MILK_SOURCE, ORANGE_SOURCE)} removed_milk = make_milk() orange_fit = make_orange() milk_report = validate_milk(removed_milk) orange_report = validate_orange(orange_fit) for path, expected_hash in SOURCE_HASHES.items(): assert sha256(path) == expected_hash print("MILK", json.dumps(milk_report, ensure_ascii=False)) print("ORANGE", json.dumps(orange_report, ensure_ascii=False))