Files
PerfectCoffee/model_assets/coffee_cup/optimize_cup_contents_mobile.py
Yanchen 0f9e127162 feat: track remaining production assets, playtest scenes and references
Close the gaps left open after the LFS migration: 177 files that were
sitting untracked now enter version control, with every binary going
through Git LFS.

- labels: milk and orange-juice wrap artwork (SVG/PNG), Seedream sources,
  prompts and Dreamina job records
- orange juice 2L: bottle, cap, empty state and three label variants
  (blend + glb each)
- cup contents: desktop and mobile-optimised variants plus 3 textures
- milk 2L: empty and packaged variants with their glb exports
- milk frother: low-poly assembly and split base/jug parts
- tamper: model, glb and fit test
- juicer: seven assembly-part review scenes and their export scripts
- playtests: extraction animation scene and grinding/tamping whitebox
- reference: Minex page candidates, user review screenshots, sequence
  analysis frames and tamper STLs
- docs: item design draft, bean research notes, region reference and the
  model-asset audit report

Re-renderable preview/check frames stay untracked on purpose.
2026-11-22 10:26:53 +08:00

341 lines
14 KiB
Python

import bpy
import bmesh
import hashlib
import json
import math
import re
import shutil
import struct
import subprocess
from pathlib import Path
from mathutils.bvhtree import BVHTree
OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/coffee_cup')
BASE = OUT / 'PerfectCoffee_CupContents.blend'
MOBILE_BLEND = OUT / 'PerfectCoffee_CupContents_Mobile.blend'
MOBILE_GLB = OUT / 'PerfectCoffee_CupContents_Mobile.glb'
ATLAS = OUT / 'textures' / 'CC_CupContents_Atlas.png'
COMPARISONS = OUT / 'optimization'
COMPARISONS.mkdir(exist_ok=True)
FFMPEG = shutil.which('ffmpeg')
assert FFMPEG, 'ffmpeg is required for the existing lossless texture and comparison pipeline'
BASE_SHA256 = hashlib.sha256(BASE.read_bytes()).hexdigest()
ORIGINAL_TEXTURE_BYTES = sum((OUT / 'textures' / name).stat().st_size for name in ('CC_Coffee_Surface.png', 'CC_Latte_Surface.png'))
SEGMENTS = 48
CUP_SEGMENTS = 24
FOAM_BOTTOM = 0.10382
FOAM_EDGE_TOP = 0.10570
FOAM_DOME = 0.00035
FIT_CLEARANCE = 0.00012
def run(command):
result = subprocess.run(command, check=True, text=True, capture_output=True)
return result.stdout + result.stderr
run([
FFMPEG, '-y', '-hide_banner', '-loglevel', 'warning',
'-i', str(OUT / 'textures' / 'CC_Coffee_Surface.png'),
'-i', str(OUT / 'textures' / 'CC_Latte_Surface.png'),
'-filter_complex',
'[0:v]scale=512:512:flags=lanczos[a];[1:v]scale=512:512:flags=lanczos[b];[a][b]hstack=inputs=2,format=rgb24[out]',
'-map', '[out]', '-frames:v', '1', '-pred', 'mixed', '-compression_level', '9', '-update', '1', str(ATLAS),
])
bpy.ops.wm.open_mainfile(filepath=str(BASE))
bpy.context.preferences.filepaths.save_version = 0
scene = bpy.context.scene
root = bpy.data.objects['CC_CupContents_Assembly']
cup = bpy.data.objects['CC_Cup_Body']
liquid = bpy.data.objects['CC_Coffee_Liquid']
foam = bpy.data.objects['CC_Milk_Foam']
coffee_mat = bpy.data.materials['CC_Coffee_Liquid']
foam_mat = bpy.data.materials['CC_Milk_Foam']
original_foam_vertices = len(foam.data.vertices)
foam.data.calc_loop_triangles()
original_foam_triangles = len(foam.data.loop_triangles)
liquid.data.calc_loop_triangles()
liquid_triangles = len(liquid.data.loop_triangles)
original_foam_bounds = {
'min_z': min(vertex.co.z for vertex in foam.data.vertices),
'max_z': max(vertex.co.z for vertex in foam.data.vertices),
'max_radius': max(math.hypot(vertex.co.x, vertex.co.y) for vertex in foam.data.vertices),
}
scene.cycles.samples = 96
scene.cycles.use_denoising = True
scene.render.resolution_x = 1400
scene.render.resolution_y = 1400
scene.render.resolution_percentage = 100
for camera_name, filename in [
('Acceptance_Latte_Cycles', 'before_latte.png'),
('Acceptance_Latte_Top_UV', 'before_latte_top.png'),
]:
scene.camera = bpy.data.objects[camera_name]
scene.render.filepath = str(COMPARISONS / filename)
bpy.ops.render.render(write_still=True)
atlas_image = bpy.data.images.load(str(ATLAS), check_existing=False)
atlas_image.name = 'CC_CupContents_Atlas'
atlas_image.colorspace_settings.name = 'sRGB'
atlas_image.pack()
for material in (coffee_mat, foam_mat):
for node in material.node_tree.nodes:
if node.type == 'TEX_IMAGE':
node.image = atlas_image
for image_name in ('CC_Coffee_Surface', 'CC_Latte_Surface'):
image = bpy.data.images.get(image_name)
if image is not None and image.users == 0:
bpy.data.images.remove(image)
for obj, offset in ((liquid, 0.0), (foam, 0.5)):
uv = obj.data.uv_layers['LiquidSurfaceUV']
for loop_uv in uv.data:
loop_uv.uv.x = offset + loop_uv.uv.x * 0.5
obj['uv_map'] = 'LiquidSurfaceUV'
obj['atlas_rect'] = [offset, 0.0, 0.5, 1.0]
def fitted_radius(z):
if z <= 0.022:
radius = 0.028 + (z - 0.002) * (0.0305 - 0.028) / 0.020
else:
radius = 0.0305 + (z - 0.022) * (0.038 - 0.0305) / 0.066
return radius * math.cos(math.pi / CUP_SEGMENTS) - FIT_CLEARANCE
outer_radius = fitted_radius(FOAM_EDGE_TOP)
rings = [
(fitted_radius(FOAM_BOTTOM), FOAM_BOTTOM),
(outer_radius, FOAM_EDGE_TOP),
(outer_radius * 0.55, FOAM_EDGE_TOP + FOAM_DOME * (1.0 - 0.55 * 0.55)),
]
vertices = []
for radius, z in rings:
for index in range(SEGMENTS):
angle = math.tau * index / SEGMENTS
vertices.append((radius * math.cos(angle), radius * math.sin(angle), z))
faces = [tuple(reversed(range(SEGMENTS)))]
for ring_index in range(len(rings) - 1):
first = ring_index * SEGMENTS
second = first + SEGMENTS
for index in range(SEGMENTS):
following = (index + 1) % SEGMENTS
faces.append((first + index, first + following, second + following, second + index))
center_index = len(vertices)
vertices.append((0.0, 0.0, FOAM_EDGE_TOP + FOAM_DOME))
last = (len(rings) - 1) * SEGMENTS
for index in range(SEGMENTS):
following = (index + 1) % SEGMENTS
faces.append((last + index, last + following, center_index))
mesh = bpy.data.meshes.new('CC_Milk_Foam_Mobile_Mesh')
mesh.from_pydata(vertices, [], faces)
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
bm.to_mesh(mesh)
bm.free()
mesh.update()
mesh.materials.append(foam_mat)
uv = mesh.uv_layers.new(name='LiquidSurfaceUV')
for polygon in mesh.polygons:
polygon.use_smooth = abs(polygon.normal.z) < 0.995
for loop_index in polygon.loop_indices:
vertex = mesh.vertices[mesh.loops[loop_index].vertex_index].co
u = 0.5 + vertex.x / (2.0 * outer_radius)
v = 0.5 + vertex.y / (2.0 * outer_radius)
uv.data[loop_index].uv = (0.5 + u * 0.5, v)
mesh.uv_layers.active = uv
old_mesh = foam.data
foam.data = mesh
if old_mesh.users == 0:
bpy.data.meshes.remove(old_mesh)
foam['radial_segments'] = SEGMENTS
foam['radial_surface_rings'] = 2
foam['top_uv_faces'] = SEGMENTS * 2
foam['atlas_rect'] = [0.5, 0.0, 0.5, 1.0]
foam['surface_texture'] = ATLAS.name
foam['surface_texture_uv'] = 'LiquidSurfaceUV; right half of atlas; original 0-1 liquid UV is remapped to U=0.5-1.0'
foam['optimization'] = '96 to 48 segments; seven concentric surface rings to one intermediate ring; thickness and dome preserved'
liquid['surface_texture'] = ATLAS.name
liquid['surface_texture_uv'] = 'LiquidSurfaceUV; left half of atlas; original 0-1 liquid UV is remapped to U=0-0.5'
root['uv_usage'] = 'LiquidSurfaceUV atlas: coffee U=0-0.5; foam U=0.5-1; shared V=0-1; each tile center U=0.25 or 0.75, V=0.5'
root['texture_atlas'] = 'CC_CupContents_Atlas.png; left coffee 512x512, right latte 512x512; RGB PNG lossless'
root['mobile_baseline_blend'] = BASE.name
root['mobile_baseline_sha256'] = BASE_SHA256
root['foam_original_segments'] = 96
root['foam_mobile_segments'] = SEGMENTS
def non_manifold_count(obj):
bm = bmesh.new()
bm.from_mesh(obj.data)
count = sum(1 for edge in bm.edges if not edge.is_manifold)
bm.free()
return count
def uv_bounds(obj):
uv = obj.data.uv_layers.active
return {
'u': [min(loop_uv.uv.x for loop_uv in uv.data), max(loop_uv.uv.x for loop_uv in uv.data)],
'v': [min(loop_uv.uv.y for loop_uv in uv.data), max(loop_uv.uv.y for loop_uv in uv.data)],
}
def glb_statistics(path):
raw = path.read_bytes()
json_length, chunk_type = struct.unpack_from('<II', raw, 12)
assert chunk_type == 0x4E4F534A
asset = json.loads(raw[20:20 + json_length])
vertices = 0
triangles = 0
for mesh in asset['meshes']:
for primitive in mesh['primitives']:
vertices += asset['accessors'][primitive['attributes']['POSITION']]['count']
triangles += asset['accessors'][primitive['indices']]['count'] // 3
return {
'bytes': len(raw),
'meshes': len(asset['meshes']),
'vertices_after_export_split': vertices,
'triangles': triangles,
'images': len(asset.get('images', [])),
'materials': len(asset.get('materials', [])),
'cameras': len(asset.get('cameras', [])),
}
bpy.context.view_layer.update()
foam.data.calc_loop_triangles()
mobile_foam_triangles = len(foam.data.loop_triangles)
cup_bvh = BVHTree.FromObject(cup, bpy.context.evaluated_depsgraph_get())
liquid_bvh = BVHTree.FromObject(liquid, bpy.context.evaluated_depsgraph_get())
foam_bvh = BVHTree.FromObject(foam, bpy.context.evaluated_depsgraph_get())
liquid_uv = uv_bounds(liquid)
foam_uv = uv_bounds(foam)
center_uv = next(uv.data[loop.index].uv[:] for loop in foam.data.loops if loop.vertex_index == center_index)
mobile_foam_bounds = {
'min_z': min(vertex.co.z for vertex in foam.data.vertices),
'max_z': max(vertex.co.z for vertex in foam.data.vertices),
'max_radius': max(math.hypot(vertex.co.x, vertex.co.y) for vertex in foam.data.vertices),
}
outer_envelope_preserved = all(
math.isclose(original_foam_bounds[key], mobile_foam_bounds[key], rel_tol=0.0, abs_tol=0.000000001)
for key in original_foam_bounds
)
geometry_and_export_passed = (
non_manifold_count(foam) == 0
and len(cup_bvh.overlap(liquid_bvh)) == 0
and len(cup_bvh.overlap(foam_bvh)) == 0
and len(liquid_bvh.overlap(foam_bvh)) == 0
and mobile_foam_triangles == 286
and len(foam.data.vertices) == 145
and outer_envelope_preserved
and abs(liquid_uv['u'][0]) < 0.000001
and abs(liquid_uv['u'][1] - 0.5) < 0.000001
and abs(foam_uv['u'][0] - 0.5) < 0.000001
and abs(foam_uv['u'][1] - 1.0) < 0.000001
and all(abs(value - 0.5) < 0.000001 for value in center_uv[1:])
and abs(center_uv[0] - 0.75) < 0.000001
and atlas_image.packed_file is not None
and hashlib.sha256(BASE.read_bytes()).hexdigest() == BASE_SHA256
)
assert geometry_and_export_passed, 'Mobile geometry, atlas UV or source preservation validation failed'
bpy.ops.object.select_all(action='DESELECT')
root.select_set(True)
liquid.select_set(True)
foam.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.export_scene.gltf(
filepath=str(MOBILE_GLB),
export_format='GLB',
use_selection=True,
export_apply=True,
export_animations=False,
export_extras=True,
export_cameras=False,
export_lights=False,
)
for camera_name, filename in [
('Acceptance_Latte_Cycles', 'after_latte.png'),
('Acceptance_Latte_Top_UV', 'after_latte_top.png'),
]:
scene.camera = bpy.data.objects[camera_name]
scene.render.filepath = str(COMPARISONS / filename)
bpy.ops.render.render(write_still=True)
metrics = {}
for view in ('latte', 'latte_top'):
before = COMPARISONS / f'before_{view}.png'
after = COMPARISONS / f'after_{view}.png'
ssim_log = run([FFMPEG, '-hide_banner', '-nostats', '-i', str(before), '-i', str(after), '-filter_complex', '[0:v][1:v]ssim', '-f', 'null', '-'])
psnr_log = run([FFMPEG, '-hide_banner', '-nostats', '-i', str(before), '-i', str(after), '-filter_complex', '[0:v][1:v]psnr', '-f', 'null', '-'])
ssim_match = re.search(r'All:([0-9.]+)', ssim_log)
psnr_match = re.search(r'average:([0-9.]+|inf)', psnr_log)
assert ssim_match and psnr_match, f'Unable to read image metrics for {view}'
metrics[view] = {'ssim_all': float(ssim_match.group(1)), 'psnr_db': psnr_match.group(1)}
run([
FFMPEG, '-y', '-hide_banner', '-loglevel', 'warning', '-i', str(before), '-i', str(after),
'-filter_complex',
'[0:v]scale=900:900:flags=lanczos[a];[1:v]scale=900:900:flags=lanczos[b];[a]pad=912:900:0:0:color=0x202124[ap];[ap][b]hstack=inputs=2[out]',
'-map', '[out]', '-frames:v', '1', '-pred', 'mixed', '-compression_level', '9', '-update', '1',
str(COMPARISONS / f'compare_{view}.png'),
])
report = {
'baseline_blend': BASE.name,
'baseline_sha256_before_optimization': BASE_SHA256,
'baseline_sha256_after_optimization': hashlib.sha256(BASE.read_bytes()).hexdigest(),
'mobile_blend': MOBILE_BLEND.name,
'mobile_glb': MOBILE_GLB.name,
'texture': {
'before': {'count': 2, 'dimensions_each': [1024, 1024], 'png_bytes_total': ORIGINAL_TEXTURE_BYTES, 'rgba8_with_mipmaps_mib': 10.6666666667},
'after': {'count': 1, 'dimensions': [1024, 512], 'tile_dimensions_each': [512, 512], 'format': 'RGB PNG, lossless', 'png_bytes': ATLAS.stat().st_size, 'rgba8_with_mipmaps_mib': 2.6666666667},
'file_size_reduction_percent': (1.0 - ATLAS.stat().st_size / ORIGINAL_TEXTURE_BYTES) * 100.0,
'gpu_memory_reduction_percent': 75.0,
},
'foam': {
'vertices_before': original_foam_vertices,
'vertices_after': len(foam.data.vertices),
'triangles_before': original_foam_triangles,
'triangles_after': mobile_foam_triangles,
'triangle_reduction_percent': (1.0 - mobile_foam_triangles / original_foam_triangles) * 100.0,
'segments_before': 96,
'segments_after': SEGMENTS,
'thickness_edge_mm': (FOAM_EDGE_TOP - FOAM_BOTTOM) * 1000.0,
'dome_rise_mm': FOAM_DOME * 1000.0,
'outer_envelope_preserved': outer_envelope_preserved,
'non_manifold_edges': non_manifold_count(foam),
},
'complete_contents_triangles_before': liquid_triangles + original_foam_triangles,
'complete_contents_triangles_after': liquid_triangles + mobile_foam_triangles,
'intersections': {
'liquid_cup': len(cup_bvh.overlap(liquid_bvh)),
'foam_cup': len(cup_bvh.overlap(foam_bvh)),
'foam_liquid': len(liquid_bvh.overlap(foam_bvh)),
},
'atlas_uv': {'coffee': liquid_uv, 'foam': foam_uv, 'foam_center': list(center_uv)},
'glb': glb_statistics(MOBILE_GLB),
'image_metrics_before_vs_after': metrics,
'comparison_convention': 'Left=original, right=Mobile; identical camera, lighting, Cycles samples, resolution and color management',
'geometry_and_export_passed': geometry_and_export_passed,
'visual_review': 'pending_manual_comparison',
}
(COMPARISONS / 'validation_mobile.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
scene.camera = bpy.data.objects['Acceptance_Latte_Cycles']
scene.render.filepath = str(COMPARISONS / 'after_latte.png')
bpy.ops.object.select_all(action='DESELECT')
root.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.wm.save_as_mainfile(filepath=str(MOBILE_BLEND))
print('MOBILE_OPTIMIZATION_VALIDATION=' + json.dumps(report, ensure_ascii=False), flush=True)
print('MOBILE_OPTIMIZATION_BUILD_COMPLETE', flush=True)