pipeline.py 8.5 KB

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