feat: establish coffee game and grinder baseline

This commit is contained in:
Yanchen
2026-11-11 14:08:47 +08:00
commit 890f3fa5f3
220 changed files with 8361 additions and 0 deletions
Binary file not shown.
@@ -0,0 +1,965 @@
import bpy
import math
import json
from pathlib import Path
from mathutils import Vector
from bpy_extras.object_utils import world_to_camera_view
OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/coffee_machine')
TEX = OUT / 'textures'
OUT.mkdir(parents=True, exist_ok=True)
TEX.mkdir(parents=True, exist_ok=True)
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.context.preferences.filepaths.save_version = 0
scene = bpy.context.scene
scene.unit_settings.system = 'METRIC'
scene.unit_settings.length_unit = 'METERS'
cm = bpy.data.collections.new('CM_CoffeeMachine_Model')
studio = bpy.data.collections.new('Studio_Exclude_From_Export')
scene.collection.children.link(cm)
scene.collection.children.link(studio)
def move_to(obj, collection=cm):
for collection_old in list(obj.users_collection):
collection_old.objects.unlink(obj)
collection.objects.link(obj)
return obj
def material(name, color, metallic=0.0, roughness=0.45):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
mat.diffuse_color = (*color, 1)
bsdf = mat.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Base Color'].default_value = (*color, 1)
bsdf.inputs['Metallic'].default_value = metallic
bsdf.inputs['Roughness'].default_value = roughness
return mat
steel = material('CM_Brushed_Steel', (0.48, 0.54, 0.58), 0.82, 0.28)
steel_light = material('CM_Satin_Steel', (0.68, 0.73, 0.76), 0.78, 0.25)
steel_dark = material('CM_Dark_Steel', (0.16, 0.20, 0.22), 0.72, 0.32)
charcoal = material('CM_Charcoal_Panels', (0.035, 0.047, 0.052), 0.32, 0.34)
rubber = material('CM_Black_Grip', (0.018, 0.023, 0.025), 0.05, 0.48)
ivory = material('CM_Ivory_Dial', (0.88, 0.87, 0.80), 0.05, 0.62)
ink = material('CM_Dial_Ink', (0.018, 0.025, 0.028), 0.0, 0.6)
red = material('CM_Signal_Red', (0.72, 0.025, 0.018), 0.15, 0.32)
orange = material('CM_Temperature_Needle', (0.92, 0.15, 0.025), 0.12, 0.32)
teal = material('CM_Flow_Needle', (0.02, 0.32, 0.42), 0.18, 0.3)
white = material('CM_Label_White', (0.84, 0.88, 0.88), 0.1, 0.5)
def assign(obj, mat):
if mat:
obj.data.materials.append(mat)
def bevel(obj, width=0.002, segments=2):
if width > 0:
mod = obj.modifiers.new('CM_Soft_Edges', 'BEVEL')
mod.width = width
mod.segments = segments
if obj.type == 'MESH':
normal = obj.modifiers.new('CM_Weighted_Normals', 'WEIGHTED_NORMAL')
normal.keep_sharp = True
normal.weight = 40
def box(name, loc, dims, mat, edge=0.002, parent=None):
bpy.ops.mesh.primitive_cube_add(size=1, location=loc)
obj = bpy.context.object
obj.name = name
obj.dimensions = dims
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
move_to(obj)
assign(obj, mat)
bevel(obj, edge, 3 if edge > 0.003 else 2)
if parent:
parent_keep(obj, parent)
return obj
def cylinder(name, loc, radius, depth, mat, axis='Z', vertices=24, edge=0.0008, parent=None):
bpy.ops.mesh.primitive_cylinder_add(vertices=vertices, radius=radius, depth=depth, location=loc)
obj = bpy.context.object
obj.name = name
if axis == 'Y':
obj.rotation_euler[0] = math.pi / 2
elif axis == 'X':
obj.rotation_euler[1] = math.pi / 2
move_to(obj)
assign(obj, mat)
for poly in obj.data.polygons:
poly.use_smooth = len(poly.vertices) == 4
bevel(obj, edge, 2)
if parent:
parent_keep(obj, parent)
return obj
def torus(name, loc, major, minor, mat, axis='Z', parent=None):
rotation = (math.pi / 2, 0, 0) if axis == 'Y' else (0, 0, 0)
bpy.ops.mesh.primitive_torus_add(
major_segments=32,
minor_segments=8,
location=loc,
rotation=rotation,
major_radius=major,
minor_radius=minor,
)
obj = bpy.context.object
obj.name = name
move_to(obj)
assign(obj, mat)
for poly in obj.data.polygons:
poly.use_smooth = True
if parent:
parent_keep(obj, parent)
return obj
def rod(name, start, end, radius, mat, vertices=16, parent=None):
start_v = Vector(start)
end_v = Vector(end)
direction = end_v - start_v
obj = cylinder(name, (start_v + end_v) / 2, radius, direction.length, mat, vertices=vertices, edge=0.0005)
obj.rotation_euler = direction.to_track_quat('Z', 'Y').to_euler()
if parent:
parent_keep(obj, parent)
return obj
def empty(name, loc=(0, 0, 0), parent=None, size=0.025):
obj = bpy.data.objects.new(name, None)
cm.objects.link(obj)
obj.empty_display_type = 'PLAIN_AXES'
obj.empty_display_size = size
obj.location = loc
bpy.context.view_layer.update()
if parent:
parent_keep(obj, parent)
return obj
def parent_keep(obj, parent):
bpy.context.view_layer.update()
obj.parent = parent
obj.matrix_parent_inverse = parent.matrix_world.inverted()
def mesh_face(name, vertices, mat, parent=None):
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], [list(range(len(vertices)))])
mesh.update()
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
if parent:
parent_keep(obj, parent)
return obj
def lathe_profile(name, center, profile, mat, segments=48, edge=0.0003, parent=None):
x, y, z = center
vertices = []
for radius, height in profile:
for index in range(segments):
angle = index * 2 * math.pi / segments
vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z + height))
faces = []
for profile_index in range(len(profile)):
next_profile = (profile_index + 1) % len(profile)
for index in range(segments):
next_index = (index + 1) % segments
faces.append((profile_index * segments + index, profile_index * segments + next_index, next_profile * segments + next_index, next_profile * segments + index))
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
for polygon in mesh.polygons:
polygon.use_smooth = True
bevel(obj, edge, 2)
if parent:
parent_keep(obj, parent)
return obj
def arc_ring(name, center, outer_radius, inner_radius, z_bottom, z_top, start_angle, end_angle, mat, parent=None, edge=0.0003):
x, y, z = center
segments = max(3, math.ceil((end_angle - start_angle) / (2 * math.pi) * 96))
vertices = []
for index in range(segments + 1):
angle = start_angle + (end_angle - start_angle) * index / segments
for radius, height in [(outer_radius, z_bottom), (inner_radius, z_bottom), (outer_radius, z_top), (inner_radius, z_top)]:
vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z + height))
faces = []
for index in range(segments):
a = index * 4
b = (index + 1) * 4
faces.extend([
(a, b, b + 2, a + 2),
(a + 1, a + 3, b + 3, b + 1),
(a, a + 1, b + 1, b),
(a + 2, b + 2, b + 3, a + 3),
])
end = segments * 4
faces.extend([(0, 2, 3, 1), (end, end + 1, end + 3, end + 2)])
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
for polygon in mesh.polygons:
polygon.use_smooth = len(polygon.vertices) == 4
bevel(obj, edge, 2)
if parent:
parent_keep(obj, parent)
return obj
def tube_between(name, start, end, outer_radius, inner_radius, mat, parent=None):
start_v = Vector(start)
end_v = Vector(end)
direction = end_v - start_v
half = direction.length / 2
obj = lathe_profile(name, (0, 0, 0), [(outer_radius, -half), (outer_radius, half), (inner_radius, half), (inner_radius, -half)], mat, 24, 0.00025)
obj.location = (start_v + end_v) / 2
obj.rotation_euler = direction.to_track_quat('Z', 'Y').to_euler()
if parent:
parent_keep(obj, parent)
return obj
def horizontal_disc(name, center, radius, mat, parent=None):
x, y, z = center
segments = 48
vertices = [(x, y, z)]
uv_coords = [(0.5, 0.5)]
for index in range(segments):
angle = index * 2 * math.pi / segments
vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z))
uv_coords.append((0.5 + math.cos(angle) / 2, 0.5 + math.sin(angle) / 2))
faces = [(0, index + 1, (index + 1) % segments + 1) for index in range(segments)]
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
uv = mesh.uv_layers.new(name='CM_FilterScreen_UV')
for loop in mesh.loops:
uv.data[loop.index].uv = uv_coords[loop.vertex_index]
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
if parent:
parent_keep(obj, parent)
return obj
def text(name, body, loc, size, mat, parent=None, align='CENTER'):
curve = bpy.data.curves.new(name + '_Font', 'FONT')
curve.body = body
curve.size = size
curve.align_x = align
curve.align_y = 'CENTER'
curve.space_character = 1.05
curve.resolution_u = 4
obj = bpy.data.objects.new(name, curve)
cm.objects.link(obj)
obj.location = loc
obj.rotation_euler = (math.pi / 2, 0, 0)
assign(obj, mat)
if parent:
parent_keep(obj, parent)
return obj
def driver(obj, prop, expression, index=1):
curve = obj.driver_add('rotation_euler', index)
drv = curve.driver
drv.type = 'SCRIPTED'
var = drv.variables.new()
var.name = 'value'
var.type = 'SINGLE_PROP'
var.targets[0].id = controller
var.targets[0].data_path = '["' + prop + '"]'
drv.expression = expression
root = empty('CM_CoffeeMachine', size=0.06)
root['front_direction'] = '-Y in Blender'
root['model_version'] = 'v1.0'
root['reference'] = 'Original single-group design based on reference 02 proportions'
controller = empty('CM_ControlState', parent=root)
controller['hot_water_open'] = 0.0
controller['brew_flow'] = 0.0
controller['temperature_c'] = 0.0
for prop in ['hot_water_open', 'brew_flow']:
controller.id_properties_ui(prop).update(min=0.0, max=1.0, description='Normalized control value')
controller.id_properties_ui('temperature_c').update(min=0.0, max=100.0, description='Displayed outlet temperature')
controller['hot_water_max_degrees'] = 270.0
controller['flow_lever_max_degrees'] = 100.0
# Main body and compact single-group housing.
body = empty('CM_Body', parent=root)
box('CM_Body_MainShell', (0, 0.025, 0.28), (0.46, 0.35, 0.36), steel, 0.012, body)
box('CM_Body_FrontPanel', (0, -0.153, 0.29), (0.45, 0.012, 0.305), steel_light, 0.006, body)
box('CM_Body_LeftPanel', (-0.229, 0.025, 0.275), (0.012, 0.325, 0.31), charcoal, 0.005, body)
box('CM_Body_RightPanel', (0.229, 0.025, 0.275), (0.012, 0.325, 0.31), charcoal, 0.005, body)
box('CM_Body_Base', (0, -0.015, 0.092), (0.46, 0.37, 0.035), steel_dark, 0.005, body)
box('CM_Body_TopLip', (0, 0.025, 0.458), (0.45, 0.345, 0.016), steel_dark, 0.005, body)
for x in [-0.185, 0.185]:
for y in [-0.105, 0.13]:
cylinder('CM_Body_Foot', (x, y, 0.028), 0.018, 0.045, rubber, vertices=20, edge=0.002, parent=body)
for x in [-0.205, 0.205]:
rod('CM_CupRail_Side', (x, -0.125, 0.49), (x, 0.155, 0.49), 0.004, steel_light, parent=body)
for y in [-0.125, 0.155]:
rod('CM_CupRail_Post', (x, y, 0.46), (x, y, 0.49), 0.0035, steel_light, parent=body)
rod('CM_CupRail_Back', (-0.205, 0.155, 0.49), (0.205, 0.155, 0.49), 0.004, steel_light, parent=body)
rod('CM_CupRail_FrontLeft', (-0.205, -0.125, 0.49), (-0.10, -0.125, 0.49), 0.004, steel_light, parent=body)
rod('CM_CupRail_FrontRight', (0.10, -0.125, 0.49), (0.205, -0.125, 0.49), 0.004, steel_light, parent=body)
text('CM_Body_Brand', 'PERFECT COFFEE', (0, -0.161, 0.421), 0.014, ink, body)
# The fixed brew interface faces down; only its external receiving geometry is modeled.
BREW_Y = -0.237
BREW_LIFT = 0.070
BREW_SEAL_Z = 0.2135 + BREW_LIFT
group = empty('CM_GroupHead', (0, BREW_Y, 0.2135), parent=root)
group['interface_axis'] = 'Z'
group['bayonet_notch_degrees'] = 42.0
group['support_arc_count'] = 2
group['spout_owner'] = 'CM_Portafilter'
cylinder('CM_GroupHead_Mount', (0, BREW_Y + 0.0435, 0.250), 0.038, 0.073, steel_dark, 'Y', 40, 0.002, group)
cylinder('CM_GroupHead_Bell', (0, BREW_Y, 0.241), 0.043, 0.042, steel_light, 'Z', 48, 0.002, group)
cylinder('CM_GroupHead_UpperCollar', (0, BREW_Y, 0.268), 0.046, 0.012, steel_light, 'Z', 48, 0.0015, group)
lathe_profile('CM_GroupHead_SealingSeat', (0, BREW_Y, 0), [(0.050, 0.2135), (0.050, 0.220), (0.0373, 0.220), (0.0373, 0.2135)], steel, 64, 0.0005, group)
for suffix, start, end in [('A', 111, 249), ('B', 291, 429)]:
arc_ring('CM_GroupHead_BayonetSupport_' + suffix, (0, BREW_Y, 0), 0.050, 0.039, 0.208, 0.2135, math.radians(start), math.radians(end), steel_light, group, 0.0004)
lathe_profile('CM_GroupHead_Gasket', (0, BREW_Y, 0), [(0.0373, 0.2135), (0.0373, 0.2165), (0.0348, 0.2165), (0.0337, 0.2148), (0.0348, 0.2135)], rubber, 64, 0.0001, group)
# Two external bayonet lugs, an open bowl and both spouts move with the handle.
portafilter = empty('CM_Portafilter', (0, BREW_Y, 0.2135), parent=root)
portafilter['connection_axis'] = 'Z'
portafilter['insertion_direction'] = '+Z'
portafilter['unlock_rotation_degrees'] = -45.0
portafilter['bayonet_lug_count'] = 2
portafilter['seal_contact_z_m'] = BREW_SEAL_Z
lathe_profile('CM_Portafilter_Bowl', (0, BREW_Y, 0), [(0.0345, 0.1815), (0.0375, 0.184), (0.0375, 0.2095), (0.0385, 0.2095), (0.0385, 0.2135), (0.0340, 0.2135), (0.0330, 0.2105), (0.0295, 0.1915), (0.0005, 0.1915), (0.0005, 0.1815)], steel_light, 64, 0.0004, portafilter)
for suffix, angle in [('A', -45), ('B', 135)]:
arc_ring('CM_Portafilter_LockingLug_' + suffix, (0, BREW_Y, 0), 0.0475, 0.0355, 0.205, 0.2079, math.radians(angle - 8), math.radians(angle + 8), steel_light, portafilter, 0.0003)
lathe_profile('CM_Portafilter_SpoutCollar', (0, BREW_Y, 0), [(0.0105, 0.1745), (0.0105, 0.1815), (0.0065, 0.1815), (0.0065, 0.1745)], steel_light, 32, 0.0005, portafilter)
tube_between('CM_Portafilter_SpoutLeft', (0, BREW_Y, 0.176), (-0.014, BREW_Y, 0.157), 0.005, 0.0032, steel_light, portafilter)
tube_between('CM_Portafilter_SpoutRight', (0, BREW_Y, 0.176), (0.014, BREW_Y, 0.157), 0.005, 0.0032, steel_light, portafilter)
rod('CM_Portafilter_Neck', (-0.024, -0.261, 0.195), (-0.064, -0.300, 0.181), 0.008, steel_light, 20, portafilter)
rod('CM_Portafilter_Grip', (-0.061, -0.297, 0.182), (-0.142, -0.400, 0.139), 0.014, rubber, 24, portafilter)
rod('CM_Portafilter_GripCap', (-0.139, -0.397, 0.140), (-0.151, -0.410, 0.135), 0.0145, steel_dark, 24, portafilter)
# Shallow drip tray: all grille holes are represented by a packed texture.
drip = empty('CM_DripTray', parent=root)
box('CM_DripTray_Base', (0, -0.16, 0.074), (0.46, 0.30, 0.045), steel_dark, 0.006, drip)
for x in [-0.222, 0.222]:
box('CM_DripTray_SideFrame', (x, -0.16, 0.099), (0.012, 0.29, 0.014), steel_light, 0.002, drip)
for y in [-0.301, -0.019]:
box('CM_DripTray_EndFrame', (0, y, 0.099), (0.44, 0.012, 0.014), steel_light, 0.002, drip)
def save_generated_image(name, pixels, size, path, non_color=False):
image = bpy.data.images.new(name, width=size, height=size, alpha=True)
if non_color:
image.colorspace_settings.name = 'Non-Color'
image.pixels = pixels
image.update()
image.filepath_raw = str(path)
image.file_format = 'PNG'
image.save()
image.pack()
return image
size = 256
albedo = []
normal_pixels = []
roughness = []
heights = []
for y in range(size):
row = []
for x in range(size):
bar_x = x % 32 < 7
bar_y = y % 32 < 5
raised = bar_x or bar_y
row.append(1.0 if raised else 0.0)
if raised:
edge = min(x % 32, 7 - x % 32, y % 32, 5 - y % 32)
shade = 0.42 + 0.05 * min(edge, 2) + 0.025 * math.sin(y * 0.7)
albedo.extend((shade, shade * 1.04, shade * 1.07, 1))
roughness.extend((0.3, 0.3, 0.3, 1))
else:
albedo.extend((0.025, 0.032, 0.036, 1))
roughness.extend((0.72, 0.72, 0.72, 1))
heights.append(row)
for y in range(size):
for x in range(size):
dx = (heights[y][(x + 1) % size] - heights[y][(x - 1) % size]) * 1.7
dy = (heights[(y + 1) % size][x] - heights[(y - 1) % size][x]) * 1.7
vec = Vector((-dx, dy, 1)).normalized()
normal_pixels.extend((vec.x * 0.5 + 0.5, vec.y * 0.5 + 0.5, vec.z * 0.5 + 0.5, 1))
tray_albedo = save_generated_image('CM_DripTray_Albedo', albedo, size, TEX / 'drip_tray_albedo.png')
tray_normal = save_generated_image('CM_DripTray_Normal', normal_pixels, size, TEX / 'drip_tray_normal.png', True)
tray_rough = save_generated_image('CM_DripTray_Roughness', roughness, size, TEX / 'drip_tray_roughness.png', True)
filter_pixels = []
for py in range(size):
for px in range(size):
dx = px % 12 - 5.5
dy = py % 12 - 5.5
if dx * dx + dy * dy <= 4:
filter_pixels.extend((0.008, 0.012, 0.014, 1))
else:
filter_pixels.extend((0.42, 0.45, 0.47, 1))
filter_image = save_generated_image('CM_FilterScreen_Albedo', filter_pixels, size, TEX / 'filter_screen.png')
filter_mat = material('CM_FilterScreen_TexturedSteel', (0.42, 0.45, 0.47), 0.65, 0.4)
filter_node = filter_mat.node_tree.nodes.new('ShaderNodeTexImage')
filter_node.image = filter_image
filter_mat.node_tree.links.new(filter_node.outputs['Color'], filter_mat.node_tree.nodes.get('Principled BSDF').inputs['Base Color'])
filter_screen = horizontal_disc('CM_Portafilter_FilterScreen', (0, BREW_Y, 0.192), 0.0285, filter_mat, portafilter)
filter_screen['holes_representation'] = 'texture'
shower_screen = horizontal_disc('CM_GroupHead_ShowerScreen', (0, BREW_Y, 0.2175), 0.0335, filter_mat, group)
shower_screen['holes_representation'] = 'texture'
# Lift only after every fixed and detachable child has been attached.
group.location.z += BREW_LIFT
portafilter.location.z += BREW_LIFT
group['cup_clearance_lift_m'] = BREW_LIFT
portafilter['cup_clearance_lift_m'] = BREW_LIFT
bpy.context.view_layer.update()
tray_mat = material('CM_DripTray_Textured_Steel', (0.4, 0.45, 0.48), 0.72, 0.35)
nodes = tray_mat.node_tree.nodes
links = tray_mat.node_tree.links
bsdf = nodes.get('Principled BSDF')
for image, socket in [(tray_albedo, 'Base Color'), (tray_rough, 'Roughness')]:
node = nodes.new('ShaderNodeTexImage')
node.image = image
links.new(node.outputs['Color'], bsdf.inputs[socket])
normal_tex = nodes.new('ShaderNodeTexImage')
normal_tex.image = tray_normal
normal_node = nodes.new('ShaderNodeNormalMap')
normal_node.inputs['Strength'].default_value = 0.65
links.new(normal_tex.outputs['Color'], normal_node.inputs['Color'])
links.new(normal_node.outputs['Normal'], bsdf.inputs['Normal'])
mesh = bpy.data.meshes.new('CM_DripTray_Top_Mesh')
mesh.from_pydata([(-0.216, -0.294, 0.098), (0.216, -0.294, 0.098), (0.216, -0.026, 0.098), (-0.216, -0.026, 0.098)], [], [[0, 1, 2, 3]])
mesh.update()
uv = mesh.uv_layers.new(name='CM_Tray_UV')
for loop, coord in zip(uv.data, [(0, 0), (1, 0), (1, 1), (0, 1)]):
loop.uv = coord
tray_top = bpy.data.objects.new('CM_DripTray_TextureSurface', mesh)
cm.objects.link(tray_top)
assign(tray_top, tray_mat)
parent_keep(tray_top, drip)
# Fixed red reading arrows and gauge construction helpers.
def fixed_arrow(name, x, y, z, parent, direction):
image = create_arrow_texture(direction, TEX / ('arrow_left.png' if direction < 0 else 'arrow_right.png'))
mat = material(name + '_DecalMaterial', (0.72, 0.025, 0.018), 0.0, 0.85)
bsdf = mat.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Specular IOR Level'].default_value = 0.0
node = mat.node_tree.nodes.new('ShaderNodeTexImage')
node.image = image
mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color'])
mat.node_tree.links.new(node.outputs['Alpha'], bsdf.inputs['Alpha'])
if hasattr(mat, 'surface_render_method'):
mat.surface_render_method = 'DITHERED'
width = 0.028
height = 0.018
mesh = bpy.data.meshes.new(name + '_DecalMesh')
mesh.from_pydata([(x - width / 2, y, z - height / 2), (x + width / 2, y, z - height / 2), (x + width / 2, y, z + height / 2), (x - width / 2, y, z + height / 2)], [], [[0, 1, 2, 3]])
mesh.update()
uv = mesh.uv_layers.new(name='CM_Decal_UV')
for loop, coord in zip(uv.data, [(0, 0), (1, 0), (1, 1), (0, 1)]):
loop.uv = coord
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
parent_keep(obj, parent)
if hasattr(obj, 'visible_shadow'):
obj.visible_shadow = False
obj['representation'] = 'decal_texture'
obj['flush_offset_m'] = 0.0003
return obj
import sys
if str(OUT) not in sys.path:
sys.path.insert(0, str(OUT))
from dial_textures import create_dial_texture, create_arrow_texture
def face_material(name, image):
mat = material(name, (0.88, 0.87, 0.80), 0.0, 0.85)
bsdf = mat.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Specular IOR Level'].default_value = 0.0
node = mat.node_tree.nodes.new('ShaderNodeTexImage')
node.image = image
mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color'])
mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Emission Color'])
bsdf.inputs['Emission Strength'].default_value = 0.15
return mat
def front_texture(name, center, radius, mat, parent):
x, y, z = center
segments = 48
vertices = [(x, y, z)]
uv_coords = [(0.5, 0.5)]
for index in range(segments):
angle = index * 2 * math.pi / segments
dx = radius * math.cos(angle)
dz = radius * math.sin(angle)
vertices.append((x + dx, y, z + dz))
uv_coords.append((0.5 + dx / (2 * radius), 0.5 + dz / (2 * radius)))
faces = [(0, index + 1, (index + 1) % segments + 1) for index in range(segments)]
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
uv = mesh.uv_layers.new(name='CM_Dial_UV')
for loop in mesh.loops:
uv.data[loop.index].uv = uv_coords[loop.vertex_index]
obj = bpy.data.objects.new(name, mesh)
cm.objects.link(obj)
assign(obj, mat)
parent_keep(obj, parent)
return obj
CONTROL_ATLAS_LABELS = ['0°', '90°', '180°', '270°', '0%', '50%', '100%']
def create_control_label_atlas(filepath):
atlas_scene = bpy.data.scenes.new('CM_ControlLabelAtlas_Temp')
bpy.context.window.scene = atlas_scene
atlas_scene.render.engine = 'CYCLES'
atlas_scene.cycles.samples = 8
atlas_scene.cycles.use_denoising = False
atlas_scene.render.resolution_x = 2048
atlas_scene.render.resolution_y = 512
atlas_scene.render.resolution_percentage = 100
atlas_scene.render.image_settings.file_format = 'PNG'
atlas_scene.render.image_settings.color_mode = 'RGBA'
atlas_scene.render.film_transparent = True
atlas_scene.render.filepath = str(filepath)
atlas_scene.view_settings.view_transform = 'Standard'
atlas_scene.view_settings.exposure = 0.0
ink_material = bpy.data.materials.new('CM_ControlLabelAtlas_Ink')
ink_material.use_nodes = True
nodes = ink_material.node_tree.nodes
nodes.clear()
emission = nodes.new('ShaderNodeEmission')
emission.inputs['Color'].default_value = (0.008, 0.012, 0.015, 1.0)
emission.inputs['Strength'].default_value = 1.0
output = nodes.new('ShaderNodeOutputMaterial')
ink_material.node_tree.links.new(emission.outputs[0], output.inputs['Surface'])
font_curves = []
metrics = {}
for index, body in enumerate(CONTROL_ATLAS_LABELS):
curve = bpy.data.curves.new('CM_AtlasGlyph_' + str(index), 'FONT')
curve.body = body
curve.size = 1.0
curve.align_x = 'LEFT'
curve.align_y = 'CENTER'
curve.resolution_u = 12
font_curves.append(curve)
obj = bpy.data.objects.new('CM_AtlasGlyph_' + str(index), curve)
atlas_scene.collection.objects.link(obj)
curve.materials.append(ink_material)
bpy.context.view_layer.update()
bounds = [Vector(corner) for corner in obj.bound_box]
min_x = min(corner.x for corner in bounds)
max_x = max(corner.x for corner in bounds)
min_y = min(corner.y for corner in bounds)
max_y = max(corner.y for corner in bounds)
width = max_x - min_x
height = max_y - min_y
scale = min(3.6 / width, 1.6 / height)
width *= scale
height *= scale
obj.scale = (scale, scale, scale)
obj.location = (
(index % 4 - 1.5) * 4 - (min_x + max_x) * scale / 2,
(index // 4 - 0.5) * 2 - (min_y + max_y) * scale / 2,
0,
)
metrics[body] = (width, height)
camera_data = bpy.data.cameras.new('CM_ControlLabelAtlas_Camera')
camera_data.type = 'ORTHO'
camera_data.ortho_scale = 16.0
camera_obj = bpy.data.objects.new('CM_ControlLabelAtlas_Camera', camera_data)
atlas_scene.collection.objects.link(camera_obj)
camera_obj.location = (0, 0, 10)
atlas_scene.camera = camera_obj
bpy.context.view_layer.update()
bpy.ops.render.render(write_still=True, scene=atlas_scene.name)
bpy.context.window.scene = scene
image = bpy.data.images.load(str(filepath), check_existing=False)
image.name = 'CM_ControlLabelAtlas'
image.pack()
for obj in list(atlas_scene.objects):
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.scenes.remove(atlas_scene)
for curve in font_curves:
if curve.users == 0:
bpy.data.curves.remove(curve)
if camera_data.users == 0:
bpy.data.cameras.remove(camera_data)
if ink_material.users == 0:
bpy.data.materials.remove(ink_material)
return image, metrics
def printed_label_material(image):
mat = material('CM_PrintedLabel_AtlasMaterial', (0.008, 0.012, 0.015), 0.0, 0.85)
bsdf = mat.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Specular IOR Level'].default_value = 0.0
node = mat.node_tree.nodes.new('ShaderNodeTexImage')
node.image = image
mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color'])
mat.node_tree.links.new(node.outputs['Alpha'], bsdf.inputs['Alpha'])
if hasattr(mat, 'surface_render_method'):
mat.surface_render_method = 'DITHERED'
if hasattr(mat, 'use_backface_culling'):
mat.use_backface_culling = True
return mat
control_label_atlas, control_label_metrics = create_control_label_atlas(TEX / 'control_label_atlas.png')
control_label_material = printed_label_material(control_label_atlas)
def printed_labels(prefix, pivot, kind):
direction = -1 if kind.startswith('hot') else 1
maximum = 270 if direction < 0 else 100
labels = [(0, '0°'), (90, '90°'), (180, '180°'), (270, '270°')] if direction < 0 else [(0, '0%'), (50, '50%'), (100, '100%')]
x, y, z = pivot.location
for value, body in labels:
atlas_width, atlas_height = control_label_metrics[body]
natural_aspect = atlas_width / atlas_height
glyph_height = min(0.005, 0.017 / natural_aspect)
glyph_width = glyph_height * natural_aspect
patch_width = glyph_width * 4.0 / atlas_width
patch_height = glyph_height * 2.0 / atlas_height
axial_center = 0.014 + glyph_width / 2
radius_center = 0.0348 - 0.009 * axial_center / 0.03
angle_height = patch_height / radius_center
center_angle = math.radians(180 + value * 270 / maximum)
vertices = []
uv_coords = []
width_segments = 4
height_segments = 8
cell = CONTROL_ATLAS_LABELS.index(body)
for ix in range(width_segments + 1):
u = ix / width_segments
axial = axial_center + direction * (u - 0.5) * patch_width
radius = 0.0348 - 0.009 * axial / 0.03
for iy in range(height_segments + 1):
v = iy / height_segments
angle = center_angle - (v - 0.5) * angle_height
normal = Vector((direction * 0.3, math.cos(angle), math.sin(angle))).normalized()
point = Vector((x + direction * axial, y + radius * math.cos(angle), z + radius * math.sin(angle))) + normal * 0.00004
vertices.append(point)
uv_coords.append(((cell % 4 + u) / 4, (cell // 4 + v) / 2))
faces = []
for ix in range(width_segments):
for iy in range(height_segments):
a = ix * (height_segments + 1) + iy
face = (a, a + height_segments + 1, a + height_segments + 2, a + 1)
faces.append(face)
mesh = bpy.data.meshes.new(prefix + '_PrintedLabel_' + str(value) + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
uv = mesh.uv_layers.new(name='CM_PrintedLabel_UV')
for loop in mesh.loops:
uv.data[loop.index].uv = uv_coords[loop.vertex_index]
for polygon in mesh.polygons:
polygon.use_smooth = True
obj = bpy.data.objects.new(prefix + '_PrintedLabel_' + str(value), mesh)
cm.objects.link(obj)
assign(obj, control_label_material)
parent_keep(obj, pivot)
if hasattr(obj, 'visible_shadow'):
obj.visible_shadow = False
obj['representation'] = 'vector_text_uv_decal'
obj['printed_text'] = body
obj['font'] = 'Blender Bfont'
obj['glyph_height_m'] = glyph_height
obj['natural_aspect_ratio'] = natural_aspect
obj['atlas_cell_aspect_ratio'] = 2.0
obj['surface_offset_m'] = 0.00004
obj['baseline_axis'] = 'X'
def conical_dial(prefix, pivot, kind):
segments = 64
height = 0.03
bottom_radius = 0.0348
top_radius = 0.0258
direction = -1 if kind.startswith('hot') else 1
x, y, z = pivot.location
vertices = []
for radius, axial_offset in [(bottom_radius, 0), (top_radius, direction * height)]:
for index in range(segments):
angle = index * 2 * math.pi / segments
vertices.append((x + axial_offset, y + radius * math.cos(angle), z + radius * math.sin(angle)))
faces = []
for index in range(segments):
next_index = (index + 1) % segments
faces.append((index, next_index, segments + next_index, segments + index))
faces.append(tuple(reversed(range(segments))))
faces.append(tuple(range(segments, segments * 2)))
if direction < 0:
faces = [tuple(reversed(face)) for face in faces]
mesh = bpy.data.meshes.new(prefix + '_ConicalMesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
image = create_dial_texture(kind, TEX / (kind + '.png'))
obj = bpy.data.objects.new(prefix + '_ConicalSide', mesh)
cm.objects.link(obj)
assign(obj, face_material(prefix + '_TextureMaterial', image))
assign(obj, steel_light)
uv = mesh.uv_layers.new(name='CM_Conical_UV')
for polygon in mesh.polygons:
polygon.material_index = 0 if polygon.index < segments else 1
polygon.use_smooth = polygon.index < segments
for loop_index in polygon.loop_indices:
vertex_index = mesh.loops[loop_index].vertex_index
if polygon.index < segments:
segment_index = polygon.index
u = segment_index / segments if vertex_index in [segment_index, segments + segment_index] else (segment_index + 1) / segments
v = 0.0 if vertex_index < segments else 1.0
uv.data[loop_index].uv = (u, v)
else:
uv.data[loop_index].uv = (0.5, 0.5)
parent_keep(obj, pivot)
printed_labels(prefix, pivot, kind)
pivot['mount_plane'] = 'YOZ'
pivot['mount_side'] = 'left' if kind.startswith('hot') else 'right'
pivot['dial_axis'] = 'X'
pivot['shape'] = 'frustum'
pivot['height_m'] = height
pivot['outward_direction'] = direction
pivot['arrow_location'] = 'front'
prop = 'hot_water_open' if kind.startswith('hot') else 'brew_flow'
driver(pivot, prop, f'-value * {math.radians(270)}', index=0)
def gauge(prefix, center, radius, needle_mat, label, unit, prop, parent=root):
x, y, z = center
assembly = empty(prefix, center, parent)
cylinder(prefix + '_Case', (x, y + 0.004, z), radius, 0.014, steel_dark, 'Y', 32, 0.0015, assembly)
torus(prefix + '_Bezel', (x, y - 0.005, z), radius - 0.002, 0.0025, steel_light, 'Y', assembly)
cylinder(prefix + '_Face', (x, y - 0.006, z), radius - 0.005, 0.002, ivory, 'Y', 32, 0.0003, assembly)
kind = 'temperature' if label == 'TEMP' else 'flow_gauge'
image = create_dial_texture(kind, TEX / (kind + '.png'))
front_texture(prefix + '_Texture', (x, y - 0.0072, z), radius - 0.005, face_material(prefix + '_TextureMaterial', image), assembly)
needle = empty(prefix + '_Needle', center, assembly, 0.01)
mesh_face(prefix + '_NeedleShape', [(x - 0.007, y - 0.0105, z - 0.0015), (x + radius * 0.72, y - 0.0105, z), (x - 0.007, y - 0.0105, z + 0.0015)], needle_mat, needle)
cylinder(prefix + '_NeedleHub', (x, y - 0.011, z), 0.0035, 0.002, needle_mat, 'Y', 20, 0.0003, assembly)
sweep = math.pi if prop == 'brew_flow' else math.pi / 100
driver(needle, prop, f'(value * {sweep}) - {math.pi}')
return assembly
def top_control(prefix, pivot, current_degrees, hot=False):
x, y, z = pivot.location
direction = -1 if hot else 1
angle = math.radians(135 + current_degrees)
dy = math.cos(angle)
dz = math.sin(angle)
cylinder(prefix + '_TopCap', (x + direction * 0.008, y, z), 0.0234, 0.016, steel_dark, 'X', 32, 0.002, pivot)
rod(prefix + '_Stem', (x + direction * 0.016, y, z), (x + direction * 0.030, y + dy * 0.040, z + dz * 0.068), 0.0055, steel_light, 20, pivot)
rod(prefix + '_Grip', (x + direction * 0.026, y + dy * 0.032, z + dz * 0.058), (x + direction * 0.043, y + dy * 0.072, z + dz * 0.125), 0.0105, rubber, 24, pivot)
if hot:
rod(prefix + '_RedMarker', (x + direction * 0.017, y, z), (x + direction * 0.017, y + dy * 0.026, z + dz * 0.026), 0.0018, red, 8, pivot)
pivot['mount_plane'] = 'YOZ'
pivot['mount_side'] = 'left' if hot else 'right'
pivot['dial_axis'] = 'X'
pivot['connector_radius_m'] = 0.0234
pivot['dial_top_radius_m'] = 0.0258
prop = 'hot_water_open' if hot else 'brew_flow'
driver(pivot, prop, f'-value * {math.radians(270)}', index=0)
# Left side-mounted frustum, with the narrow top and handle facing outward.
hot_dial = empty('CM_HotWaterDial', (-0.235, -0.095, 0.337), root)
conical_dial('CM_HotWaterDial', hot_dial, 'hot_water_conical')
hot_valve = empty('CM_HotWaterValve', (-0.265, -0.095, 0.337), root)
top_control('CM_HotWaterValve', hot_valve, 0.0, hot=True)
fixed_arrow('CM_HotWaterValve_FixedArrow', -0.214, -0.1593, 0.337, body, -1)
# Two enlarged meters remain on the front panel.
temp_gauge = gauge('CM_TempGauge', (-0.112, -0.169, 0.337), 0.048, orange, 'TEMP', '°C', 'temperature_c')
flow_gauge = gauge('CM_FlowGauge', (0.112, -0.169, 0.337), 0.048, teal, 'FLOW', '%', 'brew_flow')
# Right side-mounted frustum uses the same relationship.
flow_dial = empty('CM_FlowDial', (0.235, -0.095, 0.337), root)
conical_dial('CM_FlowDial', flow_dial, 'flow_dial_conical')
flow_lever = empty('CM_FlowLever', (0.265, -0.095, 0.337), root)
top_control('CM_FlowLever', flow_lever, 0.0)
fixed_arrow('CM_FlowLever_FixedArrow', 0.214, -0.1593, 0.337, body, 1)
# Convert the brand text so the GLB does not depend on font objects.
bpy.ops.object.select_all(action='DESELECT')
font_objects = [obj for obj in cm.objects if obj.type == 'FONT']
for obj in font_objects:
obj.select_set(True)
if font_objects:
bpy.context.view_layer.objects.active = font_objects[0]
bpy.ops.object.convert(target='MESH')
bpy.ops.object.select_all(action='DESELECT')
scene.frame_set(1)
bpy.context.view_layer.update()
# Studio setup is intentionally separate from the exported asset.
floor_mat = material('Studio_Warm_Background', (0.19, 0.22, 0.23), 0.0, 0.72)
bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, -0.002))
floor = bpy.context.object
floor.name = 'Studio_Floor'
move_to(floor, studio)
assign(floor, floor_mat)
world = bpy.data.worlds.new('Studio_World')
scene.world = world
world.use_nodes = True
world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.16, 0.19, 0.22, 1)
world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.45
def area_light(name, loc, energy, size, color, target=(0, 0, 0.24)):
data = bpy.data.lights.new(name, 'AREA')
data.energy = energy
data.shape = 'DISK'
data.size = size
data.color = color
obj = bpy.data.objects.new(name, data)
studio.objects.link(obj)
obj.location = loc
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
area_light('Studio_Key', (-0.65, -0.8, 1.15), 90, 0.75, (1.0, 0.87, 0.72))
area_light('Studio_Fill', (0.75, -0.45, 0.75), 65, 0.65, (0.72, 0.85, 1.0))
area_light('Studio_Rim', (0.1, 0.65, 1.0), 110, 0.6, (1.0, 0.95, 0.85))
def camera(name, loc, target, scale):
data = bpy.data.cameras.new(name)
data.type = 'ORTHO'
data.ortho_scale = scale
data.lens = 60
obj = bpy.data.objects.new(name, data)
studio.objects.link(obj)
obj.location = loc
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
return obj
front_camera = camera('Acceptance_Front_0deg', (0, -1.8, 0.25), (0, -0.02, 0.25), 0.68)
angle_camera = camera('Acceptance_30deg', (0.8, -1.3856, 1.1738), (0, -0.02, 0.25), 0.78)
right_camera = camera('Acceptance_Right_YOZ', (1.8, 0, 0.25), (0, 0, 0.25), 0.86)
left_camera = camera('Acceptance_Left_YOZ', (-1.8, 0, 0.25), (0, 0, 0.25), 0.86)
controls_camera = camera('Acceptance_Controls_Front_XOZ', (0, -1.8, 0.337), (0, -0.095, 0.337), 0.64)
brew_camera = camera('Acceptance_Brew_Interface', (0.32, BREW_Y - 0.398, 0.060 + BREW_LIFT), (0, BREW_Y, 0.174 + BREW_LIFT), 0.25)
bowl_camera = camera('Acceptance_Portafilter_Bowl', (0.25, BREW_Y - 0.308, 0.49 + BREW_LIFT), (0, BREW_Y - 0.028, 0.17 + BREW_LIFT), 0.25)
scene.render.engine = 'CYCLES'
scene.cycles.samples = 40
scene.cycles.use_denoising = True
scene.render.resolution_x = 1100
scene.render.resolution_y = 1100
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.film_transparent = False
scene.view_settings.view_transform = 'AgX'
scene.view_settings.exposure = -0.35
# Export only the machine collection, with current driven poses and packed textures.
bpy.ops.object.select_all(action='DESELECT')
for obj in cm.all_objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.export_scene.gltf(
filepath=str(OUT / 'PerfectCoffee_CoffeeMachine.glb'),
export_format='GLB',
use_selection=True,
export_apply=True,
export_animations=False,
export_extras=True,
)
bpy.ops.object.select_all(action='DESELECT')
scene.camera = front_camera
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == 'VIEW_3D':
area.spaces.active.region_3d.view_perspective = 'CAMERA'
area.spaces.active.shading.type = 'MATERIAL'
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / 'PerfectCoffee_CoffeeMachine.blend'))
required = ['CM_Body', 'CM_GroupHead', 'CM_HotWaterValve', 'CM_HotWaterDial', 'CM_TempGauge', 'CM_FlowGauge', 'CM_FlowLever', 'CM_FlowDial', 'CM_Portafilter', 'CM_DripTray']
driver_count = sum(len(obj.animation_data.drivers) for obj in cm.all_objects if obj.animation_data)
report = {'required_objects': {}, 'camera_bounds': {}, 'mesh_objects': 0, 'vertices': 0, 'polygons': 0, 'drivers': driver_count}
for name in required:
obj = bpy.data.objects.get(name)
report['required_objects'][name] = obj is not None
for obj in cm.all_objects:
if obj.type == 'MESH':
report['mesh_objects'] += 1
report['vertices'] += len(obj.data.vertices)
report['polygons'] += len(obj.data.polygons)
for cam, label in [(front_camera, 'front'), (angle_camera, 'angle_30deg'), (right_camera, 'right_yoz'), (left_camera, 'left_yoz')]:
scene.camera = cam
bpy.context.view_layer.update()
coverage = {}
for name in required:
obj = bpy.data.objects[name]
points = []
for child in obj.children_recursive:
if child.type == 'MESH':
points.extend([child.matrix_world @ Vector(corner) for corner in child.bound_box])
if not points:
continue
projected = [world_to_camera_view(scene, cam, point) for point in points]
bounds = [min(p.x for p in projected), max(p.x for p in projected), min(p.y for p in projected), max(p.y for p in projected)]
coverage[name] = {'bounds': [round(v, 4) for v in bounds], 'inside_frame': all(0 <= p.x <= 1 and 0 <= p.y <= 1 and p.z > 0 for p in projected)}
report['camera_bounds'][label] = coverage
for cam, filename in [(front_camera, 'preview_front.png'), (angle_camera, 'preview_30deg.png'), (right_camera, 'preview_right.png'), (left_camera, 'preview_left.png')]:
scene.camera = cam
scene.render.filepath = str(OUT / filename)
bpy.ops.render.render(write_still=True)
scene.camera = controls_camera
scene.render.resolution_x = 2400
scene.render.resolution_y = 1000
scene.render.filepath = str(OUT / 'preview_controls_front.png')
bpy.ops.render.render(write_still=True)
scene.camera = brew_camera
scene.render.resolution_x = 1400
scene.render.resolution_y = 1400
scene.render.filepath = str(OUT / 'preview_brew_interface.png')
bpy.ops.render.render(write_still=True)
portafilter.rotation_euler.z = math.radians(-45)
portafilter.location.y -= 0.035
portafilter.location.z -= 0.045
bpy.context.view_layer.update()
scene.render.filepath = str(OUT / 'preview_portafilter_detached.png')
bpy.ops.render.render(write_still=True)
scene.camera = bowl_camera
scene.render.filepath = str(OUT / 'preview_portafilter_bowl.png')
bpy.ops.render.render(write_still=True)
portafilter.rotation_euler.z = 0.0
portafilter.location.y += 0.035
portafilter.location.z += 0.045
bpy.context.view_layer.update()
scene.render.resolution_x = 1100
scene.render.resolution_y = 1100
scene.camera = front_camera
print('MODEL_VALIDATION=' + json.dumps(report), flush=True)
print('MODEL_BUILD_COMPLETE', flush=True)
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,57 @@
{
"source_machine_unchanged": true,
"source_machine_sha256": "c41f0d3636654138a13400002ddf4e32cacddb4b1af939cf5b20ad4313f8bf89",
"source_cup_unchanged": true,
"source_cup_sha256": "5ac4bfae6528989485136c87548d36e0214bd56b5bcd29dedf4a3dc548cdbada",
"lid_included": false,
"layout": {
"scheme": "A",
"brew_center_xy_m": [
0.0,
-0.2370000034570694
],
"group_seal_z_mm": 283.49998593330383,
"tray_support_z_mm": 97.99999743700027
},
"cup": {
"height_mm": 110,
"top_diameter_mm": 85,
"bottom_diameter_mm": 60,
"bottom_center_m": [
0.0,
-0.2370000034570694,
0.09799999743700027
],
"bottom_z_mm": 97.99999743700027,
"bottom_on_tray_surface": true,
"top_z_mm": 208.00000429153442
},
"lowest_spout_z_mm": 224.03399646282196,
"spout_to_tray_clearance_mm": 126.03399902582169,
"spout_clearance_above_cup_mm": 16.033992171287537,
"centered_head_projection_overlap_percent_of_cup": 100.0,
"centered_penetrations": [],
"centered_surface_contacts_excluding_tray_support": [],
"centered_passed": true,
"search": {
"xy_step_mm": 2.5,
"cup_upright": true,
"bottom_remains_on_tray": true,
"minimum_projection_overlap_percent_allowed": 25,
"tested_collision_free_candidates": 627,
"best_valid_position": {
"cup_bottom_center_m": [
0.0,
-0.2370000034570694,
0.09799999743700027
],
"offset_from_brew_axis_mm": [
0.0,
0.0
],
"head_projection_overlap_percent_of_cup": 100.0,
"penetrations": 0,
"surface_contacts_excluding_tray_support": 0
}
}
}
@@ -0,0 +1,181 @@
import bpy
import math
from pathlib import Path
SIZE = 512
INK = (0.012, 0.018, 0.020, 1.0)
PAPER = (0.88, 0.87, 0.80, 1.0)
FONT = {
'0': ['01110', '10001', '10011', '10101', '11001', '10001', '01110'],
'1': ['00100', '01100', '00100', '00100', '00100', '00100', '01110'],
'2': ['01110', '10001', '00001', '00010', '00100', '01000', '11111'],
'3': ['11110', '00001', '00001', '01110', '00001', '00001', '11110'],
'4': ['00010', '00110', '01010', '10010', '11111', '00010', '00010'],
'5': ['11111', '10000', '10000', '11110', '00001', '00001', '11110'],
'6': ['01110', '10000', '10000', '11110', '10001', '10001', '01110'],
'7': ['11111', '00001', '00010', '00100', '01000', '01000', '01000'],
'8': ['01110', '10001', '10001', '01110', '10001', '10001', '01110'],
'9': ['01110', '10001', '10001', '01111', '00001', '00001', '01110'],
'T': ['11111', '00100', '00100', '00100', '00100', '00100', '00100'],
'E': ['11111', '10000', '10000', '11110', '10000', '10000', '11111'],
'M': ['10001', '11011', '10101', '10101', '10001', '10001', '10001'],
'P': ['11110', '10001', '10001', '11110', '10000', '10000', '10000'],
'F': ['11111', '10000', '10000', '11110', '10000', '10000', '10000'],
'L': ['10000', '10000', '10000', '10000', '10000', '10000', '11111'],
'O': ['01110', '10001', '10001', '10001', '10001', '10001', '01110'],
'W': ['10001', '10001', '10001', '10101', '10101', '11011', '10001'],
'D': ['11110', '10001', '10001', '10001', '10001', '10001', '11110'],
'G': ['01110', '10001', '10000', '10111', '10001', '10001', '01110'],
'C': ['01111', '10000', '10000', '10000', '10000', '10000', '01111'],
'°': ['01100', '10010', '10010', '01100', '00000', '00000', '00000'],
'%': ['11001', '11010', '00010', '00100', '01000', '01011', '10011'],
' ': ['00000'] * 7,
}
def canvas():
return list(PAPER) * (SIZE * SIZE)
def pixel(data, x, y, color=INK):
if 0 <= x < SIZE and 0 <= y < SIZE:
index = (y * SIZE + x) * 4
data[index:index + 4] = color
def rect(data, x, y, width, height, color=INK):
for yy in range(max(0, y), min(SIZE, y + height)):
for xx in range(max(0, x), min(SIZE, x + width)):
pixel(data, xx, yy, color)
def line(data, x1, y1, x2, y2, width=2, color=INK):
dx = x2 - x1
dy = y2 - y1
length2 = dx * dx + dy * dy
min_x = max(0, int(min(x1, x2) - width - 1))
max_x = min(SIZE, int(max(x1, x2) + width + 2))
min_y = max(0, int(min(y1, y2) - width - 1))
max_y = min(SIZE, int(max(y1, y2) + width + 2))
for y in range(min_y, max_y):
for x in range(min_x, max_x):
if length2:
t = max(0, min(1, ((x - x1) * dx + (y - y1) * dy) / length2))
else:
t = 0
px = x1 + t * dx
py = y1 + t * dy
if (x - px) ** 2 + (y - py) ** 2 <= (width / 2) ** 2:
pixel(data, x, y, color)
def text(data, body, center_x, top_y, scale=4, color=INK):
body = str(body)
total = (len(body) * 6 - 1) * scale
start_x = int(center_x - total / 2)
for index, char in enumerate(body):
glyph = FONT.get(char.upper(), FONT[' '])
for row, pattern in enumerate(glyph):
for column, bit in enumerate(pattern):
if bit == '1':
rect(data, start_x + (index * 6 + column) * scale, top_y + row * scale, scale, scale, color)
def draw_gauge(data, label, unit):
center = SIZE / 2
for value in range(0, 101, 5):
angle = math.radians(180 - value * 1.8)
outer = 226
inner = 199 if value % 25 == 0 else 211
line(data, center + inner * math.cos(angle), center - inner * math.sin(angle), center + outer * math.cos(angle), center - outer * math.sin(angle), 4 if value % 25 == 0 else 2)
if value % 25 == 0:
text(data, str(value), center + 155 * math.cos(angle), int(center - 155 * math.sin(angle) - 13), 4 if value != 100 else 3)
text(data, label, center, 307, 5)
text(data, unit, center, 354, 4)
def draw_rotating(data, maximum, labels, unit):
center = SIZE / 2
for value in range(maximum + 1):
if value % 5:
continue
angle = math.radians(90 + value * 270 / maximum)
outer = 226
inner = 199 if value % 30 == 0 else 211
line(data, center + inner * math.cos(angle), center - inner * math.sin(angle), center + outer * math.cos(angle), center - outer * math.sin(angle), 4 if value % 30 == 0 else 2)
for value, label in labels:
angle = math.radians(90 + value * 270 / maximum)
text(data, label, center + 148 * math.cos(angle), int(center - 148 * math.sin(angle) - 12), 4 if len(str(label)) < 3 else 3)
text(data, unit, center, 343, 4)
def draw_conical(data, maximum):
step = 10 if maximum == 270 else 5
major_step = 30 if maximum == 270 else 25
base_y = SIZE - 1
for value in range(maximum + 1):
if value % step:
continue
angle = (180 + value * 270 / maximum) % 360
x = int(angle / 360 * SIZE) % SIZE
major = value % major_step == 0
line(data, x, base_y - 4, x, base_y - (220 if major else 136), 10 if major else 5)
def create_dial_texture(kind, filepath):
data = canvas()
if kind == 'hot_water_conical':
draw_conical(data, 270)
elif kind == 'flow_dial_conical':
draw_conical(data, 100)
elif kind == 'hot_water':
draw_rotating(data, 270, [(0, '0'), (90, '90'), (180, '180'), (270, '270')], 'DEG')
elif kind == 'flow_dial':
draw_rotating(data, 100, [(0, '0'), (25, '25'), (50, '50'), (75, '75'), (100, '100')], '%')
elif kind == 'temperature':
draw_gauge(data, 'TEMP', '°C')
elif kind == 'flow_gauge':
draw_gauge(data, 'FLOW', '%')
else:
raise ValueError(kind)
pixels = []
for y in range(SIZE - 1, -1, -1):
start = y * SIZE * 4
pixels.extend(data[start:start + SIZE * 4])
image = bpy.data.images.new('CM_' + kind + '_FaceTexture', width=SIZE, height=SIZE, alpha=True)
image.pixels = pixels
image.update()
image.filepath_raw = str(Path(filepath))
image.file_format = 'PNG'
image.save()
image.pack()
return image
def create_arrow_texture(direction, filepath):
data = [0.0] * (SIZE * SIZE * 4)
red = (0.72, 0.025, 0.018, 1.0)
for y in range(120, 393):
ratio = abs(y - 256) / 136
if direction < 0:
start = int(60 + 320 * ratio)
end = 380
else:
start = 132
end = int(452 - 320 * ratio)
for x in range(start, end + 1):
index = (y * SIZE + x) * 4
data[index:index + 4] = red
pixels = []
for y in range(SIZE - 1, -1, -1):
start = y * SIZE * 4
pixels.extend(data[start:start + SIZE * 4])
kind = 'arrow_left' if direction < 0 else 'arrow_right'
image = bpy.data.images.new('CM_' + kind + '_DecalTexture', width=SIZE, height=SIZE, alpha=True)
image.pixels = pixels
image.update()
image.filepath_raw = str(Path(filepath))
image.file_format = 'PNG'
image.save()
image.pack()
return image
@@ -0,0 +1,211 @@
from pathlib import Path
import json
import math
import bpy
from mathutils import Matrix, Vector
from bpy_extras.object_utils import world_to_camera_view
OUT = Path(__file__).resolve().parent
SOURCE = OUT / 'PerfectCoffee_CoffeeMachine.blend'
bpy.ops.wm.open_mainfile(filepath=str(SOURCE))
source_root = bpy.data.objects.get('CM_Portafilter')
if source_root is None:
raise RuntimeError('CM_Portafilter was not found in the source file.')
source_objects = [source_root, *source_root.children_recursive]
preview_scene = bpy.data.scenes.new('PerfectCoffee_Portafilter')
bpy.context.window.scene = preview_scene
model_collection = bpy.data.collections.new('CM_Portafilter_Model')
preview_scene.collection.children.link(model_collection)
studio_collection = bpy.data.collections.new('Studio_Exclude_From_Export')
preview_scene.collection.children.link(studio_collection)
object_map = {}
for source in source_objects:
copied = source.copy()
if source.data is not None:
copied.data = source.data.copy()
copied.animation_data_clear()
model_collection.objects.link(copied)
object_map[source] = copied
for source, copied in object_map.items():
copied.matrix_world = source.matrix_world.copy()
if source == source_root:
copied.parent = None
else:
copied.parent = object_map[source.parent]
copied.matrix_parent_inverse = source.matrix_parent_inverse.copy()
copied.matrix_world = source.matrix_world.copy()
portafilter = object_map[source_root]
sealing_height = source_root.matrix_world.translation.z - source_root.get('cup_clearance_lift_m', 0.0)
for source, copied in object_map.items():
if source != source_root:
copied.matrix_parent_inverse = Matrix.Identity(4)
copied.matrix_world = source.matrix_world.copy()
for source in source_objects:
bpy.data.objects.remove(source, do_unlink=True)
for copied in object_map.values():
copied.name = copied.name.removesuffix('.001')
bpy.data.scenes.remove(bpy.data.scenes['Scene'], do_unlink=True)
portafilter.location = (0, 0, sealing_height)
portafilter.rotation_euler = (0, 0, 0)
portafilter.scale = (1, 1, 1)
bpy.context.view_layer.update()
axis_direction = Vector((0, -1, 0))
segment_start = Vector((0, -0.034, (sealing_height - 0.0185)))
rod_lengths = {}
rod_endpoints = {}
for name in ('Neck', 'Grip', 'GripCap'):
rod = bpy.data.objects['CM_Portafilter_' + name]
length = max(vertex.co.z for vertex in rod.data.vertices) - min(vertex.co.z for vertex in rod.data.vertices)
if name != 'Neck':
segment_start -= axis_direction * 0.003
segment_end = segment_start + axis_direction * length
rod.matrix_world = Matrix.Translation((segment_start + segment_end) * 0.5) @ axis_direction.to_track_quat('Z', 'Y').to_matrix().to_4x4()
rod['axis_alignment'] = 'Y; shared centerline with neck, grip and cap'
rod_lengths[name] = length
rod_endpoints[name] = [list(segment_start), list(segment_end)]
segment_start = segment_end
portafilter['source_file'] = SOURCE.name
portafilter['extraction'] = 'Standalone part; source machine excluded. Bowl centered in XOY; handle aligned to Y.'
portafilter['bowl_center_xy_m'] = [0.0, 0.0]
portafilter['grip_axis'] = 'Y'
preview_scene.unit_settings.system = 'METRIC'
preview_scene.unit_settings.length_unit = 'METERS'
preview_scene.unit_settings.scale_length = 1.0
bpy.context.view_layer.update()
bowl = bpy.data.objects['CM_Portafilter_Bowl']
bowl_center = sum((bowl.matrix_world @ vertex.co for vertex in bowl.data.vertices), Vector()) / len(bowl.data.vertices)
assert abs(bowl_center.x) < 1e-7 and abs(bowl_center.y) < 1e-7
assert abs(portafilter.matrix_world.translation.x) < 1e-7 and abs(portafilter.matrix_world.translation.y) < 1e-7
for name in rod_endpoints:
rod = bpy.data.objects['CM_Portafilter_' + name]
half_length = rod_lengths[name] * 0.5
world_endpoints = [rod.matrix_world @ Vector((0, 0, sign * half_length)) for sign in (-1, 1)]
for point in world_endpoints:
assert abs(point.x) < 1e-7 and abs(point.z - (sealing_height - 0.0185)) < 1e-7, (name, [tuple(p) for p in world_endpoints], tuple(rod.location), tuple(rod.rotation_euler), tuple(portafilter.matrix_world.translation), [list(row) for row in rod.matrix_parent_inverse])
assert abs((world_endpoints[1] - world_endpoints[0]).length - rod_lengths[name]) < 1e-7
rod_endpoints[name] = [list(point) for point in world_endpoints]
mesh_objects = [obj for obj in model_collection.objects if obj.type == 'MESH']
points = [obj.matrix_world @ Vector(corner) for obj in mesh_objects for corner in obj.bound_box]
bounds_min = Vector(tuple(min(point[axis] for point in points) for axis in range(3)))
bounds_max = Vector(tuple(max(point[axis] for point in points) for axis in range(3)))
center = (bounds_min + bounds_max) * 0.5
extent = bounds_max - bounds_min
def point_at(obj, target):
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
def camera(name, direction, width, height):
data = bpy.data.cameras.new(name)
data.type = 'ORTHO'
data.clip_start = 0.001
data.clip_end = 100
obj = bpy.data.objects.new(name, data)
studio_collection.objects.link(obj)
obj.location = center + Vector(direction) * 1.2
point_at(obj, center)
preview_scene.camera = obj
data.ortho_scale = max(extent) * 1.20
bpy.context.view_layer.update()
data.lens = 55
return obj
def area_light(name, position, power, size, color):
data = bpy.data.lights.new(name, 'AREA')
data.energy = power
data.shape = 'DISK'
data.size = size
data.color = color
obj = bpy.data.objects.new(name, data)
studio_collection.objects.link(obj)
obj.location = center + Vector(position)
point_at(obj, center)
area_light('Studio_Key', (-0.4, -0.45, 0.65), 35, 0.5, (1.0, 0.92, 0.82))
area_light('Studio_Fill', (0.45, -0.1, 0.3), 25, 0.45, (0.80, 0.90, 1.0))
area_light('Studio_Rim', (0.0, 0.5, 0.6), 40, 0.4, (1.0, 1.0, 1.0))
world = bpy.data.worlds.new('Portafilter_Studio_World')
world.use_nodes = True
world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.20, 0.23, 0.27, 1)
world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.45
preview_scene.world = world
preview_scene.render.engine = 'CYCLES'
preview_scene.cycles.samples = 40
preview_scene.cycles.use_denoising = True
preview_scene.render.resolution_x = 1400
preview_scene.render.resolution_y = 1400
preview_scene.render.resolution_percentage = 100
preview_scene.render.image_settings.file_format = 'PNG'
preview_scene.render.image_settings.color_mode = 'RGBA'
preview_scene.render.film_transparent = False
preview_scene.view_settings.view_transform = 'AgX'
preview_scene.view_settings.exposure = 0.0
views = [
('Portafilter_Front_XOZ', (0, -1, 0), 'portafilter_front.png'),
('Portafilter_Right_YOZ', (1, 0, 0), 'portafilter_side.png'),
('Portafilter_Top_XOY', (0, 0, 1), 'portafilter_top.png'),
]
coverage = {}
for name, direction, filename in views:
cam = camera(name, direction, 1400, 1400)
preview_scene.camera = cam
bpy.context.view_layer.update()
projected = [world_to_camera_view(preview_scene, cam, point) for point in points]
coverage[name] = all(0 < point.x < 1 and 0 < point.y < 1 and point.z > 0 for point in projected)
if not coverage[name]:
raise RuntimeError('Model is clipped by camera: ' + name + ' bounds=' + str((list(bounds_min), list(bounds_max))) + ' camera=' + str(tuple(cam.matrix_world.translation)) + ' rotation=' + str(tuple(cam.rotation_euler)) + ' projection=' + str([tuple(point) for point in projected]))
preview_scene.render.filepath = str(OUT / filename)
bpy.ops.render.render(write_still=True)
bpy.ops.object.select_all(action='DESELECT')
for obj in model_collection.objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = portafilter
bpy.ops.export_scene.gltf(
filepath=str(OUT / 'PerfectCoffee_Portafilter.glb'),
export_format='GLB',
use_selection=True,
export_apply=True,
export_cameras=False,
export_lights=False,
export_animations=False,
)
preview_scene.camera = bpy.data.objects['Portafilter_Front_XOZ']
preview_scene.render.filepath = str(OUT / 'portafilter_front.png')
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == 'VIEW_3D':
area.spaces.active.region_3d.view_perspective = 'CAMERA'
area.spaces.active.shading.type = 'MATERIAL'
bpy.context.window.scene = preview_scene
bpy.ops.file.pack_all()
removed_orphans = bpy.data.orphans_purge(do_recursive=True)
assert not any(name in bpy.data.objects for name in ('CM_CoffeeMachine', 'CM_Body', 'CM_GroupHead'))
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / 'PerfectCoffee_Portafilter.blend'))
print('PORTAFILTER_EXPORT=' + json.dumps({
'mesh_objects': len(mesh_objects),
'vertices': sum(len(obj.data.vertices) for obj in mesh_objects),
'polygons': sum(len(obj.data.polygons) for obj in mesh_objects),
'bounds_min_m': list(bounds_min),
'bounds_max_m': list(bounds_max),
'all_views_unclipped': all(coverage.values()),
'source_modified': False,
}, ensure_ascii=False), flush=True)
print('PORTAFILTER_EXPORT_COMPLETE', flush=True)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,327 @@
from pathlib import Path
import hashlib
import json
import math
import bmesh
import bpy
from mathutils import Vector
from mathutils.bvhtree import BVHTree
ROOT = Path(__file__).resolve().parent
SOURCE = ROOT / 'PerfectCoffee_CoffeeMachine.blend'
CUP_SOURCE = ROOT.parent / 'coffee_cup' / 'PerfectCoffee_CoffeeCup.blend'
OUT = ROOT / 'cup_fit_test'
OUT.mkdir(parents=True, exist_ok=True)
source_hash = hashlib.sha256(SOURCE.read_bytes()).hexdigest()
cup_hash = hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest()
bpy.ops.wm.open_mainfile(filepath=str(SOURCE))
bpy.context.preferences.filepaths.save_version = 0
scene = bpy.context.scene
scene.name = 'Cup_Placement_Test'
machine = bpy.data.objects['CM_CoffeeMachine']
group = bpy.data.objects['CM_GroupHead']
tray = bpy.data.objects['CM_DripTray_TextureSurface']
bpy.context.view_layer.update()
brew_xy = Vector((group.matrix_world.translation.x, group.matrix_world.translation.y))
support_z = max((tray.matrix_world @ vertex.co).z for vertex in tray.data.vertices)
with bpy.data.libraries.load(str(CUP_SOURCE), link=False) as (data_from, data_to):
data_to.objects = ['CC_Cup_Body']
cup = data_to.objects[0]
test_collection = bpy.data.collections.new('Cup_Placement_Test_Only')
scene.collection.children.link(test_collection)
test_collection.objects.link(cup)
cup.parent = None
cup.matrix_world.identity()
cup.rotation_euler = (0, 0, 0)
cup.scale = (1, 1, 1)
cup.location = (brew_xy.x, brew_xy.y, support_z)
cup['test_only'] = True
cup['lid_included'] = False
cup['support_surface'] = 'CM_DripTray_TextureSurface'
cup['support_z_m'] = support_z
intersection_collection = bpy.data.collections.new('Test_Intersection_Volumes')
scene.collection.children.link(intersection_collection)
probe_collection = bpy.data.collections.new('Test_Temporary_Probes')
scene.collection.children.link(probe_collection)
probe = bpy.data.objects.new('Test_Cup_Intersection_Probe', cup.data.copy())
probe_collection.objects.link(probe)
red = bpy.data.materials.new('Test_Collision_Red')
red.use_nodes = True
red.diffuse_color = (1, 0.015, 0.005, 1)
red.node_tree.nodes.get('Principled BSDF').inputs['Base Color'].default_value = (1, 0.015, 0.005, 1)
red.node_tree.nodes.get('Principled BSDF').inputs['Roughness'].default_value = 0.5
def world_mesh(obj, depsgraph):
evaluated = obj.evaluated_get(depsgraph)
mesh = evaluated.to_mesh()
vertices = [evaluated.matrix_world @ vertex.co for vertex in mesh.vertices]
polygons = [tuple(polygon.vertices) for polygon in mesh.polygons]
evaluated.to_mesh_clear()
return vertices, polygons
def bvh_from_world(vertices, polygons):
return BVHTree.FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)
def bounds_of_vertices(vertices):
return {
'min': [min(vertex[axis] for vertex in vertices) for axis in range(3)],
'max': [max(vertex[axis] for vertex in vertices) for axis in range(3)],
}
def intersection_volume(target):
probe.data = cup.data.copy()
probe.matrix_world = cup.matrix_world.copy()
bpy.context.view_layer.update()
modifier = probe.modifiers.new('Test_Intersection', 'BOOLEAN')
modifier.operation = 'INTERSECT'
modifier.solver = 'EXACT'
modifier.object = target
bpy.context.view_layer.objects.active = probe
bpy.ops.object.modifier_apply(modifier=modifier.name)
bm = bmesh.new()
bm.from_mesh(probe.data)
volume = abs(bm.calc_volume(signed=True))
bm.free()
vertices = [probe.matrix_world @ vertex.co for vertex in probe.data.vertices]
return volume, vertices
def check_position(position, keep_intersections=False, exact=True):
cup.location = (position[0], position[1], support_z)
bpy.context.view_layer.update()
depsgraph = bpy.context.evaluated_depsgraph_get()
vertices, polygons = world_mesh(cup, depsgraph)
cup_bvh = bvh_from_world(vertices, polygons)
collisions = []
contacts = []
for target, target_bvh in machine_bvhs:
pairs = cup_bvh.overlap(target_bvh)
if not pairs:
continue
if not exact:
contacts.append({'machine_part': target.name, 'overlapping_face_pairs': len(pairs)})
continue
volume, intersection_vertices = intersection_volume(target)
entry = {
'machine_part': target.name,
'overlapping_face_pairs': len(pairs),
'intersection_volume_mm3': volume * 1e9,
}
if intersection_vertices:
entry['intersection_bounds_m'] = bounds_of_vertices(intersection_vertices)
if volume > 1e-12:
collisions.append(entry)
if keep_intersections:
intersection_mesh = probe.data.copy()
intersection_mesh.name = 'Test_Intersection_' + target.name
intersection_mesh.materials.clear()
intersection_mesh.materials.append(red)
intersection_obj = bpy.data.objects.new(intersection_mesh.name, intersection_mesh)
intersection_collection.objects.link(intersection_obj)
intersection_obj.matrix_world = probe.matrix_world.copy()
intersection_obj['test_only'] = True
else:
contacts.append(entry)
return collisions, contacts
bpy.context.view_layer.update()
depsgraph = bpy.context.evaluated_depsgraph_get()
machine_objects = [
obj for obj in machine.children_recursive
if obj.type in {'MESH', 'CURVE', 'FONT', 'SURFACE'} and obj != tray
]
machine_bvhs = []
for obj in machine_objects:
vertices, polygons = world_mesh(obj, depsgraph)
machine_bvhs.append((obj, bvh_from_world(vertices, polygons)))
centered_collisions, centered_contacts = check_position(brew_xy, keep_intersections=True)
spout_objects = [bpy.data.objects['CM_Portafilter_SpoutLeft'], bpy.data.objects['CM_Portafilter_SpoutRight']]
outlet_min_z = min(
(obj.matrix_world @ Vector(corner)).z
for obj in spout_objects for corner in obj.bound_box
)
cup_bounds = bounds_of_vertices([
cup.matrix_world @ vertex.co for vertex in cup.data.vertices
])
def circle_overlap_ratio(dx, dy, small=0.0425, large=0.05):
distance = math.hypot(dx, dy)
if distance >= small + large:
return 0.0
if distance <= large - small:
return 1.0
first = math.acos((distance * distance + small * small - large * large) / (2 * distance * small))
second = math.acos((distance * distance + large * large - small * small) / (2 * distance * large))
area = small * small * first + large * large * second - 0.5 * math.sqrt(
(-distance + small + large) * (distance + small - large)
* (distance - small + large) * (distance + small + large)
)
return area / (math.pi * small * small)
candidates = []
for ix in range(-32, 33):
dx = ix * 0.0025
for iy in range(-22, 22):
dy = iy * 0.0025
position = brew_xy + Vector((dx, dy))
overlap = circle_overlap_ratio(dx, dy)
if overlap < 0.25:
continue
collisions, contacts = check_position(position, exact=False)
if not collisions and not contacts:
candidates.append({
'cup_bottom_center_m': [position.x, position.y, support_z],
'offset_from_brew_axis_mm': [dx * 1000, dy * 1000],
'head_projection_overlap_percent_of_cup': overlap * 100,
'penetrations': 0,
'surface_contacts_excluding_tray_support': 0,
})
candidates.sort(key=lambda candidate: (
-candidate['head_projection_overlap_percent_of_cup'],
math.hypot(*candidate['offset_from_brew_axis_mm']),
))
best = candidates[0] if candidates else None
scene.render.engine = 'CYCLES'
scene.cycles.samples = 40
scene.cycles.use_denoising = True
scene.render.resolution_x = 1400
scene.render.resolution_y = 1400
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.view_settings.view_transform = 'AgX'
def point_at(obj, target):
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
def test_camera(name, location, target, scale):
data = bpy.data.cameras.new(name)
data.type = 'ORTHO'
data.ortho_scale = scale
data.clip_start = 0.001
data.clip_end = 100
obj = bpy.data.objects.new(name, data)
bpy.data.collections['Studio_Exclude_From_Export'].objects.link(obj)
obj.location = location
point_at(obj, target)
return obj
side_camera = test_camera('CupTest_Centered_YOZ', (0.9, brew_xy.y, 0.21), (0, brew_xy.y, 0.18), 0.245)
front_camera = test_camera('CupTest_Centered_XOZ', (0, -0.9, 0.215), (0, brew_xy.y, 0.18), 0.245)
cup.location = (brew_xy.x, brew_xy.y, support_z)
bpy.context.view_layer.update()
for camera, filename in [(front_camera, 'centered_front.png'), (side_camera, 'centered_side.png')]:
scene.camera = camera
scene.render.filepath = str(OUT / filename)
bpy.ops.render.render(write_still=True)
if best:
cup.location = best['cup_bottom_center_m']
bpy.context.view_layer.update()
scene.camera = side_camera
scene.render.filepath = str(OUT / 'accepted_side.png')
bpy.ops.render.render(write_still=True)
original_materials = {obj.data: list(obj.data.materials) for obj in machine_objects if obj.type == 'MESH'}
ghost = bpy.data.materials.new('Test_Top_Ghost')
ghost.use_nodes = True
nodes = ghost.node_tree.nodes
nodes.clear()
transparent = nodes.new('ShaderNodeBsdfTransparent')
solid = nodes.new('ShaderNodeBsdfPrincipled')
solid.inputs['Base Color'].default_value = (0.42, 0.52, 0.61, 1)
solid.inputs['Roughness'].default_value = 0.5
mix = nodes.new('ShaderNodeMixShader')
mix.inputs[0].default_value = 0.13
output = nodes.new('ShaderNodeOutputMaterial')
ghost.node_tree.links.new(transparent.outputs[0], mix.inputs[1])
ghost.node_tree.links.new(solid.outputs[0], mix.inputs[2])
ghost.node_tree.links.new(mix.outputs[0], output.inputs['Surface'])
for mesh, materials in original_materials.items():
mesh.materials.clear()
mesh.materials.append(ghost)
top_camera = test_camera('CupTest_Best_XOY_Ghost', (brew_xy.x, brew_xy.y, 0.9), (brew_xy.x, brew_xy.y, 0), 0.30)
scene.camera = top_camera
scene.render.filepath = str(OUT / 'accepted_top_ghost.png')
bpy.ops.render.render(write_still=True)
for mesh, materials in original_materials.items():
mesh.materials.clear()
for material in materials:
mesh.materials.append(material)
cup.location = (brew_xy.x, brew_xy.y, support_z)
bpy.context.view_layer.update()
probe.hide_render = True
probe.hide_viewport = True
scene.camera = side_camera
scene.render.filepath = str(OUT / 'centered_side.png')
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == 'VIEW_3D':
area.spaces.active.region_3d.view_perspective = 'CAMERA'
area.spaces.active.shading.type = 'MATERIAL'
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / 'CupPlacement_Test.blend'))
assert hashlib.sha256(SOURCE.read_bytes()).hexdigest() == source_hash
assert hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest() == cup_hash
report = {
'source_machine_unchanged': True,
'source_machine_sha256': source_hash,
'source_cup_unchanged': True,
'source_cup_sha256': cup_hash,
'lid_included': False,
'layout': {
'scheme': 'A',
'brew_center_xy_m': list(brew_xy),
'group_seal_z_mm': group.matrix_world.translation.z * 1000,
'tray_support_z_mm': support_z * 1000,
},
'cup': {
'height_mm': 110,
'top_diameter_mm': 85,
'bottom_diameter_mm': 60,
'bottom_center_m': [brew_xy.x, brew_xy.y, support_z],
'bottom_z_mm': cup_bounds['min'][2] * 1000,
'bottom_on_tray_surface': abs(cup_bounds['min'][2] - support_z) < 1e-7,
'top_z_mm': cup_bounds['max'][2] * 1000,
},
'lowest_spout_z_mm': outlet_min_z * 1000,
'spout_to_tray_clearance_mm': (outlet_min_z - support_z) * 1000,
'spout_clearance_above_cup_mm': (outlet_min_z - cup_bounds['max'][2]) * 1000,
'centered_head_projection_overlap_percent_of_cup': circle_overlap_ratio(0, 0) * 100,
'centered_penetrations': centered_collisions,
'centered_surface_contacts_excluding_tray_support': centered_contacts,
'centered_passed': not centered_collisions and not centered_contacts,
'search': {
'xy_step_mm': 2.5,
'cup_upright': True,
'bottom_remains_on_tray': True,
'minimum_projection_overlap_percent_allowed': 25,
'tested_collision_free_candidates': len(candidates),
'best_valid_position': best,
},
}
(OUT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
assert report['cup']['bottom_on_tray_surface'], 'Cup bottom is not on the tray surface.'
assert report['centered_passed'], 'Cup placement still intersects the coffee machine: ' + json.dumps(centered_collisions + centered_contacts)
assert best and best['offset_from_brew_axis_mm'] == [0.0, 0.0], 'The centered position is not the best valid position.'
print('CUP_PLACEMENT_VALIDATION=' + json.dumps(report, ensure_ascii=False), flush=True)
print('CUP_PLACEMENT_TEST_COMPLETE', flush=True)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.