pipeline.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """可被网站/命令行复用的生成管线。
  2. 读 manifest -> 生成各类资产 -> 写 library.json(供网站可视化列出与预览)。
  3. """
  4. import json
  5. import os
  6. import providers
  7. import spine_builder
  8. import particle_builder
  9. import tween_builder
  10. import baidu_segment
  11. HERE = os.path.dirname(os.path.abspath(__file__))
  12. def run(manifest, out_root, creds=None, log=print):
  13. """manifest: dict; out_root: 输出根目录; creds: {provider,api_key,base_url,model,size}
  14. 返回 (library_dict, base_out)。"""
  15. creds = creds or {}
  16. game = manifest.get("game", "game")
  17. base_out = os.path.join(out_root, game)
  18. chars_out = os.path.join(base_out, "characters")
  19. vfx_out = os.path.join(base_out, "vfx")
  20. ui_out = os.path.join(base_out, "ui")
  21. style = manifest.get("style", "")
  22. library = {
  23. "game": game,
  24. "slot_config": manifest.get("slot_config", {}),
  25. "characters": [],
  26. "vfx": [],
  27. "ui": [],
  28. "ui_art": [],
  29. }
  30. total_steps = len(manifest.get("characters", [])) + len(manifest.get("ui_art", [])) + len(manifest.get("vfx", [])) + (1 if manifest.get("ui", []) else 0)
  31. done_steps = 0
  32. def progress(label):
  33. nonlocal done_steps
  34. done_steps += 1
  35. log(f"进度 {done_steps}/{max(1, total_steps)} · {label}")
  36. def transparent_prompt(extra):
  37. return ", ".join([
  38. extra,
  39. "生成纯透明背景 PNG,真实 Alpha 通道,不要棋盘格,不要白底,不要阴影。",
  40. ])
  41. def alpha_report(img):
  42. img = img.convert("RGBA")
  43. alpha = img.getchannel("A")
  44. mn, mx = alpha.getextrema()
  45. transparent = sum(1 for v in alpha.getdata() if v == 0)
  46. ratio = transparent / max(1, img.width * img.height)
  47. return mn, mx, ratio
  48. def has_alpha(img):
  49. return alpha_report(img)[0] == 0
  50. def log_alpha(label, img, required):
  51. if not required:
  52. return
  53. mn, mx, ratio = alpha_report(img)
  54. if mn == 0:
  55. log(f"✅ [{label}] Alpha 透明通道有效:透明像素 {ratio:.1%}")
  56. else:
  57. log(f"⚠️ [{label}] 模型返回 PNG 但没有透明 Alpha:alpha={mn}-{mx},请重新生成或换支持透明输出的图像模型")
  58. def generate_checked(label, prompt, size, require_alpha):
  59. img = providers.generate(creds["provider"], prompt, creds["api_key"],
  60. creds.get("base_url", "https://api.openai.com/v1"),
  61. creds.get("model", "gpt-image-2"),
  62. size)
  63. log_alpha(label, img, require_alpha)
  64. if not require_alpha or has_alpha(img):
  65. return img
  66. log(f"🧠 [{label}] 模型没有真实 Alpha,直接改用百度智能抠图兜底…")
  67. try:
  68. fixed = baidu_segment.remove_background(img, label=label, log=log)
  69. except Exception as e:
  70. raise RuntimeError(f"模型没有返回真实 Alpha,百度智能抠图也失败:{e}")
  71. log_alpha(label, fixed, True)
  72. if has_alpha(fixed):
  73. return fixed
  74. raise RuntimeError("百度智能抠图返回结果仍没有真实 Alpha 透明通道")
  75. def boss_config():
  76. boss = manifest.get("slot_config", {}).get("boss", {})
  77. return boss if boss.get("enabled", False) else {}
  78. def required_boss_id():
  79. boss = boss_config()
  80. if not boss:
  81. return ""
  82. return boss.get("id") or "boss_demon_lord"
  83. def is_required_boss(c):
  84. boss_id = required_boss_id()
  85. return bool(boss_id and (c.get("role") == "boss" or c.get("id") == boss_id))
  86. required_failures = []
  87. # ---- A. 角色(Spine)----
  88. for i, c in enumerate(manifest.get("characters", [])):
  89. cid = c.get("id", f"char_{i}")
  90. anims = c.get("animations", ["idle"])
  91. if not creds.get("api_key"):
  92. log(f"⚠️ 未填 key,跳过角色 {cid}")
  93. continue
  94. try:
  95. if c.get("type") == "spine_parts":
  96. part_images = {}
  97. parts = c.get("parts") or []
  98. for part in parts:
  99. part_id = part["id"]
  100. part_prompt = ", ".join(x for x in [
  101. c.get("prompt", ""),
  102. part.get("prompt", ""),
  103. style,
  104. transparent_prompt("single separated rigging part only, centered, no text, no other body parts")
  105. ] if x)
  106. log(f"🎨 [{cid}/{part_id}] 生成 Boss 拆件…")
  107. pimg = generate_checked(f"{cid}/{part_id}", part_prompt,
  108. part.get("size", c.get("size", creds.get("size", "1024x1024"))),
  109. True)
  110. part_images[part_id] = pimg
  111. spine_builder.build_parts_character(cid, part_images, chars_out, anims, parts)
  112. w, h = 1000, 1000
  113. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  114. else:
  115. full_prompt = ", ".join(x for x in [
  116. c.get("prompt", ""), style,
  117. transparent_prompt("single game icon character or slot symbol, centered, full body in frame, no text, not a boss, not a demon lord, not dark armor"),
  118. ] if x)
  119. log(f"🎨 [{cid}] 生成角色图…")
  120. img = generate_checked(cid, full_prompt, c.get("size", creds.get("size", "1024x1024")), True)
  121. spine_builder.build_character(cid, img, chars_out, anims)
  122. w, h = spine_builder.trim_to_content(img).size
  123. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  124. library["characters"].append({
  125. "id": cid,
  126. "png": f"characters/{cid}.png",
  127. "w": w, "h": h,
  128. "type": c.get("type", "spine"),
  129. "role": c.get("role", ""),
  130. "animations": spine_builder.anim_data(anims),
  131. "files": files,
  132. })
  133. log(f"✅ [{cid}] 完成 ({anims})")
  134. progress(f"{cid}")
  135. except Exception as e:
  136. log(f"❌ [{cid}] 失败: {e}")
  137. if is_required_boss(c):
  138. required_failures.append(f"{cid}: {e}")
  139. progress(f"{cid}")
  140. boss_id = required_boss_id()
  141. if boss_id and not any(c.get("id") == boss_id for c in library["characters"]):
  142. detail = ";".join(required_failures) if required_failures else "生成结果中没有关主资源"
  143. raise RuntimeError(
  144. f"关主大魔王资源缺失:{boss_id}。已开启关主玩法,必须生成 boss 拆件和动作后才能继续。原因:{detail}"
  145. )
  146. # ---- A2. UI 美术(背景 / Logo / 卷轴框 / 按钮 等整图)----
  147. ui_art_out = os.path.join(base_out, "ui_art")
  148. for a in manifest.get("ui_art", []):
  149. aid = a.get("id", "art")
  150. if not creds.get("api_key"):
  151. log(f"⚠️ 未填 key,跳过 UI 美术 {aid}")
  152. continue
  153. try:
  154. transparent = a.get("transparent", True)
  155. extra = (transparent_prompt("single clean UI element, no text")
  156. if transparent
  157. else "full-bleed illustration, no text, no UI elements")
  158. full_prompt = ", ".join(x for x in [a.get("prompt", ""), style if a.get("use_style") else "", extra] if x)
  159. log(f"🖼 [{aid}] 生成 UI 美术…")
  160. img = generate_checked(aid, full_prompt, a.get("size", creds.get("size", "1024x1024")), transparent)
  161. os.makedirs(ui_art_out, exist_ok=True)
  162. img.save(os.path.join(ui_art_out, f"{aid}.png"))
  163. library["ui_art"].append({"id": aid, "file": f"ui_art/{aid}.png",
  164. "w": img.width, "h": img.height,
  165. "transparent": transparent})
  166. log(f"✅ [{aid}] UI 美术完成")
  167. progress(f"{aid}")
  168. except Exception as e:
  169. log(f"❌ [{aid}] UI 美术失败: {e}")
  170. progress(f"{aid}")
  171. # ---- B. 粒子 VFX ----
  172. for v in manifest.get("vfx", []):
  173. vid = v.get("id", "vfx")
  174. try:
  175. path = particle_builder.build_particle(
  176. vid, v.get("template", "burst"), v.get("color", [255, 255, 255]), vfx_out)
  177. cfg = json.load(open(path, encoding="utf-8"))
  178. library["vfx"].append({"id": vid, "template": v.get("template"),
  179. "file": f"vfx/{vid}.particle.json", "config": cfg})
  180. log(f"✨ [{vid}] 粒子配置完成")
  181. progress(f"{vid}")
  182. except Exception as e:
  183. log(f"❌ [{vid}] 粒子失败: {e}")
  184. progress(f"{vid}")
  185. # ---- C. UI Tween ----
  186. ui = manifest.get("ui", [])
  187. if ui:
  188. used = [u.get("preset") for u in ui if u.get("preset")]
  189. try:
  190. tween_builder.build_tweens(used, ui_out)
  191. for u in ui:
  192. library["ui"].append({"id": u.get("id"), "preset": u.get("preset"),
  193. "params": u.get("params", {})})
  194. log(f"🎛 TweenPresets.ts 完成 ({used})")
  195. progress("TweenPresets")
  196. except Exception as e:
  197. log(f"❌ Tween 失败: {e}")
  198. progress("TweenPresets")
  199. os.makedirs(base_out, exist_ok=True)
  200. with open(os.path.join(base_out, "library.json"), "w", encoding="utf-8") as f:
  201. json.dump(library, f, ensure_ascii=False, indent=2)
  202. log("—— 完成 ——")
  203. return library, base_out