pipeline.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 background_remover
  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. remove_bg_enabled = bool(creds.get("remove_bg", False))
  31. total_steps = len(manifest.get("characters", [])) + len(manifest.get("ui_art", [])) + len(manifest.get("vfx", [])) + (1 if manifest.get("ui", []) else 0)
  32. done_steps = 0
  33. def progress(label):
  34. nonlocal done_steps
  35. done_steps += 1
  36. log(f"进度 {done_steps}/{max(1, total_steps)} · {label}")
  37. def transparent_prompt(extra):
  38. return ", ".join([
  39. extra,
  40. "no shadow",
  41. "no background",
  42. "transparent background",
  43. "isolated subject",
  44. "clean PNG asset",
  45. "输出 PNG,背景必须是真实 Alpha 透明通道,不是白底,不是棋盘格。主体居中,边缘干净,适合用于 App、网页和海报叠加",
  46. ])
  47. # ---- A. 角色(Spine)----
  48. for i, c in enumerate(manifest.get("characters", [])):
  49. cid = c.get("id", f"char_{i}")
  50. anims = c.get("animations", ["idle"])
  51. if not creds.get("api_key"):
  52. log(f"⚠️ 未填 key,跳过角色 {cid}")
  53. continue
  54. try:
  55. if c.get("type") == "spine_parts":
  56. part_images = {}
  57. parts = c.get("parts") or []
  58. for part in parts:
  59. part_id = part["id"]
  60. part_prompt = ", ".join(x for x in [
  61. c.get("prompt", ""),
  62. part.get("prompt", ""),
  63. style,
  64. transparent_prompt("single separated rigging part only, centered, no text, no other body parts")
  65. ] if x)
  66. log(f"🎨 [{cid}/{part_id}] 生成 Boss 拆件…")
  67. pimg = providers.generate(creds["provider"], part_prompt, creds["api_key"],
  68. creds.get("base_url", "https://api.openai.com/v1"),
  69. creds.get("model", "gpt-image-2"),
  70. part.get("size", c.get("size", creds.get("size", "1024x1024"))))
  71. pimg = background_remover.remove_background(pimg, log=log, label=f"{cid}/{part_id}",
  72. enabled=remove_bg_enabled,
  73. image_url=pimg.info.get("source_url"))
  74. part_images[part_id] = pimg
  75. spine_builder.build_parts_character(cid, part_images, chars_out, anims, parts)
  76. w, h = 1000, 1000
  77. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  78. else:
  79. full_prompt = ", ".join(x for x in [
  80. c.get("prompt", ""), style,
  81. transparent_prompt("single game icon character, centered, full body in frame, no text"),
  82. ] if x)
  83. log(f"🎨 [{cid}] 生成角色图…")
  84. img = providers.generate(creds["provider"], full_prompt, creds["api_key"],
  85. creds.get("base_url", "https://api.openai.com/v1"),
  86. creds.get("model", "gpt-image-2"),
  87. c.get("size", creds.get("size", "1024x1024")))
  88. img = background_remover.remove_background(img, log=log, label=cid, enabled=remove_bg_enabled,
  89. image_url=img.info.get("source_url"))
  90. spine_builder.build_character(cid, img, chars_out, anims)
  91. w, h = spine_builder.trim_to_content(img).size
  92. files = [f"characters/{cid}.json", f"characters/{cid}.atlas", f"characters/{cid}.png"]
  93. library["characters"].append({
  94. "id": cid,
  95. "png": f"characters/{cid}.png",
  96. "w": w, "h": h,
  97. "type": c.get("type", "spine"),
  98. "role": c.get("role", ""),
  99. "animations": spine_builder.anim_data(anims),
  100. "files": files,
  101. })
  102. log(f"✅ [{cid}] 完成 ({anims})")
  103. progress(f"{cid}")
  104. except Exception as e:
  105. log(f"❌ [{cid}] 失败: {e}")
  106. progress(f"{cid}")
  107. # ---- A2. UI 美术(背景 / Logo / 卷轴框 / 按钮 等整图)----
  108. ui_art_out = os.path.join(base_out, "ui_art")
  109. for a in manifest.get("ui_art", []):
  110. aid = a.get("id", "art")
  111. if not creds.get("api_key"):
  112. log(f"⚠️ 未填 key,跳过 UI 美术 {aid}")
  113. continue
  114. try:
  115. transparent = a.get("transparent", True)
  116. extra = (transparent_prompt("single clean UI element, no text")
  117. if transparent
  118. else "full-bleed illustration, no text, no UI elements")
  119. full_prompt = ", ".join(x for x in [a.get("prompt", ""), style if a.get("use_style") else "", extra] if x)
  120. log(f"🖼 [{aid}] 生成 UI 美术…")
  121. img = providers.generate(creds["provider"], full_prompt, creds["api_key"],
  122. creds.get("base_url", "https://api.openai.com/v1"),
  123. creds.get("model", "gpt-image-2"),
  124. a.get("size", creds.get("size", "1024x1024")))
  125. img = background_remover.remove_background(img, log=log, label=aid, enabled=remove_bg_enabled and transparent,
  126. image_url=img.info.get("source_url"))
  127. os.makedirs(ui_art_out, exist_ok=True)
  128. img.save(os.path.join(ui_art_out, f"{aid}.png"))
  129. library["ui_art"].append({"id": aid, "file": f"ui_art/{aid}.png",
  130. "w": img.width, "h": img.height,
  131. "transparent": transparent})
  132. log(f"✅ [{aid}] UI 美术完成")
  133. progress(f"{aid}")
  134. except Exception as e:
  135. log(f"❌ [{aid}] UI 美术失败: {e}")
  136. progress(f"{aid}")
  137. # ---- B. 粒子 VFX ----
  138. for v in manifest.get("vfx", []):
  139. vid = v.get("id", "vfx")
  140. try:
  141. path = particle_builder.build_particle(
  142. vid, v.get("template", "burst"), v.get("color", [255, 255, 255]), vfx_out)
  143. cfg = json.load(open(path, encoding="utf-8"))
  144. library["vfx"].append({"id": vid, "template": v.get("template"),
  145. "file": f"vfx/{vid}.particle.json", "config": cfg})
  146. log(f"✨ [{vid}] 粒子配置完成")
  147. progress(f"{vid}")
  148. except Exception as e:
  149. log(f"❌ [{vid}] 粒子失败: {e}")
  150. progress(f"{vid}")
  151. # ---- C. UI Tween ----
  152. ui = manifest.get("ui", [])
  153. if ui:
  154. used = [u.get("preset") for u in ui if u.get("preset")]
  155. try:
  156. tween_builder.build_tweens(used, ui_out)
  157. for u in ui:
  158. library["ui"].append({"id": u.get("id"), "preset": u.get("preset"),
  159. "params": u.get("params", {})})
  160. log(f"🎛 TweenPresets.ts 完成 ({used})")
  161. progress("TweenPresets")
  162. except Exception as e:
  163. log(f"❌ Tween 失败: {e}")
  164. progress("TweenPresets")
  165. os.makedirs(base_out, exist_ok=True)
  166. with open(os.path.join(base_out, "library.json"), "w", encoding="utf-8") as f:
  167. json.dump(library, f, ensure_ascii=False, indent=2)
  168. log("—— 完成 ——")
  169. return library, base_out