Bake From Source: one pair under its own names even beside orphans, linked mesh data refused, one error-text site in the operator

Orphan images holding the pair's names are freed at the commit instead of forcing .001; a bake never repoints a slot Source shares through mesh data; the operator's execute is the only place a bake error becomes report text (Refusal marks the module's own fixed text, everything else goes to the console); the copied-material count is asserted. Builds (Blender add-on, no compile step).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-13 01:47:23 +02:00
commit bc88f43a19
2 changed files with 113 additions and 44 deletions

View file

@ -126,14 +126,14 @@ def _load_layout(context, collection, path):
_EXPECTED = (OSError, ValueError, RuntimeError, ImportError, KeyError)
class BakeFailed(RuntimeError):
"""The one error a bake raises past its rollback. Its message is fixed text; whatever Blender raised is on the console."""
class Refusal(ValueError):
"""A refusal Bake From Source raises itself: its message is fixed text that names no input. Blender's ValueError is not one."""
def _failure_text(exc):
"""What an operator reports for exc. This module's own ValueError and RuntimeError messages are fixed text that
names no input; any other error is reported by its type, and its text goes to the system console."""
if type(exc) in (ValueError, RuntimeError, BakeFailed):
if type(exc) in (ValueError, RuntimeError, Refusal):
return str(exc)
traceback.print_exception(exc)
return f"Stopped by {type(exc).__name__}; see the system console"
@ -521,13 +521,13 @@ def _ship_collection(context, unbound_ok=False):
active object's only collection when no ship collection holds it."""
obj = context.active_object
if obj is None:
raise ValueError("Select an object in the ship collection")
raise Refusal("Select an object in the ship collection")
ships = [collection for collection in bpy.data.collections if _is_ship(collection) and obj.name in collection.all_objects]
if len(ships) == 1:
return ships[0]
if unbound_ok and not ships and len(obj.users_collection) == 1:
return obj.users_collection[0]
raise ValueError("Select an object in exactly one ship collection" if unbound_ok
raise Refusal("Select an object in exactly one ship collection" if unbound_ok
else "Selected object must belong to exactly one bound ship collection")
@ -1130,18 +1130,18 @@ def _select_only(context, objects):
def _refuse_selecting(context, offenders, message):
"""Selects the offenders and refuses with message, which names a count and never an object."""
_select_only(context, offenders)
raise ValueError(message)
raise Refusal(message)
def _bake_inputs(context, collection):
"""The ship ID, the Source meshes and the selected render meshes Bake From Source works on, or the refusal that
stops it before anything changes."""
if context.mode != "OBJECT":
raise ValueError("Switch to Object mode before baking")
raise Refusal("Switch to Object mode before baking")
source = _child(collection, SOURCE)
sources = _meshes(source.all_objects) if source else []
if _ship_root(collection) is None or not sources:
raise ValueError("Bake From Source needs a Ship Root and a mesh in Source; run New Ship first")
raise Refusal("Bake From Source needs a Ship Root and a mesh in Source; run New Ship first")
layer = context.view_layer
hidden = [obj for obj in sources if obj.name not in layer.objects or obj.hide_get()]
if hidden:
@ -1149,7 +1149,11 @@ def _bake_inputs(context, collection):
f"{len(hidden)} Source meshes are hidden or outside the view layer; show them to bake")
targets = [obj for obj in _own_meshes(collection) if obj.name in layer.objects and obj.select_get()]
if not targets:
raise ValueError("Select the render meshes to bake onto")
raise Refusal("Select the render meshes to bake onto")
shared = {obj.data for obj in sources}
linked = [obj for obj in targets if obj.data in shared]
if linked: # a material slot belongs to the mesh data, so the bake would repoint Source's own slot
_refuse_selecting(context, linked, f"{len(linked)} selected meshes share their mesh data with a Source mesh; make them single user first")
flat = [obj for obj in targets if not obj.data.uv_layers]
if flat:
_refuse_selecting(context, flat, f"{len(flat)} selected meshes have no UV layer; unwrap them first")
@ -1251,15 +1255,21 @@ def _link_into(material, node, input_name, source, undo):
def _refuse_taken_names(ship_id, targets):
"""The ship's pair is {ship_id}.albedo and {ship_id}.normal and there is one pair: an image already holding a name must
be one this bake replaces and frees, or the new image would take a numbered name beside it."""
"""The ship's pair is {ship_id}.albedo and {ship_id}.normal and there is one pair. An image holding a name must be one
this bake replaces (used only by the selected meshes' wiring) or one nothing uses; returns those images, which the bake
frees before it names its own. Any other holder refuses."""
materials = _target_materials(targets)
holders = []
for kind, _, _ in BAKE_MAPS:
image = bpy.data.images.get(f"{ship_id}.{kind}")
if image is None:
continue
wired = [node for node in (_wired_image(material, kind) for material in materials) if node is not None and node.image == image]
if image is not None and (image.use_fake_user or image.users != len(wired)):
raise ValueError("The ship's baked image names are held by images this bake does not replace; select every "
if image.use_fake_user or image.users != len(wired):
raise Refusal("The ship's baked image names are held by images this bake does not replace; select every "
"mesh that uses them, or rename the other images")
holders.append(image)
return holders
def _bake_map(context, sources, targets, settings, extrusion, max_distance, nodes):
@ -1272,13 +1282,19 @@ def _bake_map(context, sources, targets, settings, extrusion, max_distance, node
layer.objects.active = target
for slot in target.material_slots:
slot.material.node_tree.nodes.active = nodes[slot.material.name]
try:
bpy.ops.object.bake(
use_selected_to_active=True, cage_extrusion=extrusion, max_ray_distance=max_distance, use_clear=index == 0,
**settings)
except RuntimeError: # Blender's text names objects and images
traceback.print_exc()
raise BakeFailed("The bake failed; its message is in the system console") from None
bpy.ops.object.bake(
use_selected_to_active=True, cage_extrusion=extrusion, max_ray_distance=max_distance, use_clear=index == 0,
**settings)
def _settle_images(ship_id, images, stale):
"""The commit's last step: frees the images the bake replaced and the unused ones that held the pair's names, then
names the new images {ship_id}.albedo and {ship_id}.normal."""
for image in {image.name: image for image in stale}.values(): # named before any is removed
if image.users == 0:
bpy.data.images.remove(image)
for kind, image in images.items():
image.name = f"{ship_id}.{kind}"
def _bake_from_source(context, collection, replace):
@ -1288,8 +1304,8 @@ def _bake_from_source(context, collection, replace):
were afterwards."""
ship_id, sources, targets = _bake_inputs(context, collection)
if not replace and any(_wired_image(material, kind) for material in _target_materials(targets) for kind, _, _ in BAKE_MAPS):
raise ValueError("Selected meshes already have baked images; confirm the replace")
_refuse_taken_names(ship_id, targets)
raise Refusal("Selected meshes already have baked images; confirm the replace")
holders = _refuse_taken_names(ship_id, targets)
addon = context.preferences.addons[__package__].preferences
scene, layer = context.scene, context.view_layer
previous_selection = [obj for obj in layer.objects if obj.select_get()]
@ -1350,21 +1366,14 @@ def _bake_from_source(context, collection, replace):
undo.append(partial(_remove_node, material.name, normal.name))
material.node_tree.links.new(node.outputs["Color"], normal.inputs["Color"])
_link_into(material, bsdf, "Normal", normal.outputs["Normal"], undo)
except BaseException as exc:
except BaseException:
for step in reversed(undo):
step()
if isinstance(exc, Exception) and not isinstance(exc, BakeFailed): # Blender's text names objects and images
traceback.print_exception(exc)
raise BakeFailed("The bake failed; its message is in the system console") from None
raise
finally:
for step in reversed(restore):
step()
for image in replaced.values():
if image.users == 0:
bpy.data.images.remove(image)
for kind, image in images.items():
image.name = f"{ship_id}.{kind}"
_settle_images(ship_id, images, [*replaced.values(), *holders])
return copied
@ -1382,7 +1391,7 @@ class AETHERIA_OT_bake_from_source(bpy.types.Operator):
def invoke(self, context, event):
try:
_, _, targets = _bake_inputs(context, _ship_collection(context))
except _EXPECTED:
except Exception:
return self.execute(context) # the same refusal, reported
if any(_wired_image(material, kind) for material in _target_materials(targets) for kind, _, _ in BAKE_MAPS):
self.replace = True
@ -1394,10 +1403,14 @@ class AETHERIA_OT_bake_from_source(bpy.types.Operator):
try:
copied = _bake_from_source(context, _ship_collection(context), self.replace)
self.report({"INFO"}, "Baked the albedo and normal maps from Source" + (
f"; {copied} materials shared with Source were copied for the render meshes" if copied else ""))
f"; materials shared with Source, copied for the render meshes: {copied}" if copied else ""))
return {"FINISHED"}
except _EXPECTED as exc:
return _refuse(self, exc)
except Exception as exc: # the one place a bake's error becomes report text
if type(exc) is Refusal:
return _refuse(self, exc)
traceback.print_exception(exc) # whatever else Blender raised names objects and images
self.report({"ERROR"}, "The bake failed; its message is in the system console")
return {"CANCELLED"}
def _new_ship(context, ship_id, name, reference, length):

View file

@ -241,27 +241,28 @@ def glb_image_sizes(path):
class FailingCall:
"""Stands in for a function: the n-th call raises, the others run the real one."""
def __init__(self, real, fail_on):
self.real, self.fail_on, self.calls = real, fail_on, 0
def __init__(self, real, fail_on, error=RuntimeError):
self.real, self.fail_on, self.calls, self.error = real, fail_on, 0, error
def __call__(self, *args, **arguments):
self.calls += 1
if self.calls == self.fail_on:
raise RuntimeError("probe: forced failure")
raise self.error("probe: forced failure")
return self.real(*args, **arguments)
def failing_pass(aetheria_ships, label, targets, materials, sources, replace, site, fail_on):
def failing_pass(aetheria_ships, label, targets, materials, sources, replace, site, fail_on, error=RuntimeError, rolled_back=True):
"""A run whose fail_on-th call of site raises (the Cycles bake, or one of the add-on's own commit steps) leaves the
Source, the materials, the images, the scene settings and the selection as they were."""
Source, the materials, the images, the scene settings and the selection as they were, and reports fixed text whatever the
type of the error and wherever it was raised. rolled_back=False is for a failure after the commit: only the text is checked."""
real_bpy, real_site = aetheria_ships.bpy, getattr(aetheria_ships, site, None)
if site == "bake":
patched = FailingCall(bpy.ops.object.bake, fail_on)
patched = FailingCall(bpy.ops.object.bake, fail_on, error)
proxy = {name: getattr(bpy, name) for name in dir(bpy) if not name.startswith("__")}
proxy["ops"] = types.SimpleNamespace(object=types.SimpleNamespace(bake=patched))
replacement = {"bpy": types.SimpleNamespace(**proxy)}
else:
patched = FailingCall(real_site, fail_on)
patched = FailingCall(real_site, fail_on, error)
replacement = {site: patched}
def state():
@ -280,11 +281,23 @@ def failing_pass(aetheria_ships, label, targets, materials, sources, replace, si
require(patched.calls >= fail_on, f"{label}: the forced failure never landed ({patched.calls} calls)")
require(result == {"CANCELLED"}, f"{label}: a failing run was not refused")
require("The bake failed" in message and "probe" not in message, f"{label}: Blender's own text reached the report ({message!r})")
if not rolled_back:
return
after = state()
for part, name in enumerate(("wiring", "Source materials", "scene settings and selection", "images", "material slots", "materials")):
require(before[part] == after[part], f"{label}: a failed run left the {name} changed")
class Reports:
"""Stands in for the operator instance: the real execute runs against it and its reports are kept."""
def __init__(self, replace):
self.replace, self.sent = replace, []
def report(self, kinds, text):
self.sent.append((kinds, text))
def refusal(label, expected, snapshot, offenders=None):
before = snapshot()
result, message = run(bpy.ops.aetheria.bake_from_source)
@ -596,8 +609,11 @@ def pass_five(aetheria_ships):
require(wing.data.materials[0] == source_material and fin.data.materials[0] == source_material,
"Shared material: a failed run left a copy on the mesh")
source_kept("Shared material, failed run")
result, message = run(bpy.ops.aetheria.bake_from_source, replace=True)
require(result == {"FINISHED"}, f"Shared material: the bake was refused: {message}")
operator = Reports(replace=True)
result = aetheria_ships.AETHERIA_OT_bake_from_source.execute(operator, bpy.context)
require(result == {"FINISHED"}, f"Shared material: the bake was refused: {operator.sent}")
require(len(operator.sent) == 1 and operator.sent[0][0] == {"INFO"} and operator.sent[0][1].endswith("copied for the render meshes: 1"),
f"Shared material: the report does not name the one material copied ({operator.sent})")
own = wing.data.materials[0]
require(own != source_material and fin.data.materials[0] == own, "Shared material: the meshes did not take one material of their own")
source_kept("Shared material")
@ -652,6 +668,8 @@ def pass_five(aetheria_ships):
select([first])
refusal("Free image holds the name", "held by images this bake does not replace", image_state)
bpy.data.images.remove(free)
for kind in ("albedo", "normal"): # images nothing uses, no fake user: the bake takes the names
require(bpy.data.images.new(f"{SHIP_ID}.{kind}", 4, 4).users == 0, "Names: an orphan has users")
result, message = run(bpy.ops.aetheria.bake_from_source)
require(result == {"FINISHED"}, f"Names: the first bake was refused: {message}")
one_pair("Names, first bake")
@ -663,8 +681,46 @@ def pass_five(aetheria_ships):
require(result == {"FINISHED"}, f"Names: the shared bake was refused: {message}")
one_pair("Names, shared bake")
check_images("Names", [first.data.materials[0].name, second.data.materials[0].name])
gone = {first.data.materials[0].name, second.data.materials[0].name} # she deletes the meshes and their materials
for obj in (first, second):
bpy.data.objects.remove(obj, do_unlink=True)
for name in gone:
bpy.data.materials.remove(bpy.data.materials[name])
require(all(bpy.data.images[name].users == 0 for name in pair_names), "Names: the old pair is still used")
again = new_render("Wing")
select([again])
result, message = run(bpy.ops.aetheria.bake_from_source)
require(result == {"FINISHED"}, f"Names: the re-bake was refused: {message}")
one_pair("Names, re-bake")
check_images("Names, re-bake", [again.data.materials[0].name])
print("PASS 5 pair names ok")
# A target that shares Source's mesh data is refused: the slot belongs to the data, so Source's own would be repointed.
purge()
linked = new_render("Wing")
linked.data = source.data
select([linked])
refusal("Linked mesh data", "share their mesh data with a Source mesh", lambda: (owned(), image_state()), [linked])
source_kept("Linked mesh data")
print("PASS 5 linked mesh data ok")
# Whatever Blender raises, wherever in the operator, the report is fixed text and the run is undone (a failure after the
# commit has nothing to undo).
purge()
target = new_render("Wing")
material = with_material(target, "Own")
select([target])
for site, error, rolled_back in (("_refuse_taken_names", RuntimeError, True), ("_bake_inputs", RuntimeError, True),
("bake", ValueError, True), ("_settle_images", RuntimeError, False)):
failing_pass(aetheria_ships, f"Text at {site}", [target], [material], sources, False, site, 1, error, rolled_back)
purge_pair = [i for i in bpy.data.images if i.name.startswith(SHIP_ID)]
for image in purge_pair:
bpy.data.images.remove(image)
for wired in [n for n in material.node_tree.nodes if n.type in ("TEX_IMAGE", "NORMAL_MAP")]:
material.node_tree.nodes.remove(wired)
select([target])
print("PASS 5 error text ok")
# The relief bound rejects a copy of Source as the target and accepts a real hull.
purge()
flat = new_render("Fin", ratio=1.0)