Agent skills that make real-time game VFX: procedural Effekseer effects, video-model flipbooks, or both, played in Godot and Unity (Claude Code, Codex and other Agent Skills hosts).
Python
Add video-flipbook workflow and Unity (URP) pipeline (v0.3)
Kanaea9eb5c08f7e
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex b12384f..5168b47 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -4,14 +4,14 @@"name": "KanaWorks_AI"},"metadata": {- "description": "Game VFX authoring skills for Effekseer and Godot."+ "description": "Game VFX authoring skills for Effekseer, Godot and Unity."},"plugins": [{"name": "effekseer-vfx","source": "./",- "description": "Author real-time game VFX as code for Effekseer and verify them in real Godot renders.",- "version": "0.2.0"+ "description": "Author real-time game VFX as code for Effekseer and verify them in real Godot renders; video-model flipbooks and a Unity (URP) pipeline.",+ "version": "0.3.0"}]}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5e14de7..626d55e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "effekseer-vfx",- "version": "0.2.0",- "description": "Author real-time game VFX as code for Effekseer and verify them in real Godot renders: briefs, textures, recipes, EffekseerCore build, filmstrip review and independent scoring.",+ "version": "0.3.0",+ "description": "Author real-time game VFX as code for Effekseer and verify them in real Godot renders, or turn image-to-video clips into flipbook skills for Godot and Unity (URP): briefs, textures, recipes, EffekseerCore build, filmstrip review and independent scoring.","author": {"name": "KanaWorks_AI","url": "https://x.com/KanaWorks_AI"diff --git a/README.es.md b/README.es.mdnew file mode 100644index 0000000..095d990--- /dev/null+++ b/README.es.md@@ -0,0 +1,268 @@+# effekseer-vfx-skill++<div align="center">++<img src="docs/assets/banner-es.jpg" alt="VFX Skill: tu agente de código crea VFX de juego en tiempo real para Effekseer, Godot y Unity" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>Un proyecto de KanaWorks_AI</b></a></p>++[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Português (Brasil)](README.pt-BR.md) | Español++</div>++> Este documento es una traducción del README en inglés. Los agentes cargan los archivos en inglés de `skills/`; si hay diferencias, prevalece la versión en inglés.++Habilidades de agente (agent skills) que permiten a un agente de programación (Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode y otros+hosts compatibles con [Agent Skills](https://agentskills.io)) crear VFX de juego en tiempo real con código, iterando como lo haría un artista de VFX:++**brief de diseño → texturas → receta en Python → compilación con EffekseerCore → filmstrip real en Godot → mirar → corregir una sola cosa → repetir → revisión independiente**++- **`effekseer-vfx`** — la habilidad de creación: reglas de oficio, convenciones verificadas de los motores Effekseer/Godot, unas 30+ primitivas de capa combinables, un linter estático, el compilador oficial de EffekseerCore con verificación por relectura save/open, un Godot Lab que+ escenifica cada efecto como un intercambio entre dos maniquíes, captura de filmstrips con marcas de píxeles, historial de iteraciones y+ evidencias a prueba de manipulación que vinculan cada revisión con la compilación exacta que vio.+- **`vfx-review`** — la habilidad de revisión: un agente distinto puntúa el filmstrip según una rúbrica fija sin ver la+ receta, porque el autor nunca califica su propio trabajo.+- **Ejemplos** — dieciséis efectos terminados con sus briefs y texturas: cuatro parejas a distancia (fuego, hielo, veneno, oscuridad:+ proyectil + impacto), uno de cada tipo de golpe, tajo, carga, escudo y curación, y un set kaiju (una carga que asciende por las+ placas dorsales, un rayo atómico que se puede barrer, una explosión fotográfica), además de tres casos diagnosticados con su antes y después.+- **Efectos grandes y realistas** — `scale='kaiju'` compila una receta a escala de personaje 40 veces más grande y 2,5 veces más lenta+ (tamaños, velocidades, gravedad, presupuestos y la cámara de revisión se ajustan en consecuencia); `beam()` crea un rayo sostenido cuyo punto final el+ juego mueve en cada fotograma (`Vfx.beam()` → `aim()` → `release()`); `charge_chain()` enciende arcos a lo largo de una cadena de+ puntos; flipbooks fotográficos de fuego, hollín y humo; partículas suaves verificadas en Forward+.+- **Combos, blockout y formas estilizadas** — un brief de secuencia vincula varios efectos a los tiempos de una+ animación de personaje y organiza el trabajo en blockout → detalle → pulido (una revisión independiente del blockout debe aprobarse antes de cualquier+ trabajo de texturas); las capturas pueden venir del propio juego; las referencias incluyen listas de qué tomar de ellas, que el revisor comprueba; `vfx+ paintover` convierte un fotograma capturado en un prompt de edición de imagen para obtener un objetivo conceptual. Primitivas estilizadas de bordes duros+ (`spiral_ribbons`, `spike_crown`, `speed_streaks`, `stylized_pair`, `sparkle`), plantillas de máscaras en escala de grises y+ feedback de pantalla (`screen=`: sacudida, impact frame, hit-stop) que el Lab reproduce y que `Vfx.screen_cue` entrega al juego.++## Tres formas de crear un efecto (novedad de la 0.3)++Se elige por efecto; nada obliga a usar una sola forma.++| Forma | Cómo | Se reproduce en |+|---|---|---|+| **Procedural** | primitivas en capas en una receta de Python, texturas pintadas, compilación con EffekseerCore, revisión en Godot (todo lo descrito arriba) | Effekseer → Godot |+| **Flipbook de vídeo** | un modelo de imagen a vídeo (verificado con Seedance 2.5; sirve cualquier modelo que admita primer y último fotograma) pinta el movimiento sobre fondo negro; `vfx video-flipbook` hace el keying, recorta, enmascara y empaqueta el clip, y `vfx video-grade` da a todas las hojas de un elemento el mismo aspecto cel-shaded | Unity (URP), o Effekseer → Godot |+| **Combinada** | la hoja es la capa principal de una receta (`video_body(...)`); las primitivas añaden el destello de contacto, chispas, anillos, grietas, decals y distorsión por calor | Effekseer → Godot, Unity |++**Lo que antes no era posible y ahora sí:**++- **Cambios de forma continuos.** Una columna de agua que sale disparada hacia arriba, eleva al objetivo por los aires y se desploma como lluvia;+ una bola de fuego que estalla y se revuelve hasta convertirse en humo gris; un orbe cuyas llamas se agitan en un bucle sin costuras. Las primitivas escalan,+ desvanecen, desplazan y erosionan una imagen; no pueden convertir fuego en humo dentro de una misma silueta. Un modelo de vídeo dibuja todos+ los fotogramas intermedios.+- **Un aspecto de anime pintado a mano en movimiento**, coherente en todo un set de elementos: una rampa de valores por elemento ajusta+ todas las hojas a los mismos escalones planos (borde oscuro, cuerpo, luz, núcleo incandescente).+- **Unity.** Antes la habilidad llegaba solo hasta Godot. `vfx unity-install <UnityProject>` añade un paquete de runtime para URP+ (habilidades `ElementProfile` basadas en datos con lanzamiento como proyectil, rayo instantáneo o erupción desde el suelo, partículas en capas,+ hit-stop, sacudida de cámara, elevación del objetivo) y sus texturas procedurales; `vfx unity-export` copia una hoja con su cuadrícula; tres+ opciones de menú (o un único comando en modo batch que un agente puede ejecutar) convierten las hojas en una habilidad jugable y una escena de demostración.+- **Reproducible a partir de una frase.** El prompt de cada clip y los parámetros de cada hoja quedan registrados en+ `vfx/video_prompts.json`, de modo que un agente puede reconstruir o variar una hoja con exactitud. Pide: *"Crea una habilidad de columna de agua a partir de un+ flipbook de vídeo y configúrala en mi proyecto de Unity."*++Guía: [`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md). La habilidad solo distribuye la+técnica: los clips, hojas y personajes que generes se quedan en tu propio proyecto.++## Requisitos++| Modo | Qué puedes hacer | Requiere |+|---|---|---|+| authoring | escribir briefs y recetas, pasar el linter, procesar y medir texturas | Python 3.11+ o [uv](https://docs.astral.sh/uv/) en macOS, Linux o Windows (el Python 3.9 que trae macOS es demasiado antiguo) |+| build | compilar `.efkefc` / `.efk` con el EffekseerCore oficial | **macOS en Apple silicon** o **Windows x64**, conexión de red para la primera instalación (~250 MB en `~/.cache/effekseer-vfx`) |+| render | revisión de filmstrips en Godot, Lab, vista previa, empaquetado | lo anterior + [Godot 4](https://godotengine.org) (Forward+) en el `PATH` o en `GODOT`; `ffmpeg` para clips de referencia y grabaciones |+| flipbooks de vídeo | comandos `video-*` | modo authoring + `ffmpeg`; clips de cualquier modelo de imagen a vídeo |+| Unity | reproducir hojas como habilidades de elemento | Unity 6 (6000.0+) con URP 17; verificado en 6000.5 |++Build y render están verificados en macOS ARM64 (Effekseer Core 1.80.7, EffekseerForGodot4 1.80.5.1, Godot 4.7, .NET 9)+y en Windows 11 x64 (las mismas versiones, Godot 4.7.2). En Windows ARM64 la instalación obtiene el runtime de .NET correspondiente, pero+no está verificado. Linux ejecuta el modo authoring; su ruta de build no está verificada.++En Windows, todos los comandos `sh <skill>/scripts/...` de abajo también funcionan desde Git Bash (el que usa Claude Code); desde cmd o+PowerShell, usa `<skill>\scripts\vfx.cmd` en lugar de `vfx` y+`powershell -NoProfile -ExecutionPolicy Bypass -File <skill>\scripts\setup.ps1` en lugar de `setup.sh`.++## Instalación++La forma más sencilla: dale la URL de este repositorio a tu agente de programación y pídele que instale la habilidad. Los pasos que+sigue están en [Para agentes: instalar desde esta URL](#para-agentes-instalar-desde-esta-url). O instálala tú mismo:++**Claude Code** (escribe esto en Claude Code)++```text+/plugin marketplace add kanaworksai-hue/effekseer-vfx-skill+/plugin install effekseer-vfx@effekseer-vfx+```++**Codex** (pídelo en un chat de Codex; las habilidades se instalan en `~/.codex/skills`, o en `$CODEX_HOME/skills`, y se+usan a partir del siguiente turno o de una nueva sesión)++```text+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/effekseer-vfx+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/vfx-review+```++**Otros agentes** (Cursor, Gemini CLI, Copilot, OpenCode, ...)++```sh+npx skills add kanaworksai-hue/effekseer-vfx-skill+```++O copia `skills/effekseer-vfx` y `skills/vfx-review` en la carpeta de habilidades de tu agente (`~/.claude/skills/`,+`.agents/skills/`, ...). Cada carpeta de habilidad+incluye su propio `LICENSE` (y `effekseer-vfx`, su `THIRD_PARTY_NOTICES.md`), así que una carpeta copiada los conserva.++### Para agentes: instalar desde esta URL++1. **Obtén los archivos.** Si tu host tiene un instalador de plugins o de habilidades, úsalo preferentemente (los comandos de arriba); un comando de barra+ como `/plugin` debe escribirlo el usuario, así que muéstraselo. Si no, clona el repositorio y copia las dos carpetas de+ habilidades en tu carpeta de habilidades, sin cambiarles el nombre: `git clone --depth 1 <URL de este repositorio>` y luego copia+ `skills/effekseer-vfx` y `skills/vfx-review` a `~/.claude/skills/` (Claude Code, todos los proyectos),+ `<project>/.claude/skills/` (Claude Code, un solo proyecto), `~/.codex/skills/` (Codex; `$CODEX_HOME/skills` si está definido) o+ la carpeta de habilidades de tu host (por ejemplo `.agents/skills/`).+ No copies nada más; las habilidades son autocontenidas y de solo lectura en tiempo de ejecución.+2. **Cárgalas.** Si las habilidades todavía no aparecen en tu lista de habilidades, pide al usuario que inicie una nueva sesión.+3. **Comprueba la máquina.** Desde el proyecto de juego del usuario, ejecuta `sh <skill>/scripts/vfx doctor` (`<skill>` es la+ carpeta `effekseer-vfx` instalada; en Windows fuera de Git Bash, `<skill>\scripts\vfx.cmd doctor`) y sigue sus+ pasos `next`.+4. **Pregunta antes de descargar.** `sh <skill>/scripts/setup.sh` (Windows: `setup.ps1`; el comando exacto está en el+ `next` de `doctor`) instala la cadena de herramientas en `~/.cache/effekseer-vfx`+ (unos 250 MB en macOS ARM64 y Windows x64; `--authoring-only` en el resto), y el primer `vfx init` descarga el plugin oficial+ de Effekseer para Godot (unos 34 MB). La instalación requiere Python 3.11+ o uv: si `doctor` no encuentra ninguno de los dos, pide al usuario+ que instale uno. Godot 4 nunca se instala en nombre del usuario; pídele que lo instale (o que te permita+ hacerlo) y que defina `GODOT` si no está en el `PATH`.+5. **Ejecuta Godot fuera del sandbox.** `vfx review`, `preview` y `showcase` abren una ventana de Godot en el escritorio del+ usuario. Un agente en sandbox (por ejemplo, Codex en su sandbox de espacio de trabajo) no puede abrirla: ejecuta esos comandos con+ la aprobación del usuario fuera del sandbox; si tu host no puede salir de su sandbox, dale al usuario el comando exacto para+ ejecutarlo en una terminal de su escritorio. Una revisión que no renderiza ningún fotograma se detiene tras unos 90 s con "rendered no frame"+ (lo más probable es que la ventana no se haya podido abrir; revisa la salida de Godot que incluye). `render: true` en `doctor` solo significa que+ se encontró Godot.+6. **Confirma que funciona.** Vuelve a ejecutar `vfx doctor` (`modes` debería mostrar lo que admite esta máquina) y luego sigue+ [Primeros pasos](#primeros-pasos). Informa de lo que funciona y de lo que falta; no afirmes que build o render funcionan en una+ máquina donde `doctor` indica que no.++## Primeros pasos++Pide a tu agente, dentro de tu proyecto de juego: *"Configura aquí la habilidad effekseer-vfx y enséñame el ejemplo de fuego."* Ejecutará:++```sh+sh <skill>/scripts/vfx doctor # what this machine can do, and what to install+sh <skill>/scripts/setup.sh # macOS ARM64 / Windows x64; use --authoring-only elsewhere (asks you first)+sh <skill>/scripts/vfx init # creates vfx/ with the Godot Lab, materials and math textures+sh <skill>/scripts/vfx examples add fire+sh <skill>/scripts/vfx build --ids VFX_Projectile_Fire VFX_Fire_Explosion+sh <skill>/scripts/vfx review --ids VFX_Projectile_Fire VFX_Fire_Explosion --note "baseline"+sh <skill>/scripts/vfx showcase # play the library in the Lab+```++Después pide un efecto: *"Crea un impacto de rayo para un hechizo con objetivo, corto y seco, con descarga de retorno."* La+habilidad hace que el agente escriba un brief, solicite texturas pintadas a tu herramienta de generación de imágenes (o te las pida+a ti), escriba la receta, compile, revise los filmstrips durante varias rondas y entregue el resultado a un revisor independiente+antes de informar de que `effect-verify` ha pasado. Hasta que se envíe esa revisión independiente y se vuelva a ejecutar `vfx overview`,+`effect-verify` indica `verified: false` aunque el efecto se renderice correctamente; en ese punto, un agente debería informar de que+"compila y se renderiza" en lugar de "verificado". La cadena de herramientas se encuentra en `~/.cache/effekseer-vfx`; define+`EFFEKSEER_VFX_HOME` para ubicarla en otro lugar (consulta [la referencia de comandos](skills/effekseer-vfx/references/cli.md)).++## Generación de imágenes++Las formas pintadas complejas (humo, arcos de tajo, fuego, grietas, hielo, símbolos) deben venir de un modelo de generación de imágenes; la+habilidad nunca las simula con código. Si tu agente tiene una herramienta de imágenes integrada o conectada, la usa con los prompts que+registra en `vfx/texture_prompts.json`. Si no, te indica exactamente qué imagen generar y dónde guardarla.+Las formas matemáticas (resplandores, anillos, ruido, degradados, estelas, mapas de distorsión) se generan de forma procedural.++## Usar los efectos en un juego++Los efectos se generan como exportaciones de runtime `.efk` y fuentes `.efkefc` con un `vfx_manifest.json`. El proyecto de Godot generado+incluye una pequeña API:++```gdscript+var handle = Vfx.play("VFX_Fire_Explosion", position)+var shot = Vfx.launch("VFX_Projectile_Fire", from, to)+shot.arrived.connect(func(at): Vfx.play("VFX_Fire_Explosion", at))+```++Los rayos se apuntan en cada fotograma; el punto final lo controla el juego (un raycast, un hueso del objetivo):++```gdscript+var ray = Vfx.beam("VFX_Kaiju_Atomic_Beam", mouth, target)+ray.aim(mouth, new_target) # each frame: sweep, follow the head+ray.release() # narrows and fades out, then frees itself+```++Consulta [`skills/effekseer-vfx/references/godot.md`](skills/effekseer-vfx/references/godot.md) y, para gigantes y kaijus,+[`references/scale.md`](skills/effekseer-vfx/references/scale.md).++## Estructura del repositorio++```+skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,+ setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,+ brief schema, examples, unity/ URP package)+skills/vfx-review/ SKILL.md for the independent reviewer+docs/zh/, docs/ja/ Chinese and Japanese translations of the references+.claude-plugin/ Claude Code plugin and marketplace manifests+tests/ pure-Python tests (no Core or Godot needed)+```++## Limitaciones++- Las métricas de revisión son heurísticas de píxeles sobre el viewport real, no mediciones de GPU ni de overdraw.+- El sistema de revisión controla un Godot en ventana en macOS y Windows; todavía no se admite la captura headless en Linux. En+ Windows, la ventana de Godot conserva el foco mientras captura (macOS devuelve el foco a tu aplicación).+- En Windows, las pruebas de seguridad de enlaces simbólicos requieren el Modo de desarrollador (o una shell de administrador) y se omiten sin él.+- Las puntuaciones de los ejemplos corresponden a una revisión independiente de los renders del Lab de cápsulas de la propia habilidad (dos de los dieciséis se calificaron como+ `iterate`); vuelve a compilarlos y revisarlos antes de confiar en ellas.+- Las partículas `soft` están verificadas en Forward+ (solo se desvanecen frente a la profundidad opaca); el renderizador Compatibility no tiene+ textura de profundidad y no puede usarlas.++## Desarrollo++```sh+sh skills/effekseer-vfx/scripts/setup.sh --authoring-only+~/.cache/effekseer-vfx/venv/bin/python -m pip install pytest+~/.cache/effekseer-vfx/venv/bin/python -m pytest -q tests+```++En Windows (PowerShell; quita `--authoring-only` para ejecutar también las pruebas de compilación de EffekseerCore):++```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scripts\setup.ps1 --authoring-only+~\.cache\effekseer-vfx\venv\Scripts\python.exe -m pip install pytest # a venv made by uv: uv pip install --python <that python.exe> pytest+~\.cache\effekseer-vfx\venv\Scripts\python.exe -X utf8 -m pytest -q tests+```++Las contribuciones que confirmen una nueva convención de motor deben añadirla a+`skills/effekseer-vfx/references/engine-conventions.md` junto con la forma en que se midió.++## Licencia y créditos++- **Este proyecto:** [MIT](LICENSE). Úsalo, modifícalo y distribúyelo, también con fines comerciales; conserva el aviso de copyright y la licencia en las copias del código.+- **Lo que creas con él:** los efectos, texturas, flipbooks y skills de Unity que construyes en tu proyecto son tuyos. Este repositorio no reclama nada sobre ellos.+- **Modelos de vídeo e imagen:** los clips e imágenes que generas (por ejemplo, con Seedance 2.5) se rigen por los términos de ese modelo, no por esta licencia. Revísalos antes de un uso comercial. Aquí no se distribuye nada de eso.+- **Componentes de terceros:** Effekseer, EffekseerForGodot4, .NET y el effekseer-ai incluido conservan sus propias licencias. Consulta [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).+- **Marca y ejemplos:** el nombre KanaWorks_AI, el logo y el personaje Kana son © 東京AI映像合同会社 (Tokyo AI Visuals LLC) y **no** están cubiertos por la licencia MIT. Los efectos, personajes e imágenes del banner y de los vídeos promocionales son ejemplos: no se incluyen ni se licencian. Consulta [docs/brand](docs/brand/README.md).++Effekseer, Godot y Unity son marcas de sus respectivos propietarios. Este es un proyecto independiente, sin afiliación ni respaldo de ellos.++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Hecho con ♥ por <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>++<p><sub>Si la skill te ahorra tiempo, una ⭐ mantiene las actualizaciones y ayuda a que otros la encuentren. Más proyectos: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>++</div>diff --git a/README.ja.md b/README.ja.mdindex 66960a7..7194451 100644--- a/README.ja.md+++ b/README.ja.md@@ -1,6 +1,23 @@# effekseer-vfx-skill-[English](README.md) | [简体中文](README.zh-CN.md) | 日本語+<div align="center">++<img src="docs/assets/banner-ja.jpg" alt="VFX Skill:コーディングエージェントが Effekseer・Godot・Unity 向けのリアルタイムゲームVFXを作る" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>KanaWorks_AI のプロジェクト</b></a></p>++[English](README.md) | [简体中文](README.zh-CN.md) | 日本語 | [한국어](README.ko.md) | [Português (Brasil)](README.pt-BR.md) | [Español](README.es.md)++</div>> 日本語のドキュメントは英語版の翻訳です。エージェントが実際に読み込むのは `skills/` 以下の英語ファイルで、内容が食い違う場合は英語版が正です。翻訳の一覧は [docs/ja/README.md](docs/ja/README.md) にあります。@@ -15,6 +32,25 @@- **大規模でリアルなエフェクト** — `scale='kaiju'` は、キャラクタースケールのレシピを 40 倍大きく 2.5 倍遅くビルドします(サイズ、速度、重力、予算、レビューのカメラがすべて追従します)。`beam()` は、ゲームが毎フレーム終点を動かす保持型のビームを作ります(`Vfx.beam()` → `aim()` → `release()`)。`charge_chain()` は点の連なりに沿ってアークを灯します。写真調の炎、煤、煙のフリップブック。Forward+ で検証済みのソフトパーティクル。- **コンボ、ブロックアウト、スタイライズ形状** — シーケンスブリーフで複数のエフェクトをキャラクターアニメーションの拍に結び付け、ブロックアウト → ディテール → ポリッシュの順に進めます(テクスチャ作業の前に独立したブロックアウトレビューの合格が必要)。キャプチャはゲーム本体から取り込めます。参照には「盗むもの」のリストを付け、レビュアーが確認します。`vfx paintover` はキャプチャしたフレームをコンセプト用の画像編集プロンプトにします。ハードエッジのスタイライズ用プリミティブ(`spiral_ribbons`、`spike_crown`、`speed_streaks`、`stylized_pair`、`sparkle`)、グレースケールマスクのテンプレート、画面フィードバック(`screen=`:シェイク、インパクトフレーム、ヒットストップ。Lab が再生し、`Vfx.screen_cue` でゲームに渡します)。+## エフェクトの3つの作り方(0.3 の新機能)++エフェクトごとに選べます。どれかを強制することはありません。++| 方法 | やり方 | 再生先 |+|---|---|---|+| **プロシージャル** | Python レシピでプリミティブを重ね、手描きテクスチャを使い、EffekseerCore でビルド、Godot でレビュー(上記のすべて) | Effekseer → Godot |+| **動画フリップブック** | 画像から動画を作るモデル(Seedance 2.5 で検証。最初と最後のフレームを指定できるモデルなら可)が黒背景に動きを描き、`vfx video-flipbook` がキー抜き・切り出し・マスク・シート化、`vfx video-grade` が同じ属性のシートを同じセル調の見た目に揃えます | Unity(URP)、または Effekseer → Godot |+| **組み合わせ** | シートをレシピの本体レイヤー(`video_body(...)`)にし、接触フラッシュ・火花・リング・ひび・デカール・陽炎はプリミティブで足します | Effekseer → Godot、Unity |++**以前はできず、今はできること:**++- **形が連続して変わるエフェクト。** 水柱が噴き上がって相手を持ち上げ、雨になって崩れる。火球が弾け、渦を巻きながら灰色の煙に変わる。炎が渦巻く球がつなぎ目なくループする。プリミティブは絵を拡大・フェード・スクロール・侵食できても、一つのシルエットの中で炎を煙に変えることはできません。動画モデルはその中割りをすべて描きます。+- **動く手描きアニメ調の見た目を、属性セット全体でそろえる。** 属性ごとに一本の明度ランプで、すべてのシートを同じ平坦な段階(暗い縁、本体、明部、白熱の芯)に揃えます。+- **Unity。** 以前は Godot までで止まっていました。`vfx unity-install <UnityProject>` で URP ランタイムパッケージ(データ駆動の `ElementProfile` スキル:飛翔体・即着弾・地面噴出の3種の発射方式、レイヤー粒子、ヒットストップ、画面揺れ、相手の持ち上げ)とプロシージャルテクスチャを追加し、`vfx unity-export` でシートをグリッド情報付きでコピー。3つのメニュー(またはエージェントが実行できるバッチコマンド1つ)でシートが遊べるスキルとデモシーンになります。+- **一文から再現できる。** クリップのプロンプトとシートのパラメータはすべて `vfx/video_prompts.json` に記録されるので、エージェントは正確に作り直したり変化させたりできます。例:*「動画フリップブックで水柱スキルを作って、私の Unity プロジェクトに組み込んで」*++ガイド:[`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md)。スキルが配布するのは技術だけです。あなたが生成したクリップ・シート・キャラクターはあなたのプロジェクトに残ります。+## 動作要件| モード | できること | 必要なもの |@@ -22,6 +58,8 @@| authoring | ブリーフとレシピの作成、lint、テクスチャの処理と計測 | macOS、Linux または Windows 上の Python 3.11+ または [uv](https://docs.astral.sh/uv/)(macOS 標準の Python 3.9 は古すぎます) || build | 公式 EffekseerCore による `.efkefc` / `.efk` のコンパイル | **Apple silicon の macOS** または **Windows x64**、初回セットアップ時のネットワーク接続(`~/.cache/effekseer-vfx` に約 250 MB) || render | Godot のフィルムストリップレビュー、Lab、プレビュー、パッケージング | 上記 + `PATH` 上または `GODOT` で指定した [Godot 4](https://godotengine.org)(Forward+)。リファレンスクリップと録画には `ffmpeg` |+| 動画フリップブック | `video-*` コマンド | authoring モード + `ffmpeg`。クリップは任意の画像→動画モデルから |+| Unity | シートを属性スキルとして再生 | URP 17 の Unity 6(6000.0 以降)。6000.5 で検証 |build と render は macOS ARM64(Effekseer Core 1.80.7、EffekseerForGodot4 1.80.5.1、Godot 4.7、.NET 9)と Windows 11 x64(同じバージョン、Godot 4.7.2)で検証済みです。Windows ARM64 ではセットアップが対応する .NET ランタイムを入れますが、検証はされていません。Linux では authoring モードで動作し、build の経路は検証されていません。@@ -131,7 +169,7 @@ ray.release() # narrows and fades out, then frees itself```skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,- brief schema, examples)+ brief schema, examples, unity/ URP package)skills/vfx-review/ SKILL.md for the independent reviewerdocs/zh/, docs/ja/ Chinese and Japanese translations of the references.claude-plugin/ Claude Code plugin and marketplace manifests@@ -140,7 +178,7 @@ tests/ pure-Python tests (no Core or Godot needed)| パス | 内容 ||---|---|-| `skills/effekseer-vfx/` | SKILL.md、references/(クラフト、エンジン規約、レビューなど)、scripts/(vfx CLI と vfx.cmd、setup.sh と setup.ps1、vfxkit、同梱の effekseer_ai)、assets/(Godot Lab、マテリアル、評価基準、ブリーフスキーマ、サンプル) |+| `skills/effekseer-vfx/` | SKILL.md、references/(クラフト、エンジン規約、レビューなど)、scripts/(vfx CLI と vfx.cmd、setup.sh と setup.ps1、vfxkit、同梱の effekseer_ai)、assets/(Godot Lab、マテリアル、評価基準、ブリーフスキーマ、サンプル、unity/ URP パッケージ) || `skills/vfx-review/` | 独立レビュアー用の SKILL.md || `docs/zh/`、`docs/ja/` | リファレンスの中国語訳と日本語訳 || `.claude-plugin/` | Claude Code のプラグインとマーケットプレイスのマニフェスト |@@ -174,9 +212,24 @@ powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scripts新しいエンジン規約を確認したコントリビューションでは、それを計測方法と一緒に`skills/effekseer-vfx/references/engine-conventions.md` に追記してください。-## ライセンス+## ライセンスとクレジット++- **このプロジェクト:** [MIT](LICENSE)。著作権表示とライセンス文をコードのコピーに残せば、商用を含めて自由に使用・改変・配布できます。+- **作ったもの:** あなたのプロジェクトで作ったエフェクト、テクスチャ、フリップブック、Unity スキルはあなたのものです。本リポジトリは権利を主張しません。+- **動画・画像モデル:** 生成したクリップや画像(例:Seedance 2.5)には、そのモデルの利用規約が適用され、本ライセンスは及びません。商用利用の前に確認してください。本リポジトリでは配布していません。+- **サードパーティ:** Effekseer、EffekseerForGodot4、.NET、同梱の effekseer-ai はそれぞれのライセンスに従います。[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) を参照してください。+- **ブランドと作例:** KanaWorks_AI の名称、ロゴ、Kana のキャラクターの権利は東京AI映像合同会社に帰属し、MIT ライセンスの対象**外**です。バナーや紹介動画のエフェクト・キャラクター・映像は作例であり、配布物に含まれず、ライセンスの対象外です。[docs/brand](docs/brand/README.md) を参照してください。++Effekseer、Godot、Unity はそれぞれの所有者の商標です。本プロジェクトは独立したもので、それらと提携・承認関係にはありません。++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Made with ♥ by <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>-MIT。[LICENSE](LICENSE) を参照してください。サードパーティのコンポーネントとダウンロード:[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。-Effekseer および Godot はそれぞれの所有者の商標です。本プロジェクトはそれらと提携していません。+<p><sub>役に立ったら ⭐ をお願いします。更新の励みになり、他の人にも見つけてもらえます。ほかのプロジェクト: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>-作者:KanaWorks_AI(X:[@KanaWorks_AI](https://x.com/KanaWorks_AI))。+</div>diff --git a/README.ko.md b/README.ko.mdnew file mode 100644index 0000000..5322c32--- /dev/null+++ b/README.ko.md@@ -0,0 +1,267 @@+# effekseer-vfx-skill++<div align="center">++<img src="docs/assets/banner-ko.jpg" alt="VFX Skill: 코딩 에이전트가 Effekseer, Godot, Unity용 실시간 게임 VFX를 만듭니다" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>KanaWorks_AI 프로젝트</b></a></p>++[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | 한국어 | [Português (Brasil)](README.pt-BR.md) | [Español](README.es.md)++</div>++> 이 문서는 영어 README의 번역본입니다. 에이전트가 실제로 불러오는 것은 `skills/` 아래의 영어 파일이며, 내용이 서로 다를 경우 영어판이 우선합니다.++코딩 에이전트(Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode 및 기타+[Agent Skills](https://agentskills.io) 호스트)가 VFX 아티스트가 반복 작업하는 방식 그대로, 실시간 게임 VFX를 코드로 만들 수 있게 해 주는 에이전트 스킬입니다.++**디자인 브리프 → 텍스처 → Python 레시피 → EffekseerCore 빌드 → 실제 Godot 필름스트립 → 확인 → 한 가지만 수정 → 반복 → 독립 리뷰**++- **`effekseer-vfx`** — 제작 스킬. 크래프트 규칙, 실측으로 검증한 Effekseer/Godot 엔진 규약, 조합해서 쓰는 약 30개의+ 레이어 프리미티브, 정적 린터, save/open 리드백 검증이 포함된 공식 EffekseerCore 컴파일러, 모든 이펙트를 두 더미 사이의+ 주고받기로 연출하는 Godot Lab, 픽셀 플래그가 붙는 필름스트립 캡처, 반복 이력, 그리고 리뷰를 그 리뷰가 실제로 본 빌드와+ 정확히 묶어 주는 변조 감지 가능한 증거 기록을 갖추고 있습니다.+- **`vfx-review`** — 리뷰어 스킬. 작성자는 자기 작업을 채점하지 않으므로, 별도의 에이전트가 레시피를 보지 않은 채 고정된+ 평가 기준으로 스트립을 채점합니다.+- **예제** — 브리프와 텍스처가 포함된 완성 이펙트 16종: 원거리 페어 4쌍(화염, 얼음, 독, 암흑: 투사체 + 착탄),+ 히트·베기·차지·실드·힐 각 1종, 그리고 괴수 세트(등지느러미 골판을 타고 올라가는 차지, 휩쓸 수 있는 원자 빔,+ 실사풍 폭발). 여기에 진단 전후 비교 사례 3건이 더해집니다.+- **대형·실사풍 이펙트** — `scale='kaiju'`는 캐릭터 스케일 레시피를 40배 크고 2.5배 느리게 빌드합니다+ (크기, 속도, 중력, 예산, 리뷰 카메라가 모두 따라 바뀝니다). `beam()`은 게임이 매 프레임 끝점을 움직이는+ 유지형 빔을 만듭니다(`Vfx.beam()` → `aim()` → `release()`). `charge_chain()`은 점들의 연결을 따라 아크를+ 점등합니다. 실사풍 화염·그을음·연기 플립북, Forward+에서 검증된 소프트 파티클도 포함됩니다.+- **콤보, 블록아웃, 스타일라이즈드 형태** — 시퀀스 브리프는 여러 이펙트를 캐릭터 애니메이션의 박자에 묶고,+ 블록아웃 → 디테일 → 폴리시 순서로 작업을 관문화합니다(텍스처 작업 전에 독립 블록아웃 리뷰를 통과해야 합니다).+ 캡처는 게임 자체에서 가져올 수 있고, 레퍼런스에는 리뷰어가 확인하는 '가져올 것' 목록이 붙으며, `vfx+ paintover`는 캡처한 프레임을 콘셉트 목표용 이미지 편집 프롬프트로 바꿉니다. 하드 엣지 스타일라이즈드 프리미티브+ (`spiral_ribbons`, `spike_crown`, `speed_streaks`, `stylized_pair`, `sparkle`), 그레이스케일 마스크 템플릿, 그리고+ 화면 피드백(`screen=`: 셰이크, 임팩트 프레임, 히트스톱)을 제공하며, 화면 피드백은 Lab이 재생하고 `Vfx.screen_cue`가 게임에 전달합니다.++## 이펙트를 만드는 세 가지 방법 (0.3 신기능)++이펙트마다 고를 수 있으며, 어느 한 방법을 강제하지 않습니다.++| 방법 | 방식 | 재생 환경 |+|---|---|---|+| **프로시저럴** | Python 레시피에서 프리미티브를 레이어로 쌓고, 페인팅한 텍스처를 쓰고, EffekseerCore로 빌드하고, Godot에서 리뷰(위에서 설명한 전부) | Effekseer → Godot |+| **비디오 플립북** | 이미지-투-비디오 모델(Seedance 2.5로 검증, 첫 프레임과 마지막 프레임을 지정할 수 있는 모델이면 무엇이든 가능)이 검은 배경 위에 움직임을 그리고, `vfx video-flipbook`이 키잉·크롭·마스킹·시트 패킹을 하며, `vfx video-grade`가 한 속성의 모든 시트에 같은 셀 셰이딩 룩을 입힙니다 | Unity (URP), 또는 Effekseer → Godot |+| **조합** | 시트를 레시피의 본체 레이어(`video_body(...)`)로 쓰고, 접촉 플래시·스파크·링·균열·데칼·열 아지랑이는 프리미티브로 더합니다 | Effekseer → Godot, Unity |++**예전에는 불가능했지만 이제 가능한 것:**++- **연속적인 형태 변화.** 솟구친 물기둥이 대상을 공중으로 띄웠다가 비가 되어 무너져 내리고,+ 화염구가 터지며 회색 연기로 끓어오르고, 불꽃이 휘몰아치는 구체가 이음매 없이 루프합니다. 프리미티브는 그림을 스케일·페이드·스크롤·침식할 수는 있어도+ 하나의 실루엣 안에서 불을 연기로 바꿀 수는 없습니다. 비디오 모델은 그 사이의 모든 중간 프레임을 그려 줍니다.+- **움직이는 손그림 애니메이션 룩을 속성 세트 전체에 일관되게.** 속성마다 하나의 명도 램프로+ 모든 시트를 같은 평면 단계(어두운 테두리, 본체, 밝은 부분, 뜨거운 코어)로 그레이딩합니다.+- **Unity.** 이전에는 Godot까지만 지원했습니다. `vfx unity-install <UnityProject>`는 URP 런타임 패키지+ (투사체·즉발 볼트·지면 분출 방식의 발동을 지원하는 데이터 기반 `ElementProfile` 스킬, 레이어드 파티클,+ 히트스톱, 셰이크, 대상 띄우기)와 그 프로시저럴 텍스처를 추가합니다. `vfx unity-export`는 시트를 그리드 정보와 함께 복사하고,+ 메뉴 항목 3개(또는 에이전트가 실행할 수 있는 배치 모드 명령 1개)로 시트를 플레이 가능한 스킬과 데모 씬으로 만듭니다.+- **한 문장으로 재현 가능.** 모든 클립의 프롬프트와 모든 시트의 파라미터가+ `vfx/video_prompts.json`에 기록되므로, 에이전트가 시트를 정확히 다시 만들거나 변형할 수 있습니다. 이렇게 요청해 보세요: *"비디오 플립북으로+ 물기둥 스킬을 만들어서 내 Unity 프로젝트에 세팅해 줘."*++가이드: [`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md). 이 스킬이 배포하는 것은+기법뿐이며, 여러분이 생성한 클립·시트·캐릭터는 여러분의 프로젝트에 남습니다.++## 요구 사항++| 모드 | 할 수 있는 일 | 필요한 것 |+|---|---|---|+| authoring | 브리프와 레시피 작성, 린트, 텍스처 처리 및 측정 | macOS, Linux 또는 Windows의 Python 3.11+ 또는 [uv](https://docs.astral.sh/uv/) (macOS 기본 Python 3.9는 너무 오래됨) |+| build | 공식 EffekseerCore로 `.efkefc` / `.efk` 컴파일 | **Apple silicon macOS** 또는 **Windows x64**, 최초 설치 시 네트워크 연결(`~/.cache/effekseer-vfx`에 약 250 MB) |+| render | Godot 필름스트립 리뷰, Lab, 프리뷰, 패키징 | 위의 항목 + `PATH`에 있거나 `GODOT`로 지정한 [Godot 4](https://godotengine.org) (Forward+), 레퍼런스 클립과 녹화에는 `ffmpeg` |+| 비디오 플립북 | `video-*` 명령 | authoring 모드 + `ffmpeg`, 클립은 어떤 이미지-투-비디오 모델에서 만들어도 됨 |+| Unity | 시트를 속성 스킬로 재생 | URP 17이 포함된 Unity 6 (6000.0+), 6000.5에서 검증됨 |++build와 render는 macOS ARM64(Effekseer Core 1.80.7, EffekseerForGodot4 1.80.5.1, Godot 4.7, .NET 9)와+Windows 11 x64(같은 버전, Godot 4.7.2)에서 검증되었습니다. Windows ARM64는 설치 과정에서 맞는 .NET 런타임을 받지만+검증되지는 않았습니다. Linux는 authoring 모드로 동작하며, build 경로는 검증되지 않았습니다.++Windows에서는 아래의 모든 `sh <skill>/scripts/...` 명령이 Git Bash(Claude Code가 사용하는 셸)에서도 동작합니다. cmd나+PowerShell에서는 `vfx` 대신 `<skill>\scripts\vfx.cmd`를, `setup.sh` 대신+`powershell -NoProfile -ExecutionPolicy Bypass -File <skill>\scripts\setup.ps1`을 사용하세요.++## 설치++가장 간단한 방법: 이 저장소의 URL을 코딩 에이전트에게 주고 스킬 설치를 요청하세요. 에이전트가+따르는 절차는 [에이전트용: 이 URL에서 설치하기](#에이전트용-이-url에서-설치하기)에 있습니다. 직접 설치할 수도 있습니다.++**Claude Code** (Claude Code에서 입력)++```text+/plugin marketplace add kanaworksai-hue/effekseer-vfx-skill+/plugin install effekseer-vfx@effekseer-vfx+```++**Codex** (Codex 채팅에서 요청합니다. 스킬은 `~/.codex/skills` 또는 `$CODEX_HOME/skills`에 설치되며,+다음 턴이나 새 세션부터 사용됩니다)++```text+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/effekseer-vfx+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/vfx-review+```++**기타 에이전트** (Cursor, Gemini CLI, Copilot, OpenCode, ...)++```sh+npx skills add kanaworksai-hue/effekseer-vfx-skill+```++또는 `skills/effekseer-vfx`와 `skills/vfx-review`를 에이전트의 스킬 폴더(`~/.claude/skills/`,+`.agents/skills/`, ...)에 복사하세요. 각 스킬 폴더에는+자체 `LICENSE`(그리고 `effekseer-vfx`에는 `THIRD_PARTY_NOTICES.md`)가 들어 있어, 폴더만 복사해도 함께 유지됩니다.++### 에이전트용: 이 URL에서 설치하기++1. **파일을 받는다.** 호스트에 플러그인 또는 스킬 설치 도구가 있다면 그것을 우선 사용합니다(위의 명령). `/plugin` 같은+ 슬래시 명령은 사용자가 직접 입력해야 하므로 사용자에게 보여 줍니다. 그렇지 않으면 저장소를 클론하고 두 스킬+ 폴더를 이름 그대로 스킬 폴더에 복사합니다: `git clone --depth 1 <이 저장소의 URL>` 후+ `skills/effekseer-vfx`와 `skills/vfx-review`를 `~/.claude/skills/`(Claude Code, 모든 프로젝트),+ `<project>/.claude/skills/`(Claude Code, 단일 프로젝트), `~/.codex/skills/`(Codex, 설정되어 있으면 `$CODEX_HOME/skills`) 또는+ 호스트의 스킬 폴더(예: `.agents/skills/`)에 복사합니다.+ 그 밖의 것은 복사하지 않습니다. 스킬은 자기 완결적이며 실행 시에는 읽기 전용입니다.+2. **불러온다.** 스킬 목록에 아직 스킬이 보이지 않으면 사용자에게 새 세션을 시작해 달라고 요청합니다.+3. **머신을 점검한다.** 사용자의 게임 프로젝트에서 `sh <skill>/scripts/vfx doctor`를 실행하고(`<skill>`은+ 설치된 `effekseer-vfx` 폴더, Git Bash가 아닌 Windows 환경에서는 `<skill>\scripts\vfx.cmd doctor`) 그+ `next` 단계를 따릅니다.+4. **다운로드 전에 묻는다.** `sh <skill>/scripts/setup.sh`(Windows는 `setup.ps1`, 정확한 명령은+ `doctor`의 `next`에 있습니다)는 툴체인을 `~/.cache/effekseer-vfx`에 설치합니다+ (macOS ARM64와 Windows x64에서 약 250 MB, 그 외 환경에서는 `--authoring-only`). 또한 첫 `vfx init`은 공식+ Effekseer Godot 플러그인(약 34 MB)을 다운로드합니다. 설치에는 Python 3.11+ 또는 uv가 필요합니다. `doctor`가 둘 다 없다고 보고하면 사용자에게+ 하나를 설치해 달라고 요청합니다. Godot 4는 절대 사용자 대신 설치하지 않습니다. 사용자에게 설치를 요청하거나(또는 대신 설치해도 되는지+ 허락을 받고), `PATH`에 없으면 `GODOT`을 설정해 달라고 요청합니다.+5. **Godot은 샌드박스 밖에서 실행한다.** `vfx review`, `preview`, `showcase`는 사용자의 데스크톱에 Godot 창을+ 엽니다. 샌드박스 안의 에이전트(예: 워크스페이스 샌드박스 안의 Codex)는 창을 열 수 없으므로, 이 명령들은+ 사용자의 승인을 받아 샌드박스 밖에서 실행합니다. 호스트가 샌드박스를 벗어날 수 없다면 사용자가 데스크톱 터미널에서 실행할 수 있도록+ 정확한 명령을 전달합니다. 프레임을 하나도 렌더링하지 못한 리뷰는 약 90초 후 "rendered no frame"으로 중단됩니다+ (창을 열지 못했을 가능성이 가장 높으니, 함께 출력되는 Godot 로그를 확인하세요). `doctor`의 `render: true`는+ Godot을 찾았다는 의미일 뿐입니다.+6. **동작을 확인한다.** `vfx doctor`를 다시 실행하고(`modes`에 이 머신이 지원하는 기능이 표시됩니다)+ [시작하기](#시작하기)를 따릅니다. 동작하는 것과 부족한 것을 보고하고, `doctor`가 build나 render를 지원하지 않는다고 하는+ 머신에서 그것이 동작한다고 주장하지 않습니다.++## 시작하기++게임 프로젝트에서 에이전트에게 이렇게 요청하세요: *"여기에 effekseer-vfx 스킬을 세팅하고 화염 예제를 보여 줘."* 에이전트는 다음을 실행합니다.++```sh+sh <skill>/scripts/vfx doctor # what this machine can do, and what to install+sh <skill>/scripts/setup.sh # macOS ARM64 / Windows x64; use --authoring-only elsewhere (asks you first)+sh <skill>/scripts/vfx init # creates vfx/ with the Godot Lab, materials and math textures+sh <skill>/scripts/vfx examples add fire+sh <skill>/scripts/vfx build --ids VFX_Projectile_Fire VFX_Fire_Explosion+sh <skill>/scripts/vfx review --ids VFX_Projectile_Fire VFX_Fire_Explosion --note "baseline"+sh <skill>/scripts/vfx showcase # play the library in the Lab+```++그다음 이펙트를 요청하세요: *"타깃 지정 주문에 쓸 낙뢰를 만들어 줘. 짧고 날카롭게, 리턴 스트로크도 넣어서."* 이+스킬에 따라 에이전트는 브리프를 작성하고, 여러분의 이미지 생성 도구에 페인팅 텍스처를 요청하고(또는 여러분에게+준비를 부탁하고), 레시피를 작성해 빌드하고, 여러 라운드에 걸쳐 스트립을 리뷰한 뒤, 결과를 독립 리뷰어에게 넘기고 나서야+`effect-verify` 통과를 보고합니다. 독립 리뷰가 제출되고 `vfx overview`를 다시 실행하기 전까지는, 이펙트가 올바르게 렌더링되더라도+`effect-verify`가 `verified: false`를 표시합니다. 이 시점에서 에이전트는 "검증됨"이 아니라+"빌드와 렌더링이 된다"고 보고해야 합니다. 툴체인은 `~/.cache/effekseer-vfx`에 있으며, 다른 곳에 두려면+`EFFEKSEER_VFX_HOME`을 설정하세요([명령 레퍼런스](skills/effekseer-vfx/references/cli.md) 참조).++## 이미지 생성++복잡한 페인팅 형태(연기, 베기 궤적, 화염, 균열, 얼음, 문양)는 반드시 이미지 생성 모델에서 만들어야 하며,+이 스킬은 결코 코드로 흉내 내지 않습니다. 에이전트에 내장되었거나 연결된 이미지 도구가 있으면, `vfx/texture_prompts.json`에+기록한 프롬프트로 그 도구를 사용합니다. 없으면 어떤 이미지를 생성해 어디에 저장해야 하는지 정확히 알려 줍니다.+수학적 형태(글로우, 링, 노이즈, 그라디언트, 트레일, 디스토션 맵)는 프로시저럴로 생성됩니다.++## 게임에서 이펙트 사용하기++이펙트는 최종적으로 `.efk` 런타임 익스포트와 `.efkefc` 소스, 그리고 `vfx_manifest.json`으로 출력됩니다. 생성된 Godot 프로젝트에는+작은 API가 들어 있습니다.++```gdscript+var handle = Vfx.play("VFX_Fire_Explosion", position)+var shot = Vfx.launch("VFX_Projectile_Fire", from, to)+shot.arrived.connect(func(at): Vfx.play("VFX_Fire_Explosion", at))+```++빔은 매 프레임 조준하며, 끝점(레이캐스트, 타깃 본)은 게임이 관리합니다.++```gdscript+var ray = Vfx.beam("VFX_Kaiju_Atomic_Beam", mouth, target)+ray.aim(mouth, new_target) # each frame: sweep, follow the head+ray.release() # narrows and fades out, then frees itself+```++[`skills/effekseer-vfx/references/godot.md`](skills/effekseer-vfx/references/godot.md)를 참조하고, 거인과 괴수에 대해서는+[`references/scale.md`](skills/effekseer-vfx/references/scale.md)도 참조하세요.++## 저장소 구조++```+skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,+ setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,+ brief schema, examples, unity/ URP package)+skills/vfx-review/ SKILL.md for the independent reviewer+docs/zh/, docs/ja/ Chinese and Japanese translations of the references+.claude-plugin/ Claude Code plugin and marketplace manifests+tests/ pure-Python tests (no Core or Godot needed)+```++## 제한 사항++- 리뷰 지표는 실제 뷰포트에 대한 픽셀 휴리스틱이며, GPU나 오버드로를 측정한 값이 아닙니다.+- 리뷰 하네스는 macOS와 Windows에서 창 모드 Godot을 구동합니다. 헤드리스 Linux 캡처는 아직 지원하지 않습니다.+ Windows에서는 캡처하는 동안 Godot 창이 포커스를 유지합니다(macOS는 포커스를 사용 중인 앱으로 되돌려 줍니다).+- Windows에서 심볼릭 링크 안전성 테스트는 개발자 모드(또는 관리자 셸)가 필요하며, 없으면 건너뜁니다.+- 예제 점수는 스킬 자체의 캡슐 Lab 렌더에 대한 독립 리뷰 결과입니다(16종 중 2종은+ `iterate` 판정). 이 점수에 의존하기 전에 다시 빌드하고 리뷰하세요.+- `soft` 파티클은 Forward+에서 검증되었습니다(불투명 깊이에 대해서만 페이드됩니다). Compatibility 렌더러에는+ 깊이 텍스처가 없어 사용할 수 없습니다.++## 개발++```sh+sh skills/effekseer-vfx/scripts/setup.sh --authoring-only+~/.cache/effekseer-vfx/venv/bin/python -m pip install pytest+~/.cache/effekseer-vfx/venv/bin/python -m pytest -q tests+```++Windows의 경우(PowerShell, `--authoring-only`를 빼면 EffekseerCore 빌드 테스트도 실행됩니다):++```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scripts\setup.ps1 --authoring-only+~\.cache\effekseer-vfx\venv\Scripts\python.exe -m pip install pytest # a venv made by uv: uv pip install --python <that python.exe> pytest+~\.cache\effekseer-vfx\venv\Scripts\python.exe -X utf8 -m pytest -q tests+```++새로운 엔진 규약을 확인한 기여에서는 그 규약을 측정 방법과 함께+`skills/effekseer-vfx/references/engine-conventions.md`에 추가해 주세요.++## 라이선스와 크레딧++- **이 프로젝트:** [MIT](LICENSE). 코드 사본에 저작권 표시와 라이선스 문구를 남기면 상업적 용도를 포함해 자유롭게 사용·수정·배포할 수 있습니다.+- **직접 만든 것:** 여러분의 프로젝트에서 만든 이펙트, 텍스처, 플립북, Unity 스킬은 여러분의 것입니다. 이 저장소는 어떤 권리도 주장하지 않습니다.+- **비디오·이미지 모델:** 생성한 클립과 이미지(예: Seedance 2.5)에는 이 라이선스가 아니라 해당 모델의 이용 약관이 적용됩니다. 상업적으로 사용하기 전에 확인하세요. 이 저장소는 생성물을 배포하지 않습니다.+- **서드파티 구성 요소:** Effekseer, EffekseerForGodot4, .NET, 포함된 effekseer-ai는 각자의 라이선스를 따릅니다. [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)를 참조하세요.+- **브랜드와 예시:** KanaWorks_AI 이름, 로고, Kana 캐릭터의 권리는 東京AI映像合同会社(Tokyo AI Visuals LLC)에 있으며 MIT 라이선스의 대상이 **아닙니다**. 배너와 홍보 영상의 이펙트, 캐릭터, 영상은 예시이며 저장소에 포함되지 않고 라이선스 대상도 아닙니다. [docs/brand](docs/brand/README.md)를 참조하세요.++Effekseer, Godot, Unity는 각 소유자의 상표입니다. 이 프로젝트는 독립 프로젝트이며 이들과 제휴하거나 승인을 받지 않았습니다.++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Made with ♥ by <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>++<p><sub>도움이 되었다면 ⭐를 눌러 주세요. 업데이트를 이어 가는 힘이 되고 다른 사람들도 찾기 쉬워집니다. 다른 프로젝트: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>++</div>diff --git a/README.md b/README.mdindex 055d498..7a76c37 100644--- a/README.md+++ b/README.md@@ -1,6 +1,23 @@# effekseer-vfx-skill-English | [简体中文](README.zh-CN.md) | [日本語](README.ja.md)+<div align="center">++<img src="docs/assets/banner-en.jpg" alt="VFX Skill: your coding agent makes real-time game VFX for Effekseer, Godot and Unity" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>A KanaWorks_AI project</b></a></p>++English | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Português (Brasil)](README.pt-BR.md) | [Español](README.es.md)++</div>Agent skills that let a coding agent (Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and other[Agent Skills](https://agentskills.io) hosts) make real-time game VFX the way a VFX artist iterates, in code:@@ -27,6 +44,35 @@ Agent skills that let a coding agent (Claude Code, Codex, Cursor, Gemini CLI, Gi(`spiral_ribbons`, `spike_crown`, `speed_streaks`, `stylized_pair`, `sparkle`), greyscale mask templates, andscreen feedback (`screen=`: shake, impact frame, hit-stop) that the Lab plays and `Vfx.screen_cue` hands to the game.+## Three ways to make an effect (new in 0.3)++You choose per effect; nothing forces one way.++| Way | How | Plays in |+|---|---|---|+| **Procedural** | layered primitives in a Python recipe, painted textures, EffekseerCore build, Godot review (everything above) | Effekseer → Godot |+| **Video flipbook** | an image-to-video model (verified with Seedance 2.5; any model with first and last frames works) paints the motion on black; `vfx video-flipbook` keys, crops, masks and packs it, `vfx video-grade` gives every sheet of an element the same cel-shaded look | Unity (URP), or Effekseer → Godot |+| **Combined** | the sheet is the body layer of a recipe (`video_body(...)`); primitives add the contact flash, sparks, rings, cracks, decals and heat haze | Effekseer → Godot, Unity |++**What was not possible before and is now:**++- **Continuous shape changes.** A water column that shoots up, carries the target into the air and collapses as rain;+ a fireball that bursts and boils into grey smoke; an orb whose flames churn in a seamless loop. Primitives scale,+ fade, scroll and erode a picture; they cannot turn fire into smoke inside one silhouette. A video model draws every+ in-between.+- **A hand-painted anime look in motion**, consistent across a whole element set: one value ramp per element grades+ every sheet to the same flat steps (dark rim, body, light, hot core).+- **Unity.** The skill used to stop at Godot. `vfx unity-install <UnityProject>` adds a URP runtime package+ (data-driven `ElementProfile` skills with projectile, instant-bolt and ground-eruption delivery, layered particles,+ hit-stop, shake, target lift) and its procedural textures; `vfx unity-export` copies a sheet with its grid; three+ menu items (or one batch-mode command an agent can run) turn sheets into a playable skill and a demo scene.+- **Reproducible from a sentence.** Every clip's prompt and every sheet's parameters are recorded in+ `vfx/video_prompts.json`, so an agent can rebuild or vary a sheet exactly. Ask: *"Make a water-column skill from a+ video flipbook and set it up in my Unity project."*++Guide: [`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md). The skill ships the+technique only: clips, sheets and characters you generate stay in your own project.+## Requirements| Mode | What you can do | Needs |@@ -34,6 +80,8 @@ Agent skills that let a coding agent (Claude Code, Codex, Cursor, Gemini CLI, Gi| authoring | write briefs and recipes, lint, process and measure textures | Python 3.11+ or [uv](https://docs.astral.sh/uv/) on macOS, Linux or Windows (macOS's built-in Python 3.9 is too old) || build | compile `.efkefc` / `.efk` through the official EffekseerCore | **macOS on Apple silicon** or **Windows x64**, network for the first setup (~250 MB into `~/.cache/effekseer-vfx`) || render | Godot filmstrip review, Lab, preview, packaging | the above + [Godot 4](https://godotengine.org) (Forward+) on `PATH` or in `GODOT`; `ffmpeg` for reference clips and recordings |+| video flipbooks | `video-*` commands | authoring mode + `ffmpeg`; clips from any image-to-video model |+| Unity | play sheets as element skills | Unity 6 (6000.0+) with URP 17; verified on 6000.5 |Build and render are verified on macOS ARM64 (Effekseer Core 1.80.7, EffekseerForGodot4 1.80.5.1, Godot 4.7, .NET 9)and on Windows 11 x64 (the same versions, Godot 4.7.2). Windows ARM64 gets the matching .NET runtime from setup but is@@ -158,7 +206,7 @@ See [`skills/effekseer-vfx/references/godot.md`](skills/effekseer-vfx/references```skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,- brief schema, examples)+ brief schema, examples, unity/ URP package)skills/vfx-review/ SKILL.md for the independent reviewerdocs/zh/, docs/ja/ Chinese and Japanese translations of the references.claude-plugin/ Claude Code plugin and marketplace manifests@@ -195,9 +243,24 @@ powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scriptsContributions that confirm a new engine convention should add it to`skills/effekseer-vfx/references/engine-conventions.md` together with how it was measured.-## License+## License and credits++- **This project:** [MIT](LICENSE). Use, change and ship it, commercially too; keep the copyright and license notice with copies of the code.+- **What you make with it:** the effects, textures, flipbooks and Unity skills you build in your own project are yours. This repository claims nothing in them.+- **Video and image models:** clips and images you generate (for example with Seedance 2.5) follow that model's terms, not this license. Check them before commercial use. None are distributed here.+- **Third-party components:** Effekseer, EffekseerForGodot4, .NET and the vendored effekseer-ai keep their own licenses. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).+- **Brand and showcase:** the KanaWorks_AI name, logo and the Kana character are © 東京AI映像合同会社 (Tokyo AI Visuals LLC) and are **not** covered by the MIT license. The effects, characters and footage in the banner and the promo videos are examples: not included and not licensed. See [docs/brand](docs/brand/README.md).++Effekseer, Godot and Unity are trademarks of their respective owners. This is an independent project, not affiliated with or endorsed by them.++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Made with ♥ by <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>-MIT, see [LICENSE](LICENSE). Third-party components and downloads: [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).-Effekseer and Godot are trademarks of their respective owners; this project is not affiliated with them.+<p><sub>If the skill saves you time, a ⭐ keeps the updates coming and helps others find it. More projects: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>-Made by KanaWorks_AI ([@KanaWorks_AI](https://x.com/KanaWorks_AI) on X).+</div>diff --git a/README.pt-BR.md b/README.pt-BR.mdnew file mode 100644index 0000000..4667a81--- /dev/null+++ b/README.pt-BR.md@@ -0,0 +1,206 @@+# effekseer-vfx-skill++<div align="center">++<img src="docs/assets/banner-pt.jpg" alt="VFX Skill: seu agente de código cria VFX de jogo em tempo real para Effekseer, Godot e Unity" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>Um projeto KanaWorks_AI</b></a></p>++[English](README.md) | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | Português (Brasil) | [Español](README.es.md)++</div>++> Este documento é uma tradução do README em inglês. Os agentes carregam os arquivos em inglês dentro de `skills/`; se houver divergência entre as versões, vale a versão em inglês.++Skills de agente que permitem que um agente de programação (Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode e outros hosts compatíveis com+[Agent Skills](https://agentskills.io)) crie VFX de jogos em tempo real do mesmo jeito que um artista de VFX itera, só que em código:++**brief de design → texturas → receita em Python → build no EffekseerCore → filmstrip real no Godot → olhar → corrigir uma coisa → repetir → revisão independente**++- **`effekseer-vfx`** — a skill de criação: regras de ofício, convenções de engine do Effekseer/Godot já verificadas, cerca de 30 primitivas de camada combináveis, um linter estático, o compilador oficial EffekseerCore com verificação por releitura (save/open), um Godot Lab que encena cada efeito como uma troca entre dois dummies, captura de filmstrip com flags de pixel, histórico de iterações e evidências à prova de adulteração que vinculam uma revisão ao build exato que ela viu.+- **`vfx-review`** — a skill de revisão: um agente separado dá nota ao strip segundo uma rubrica fixa, sem ver a receita, porque o autor nunca avalia o próprio trabalho.+- **Exemplos** — dezesseis efeitos prontos, com briefs e texturas: quatro pares de longo alcance (fogo, gelo, veneno, trevas: projétil + impacto), um de cada para golpe, corte, carga, escudo e cura, e um conjunto kaiju (uma carga que sobe pelas placas dorsais, um raio atômico capaz de varrer a área, uma explosão fotográfica), além de três casos de antes/depois com diagnóstico.+- **Efeitos grandes e realistas** — `scale='kaiju'` gera uma receita em escala de personagem 40x maior e 2,5x mais lenta (tamanhos, velocidades, gravidade, orçamentos e a câmera de revisão acompanham); `beam()` cria um raio sustentado cujo ponto final o jogo move a cada frame (`Vfx.beam()` → `aim()` → `release()`); `charge_chain()` acende arcos ao longo de uma cadeia de pontos; flipbooks fotográficos de fogo, fuligem e fumaça; soft particles verificadas no Forward+.+- **Combos, blockout e formas estilizadas** — um brief de sequência amarra vários efeitos aos tempos de uma animação de personagem e conduz o trabalho pelas etapas blockout → detalhe → polimento (uma revisão independente do blockout precisa ser aprovada antes de qualquer trabalho de textura); as capturas podem vir do próprio jogo; as referências trazem listas do que "roubar", que o revisor confere; `vfx paintover` transforma um frame capturado em um prompt de edição de imagem para gerar uma referência de concept. Primitivas estilizadas de borda dura (`spiral_ribbons`, `spike_crown`, `speed_streaks`, `stylized_pair`, `sparkle`), templates de máscara em tons de cinza e feedback de tela (`screen=`: shake, impact frame, hit-stop) que o Lab reproduz e `Vfx.screen_cue` repassa ao jogo.++## Três formas de criar um efeito (novidade da 0.3)++Você escolhe por efeito; nada obriga a seguir um único caminho.++| Forma | Como | Roda em |+|---|---|---|+| **Procedural** | primitivas em camadas numa receita Python, texturas pintadas, build no EffekseerCore, revisão no Godot (tudo o que foi descrito acima) | Effekseer → Godot |+| **Flipbook de vídeo** | um modelo de imagem para vídeo (verificado com o Seedance 2.5; qualquer modelo que aceite primeiro e último frame serve) pinta o movimento sobre fundo preto; `vfx video-flipbook` faz o key, recorta, aplica máscara e monta a sheet, e `vfx video-grade` dá a todas as sheets de um elemento o mesmo visual cel-shaded | Unity (URP), ou Effekseer → Godot |+| **Combinada** | a sheet é a camada principal (body) de uma receita (`video_body(...)`); as primitivas adicionam o flash de contato, faíscas, anéis, rachaduras, decals e a distorção de calor (heat haze) | Effekseer → Godot, Unity |++**O que antes não era possível e agora é:**++- **Mudanças contínuas de forma.** Uma coluna d'água que dispara para cima, leva o alvo para o ar e desaba como chuva; uma bola de fogo que explode e se revolve em fumaça cinza; um orbe cujas chamas se agitam em um loop sem emendas. Primitivas escalam, fazem fade, rolam (scroll) e erodem uma imagem; elas não conseguem transformar fogo em fumaça dentro de uma mesma silhueta. Um modelo de vídeo desenha todos os in-betweens.+- **Um visual de anime pintado à mão, em movimento**, consistente em todo o conjunto de um elemento: uma rampa de valores por elemento ajusta todas as sheets aos mesmos degraus chapados (borda escura, corpo, luz, núcleo incandescente).+- **Unity.** Antes, a skill parava no Godot. `vfx unity-install <UnityProject>` adiciona um pacote de runtime para URP (skills `ElementProfile` orientadas a dados, com entrega por projétil, raio instantâneo e erupção do chão, partículas em camadas, hit-stop, tremor de tela, levantamento do alvo) e suas texturas procedurais; `vfx unity-export` copia uma sheet junto com o seu grid; três itens de menu (ou um único comando em batch mode que um agente pode executar) transformam sheets em uma skill jogável e em uma cena de demonstração.+- **Reproduzível a partir de uma frase.** O prompt de cada clipe e os parâmetros de cada sheet ficam registrados em `vfx/video_prompts.json`, então um agente pode reconstruir ou variar uma sheet com exatidão. Peça: *"Crie uma skill de coluna d'água a partir de um flipbook de vídeo e configure-a no meu projeto Unity."*++Guia: [`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md). A skill distribui apenas a técnica: os clipes, as sheets e os personagens que você gerar ficam no seu próprio projeto.++## Requisitos++| Modo | O que dá para fazer | Requer |+|---|---|---|+| authoring | escrever briefs e receitas, rodar o lint, processar e medir texturas | Python 3.11+ ou [uv](https://docs.astral.sh/uv/) em macOS, Linux ou Windows (o Python 3.9 que vem com o macOS é antigo demais) |+| build | compilar `.efkefc` / `.efk` pelo EffekseerCore oficial | **macOS em Apple silicon** ou **Windows x64**, conexão de rede na primeira configuração (~250 MB em `~/.cache/effekseer-vfx`) |+| render | revisão de filmstrip no Godot, Lab, preview, empacotamento | o item anterior + [Godot 4](https://godotengine.org) (Forward+) no `PATH` ou em `GODOT`; `ffmpeg` para clipes de referência e gravações |+| flipbooks de vídeo | comandos `video-*` | modo authoring + `ffmpeg`; clipes de qualquer modelo de imagem para vídeo |+| Unity | reproduzir sheets como skills de elemento | Unity 6 (6000.0+) com URP 17; verificado na 6000.5 |++Build e render estão verificados no macOS ARM64 (Effekseer Core 1.80.7, EffekseerForGodot4 1.80.5.1, Godot 4.7, .NET 9) e no Windows 11 x64 (as mesmas versões, Godot 4.7.2). No Windows ARM64, o setup instala o runtime .NET correspondente, mas a plataforma não foi verificada. No Linux roda o modo authoring; o caminho de build não foi verificado.++No Windows, todos os comandos `sh <skill>/scripts/...` abaixo também funcionam no Git Bash (o que o Claude Code usa); no cmd ou no PowerShell, use `<skill>\scripts\vfx.cmd` no lugar de `vfx` e+`powershell -NoProfile -ExecutionPolicy Bypass -File <skill>\scripts\setup.ps1` no lugar de `setup.sh`.++## Instalação++O jeito mais simples: passe a URL deste repositório para o seu agente de programação e peça que ele instale a skill. Os passos que ele segue estão em [Para agentes: instalação a partir desta URL](#para-agentes-instalação-a-partir-desta-url). Ou instale você mesmo:++**Claude Code** (digite isto no Claude Code)++```text+/plugin marketplace add kanaworksai-hue/effekseer-vfx-skill+/plugin install effekseer-vfx@effekseer-vfx+```++**Codex** (peça em um chat do Codex; as skills vão para `~/.codex/skills`, ou `$CODEX_HOME/skills`, e passam a ser usadas a partir do próximo turno ou de uma nova sessão)++```text+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/effekseer-vfx+$skill-installer install https://github.com/kanaworksai-hue/effekseer-vfx-skill/tree/main/skills/vfx-review+```++**Outros agentes** (Cursor, Gemini CLI, Copilot, OpenCode, ...)++```sh+npx skills add kanaworksai-hue/effekseer-vfx-skill+```++Ou copie `skills/effekseer-vfx` e `skills/vfx-review` para a pasta de skills do seu agente (`~/.claude/skills/`, `.agents/skills/`, ...). Cada pasta de skill traz o próprio `LICENSE` (e a `effekseer-vfx`, também o seu `THIRD_PARTY_NOTICES.md`), então uma pasta copiada continua com esses arquivos.++### Para agentes: instalação a partir desta URL++1. **Obtenha os arquivos.** Se o seu host tiver um instalador de plugins ou de skills, dê preferência a ele (os comandos acima); um slash command como `/plugin` precisa ser digitado pelo usuário, então mostre o comando a ele. Caso contrário, clone o repositório e copie as duas pastas de skill para a sua pasta de skills, mantendo os nomes: `git clone --depth 1 <URL deste repositório>`, depois copie `skills/effekseer-vfx` e `skills/vfx-review` para `~/.claude/skills/` (Claude Code, todos os projetos), `<project>/.claude/skills/` (Claude Code, um único projeto), `~/.codex/skills/` (Codex; `$CODEX_HOME/skills` se estiver definido) ou para a pasta de skills do seu host (por exemplo, `.agents/skills/`).+ Não copie mais nada; as skills são autocontidas e somente leitura em tempo de execução.+2. **Carregue as skills.** Se elas ainda não aparecerem na sua lista de skills, peça ao usuário que inicie uma nova sessão.+3. **Verifique a máquina.** A partir do projeto de jogo do usuário, rode `sh <skill>/scripts/vfx doctor` (`<skill>` é a pasta `effekseer-vfx` instalada; no Windows fora do Git Bash, `<skill>\scripts\vfx.cmd doctor`) e siga os passos indicados em `next`.+4. **Pergunte antes de baixar.** `sh <skill>/scripts/setup.sh` (Windows: `setup.ps1`; o comando exato está no `next` do `doctor`) instala o toolchain em `~/.cache/effekseer-vfx` (cerca de 250 MB no macOS ARM64 e no Windows x64; `--authoring-only` nas demais plataformas), e o primeiro `vfx init` baixa o plugin oficial do Effekseer para Godot (cerca de 34 MB). O setup precisa de Python 3.11+ ou uv: se o `doctor` não encontrar nenhum dos dois, peça ao usuário que instale um deles. O Godot 4 nunca é instalado automaticamente para o usuário; peça que ele o instale (ou que permita que você instale) e defina `GODOT` se ele não estiver no `PATH`.+5. **Rode o Godot fora do sandbox.** `vfx review`, `preview` e `showcase` abrem uma janela do Godot na área de trabalho do usuário. Um agente em sandbox (o Codex no sandbox do workspace, por exemplo) não consegue abrir essa janela: rode esses comandos fora do sandbox, com a aprovação do usuário; se o seu host não puder sair do sandbox, passe ao usuário o comando exato para ele rodar em um terminal na área de trabalho. Uma revisão que não renderiza nenhum frame é interrompida após cerca de 90 s com "rendered no frame" (o mais provável é que a janela não tenha conseguido abrir; confira a saída do Godot incluída na mensagem). `render: true` no `doctor` significa apenas que o Godot foi encontrado.+6. **Confirme que funciona.** Rode `vfx doctor` de novo (`modes` deve mostrar o que esta máquina suporta) e depois siga os [Primeiros passos](#primeiros-passos). Informe o que funciona e o que está faltando; não afirme que build ou render funcionam em uma máquina onde o `doctor` diz que não funcionam.++## Primeiros passos++Peça ao seu agente, dentro do seu projeto de jogo: *"Configure a skill effekseer-vfx aqui e me mostre o exemplo de fogo."* Ele vai rodar:++```sh+sh <skill>/scripts/vfx doctor # what this machine can do, and what to install+sh <skill>/scripts/setup.sh # macOS ARM64 / Windows x64; use --authoring-only elsewhere (asks you first)+sh <skill>/scripts/vfx init # creates vfx/ with the Godot Lab, materials and math textures+sh <skill>/scripts/vfx examples add fire+sh <skill>/scripts/vfx build --ids VFX_Projectile_Fire VFX_Fire_Explosion+sh <skill>/scripts/vfx review --ids VFX_Projectile_Fire VFX_Fire_Explosion --note "baseline"+sh <skill>/scripts/vfx showcase # play the library in the Lab+```++Depois, peça um efeito: *"Crie um relâmpago para um feitiço com alvo, curto e seco, com descarga de retorno."* A skill faz o agente escrever um brief, pedir texturas pintadas à sua ferramenta de geração de imagens (ou pedir que você as forneça), escrever a receita, fazer o build, revisar os strips ao longo de várias rodadas e entregar o resultado a um revisor independente antes de reportar `effect-verify` como aprovado. Até que essa revisão independente seja enviada e `vfx overview` seja executado de novo, `effect-verify` indica `verified: false`, mesmo quando o efeito renderiza corretamente; nesse ponto, o agente deve reportar "compila e renderiza", e não "verificado". O toolchain fica em `~/.cache/effekseer-vfx`; defina `EFFEKSEER_VFX_HOME` para colocá-lo em outro lugar (veja [a referência de comandos](skills/effekseer-vfx/references/cli.md)).++## Geração de imagens++Formas pintadas complexas (fumaça, arcos de corte, fogo, rachaduras, gelo, símbolos) precisam vir de um modelo de geração de imagens; a skill nunca as simula com código. Se o seu agente tiver uma ferramenta de imagem integrada ou conectada, ele a usa com os prompts que registra em `vfx/texture_prompts.json`. Caso contrário, ele diz exatamente qual imagem você deve gerar e onde salvá-la.+Formas matemáticas (glows, anéis, ruído, gradientes, trails, mapas de distorção) são geradas proceduralmente.++## Usando os efeitos em um jogo++Os efeitos terminam como exports de runtime `.efk` e fontes `.efkefc`, acompanhados de um `vfx_manifest.json`. O projeto Godot gerado contém uma pequena API:++```gdscript+var handle = Vfx.play("VFX_Fire_Explosion", position)+var shot = Vfx.launch("VFX_Projectile_Fire", from, to)+shot.arrived.connect(func(at): Vfx.play("VFX_Fire_Explosion", at))+```++Os raios (beams) são mirados a cada frame; o ponto final é controlado pelo jogo (um ray cast, um bone do alvo):++```gdscript+var ray = Vfx.beam("VFX_Kaiju_Atomic_Beam", mouth, target)+ray.aim(mouth, new_target) # each frame: sweep, follow the head+ray.release() # narrows and fades out, then frees itself+```++Veja [`skills/effekseer-vfx/references/godot.md`](skills/effekseer-vfx/references/godot.md) e, para gigantes e kaiju,+[`references/scale.md`](skills/effekseer-vfx/references/scale.md).++## Estrutura do repositório++```+skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,+ setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,+ brief schema, examples, unity/ URP package)+skills/vfx-review/ SKILL.md for the independent reviewer+docs/zh/, docs/ja/ Chinese and Japanese translations of the references+.claude-plugin/ Claude Code plugin and marketplace manifests+tests/ pure-Python tests (no Core or Godot needed)+```++## Limitações++- As métricas de revisão são heurísticas de pixel sobre o viewport real, não medições de GPU ou de overdraw.+- O harness de revisão controla um Godot em janela no macOS e no Windows; a captura headless no Linux ainda não é suportada. No Windows, a janela do Godot mantém o foco durante a captura (o macOS devolve o foco ao seu app).+- No Windows, os testes de segurança de symlinks precisam do Modo de Desenvolvedor (ou de um shell de administrador) e são pulados sem ele.+- As notas dos exemplos vêm de uma revisão independente dos renders da própria skill no Lab com cápsulas (dois dos dezesseis foram avaliados como `iterate`); refaça o build e a revisão antes de confiar nelas.+- As partículas `soft` estão verificadas no Forward+ (o fade acontece apenas contra a profundidade opaca); o renderer Compatibility não tem textura de profundidade e não consegue usá-las.++## Desenvolvimento++```sh+sh skills/effekseer-vfx/scripts/setup.sh --authoring-only+~/.cache/effekseer-vfx/venv/bin/python -m pip install pytest+~/.cache/effekseer-vfx/venv/bin/python -m pytest -q tests+```++No Windows (PowerShell; remova `--authoring-only` para rodar também os testes de build do EffekseerCore):++```powershell+powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scripts\setup.ps1 --authoring-only+~\.cache\effekseer-vfx\venv\Scripts\python.exe -m pip install pytest # a venv made by uv: uv pip install --python <that python.exe> pytest+~\.cache\effekseer-vfx\venv\Scripts\python.exe -X utf8 -m pytest -q tests+```++Contribuições que confirmem uma nova convenção de engine devem adicioná-la a+`skills/effekseer-vfx/references/engine-conventions.md`, junto com a forma como ela foi medida.++## Licença e créditos++- **Este projeto:** [MIT](LICENSE). Use, modifique e distribua, inclusive comercialmente; mantenha o aviso de copyright e a licença junto às cópias do código.+- **O que você cria com ele:** os efeitos, texturas, flipbooks e skills de Unity que você constrói no seu projeto são seus. Este repositório não reivindica nada sobre eles.+- **Modelos de vídeo e imagem:** clipes e imagens que você gera (por exemplo, com Seedance 2.5) seguem os termos desse modelo, não esta licença. Confira antes de uso comercial. Nada disso é distribuído aqui.+- **Componentes de terceiros:** Effekseer, EffekseerForGodot4, .NET e o effekseer-ai incluído mantêm suas próprias licenças. Veja [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).+- **Marca e exemplos:** o nome KanaWorks_AI, o logo e a personagem Kana são © 東京AI映像合同会社 (Tokyo AI Visuals LLC) e **não** estão cobertos pela licença MIT. Os efeitos, personagens e imagens do banner e dos vídeos de divulgação são exemplos: não estão incluídos nem licenciados. Veja [docs/brand](docs/brand/README.md).++Effekseer, Godot e Unity são marcas de seus respectivos proprietários. Este é um projeto independente, sem afiliação ou endosso deles.++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Feito com ♥ por <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>++<p><sub>Se a skill te poupa tempo, uma ⭐ mantém as atualizações vindo e ajuda outras pessoas a encontrá-la. Mais projetos: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>++</div>diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 16d9705..b05de27 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -1,6 +1,23 @@# effekseer-vfx-skill-[English](README.md) | 简体中文 | [日本語](README.ja.md)+<div align="center">++<img src="docs/assets/banner-zh.jpg" alt="VFX Skill:让编程 agent 为 Effekseer、Godot、Unity 制作实时游戏特效" width="820">++<p>+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-6b4dff?style=flat-square"></a>+ <a href="https://agentskills.io"><img alt="Agent Skill" src="https://img.shields.io/badge/Agent_Skill-Claude_Code_·_Codex_·_Cursor-19b8d6?style=flat-square"></a>+ <img alt="Effekseer 1.80" src="https://img.shields.io/badge/Effekseer-1.80-ff7d2e?style=flat-square">+ <img alt="Godot 4" src="https://img.shields.io/badge/Godot-4-478cbf?style=flat-square&logo=godotengine&logoColor=white">+ <img alt="Unity 6 URP" src="https://img.shields.io/badge/Unity_6-URP-111?style=flat-square&logo=unity">+ <a href="https://github.com/kanaworksai-hue/effekseer-vfx-skill/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/kanaworksai-hue/effekseer-vfx-skill?style=flat-square&logo=github&label=stars&color=f5c518"></a>+</p>++<p><a href="https://github.com/kanaworksai-hue"><img src="docs/brand/kanaworks-mark.png" height="22" alt="" align="absmiddle"></a> <a href="https://github.com/kanaworksai-hue"><b>KanaWorks_AI 出品</b></a></p>++[English](README.md) | 简体中文 | [日本語](README.ja.md) | [한국어](README.ko.md) | [Português (Brasil)](README.pt-BR.md) | [Español](README.es.md)++</div>> 中文文档是英文原文的翻译,仅供阅读参考。agent 实际加载的是 `skills/` 下的英文文件(`SKILL.md` 与 `references/*.md`);两者不一致时以英文为准。中文译文索引见 [docs/zh/README.md](docs/zh/README.md)。@@ -17,6 +34,25 @@- **大型与写实效果** —— `scale='kaiju'` 把角色尺度的配方构建得大 40 倍、慢 2.5 倍(尺寸、速度、重力、预算和复查镜头全都随之变化);`beam()` 制作一条持续光束,终点由游戏每帧移动(`Vfx.beam()` → `aim()` → `release()`);`charge_chain()` 沿一串点点亮电弧;照片级的火焰、烟灰和烟雾序列帧;软粒子已在 Forward+ 中验证。- **连段、灰盒与风格化形状** —— 序列简报把多个特效绑定到角色动画的节拍上,按灰盒 → 细节 → 打磨推进(贴图工作之前必须先通过独立的灰盒评审);截图可以直接来自游戏本身;参考资料附带“偷什么”清单,由评审逐项检查;`vfx paintover` 把截到的关键帧变成概念图用的图像编辑提示词。硬边风格化原语(`spiral_ribbons`、`spike_crown`、`speed_streaks`、`stylized_pair`、`sparkle`)、灰度遮罩模板,以及屏幕反馈(`screen=`:震屏、冲击帧、顿帧,由 Lab 播放,并通过 `Vfx.screen_cue` 交给游戏)。+## 三种做法(0.3 新增)++每个特效自己选,不强制任何一种。++| 做法 | 怎么做 | 在哪里播放 |+|---|---|---|+| **程序化** | Python 配方叠加图元、手绘贴图、EffekseerCore 编译、Godot 审查(即上面的全部内容) | Effekseer → Godot |+| **视频序列帧** | 图生视频模型(用 Seedance 2.5 验证;任何支持首尾帧的模型都行)在黑底上画出运动;`vfx video-flipbook` 负责抠像、统一裁切、遮罩并拼成图集,`vfx video-grade` 让同一元素的所有图集都是同一套赛璐珞色阶 | Unity(URP),或 Effekseer → Godot |+| **联合** | 图集作为配方的主体层(`video_body(...)`),接触闪光、火花、冲击环、裂纹、贴花和热扭曲由图元补上 | Effekseer → Godot、Unity |++**以前做不到、现在能做到的:**++- **连续变形的特效。** 水柱冲起、把目标托上半空、再化作雨水落下;火球炸开后翻滚着变成灰烟;火焰翻卷的球体无缝循环。图元能缩放、淡出、滚动、侵蚀一张图,却没法在同一个轮廓里把火变成烟;视频模型把每一帧中间态都画出来了。+- **会动的手绘二次元质感,并且整套元素统一。** 每个元素一条明度色阶,把所有图集压成同样的平涂层次(暗边、主体、亮部、高热核心)。+- **Unity。** 以前只能到 Godot。`vfx unity-install <UnityProject>` 会加入一个 URP 运行时包(数据驱动的 `ElementProfile` 技能:飞行弹道、瞬间命中、地面喷发三种出手方式,分层粒子,顿帧、震屏、把目标托起)和程序生成的贴图;`vfx unity-export` 把图集连同网格信息拷进去;三个菜单(或 agent 可直接运行的一条批处理命令)就能把图集变成可玩的技能和演示场景。+- **一句话就能复现。** 每段视频的提示词和每张图集的参数都记录在 `vfx/video_prompts.json`,agent 可以精确重做或改出变体。比如对 agent 说:*「用视频序列帧做一个水柱技能,并装进我的 Unity 项目。」*++指南:[`references/video-flipbook.md`](skills/effekseer-vfx/references/video-flipbook.md)。本 skill 只开源技术;你自己生成的视频、图集和角色都留在你自己的项目里。+## 环境要求| 模式 | 能做什么 | 需要 |@@ -24,6 +60,8 @@| authoring | 写简报和配方、lint、处理和测量纹理 | macOS、Linux 或 Windows 上的 Python 3.11+ 或 [uv](https://docs.astral.sh/uv/)(macOS 自带的 Python 3.9 太旧) || build | 通过官方 EffekseerCore 编译 `.efkefc` / `.efk` | **Apple 芯片的 macOS** 或 **Windows x64**,首次安装需要联网(约 250 MB,装到 `~/.cache/effekseer-vfx`) || render | Godot 连拍复查、Lab、预览、打包 | 以上全部 + 位于 `PATH` 或 `GODOT` 中的 [Godot 4](https://godotengine.org)(Forward+);参考视频和录像需要 `ffmpeg` |+| 视频序列帧 | `video-*` 命令 | authoring 模式 + `ffmpeg`;视频可来自任意图生视频模型 |+| Unity | 把图集作为元素技能播放 | Unity 6(6000.0+)+ URP 17;已在 6000.5 验证 |build 和 render 已在 macOS ARM64(Effekseer Core 1.80.7、EffekseerForGodot4 1.80.5.1、Godot 4.7、.NET 9)和Windows 11 x64(版本相同,Godot 4.7.2)上验证。Windows ARM64 的安装脚本会装上对应的 .NET 运行时,但未经验证。@@ -136,7 +174,7 @@ ray.release() # narrows and fades out, then frees itself```skills/effekseer-vfx/ SKILL.md, references/ (craft, engine conventions, review...), scripts/ (vfx CLI and vfx.cmd,setup.sh and setup.ps1, vfxkit, vendored effekseer_ai), assets/ (Godot Lab, materials, rubric,- brief schema, examples)+ brief schema, examples, unity/ URP package)skills/vfx-review/ SKILL.md for the independent reviewerdocs/zh/, docs/ja/ Chinese and Japanese translations of the references.claude-plugin/ Claude Code plugin and marketplace manifests@@ -176,9 +214,24 @@ powershell -NoProfile -ExecutionPolicy Bypass -File skills\effekseer-vfx\scripts确认了新引擎约定的贡献,应把它连同测量方法一起写进`skills/effekseer-vfx/references/engine-conventions.md`(英文原文)。-## 许可证+## 许可与署名++- **本项目:** [MIT](LICENSE)。只要在代码副本中保留版权声明和许可文本,就可以自由使用、修改和分发,包括商用。+- **你做出来的东西:** 你在自己项目里做的特效、贴图、序列帧和 Unity 技能归你所有,本仓库不主张任何权利。+- **视频 / 图像模型:** 你生成的视频和图片(例如用 Seedance 2.5)受该模型的使用条款约束,不受本许可约束。商用前请先确认。本仓库不分发任何生成内容。+- **第三方组件:** Effekseer、EffekseerForGodot4、.NET 以及内置的 effekseer-ai 各自遵循自己的许可,见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。+- **品牌与作例:** KanaWorks_AI 名称、logo 和 Kana 形象版权归东京AI映像合同会社所有,**不在** MIT 授权范围内。横幅和宣传视频里的特效、角色和画面都是作例,不包含在仓库中,也不在授权范围内。见 [docs/brand](docs/brand/README.md)。++Effekseer、Godot 和 Unity 是其各自所有者的商标。本项目为独立项目,与它们没有关联,也未获其认可。++<br>++<div align="center">++<a href="https://x.com/KanaWorks_AI"><img src="docs/brand/kanaworks-logo.png" width="130" alt="KanaWorks_AI"></a>++<p><b>Made with ♥ by <a href="https://x.com/KanaWorks_AI">KanaWorks_AI</a></b> · <a href="https://x.com/KanaWorks_AI">@KanaWorks_AI</a> on X</p>-MIT,见 [LICENSE](LICENSE)。第三方组件与下载内容:[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。-Effekseer 和 Godot 是其各自所有者的商标;本项目与它们没有关联。+<p><sub>觉得有用的话点个 ⭐,这是持续更新的动力,也能让更多人发现它。更多项目: <a href="https://github.com/kanaworksai-hue">github.com/kanaworksai-hue</a></sub></p>-作者:KanaWorks_AI(X:[@KanaWorks_AI](https://x.com/KanaWorks_AI))。+</div>diff --git a/docs/assets/banner-en.jpg b/docs/assets/banner-en.jpgnew file mode 100644index 0000000..aa082e8Binary files /dev/null and b/docs/assets/banner-en.jpg differdiff --git a/docs/assets/banner-es.jpg b/docs/assets/banner-es.jpgnew file mode 100644index 0000000..6b078bdBinary files /dev/null and b/docs/assets/banner-es.jpg differdiff --git a/docs/assets/banner-ja.jpg b/docs/assets/banner-ja.jpgnew file mode 100644index 0000000..af98f36Binary files /dev/null and b/docs/assets/banner-ja.jpg differdiff --git a/docs/assets/banner-ko.jpg b/docs/assets/banner-ko.jpgnew file mode 100644index 0000000..4e2bc13Binary files /dev/null and b/docs/assets/banner-ko.jpg differdiff --git a/docs/assets/banner-pt.jpg b/docs/assets/banner-pt.jpgnew file mode 100644index 0000000..1445ff2Binary files /dev/null and b/docs/assets/banner-pt.jpg differdiff --git a/docs/assets/banner-zh.jpg b/docs/assets/banner-zh.jpgnew file mode 100644index 0000000..42741c9Binary files /dev/null and b/docs/assets/banner-zh.jpg differdiff --git a/docs/assets/social-preview.jpg b/docs/assets/social-preview.jpgnew file mode 100644index 0000000..3c86de6Binary files /dev/null and b/docs/assets/social-preview.jpg differdiff --git a/docs/brand/README.md b/docs/brand/README.mdnew file mode 100644index 0000000..8702f8d--- /dev/null+++ b/docs/brand/README.md@@ -0,0 +1,17 @@+# KanaWorks_AI brand assets++The files in this folder are the KanaWorks_AI name, logo and mark. They, and the character **Kana**, are © 東京AI映像合同会社 (Tokyo AI Visuals LLC) and are **not** covered by this project's MIT license. The same applies where Kana, the logo and the showcase art appear in other images, such as the banners and the social preview in `docs/assets/`, and to the effects, characters and footage in the promo videos (examples only, not included). You may show them unchanged when you link to or write about this project. Please don't use them as the logo, mascot or branding of your own project or product, and don't edit them.++The code, docs and all other content in this repository stay under the [MIT license](../../LICENSE), commercial use included.++---++**简体中文:** 本目录中的 KanaWorks_AI 名称、logo 和标志,以及 Kana 形象,版权归东京AI映像合同会社所有,**不在**本项目的 MIT 授权范围内。其他图片(如 `docs/assets/` 中的横幅和社交预览图)里出现的 Kana、logo 和展示插画,以及宣传视频里的特效、角色和画面(仅为作例,不包含在仓库中)同样适用。介绍或链接本项目时可以原样展示,但请不要把它们用作你自己项目或产品的 logo、吉祥物或品牌,也不要修改。仓库中的代码、文档和其他内容均为 MIT 授权,可以商用。++**日本語:** このフォルダにある KanaWorks_AI の名称、ロゴ、マーク、およびキャラクター **Kana** の権利は東京AI映像合同会社に帰属し、本プロジェクトの MIT ライセンスの対象**外**です。`docs/assets/` のバナーやソーシャルプレビューなど他の画像に登場する Kana、ロゴ、紹介用イラスト、紹介動画のエフェクト・キャラクター・映像(作例であり、配布物には含まれません)も同様です。本プロジェクトを紹介・リンクする際に、そのままの形で表示するのは構いません。ただし、ご自身のプロジェクトや製品のロゴ、マスコット、ブランドとして使ったり、改変したりしないでください。コード、ドキュメント、その他の内容は MIT ライセンスで、商用利用も可能です。++**한국어:** 이 폴더의 KanaWorks_AI 이름, 로고, 마크와 캐릭터 **Kana**의 권리는 東京AI映像合同会社(Tokyo AI Visuals LLC)에 있으며, 이 프로젝트의 MIT 라이선스 대상이 **아닙니다**. `docs/assets/`의 배너와 소셜 미리보기 등 다른 이미지에 나오는 Kana, 로고, 소개 일러스트, 그리고 홍보 영상의 이펙트·캐릭터·영상(예시이며 저장소에 포함되지 않음)에도 똑같이 적용됩니다. 이 프로젝트를 소개하거나 링크할 때 원래 모습 그대로 보여 주는 것은 괜찮지만, 여러분의 프로젝트나 제품의 로고, 마스코트, 브랜드로 쓰거나 수정하지 마세요. 코드, 문서 및 그 밖의 내용은 MIT 라이선스이며 상업적 사용도 가능합니다.++**Português (Brasil):** o nome KanaWorks_AI, o logo, a marca e a personagem **Kana** são © 東京AI映像合同会社 (Tokyo AI Visuals LLC) e **não** estão cobertos pela licença MIT deste projeto. O mesmo vale para Kana, o logo e a arte de divulgação em outras imagens, como os banners e a prévia social em `docs/assets/`, e para os efeitos, personagens e imagens dos vídeos de divulgação (apenas exemplos, não incluídos). Você pode mostrá-los sem alterações ao divulgar ou linkar este projeto, mas não os use como logo, mascote ou marca do seu próprio projeto ou produto, nem os modifique. O código, a documentação e todo o resto continuam sob a licença MIT, inclusive para uso comercial.++**Español:** el nombre KanaWorks_AI, el logo, la marca y el personaje **Kana** son © 東京AI映像合同会社 (Tokyo AI Visuals LLC) y **no** están cubiertos por la licencia MIT de este proyecto. Lo mismo se aplica a Kana, el logo y la ilustración promocional en otras imágenes, como los banners y la vista previa social de `docs/assets/`, y a los efectos, personajes e imágenes de los vídeos promocionales (solo ejemplos, no incluidos). Puedes mostrarlos sin cambios al enlazar o escribir sobre este proyecto, pero no los uses como logo, mascota o marca de tu propio proyecto o producto, ni los modifiques. El código, la documentación y todo lo demás siguen bajo la licencia MIT, incluido el uso comercial.diff --git a/docs/brand/kanaworks-logo.png b/docs/brand/kanaworks-logo.pngnew file mode 100644index 0000000..aec7d7dBinary files /dev/null and b/docs/brand/kanaworks-logo.png differdiff --git a/docs/brand/kanaworks-mark.png b/docs/brand/kanaworks-mark.pngnew file mode 100644index 0000000..9cf4209Binary files /dev/null and b/docs/brand/kanaworks-mark.png differdiff --git a/skills/effekseer-vfx/SKILL.md b/skills/effekseer-vfx/SKILL.mdindex 68ed9ad..3d8239e 100644--- a/skills/effekseer-vfx/SKILL.md+++ b/skills/effekseer-vfx/SKILL.md@@ -1,10 +1,10 @@---name: effekseer-vfx-description: Author real-time game VFX as code for the Effekseer engine and verify them in a real Godot render. Use when asked to create, edit, review or iterate on Effekseer effects (.efkefc/.efk), game hit, slash, projectile, explosion, beam, charge, magic, buff or shield VFX, combos and finishers driven by a character animation, stylized hard-edged VFX, realistic or kaiju/giant-scale effects, or a VFX library for a Godot game. Covers design briefs, sequences with a blockout gate, reference steal lists, paintover concepts, texture generation prompts, Python recipe code, EffekseerCore compilation, filmstrip review, screen feedback, independent scoring and export.+description: Author real-time game VFX as code for the Effekseer engine and verify them in a real Godot render, and turn image-to-video clips into flipbook skills for Effekseer/Godot or Unity (URP). Use when asked to create, edit, review or iterate on Effekseer effects (.efkefc/.efk), game hit, slash, projectile, explosion, beam, charge, magic, buff or shield VFX, combos and finishers driven by a character animation, stylized hard-edged VFX, realistic or kaiju/giant-scale effects, a VFX library for a Godot game, video-model flipbooks (water columns, fire turning to smoke, looping orbs) or element skills in Unity. Covers design briefs, sequences with a blockout gate, reference steal lists, paintover concepts, texture generation prompts, Python recipe code, EffekseerCore compilation, filmstrip review, screen feedback, independent scoring and export.license: MITcompatibility: Build and render need macOS on Apple silicon or Windows (x64), Godot 4.x and network access for the first setup (Effekseer Core, .NET runtime, Effekseer Godot plugin). Authoring, lint and texture processing run on macOS, Linux or Windows with Python 3.11+.metadata:- version: "0.2.0"+ version: "0.3.0"---# Effekseer VFX@@ -50,6 +50,16 @@ look. Say so plainly: report the work as **not compiled and not render-verified*9. **Independent review.** The author never scores its own effect. Run `vfx review-handoff <ID>`: it writes a complete reviewer brief (images, captured frames, manifest context, rubric, where to save the report, and the path of the `vfx-review` skill installed next to this one) and returns `prompt_file`, `report_file` and the exact submit command. Give that brief, unchanged, to a separate agent that has not seen the recipe: start a subagent with it if your host can, telling it nothing else about the effect; otherwise ask the user to open a new session and paste it. When `report_file` exists, run the returned `vfx review-submit <evidence_id> <report_file> --reviewer <that agent's identifier>` (its subagent ID or name, or the session ID; never `author` or `self`; frames default to the report's `observed_frames`). Never write the report yourself.10. `vfx overview` (no `--ids`: the library baseline), then `vfx effect-verify <ID>`. Only `verified: true` may be reported as done; otherwise list what is missing. If the round limit is reached without a ship verdict, report the unresolved items.+## Three ways to make an effect++Pick per effect; none is required. **Procedural** (everything above): layered primitives in a recipe, Effekseer →+Godot. **Video flipbook**: an image-to-video clip on black becomes a graded sheet (`vfx video-first-frame`,+`video-timeline`, `video-flipbook`, `video-grade`) — the way to get a continuous change of shape that primitives cannot+draw (a column that rises and collapses, fire that boils into smoke, a looping orb). **Combined**: the sheet is the+body layer of a recipe (`video_body(...)`) and primitives add the flash, sparks, rings, cracks and decals. Sheets play in+Effekseer/Godot or, through `vfx unity-install` / `unity-export`, in Unity (URP) as data-driven element skills. Read+[video-flipbook](references/video-flipbook.md) before any of it.+## Making a combo or a skill with several beatsWhen several effects fire on the beats of one animation (a laser chain ending on a finisher), work on them as a@@ -67,7 +77,8 @@ record it in `cut`. Each effect in the sequence still has its own brief, recipe- The body changes shape (dissolve, sweep, UV distortion, flipbook, re-struck shapes); it never only scales and fades. Particles ease out (fast, then slow).- Elements differ in at least three of shape, motion, rhythm, material and secondary motion — never a recolour.- Do not draw complex painted shapes with Python. If no image generation tool is available, write the prompt into `vfx/texture_prompts.json` and ask the user for the image.-- Keep generated originals in `vfx/textures/generated/` and write processed copies to `vfx/textures/processed/`; record every prompt.+- Keep generated originals in `vfx/textures/generated/` and write processed copies to `vfx/textures/processed/`; record every prompt (`vfx video-flipbook --prompt-file` records clips in `vfx/video_prompts.json`).+- A video clip is a body, never a finished effect: the engine adds the contact flash, secondary motion and ground. Generate it with a first and a last frame on pure black, skip opening white flashes, grade every sheet of one element with the same ramp, and no hit-stop while it plays (hit-stop freezes the flipbook).- Units: recipe timing in 60 FPS frames, F-curves in percent of life, manifest duration/peak in seconds, Godot API rotation in radians.- Write recipes at the Lab's character scale; for a larger world declare `scale` instead of hand-scaling numbers ([scale](references/scale.md)). Frames in briefs and reviews are the built, scaled timeline.- Every effect declares `delivery`; a projectile needs a paired impact effect that points back to it.@@ -82,6 +93,7 @@ record it in `cut`. Each effect in the sequence still has its own brief, recipe| Task | Also read ||---|---|| new painted texture, flipbook, texture problem | [textures.md](references/textures.md) |+| image-to-video clip → flipbook, `video_body`, combined effects, Unity (URP) skills | [video-flipbook.md](references/video-flipbook.md) || slash, projectile, charge, aura, anything that travels | [motion.md](references/motion.md) || shield, pillar, boss, status, volumes, occlusion | [shapes.md](references/shapes.md) || matching a reference video | [reference.md](references/reference.md) |diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/CreateElementSkill.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/CreateElementSkill.csnew file mode 100644index 0000000..ae2f702--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/CreateElementSkill.cs@@ -0,0 +1,269 @@+using System;+using System.IO;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.Rendering;++namespace VfxSkill.EditorTools+{+ /// <summary>+ /// What one skill is made of. The window edits one; agents write the same fields as JSON and run+ /// <c>Unity -batchmode -projectPath P -executeMethod VfxSkill.EditorTools.CreateElementSkill.FromCommandLine -vfxSpec spec.json -quit</c>.+ /// Texture fields are asset paths (Assets/VfxSkill/Flipbooks/...); enum fields are their names.+ /// </summary>+ [Serializable]+ public class SkillSpec+ {+ public string name = "Fire";+ public Color theme = new Color(1f, 0.5f, 0.12f), dark = new Color(0.32f, 0.05f, 0.03f);+ public string delivery = nameof(DeliveryType.Projectile);+ public string orb, body, decal;+ public Vector2Int orbGrid = new Vector2Int(1, 1), bodyGrid = new Vector2Int(8, 8);+ public int orbFps = 24;+ [Tooltip("Eruption only: stretch the column sideways so it reads wider than the target")] public float columnWidthScale = 1.6f;+ public string extra = nameof(ImpactExtra.None), contact = nameof(ContactAccent.Star), trail = nameof(TrailStyle.EmberSmoke), linger = nameof(LingerStyle.Smolder);++ public T Enum<T>(string value, T fallback) where T : struct => System.Enum.TryParse(value, true, out T v) ? v : fallback;+ }++ /// <summary>+ /// Turns processed sheets into a playable skill: materials (orb, body flipbook, ground decal, contact star / ring,+ /// mesh shell) plus an ElementProfile asset with defaults for the chosen delivery. Everything else is tuned on the+ /// profile afterwards; only a new kind of motion needs code (a new enum value in ElementProfile and its case in+ /// ElementSkill).+ /// </summary>+ public class CreateElementSkill : EditorWindow+ {+ SkillSpec spec = new SkillSpec();+ Texture2D orb, body, decal;++ [MenuItem("VFX Skill/2. Create element skill from flipbooks")]+ static void Open() => GetWindow<CreateElementSkill>("Create element skill").minSize = new Vector2(420, 520);++ void OnGUI()+ {+ EditorGUILayout.HelpBox("Sheets come from `vfx video-flipbook` + `vfx video-grade` (copy them in with `vfx unity-export`, " ++ "which also writes the grid). The body flipbook is the effect's main shape; the orb is what flies or charges.", MessageType.Info);+ spec.name = EditorGUILayout.TextField("Name", spec.name);+ spec.theme = EditorGUILayout.ColorField("Theme colour", spec.theme);+ spec.dark = EditorGUILayout.ColorField("Dark rim colour", spec.dark);+ var delivery = (DeliveryType)EditorGUILayout.EnumPopup(new GUIContent("Delivery", "Projectile flies; Instant connects (lightning); Eruption bursts from the ground under the target"),+ spec.Enum(spec.delivery, DeliveryType.Projectile));+ spec.delivery = delivery.ToString();+ EditorGUILayout.Space();+ orb = Field("Orb (projectile / palm charge)", orb, ref spec.orbGrid);+ spec.orbFps = EditorGUILayout.IntSlider(new GUIContent("Orb loop fps", "Used when the orb is a looping flipbook (grid > 1×1)"), spec.orbFps, 6, 60);+ body = Field(delivery == DeliveryType.Eruption ? "Column flipbook (body)" : "Impact flipbook (body)", body, ref spec.bodyGrid);+ if (delivery == DeliveryType.Eruption)+ spec.columnWidthScale = EditorGUILayout.Slider(new GUIContent("Column width scale", "Stretch the column sideways so it reads wider than the target"), spec.columnWidthScale, 1f, 2.5f);+ decal = (Texture2D)EditorGUILayout.ObjectField("Ground decal (optional)", decal, typeof(Texture2D), false);+ EditorGUILayout.Space();+ spec.extra = EditorGUILayout.EnumPopup("Impact extra (mesh shell)", spec.Enum(spec.extra, ImpactExtra.None)).ToString();+ spec.contact = EditorGUILayout.EnumPopup("Contact accent", spec.Enum(spec.contact, ContactAccent.Star)).ToString();+ spec.trail = EditorGUILayout.EnumPopup("Trail", spec.Enum(spec.trail, TrailStyle.EmberSmoke)).ToString();+ spec.linger = EditorGUILayout.EnumPopup("Linger", spec.Enum(spec.linger, LingerStyle.Smolder)).ToString();+ EditorGUILayout.Space();+ using (new EditorGUI.DisabledScope(!orb || !body || string.IsNullOrWhiteSpace(spec.name)))+ if (GUILayout.Button("Create materials + ElementProfile", GUILayout.Height(32)))+ {+ spec.orb = AssetDatabase.GetAssetPath(orb); spec.body = AssetDatabase.GetAssetPath(body); spec.decal = decal ? AssetDatabase.GetAssetPath(decal) : null;+ var p = Create(spec);+ Selection.activeObject = p; EditorGUIUtility.PingObject(p);+ }+ }++ Texture2D Field(string label, Texture2D tex, ref Vector2Int grid)+ {+ var t = (Texture2D)EditorGUILayout.ObjectField(label, tex, typeof(Texture2D), false);+ if (t && t != tex && TryReadGrid(AssetDatabase.GetAssetPath(t), out var g)) grid = g; // the sidecar from `vfx unity-export` knows the grid+ grid = EditorGUILayout.Vector2IntField(" grid (cols, rows)", grid);+ grid = Vector2Int.Max(grid, Vector2Int.one);+ return t;+ }++ static bool TryReadGrid(string texturePath, out Vector2Int grid)+ {+ grid = Vector2Int.one;+ string json = Path.ChangeExtension(texturePath, ".flipbook.json");+ if (string.IsNullOrEmpty(texturePath) || !File.Exists(json)) return false;+ var data = JsonUtility.FromJson<Sidecar>(File.ReadAllText(json));+ if (data?.grid == null || data.grid.Length < 2) return false;+ grid = new Vector2Int(data.grid[0], data.grid[1]);+ return true;+ }++ [Serializable] class Sidecar { public int[] grid; public int[] cell; public float bottom_inset; }++ static bool TryReadSidecar(string texturePath, out Sidecar data)+ {+ data = null;+ string json = string.IsNullOrEmpty(texturePath) ? null : Path.ChangeExtension(texturePath, ".flipbook.json");+ if (json == null || !File.Exists(json)) return false;+ data = JsonUtility.FromJson<Sidecar>(File.ReadAllText(json));+ return data != null;+ }++ /// <summary>Starting values for a new profile, from skills that passed review: a video body is already a full+ /// effect, so it stays smaller than the target (it must not hide the hit reaction), rises out of the face, and gets+ /// no hit-stop (hit-stop freezes the flipbook's first cells into a flat card).</summary>+ static void Defaults(ElementProfile p, DeliveryType delivery, SkillSpec spec)+ {+ p.flashSize = 1.1f; p.sparkCount = 16; p.decalSize = 1.8f; p.decalLife = 2.3f; p.lingerTime = 1.3f;+ if (delivery == DeliveryType.Eruption)+ {+ p.castSpeed = 1.1f; p.chargeSize = 0.3f; p.flightSize = 0.5f; p.speed = 12f; p.gravityScale = 0.5f; p.lift = 0.3f;+ p.columnHeight = 4f; p.columnLift = 1.5f; p.columnLife = 1.4f; p.columnBehind = 0.35f; p.columnHoldEnd = 0.5f;+ p.impactLife = 1f; p.lightIntensity = 3f; p.lightRange = 2.6f; p.decalSize = 2.4f; p.decalLife = 2.4f;+ p.hitStop = 0.06f; p.shake = 0.16f; p.shakeTime = 0.3f; p.knockback = 1.3f;+ }+ else+ {+ p.castSpeed = 0.85f; p.chargeSize = 0.4f; p.flightSize = 0.85f; p.speed = 14f; p.gravityScale = 0.02f; p.lift = 0f;+ p.spinDegPerSec = spec.orbGrid.x * spec.orbGrid.y > 1 ? 0f : 500f; // a looping orb sheet already churns; spinning it turns flames upside down+ p.impactSize = 1.8f; p.impactLife = 2f; p.impactRise = 1.1f; p.impactOffset = new Vector3(0, 0.15f, -0.2f); p.aimHeight = -0.3f;+ p.lightIntensity = 6f; p.lightRange = 3.2f; p.reactTime = 1.5f;+ p.cutTrailOnHit = spec.Enum(spec.trail, TrailStyle.EmberSmoke) == TrailStyle.EmberSmoke;+ p.hitStop = 0f; p.shake = 0.24f; p.shakeTime = 0.32f; p.knockback = 1.1f;+ }+ }++ /// <summary>Batch entry point: reads the SkillSpec JSON named by -vfxSpec, creates the skill, then rebuilds the demo scene.</summary>+ public static void FromCommandLine()+ {+ var args = Environment.GetCommandLineArgs();+ int i = Array.IndexOf(args, "-vfxSpec");+ if (i < 0 || i + 1 >= args.Length) throw new ArgumentException("pass -vfxSpec <spec.json>");+ string specPath = Path.GetFullPath(args[i + 1]); // relative paths resolve against the Unity project, not the caller+ if (!File.Exists(specPath)) throw new FileNotFoundException($"-vfxSpec {specPath} not found (pass an absolute path)");+ var spec = JsonUtility.FromJson<SkillSpec>(File.ReadAllText(specPath));+ var p = Create(spec);+ string issues = p.Validate();+ if (issues.Length > 0) throw new InvalidOperationException($"{AssetDatabase.GetAssetPath(p)}: {issues}");+ DemoSceneBuilder.Build();+ }++ public static ElementProfile Create(SkillSpec spec)+ {+ var orb = AssetDatabase.LoadAssetAtPath<Texture2D>(spec.orb);+ var body = AssetDatabase.LoadAssetAtPath<Texture2D>(spec.body);+ var decal = string.IsNullOrEmpty(spec.decal) ? null : AssetDatabase.LoadAssetAtPath<Texture2D>(spec.decal);+ if (!orb || !body) throw new FileNotFoundException($"orb '{spec.orb}' and body '{spec.body}' must be texture assets");+ if (TryReadGrid(spec.orb, out var og)) spec.orbGrid = og;+ if (TryReadGrid(spec.body, out var bg)) spec.bodyGrid = bg;+ if (!AssetDatabase.LoadAssetAtPath<Material>(VfxSkillSetup.SharedDir + "M_Spark.mat")) VfxSkillSetup.Setup();++ var delivery = spec.Enum(spec.delivery, DeliveryType.Projectile);+ Color theme = spec.theme, dark = spec.dark;+ string safe = string.Concat(spec.name.Split(Path.GetInvalidFileNameChars())).Replace(' ', '_');+ string dir = VfxSkillSetup.SkillDir + safe + "/";+ VfxSkillSetup.Folder(dir);+ var painted = Shader.Find("VfxSkill/PaintedFX");+ Color core = Color.Lerp(theme, Color.white, 0.85f);++ var orbMat = VfxSkillSetup.Painted(dir + $"M_{safe}_Orb.mat", painted, orb, 0.004f, 0.3f, false);+ // a looping orb sheet animates itself; a single image must switch it off again (the material may be re-created)+ orbMat.SetVector("_Flip", spec.orbGrid.x * spec.orbGrid.y > 1 ? new Vector4(spec.orbGrid.x, spec.orbGrid.y, spec.orbFps, 0) : new Vector4(1, 1, 0, 0));+ if (spec.orbGrid.x * spec.orbGrid.y > 1) orbMat.SetFloat("_Distort", 0.002f);++ bool eruption = delivery == DeliveryType.Eruption;+ var bodyMat = VfxSkillSetup.Painted(dir + $"M_{safe}_Body.mat", painted, body, 0f, 0.2f, true);+ bodyMat.SetVector("_Tiles", new Vector4(spec.bodyGrid.x, spec.bodyGrid.y, 0, 0));+ bodyMat.SetFloat("_ErodeNoise", 0.25f);+ bodyMat.SetFloat("_CamPush", eruption ? 0f : 0.55f); // impacts float to the target's surface; a column stands on the ground behind it+ if (!eruption) bodyMat.SetVector("_Grow", new Vector4(0.3f, 0.07f, 0, 0)); // video bursts start full size: snap up from 30 %++ var decalMat = VfxSkillSetup.Painted(dir + $"M_{safe}_Decal.mat", painted, decal ? decal : VfxSkillSetup.Tex("T_Decal"), 0.002f, 0.35f, false);+ decalMat.SetFloat("_ErodeNoise", 0.6f); decalMat.SetFloat("_AlphaBoost", 1.2f); VfxSkillSetup.Soft(decalMat, 0);+ if (!decal) decalMat.SetColor("_Tint", Color.Lerp(dark, Color.black, 0.3f) * 1.4f);+ EditorUtility.SetDirty(orbMat); EditorUtility.SetDirty(bodyMat); EditorUtility.SetDirty(decalMat); // edited after Mat() saved them++ var extra = spec.Enum(spec.extra, ImpactExtra.None);+ if (eruption && extra == ImpactExtra.None) extra = ImpactExtra.CrownSplash;+ var star = VfxSkillSetup.Shell(dir + $"M_{safe}_Star.mat", "T_MaskHitStar", Color.white, theme, dark);+ var ring = VfxSkillSetup.Shell(dir + $"M_{safe}_Ring.mat", "T_MaskRing", Color.white, Color.Lerp(theme, Color.white, 0.6f), theme, 0.08f, 0.06f, 1.01f, 0.35f);+ bool funnel = extra == ImpactExtra.Funnel;+ string shellMask = funnel ? "T_MaskRibbon" : extra == ImpactExtra.Arcs || delivery == DeliveryType.Instant ? "T_MaskBoltStrip" : "T_MaskCrown";+ var shell = VfxSkillSetup.Shell(dir + $"M_{safe}_Shell.mat", shellMask, core, theme, dark, 0.06f, 0.05f, 0.5f, 0.2f,+ funnel ? new Vector2(-0.6f, 0) : Vector2.zero, funnel ? 1f : 0f);+ var glow = VfxSkillSetup.Particle(dir + $"M_{safe}_Glow.mat", Shader.Find("VfxSkill/ParticleSoft"), "T_MaskBoltStrip", new Color(theme.r, theme.g, theme.b, 0.42f), false, 0f);++ string path = dir + $"EP_{safe}.asset";+ var p = AssetDatabase.LoadAssetAtPath<ElementProfile>(path);+ bool fresh = !p;+ if (fresh) p = CreateInstance<ElementProfile>();+ if (fresh) Defaults(p, delivery, spec); // never overwrite numbers someone already tuned+ p.displayName = spec.name; p.theme = theme; p.dark = dark; p.delivery = delivery;+ p.orb = orbMat; p.impact = bodyMat; p.decal = decalMat; p.star = star; p.ring = ring; p.shell = shell; p.glow = glow;+ p.extra = extra; p.contact = spec.Enum(spec.contact, ContactAccent.Star);+ p.trail = spec.Enum(spec.trail, TrailStyle.EmberSmoke); p.linger = spec.Enum(spec.linger, LingerStyle.Smolder);+ if (eruption)+ {+ p.columnAspect = body.width / (float)spec.bodyGrid.x / (body.height / (float)spec.bodyGrid.y) * spec.columnWidthScale;+ if (TryReadSidecar(spec.body, out var side) && side.bottom_inset > 0) p.columnRootInset = side.bottom_inset; // root sits on the ground, not above it+ }+ if (fresh) AssetDatabase.CreateAsset(p, path); else EditorUtility.SetDirty(p);+ AssetDatabase.SaveAssets();+ string issues = p.Validate();+ Debug.Log($"[VfxSkill] created {path}" + (issues.Length > 0 ? " — check: " + issues : ""));+ return p;+ }+ }++ /// <summary>A throwaway stage to judge skills on: ground, light, a caster and a target, and every ElementProfile under Assets/VfxSkill/Skills.</summary>+ public static class DemoSceneBuilder+ {+ public const string ScenePath = VfxSkillSetup.Root + "/Demo/VfxSkillDemo.unity";++ [MenuItem("VFX Skill/3. Build demo scene")]+ public static void Build()+ {+ if (!Application.isBatchMode && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) return;+ var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);+ var lit = Shader.Find("Universal Render Pipeline/Lit");+ var sun = new GameObject("Sun").AddComponent<Light>(); sun.type = LightType.Directional; sun.shadows = LightShadows.Soft;+ sun.transform.rotation = Quaternion.Euler(50, -30, 0);+ RenderSettings.ambientMode = AmbientMode.Trilight;+ RenderSettings.ambientSkyColor = new Color(0.62f, 0.72f, 0.9f); RenderSettings.ambientEquatorColor = new Color(0.5f, 0.52f, 0.55f); RenderSettings.ambientGroundColor = new Color(0.3f, 0.28f, 0.26f);+ var ground = GameObject.CreatePrimitive(PrimitiveType.Plane); ground.name = "Ground"; ground.transform.localScale = Vector3.one * 10;+ ground.GetComponent<Renderer>().sharedMaterial = Lit(lit, new Color(0.42f, 0.45f, 0.42f), "M_Ground");++ var caster = new GameObject("Caster"); // root on the ground: skills measure the hand and aim from the feet+ Capsule("Visual", Vector3.zero, Lit(lit, new Color(0.95f, 0.75f, 0.25f), "M_Caster")).transform.SetParent(caster.transform, false);+ var target = new GameObject("Target"); target.transform.SetPositionAndRotation(new Vector3(0, 0, 4.5f), Quaternion.Euler(0, 180, 0));+ var tv = Capsule("Visual", Vector3.zero, Lit(lit, new Color(0.92f, 0.92f, 0.95f), "M_Target")); tv.transform.SetParent(target.transform, false);+ target.AddComponent<DemoTarget>().visual = tv.transform;++ var cam = new GameObject("Main Camera").AddComponent<Camera>(); cam.tag = "MainCamera";+ cam.transform.position = new Vector3(-5.6f, 1.7f, 2.6f); cam.transform.LookAt(new Vector3(0, 1.1f, 2.4f)); cam.fieldOfView = 50;+ var fx = new GameObject("ElementFX").AddComponent<ElementFX>(); fx.groundY = 0;++ var demo = caster.AddComponent<SkillDemo>();+ foreach (var guid in AssetDatabase.FindAssets("t:ElementProfile", new[] { VfxSkillSetup.SkillDir.TrimEnd('/') }))+ {+ var p = AssetDatabase.LoadAssetAtPath<ElementProfile>(AssetDatabase.GUIDToAssetPath(guid));+ var s = caster.AddComponent<ElementSkill>(); s.profile = p; s.target = target.transform; s.targetOffset = new Vector3(0, 1f, 0); s.targetRadius = 0.5f;+ demo.skills.Add(s);+ }+ VfxSkillSetup.Folder(Path.GetDirectoryName(ScenePath));+ EditorSceneManager.SaveScene(scene, ScenePath);+ Debug.Log($"[VfxSkill] {ScenePath} with {demo.skills.Count} skill(s). Enter Play mode: skills cast in turn; click a button (or 1–9 with the legacy Input Manager) to pick one.");+ }++ // Saved as assets so the scene keeps its colours after reopening (in-memory materials are lost with the scene).+ static Material Lit(Shader lit, Color c, string name)+ {+ string path = VfxSkillSetup.Root + "/Demo/" + name + ".mat";+ VfxSkillSetup.Folder(VfxSkillSetup.Root + "/Demo");+ return VfxSkillSetup.Mat(path, lit, m => m.SetColor("_BaseColor", c));+ }++ static GameObject Capsule(string name, Vector3 pos, Material mat)+ {+ var go = GameObject.CreatePrimitive(PrimitiveType.Capsule); go.name = name; go.transform.position = pos + Vector3.up;+ UnityEngine.Object.DestroyImmediate(go.GetComponent<Collider>());+ go.GetComponent<Renderer>().sharedMaterial = mat;+ return go;+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkill.Editor.asmdef b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkill.Editor.asmdefnew file mode 100644index 0000000..7c5bd3a--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkill.Editor.asmdef@@ -0,0 +1,13 @@+{+ "name": "VfxSkill.Editor",+ "rootNamespace": "VfxSkill.EditorTools",+ "references": [+ "VfxSkill.Runtime",+ "Unity.RenderPipelines.Universal.Runtime",+ "Unity.RenderPipelines.Core.Runtime"+ ],+ "includePlatforms": [+ "Editor"+ ],+ "autoReferenced": true+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkillSetup.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkillSetup.csnew file mode 100644index 0000000..c78a85c--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Editor/VfxSkillSetup.cs@@ -0,0 +1,155 @@+using System.IO;+using UnityEditor;+using UnityEngine;+using UnityEngine.Rendering;+using UnityEngine.Rendering.Universal;++namespace VfxSkill.EditorTools+{+ /// <summary>+ /// Shared materials every skill uses (sparks, contact flash, neutral smoke, droplets) and the URP depth texture+ /// soft particles need. Textures come from `vfx unity-install`, which writes procedural sheets and masks into+ /// Assets/VfxSkill/Generated/Textures; nothing here is painted.+ /// </summary>+ public static class VfxSkillSetup+ {+ public const string Root = "Assets/VfxSkill";+ public const string TexDir = Root + "/Generated/Textures/";+ public const string SharedDir = Root + "/Resources/VfxSkill/"; // ElementFX loads these by name at run time+ public const string SkillDir = Root + "/Skills/";++ [MenuItem("VFX Skill/1. Setup shared materials")]+ public static void Setup()+ {+ Folder(SharedDir); Folder(SkillDir);+ var part = Shader.Find("VfxSkill/ParticleSoft");+ var painted = Shader.Find("VfxSkill/PaintedFX");+ if (!part || !painted) { Debug.LogError("[VfxSkill] shaders not found: is the package installed under Packages/?"); return; }+ Particle(SharedDir + "M_Spark.mat", part, "T_Flash", Color.white, false, 0.05f);+ Particle(SharedDir + "M_Flash.mat", part, "T_Flash", new Color(1f, 1.2f, 1.5f, 1), true, 0.1f);+ Painted(SharedDir + "M_Smoke.mat", painted, "T_Smoke_2x2", 0.004f, 0.35f, true);+ Painted(SharedDir + "M_Drop.mat", painted, "T_Drop_2x2", 0f, 0.2f, true);+ EnableDepthTexture();+ AssetDatabase.SaveAssets();+ Debug.Log("[VfxSkill] shared materials ready in " + SharedDir);+ }++ /// <summary>Create an asset folder (and its parents) the AssetDatabase knows about, so CreateAsset can write into it.</summary>+ public static void Folder(string assetDir)+ {+ assetDir = assetDir.TrimEnd('/');+ if (AssetDatabase.IsValidFolder(assetDir)) return;+ string parent = Path.GetDirectoryName(assetDir).Replace('\\', '/');+ Folder(parent);+ AssetDatabase.CreateFolder(parent, Path.GetFileName(assetDir));+ }++ public static Texture2D Tex(string name)+ {+ var t = AssetDatabase.LoadAssetAtPath<Texture2D>(TexDir + name + ".png");+ if (!t) Debug.LogWarning("[VfxSkill] missing generated texture " + name + " — run `vfx unity-install <project>` again");+ return t;+ }++ /// <summary>Create (or refresh) a material at `path`. Properties are set before CreateAsset: a material saved+ /// first and edited afterwards can lose its textures on the next asset operation.</summary>+ public static Material Mat(string path, Shader sh, System.Action<Material> fill)+ {+ var m = AssetDatabase.LoadAssetAtPath<Material>(path);+ bool fresh = !m;+ if (fresh) m = new Material(sh); else m.shader = sh;+ fill(m);+ if (fresh) AssetDatabase.CreateAsset(m, path); else EditorUtility.SetDirty(m);+ return m;+ }++ public static void Soft(Material m, float fade)+ {+ m.SetFloat("_SoftFade", Mathf.Max(fade, 0.0001f));+ bool on = fade > 0.001f;+ m.SetFloat("_SoftOn", on ? 1 : 0);+ if (on) m.EnableKeyword("_SOFTPARTICLES"); else m.DisableKeyword("_SOFTPARTICLES");+ }++ public static Material Particle(string path, Shader sh, string tex, Color c, bool additive, float soft) => Mat(path, sh, m =>+ {+ m.SetTexture("_MainTex", Tex(tex));+ m.SetColor("_Color", c);+ Soft(m, soft);+ m.SetFloat("_SrcBlend", (float)(additive ? BlendMode.One : BlendMode.SrcAlpha));+ m.SetFloat("_DstBlend", (float)(additive ? BlendMode.One : BlendMode.OneMinusSrcAlpha));+ });++ public static Material Painted(string path, Shader sh, Texture2D tex, float distort, float soft, bool particle) => Mat(path, sh, m =>+ {+ m.SetTexture("_MainTex", tex);+ m.SetTexture("_NoiseTex", Tex("T_FlowNoise"));+ m.SetFloat("_Distort", distort);+ m.SetFloat("_Soft", soft);+ Soft(m, particle ? 0.12f : 0.01f);+ m.SetColor("_Tint", particle ? new Color(1.0f, 1.05f, 1.1f, 1) : new Color(1.1f, 1.12f, 1.15f, 1));+ });++ public static Material Painted(string path, Shader sh, string tex, float distort, float soft, bool particle) => Painted(path, sh, Tex(tex), distort, soft, particle);++ /// <summary>A StylizedShell material: a greyscale distance mask drawn as core / body / dark rim, eroded by a threshold.</summary>+ public static Material Shell(string path, string mask, Color core, Color body, Color rim, float cutoff = 0.06f, float rimWidth = 0.05f,+ float coreLevel = 0.5f, float noise = 0.15f, Vector2 scroll = default, float erodeDir = 0f) =>+ Mat(path, Shader.Find("VfxSkill/StylizedShell"), m =>+ {+ m.SetTexture("_MainTex", Tex(mask));+ m.SetTexture("_NoiseTex", Tex("T_FlowNoise"));+ m.SetColor("_Core", core); m.SetColor("_Body", body); m.SetColor("_Rim", rim);+ m.SetFloat("_Cutoff", cutoff); m.SetFloat("_RimWidth", rimWidth); m.SetFloat("_CoreLevel", coreLevel);+ m.SetFloat("_NoiseAmt", noise); m.SetVector("_Scroll", new Vector4(scroll.x, scroll.y, 0, 0));+ m.SetFloat("_ErodeDir", erodeDir);+ Soft(m, 0f);+ });++ /// <summary>Soft particles need the camera depth texture: turn it on for every URP asset the project's quality levels+ /// use (a separate mobile asset without it would fade soft particles out on device), and nothing else.</summary>+ static void EnableDepthTexture()+ {+ var assets = new System.Collections.Generic.HashSet<UniversalRenderPipelineAsset>();+ if (GraphicsSettings.defaultRenderPipeline is UniversalRenderPipelineAsset d) assets.Add(d);+ for (int i = 0; i < QualitySettings.count; i++)+ if (QualitySettings.GetRenderPipelineAssetAt(i) is UniversalRenderPipelineAsset q) assets.Add(q);+ foreach (var a in assets)+ if (!a.supportsCameraDepthTexture) { a.supportsCameraDepthTexture = true; EditorUtility.SetDirty(a); Debug.Log("[VfxSkill] depth texture enabled on " + a.name); }+ }+ }++ /// <summary>+ /// Import rules for the textures this package uses. Flipbook sheets (Assets/VfxSkill/Flipbooks/, or any texture+ /// with a .flipbook.json sidecar): no mipmaps (a 6 px gutter does not survive low mips), clamped, never rescaled to a+ /// power of two (8×5 and 8×7 sheets would shift every cell), up to 4096 on desktop and 2048 on mobile.+ /// Generated masks are linear data; the rest are colour.+ /// </summary>+ public class VfxSkillTextureRules : AssetPostprocessor+ {+ void OnPreprocessTexture()+ {+ bool flipbook = assetPath.Contains("/VfxSkill/Flipbooks/") || File.Exists(Path.ChangeExtension(assetPath, ".flipbook.json"));+ bool generated = assetPath.StartsWith(VfxSkillSetup.TexDir);+ if (!flipbook && !generated) return;+ var ti = (TextureImporter)assetImporter;+ string n = Path.GetFileNameWithoutExtension(assetPath);+ bool mask = generated && n.StartsWith("T_Mask");+ ti.textureType = TextureImporterType.Default;+ ti.sRGBTexture = !mask && n != "T_FlowNoise";+ ti.alphaIsTransparency = !mask;+ ti.alphaSource = TextureImporterAlphaSource.FromInput;+ ti.wrapMode = n == "T_FlowNoise" || n == "T_MaskRibbon" || n == "T_MaskCrown" ? TextureWrapMode.Repeat : TextureWrapMode.Clamp;+ ti.mipmapEnabled = !flipbook;+ if (flipbook) ti.npotScale = TextureImporterNPOTScale.None;+ ti.maxTextureSize = flipbook ? 4096 : 2048;+ ti.textureCompression = TextureImporterCompression.CompressedHQ;+ foreach (var platform in new[] { "Android", "iPhone" })+ ti.SetPlatformTextureSettings(new TextureImporterPlatformSettings+ {+ name = platform, overridden = true, maxTextureSize = flipbook ? 2048 : 1024,+ format = TextureImporterFormat.ASTC_6x6, compressionQuality = 50,+ });+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/BoltPath.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/BoltPath.csnew file mode 100644index 0000000..a1e568c--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/BoltPath.cs@@ -0,0 +1,102 @@+using System.Collections.Generic;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Procedural lightning: midpoint displacement builds an uneven jagged trunk plus 2–3 tapering forks, output as a camera-facing strip mesh.+ /// Across the strip v ∈ [0,1] (with the ridge mask of T_MaskBoltStrip, StylizedShell yields a white core + violet glow + dark rim);+ /// along the strip u follows the path. Every call makes a new path (each strike has a different shape).+ /// </summary>+ public static class BoltPath+ {+ static readonly List<Vector3> pts = new List<Vector3>();+ static readonly List<float> wid = new List<float>();+ static readonly List<Vector3> verts = new List<Vector3>();+ static readonly List<Vector2> uvs = new List<Vector2>(), uv2s = new List<Vector2>();+ static readonly List<Color> cols = new List<Color>();+ static readonly List<int> tris = new List<int>();++ static readonly List<(List<Vector3> pts, float width, float taper)> lines = new List<(List<Vector3>, float, float)>();++ /// <summary>+ /// Writes a bolt from a to b into mesh (hard-edged white-core strip); if glow is not null, the same path is also written as a soft strip glowScale times wider (for the glow).+ /// width: trunk width (m); forks: fork count (forks are 0.35× the trunk width); jag: jaggedness (fraction of length).+ /// </summary>+ public static void Build(Mesh mesh, Vector3 a, Vector3 b, Vector3 camPos, float width, int forks, float jag = 0.12f, int depth = 5, Mesh glow = null, float glowScale = 3.2f)+ {+ lines.Clear();+ var main = Jagged(a, b, jag, depth);+ lines.Add((main, width, 1f));+ for (int f = 0; f < forks; f++)+ {+ int i = Random.Range(main.Count / 5, main.Count * 3 / 4);+ Vector3 dir = (b - a);+ float len = dir.magnitude * Random.Range(0.15f, 0.32f);+ Vector3 side = Vector3.Cross(dir, Random.onUnitSphere).normalized;+ Vector3 fd = Vector3.Slerp(dir.normalized, side, Random.Range(0.35f, 0.6f)).normalized;+ lines.Add((Jagged(main[i], main[i] + fd * len, jag * 1.2f, Mathf.Max(1, depth - 2)), width * 0.35f, 0f));+ }+ Write(mesh, camPos, 1f);+ if (glow) Write(glow, camPos, glowScale);+ }++ static void Write(Mesh mesh, Vector3 camPos, float scale)+ {+ verts.Clear(); uvs.Clear(); uv2s.Clear(); cols.Clear(); tris.Clear();+ Random.State st = Random.state; Random.InitState(1234); // both strips get the same width jitter+ foreach (var (pts, w, taper) in lines) Strip(pts, w * scale, taper, camPos);+ Random.state = st;+ mesh.Clear();+ mesh.SetVertices(verts); mesh.SetUVs(0, uvs); mesh.SetUVs(1, uv2s); mesh.SetColors(cols); mesh.SetTriangles(tris, 0);+ mesh.RecalculateBounds();+ }++ static List<Vector3> Jagged(Vector3 a, Vector3 b, float jag, int depth)+ {+ var list = new List<Vector3> { a, b };+ float amp = (b - a).magnitude * jag;+ Vector3 axis = (b - a).normalized;+ for (int d = 0; d < depth; d++)+ {+ var next = new List<Vector3>(list.Count * 2);+ for (int i = 0; i < list.Count - 1; i++)+ {+ next.Add(list[i]);+ float t = Random.Range(0.3f, 0.7f); // uneven segment split+ Vector3 off = Vector3.ProjectOnPlane(Random.insideUnitSphere, axis) * amp;+ next.Add(Vector3.Lerp(list[i], list[i + 1], t) + off);+ }+ next.Add(list[list.Count - 1]);+ list = next; amp *= 0.55f;+ }+ return list;+ }++ // Taper: startTaper=1 tapers both ends (trunk), 0 tapers only the tip (forks grow out of the trunk)+ static void Strip(List<Vector3> p, float width, float startTaper, Vector3 camPos)+ {+ int baseIdx = verts.Count, n = p.Count;+ for (int i = 0; i < n; i++)+ {+ float u = (float)i / (n - 1);+ Vector3 tan = (p[Mathf.Min(i + 1, n - 1)] - p[Mathf.Max(i - 1, 0)]).normalized;+ Vector3 toCam = (camPos - p[i]).normalized;+ Vector3 side = Vector3.Cross(tan, toCam).normalized;+ float taper = Mathf.Lerp(1f, Mathf.SmoothStep(0, 1, u / 0.15f), startTaper) * Mathf.SmoothStep(0, 1, (1 - u) / 0.3f);+ float w = width * (0.35f + 0.65f * taper) * Random.Range(0.8f, 1.15f);+ verts.Add(p[i] - side * w * 0.5f); verts.Add(p[i] + side * w * 0.5f);+ uvs.Add(new Vector2(u, 0)); uvs.Add(new Vector2(u, 1));+ uv2s.Add(new Vector2(u, u)); uv2s.Add(new Vector2(u, u));+ var c = new Color(1, 1, 1, Mathf.Lerp(0.55f, 1f, taper)); // vertex alpha: tips erode and thin out earlier+ cols.Add(c); cols.Add(c);+ if (i < n - 1)+ {+ int k = baseIdx + i * 2;+ tris.Add(k); tris.Add(k + 2); tris.Add(k + 1);+ tris.Add(k + 1); tris.Add(k + 2); tris.Add(k + 3);+ }+ }+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/CastDriver.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/CastDriver.csnew file mode 100644index 0000000..cebc591--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/CastDriver.cs@@ -0,0 +1,87 @@+using System;+using System.Collections;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Cast animation adapter: Legacy Animation (e.g. a GLB imported via glTFast) or Animator (Mecanim).+ /// Release moment:+ /// · Legacy: if the cast clip has an Animation Event with function name "Release", its time is used, otherwise releaseTime; converted to seconds via castStart / speed.+ /// · Animator: the cast state's clip must have a "Release" event. The skill waits for it (ReleasedSince) and falls back to releaseTime / speed only if it never arrives.+ /// The Animator's overall speed is changed only during the cast and restored after release.+ /// </summary>+ public class CastDriver : MonoBehaviour+ {+ [Header("Legacy Animation (GLB)")]+ public Animation legacy;+ public string castClip = "cast_a_spell";+ public string idleClip = "idle";+ [Header("Animator (Mecanim)")]+ public Animator animator;+ public string castTrigger = "Cast";+ [Header("Timing")]+ [Tooltip("Release moment in the cast clip (seconds at clip speed 1); a Release event on the clip takes precedence")] public float releaseTime = 2.5f;+ [Tooltip("Legacy: start playing the clip from this time (skips the idle stance at the start)")] public float castStart = 0.6f;+ public float speed = 1.8f;+ [Tooltip("Hand bone the orb is released from (empty = a fixed point in front of the caster)")] public Transform hand;+ public Vector3 handOffset = new Vector3(0, 0, 0.1f);++ /// <summary>Called when the "Release" animation event fires.</summary>+ public event Action Released;+ int releaseCount;+ float savedAnimatorSpeed = 1f;+ Coroutine restore;++ public Vector3 HandPosition => hand ? hand.position + transform.TransformDirection(handOffset) : transform.TransformPoint(new Vector3(0, 1.1f, 0.5f));+ public bool UsesReleaseEvent => !UsesLegacy && animator;+ bool UsesLegacy => legacy && legacy[castClip] != null;+ /// <summary>Current Release count; a skill stores it, and once ReleasedSince(n) is true the release has happened.</summary>+ public int ReleaseStamp => releaseCount;+ public bool ReleasedSince(int stamp) => releaseCount > stamp;++ /// <summary>Starts the cast and returns the expected seconds until release (for Animator this is the fallback timeout).</summary>+ public float Cast(float speedScale = 1f)+ {+ float spd = speed * Mathf.Max(0.1f, speedScale);+ if (UsesLegacy)+ {+ var st = legacy[castClip];+ st.speed = spd; st.wrapMode = WrapMode.Once;+ legacy.CrossFade(castClip, 0.12f); st.time = castStart;+ if (legacy[idleClip] != null) legacy.CrossFadeQueued(idleClip, 0.35f, QueueMode.CompleteOthers);+ return Mathf.Max(0.15f, (EventTime(st.clip) - castStart) / spd);+ }+ if (animator)+ {+ if (restore == null) savedAnimatorSpeed = animator.speed;+ else StopCoroutine(restore);+ float scale = spd / Mathf.Max(speed, 1e-3f);+ animator.speed = savedAnimatorSpeed * scale;+ animator.SetTrigger(castTrigger);+ float delay = Mathf.Max(0.15f, releaseTime / spd);+ restore = StartCoroutine(RestoreSpeed(delay + 0.6f));+ return delay;+ }+ return 0.4f;+ }++ IEnumerator RestoreSpeed(float after)+ {+ yield return new WaitForSeconds(after);+ if (animator) animator.speed = savedAnimatorSpeed;+ restore = null;+ }++ void OnDisable() { if (restore != null && animator) animator.speed = savedAnimatorSpeed; restore = null; }++ float EventTime(AnimationClip clip)+ {+ foreach (var e in clip.events) if (e.functionName == "Release") return e.time;+ return releaseTime;+ }++ // Animation Event receiver (called by both Legacy and Animator)+ public void Release() { releaseCount++; Released?.Invoke(); }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/DemoTarget.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/DemoTarget.csnew file mode 100644index 0000000..99f53aa--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/DemoTarget.cs@@ -0,0 +1,88 @@+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// A hit reaction good enough to judge effects on: spring knockback, squash and stretch, a tilt away from the hit,+ /// a short flash in the element's colour, and being lifted and dropped by eruption skills (ElementHit.lift).+ /// Strength is ElementHit.power × the profile's knockback; ticks (power < 1) only twitch and flash.+ /// Put it on the target's root; `visual` is the child that moves (defaults to the first child).+ /// Real games replace this with their own IElementHitReceiver (stagger, damage numbers, elemental reactions).+ /// </summary>+ public class DemoTarget : MonoBehaviour, IElementHitReceiver+ {+ public Transform visual;+ public float floatAmp = 0.0f, floatFreq = 1.6f;+ [Range(0, 1), Tooltip("How much of the element colour the body takes on a hit (white targets: keep it low)")] public float flashTint = 0.18f;++ float squash, squashVel, tilt, tiltVel, flash;+ Vector3 push, pushVel;+ float air, airVel, liftTo, liftUntil, fallG = 22f; // lifted by a column: held at liftTo, then dropped with fallG+ Vector3 shift, shiftTo, shiftVel; // moved over the column while lifted, eased back after landing+ Color flashColor = Color.white;+ Vector3 baseLocal;+ Renderer[] rends;+ MaterialPropertyBlock mpb;+ static readonly int BaseId = Shader.PropertyToID("_BaseColor"), EmitId = Shader.PropertyToID("_EmissionColor");++ void Start()+ {+ if (!visual) visual = transform.childCount > 0 ? transform.GetChild(0) : transform;+ baseLocal = visual.localPosition;+ rends = visual.GetComponentsInChildren<Renderer>();+ mpb = new MaterialPropertyBlock();+ }++ public void OnElementHit(in ElementHit hit)+ {+ float k = hit.power * (hit.element ? hit.element.knockback : 1f);+ Vector3 d = hit.direction; d.y = Mathf.Max(d.y, 0);+ if (hit.lift > 0)+ {+ liftTo = Mathf.Max(liftTo, hit.lift); liftUntil = Mathf.Max(liftUntil, Time.time + hit.liftTime);+ shiftTo = transform.InverseTransformVector(hit.liftShift); if (hit.liftGravity > 0) fallG = hit.liftGravity;+ }+ else if (d.y > 0.7f) airVel = Mathf.Max(airVel, 2.3f * Mathf.Sqrt(Mathf.Max(k, 0f))); // other upward hits: a small hop+ else pushVel += transform.InverseTransformDirection(d.normalized) * 4.5f * k;+ squashVel -= 6f * k;+ tiltVel += 300f * k * Mathf.Sign(Vector3.Dot(hit.direction, transform.forward) + 0.001f);+ flash = Mathf.Max(flash, Mathf.Lerp(0.5f, 1f, hit.power));+ flashColor = hit.element ? hit.element.theme : Color.white;+ }++ void Update()+ {+ if (!visual) return;+ float dt = Time.deltaTime;+ squashVel += (-180f * squash - 12f * squashVel) * dt; squash += squashVel * dt;+ tiltVel += (-120f * tilt - 9f * tiltVel) * dt; tilt += tiltVel * dt;+ pushVel += (-90f * push - 11f * pushVel) * dt; push += pushVel * dt;+ flash = Mathf.Max(0, flash - dt * 7f);+ if (Time.time < liftUntil)+ {+ air = Mathf.SmoothDamp(air, liftTo + 0.06f * Mathf.Sin(Time.time * 9f), ref airVel, 0.08f);+ }+ else if (air > 0 || airVel > 0)+ {+ liftTo = 0;+ airVel = Mathf.Min(airVel, 0f) - fallG * dt; air += airVel * dt;+ if (air <= 0) { air = 0; airVel = 0; squashVel -= 4f; }+ }+ if (Time.time < liftUntil || air > 0) shift = Vector3.SmoothDamp(shift, shiftTo, ref shiftVel, 0.12f);+ else { shiftTo = Vector3.zero; shift = Vector3.SmoothDamp(shift, Vector3.zero, ref shiftVel, 0.35f); }+ float s = Mathf.Clamp(squash, -0.28f, 0.3f);+ visual.localScale = new Vector3(1 - s * 0.6f, 1 + s, 1 - s * 0.6f);+ visual.localRotation = Quaternion.Euler(Mathf.Clamp(tilt, -30, 30), 0, 0);+ visual.localPosition = baseLocal + shift + Vector3.ClampMagnitude(push, 0.6f) + Vector3.up * (air + Mathf.Sin(Time.time * floatFreq * Mathf.PI * 2) * floatAmp);+ if (rends == null) return;+ Color baseC = Color.Lerp(Color.white, flashColor * 1.2f, flash * flashTint), emit = flashColor * flash * 0.2f;+ foreach (var r in rends)+ {+ if (!r) continue;+ r.GetPropertyBlock(mpb);+ mpb.SetColor(BaseId, baseC); mpb.SetColor(EmitId, emit);+ r.SetPropertyBlock(mpb);+ }+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementFX.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementFX.csnew file mode 100644index 0000000..6c18870--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementFX.cs@@ -0,0 +1,486 @@+using System.Collections.Generic;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Particle hub for element skills. All particles are world-space and emitted manually; materials are referenced directly by ElementProfile (no lookup by string).+ /// Layer roles (see effekseer-vfx craft/layering):+ /// core = contact flash / sparks (additive, small area, lit for only 2 frames)+ /// body = impact flipbooks, water crown / wind band / lightning shells (alpha-blended three-tone cel colour that doesn't wash out on bright backgrounds)+ /// matter = smoke / poison mist / water droplets / poison drips / bubbles (alpha-blended, with weight)+ /// ground = ground decals (scorch / poison pool / water stain / cracks / wind streaks), fading out by erosion+ /// Budget: density (0–1) scales all rate-based particle counts; maxParticleSize limits the screen share of large quads (mobile overdraw).+ /// </summary>+ [DefaultExecutionOrder(-100)]+ public class ElementFX : MonoBehaviour+ {+ static ElementFX _inst;+ public static ElementFX I+ {+ get+ {+ if (_inst) return _inst;+ _inst = FindAnyObjectByType<ElementFX>();+ if (!_inst) _inst = new GameObject("ElementFX").AddComponent<ElementFX>();+ return _inst;+ }+ }++ [Tooltip("Ground height when there is no collider")] public float groundY = 0f;+ [Tooltip("Layers for ground detection (only Default by default; characters, hit targets and objects with rigidbodies are skipped)")] public LayerMask groundMask = 1;+ [Range(0.1f, 1f), Tooltip("Quality: multiplier for rate-based particle counts (0.5 on low-end devices)")] public float density = 1f;+ [SerializeField, Range(0.2f, 2f), Tooltip("Maximum fraction of screen height a single particle may cover")] float maxScreenSize = 0.9f;+ /// <summary>Maximum screen share of a single particle (runtime changes apply to all systems immediately, except decals).</summary>+ public float MaxScreenSize+ {+ get => maxScreenSize;+ set { maxScreenSize = value; foreach (var r in GetComponentsInChildren<ParticleSystemRenderer>(true)) if (!r.name.StartsWith("Decal_") && !r.name.StartsWith("Column_")) r.maxParticleSize = value; }+ }+ [Tooltip("Maximum concurrent impact bodies of the same kind (at the limit Unity drops the newly emitted one)")] public int maxBodiesPerElement = 32;+ [Header("Hit lights")]+ [Tooltip("Theme-coloured point light on hit (per-pixel lighting has a cost on mobile; turn off on low quality)")] public bool hitLights = true;+ [Range(0, 4), Tooltip("Maximum concurrent hit lights; 1 by default on mobile")] public int maxHitLights = 4;++ ParticleSystem sparks, streaks, flash, smoke, drops, bubbles, goo, embers;+ readonly Dictionary<Material, ParticleSystem> shapes = new Dictionary<Material, ParticleSystem>();+ readonly List<Light> lights = new List<Light>();+ readonly List<float> lightEnd = new List<float>(), lightLife = new List<float>(), lightPeak = new List<float>();+ readonly Dictionary<Material, ParticleSystem> flipbooks = new Dictionary<Material, ParticleSystem>();+ readonly Dictionary<Material, ParticleSystem> columns = new Dictionary<Material, ParticleSystem>();+ readonly Dictionary<Material, ParticleSystem> trails = new Dictionary<Material, ParticleSystem>();+ readonly Dictionary<Material, ParticleSystem> decals = new Dictionary<Material, ParticleSystem>();+ readonly List<ShellPiece> shellPool = new List<ShellPiece>();+ readonly Dictionary<(ParticleSystem, Material), ParticleSystem> variants = new Dictionary<(ParticleSystem, Material), ParticleSystem>();+ static Mesh quad;+ /// <summary>Maximum screen share allowed for the column (water column): single layer, shown only for ~2 s on hit; verify mobile overdraw on device.</summary>+ const float ColumnMaxScreen = 1.6f;+ static readonly RaycastHit[] hits = new RaycastHit[8];++ static Material Res(string n) => Resources.Load<Material>("VfxSkill/" + n);++ void Awake()+ {+ if (_inst && _inst != this) { Destroy(gameObject); return; }+ _inst = this;+ if (Application.isMobilePlatform) maxHitLights = Mathf.Min(maxHitLights, 1);+ Build();+ PrewarmLights();+ }++ // Warm-up: create the lights at startup, place them right in front of the camera and light them at tiny intensity for 2 frames, so shader variants with additional lights compile at load and the first hit doesn't hitch.+ // Objects that appear later still compile when first lit; in production also prewarm with ShaderVariantCollection / GraphicsStateCollection.+ void PrewarmLights()+ {+ if (!hitLights) return;+ EnsureLights();+ var cam = Camera.main;+ for (int i = 0; i < lights.Count; i++)+ {+ var l = lights[i];+ l.transform.position = cam ? cam.transform.position + cam.transform.forward * 3f : Vector3.zero;+ l.intensity = 0.01f; l.range = 4f; l.enabled = true;+ lightEnd[i] = Time.time + 0.1f; lightLife[i] = 0.1f; lightPeak[i] = 0.01f;+ }+ }++ void EnsureLights()+ {+ while (lights.Count < maxHitLights)+ {+ var l = new GameObject("HitLight").AddComponent<Light>(); l.transform.SetParent(transform, false);+ l.type = LightType.Point; l.shadows = LightShadows.None; l.enabled = false;+ lights.Add(l); lightEnd.Add(0); lightLife.Add(1); lightPeak.Add(0);+ }+ }++ ParticleSystem PS(string name, Material mat, int max, ParticleSystemRenderMode mode)+ {+ if (!mat) Debug.LogError($"[ElementFX] {name}: material missing");+ var go = new GameObject(name); go.transform.SetParent(transform, false);+ var ps = go.AddComponent<ParticleSystem>();+ ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);+ var m = ps.main; m.playOnAwake = false; m.simulationSpace = ParticleSystemSimulationSpace.World;+ m.maxParticles = max; m.startSpeed = 0; m.scalingMode = ParticleSystemScalingMode.Shape;+ var em = ps.emission; em.enabled = false;+ var sh = ps.shape; sh.enabled = false;+ var r = go.GetComponent<ParticleSystemRenderer>();+ r.sharedMaterial = mat; r.renderMode = mode; r.sortMode = ParticleSystemSortMode.Distance;+ r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.receiveShadows = false;+ r.maxParticleSize = maxScreenSize;+ ps.Play();+ return ps;+ }++ static AnimationCurve Curve(params float[] tv) { var c = new AnimationCurve(); for (int i = 0; i < tv.Length; i += 2) c.AddKey(tv[i], tv[i + 1]); return c; }+ static Gradient Fade(float inT, float hold)+ {+ var g = new Gradient();+ g.SetKeys(new[] { new GradientColorKey(Color.white, 0), new GradientColorKey(Color.white, 1) },+ new[] { new GradientAlphaKey(inT > 0 ? 0 : 1, 0), new GradientAlphaKey(1, Mathf.Max(inT, 0.001f)), new GradientAlphaKey(1, hold), new GradientAlphaKey(0, 1) });+ return g;+ }+ static void Drag(ParticleSystem ps, float drag)+ {+ var lv = ps.limitVelocityOverLifetime; lv.enabled = true; lv.drag = drag; lv.multiplyDragByParticleSize = false; lv.limit = 80;+ }+ static void Sheet(ParticleSystem ps, int n)+ {+ var ts = ps.textureSheetAnimation; ts.enabled = true; ts.numTilesX = n; ts.numTilesY = n;+ ts.frameOverTime = new ParticleSystem.MinMaxCurve(0); ts.startFrame = new ParticleSystem.MinMaxCurve(0, n * n - 0.01f);+ }++ void Build()+ {+ // core: small sparks, fast then slowing (drag)+ // sparks / speed lines use alpha-blended saturated colour: additive is invisible on bright backgrounds and white targets+ sparks = PS("Sparks", Res("M_Spark"), 3000, ParticleSystemRenderMode.Billboard);+ { var c = sparks.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.25f);+ var sz = sparks.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 1, 1, 0.15f));+ Drag(sparks, 3f); }+ // speed lines: stretched bright streaks (directional spray along the trajectory on hit)+ streaks = PS("Streaks", Res("M_Spark"), 2000, ParticleSystemRenderMode.Stretch);+ { var c = streaks.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.2f);+ var r = streaks.GetComponent<ParticleSystemRenderer>(); r.velocityScale = 0.05f; r.lengthScale = 2f;+ Drag(streaks, 2.5f); }+ // contact flash: lives about 2 frames, grows fast then vanishes+ flash = PS("Flash", Res("M_Flash"), 100, ParticleSystemRenderMode.Billboard);+ { var c = flash.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.3f);+ var sz = flash.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 0.6f, 1, 1.25f)); }+ // matter: translucent smoke puffs / poison mist, slowly expanding and slowing down+ smoke = PS("Smoke", Res("M_Smoke"), 800, ParticleSystemRenderMode.Billboard); // neutral grey smoke, tinted by vertex colour+ { Sheet(smoke, 2);+ var c = smoke.colorOverLifetime; c.enabled = true; c.color = Fade(0.15f, 0.3f);+ var sz = smoke.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 0.5f, 0.3f, 0.9f, 1, 1.4f));+ var rot = smoke.rotationOverLifetime; rot.enabled = true; rot.z = new ParticleSystem.MinMaxCurve(-0.6f, 0.6f);+ var m = smoke.main; m.startRotation = new ParticleSystem.MinMaxCurve(0, Mathf.PI * 2);+ Drag(smoke, 1.2f); }+ // matter: water droplets / poison drips (affected by gravity)+ drops = PS("Drops", Res("M_Drop"), 1500, ParticleSystemRenderMode.Billboard);+ { Sheet(drops, 2);+ var m = drops.main; m.gravityModifier = 1f;+ var c = drops.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.75f);+ var sz = drops.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 1, 0.8f, 0.9f, 1, 0.4f)); }+ // matter: bubbles (poison pool), slowly rising and growing, then a final swell and pop+ bubbles = PS("Bubbles", Res("M_Drop"), 300, ParticleSystemRenderMode.Billboard);+ { Sheet(bubbles, 2);+ var c = bubbles.colorOverLifetime; c.enabled = true; c.color = Fade(0.1f, 0.85f);+ var sz = bubbles.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 0.3f, 0.8f, 1f, 0.92f, 1.35f, 1, 0f));+ Drag(bubbles, 2f); }+ // core: embers with negative gravity, drifting up and slowly shrinking (fire physics: heat rises)+ embers = PS("Embers", Res("M_Spark"), 600, ParticleSystemRenderMode.Billboard);+ { var m = embers.main; m.gravityModifier = -0.35f;+ var c = embers.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.6f);+ var sz = embers.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 1, 1, 0.25f));+ var no = embers.noise; no.enabled = true; no.strength = 0.6f; no.frequency = 1.2f;+ Drag(embers, 0.8f); }+ // matter: sticky poison strands (stretched, slowly running down the surface)+ goo = PS("Goo", Res("M_Drop"), 400, ParticleSystemRenderMode.Stretch);+ { Sheet(goo, 2);+ var m = goo.main; m.gravityModifier = 1.1f; // viscous: starts slow and speeds up, about 0.5 s from the top to the lower edge+ var r = goo.GetComponent<ParticleSystemRenderer>(); r.velocityScale = 0.1f; r.lengthScale = 1.3f; // short tail: at most about 1/3 of the body+ var c = goo.colorOverLifetime; c.enabled = true; c.color = Fade(0.05f, 0.8f);+ var sz = goo.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 0.6f, 0.5f, 1f, 1, 0.7f));+ Drag(goo, 0.5f); }+ }++ /// <summary>Cel shape particles (impact star / shock ring): StylizedShell material, vertex alpha 1→0 = erosion progress (the thinnest points break first).</summary>+ ParticleSystem Shape(Material mat)+ {+ if (shapes.TryGetValue(mat, out var ps) && ps) return ps;+ ps = PS("Shape_" + mat.name, mat, 40, ParticleSystemRenderMode.Billboard);+ var c = ps.colorOverLifetime; c.enabled = true;+ var g = new Gradient();+ g.SetKeys(new[] { new GradientColorKey(Color.white, 0), new GradientColorKey(Color.white, 1) },+ new[] { new GradientAlphaKey(1, 0), new GradientAlphaKey(0.85f, 0.4f), new GradientAlphaKey(0, 1) });+ c.color = g;+ bool star = mat.name.EndsWith("_Star"); // CreateElementSkill names contact stars M_<Skill>_Star+ var sz = ps.sizeOverLifetime; sz.enabled = true;+ sz.size = new ParticleSystem.MinMaxCurve(1, star ? Curve(0, 1f, 0.5f, 0.6f, 1, 0.2f) // star (contact white core): largest on the first frame, shrinking each frame+ : Curve(0, 0.45f, 0.25f, 0.9f, 1, 1.15f)); // shock ring: snaps open, then keeps growing slowly+ shapes[mat] = ps;+ return ps;+ }++ ParticleSystem Flipbook(Material mat)+ {+ if (flipbooks.TryGetValue(mat, out var ps) && ps) return ps;+ ps = PS("Flip_" + mat.name, mat, maxBodiesPerElement, ParticleSystemRenderMode.Billboard);+ var ts = ps.textureSheetAnimation; ts.enabled = true; SetTiles(ts, mat);+ ts.animation = ParticleSystemAnimationType.WholeSheet;+ ts.frameOverTime = new ParticleSystem.MinMaxCurve(1, AnimationCurve.Linear(0, 0, 1, 1));+ var c = ps.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.85f); // erode once more at the end so it never pops out+ Vector4 grow = mat.HasProperty("_Grow") ? mat.GetVector("_Grow") : Vector4.zero; // the material can request a 'snap-grow from small' (for atlases whose first frame is already full size, e.g. explosions)+ var sz = ps.sizeOverLifetime; sz.enabled = true;+ sz.size = new ParticleSystem.MinMaxCurve(1, grow.x > 0 && grow.y > 0 ? Curve(0, grow.x, grow.y, 1f, 1, 1.15f) : Curve(0, 0.85f, 0.2f, 1f, 1, 1.2f)); // the body keeps growing and spreading instead of fading in place+ flipbooks[mat] = ps;+ return ps;+ }++ /// <summary>Atlas layout: the material's _Tiles (columns, rows); 8×8 if absent.</summary>+ static void SetTiles(ParticleSystem.TextureSheetAnimationModule ts, Material mat)+ {+ Vector4 t = mat && mat.HasProperty("_Tiles") ? mat.GetVector("_Tiles") : new Vector4(8, 8, 0, 0);+ ts.numTilesX = Mathf.Max(1, (int)t.x); ts.numTilesY = Mathf.Max(1, (int)t.y);+ }++ /// <summary>+ /// Vertical flipbook column (water column): faces the camera around Y only, with its bottom edge pinned to the emit point (the column grows out of the ground and doesn't tip over in high-angle shots).+ /// frames: life fraction → frame progress (fast surge, hold, collapse), from ElementProfile.columnFrames; only the first call per material takes effect.+ /// </summary>+ ParticleSystem Columns(Material mat, AnimationCurve frames)+ {+ if (columns.TryGetValue(mat, out var ps) && ps) return ps;+ ps = PS("Column_" + mat.name, mat, 8, ParticleSystemRenderMode.VerticalBillboard);+ var m = ps.main; m.startSize3D = true;+ var r = ps.GetComponent<ParticleSystemRenderer>(); r.pivot = new Vector3(0, 0.5f, 0); r.maxParticleSize = ColumnMaxScreen; // the column is meant to extend past the frame; not limited by MaxScreenSize (otherwise it suddenly shrinks in close-ups)+ var ts = ps.textureSheetAnimation; ts.enabled = true; SetTiles(ts, mat);+ ts.animation = ParticleSystemAnimationType.WholeSheet;+ ts.frameOverTime = new ParticleSystem.MinMaxCurve(1, frames != null && frames.length >= 2 ? frames : AnimationCurve.Linear(0, 0, 1, 1));+ var c = ps.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0.92f);+ columns[mat] = ps;+ return ps;+ }++ public static void Column(Material mat, Vector3 basePos, float height, float aspect, float life, AnimationCurve frames = null)+ {+ if (!mat) return;+ var e = P(basePos, Vector3.zero, height, life, Color.white);+ e.startSize3D = new Vector3(height * aspect, height, 1);+ I.Columns(mat, frames).Emit(e, 1);+ }++ /// <summary>The same particle system with a different material (an element's own smoke / droplet texture); cloned on demand and cached.</summary>+ ParticleSystem Variant(ParticleSystem baseSys, Material mat)+ {+ if (!mat) return baseSys;+ if (variants.TryGetValue((baseSys, mat), out var ps) && ps) return ps;+ ps = Instantiate(baseSys, transform);+ ps.name = baseSys.name + "_" + mat.name;+ ps.GetComponent<ParticleSystemRenderer>().sharedMaterial = mat;+ ps.Play();+ variants[(baseSys, mat)] = ps;+ return ps;+ }++ ParticleSystem Trail(Material mat)+ {+ if (trails.TryGetValue(mat, out var ps) && ps) return ps;+ ps = PS("Trail_" + mat.name, mat, 400, ParticleSystemRenderMode.Billboard);+ var c = ps.colorOverLifetime; c.enabled = true; c.color = Fade(0, 0f);+ var sz = ps.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 1, 1, 0.3f));+ trails[mat] = ps;+ return ps;+ }++ ParticleSystem Decal(Material mat)+ {+ if (decals.TryGetValue(mat, out var ps) && ps) return ps;+ ps = PS("Decal_" + mat.name, mat, 40, ParticleSystemRenderMode.HorizontalBillboard);+ var r = ps.GetComponent<ParticleSystemRenderer>(); r.sortingFudge = 50; r.maxParticleSize = 5; // draw ground decals first; decals lie flat on the ground and aren't limited by screen share+ var c = ps.colorOverLifetime; c.enabled = true; c.color = Fade(0.05f, 0.4f); // vertex alpha drives PaintedFX erosion: breaks up and fades, always ending at 0+ var sz = ps.sizeOverLifetime; sz.enabled = true; sz.size = new ParticleSystem.MinMaxCurve(1, Curve(0, 0.5f, 0.1f, 1f, 1, 1.06f));+ decals[mat] = ps;+ return ps;+ }++ /// <summary>Clears all effects. Call only when no skill is playing (e.g. camera cuts, scene changes), otherwise a playing skill loses the shells it borrowed.</summary>+ public void ClearAll()+ {+ foreach (var p in new[] { sparks, streaks, flash, smoke, drops, bubbles, goo, embers }) if (p) p.Clear();+ foreach (var d in new[] { flipbooks, columns, trails, decals, shapes }) foreach (var p in d.Values) if (p) p.Clear();+ foreach (var l in lights) if (l) l.enabled = false;+ foreach (var p in variants.Values) if (p) p.Clear();+ foreach (var s in shellPool) if (s) s.Release();+ }++ /// <summary>Converts a rate (per second) × density into this frame's emit count (stochastic rounding, accurate on average).</summary>+ public static int Rate(float perSecond, float dt)+ {+ float n = perSecond * dt * (_inst ? _inst.density : 1f);+ int k = Mathf.FloorToInt(n);+ if (Random.value < n - k) k++;+ return k;+ }++ /// <summary>Burst count scaled by the quality budget (at least 1).</summary>+ public static int Count(int n) => n <= 0 ? 0 : Mathf.Max(1, Mathf.RoundToInt(n * (_inst ? _inst.density : 1f)));++ /// <summary>Ground point directly below p: only hits groundMask layers, skipping characters / hit targets / objects with rigidbodies; falls back to groundY if nothing is hit.</summary>+ public static Vector3 GroundAt(Vector3 p)+ {+ var g = I;+ int n = Physics.RaycastNonAlloc(p + Vector3.up * 2f, Vector3.down, hits, 20f, g.groundMask, QueryTriggerInteraction.Ignore);+ float best = float.MaxValue; Vector3 point = default; bool found = false;+ for (int i = 0; i < n; i++)+ {+ var c = hits[i].collider;+ if (c.attachedRigidbody || c.GetComponentInParent<IElementHitReceiver>() != null || c.GetComponentInParent<CharacterController>()) continue;+ if (hits[i].distance < best) { best = hits[i].distance; point = hits[i].point; found = true; }+ }+ if (found) return point;+ p.y = g.groundY; return p;+ }++ static ParticleSystem.EmitParams P(Vector3 p, Vector3 v, float s, float l, Color c, float rot = 0)+ => new ParticleSystem.EmitParams { position = p, velocity = v, startSize = s, startLifetime = l, startColor = c, rotation = rot, applyShapeToPosition = false };++ public static void Spark(Vector3 p, Vector3 v, float s, float l, Color c) => I.sparks.Emit(P(p, v, s, l, c), 1);+ public static void Streak(Vector3 p, Vector3 v, float s, float l, Color c) => I.streaks.Emit(P(p, v, s, l, c), 1);+ /// <summary>Contact flash: 0.06 s by default ≈ 2 frames (30 fps).</summary>+ public static void Flash(Vector3 p, float s, Color c, float l = 0.06f) => I.flash.Emit(P(p, Vector3.zero, s, l, Color.Lerp(c, Color.white, 0.55f)), 1);+ public static void Smoke(Vector3 p, Vector3 v, float s, float l, Color c, Material mat = null) => I.Variant(I.smoke, mat).Emit(P(p, v, s, l, c, Random.Range(0, 360f)), 1);+ public static void Drop(Vector3 p, Vector3 v, float s, float l, Color c, Material mat = null) => I.Variant(I.drops, mat).Emit(P(p, v, s, l, c), 1);+ public static void Bubble(Vector3 p, Vector3 v, float s, float l, Color c, Material mat = null) => I.Variant(I.bubbles, mat).Emit(P(p, v, s, l, c), 1);+ public static void Ember(Vector3 p, Vector3 v, float s, float l, Color c) => I.embers.Emit(P(p, v, s, l, c), 1);+ public static void Goo(Vector3 p, Vector3 v, float s, float l, Color c, Material mat = null) => I.Variant(I.goo, mat).Emit(P(p, v, s, l, c), 1);+ /// <summary>Cel shape (impact star / shock ring) with a very short life (0.1–0.25 s).</summary>+ public static void Shape(Material mat, Vector3 p, float size, float life, float rot = -1) { if (mat) I.Shape(mat).Emit(P(p, Vector3.zero, size, life, Color.white, rot < 0 ? Random.Range(0, 360f) : rot), 1); }++ /// <summary>Real light on hit: a theme-coloured point light that flares instantly and decays fast (lights the target and the ground).</summary>+ public static void LightFlash(Vector3 p, Color c, float intensity, float range, float life)+ {+ var g = I;+ if (!g.hitLights) return;+ g.EnsureLights(); // also works if hitLights is turned on at runtime+ if (g.lights.Count == 0 || g.maxHitLights <= 0) return;+ int idx = 0; float oldest = float.MaxValue; // prefer an idle light; if all are busy, reuse the one that goes out soonest+ for (int i = 0; i < Mathf.Min(g.lights.Count, g.maxHitLights); i++)+ {+ if (!g.lights[i]) continue;+ float end = g.lights[i].enabled ? g.lightEnd[i] : float.MinValue;+ if (end < oldest) { oldest = end; idx = i; }+ }+ var lt = g.lights[idx];+ lt.transform.position = p; lt.color = c; lt.range = range; lt.intensity = intensity; lt.enabled = true;+ g.lightEnd[idx] = Time.time + life; g.lightLife[idx] = life; g.lightPeak[idx] = intensity;+ }++ void Update()+ {+ for (int i = 0; i < lights.Count; i++)+ {+ if (!lights[i] || !lights[i].enabled) continue;+ if (i >= maxHitLights || !hitLights) { lights[i].enabled = false; continue; }+ float k = (lightEnd[i] - Time.time) / Mathf.Max(lightLife[i], 1e-3f);+ if (k <= 0) { lights[i].enabled = false; continue; }+ lights[i].intensity = lightPeak[i] * k * k;+ }+ }+ static ParticleSystem.Particle[] cutBuf;+ /// <summary>Cuts the trail on hit: afterimages of this material keep at most maxRemain seconds of remaining life (so the trail doesn't keep pouring into the blast after the orb is gone).</summary>+ public static void CutTrail(Material mat, float maxRemain)+ {+ if (!mat || !I.trails.TryGetValue(mat, out var ps) || !ps) return;+ int n = ps.particleCount; if (n == 0) return;+ if (cutBuf == null || cutBuf.Length < n) cutBuf = new ParticleSystem.Particle[Mathf.NextPowerOfTwo(n)];+ n = ps.GetParticles(cutBuf, n);+ for (int i = 0; i < n; i++) cutBuf[i].remainingLifetime = Mathf.Min(cutBuf[i].remainingLifetime, maxRemain);+ ps.SetParticles(cutBuf, n);+ }++ public static void TrailPuff(Material mat, Vector3 p, float s, float l) { if (mat) I.Trail(mat).Emit(P(p, Vector3.zero, s, l, new Color(1, 1, 1, 0.6f), Random.Range(0, 360f)), 1); }++ /// <summary>Ground decal: placed on the raycast ground and fully eroded by the end of its life.</summary>+ public static void GroundDecal(Material mat, Vector3 p, float size, float life, Color tint)+ {+ if (!mat) return;+ p = GroundAt(p) + Vector3.up * 0.02f;+ I.Decal(mat).Emit(P(p, Vector3.zero, size, life, tint, Random.Range(0, 360f)), 1);+ }++ /// <summary>Impact flipbook (body). The push toward the camera is done in the shader via the material's _CamPush and updates live with the camera.</summary>+ public static void Body(Material mat, Vector3 p, Vector3 velocity, float size, float life)+ {+ if (!mat) return;+ I.Flipbook(mat).Emit(P(p, velocity, size, life, Color.white, Random.Range(-10f, 10f)), 1);+ }++ /// <summary>Camera-facing quad (the orb in flight).</summary>+ public static Transform Quad(string name, Material mat, Transform parent)+ {+ if (!quad)+ {+ quad = new Mesh { name = "ElementQuad" };+ quad.vertices = new[] { new Vector3(-0.5f, -0.5f, 0), new Vector3(0.5f, -0.5f, 0), new Vector3(-0.5f, 0.5f, 0), new Vector3(0.5f, 0.5f, 0) };+ quad.uv = new[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) };+ quad.colors = new[] { Color.white, Color.white, Color.white, Color.white };+ quad.triangles = new[] { 0, 2, 1, 1, 2, 3 };+ quad.RecalculateNormals(); quad.RecalculateBounds();+ }+ var go = new GameObject(name);+ go.transform.SetParent(parent, true);+ go.AddComponent<MeshFilter>().sharedMesh = quad;+ var r = go.AddComponent<MeshRenderer>(); r.sharedMaterial = mat;+ r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;+ return go.transform;+ }++ public static void Face(Transform t, float spinDeg)+ {+ var cam = Camera.main; if (!cam) return;+ t.rotation = Quaternion.LookRotation(t.position - cam.transform.position, cam.transform.up) * Quaternion.Euler(0, 0, spinDeg);+ }++ /// <summary>Takes a shell from the pool (water crown / wind band / lightning); call Release() when done. Hide it (flicker) with Visible; it won't be lent to anyone else.</summary>+ public static ShellPiece Shell(Material mat)+ {+ var g = I;+ foreach (var s in g.shellPool) if (s && !s.InUse) { s.Init(mat); return s; }+ var p = ShellPiece.Create(g.transform);+ g.shellPool.Add(p); p.Init(mat);+ return p;+ }+ }++ /// <summary>Pooled shell: its own Mesh + MaterialPropertyBlock (erosion, opacity).</summary>+ public class ShellPiece : MonoBehaviour+ {+ public Mesh mesh;+ /// <summary>Currently borrowed (regardless of visibility).</summary>+ public bool InUse { get; private set; }+ /// <summary>For flicker: toggles rendering only, without returning it to the pool.</summary>+ public bool Visible { get => mr.enabled; set => mr.enabled = value; }+ MeshRenderer mr;+ MaterialPropertyBlock mpb;+ static readonly int ErosionId = Shader.PropertyToID("_Erosion"), OpacityId = Shader.PropertyToID("_Opacity");++ public static ShellPiece Create(Transform parent)+ {+ var go = new GameObject("Shell"); go.transform.SetParent(parent, false);+ var p = go.AddComponent<ShellPiece>();+ p.mesh = new Mesh { name = "ShellMesh" }; p.mesh.MarkDynamic();+ go.AddComponent<MeshFilter>().sharedMesh = p.mesh;+ p.mr = go.AddComponent<MeshRenderer>();+ p.mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; p.mr.receiveShadows = false;+ p.mpb = new MaterialPropertyBlock();+ return p;+ }++ public void Init(Material mat)+ {+ mr.sharedMaterial = mat;+ transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity); transform.localScale = Vector3.one;+ Set(0, 1);+ InUse = true; mr.enabled = true;+ gameObject.SetActive(true);+ }++ public void Release() { InUse = false; gameObject.SetActive(false); }++ void OnDestroy() { if (mesh) Destroy(mesh); } // the mesh is created per piece, not an asset: free it with the scene++ public void Set(float erosion, float opacity)+ {+ mpb.SetFloat(ErosionId, erosion); mpb.SetFloat(OpacityId, opacity);+ mr.SetPropertyBlock(mpb);+ }++ public void CopyMesh(Mesh src)+ {+ mesh.Clear();+ mesh.vertices = src.vertices; mesh.uv = src.uv; mesh.uv2 = src.uv2; mesh.colors = src.colors;+ mesh.normals = src.normals; mesh.triangles = src.triangles; mesh.RecalculateBounds();+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementProfile.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementProfile.csnew file mode 100644index 0000000..c098e6e--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementProfile.cs@@ -0,0 +1,160 @@+using UnityEngine;++namespace VfxSkill+{+ public enum DeliveryType { Projectile, Instant, Eruption }+ public enum TrailStyle { None, Droplets, EmberSmoke, ToxicDrip, Helix }+ public enum ImpactExtra { None, CrownSplash, Fireball, Splat, Funnel, Arcs }+ public enum LingerStyle { None, Drip, Smolder, Pool, Swirl, Static }+ /// <summary>Element-specific shape at the moment of contact (so the five elements don't share one generic 'hit stamp').</summary>+ public enum ContactAccent { None, Star, FoamRing, AirRing, ArcBurst }++ /// <summary>+ /// All data for one element skill: textures/materials, trajectory, trail, impact, linger, hit feel.+ /// Adding an element = creating a new ElementProfile asset (Create → VfxSkill → Element Profile),+ /// picking existing Trail/Impact/Linger styles and filling in values; code is needed only for a brand-new kind of motion (add a style).+ /// </summary>+ [CreateAssetMenu(menuName = "VfxSkill/Element Profile", fileName = "EP_NewElement")]+ public class ElementProfile : ScriptableObject+ {+ [Header("Identity")]+ public string displayName = "Element";+ [Tooltip("Main colour (sparks, flashes, target hit tint)")] public Color theme = Color.white;+ [Tooltip("Dark rim colour (ink rim, residue)")] public Color dark = Color.black;++ [Header("Materials")]+ public Material orb;+ public Material impact;+ public Material decal;+ [Tooltip("StylizedShell material for the extra impact shells (water crown / wind bands / lightning strip)")] public Material shell;+ [Tooltip("Lightning glow (soft strip)")] public Material glow;+ [Tooltip("Contact burst: star (StylizedShell)")] public Material star;+ [Tooltip("Contact burst: shock ring (StylizedShell)")] public Material ring;+ [Tooltip("Optional: this element's smoke (empty = shared neutral grey smoke)")] public Material smoke;+ [Tooltip("Optional: this element's droplets / drips / bubbles (empty = shared ones)")] public Material matter;++ [Header("Charge & delivery")]+ public DeliveryType delivery = DeliveryType.Projectile;+ [Tooltip("Cast animation speed multiplier (rhythm differs: lightning fast, poison slow)"), Min(0.1f)] public float castSpeed = 1f;+ [Tooltip("Orb size in the palm while charging (m)")] public float chargeSize = 0.32f;+ [Tooltip("Orb size in flight (m)")] public float flightSize = 0.6f;+ [Tooltip("m/s"), Min(0.5f)] public float speed = 10f;+ [Tooltip("Gravity multiplier")] public float gravityScale = 0.45f;+ [Tooltip("Extra lift at the apex of the arc (m)")] public float lift = 0.5f;+ public float spinDegPerSec = 600f;++ [Header("Eruption (delivery = Eruption: a column bursting up beneath the target)")]+ [Tooltip("Optional: column front layer (translucent, drawn over the target). Empty = a single column layer drawn behind the target (face stays visible). The column itself uses impact")] public Material columnFront;+ [Tooltip("Column height (m)")] public float columnHeight = 3.4f;+ [Tooltip("How high the target is lifted off the ground (m); held there until the column top collapses")] public float columnLift = 1.4f;+ [Tooltip("Gravity for the target's fall after the lift (m/s², cartoon gravity is faster than the real 9.8): the landing crown is timed from it"), Min(1f)] public float columnFallGravity = 22f;+ [Tooltip("How far behind the target the column root sits (m, along the ground, away from the camera at the moment of eruption): the column draws behind the target yet still grows out of the ground (pushing it back in the material does not work: from a high angle the root would float above the ground)"), Range(0f, 3f)] public float columnBehind = 0.6f;+ [Tooltip("Canopy rim height (fraction of column height): rain falls from here when it collapses"), Range(0f, 1f)] public float columnRim = 0.5f;+ [Tooltip("Distance from the column root to the bottom of its atlas cell (fraction of column height, gutter included): the column is sunk into the ground by this much so the root sits on the ground (otherwise it floats, leaving a strip of dry ground between it and the puddle)"), Range(0f, 0.5f)] public float columnRootInset = 0f;+ [Tooltip("Atlas cell width / height")] public float columnAspect = 0.545f;+ [Tooltip("Total column duration (s): surge up → hold → collapse → ground splash"), Min(0.2f)] public float columnLife = 2.4f;+ [Tooltip("Column atlas timing: x = life fraction 0–1, y = frame progress 0–1 (fast surge, hold, collapse). Retune this curve to the new source video when swapping the atlas")]+ public AnimationCurve columnFrames = LinearCurve(0, 0, 0.1f, 0.143f, 0.4f, 0.5f, 0.54f, 0.73f, 1, 1);+ [Tooltip("Life fraction where the lift ends and the rain starts: slightly before the hold segment of columnFrames ends (0.4), so the target starts falling and the column top collapses right after instead of hanging in the air"), Range(0.05f, 0.95f)] public float columnHoldEnd = 0.34f;+ [Tooltip("Warning time after the orb dives into the ground and before the column erupts (s): ground bubbles, a water ring spreads"), Min(0f)] public float warnTime = 0.35f;++ [Header("Trail (emitted by distance, frame-rate independent)")]+ public TrailStyle trail = TrailStyle.Droplets;+ [Tooltip("Distance between trail emissions (m)"), Min(0.01f)] public float trailSpacing = 0.06f;+ [Tooltip("Cut this trail's afterimages on hit (fire: once the orb is gone the trail must not keep pouring into the blast). Note: cut per material, so with rapid casts of the same element it also cuts the trail of a shot still in flight")] public bool cutTrailOnHit = false;++ [Header("Aim")]+ [Tooltip("Hit point height offset (m): different elements hit different parts of the target")] public float aimHeight = 0f;+ [Tooltip("Drops onto the target from above (poison's high lob): the hit point is on top of the target")] public bool fromAbove = false;++ [Header("Impact")]+ public ImpactExtra extra = ImpactExtra.None;+ [Tooltip("Impact flipbook size (m). Keep it under 1.4x the target, or it covers the hit reaction")] public float impactSize = 2.2f;+ [Tooltip("Impact flipbook duration (s)")] public float impactLife = 1.4f;+ [Tooltip("Upward drift speed of the whole impact flipbook (m/s); fire smoke should rise")] public float impactRise = 0f;+ [Tooltip("Flipbook centre offset from the hit point (target-local: x right, y up, z toward the caster)")] public Vector3 impactOffset = Vector3.zero;+ [Tooltip("Element-specific contact accent: water = foam ring opening along the hit surface, wind = pressure ring around the body, lightning = short radiating arcs, fire / poison = small star")] public ContactAccent contact = ContactAccent.Star;+ [Tooltip("Contact flash size (m); lasts only 2 frames")] public float flashSize = 0.9f;+ public int sparkCount = 14;++ [Tooltip("Hit light: theme-coloured point light intensity / range")] public float lightIntensity = 6f;+ public float lightRange = 4f;++ [Header("Ground")]+ public float decalSize = 1.6f;+ [Tooltip("Decal colour multiplier (darken fire scorch marks)")] public Color decalTint = Color.white;+ [Tooltip("Decal life (s); the skill is not finished until it has fully faded"), Min(0f)] public float decalLife = 1.8f;++ [Header("Linger")]+ public LingerStyle linger = LingerStyle.None;+ [Min(0f)] public float lingerTime = 1.2f;++ [Header("Hit feel")]+ [Tooltip("Hit stop (real seconds, frame-rate independent)"), Min(0f)] public float hitStop = 0.08f;+ public float shake = 0.12f;+ public float shakeTime = 0.25f;+ [Tooltip("Hit strength (knockback / squash)"), Min(0f)] public float knockback = 1f;+ [Tooltip(">0: hold the target's hit reaction for at least this long (s), e.g. fire that keeps burning around the head should keep the reaction until it is gone; 0 = the target's own default duration"), Min(0f)] public float reactTime = 0f;+ [Tooltip("Extra damage-over-time ticks (poison, wind)")] public int ticks = 0;+ [Min(0.05f)] public float tickInterval = 0.35f;++ /// <summary>Polyline curve (each segment's tangents = its slope): frame progress advances at a steady rate without stalling at keys. Arguments are (time, value) pairs.</summary>+ public static AnimationCurve LinearCurve(params float[] tv)+ {+ int n = tv.Length / 2; var keys = new Keyframe[n];+ for (int i = 0; i < n; i++)+ {+ float inT = i > 0 ? (tv[2 * i + 1] - tv[2 * i - 1]) / Mathf.Max(1e-5f, tv[2 * i] - tv[2 * i - 2]) : 0;+ float outT = i < n - 1 ? (tv[2 * i + 3] - tv[2 * i + 1]) / Mathf.Max(1e-5f, tv[2 * i + 2] - tv[2 * i]) : 0;+ keys[i] = new Keyframe(tv[2 * i], tv[2 * i + 1], inT, outT);+ }+ return new AnimationCurve(keys);+ }++ /// <summary>Checks that the materials required by the chosen styles are assigned and values are in safe ranges; returns a list of problems (empty = OK). Runtime clamps again where the values are used.</summary>+ public string Validate()+ {+ var sb = new System.Text.StringBuilder();+ void Need(Object o, string what) { if (!o) sb.Append(what).Append("; "); }+ // value ranges: 0 or negatives would make flight / trails loop forever+ void Range(float v, float min, string what) { if (!(v >= min)) sb.Append(what).Append(" < ").Append(min).Append("; "); }+ Need(decal, "decal"); Need(star, "star (contact core)");+ if (contact == ContactAccent.FoamRing || contact == ContactAccent.AirRing) Need(ring, "ring");+ if (delivery == DeliveryType.Projectile) Need(orb, "orb");+ if (delivery == DeliveryType.Instant) { Need(orb, "orb (palm charge)"); Need(shell, "shell (bolt)"); }+ if (delivery == DeliveryType.Eruption)+ {+ Need(orb, "orb (dives into the ground)"); Need(impact, "impact (column)");+ Range(columnHeight, 0.1f, "columnHeight"); Range(columnAspect, 0.05f, "columnAspect"); Range(columnLife, 0.2f, "columnLife");+ Range(warnTime, 0f, "warnTime"); Range(columnLift, 0f, "columnLift"); Range(columnFallGravity, 1f, "columnFallGravity"); Range(columnBehind, 0f, "columnBehind"); Range(columnRim, 0f, "columnRim"); Range(speed, 0.5f, "speed"); Range(trailSpacing, 0.01f, "trailSpacing");+ if (columnFrames == null || columnFrames.length < 2) sb.Append("columnFrames (needs ≥2 keys); ");+ }+ if (extra == ImpactExtra.CrownSplash || extra == ImpactExtra.Funnel || extra == ImpactExtra.Arcs || contact == ContactAccent.ArcBurst) Need(shell, "shell (" + extra + ")");+ if (impactLife > 0) Need(impact, "impact");+ if (delivery == DeliveryType.Projectile) { Range(speed, 0.5f, "speed"); Range(trailSpacing, 0.01f, "trailSpacing"); }+ Range(castSpeed, 0.1f, "castSpeed"); Range(tickInterval, 0.05f, "tickInterval"); Range(knockback, 0f, "knockback");+ return sb.ToString();+ }++ void OnValidate() { var e = Validate(); if (e.Length > 0) Debug.LogWarning($"[ElementProfile] {name}: {e}", this); }+ }++ /// <summary>Full info for one element hit (replaces string-based SendMessage).</summary>+ public struct ElementHit+ {+ public ElementProfile element;+ public Vector3 point, direction;+ [Tooltip("1 = main hit; <1 = tick / follow-up hit")] public float power;+ [Tooltip(">0: lift the target this high off the ground (m), hold for liftTime seconds, then let it fall freely (the water column lifting the target); receivers that do not support it may ignore it")] public float lift;+ public float liftTime;+ [Tooltip("Horizontal shift of the target during the lift (world space): moves it over the column, then eases back after landing")] public Vector3 liftShift;+ [Tooltip("Fall gravity after the lift (m/s²): the skill times the landing splash with the same value, and the receiver falls with it")] public float liftGravity;+ public Component source;+ }++ /// <summary>Add to the target (or one of its parents) to receive element hits; use element to drive elemental reactions.</summary>+ public interface IElementHitReceiver+ {+ void OnElementHit(in ElementHit hit);+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementSkill.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementSkill.csnew file mode 100644index 0000000..cf9f053--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/ElementSkill.cs@@ -0,0 +1,843 @@+using System.Collections;+using System.Collections.Generic;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Element skill: cast → charge in the palm → flight (or instant link) → impact → linger. All parameters come from ElementProfile.+ /// · Each Play() is an independent shot: rapid casts don't interrupt the previous shot, which still lands.+ /// · The landing point follows a moving target; if the target disappears mid-flight, the shot flies to its last known position.+ /// · Trails are emitted by distance travelled, so density is frame-rate independent.+ /// · Hits are reported to the target through IElementHitReceiver (with element info, for elemental reactions).+ /// · When the component is disabled / destroyed (caster dies): all in-flight orbs and shells are reclaimed immediately, IsPlaying drops to zero and Finished fires.+ /// Element differences follow effekseer-vfx craft §3/§4: at least three of shape, motion, rhythm, material and secondary motion differ.+ /// The motion of each style (Trail / Impact / Linger) lives here; a new element only needs a new ElementProfile that picks styles.+ /// </summary>+ public class ElementSkill : SkillBase+ {+ public ElementProfile profile;+ public CastDriver caster;+ [Tooltip("Target radius: the hit point is on the target surface facing the caster")] public float targetRadius = 0.45f;++ int active;+ readonly List<ShellPiece> held = new List<ShellPiece>(); // pooled shells borrowed by this component (all returned on disable)+ /// <summary>Fires when any element skill hits (review tools use it to log hit frames).</summary>+ public static event System.Action<ElementSkill> AnyHit;+ ElementProfile P => profile;++ public override void Play()+ {+ if (!profile) { Debug.LogError($"[ElementSkill] {name}: no ElementProfile assigned", this); return; }+ string missing = profile.Validate();+ if (missing.Length > 0) Debug.LogError($"[ElementSkill] {profile.name}: missing {missing}", this);+ StartCoroutine(Cast(target));+ }++ protected override IEnumerator Run() { yield break; } // the base class's single-shot flow is not used++ protected override void OnDisable()+ {+ base.OnDisable();+ StopAllCoroutines(); // Unity doesn't stop coroutines on enabled=false: otherwise flight / crown coroutines would keep modifying shells already returned (and possibly borrowed by someone else)+ foreach (var s in held) if (s) s.Release();+ held.Clear();+ if (active > 0) { active = 0; RaiseFinished(); }+ }++ ShellPiece Take(Material m) { var s = ElementFX.Shell(m); held.Add(s); return s; }+ void Give(ShellPiece s) { if (!s) return; s.Release(); held.Remove(s); }++ Vector3 Hand => caster ? caster.HandPosition : HandPos;++ /// <summary>Hit point on the target: the surface facing the caster (the top when fromAbove), with per-element height from aimHeight.</summary>+ Vector3 Surface(Transform tgt, Vector3 lastKnown, Vector3 from)+ {+ Vector3 c = (tgt ? tgt.position + targetOffset : lastKnown) + Vector3.up * P.aimHeight;+ if (P.fromAbove) return c + Vector3.up * targetRadius * 0.9f + Vector3.ProjectOnPlane(from - c, Vector3.up).normalized * targetRadius * 0.4f;+ Vector3 toFrom = Vector3.ProjectOnPlane(from - c, Vector3.up);+ return c + (toFrom.sqrMagnitude > 1e-4f ? toFrom.normalized * targetRadius : Vector3.zero);+ }++ Vector3 Center(Transform tgt, Vector3 lastKnown) => tgt ? tgt.position + targetOffset : lastKnown;++ IEnumerator Cast(Transform tgt)+ {+ active++; IsPlaying = true;+ Vector3 lastKnown = tgt ? tgt.position + targetOffset : transform.TransformPoint(fallbackTarget);+ int stamp = caster ? caster.ReleaseStamp : 0;+ float charge = caster ? caster.Cast(P.castSpeed) : 0.4f;+ var pieces = new List<Object>();++ IEnumerator body = P.delivery == DeliveryType.Instant ? Lightning(tgt, lastKnown, charge, stamp, pieces)+ : P.delivery == DeliveryType.Eruption ? Eruption(tgt, lastKnown, charge, stamp, pieces)+ : Projectile(tgt, lastKnown, charge, stamp, pieces);+ yield return body;++ foreach (var o in pieces) if (o) { spawned.Remove(o); Destroy(o); }+ if (active > 0 && --active == 0) { IsPlaying = false; RaiseFinished(); }+ }++ /// <summary>Whether charging is done: Animator waits for the Release animation event (with a timeout fallback), Legacy goes by time.</summary>+ bool ChargeDone(float t, float charge, int stamp)+ {+ if (caster && caster.UsesReleaseEvent)+ {+ if (caster.ReleasedSince(stamp)) return true;+ if (t > charge + 1f) { Debug.LogWarning($"[ElementSkill] {caster.name}: Animator cast has no \"Release\" animation event — released by timeout (1 s late). Add the event to the cast clip.", caster); return true; }+ return false;+ }+ return t >= charge;+ }++ // ───────────────────────── Charge ─────────────────────────+ /// <summary>A small orb grows in the palm while secondary matter converges on the hand, until the cast animation releases.</summary>+ IEnumerator Charge(Transform orb, float charge, int stamp)+ {+ float t = 0;+ while (!ChargeDone(t, charge, stamp))+ {+ float k = Mathf.Clamp01(t / charge);+ orb.position = Hand;+ orb.localScale = Vector3.one * P.chargeSize * EaseOutBack(Mathf.Clamp01(k * 1.3f), 2.2f);+ ElementFX.Face(orb, P.spinDegPerSec * 0.5f * t);+ for (int i = ElementFX.Rate(28 * (1 - k * 0.6f), Time.deltaTime); i > 0; i--)+ {+ Vector3 p = Hand + Random.onUnitSphere * Random.Range(0.3f, 0.5f);+ ElementFX.Spark(p, (Hand - p) / 0.18f, Random.Range(0.04f, 0.07f), 0.18f, P.theme);+ }+ t += Time.deltaTime; yield return null;+ }+ }++ // ───────────────────────── Projectile ─────────────────────────+ IEnumerator Projectile(Transform tgt, Vector3 lastKnown, float charge, int stamp, List<Object> pieces)+ {+ var orb = ElementFX.Quad("Orb_" + P.displayName, P.orb, null); // world space: a scaled caster rig must not scale the orb+ pieces.Add(orb.gameObject); spawned.Add(orb.gameObject);+ orb.localScale = Vector3.zero;++ // 1) Charge+ yield return Charge(orb, charge, stamp);++ // 2) Flight: analytic trajectory + tracking target movement+ Vector3 hand = Hand;+ Vector3 aim0 = Surface(tgt, lastKnown, hand);+ float dist = Vector3.Distance(hand, aim0);+ float T = Mathf.Max(0.08f, dist / Mathf.Max(0.5f, P.speed)); // runtime clamp: even speed = 0 can't fly forever+ Vector3 g = Physics.gravity * P.gravityScale + Vector3.down * (P.lift > 0 ? 8f * P.lift / (T * T) : 0f);+ Vector3 v0 = (aim0 - hand) / T - 0.5f * g * T;+ ElementFX.Flash(hand, P.chargeSize * 2.2f, P.theme, 0.05f);+ float tf = 0, carry = 0, travelled = 0;+ Vector3 prev = hand, aim = aim0;+ while (true)+ {+ if (tgt) lastKnown = tgt.position + targetOffset;+ aim = Surface(tgt, lastKnown, hand);+ tf = Mathf.Min(tf + Time.deltaTime, T);+ float s = tf / T;+ Vector3 pos = hand + v0 * tf + 0.5f * g * tf * tf + (aim - aim0) * (s * s * (3 - 2 * s));+ Vector3 vel = v0 + g * tf;+ Vector3 d = vel.sqrMagnitude > 1e-6f ? vel.normalized : (aim - hand).normalized;+ float seg = Vector3.Distance(prev, pos);+ carry += seg;+ float spacing = Mathf.Max(0.01f, P.trailSpacing);+ int emits = 0;+ while (carry >= spacing && emits++ < 64) // trail: fill in by distance (frame-rate independent); at most 64 per frame so a tiny spacing can't hang+ {+ carry -= spacing;+ float back = seg > 1e-5f ? carry / seg : 0;+ EmitTrail(Vector3.Lerp(pos, prev, Mathf.Clamp01(back)), vel, d, travelled + seg - carry);+ }+ if (carry >= spacing) carry %= spacing;+ travelled += seg; prev = pos;+ if (tf >= T) break; // the contact frame is handled by the impact (orb, flash and body switch on the same frame)+ orb.position = pos;+ float flick = P.trail == TrailStyle.EmberSmoke ? 1 + 0.12f * Mathf.Sin(tf * 60) + 0.06f * Mathf.Sin(tf * 137) : 1 + 0.04f * Mathf.Sin(tf * 30);+ orb.localScale = Vector3.one * P.flightSize * flick;+ ElementFX.Face(orb, P.spinDegPerSec * tf);+ yield return null;+ }++ // 3) Impact+ orb.gameObject.SetActive(false);+ if (P.cutTrailOnHit) ElementFX.CutTrail(P.orb, 0.04f); // orb is gone: cut the trail within 1 frame (only for elements with the toggle on)+ Vector3 hitDir = (v0 + g * T).normalized;+ float hitTime = Time.time;+ Hit(tgt, lastKnown, aim, hitDir);+ yield return Linger(tgt, lastKnown, aim, hitDir);+ while (Time.time - hitTime < P.decalLife) yield return null; // the skill finishes only after the ground mark has fully faded+ }++ void EmitTrail(Vector3 p, Vector3 vel, Vector3 d, float travelled)+ {+ switch (P.trail)+ {+ case TrailStyle.Droplets: // water: droplets fling off carrying some of the velocity and fall under gravity+ ElementFX.Drop(p + Random.insideUnitSphere * 0.08f, vel * Random.Range(0.1f, 0.25f) + Random.insideUnitSphere * 0.5f + Vector3.down * 0.5f,+ Random.Range(0.05f, 0.09f), Random.Range(0.45f, 0.7f), Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ break;+ case TrailStyle.EmberSmoke: // fire: embers drift up + flame afterimages (no smoke in flight: small puffs read as grey rubble at a distance)+ ElementFX.Spark(p + Random.insideUnitSphere * 0.08f, Vector3.up * Random.Range(1.0f, 2.2f) + Random.insideUnitSphere * 0.5f,+ Random.Range(0.04f, 0.08f), Random.Range(0.35f, 0.6f), Color.Lerp(P.theme, new Color(1, 0.9f, 0.5f), 0.4f));+ ElementFX.TrailPuff(P.orb, p, P.flightSize * Random.Range(0.45f, 0.65f), 0.12f);+ break;+ case TrailStyle.ToxicDrip: // poison: drips fall one by one + an occasional small bubble (no smoke: reads as soot from afar)+ ElementFX.TrailPuff(P.orb, p, P.flightSize * Random.Range(0.45f, 0.6f), 0.14f); // afterimages of the poison orb join into a continuous stream (not scattered dots)+ if (Random.value < 0.35f)+ ElementFX.Drop(p + Random.insideUnitSphere * 0.06f, vel * 0.05f + Vector3.down * 0.6f, Random.Range(0.06f, 0.1f), 0.7f, P.theme, P.matter);+ if (Random.value < 0.15f)+ ElementFX.Bubble(p + Random.insideUnitSphere * 0.1f, Vector3.up * 0.3f, Random.Range(0.07f, 0.11f), 0.5f, Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ break;+ case TrailStyle.Helix: // wind: sheared airflow dashes (most velocity flung backward, stretched into dashes along the path), a few spiralling around the axis+ {+ Vector3 side = Vector3.Cross(d, Vector3.up).normalized, up = Vector3.Cross(side, d);+ float a = travelled * 9f + (Random.value < 0.5f ? 0 : Mathf.PI);+ Vector3 r = side * Mathf.Cos(a) + up * Mathf.Sin(a);+ ElementFX.Streak(p + r * Random.Range(0.12f, 0.28f), -d * Random.Range(5f, 8f) + Vector3.Cross(d, r) * 1.5f, 0.05f, 0.12f, Color.Lerp(P.theme, Color.white, 0.25f));+ if (Random.value < 0.3f) ElementFX.TrailPuff(P.orb, p, P.flightSize * 0.45f, 0.1f);+ break;+ }+ }+ }++ // ───────────────────────── Impact ─────────────────────────+ void Notify(Transform tgt, Vector3 p, Vector3 dir, float power)+ {+ if (!tgt) return;+ var hit = new ElementHit { element = P, point = p, direction = dir, power = power, source = this };+ foreach (var r in tgt.GetComponentsInParent<IElementHitReceiver>()) r.OnElementHit(hit);+ }++ /// <summary>+ /// Contact burst (the 'brightest 2–3 frames'): every element gets a small white-hot core + directional sparks + a short-range point light at the target's centre,+ /// plus the element-specific contact accent (profile.contact). tick = damage tick: only a small core + small star + a few sparks.+ /// </summary>+ void Burst(Vector3 p, Vector3 dir, float power, Vector3 center, bool tick = false)+ {+ var cam = Camera.main;+ Vector3 toCam = cam ? (cam.transform.position - p).normalized : -dir;+ Vector3 front = p + toCam * 0.3f;+ ElementFX.Flash(front, P.flashSize * 0.5f * Mathf.Lerp(0.6f, 1f, power), Color.white, 0.06f);+ // white-hot core: additive white is invisible on a white target, so the core is a small cel star (white core + element colour + matching dark rim), lit for only 2 frames+ ElementFX.Shape(P.star, front, P.flashSize * (tick ? 0.5f : 1.0f), 0.08f);+ ElementFX.LightFlash(center, P.theme, P.lightIntensity * power, P.lightRange, tick ? 0.08f : 0.12f);+ Vector3 fwd = Vector3.ProjectOnPlane(dir, Vector3.up).normalized;+ Color hot = Color.Lerp(P.theme, Color.white, 0.25f);+ int n = ElementFX.Count(Mathf.RoundToInt(P.sparkCount * (tick ? 0.35f : power)));+ for (int i = 0; i < n; i++) // directional spray along the hit direction (not a symmetric sphere), fast then slowing+ {+ Vector3 sd = (fwd * Random.Range(-0.3f, 0.5f) + Random.insideUnitSphere * 0.9f + Vector3.up * Random.Range(0.1f, 0.5f)).normalized;+ ElementFX.Streak(p, sd * Random.Range(6f, 11f), Random.Range(0.05f, 0.08f), Random.Range(0.14f, 0.24f), hot);+ ElementFX.Spark(p, sd * Random.Range(3f, 7f), Random.Range(0.06f, 0.11f), Random.Range(0.3f, 0.5f), P.theme);+ }+ if (tick) return;+ switch (P.contact)+ {+ case ContactAccent.Star: break; // core star only+ case ContactAccent.FoamRing: StartCoroutine(PlaneRing(front, Vector3.Slerp(-fwd, toCam, 0.6f).normalized, 0.3f, 1.6f, 0.16f, true)); break; // opens toward the camera so it reads as a ring+ case ContactAccent.AirRing:+ StartCoroutine(PlaneRing(p, Vector3.Slerp(Vector3.up, toCam, 0.45f).normalized, 0.6f, 2.6f, 0.2f, false));+ for (int i = 0, m = ElementFX.Count(12); i < m; i++) // airflow lines flung sideways + dust+ {+ Vector3 sd = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up).normalized;+ ElementFX.Streak(p, sd * Random.Range(7f, 11f), 0.06f, 0.25f, Color.Lerp(P.theme, Color.white, 0.4f));+ ElementFX.Smoke(ElementFX.GroundAt(p) + sd * 0.3f + Vector3.up * 0.1f, sd * Random.Range(1.5f, 2.5f) + Vector3.up * 0.3f, Random.Range(0.35f, 0.5f), 0.6f, new Color(0.78f, 0.74f, 0.64f, 0.35f), P.smoke);+ }+ break;+ case ContactAccent.ArcBurst: StartCoroutine(ArcBurst(p, toCam)); break;+ }+ }++ static Mesh ringQuad;+ static Mesh RingQuad()+ {+ if (ringQuad) return ringQuad;+ ringQuad = new Mesh { name = "RingQuad" };+ ringQuad.vertices = new[] { new Vector3(-0.5f, 0, -0.5f), new Vector3(0.5f, 0, -0.5f), new Vector3(-0.5f, 0, 0.5f), new Vector3(0.5f, 0, 0.5f) };+ ringQuad.uv = new[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) };+ ringQuad.uv2 = new[] { Vector2.one * 0.5f, Vector2.one * 0.5f, Vector2.one * 0.5f, Vector2.one * 0.5f };+ ringQuad.colors = new[] { Color.white, Color.white, Color.white, Color.white };+ ringQuad.normals = new[] { Vector3.up, Vector3.up, Vector3.up, Vector3.up };+ ringQuad.triangles = new[] { 0, 2, 1, 1, 2, 3 };+ ringQuad.RecalculateBounds();+ return ringQuad;+ }++ // ring opening in the plane defined by normal (water: foam ring along the hit surface that breaks into droplets; wind: horizontal pressure ring around the body)+ IEnumerator PlaneRing(Vector3 p, Vector3 normal, float from, float to, float life, bool tearIntoDrops)+ {+ var r = Take(P.ring); r.CopyMesh(RingQuad());+ r.transform.position = p; r.transform.rotation = Quaternion.FromToRotation(Vector3.up, normal) * Quaternion.Euler(0, Random.Range(0, 360f), 0);+ float t = 0; bool torn = false;+ while (t < life && r)+ {+ float k = t / life;+ r.transform.localScale = Vector3.one * Mathf.Lerp(from, to, EaseOutCubic(k));+ r.Set(Mathf.Clamp01((k - 0.35f) / 0.65f), 1f);+ if (tearIntoDrops && !torn && k > 0.6f)+ {+ torn = true;+ for (int i = 0, n = ElementFX.Count(16); i < n; i++)+ {+ float ang = Random.Range(0, Mathf.PI * 2);+ Vector3 o = r.transform.rotation * new Vector3(Mathf.Cos(ang), 0, Mathf.Sin(ang)) * to * 0.4f;+ ElementFX.Drop(p + o, o.normalized * Random.Range(1.5f, 2.5f) + Vector3.down * 0.3f, Random.Range(0.05f, 0.09f), 0.5f, Color.Lerp(P.theme, Color.white, 0.4f), P.matter);+ }+ }+ t += Time.deltaTime; yield return null;+ }+ Give(r);+ }++ // lightning contact: 4–5 short arcs radiating from the hit point, lit for 2 frames (not a white smoke puff)+ IEnumerator ArcBurst(Vector3 p, Vector3 toCam)+ {+ var cam = Camera.main; if (!cam) yield break;+ var arcs = new List<ShellPiece>();+ for (int i = 0; i < 4; i++) arcs.Add(Take(P.shell));+ for (int f = 0; f < 3; f++)+ {+ foreach (var a in arcs)+ {+ if (!a) continue;+ bool on = f < 2;+ a.Visible = (on);+ if (on)+ {+ Vector3 d = Vector3.Slerp(Random.onUnitSphere, toCam, 0.35f).normalized;+ BoltPath.Build(a.mesh, p + toCam * 0.2f, p + toCam * 0.2f + d * Random.Range(0.4f, 0.75f), cam.transform.position, 0.07f, 1, 0.3f, 3);+ }+ }+ yield return null;+ }+ foreach (var a in arcs) Give(a);+ }++ void Hit(Transform tgt, Vector3 lastKnown, Vector3 p, Vector3 dir)+ {+ AnyHit?.Invoke(this);+ Notify(tgt, p, dir, 1f);+ Burst(p, dir, 1f, Center(tgt, lastKnown));+ if (P.linger == LingerStyle.Drip) StartCoroutine(Streams(tgt, lastKnown, Color.Lerp(P.theme, Color.white, 0.5f), 8, 1.8f, 0.35f, P.matter, false, dir));+ // poison: no drips hanging on the face (art review: looked like a leaf stuck to the face); poisoning reads through the green flash on ticks + the bubbling pool+ Quaternion frame = Quaternion.LookRotation(Vector3.ProjectOnPlane(-dir, Vector3.up).normalized, Vector3.up);+ ElementFX.Body(P.impact, p + frame * P.impactOffset, Vector3.up * P.impactRise, P.impactSize, P.impactLife);+ switch (P.extra)+ {+ case ImpactExtra.CrownSplash: StartCoroutine(Crown(p, dir)); break;+ case ImpactExtra.Fireball: FireBurst(p); break;+ case ImpactExtra.Splat: Splat(tgt, lastKnown, p, dir); break;+ case ImpactExtra.Funnel: StartCoroutine(Funnel(tgt, p)); break;+ case ImpactExtra.Arcs: StartCoroutine(Arcs(tgt, lastKnown, 1.7f)); break;+ }+ ElementFX.GroundDecal(P.decal, Center(tgt, lastKnown), P.decalSize, P.decalLife, P.decalTint); // ground mark directly below the target+ HitFeel.Stop(P.hitStop);+ HitFeel.Shake(P.shake, P.shakeTime);+ if (P.ticks > 0) StartCoroutine(Ticks(tgt, lastKnown, dir));+ }++ /// <param name="raise">Extra height for ticks (m): while the water column lifts the target, ticks land at the lifted position</param>+ /// <param name="splashOnly">Splash only (while held up by the column): no star, since a star on the body looks like a misplaced sticker</param>+ /// <param name="raiseUntil">raise applies only before this time (Time.time): after the lift, ticks return to ground height instead of hitting mid-air</param>+ IEnumerator Ticks(Transform tgt, Vector3 lastKnown, Vector3 dir, float raise = 0f, bool splashOnly = false, float raiseUntil = float.MaxValue)+ {+ for (int i = 0; i < P.ticks; i++)+ {+ yield return new WaitForSeconds(P.tickInterval);+ Vector3 c = Center(tgt, lastKnown) + Vector3.up * (Time.time < raiseUntil ? raise : 0f) + Random.onUnitSphere * targetRadius * 0.8f;+ Vector3 d = P.extra == ImpactExtra.Funnel ? Vector3.up : dir;+ Notify(tgt, c, d, 0.35f);+ if (splashOnly)+ for (int k = 0, n = ElementFX.Count(8); k < n; k++)+ ElementFX.Drop(c, Random.insideUnitSphere * 1.5f + Vector3.up * Random.Range(1f, 2f), Random.Range(0.05f, 0.08f), 0.5f, Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ else Burst(c, d, 0.45f, Center(tgt, lastKnown), true); // tick: small core + small star + a few sparks + target flashes the element colour+ }+ }++ // water: two crown-shaped water sheets open from the hit surface toward the caster → droop under gravity → break into falling droplets+ /// <param name="droop">Sheets droop and sink under gravity (crown hitting the body); a crown from a ground eruption opens flat along the ground without drooping (otherwise it flips into a downward funnel, like the column stabbed into the ground)</param>+ /// <param name="life">Crown life (s): a landing crown must be quick (about 0.28 s), or the target looks like it is sitting in a blue bowl</param>+ IEnumerator Crown(Vector3 p, Vector3 dir, float scale = 1f, bool droop = true, float life = 0.62f)+ {+ Vector3 axis = (Vector3.ProjectOnPlane(-dir, Vector3.up).normalized * 0.75f + Vector3.up * 0.65f).normalized;+ var a = Take(P.shell); a.CopyMesh(CrownMesh());+ var b = Take(P.shell); b.CopyMesh(CrownMesh());+ float spinB = Random.Range(20f, 40f);+ float t = 0;+ bool dropped = false;+ while (t < life && a && b)+ {+ float k = t / life;+ for (int i = 0; i < 2; i++)+ {+ var piece = i == 0 ? a : b;+ float kk = Mathf.Clamp01((t - i * 0.05f) / life);+ float open = EaseOutCubic(Mathf.Clamp01(kk / 0.32f));+ Vector3 ax = droop ? Vector3.Slerp(axis, Vector3.down, kk * kk * 0.55f) : axis; // droop under gravity+ piece.transform.position = p + (droop ? Vector3.down * 0.4f * kk * kk : Vector3.zero);+ piece.transform.rotation = Quaternion.FromToRotation(Vector3.up, ax) * Quaternion.Euler(0, i * spinB, 0);+ float sc = (i == 0 ? 0.8f : 0.58f) * scale; // don't cover the target's face+ piece.transform.localScale = new Vector3(sc * (0.45f + 0.75f * open), sc * (0.25f + 0.85f * open), sc * (0.45f + 0.75f * open));+ piece.Set(Mathf.Clamp01((kk - 0.3f) / 0.7f), 0.88f); // translucent (target shows through); holes open and it breaks up after 0.3+ }+ if (!dropped && k > 0.35f) // sheet breaks → a ring of droplets falls outward and down (not tossed up)+ {+ dropped = true;+ for (int i = 0, n = ElementFX.Count(22); i < n; i++)+ {+ float ang = Random.Range(0, Mathf.PI * 2);+ Vector3 rim = Quaternion.FromToRotation(Vector3.up, axis) * new Vector3(Mathf.Cos(ang), 0.9f, Mathf.Sin(ang)) * 0.8f * scale;+ Vector3 v = Vector3.ProjectOnPlane(rim, Vector3.up).normalized * Random.Range(1.2f, 2.4f) + Vector3.up * Random.Range(-0.5f, 0.6f);+ ElementFX.Drop(p + rim, v, Random.Range(0.06f, 0.11f), Random.Range(0.45f, 0.65f), Color.Lerp(P.theme, Color.white, 0.25f), P.matter);+ }+ }+ t += Time.deltaTime; yield return null;+ }+ Give(a); Give(b);+ }++ static Mesh crownMesh, ribbonA, ribbonB, ribbonC;+ static Mesh CrownMesh() => crownMesh ? crownMesh : crownMesh = MeshBuilder.Build("Crown", 48, 8, (u, v) =>+ {+ float a = u * Mathf.PI * 2;+ float r = Mathf.Lerp(0.22f, 0.8f, Mathf.Pow(v, 0.8f)); // flared: wider toward the top+ float h = 0.9f * v * (1 - 0.18f * v);+ return new Vector3(r * Mathf.Cos(a), h, r * Mathf.Sin(a));+ }, 2f, 1f, wrapU: true);++ // fire: embers shoot up out of frame (negative gravity, bright head on top), a few fast rising fire streaks+ void FireBurst(Vector3 p)+ {+ Color ember = Color.Lerp(P.theme, new Color(1, 0.85f, 0.4f), 0.5f);+ for (int i = 0, n = ElementFX.Count(30); i < n; i++)+ ElementFX.Ember(p + Random.insideUnitSphere * 0.35f, Random.insideUnitSphere * 2.2f + Vector3.up * Random.Range(2.5f, 5f), Random.Range(0.07f, 0.13f), Random.Range(1.2f, 1.9f), ember);+ // small fireballs splashing along the ground: same cartoon atlas as the main fireball (same outline, shading, burning into curling smoke), spreading to both sides behind the target+ // (art review: soft grey smoke pushed along the ground read as a sticker and clashed with the cartoon fireball style; also keep it out of the foreground)+ Vector3 gp = ElementFX.GroundAt(p);+ Vector3 back = -LingerToCam(gp);+ for (int i = 0, n = ElementFX.Count(3); i < n; i++)+ {+ Vector3 o = Quaternion.Euler(0, Mathf.Lerp(-75f, 75f, n > 1 ? i / (n - 1f) : 0.5f) + Random.Range(-10f, 10f), 0) * back;+ ElementFX.Body(P.impact, gp + o * Random.Range(0.55f, 0.75f) + Vector3.up * 0.3f, o * 0.6f + Vector3.up * P.impactRise * 0.8f, P.impactSize * Random.Range(0.32f, 0.4f), P.impactLife * 0.7f);+ }+ }++ // poison: slams down from above → splatter (purple rim, green core) → sticky strands run down the target+ void Splat(Transform tgt, Vector3 lastKnown, Vector3 p, Vector3 dir)+ {+ for (int i = 0, n = ElementFX.Count(18); i < n; i++)+ {+ Vector3 v = Random.insideUnitSphere * 1.6f + Vector3.up * Random.Range(0.4f, 1.4f) + Vector3.ProjectOnPlane(-dir, Vector3.up).normalized * 0.6f;+ ElementFX.Drop(p + Random.insideUnitSphere * 0.2f, v, Random.Range(0.07f, 0.13f), Random.Range(0.6f, 0.9f), i % 3 == 0 ? P.dark * 1.6f : P.theme, P.matter); // one in three is a plum-purple drop+ }+ Vector3 c = Center(tgt, lastKnown);+ var cam = Camera.main;+ Vector3 toCam = cam ? Vector3.ProjectOnPlane(cam.transform.position - c, Vector3.up).normalized : -dir;+ // the running strands are handled by Streams (3 continuous sticky strands, not short lines scattered all over the body)+ }++ // wind: three 3D airflow bands spin around the target (a funnel, narrow at the bottom and wide at the top, from the ground up over the head), then tear apart from bottom to top and dissipate+ IEnumerator Funnel(Transform tgt, Vector3 p)+ {+ Vector3 g = ElementFX.GroundAt(p);+ var ribbons = new[] { Take(P.shell), Take(P.shell), Take(P.shell) };+ ribbons[0].CopyMesh(RibbonMesh(ref ribbonA, 0f, 1.25f));+ ribbons[1].CopyMesh(RibbonMesh(ref ribbonB, 0.33f, 1.05f));+ ribbons[2].CopyMesh(RibbonMesh(ref ribbonC, 0.66f, 0.9f));+ float life = 1.3f, t = 0, ang = 0;+ while (t < life)+ {+ float k = t / life;+ if (tgt) g = ElementFX.GroundAt(tgt.position);+ ang += Mathf.Lerp(720f, 220f, k) * Time.deltaTime; // fast then slowing+ float grow = EaseOutBack(Mathf.Clamp01(t / 0.18f), 1.4f);+ for (int i = 0; i < 3; i++)+ {+ var r = ribbons[i];+ if (!r) continue;+ r.transform.position = g;+ r.transform.rotation = Quaternion.Euler(0, -ang * (1 + i * 0.15f) + i * 120, 0);+ r.transform.localScale = new Vector3(grow, Mathf.Lerp(0.6f, 1f, grow), grow);+ r.Set(Mathf.Clamp01((k - 0.35f - i * 0.04f) / 0.5f), 1f - Mathf.SmoothStep(0, 1, (k - 0.75f) / 0.2f)); // tears from the bottom up from 0.35, then fades out as a whole instead of vanishing in one frame+ }+ if (Random.value < Time.deltaTime * 14 * (1 - k)) // dust swept up from the ground, spiralling outward+ {+ Vector3 o = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)).normalized;+ ElementFX.Smoke(g + o * 0.5f + Vector3.up * 0.1f, Vector3.Cross(Vector3.up, o) * 2.2f + o * 0.8f + Vector3.up * 0.4f, Random.Range(0.35f, 0.5f), 0.7f, new Color(0.78f, 0.74f, 0.64f, 0.28f), P.smoke);+ }+ if (Random.value < Time.deltaTime * 24 * (1 - k)) // swept-up leaves / debris+ ElementFX.Spark(g + Random.insideUnitSphere * 0.9f + Vector3.up * Random.Range(0.2f, 1.8f), Vector3.Cross(Vector3.up, Random.onUnitSphere) * 5f + Vector3.up * 2f, 0.07f, 0.35f, Color.Lerp(P.theme, Color.white, 0.3f));+ t += Time.deltaTime; yield return null;+ }+ foreach (var r in ribbons) Give(r);+ }++ static Mesh RibbonMesh(ref Mesh cache, float phase, float turns)+ {+ if (cache) return cache;+ float ph = phase;+ cache = MeshBuilder.Build("WindRibbon", 96, 4, (u, v) =>+ {+ float h = 0.1f + 1.0f * u; // from the lower body to the shoulders, keeping the face clear+ float r = Mathf.Lerp(0.42f, 1.05f, Mathf.Pow(u, 1.2f)); // narrow at the bottom, wide at the top+ float a = (u * turns + ph) * Mathf.PI * 2;+ Vector3 c = new Vector3(r * Mathf.Cos(a), h, r * Mathf.Sin(a));+ return c + Vector3.up * (v - 0.5f) * Mathf.Lerp(0.26f, 0.44f, u); // band widens toward the top+ }, 1f, 1f, alpha: (u, v) => 1f);+ // uv: u along the band (texture U), v across; uv2.y = height parameter (the material uses it for bottom-to-top erosion)+ var uv2 = cache.uv2; for (int i = 0; i < uv2.Length; i++) uv2[i] = new Vector2(uv2[i].x, uv2[i].x); cache.uv2 = uv2;+ return cache;+ }++ // arcs: crawl over the camera-facing side of the target (3 at once, reshaped every 1–2 frames), occasionally jumping to the ground, thinning out over time (usable by any element: ImpactExtra.Arcs)+ IEnumerator Arcs(Transform tgt, Vector3 lastKnown, float dur)+ {+ var cam = Camera.main; if (!cam) yield break;+ var arcs = new List<ShellPiece>(); var glows = new List<ShellPiece>();+ for (int i = 0; i < 3; i++) { arcs.Add(Take(P.shell)); glows.Add(P.glow ? Take(P.glow) : null); }+ var ground = Take(P.shell);+ float t = 0; int frame = 0;+ while (t < dur)+ {+ float k = t / dur;+ Vector3 c = Center(tgt, lastKnown);+ Vector3 toCam = (cam.transform.position - c).normalized;+ for (int i = 0; i < arcs.Count; i++)+ {+ if (!arcs[i]) continue;+ if ((frame + i) % 2 != 0) continue; // each arc reshapes every 2 frames, the three staggered+ bool show = i == 0 ? Random.value < 1.3f - k * 0.6f : Random.value < 1.1f - k * (1.1f + i * 0.3f); // thinning out, but the first arc stays until the end+ arcs[i].Visible = show; if (glows[i]) glows[i].Visible = show;+ if (!show) continue;+ // both ends on the camera-facing surface of the target (never floating in the air), chord 40–90 cm, shorter over time+ Vector3 BelowHead(Vector3 d) { d.y = Mathf.Min(d.y, -0.05f) ; return d.normalized; } // arcs stay below eye level (keep the face clear for the hit reaction)+ Vector3 a = c + BelowHead(Vector3.Slerp(Random.onUnitSphere, toCam, 0.6f)) * targetRadius * 1.05f, b = a;+ for (int tries = 0; tries < 8; tries++)+ {+ b = c + BelowHead(Vector3.Slerp(Random.onUnitSphere, toCam, 0.6f)) * targetRadius * 1.05f;+ float len = Vector3.Distance(a, b);+ if (len > 0.4f * (1 - k * 0.4f) && len < 0.9f) break;+ }+ BoltPath.Build(arcs[i].mesh, a, b, cam.transform.position, 0.085f, 1, 0.22f, 4, glows[i] ? glows[i].mesh : null, 3.2f);+ if (Random.value < 0.5f) for (int j = 0; j < 3; j++) ElementFX.Spark(a, Random.insideUnitSphere * 3f, 0.06f, 0.18f, P.theme);+ }+ bool jump = frame % 4 == 1 && Random.value < 1f - k * 0.7f; // occasionally one jumps to the ground+ ground.Visible = (jump);+ if (jump)+ {+ Vector3 gp = ElementFX.GroundAt(c) + new Vector3(Random.Range(-0.4f, 0.4f), 0.02f, Random.Range(-0.4f, 0.4f));+ BoltPath.Build(ground.mesh, c + toCam * targetRadius, gp, cam.transform.position, 0.085f, 1, 0.2f, 4);+ ElementFX.Shape(P.star, gp + Vector3.up * 0.05f, 0.35f, 0.05f); // on the frame it hits the ground, flash at the crack+ }+ frame++; t += Time.deltaTime; yield return null;+ }+ foreach (var a in arcs) Give(a); foreach (var g in glows) Give(g); Give(ground);+ }++ // ───────────────────────── Eruption (water column) ─────────────────────────+ // column atlas timing (profile.columnFrames) and the collapse moment (profile.columnHoldEnd) live in config, so swapping the atlas only changes data+ /// <summary>+ /// Charge → the water orb lobs low and dives in at the target's feet (cue: a small crown splashes up on landing) → a water ring spreads on the ground and bubbles as a warning →+ /// eruption (the brightest frame: white flash at the root + ground shock ring + radial splashes + water streaks shooting up the column) → the target is lifted to the top and held →+ /// the top collapses like an umbrella, rain falls from it and the target drops with it → wet ground.+ /// The column root sits on the ground behind the target (profile.columnBehind, from the camera direction at the moment of eruption; with an orbiting camera the root may end up off to the side):+ /// the target hides only the middle of the column, the column stays connected from the ground to the target's feet, and the face is always visible.+ /// columnFront (optional): an extra translucent front layer on top.+ /// </summary>+ IEnumerator Eruption(Transform tgt, Vector3 lastKnown, float charge, int stamp, List<Object> pieces)+ {+ var orb = ElementFX.Quad("Orb_" + P.displayName, P.orb, null); // world space: a scaled caster rig must not scale the orb+ pieces.Add(orb.gameObject); spawned.Add(orb.gameObject);+ orb.localScale = Vector3.zero;+ yield return Charge(orb, charge, stamp);++ // 1) the water orb lobs low and dives in at the target's feet (landing on the caster's side of the target so the landing is visible)+ Vector3 hand = Hand;+ Vector3 gp = ElementFX.GroundAt(Center(tgt, lastKnown));+ Vector3 toHand = Vector3.ProjectOnPlane(hand - gp, Vector3.up).normalized;+ Vector3 entry = gp + toHand * targetRadius * 0.9f;+ float T = Mathf.Max(0.12f, Vector3.Distance(hand, entry) / Mathf.Max(0.5f, P.speed));+ Vector3 g = Physics.gravity * P.gravityScale + Vector3.down * (P.lift > 0 ? 8f * P.lift / (T * T) : 0f); // same arc parameters as the projectile+ Vector3 v0 = (entry - hand) / T - 0.5f * g * T; // analytic trajectory: lands exactly on entry after T seconds+ ElementFX.Flash(hand, P.chargeSize * 2.2f, P.theme, 0.05f);+ float tf = 0, carry = 0, spacing = Mathf.Max(0.01f, P.trailSpacing); Vector3 prev = hand;+ while (tf < T)+ {+ tf = Mathf.Min(tf + Time.deltaTime, T);+ Vector3 pos = hand + v0 * tf + 0.5f * g * tf * tf, vel = v0 + g * tf;+ float seg = Vector3.Distance(prev, pos);+ carry += seg;+ for (int n = 0; carry >= spacing && n < 64; n++) // trail filled in by distance and interpolated along this frame's path (same as the projectile)+ {+ carry -= spacing;+ EmitTrail(Vector3.Lerp(pos, prev, seg > 1e-5f ? Mathf.Clamp01(carry / seg) : 0), vel, vel.normalized, 0);+ }+ if (carry >= spacing) carry %= spacing;+ prev = pos;+ orb.position = pos; orb.localScale = Vector3.one * P.flightSize * Mathf.Lerp(1f, 0.7f, tf / T);+ ElementFX.Face(orb, P.spinDegPerSec * tf);+ yield return null;+ }+ orb.gameObject.SetActive(false);++ // column root: from directly below the target, shift back by columnBehind (away from the camera, along the ground), so the column draws behind the target while the root, puddle and water rings share one spot on the ground+ var cam = Camera.main;+ Vector3 CamFlat(Vector3 at) => cam ? Vector3.ProjectOnPlane(cam.transform.position - at, Vector3.up).normalized : toHand;+ Vector3 Base(Vector3 under) => ElementFX.GroundAt(under - CamFlat(under) * P.columnBehind);+ Vector3 bp = Base(gp);++ // 2) dive: small crown + droplets splashing up; warning: a water ring spreads at the root + bubbles + a slight tremor+ if (P.extra == ImpactExtra.CrownSplash) StartCoroutine(Crown(entry + Vector3.up * 0.03f, Vector3.down, 0.55f, false));+ ElementFX.Shape(P.star, entry + Vector3.up * 0.15f, P.flashSize * 0.5f, 0.06f);+ for (int i = 0, n = ElementFX.Count(12); i < n; i++)+ ElementFX.Drop(entry + Random.insideUnitSphere * 0.1f, Random.insideUnitSphere * 1.2f + Vector3.up * Random.Range(1.5f, 2.6f), Random.Range(0.05f, 0.08f), 0.45f, Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ float decalLife = P.decalLife + P.warnTime + P.columnLife * 0.5f; // the wet mark lasts from the dive until after the column has collapsed+ ElementFX.GroundDecal(P.decal, bp, P.decalSize, decalLife, P.decalTint); // wet mark centred on the column root (the column bursts out of the puddle, and the target lands back in it)+ float decalStart = Time.time;+ if (P.ring) StartCoroutine(PlaneRing(bp + Vector3.up * 0.04f, Vector3.up, 0.3f, 1.4f, P.warnTime + 0.2f, false));+ HitFeel.Shake(P.shake * 0.3f, P.warnTime);+ float w = 0;+ while (w < P.warnTime)+ {+ if (tgt) { gp = ElementFX.GroundAt(Center(tgt, lastKnown = tgt.position + targetOffset)); bp = Base(gp); }+ for (int i = ElementFX.Rate(40, Time.deltaTime); i > 0; i--)+ ElementFX.Bubble(bp + new Vector3(Random.Range(-0.5f, 0.5f), 0.04f, Random.Range(-0.5f, 0.5f)), Vector3.up * Random.Range(0.4f, 0.9f), Random.Range(0.08f, 0.14f), 0.35f, Color.Lerp(P.theme, Color.white, 0.35f), P.matter);+ w += Time.deltaTime; yield return null;+ }++ // 3) eruption: the brightest frame of the sequence: white flash at the root + star + ground shock ring + radial splashes + water streaks shooting up the column; the target is lifted+ float hitTime = Time.time, hold = P.columnLife * P.columnHoldEnd;+ Vector3 sunk = bp + Vector3.down * P.columnHeight * P.columnRootInset; // in the atlas the column root is not at the very bottom of the cell: sink it so the root touches the ground+ ElementFX.Column(P.impact, sunk, P.columnHeight, P.columnAspect, P.columnLife, P.columnFrames);+ if (P.columnFront) ElementFX.Column(P.columnFront, sunk, P.columnHeight, P.columnAspect, P.columnLife, P.columnFrames);+ Vector3 c = Center(tgt, lastKnown);+ Vector3 toCam = CamFlat(gp);+ Vector3 root = gp + Vector3.up * P.flashSize * 0.85f + toCam * targetRadius; // root burst in front of the target's feet; centre raised above the flash radius so the quad doesn't cut into the ground and get a straight clipped edge+ AnyHit?.Invoke(this);+ bool lifted = false;+ if (tgt) foreach (var r in tgt.GetComponentsInParent<IElementHitReceiver>())+ {+ r.OnElementHit(new ElementHit { element = P, point = root, direction = Vector3.up, power = 1f, lift = P.columnLift, liftTime = hold, liftShift = Vector3.ProjectOnPlane(bp - gp, Vector3.up), liftGravity = P.columnFallGravity, source = this }); // lift over the column (horizontal shift only, so height doesn't change on slopes)+ lifted = true;+ }+ float landAt = 0f;+ if (lifted && P.columnLift > 0) // only a lifted target lands back in the puddle: play the landing ring after the lift ends + the free-fall time+ {+ landAt = hold + Mathf.Sqrt(2f * P.columnLift / Mathf.Max(1f, P.columnFallGravity));+ StartCoroutine(LandingSplash(bp, landAt));+ }+ ElementFX.Flash(root, P.flashSize * 1.6f, Color.white, 0.07f); // soft radial flash only (an outlined small star reads as a round sticker here)+ ElementFX.LightFlash(gp + Vector3.up * 1.2f, P.theme, P.lightIntensity, P.lightRange, 0.25f);+ if (P.ring) StartCoroutine(PlaneRing(bp + Vector3.up * 0.06f, Vector3.up, 0.6f, 2.4f, 0.3f, true)); // ground shock ring: fast, short, breaks into droplets+ if (P.extra == ImpactExtra.CrownSplash) StartCoroutine(Crown(bp + Vector3.up * 0.05f, Vector3.down, 1.2f, false));+ float colW = P.columnHeight * P.columnAspect;+ for (int i = 0, n = ElementFX.Count(P.sparkCount * 2); i < n; i++) // radial splashes: outward along the ground, slightly upward+ {+ Vector3 o = Quaternion.Euler(0, Random.Range(0, 360f), 0) * Vector3.forward;+ ElementFX.Drop(bp + o * colW * 0.2f + Vector3.up * 0.1f, o * Random.Range(2.5f, 4.5f) + Vector3.up * Random.Range(1.5f, 3f), Random.Range(0.06f, 0.11f), Random.Range(0.5f, 0.75f), Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ }+ for (int i = 0, n = ElementFX.Count(10); i < n; i++) // water streaks shooting up the column (sense of speed)+ {+ Vector3 o = Quaternion.Euler(0, Random.Range(0, 360f), 0) * Vector3.forward * colW * Random.Range(0.12f, 0.22f);+ ElementFX.Streak(bp + o + Vector3.up * Random.Range(0.1f, 0.8f), Vector3.up * Random.Range(10f, 15f), Random.Range(0.06f, 0.09f), Random.Range(0.18f, 0.28f), Color.Lerp(P.theme, Color.white, 0.45f));+ }+ HitFeel.Stop(P.hitStop);+ HitFeel.Shake(P.shake, P.shakeTime);+ if (P.ticks > 0) StartCoroutine(Ticks(tgt, lastKnown, Vector3.up, P.columnLift, true, hitTime + hold));++ // 4) the top collapses like an umbrella: rain falls from the rim (staggered over 0.35 s, not all at once), the target drops back to the ground, then water runs down its body+ while (Time.time - hitTime < hold) yield return null;+ Vector3 rim = bp + Vector3.up * P.columnHeight * P.columnRim; // actual rim height (not the column top)+ for (float r = 0; r < 0.35f; r += Time.deltaTime)+ {+ for (int i = ElementFX.Rate(110, Time.deltaTime); i > 0; i--)+ {+ Vector3 o = Quaternion.Euler(0, Random.Range(0, 360f), 0) * Vector3.forward * colW * Random.Range(0.25f, 0.45f);+ ElementFX.Drop(rim + o + Vector3.down * r * 2f, o.normalized * Random.Range(0.2f, 0.6f) + Vector3.down * Random.Range(1f, 2f), Random.Range(0.06f, 0.1f), Random.Range(0.7f, 1f), Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ }+ yield return null;+ }+ Vector3 flat = Vector3.ProjectOnPlane(c - hand, Vector3.up).normalized;+ if (P.linger == LingerStyle.Drip) StartCoroutine(Streams(tgt, lastKnown, Color.Lerp(P.theme, Color.white, 0.5f), 6, 0.8f, 0.35f, P.matter, false, flat));+ yield return Linger(tgt, lastKnown, c, flat);+ while (Time.time - hitTime < Mathf.Max(P.columnLife, landAt + 0.4f) || Time.time - decalStart < decalLife) yield return null; // finished only when the column, landing ring and ground mark have all faded+ }++ IEnumerator LandingSplash(Vector3 at, float delay)+ {+ if (delay > 0) yield return new WaitForSeconds(delay);+ // only a flat ring on the ground (spreading out, breaking into droplets) + droplets splashing outward; a 3D crown around the target's base reads as 'sitting in a blue bowl'+ if (P.ring) StartCoroutine(PlaneRing(at + Vector3.up * 0.05f, Vector3.up, 0.6f, 2.2f, 0.3f, true));+ for (int i = 0, n = ElementFX.Count(14); i < n; i++)+ {+ Vector3 o = Quaternion.Euler(0, (i + Random.value) * 360f / n, 0) * Vector3.forward;+ ElementFX.Drop(at + o * 0.4f + Vector3.up * 0.05f, o * Random.Range(1.8f, 3f) + Vector3.up * Random.Range(1f, 2f), Random.Range(0.05f, 0.09f), 0.5f, Color.Lerp(P.theme, Color.white, 0.3f), P.matter);+ }+ }++ // ───────────────────────── Lightning (instant) ─────────────────────────+ IEnumerator Lightning(Transform tgt, Vector3 lastKnown, float charge, int stamp, List<Object> pieces)+ {+ var cam = Camera.main;+ if (!cam) { Debug.LogError("[ElementSkill] lightning needs a camera to face", this); yield break; }+ var orb = ElementFX.Quad("Orb_" + P.displayName, P.orb, null); // world space: a scaled caster rig must not scale the orb+ pieces.Add(orb.gameObject); spawned.Add(orb.gameObject);+ var micro = Take(P.shell);+ float t = 0; int frame = 0;+ // 1) crackling charge in the palm: small orb + a new small arc every two or three frames+ while (!ChargeDone(t, charge, stamp))+ {+ Vector3 h = Hand;+ orb.position = h; orb.localScale = Vector3.one * P.chargeSize * (0.7f + 0.3f * Mathf.Clamp01(t / charge)) * (1 + 0.15f * Mathf.Sin(t * 70));+ ElementFX.Face(orb, Random.Range(0, 360f));+ bool show = frame % 3 != 2;+ micro.Visible = (show);+ if (show) BoltPath.Build(micro.mesh, h + Random.insideUnitSphere * 0.08f, h + Random.onUnitSphere * Random.Range(0.25f, 0.45f), cam.transform.position, 0.06f, 1, 0.25f, 3);+ for (int i = ElementFX.Rate(25, Time.deltaTime); i > 0; i--) ElementFX.Spark(h + Random.insideUnitSphere * 0.2f, Random.insideUnitSphere * 2.5f, 0.05f, 0.12f, P.theme);+ frame++; t += Time.deltaTime; yield return null;+ }+ orb.gameObject.SetActive(false); Give(micro);++ // 2) strikes scheduled in frames: main strike on frames 0–1, return stroke on frame 3, after-flash on frame 6 (each strike is guaranteed to be drawn, each with a different path)+ // Timing is counted in frames so every strike is visible for at least 1 frame at any frame rate; the whole sequence is about 0.12 s at 60 fps, 0.23 s at 30 fps.+ Vector3 hand = Hand;+ Vector3 aim = Surface(tgt, lastKnown, hand);+ Vector3 dir = (aim - hand).normalized;+ var bolt = Take(P.shell);+ var glow = P.glow ? Take(P.glow) : null;+ int[] strikeFrames = { 0, 1, 3, 6 };+ float[] width = { 0.3f, 0.28f, 0.24f, 0.2f };+ float[] power = { 1f, 0f, 0.6f, 0.45f };+ int si = 0;+ float hitTime = Time.time;+ for (int f = 0; f <= 7; f++)+ {+ hand = Hand; // the bolt root stays attached to the hand (the hand is moving)+ if (tgt) { lastKnown = tgt.position + targetOffset; aim = Surface(tgt, lastKnown, hand); }+ bool on = si < strikeFrames.Length && strikeFrames[si] == f;+ bolt.Visible = (on); if (glow) glow.Visible = on;+ if (on)+ {+ BoltPath.Build(bolt.mesh, hand, aim, cam.transform.position, width[si], si == 0 ? 3 : 2, 0.13f, 5, glow ? glow.mesh : null);+ bolt.Set(0, 1f);+ if (f == 0) { Hit(tgt, lastKnown, aim, dir); ElementFX.Flash(hand, P.chargeSize * 2.5f, P.theme, 0.05f); }+ else if (power[si] > 0) { Notify(tgt, aim, dir, power[si]); Burst(aim, dir, power[si], Center(tgt, lastKnown), true); }+ si++;+ }+ yield return null;+ }+ Give(bolt); Give(glow);+ yield return Linger(tgt, lastKnown, aim, dir);+ while (Time.time - hitTime < P.decalLife) yield return null;+ }++ // a few streams down the camera-facing side of the target: each has a fixed start point that emits a drop every few frames.+ // sticky=false (water): small droplets slide quickly down the body and fall under gravity once they leave the lower edge, reading as flowing water.+ // sticky=true (poison): thick poison first clings and stretches, then drops faster and faster, reading as sticky strands.+ IEnumerator Streams(Transform tgt, Vector3 lastKnown, Color col, int count, float dur, float startH, Material mat, bool sticky, Vector3 hitDir)+ {+ var cam = Camera.main;+ var offs = new Vector3[count];+ // start points on the half facing away from the caster (the face looks toward the caster): streams run from the side / back of the head and never over the eyes+ Vector3 c0 = Center(tgt, lastKnown);+ Vector3 toCam0 = cam ? Vector3.ProjectOnPlane(cam.transform.position - c0, Vector3.up).normalized : Vector3.back;+ float away = Mathf.Sign(Vector3.Dot(Vector3.Cross(Vector3.up, toCam0), hitDir) + 1e-4f);+ for (int i = 0; i < count; i++) offs[i] = new Vector3(away * Mathf.Lerp(0.2f, 0.7f, (i + Random.value * 0.5f) / count), startH + Random.Range(-0.25f, 0.1f), 0); // keep the three apart instead of merging into one+ float t = 0, next = 0;+ while (t < dur)+ {+ if (t >= next)+ {+ next = t + (sticky ? Random.Range(0.16f, 0.22f) : Random.Range(0.08f, 0.12f)); // poison: drop by drop, each stream staggered+ Vector3 c = Center(tgt, lastKnown);+ Vector3 toCam = cam ? Vector3.ProjectOnPlane(cam.transform.position - c, Vector3.up).normalized : Vector3.back;+ Vector3 side = Vector3.Cross(Vector3.up, toCam);+ for (int i = 0; i < count; i++)+ {+ if (sticky && Mathf.Repeat(t / 0.5f + i / (float)count, 1f) > 0.3f) continue; // poison: three staggered streams, one drop per stream every 0.5 s+ if (Random.value < t / dur * 0.6f) continue; // thinning out+ Vector3 o = side * offs[i].x * targetRadius + Vector3.up * offs[i].y * targetRadius;+ float surf = Mathf.Sqrt(Mathf.Max(0.05f, 1 - (offs[i].x * offs[i].x + offs[i].y * offs[i].y) * 0.8f));+ Vector3 p = c + o + toCam * targetRadius * (surf + 0.12f);+ if (sticky) ElementFX.Goo(p, Vector3.down * 0.1f, 0.16f, 0.55f, col, mat); // heavy drop head with a short tail+ else+ {+ bool big = Random.value < 0.25f; // an occasional big droplet (with highlight) that stretches as it leaves the lower edge and falls into the water stain+ ElementFX.Drop(p, Vector3.down * Random.Range(0.8f, 1.3f) + toCam * 0.15f, big ? 0.12f : Random.Range(0.06f, 0.09f), Random.Range(0.5f, 0.7f), big ? Color.Lerp(col, Color.white, 0.4f) : col, mat);+ }+ }+ }+ t += Time.deltaTime; yield return null;+ }+ }++ // ───────────────────────── Linger ─────────────────────────+ static Vector3 LingerToCam(Vector3 at)+ {+ var cam = Camera.main;+ Vector3 d = cam ? Vector3.ProjectOnPlane(cam.transform.position - at, Vector3.up) : Vector3.back;+ return d.sqrMagnitude > 1e-6f ? d.normalized : Vector3.back;+ }++ IEnumerator Linger(Transform tgt, Vector3 lastKnown, Vector3 p, Vector3 dir)+ {+ float dur = P.lingerTime, t = 0;+ Vector3 gp = ElementFX.GroundAt(Center(tgt, lastKnown));+ while (t < dur)+ {+ float k = 1 - t / dur, dt = Time.deltaTime;+ Vector3 c = Center(tgt, lastKnown);+ switch (P.linger)+ {+ case LingerStyle.Drip: // water: a few streams slowly run down the camera-facing side, dripping from the sides and bottom edge (never onto the face), tapering off+ {+ var wcam = Camera.main; Vector3 wToCam = wcam ? Vector3.ProjectOnPlane(wcam.transform.position - c, Vector3.up).normalized : -dir;+ // (the running streams are handled by Streams)+ }+ for (int i = ElementFX.Rate(24 * k, dt); i > 0; i--)+ {+ float side = Random.value < 0.5f ? -1 : 1;+ Vector3 o = new Vector3(side * Random.Range(0.35f, 0.5f), Random.Range(-0.55f, -0.1f), Random.Range(-0.3f, 0.3f));+ ElementFX.Drop(c + Quaternion.LookRotation(-dir) * o, Vector3.down * 0.3f, Random.Range(0.04f, 0.08f), 0.6f, Color.Lerp(P.theme, Color.white, 0.25f), P.matter);+ }+ break;+ case LingerStyle.Smolder: // fire: embers rise out of frame from the scorch mark and the target, faint smoke billows up from behind the target (in front it reads as an ink blot stuck on the body), embers in the scorch flicker 2–3 times+ if (Random.value < dt * 2.2f * k) ElementFX.LightFlash(gp + Vector3.up * 0.2f, new Color(1f, 0.32f, 0.08f), 2f, 1.4f, 0.25f); // reddish: orange light on greenish ground turns yellow-green+ for (int i = ElementFX.Rate(22 * k, dt); i > 0; i--)+ ElementFX.Ember((Random.value < 0.5f ? gp : c) + Random.insideUnitSphere * 0.5f + Vector3.up * 0.05f, Vector3.up * Random.Range(1f, 2.4f) + Random.insideUnitSphere * 0.3f, Random.Range(0.05f, 0.09f), Random.Range(1.0f, 1.6f), P.theme);+ for (int i = ElementFX.Rate(5 * k, dt); i > 0; i--)+ ElementFX.Smoke(gp - LingerToCam(gp) * (targetRadius + 0.2f) + Random.insideUnitSphere * 0.3f + Vector3.up * 0.2f, Vector3.up * Random.Range(0.8f, 1.2f), Random.Range(0.3f, 0.45f), 0.9f, new Color(0.55f, 0.5f, 0.48f, 0.3f), P.smoke);+ break;+ case LingerStyle.Pool: // poison: pool bubbles (rise, swell, pop) + low ground mist spreading outward + still running down the target+ for (int i = ElementFX.Rate(16 * k, dt); i > 0; i--)+ ElementFX.Bubble(gp + new Vector3(Random.Range(-0.7f, 0.7f), 0.05f, Random.Range(-0.7f, 0.7f)), Vector3.up * Random.Range(0.15f, 0.35f), Random.Range(0.15f, 0.28f), Random.Range(0.6f, 0.9f), Color.Lerp(P.theme, Color.white, 0.15f), P.matter);+ for (int i = ElementFX.Rate(7 * k, dt); i > 0; i--)+ {+ Vector3 o = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f)).normalized;+ ElementFX.Smoke(gp + o * 0.35f + Vector3.up * 0.15f, o * Random.Range(0.4f, 0.7f) + Vector3.up * 0.04f, Random.Range(1.0f, 1.4f), Random.Range(1.2f, 1.6f), new Color(0.66f, 0.84f, 0.5f, 0.16f), P.smoke); // faint, large mist spreading along the ground+ }+ var lcam = Camera.main; Vector3 lToCam = lcam ? Vector3.ProjectOnPlane(lcam.transform.position - c, Vector3.up).normalized : -dir;+ // (strands are handled by Streams)+ break;+ case LingerStyle.Swirl: // wind: leftover swirl lines wind down+ for (int i = ElementFX.Rate(18 * k, dt); i > 0; i--)+ {+ float a = Random.Range(0, Mathf.PI * 2); Vector3 r = new Vector3(Mathf.Cos(a), 0, Mathf.Sin(a));+ ElementFX.Streak(gp + r * 0.9f + Vector3.up * Random.Range(0.1f, 1.2f), Vector3.Cross(Vector3.up, r) * 5f + Vector3.up * 1.2f, 0.05f, 0.25f, Color.Lerp(P.theme, Color.white, 0.2f));+ }+ break;+ case LingerStyle.Static: // lightning: small sparks jumping along the ground cracks, thinning out+ if (Random.value < dt * 14 * k)+ {+ Vector3 sp = gp + new Vector3(Random.Range(-0.5f, 0.5f), 0.05f, Random.Range(-0.5f, 0.5f));+ ElementFX.Shape(P.star, sp + Vector3.up * 0.05f, Random.Range(0.25f, 0.4f), 0.08f);+ for (int i = 0; i < 3; i++) ElementFX.Spark(sp, Random.insideUnitSphere * 2f + Vector3.up, 0.05f, 0.14f, P.theme);+ }+ break;+ }+ t += dt; yield return null;+ }+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/HitFeel.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/HitFeel.csnew file mode 100644index 0000000..d229923--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/HitFeel.cs@@ -0,0 +1,156 @@+using System.Collections.Generic;+using UnityEngine;+using UnityEngine.Rendering;++namespace VfxSkill+{+ /// <summary>+ /// Layered time scale: Time.timeScale = (Paused ? 0 : BaseScale) × (in hit stop ? 0.03 : 1).+ /// For game pause / slow motion, set GameTime.Paused / GameTime.BaseScale instead of writing Time.timeScale directly.+ /// Compatibility with legacy code that bypasses this: when an external write is detected —+ /// writing 0 → treated as pause; writing back the frozen value (the 0.03 that old pause code saved mid-freeze and restores on unpause) → treated as unpause, base scale unchanged;+ /// any other value → treated as the new base scale. So pausing in the middle of a hit stop never leaves the game stuck at 3% speed.+ /// </summary>+ public static class GameTime+ {+ static bool paused; static float baseScale = 1f; static bool freezing;+ static float lastWritten = 1f, lastFreezeRealTime = -100f;+ public const float FrozenScale = 0.03f;+ /// <summary>Compatibility with legacy pause code that writes Time.timeScale directly (see class comment). Turn this off if your project uses 3% slow motion itself.</summary>+ public static bool AbsorbLegacyWrites = true;++ public static bool Paused { get { Sync(); return paused; } set { Sync(); paused = value; Apply(); } }+ public static float BaseScale { get { Sync(); return baseScale; } set { Sync(); baseScale = Mathf.Max(0, value); Apply(); } }+ /// <summary>Hit stop flag (driven by HitFeel; tests may set it directly).</summary>+ public static bool Freezing+ {+ get => freezing;+ set { Sync(); if (freezing || value) lastFreezeRealTime = Time.realtimeSinceStartup; freezing = value; Apply(); }+ }++ /// <summary>Absorbs external writes to Time.timeScale.</summary>+ public static void Sync()+ {+ float v = Time.timeScale;+ if (Mathf.Approximately(v, lastWritten)) return;+ bool recentFreeze = freezing || Time.realtimeSinceStartup - lastFreezeRealTime < 2f;+ if (v <= 0f) paused = true;+ else if (AbsorbLegacyWrites && recentFreeze && (Mathf.Approximately(v, baseScale * FrozenScale) || Mathf.Approximately(v, FrozenScale)))+ paused = false; // old pause code restored the value it saved during the freeze+ else { paused = false; baseScale = v; }+ Apply(); // write the correct value back immediately (e.g. old code restored 0.03 after the freeze had already ended)+ }++ static void Apply()+ {+ float v = paused ? 0f : baseScale * (freezing ? FrozenScale : 1f);+ Time.timeScale = v; lastWritten = v;+ }++ /// <summary>Resets to defaults (called automatically on entering Play Mode, so static state doesn't leak into the next run when domain reload is disabled).</summary>+ [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]+ public static void ResetAll() { paused = false; baseScale = 1f; freezing = false; lastFreezeRealTime = -100f; Apply(); }+ }++ /// <summary>+ /// Hit-feel service: hit stop + camera shake. A single global instance that persists across scenes and doesn't depend on any particular camera.+ /// Hit stop: timed in real seconds (recording frame interval when recording offline); total freeze within any sliding 1 s window is capped at maxFreezePerSecond, so rapid hits can't keep the game frozen;+ /// it neither counts down nor resumes while paused. Time scale is written only through GameTime.+ /// Shake: an offset is applied before the camera renders and undone after, without touching the camera Transform, so it doesn't fight Cinemachine or other camera controllers; only the main Game camera shakes (not UI / render-texture cameras).+ /// </summary>+ public class HitFeel : MonoBehaviour+ {+ static HitFeel _inst;+ static HitFeel I+ {+ get+ {+ if (_inst) return _inst;+ var go = new GameObject("[HitFeel]") { hideFlags = HideFlags.HideAndDontSave };+ if (Application.isPlaying) DontDestroyOnLoad(go);+ _inst = go.AddComponent<HitFeel>();+ return _inst;+ }+ }++ /// <summary>Maximum total freeze within any 1 s (s).</summary>+ public static float maxFreezePerSecond = 0.15f;++ float freezeLeft, clock;+ readonly Queue<(float t, float d)> history = new Queue<(float, float)>(); // freeze amount per frame in real time (sliding window)+ float windowSum;+ float shakeAmp, shakeDur, shakeT;+ Camera shakenCam; Vector3 shakeOffset;++ /// <summary>Hit stop for seconds (real time).</summary>+ public static void Stop(float seconds)+ {+ if (seconds <= 0) return;+ var h = I;+ if (h.Budget <= 0) return; // budget used up: this hit doesn't freeze and its duration isn't recorded+ h.freezeLeft = Mathf.Max(h.freezeLeft, seconds); // new hits don't stack; they only extend to the longer one+ if (!GameTime.Freezing) GameTime.Freezing = true;+ }++ public static void Shake(float amplitude, float duration)+ {+ var h = I;+ if (amplitude < h.shakeAmp * (1 - h.shakeT / Mathf.Max(h.shakeDur, 1e-3f))) return; // don't interrupt a stronger shake+ h.shakeAmp = amplitude; h.shakeDur = duration; h.shakeT = 0;+ }++ /// <summary>Ends hit stop and shake immediately (call on camera cuts and scene changes).</summary>+ public static void ResetAll()+ {+ if (!_inst) return;+ _inst.freezeLeft = 0; GameTime.Freezing = false;+ _inst.shakeT = _inst.shakeDur;+ }++ float Budget => maxFreezePerSecond - windowSum;+ static float RealDelta => Time.captureDeltaTime > 0 ? Time.captureDeltaTime : Time.unscaledDeltaTime;++ void Update()+ {+ GameTime.Sync();+ float d = RealDelta;+ clock += d;+ while (history.Count > 0 && history.Peek().t < clock - 1f) windowSum -= history.Dequeue().d;+ if (GameTime.Freezing)+ {+ if (GameTime.Paused) return; // paused: don't count down+ freezeLeft -= d;+ history.Enqueue((clock, d)); windowSum += d;+ if (freezeLeft <= 0 || Budget <= 0) { freezeLeft = 0; GameTime.Freezing = false; }+ }+ if (shakeT < shakeDur) shakeT += d;+ }++ void OnEnable()+ {+ RenderPipelineManager.beginCameraRendering += Begin;+ RenderPipelineManager.endCameraRendering += End;+ }++ void OnDisable()+ {+ RenderPipelineManager.beginCameraRendering -= Begin;+ RenderPipelineManager.endCameraRendering -= End;+ if (GameTime.Freezing) GameTime.Freezing = false;+ }++ void Begin(ScriptableRenderContext ctx, Camera cam)+ {+ if (shakeT >= shakeDur || cam.cameraType != CameraType.Game || cam.targetTexture || cam != Camera.main) return;+ float k = 1 - shakeT / shakeDur;+ shakeOffset = (cam.transform.right * Mathf.Sin(shakeT * 90) + cam.transform.up * Mathf.Cos(shakeT * 77)) * shakeAmp * k * k;+ cam.transform.position += shakeOffset; shakenCam = cam;+ }++ void End(ScriptableRenderContext ctx, Camera cam)+ {+ if (cam != shakenCam) return;+ cam.transform.position -= shakeOffset; shakenCam = null; shakeOffset = Vector3.zero;+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/MeshBuilder.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/MeshBuilder.csnew file mode 100644index 0000000..1b0e6ac--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/MeshBuilder.cs@@ -0,0 +1,73 @@+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Procedural meshes for the element skills. All are parametric surfaces pos(u, v):+ /// u ∈ [0,1] along the main direction (around / length), v ∈ [0,1] along the secondary direction (height / width).+ /// Normals and tangents come from finite differences (tangent = ∂pos/∂u, which anisotropic highlights in a shader rely on).+ /// Without flipping, normal = ∂v × ∂u, so surfaces parameterised by (azimuth, height) face outward; Tube/Ring need flip.+ /// </summary>+ public static class MeshBuilder+ {+ public delegate Vector3 Surface(float u, float v);++ public static Mesh Build(string name, int nu, int nv, Surface f, float uRepeat, float vRepeat,+ bool wrapU = false, bool flip = false, System.Func<float, float, float> alpha = null)+ {+ int cols = nu + 1, rows = nv + 1;+ var pos = new Vector3[cols * rows];+ var col = new Color[pos.Length];+ var uv2 = new Vector2[pos.Length];+ var nrm = new Vector3[pos.Length];+ var tan = new Vector4[pos.Length];+ var uv = new Vector2[pos.Length];+ const float e = 1e-3f;+ for (int j = 0; j < rows; j++)+ for (int i = 0; i < cols; i++)+ {+ float u = (float)i / nu, v = (float)j / nv;+ int k = j * cols + i;+ pos[k] = f(u, v);+ float u0 = wrapU ? u - e : Mathf.Max(0, u - e), u1 = wrapU ? u + e : Mathf.Min(1, u + e);+ float v0 = Mathf.Max(0, v - e), v1 = Mathf.Min(1, v + e);+ // Note: Vector3.Normalize returns 0 for vectors shorter than 1e-5, which finite differences on small meshes can fall below, so everything is normalised by hand+ Vector3 du = SafeNorm(f(u1, v) - f(u0, v), Vector3.zero);+ Vector3 dv = SafeNorm(f(u, v1) - f(u, v0), Vector3.zero);+ Vector3 n = SafeNorm(Vector3.Cross(dv, du), Vector3.up); // fall back to up at degenerate points such as poles+ if (flip) n = -n;+ nrm[k] = n;+ Vector3 t = du == Vector3.zero ? Vector3.right : du;+ // Unity convention: B = cross(N, T) * w; here w makes B point along +v+ tan[k] = new Vector4(t.x, t.y, t.z, flip ? 1 : -1);+ uv[k] = new Vector2(u * uRepeat, v * vRepeat);+ uv2[k] = new Vector2(u, v); // normalised parameter coordinates (for shape masks)+ col[k] = new Color(1, 1, 1, alpha != null ? Mathf.Clamp01(alpha(u, v)) : 1f); // vertex alpha: fade at the ends+ }+ var tris = new int[nu * nv * 6];+ int ti = 0;+ for (int j = 0; j < nv; j++)+ for (int i = 0; i < nu; i++)+ {+ int a = j * cols + i, b = a + 1, c = a + cols, d = c + 1;+ if (!flip) { tris[ti++] = a; tris[ti++] = c; tris[ti++] = b; tris[ti++] = b; tris[ti++] = c; tris[ti++] = d; }+ else { tris[ti++] = a; tris[ti++] = b; tris[ti++] = c; tris[ti++] = b; tris[ti++] = d; tris[ti++] = c; }+ }+ var m = new Mesh { name = name };+ if (pos.Length > 65000) m.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;+ m.vertices = pos; m.normals = nrm; m.tangents = tan; m.uv = uv; m.uv2 = uv2; m.colors = col; m.triangles = tris;+ m.RecalculateBounds();+ return m;+ }++ static Vector3 SafeNorm(Vector3 v, Vector3 fallback)+ {+ float m = Mathf.Sqrt(v.x * v.x + v.y * v.y + v.z * v.z);+ return m > 1e-12f ? v / m : fallback;+ }++ static float TwoPi => Mathf.PI * 2;++ /// <summary>Hemisphere shield with its base at y=0.</summary>+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/PaintedFX.shader b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/PaintedFX.shadernew file mode 100644index 0000000..825b617--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/PaintedFX.shader@@ -0,0 +1,96 @@+// Hand-painted effect textures (e.g. AI-generated, anime-style element textures).+// Keeps the painting as is and only adds: slight flow-noise UV distortion (so painted water feels alive) + soft erosion fade-out + HDR tint.+// Meshes drive erosion with _Erosion; particles with vertex alpha (Color over Lifetime).+Shader "VfxSkill/PaintedFX"+{+ Properties+ {+ _MainTex ("Painted Texture (RGBA)", 2D) = "white" {}+ _NoiseTex ("Distortion Noise (RG)", 2D) = "gray" {}+ [HDR]_Tint ("Tint", Color) = (1.15, 1.15, 1.2, 1)+ _Distort ("UV distortion amount", Range(0, 0.05)) = 0.008+ _DistortScale ("Distortion scale (xy) scroll (zw)", Vector) = (2, 2, 0.15, -0.3)+ _Erosion ("Erosion", Range(0, 1)) = 0+ _AlphaBoost ("Alpha boost", Range(0.5, 3)) = 1.4+ _Soft ("Erosion softness", Range(0.01, 0.6)) = 0.25+ _ErodeNoise ("Erosion noise", Range(0, 1)) = 0.45+ _SoftFade ("Soft particle distance", Float) = 0.1+ _TimeOffset ("Time offset", Float) = 0+ _CamPush ("Push toward camera (m)", Float) = 0+ _Tiles ("Flipbook tiles cols/rows (particle sheet)", Vector) = (8, 8, 0, 0)+ _Grow ("Particle sheet: start scale, grow time (0 = default curve)", Vector) = (0, 0, 0, 0)+ _Flip ("Self-animated loop on a quad: cols, rows, fps (0 = off)", Vector) = (1, 1, 0, 0)+ [Toggle(_SOFTPARTICLES)] _SoftOn ("Soft particles (needs depth texture)", Float) = 1+ [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Src Blend", Float) = 5+ [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Dst Blend", Float) = 10+ [Enum(UnityEngine.Rendering.CullMode)] _Cull ("Cull", Float) = 0+ }+ SubShader+ {+ Tags { "RenderType" = "Transparent" "Queue" = "Transparent" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }+ Pass+ {+ Tags { "LightMode" = "UniversalForward" }+ Blend [_SrcBlend] [_DstBlend]+ ZWrite Off+ Cull [_Cull]+ HLSLPROGRAM+ #pragma vertex vert+ #pragma fragment frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ #pragma shader_feature_local _SOFTPARTICLES+ #if defined(_SOFTPARTICLES)+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"+ #endif+ TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);+ TEXTURE2D(_NoiseTex); SAMPLER(sampler_NoiseTex);+ CBUFFER_START(UnityPerMaterial)+ float4 _MainTex_ST, _NoiseTex_ST, _DistortScale, _Tiles, _Flip;+ half4 _Tint;+ float _Distort, _Erosion, _AlphaBoost, _Soft, _ErodeNoise, _SoftFade, _TimeOffset, _SrcBlend, _DstBlend, _Cull, _CamPush, _SoftOn;+ CBUFFER_END+ struct A { float4 pos : POSITION; float2 uv : TEXCOORD0; half4 col : COLOR; };+ struct V { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; half4 col : COLOR; float4 sp : TEXCOORD1; float2 cell : TEXCOORD2; };+ V vert(A i)+ {+ V o;+ float3 w = TransformObjectToWorld(i.pos.xyz);+ float camDist = distance(_WorldSpaceCameraPos, w);+ w += (_WorldSpaceCameraPos - w) / max(camDist, 1e-4) * min(_CamPush, max(0, camDist - _ProjectionParams.y * 4)); // never push past the near plane // push the impact flipbook toward the camera so the target model doesn't hide it; updates live as the camera moves+ o.pos = TransformWorldToHClip(w); o.uv = TRANSFORM_TEX(i.uv, _MainTex); o.col = i.col; o.sp = ComputeScreenPos(o.pos);+ o.cell = -1; // <0: plain texture, uv is the atlas uv+ if (_Flip.z > 0) // orb in flight (e.g. fireball): the quad loops the atlas itself (first cell at top left)+ {+ float2 grid = max(_Flip.xy, 1);+ float frames = grid.x * grid.y;+ float f = min(floor(frac((_Time.y + _TimeOffset) * _Flip.z / frames) * frames), frames - 1); // frac stays in 0–1 even for negative time+ o.cell = float2(fmod(f, grid.x), grid.y - 1 - floor(f / grid.x));+ o.uv = saturate(i.uv); // cell-local uv: distortion and noise are computed within the cell, then mapped to the atlas in the fragment stage+ }+ return o;+ }+ half4 frag(V i) : SV_Target+ {+ float t = _Time.y + _TimeOffset;+ half2 n = SAMPLE_TEXTURE2D(_NoiseTex, sampler_NoiseTex, i.uv * _DistortScale.xy + _DistortScale.zw * t).rg;+ float2 uv = i.uv + (n - 0.5) * 2 * _Distort;+ if (i.cell.x >= 0) uv = (saturate(uv) + i.cell) / max(_Flip.xy, 1); // self-looping atlas: clamp the distorted uv to this cell so it can't bleed into neighbouring frames+ half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv);+ tex.a = saturate(tex.a * _AlphaBoost); // painted water needs more opacity on bright backgrounds+ // erosion: combine mesh _Erosion with particle vertex alpha; noise breaks up the vanishing edge+ float e = saturate(_Erosion + (1 - i.col.a));+ float m = tex.a * (1 - _ErodeNoise + _ErodeNoise * n.g * 1.6);+ // e=0 fully kept, e=1 fully gone; the threshold advances smoothly in between+ half a = tex.a * smoothstep(e, e + _Soft, m + (1 - e) * _Soft);+ #if defined(_SOFTPARTICLES)+ float2 suv = i.sp.xy / i.sp.w;+ a *= saturate((LinearEyeDepth(SampleSceneDepth(suv), _ZBufferParams) - i.sp.w) / max(_SoftFade, 1e-3));+ #endif+ half3 c = tex.rgb * i.col.rgb * _Tint.rgb;+ if (_DstBlend == 1) c *= a;+ return half4(c, a);+ }+ ENDHLSL+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/ParticleSoft.shader b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/ParticleSoft.shadernew file mode 100644index 0000000..e44c774--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/ParticleSoft.shader@@ -0,0 +1,75 @@+// Shared particle shader for splashes / mist / ripples (URP)+// vertex colour × texture × HDR colour; soft particles (fade where they intersect the scene); fade near the camera+Shader "VfxSkill/ParticleSoft"+{+ Properties+ {+ _MainTex ("Texture", 2D) = "white" {}+ [HDR]_Color ("Color", Color) = (1, 1, 1, 1)+ _SoftFade ("Soft Particle Distance", Float) = 0.3+ _CameraFade ("Camera Near Fade", Float) = 0.6+ _AlphaPow ("Alpha Power", Float) = 1+ [Toggle(_SOFTPARTICLES)] _SoftOn ("Soft particles (needs depth texture)", Float) = 1+ [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Src Blend", Float) = 5+ [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Dst Blend", Float) = 10+ }+ SubShader+ {+ Tags { "RenderType" = "Transparent" "Queue" = "Transparent" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" "PreviewType" = "Plane" }+ Pass+ {+ Name "ParticleForward"+ Tags { "LightMode" = "UniversalForward" }+ Blend [_SrcBlend] [_DstBlend]+ ZWrite Off+ Cull Off++ HLSLPROGRAM+ #pragma vertex vert+ #pragma fragment frag+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ #pragma shader_feature_local _SOFTPARTICLES+ #if defined(_SOFTPARTICLES)+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"+ #endif++ TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);+ CBUFFER_START(UnityPerMaterial)+ float4 _MainTex_ST;+ half4 _Color;+ float _SoftFade, _CameraFade, _AlphaPow, _SrcBlend, _DstBlend, _SoftOn;+ CBUFFER_END++ struct Attributes { float4 positionOS : POSITION; float2 uv : TEXCOORD0; half4 color : COLOR; };+ struct Varyings { float4 positionCS : SV_POSITION; float2 uv : TEXCOORD0; half4 color : COLOR; float4 screenPos : TEXCOORD1; };++ Varyings vert(Attributes v)+ {+ Varyings o;+ o.positionCS = TransformObjectToHClip(v.positionOS.xyz);+ o.uv = TRANSFORM_TEX(v.uv, _MainTex);+ o.color = v.color;+ o.screenPos = ComputeScreenPos(o.positionCS);+ return o;+ }++ half4 frag(Varyings i) : SV_Target+ {+ half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);+ half4 c = tex * i.color * _Color;+ c.a = pow(saturate(c.a), _AlphaPow);+ float z = i.screenPos.w;+ #if defined(_SOFTPARTICLES)+ float2 suv = i.screenPos.xy / i.screenPos.w;+ float sceneZ = LinearEyeDepth(SampleSceneDepth(suv), _ZBufferParams);+ c.a *= saturate((sceneZ - z) / max(_SoftFade, 1e-3));+ #endif+ c.a *= saturate((z - _ProjectionParams.y) / max(_CameraFade, 1e-3));+ // with additive blending, multiply alpha into the colour+ if (_DstBlend == 1) c.rgb *= c.a;+ return c;+ }+ ENDHLSL+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/StylizedShell.shader b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/StylizedShell.shadernew file mode 100644index 0000000..17dbf0f--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/Shaders/StylizedShell.shader@@ -0,0 +1,91 @@+// Cel-shaded mesh effects (water crown, wind bands, lightning): greyscale shape mask + hard threshold.+// Mask value = distance from the edge. Below the threshold is transparent; just above it is a dark band (ink rim), the middle is the saturated body, the thickest part is a white-hot core.+// Erosion (_Erosion + vertex alpha) raises the threshold: the thinnest parts vanish first and the edge stays hard (hand-drawn-animation style dissipation).+// Same rule as the value ramp of the flipbook grade (vfx video-grade), so meshes and flipbooks share one look.+Shader "VfxSkill/StylizedShell"+{+ Properties+ {+ _MainTex ("Shape Mask (A)", 2D) = "white" {}+ _NoiseTex ("Breakup Noise (R)", 2D) = "gray" {}+ [HDR]_Core ("Core", Color) = (1, 1, 1, 1)+ [HDR]_Body ("Body", Color) = (0.2, 0.55, 1, 1)+ _Rim ("Rim (ink)", Color) = (0.03, 0.12, 0.35, 1)+ _Cutoff ("Base cutoff", Range(0, 0.9)) = 0.12+ _RimWidth ("Rim width", Range(0, 0.4)) = 0.1+ _CoreLevel ("Core level", Range(0.3, 1.01)) = 0.82+ _Erosion ("Erosion", Range(0, 1)) = 0+ _ErodeDir ("Erode bottom-up (uv2.y)", Range(-1, 1)) = 0+ _NoiseAmt ("Noise breakup", Range(0, 1)) = 0.35+ _NoiseScale ("Noise scale (xy) scroll (zw)", Vector) = (3, 1.5, 0.2, -0.4)+ _Scroll ("Mask UV scroll (xy)", Vector) = (0, 0, 0, 0)+ _Opacity ("Opacity", Range(0, 1)) = 1+ _CamPush ("Push toward camera (m)", Float) = 0+ _SoftFade ("Soft particle distance", Float) = 0.15+ [Toggle(_SOFTPARTICLES)] _SoftOn ("Soft particles (needs depth texture)", Float) = 1+ [Enum(UnityEngine.Rendering.CullMode)] _Cull ("Cull", Float) = 0+ }+ SubShader+ {+ Tags { "RenderType" = "Transparent" "Queue" = "Transparent" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }+ Pass+ {+ Tags { "LightMode" = "UniversalForward" }+ Blend SrcAlpha OneMinusSrcAlpha+ ZWrite Off+ Cull [_Cull]+ HLSLPROGRAM+ #pragma vertex vert+ #pragma fragment frag+ #pragma shader_feature_local _SOFTPARTICLES+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"+ #if defined(_SOFTPARTICLES)+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"+ #endif+ TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);+ TEXTURE2D(_NoiseTex); SAMPLER(sampler_NoiseTex);+ CBUFFER_START(UnityPerMaterial)+ float4 _MainTex_ST, _NoiseTex_ST, _NoiseScale, _Scroll;+ half4 _Core, _Body, _Rim;+ float _Cutoff, _RimWidth, _CoreLevel, _Erosion, _ErodeDir, _NoiseAmt, _Opacity, _CamPush, _SoftFade, _SoftOn, _Cull;+ CBUFFER_END+ struct A { float4 pos : POSITION; float2 uv : TEXCOORD0; float2 uv2 : TEXCOORD1; half4 col : COLOR; };+ struct V { float4 pos : SV_POSITION; float4 uv : TEXCOORD0; half4 col : COLOR; float4 sp : TEXCOORD1; };+ V vert(A i)+ {+ V o;+ float3 w = TransformObjectToWorld(i.pos.xyz);+ float camDist = distance(_WorldSpaceCameraPos, w);+ w += (_WorldSpaceCameraPos - w) / max(camDist, 1e-4) * min(_CamPush, max(0, camDist - _ProjectionParams.y * 4)); // never push past the near plane // sorting / intersection: push slightly toward the camera instead of a fixed offset baked in at emit time+ o.pos = TransformWorldToHClip(w);+ o.uv = float4(TRANSFORM_TEX(i.uv, _MainTex), i.uv2);+ o.col = i.col; o.sp = ComputeScreenPos(o.pos);+ return o;+ }+ half4 frag(V i) : SV_Target+ {+ float t = _Time.y;+ float m = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv.xy + _Scroll.xy * t).a;+ float n = SAMPLE_TEXTURE2D(_NoiseTex, sampler_NoiseTex, i.uv.xy * _NoiseScale.xy + _NoiseScale.zw * t).r;+ float e = saturate(_Erosion + (1 - i.col.a));+ e = saturate(e + _ErodeDir * e * (0.5 - i.uv.w) * 1.6); // directional erosion: >0 dissolves from the bottom first+ float thr = _Cutoff + e * (1.02 - _Cutoff);+ float s = m - (n - 0.5) * _NoiseAmt * (0.35 + e);+ float aa = max(fwidth(s) * 1.2, 1e-3);+ half a = smoothstep(thr, thr + aa, s);+ float rimW = _RimWidth * (1 - 0.85 * e); // the rim thins as it erodes, so a dissolving shape never turns entirely dark+ half rim = 1 - smoothstep(thr + rimW, thr + rimW + aa, s);+ // the core appears only in the original core area and always inside the rim; it shrinks during erosion so what remains never turns entirely core-coloured+ half core = smoothstep(_CoreLevel + e * 0.3, _CoreLevel + e * 0.3 + aa, s) * smoothstep(thr + rimW + 0.04, thr + rimW + 0.04 + aa, s);+ half3 c = lerp(lerp(_Body.rgb, _Core.rgb, core), _Rim.rgb, rim);+ a *= _Opacity;+ #if defined(_SOFTPARTICLES)+ float2 suv = i.sp.xy / i.sp.w;+ a *= saturate((LinearEyeDepth(SampleSceneDepth(suv), _ZBufferParams) - i.sp.w) / max(_SoftFade, 1e-3));+ #endif+ return half4(c, a);+ }+ ENDHLSL+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillBase.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillBase.csnew file mode 100644index 0000000..ee7b1d8--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillBase.cs@@ -0,0 +1,74 @@+using System;+using System.Collections;+using System.Collections.Generic;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Base of a skill component. Put it on the caster (or a cast point); transform.forward is the cast direction.+ /// Play() casts once at `target` (or at `fallbackTarget` when there is none). Spawned objects are cleaned up when the+ /// skill finishes or the component is disabled.+ /// </summary>+ public abstract class SkillBase : MonoBehaviour+ {+ [Header("Target")]+ public Transform target;+ [Tooltip("Aim point relative to the target's pivot (the centre of its body)")]+ public Vector3 targetOffset = new Vector3(0, 1.0f, 0);+ [Tooltip("Aim point relative to the caster when there is no target")]+ public Vector3 fallbackTarget = new Vector3(0, 1.0f, 7f);+ [Tooltip("Casting hand relative to the caster (used when no CastDriver tracks a real hand bone)")]+ public Vector3 handOffset = new Vector3(0.0f, 1.25f, 0.55f);+ public bool playOnStart;++ public bool IsPlaying { get; protected set; }+ public event Action Finished;++ protected readonly List<UnityEngine.Object> spawned = new List<UnityEngine.Object>();++ protected Vector3 TargetPos => target ? target.position + targetOffset : transform.TransformPoint(fallbackTarget);+ protected Vector3 HandPos => transform.TransformPoint(handOffset);++ void Start() { if (playOnStart) Play(); }++ public void Play(Transform newTarget)+ {+ target = newTarget;+ Play();+ }++ public virtual void Play()+ {+ StopAllCoroutines();+ Cleanup();+ StartCoroutine(Runner());+ }++ IEnumerator Runner()+ {+ IsPlaying = true;+ yield return Run();+ Cleanup();+ IsPlaying = false;+ Finished?.Invoke();+ }++ protected abstract IEnumerator Run();++ protected void RaiseFinished() => Finished?.Invoke();++ protected virtual void Cleanup()+ {+ foreach (var o in spawned) if (o) Destroy(o);+ spawned.Clear();+ }++ protected virtual void OnDisable() { Cleanup(); IsPlaying = false; }++ public static float EaseOutBack(float x, float s = 1.70158f) { x -= 1; return x * x * ((s + 1) * x + s) + 1; }+ public static float EaseOutCubic(float x) { x = 1 - x; return 1 - x * x * x; }+ public static float EaseInCubic(float x) => x * x * x;+ public static float EaseInOut(float x) => x * x * (3 - 2 * x);+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillDemo.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillDemo.csnew file mode 100644index 0000000..c842ef9--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/SkillDemo.cs@@ -0,0 +1,63 @@+using System.Collections;+using System.Collections.Generic;+using UnityEngine;++namespace VfxSkill+{+ /// <summary>+ /// Demo driver for the scene built by "VFX Skill/3. Build demo scene": casts the listed skills in turn, or the one+ /// picked with the on-screen buttons / number keys. Not meant for games — call ElementSkill.Play() from your own code.+ /// </summary>+ public class SkillDemo : MonoBehaviour+ {+ public List<ElementSkill> skills = new List<ElementSkill>();+ [Tooltip("Cast every skill in turn, waiting this long after each one finishes (0 = only on button / key)"), Min(0f)]+ public float autoInterval = 0.8f;+ [Range(0.1f, 1f), Tooltip("Time scale while playing (slow motion to judge timing)")] public float timeScale = 1f;++ int next;+ ElementSkill current;++ IEnumerator Start()+ {+ if (autoInterval <= 0) yield break;+ while (true)+ {+ yield return new WaitForSeconds(autoInterval);+ if (autoInterval <= 0) yield break; // a button was pressed: manual from now on+ if (skills.Count == 0) continue;+ Cast(next);+ next = (next + 1) % skills.Count;+ while (current && current.IsPlaying) yield return null;+ }+ }++ void Update()+ {+ GameTime.BaseScale = timeScale;+#if ENABLE_LEGACY_INPUT_MANAGER+ for (int i = 0; i < Mathf.Min(skills.Count, 9); i++)+ if (Input.GetKeyDown(KeyCode.Alpha1 + i)) { autoInterval = 0; Cast(i); }+#endif+ }++ public void Cast(int i)+ {+ if (i < 0 || i >= skills.Count || !skills[i] || !skills[i].profile) return;+ current = skills[i];+ current.Play();+ }++ void OnGUI()+ {+ GUILayout.BeginArea(new Rect(12, 12, 220, 40 + 30 * skills.Count));+ for (int i = 0; i < skills.Count; i++)+ {+ var s = skills[i];+ if (!s || !s.profile) continue;+ if (GUILayout.Button($"{i + 1}. {s.profile.displayName} ({s.profile.delivery})")) { autoInterval = 0; Cast(i); }+ }+ GUILayout.EndArea();+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/VfxSkill.Runtime.asmdef b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/VfxSkill.Runtime.asmdefnew file mode 100644index 0000000..36b90b2--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Runtime/VfxSkill.Runtime.asmdef@@ -0,0 +1,6 @@+{+ "name": "VfxSkill.Runtime",+ "rootNamespace": "VfxSkill",+ "references": [],+ "autoReferenced": true+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ElementProfileTests.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ElementProfileTests.csnew file mode 100644index 0000000..b411e49--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ElementProfileTests.cs@@ -0,0 +1,31 @@+using NUnit.Framework;+using UnityEngine;++namespace VfxSkill.Tests+{+ /// <summary>When a designer enters 0 / negative values in the Inspector, Validate must report them (runtime also clamps separately, so nothing loops forever).</summary>+ public class ElementProfileTests+ {+ [Test]+ public void ZeroSpeedAndSpacing_AreReported()+ {+ var p = ScriptableObject.CreateInstance<ElementProfile>();+ p.speed = 0; p.trailSpacing = 0;+ string e = p.Validate();+ StringAssert.Contains("speed", e);+ StringAssert.Contains("trailSpacing", e);+ Object.DestroyImmediate(p);+ }++ [Test]+ public void SafeValues_ReportOnlyMissingMaterials()+ {+ var p = ScriptableObject.CreateInstance<ElementProfile>();+ p.speed = 10; p.trailSpacing = 0.05f;+ string e = p.Validate();+ StringAssert.DoesNotContain("speed <", e);+ StringAssert.DoesNotContain("trailSpacing <", e);+ Object.DestroyImmediate(p);+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/EruptionTests.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/EruptionTests.csnew file mode 100644index 0000000..48a18a2--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/EruptionTests.cs@@ -0,0 +1,46 @@+using NUnit.Framework;+using UnityEngine;++namespace VfxSkill.Tests+{+ /// <summary>Eruption (water column) config checks, frame curve and atlas layout: these must not silently break when the atlas or parameters change.</summary>+ public class EruptionTests+ {+ [Test]+ public void BadEruptionValues_AreReported()+ {+ var p = ScriptableObject.CreateInstance<ElementProfile>();+ p.delivery = DeliveryType.Eruption;+ p.columnHeight = 0; p.columnLife = 0; p.warnTime = -1; p.columnLift = -1; p.knockback = -1;+ p.columnFrames = new AnimationCurve();+ string e = p.Validate();+ foreach (var what in new[] { "columnHeight", "columnLife", "warnTime", "columnLift", "knockback", "columnFrames", "impact (column)" })+ StringAssert.Contains(what, e);+ StringAssert.DoesNotContain("columnFront", e); // the front layer is optional+ Object.DestroyImmediate(p);+ }++ [Test]+ public void DefaultColumnCurve_StartsAt0_EndsAt1_AndNeverGoesBack()+ {+ var p = ScriptableObject.CreateInstance<ElementProfile>();+ var c = p.columnFrames;+ Assert.AreEqual(0f, c.Evaluate(0f), 1e-4f);+ Assert.AreEqual(1f, c.Evaluate(1f), 1e-4f);+ float prev = -1;+ for (int i = 0; i <= 100; i++) { float v = c.Evaluate(i / 100f); Assert.GreaterOrEqual(v, prev - 1e-3f, $"frame curve goes backwards at {i}%"); prev = v; }+ Assert.That(p.columnHoldEnd, Is.InRange(0.05f, 0.95f));+ Object.DestroyImmediate(p);+ }++ [Test]+ public void LinearCurve_HasSegmentSlopes()+ {+ var c = ElementProfile.LinearCurve(0, 0, 0.5f, 0.25f, 1, 1);+ Assert.AreEqual(0.125f, c.Evaluate(0.25f), 1e-3f); // first segment slope is 0.5: the midpoint lies exactly on the line (flat tangents would sag below it)+ Assert.AreEqual(0.625f, c.Evaluate(0.75f), 1e-3f);+ Assert.AreEqual(0.5f, c.keys[1].inTangent, 1e-4f); Assert.AreEqual(1.5f, c.keys[1].outTangent, 1e-4f);+ }++ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/GameTimeTests.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/GameTimeTests.csnew file mode 100644index 0000000..707b1c5--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/GameTimeTests.cs@@ -0,0 +1,73 @@+using NUnit.Framework;+using UnityEngine;++namespace VfxSkill.Tests+{+ /// <summary>Layered time scale: hit stop and pause / slow motion never overwrite each other (regression test for a blocking issue found in technical review).</summary>+ public class GameTimeTests+ {+ [SetUp] public void Reset() => GameTime.ResetAll();+ [TearDown] public void Restore() => GameTime.ResetAll();++ [Test]+ public void FreezeThenRelease_RestoresBaseScale()+ {+ GameTime.BaseScale = 0.5f;+ GameTime.Freezing = true;+ Assert.AreEqual(0.5f * GameTime.FrozenScale, Time.timeScale, 1e-5f);+ GameTime.Freezing = false;+ Assert.AreEqual(0.5f, Time.timeScale, 1e-5f);+ }++ [Test]+ public void PauseViaApi_DuringFreeze_ResumesToBaseNotFrozen()+ {+ GameTime.Freezing = true;+ GameTime.Paused = true;+ GameTime.Freezing = false; // hit stop ends while paused+ Assert.AreEqual(0f, Time.timeScale);+ GameTime.Paused = false;+ Assert.AreEqual(1f, Time.timeScale, 1e-5f);+ }++ [Test]+ public void LegacyPauseCode_SavesFrozenValue_DoesNotGetStuck()+ {+ GameTime.Freezing = true;+ float saved = Time.timeScale; // old pause code: save the current value (= 0.03)+ Time.timeScale = 0f; // then write 0+ GameTime.Freezing = false; // the hit stop service ends the freeze while paused+ Assert.AreEqual(0f, Time.timeScale, "must stay 0 while paused");+ Time.timeScale = saved; // old code restores the saved 0.03+ GameTime.Sync();+ Assert.IsFalse(GameTime.Paused);+ Assert.AreEqual(1f, GameTime.BaseScale, 1e-5f, "the frozen value must not be taken as the new base scale");+ GameTime.Freezing = false; // back to normal speed on the next write+ Assert.AreEqual(1f, Time.timeScale, 1e-5f);+ }++ [Test]+ public void ProjectSlowMotionAtThreePercent_NotMistakenForResume_WhenLegacyRuleOff()+ {+ GameTime.AbsorbLegacyWrites = false;+ try+ {+ GameTime.Freezing = true; GameTime.Freezing = false;+ Time.timeScale = GameTime.FrozenScale; // the project's own 3% slow motion+ GameTime.Sync();+ Assert.AreEqual(GameTime.FrozenScale, GameTime.BaseScale, 1e-5f);+ }+ finally { GameTime.AbsorbLegacyWrites = true; }+ }++ [Test]+ public void ExternalSlowMotion_IsAdoptedAsBase()+ {+ Time.timeScale = 0.25f; // slow motion written directly from elsewhere+ GameTime.Freezing = true;+ Assert.AreEqual(0.25f * GameTime.FrozenScale, Time.timeScale, 1e-5f);+ GameTime.Freezing = false;+ Assert.AreEqual(0.25f, Time.timeScale, 1e-5f);+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ShellPoolTests.cs b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ShellPoolTests.csnew file mode 100644index 0000000..2436e36--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/ShellPoolTests.cs@@ -0,0 +1,26 @@+using NUnit.Framework;+using UnityEngine;++namespace VfxSkill.Tests+{+ /// <summary>Shell pool: a shell that is borrowed but temporarily hidden (flickering) must not be lent to anyone else (regression test for a blocking issue found in technical review).</summary>+ public class ShellPoolTests+ {+ [Test]+ public void HiddenShell_IsNotHandedOutAgain()+ {+ var hub = new GameObject("ElementFX_Test").AddComponent<ElementFX>();+ try+ {+ var a = ElementFX.Shell(null);+ a.Visible = false; // flickering: hidden but still in use+ var b = ElementFX.Shell(null);+ Assert.AreNotSame(a, b);+ a.Release();+ var c = ElementFX.Shell(null);+ Assert.AreSame(a, c, "should be reused after release");+ }+ finally { Object.DestroyImmediate(hub.gameObject); }+ }+ }+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/VfxSkill.Tests.asmdef b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/VfxSkill.Tests.asmdefnew file mode 100644index 0000000..a3d77d4--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/Tests/Editor/VfxSkill.Tests.asmdef@@ -0,0 +1,9 @@+{+ "name": "VfxSkill.Tests",+ "references": ["VfxSkill.Runtime", "UnityEngine.TestRunner", "UnityEditor.TestRunner"],+ "includePlatforms": ["Editor"],+ "overrideReferences": true,+ "precompiledReferences": ["nunit.framework.dll"],+ "defineConstraints": ["UNITY_INCLUDE_TESTS"],+ "autoReferenced": false+}diff --git a/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/package.json b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/package.jsonnew file mode 100644index 0000000..9ef2b9d--- /dev/null+++ b/skills/effekseer-vfx/assets/unity/com.vfx-skill.flipbook/package.json@@ -0,0 +1,10 @@+{+ "name": "com.vfx-skill.flipbook",+ "displayName": "VFX Skill — Video Flipbook Skills (URP)",+ "version": "0.3.0",+ "unity": "6000.0",+ "description": "Real-time element skills built from video-model flipbooks: a data-driven ElementProfile per element, projectile / instant bolt / ground-eruption delivery, layered core-body-matter-ground particles, hit feel (hit-stop, shake, lift) and an editor wizard that turns a processed sheet into a playable skill. Installed by the effekseer-vfx skill (`vfx unity-install`).",+ "dependencies": { "com.unity.render-pipelines.universal": "17.0.0" },+ "keywords": ["vfx", "flipbook", "skill", "urp"],+ "license": "MIT"+}diff --git a/skills/effekseer-vfx/references/cli.md b/skills/effekseer-vfx/references/cli.mdindex 429dcbf..7947b04 100644--- a/skills/effekseer-vfx/references/cli.md+++ b/skills/effekseer-vfx/references/cli.md@@ -6,7 +6,7 @@ warnings during a build go to stderr. Exit codes: 0 ok, 1 failed check or error2 setup required: the toolchain is missing (`SetupRequired`) or there is no workspace here (`WorkspaceMissing`).Image results are file paths — open them.-Every command except `doctor`, `init`, `examples`, `rubric`, `layer-schema` and `process-texture` needs a workspace+Every command except `doctor`, `init`, `examples`, `rubric`, `layer-schema`, `process-texture`, `unity-install` and `unity-export` needs a workspacemade by `vfx init` (`vfx/src/` and `vfx/vfx_manifest.json`). Run from the game project or pass `--project`; a commandrun in the wrong folder fails with `WorkspaceMissing` instead of creating a stray `vfx/`. The current directory iskept off Python's import path, and `vfx/src` helpers resolve only as `_name` files, so project files never shadow@@ -38,6 +38,12 @@ outside `EFFEKSEER_VFX_HOME`.| `texture-info [names...]` | Python | coverage, bbox, border contact, orientation, bulge, seam ratio || `texture-audit <name> [--role R] [--grid C R] [--loop] [--allow-empty i...]` | Python | role checks + preview image || `process-texture <src> <dst> [--size N] [--color] [--grid C R]` | Python | crop, alpha, padding, power-of-two resize |+| `video-first-frame <src> <dst> [--width] [--height] [--fill .35] [--anchor center\|bottom]` | Python | the element image on pure black at the clip's starting size, plus a pure black last frame (`black_<W>x<H>.png` beside it) |+| `video-timeline <clip> [--step 2]` | Python, ffmpeg | labelled contact sheet (24 fps numbering) to pick the span for a flipbook |+| `video-flipbook <clip> <dst> [--grid C R] [--cell] [--cell-h] [--start --end \| --frames a:b:s] [--crop auto\|full] [--box cx,cy,half] [--pad] [--radius] [--feather] [--mask-power] [--floor] [--gain] [--gutter 6] [--prompt \| --prompt-file]` | Python, ffmpeg | luminance key on black, one shared crop, noisy round / rounded-box mask per cell, transparent gutters; fails if a cell border keeps alpha; records the clip and prompt in `vfx/video_prompts.json` |+| `video-grade <src> <dst> [--grid C R] [--ramp 'p:r,g,b;...'] [--erode] [--erode-pow] [--tail-fade] [--highlight] [--smoke r,g,b] [--smoke-start] [--keep-embers] [--ramp-fade t0,t1] [--late-gamma] [--late-alpha] [--alpha-gamma] [--late-blur] [--body-mask] [--open N --open-until t] [--cut-below y --cut-from t]` | Python | one value ramp per element over a keyed sheet (without `--ramp` the clip keeps its own colours); erodes keying haze, fades the tail, cools fire to smoke, keeps cell borders transparent; `<src>` may be a bare processed-sheet name; see [video-flipbook](video-flipbook.md) |+| `unity-install <UnityProject> [--force]` | Python | copy the URP flipbook-skill package into `Packages/` (an existing copy only with `--force`, which keeps Unity's `.meta` GUIDs) and (re)write its procedural textures into `Assets/VfxSkill/Generated/Textures` |+| `unity-export <sheet> <UnityProject> [--grid C R] [--name N]` | Python | copy a sheet into `Assets/VfxSkill/Flipbooks/` with a `.flipbook.json` sidecar (grid, cell, measured bottom inset; the grid defaults to the one recorded by `video-flipbook` / `video-grade` in the vfx workspace, so run it from there or pass `--project` / `--grid`) || `build [--ids ...]` | Core | lint, compile, save/open read-back, manifest, build receipt; without `--ids` also prunes effects this skill built whose source left `vfx/src` (see below) || `compile <recipe.json> [--source] [--runtime]` | Core | compile one recipe JSON || `export [--output DIR]` | Core | re-export all built effects to `.efk` with `resources/` |@@ -119,7 +125,9 @@ Warnings (craft hints; the strip decides):<project>/vfx/src/VFX_*.py recipe sources (yours) ┐briefs/VFX_*.json design briefs │- texture_prompts.json prompts of painted textures │ the effect library:+ texture_prompts.json prompts of painted textures │+ video_prompts.json clips, prompts and sheet parameters │+ videos/ image-to-video originals │ the effect library:textures/generated/ image-model originals (never edited)│ keep under version controltextures/processed/ game textures (incl. procedural) │recipes/*.json compiled recipe snapshots │diff --git a/skills/effekseer-vfx/references/primitives.md b/skills/effekseer-vfx/references/primitives.mdindex 6f3e8ed..35c756f 100644--- a/skills/effekseer-vfx/references/primitives.md+++ b/skills/effekseer-vfx/references/primitives.md@@ -52,6 +52,7 @@ nature: contact stars, glows, sparks and smoke puffs (stacked into volume).| `orbit_band` | accretion disk, orbiting rune ring | Ring in a tilted plane, noise flowing round it; `arc=(-90,90)` far half, `(90,270)` near half || `smoke` | smoke, fog, dust, dark residue | painted smoke flipbook `T_SmokeSheet01` + light erosion; `texture='T_Smoke02'` for a single still puff — ice mist keeps the still puff so it differs from fire's rolling smoke || `billow` | fireball, the same billow as smoke | painted 4×4 flipbook `T_ExplosionSheet01` played once + `ramp` colour stops |+| `video_body(name, texture, grid, size, frame_length=2, column=None, loop=False, root_inset=0)` | a body whose shape keeps changing: geyser that rises and collapses, burst that boils into smoke, looping orb | a sheet from `vfx video-flipbook` + `video-grade` played once (or looped) by one Blend particle, left white; `column=<cell w/h>` stands it up from its base; see [video-flipbook](video-flipbook.md) || `flame` | flame tongues, fire walls, ground fire | the explosion flipbook growing from its base, cooling white → colour → dark, eaten by noise with a hot rim (no clip-art flame silhouette) || `decal` | seals, cracks, scorch marks | ground-plane sprite, depth tested || `standing` | spikes, bolts, beams | YAxisFixed sprite pivoting at its base |diff --git a/skills/effekseer-vfx/references/video-flipbook.md b/skills/effekseer-vfx/references/video-flipbook.mdnew file mode 100644index 0000000..2243fe0--- /dev/null+++ b/skills/effekseer-vfx/references/video-flipbook.md@@ -0,0 +1,161 @@+# Video flipbooks++An image model paints one frame. An image-to-video model also paints the **motion**: a water column that shoots up,+holds the target in the air and collapses as rain; a fireball that bursts and boils into grey smoke. Those are+continuous changes of shape and material that layered primitives cannot draw: a primitive can scale, fade, scroll and+erode a picture, but it cannot turn fire into smoke inside the same silhouette. A video flipbook can, because the model+drew every in-between.++The skill turns such a clip into a straight-alpha sheet, gives every sheet the same graded look, and plays it in either+engine. Nothing here depends on one video service: any image-to-video model that accepts a first and a last frame+works. The prompts and numbers below were verified with Seedance 2.5.++## Three ways to work — pick per effect, mix freely++| Mode | What makes the effect | Engine | Best for |+|---|---|---|---|+| **Procedural** (the original skill) | layered primitives in a Python recipe, painted textures | Effekseer → Godot | hits, slashes, auras, beams, shields; anything that must stay crisp, tiny or runtime-driven |+| **Video flipbook** | one generated clip as the body; the Unity runtime adds core, matter and ground | Unity (URP) | a single strong shape change: geysers, fire-to-smoke bursts, looping orbs, transformations |+| **Combined** | the clip is the body layer (`video_body`), primitives add contact flash, sparks, rings, cracks, decals, heat haze | Effekseer → Godot (or Unity with its own layers) | hero impacts: the clip gives the motion, primitives give the timing, the white-hot core and secondary motion |++Rules that stay true in every mode: time structure (anticipation → contact → body → secondary → dissipation), value+layering (hot core, saturated body, dark rim), and an independent review before calling an effect done. A clip is a+body, not a finished effect: it has no contact frame, no sparks that react to the target and no ground contact until+the engine adds them.++## Pipeline++```sh+vfx video-first-frame <element.png> vfx/textures/generated/<id>_first.png --fill .35 [--anchor bottom]+# generate the clip (image-to-video, first + last frame) → save it as vfx/videos/<id>.mp4+vfx video-timeline vfx/videos/<id>.mp4 # labelled frames: pick the span+vfx video-flipbook vfx/videos/<id>.mp4 <ID> --grid 8 8 --cell 256 --start 24 --end 100 \+ --prompt-file <prompt.txt> # key, crop, mask, gutter, record+vfx video-grade <ID> <ID>_graded --ramp "..." # one look per element+vfx texture-audit <ID>_graded --role flipbook --grid 8 8 # border alpha, coverage, empty cells+```++`video-first-frame` puts the element image on pure black at the size and place the clip should start from and also+writes a pure black last frame. Bare sheet names live in `vfx/textures/processed/` (a path starting with `vfx/` is+project-relative). Every run records the clip, the prompt and the exact parameters in+`vfx/video_prompts.json` (lint accepts textures recorded there or in `texture_prompts.json`); contact sheets go to+`vfx/work/video/`. Originals stay in `vfx/videos/` and `vfx/textures/generated/`.++## Generating the clip++- **Image-to-video with first and last frame.** First frame = the element on black (`video-first-frame`). Last frame:+ pure black for a burst or a column (the effect must fully dissipate), the **same image as the first frame** for a+ loop (an orb that burns in place: the clip comes back to its start, so one period loops seamlessly).+- **Fixed camera, pure black background, nothing but the effect**: no character, ground, reflection, fog, text, music.+- **Keep it inside the frame**: say where the effect stays ("centred, the top never leaves the frame") — a clipped edge+ becomes a hard line in the sheet.+- **Say what it is NOT.** Models drift to clichés: an explosion becomes a mushroom cloud with a smoke column, a water+ burst becomes a white foam cloud. Name them: "not a mushroom cloud, no smoke column", "the water stays clear blue,+ never white foam".+- **Beats with whole-second timestamps**, one change per beat, and the end state of each beat.+- **Style from the first frame**: "keep the first frame's hand-painted cel style and palette: <core>, <inner>, <body>,+ <dark rim>, hard value steps, clean, not realistic".+- 4–5 s at 720p or 1080p is enough; 24 fps is the decode rate.++Template (write it in the language your model reads best):++```text+A stylized anime game skill effect: <what it is>. Pure black background, the camera is completely fixed, only the+effect is in frame — no character, ground or scenery. <Where it stays: centred, never crosses the frame edges>.+<Not: the cliché to avoid>.+0-1 s: <the first frame's element> <anticipation>, then <the burst / rise>.+1-2 s: <the body: how the shape changes, where secondary pieces go>.+2-4 s: <dissipation: how it breaks up / cools / falls>, until the frame is pure black again, matching the last frame.+Keep the first frame's hand-painted cel style and palette: <core>, <inner>, <body>, <dark rim>; hard value steps,+clean, not realistic. The background stays pure black; no ground, reflection or text. No music, no sound.+```++## Making the sheet++- **Pick the span** on the timeline. Skip an opening white flash or any frame that fills the screen (the body is small+ first; the engine grows it with `size_curve` / `_Grow`). Stop when the effect is gone.+- **Grid**: 8×8 for bursts; tall subjects use tall cells (`--grid 8 7 --cell 224 --cell-h 400` for a column).+ Loops: exactly one period (`--frames 40:79:1` for a 40-frame cycle).+- **Crop**: `auto` takes one shared box over every frame (no jitter). Stray sparks inflate it; then give `--box cx,cy,half`.+- **Mask**: round (`--mask-power 2`) for bursts and orbs, rounded box (`3`–`5`) for columns and wide splashes so the+ top and base are not shaved. Every cell gets a transparent gutter (`--gutter 6`); the command fails if any cell+ border still has alpha.+- **Grade**: `--ramp` maps density to 3–4 flat steps, dark rim → body → light → hot core. `--erode` removes the haze+ keying leaves; `--tail-fade` fades the last cells to zero; `--smoke r,g,b --smoke-start .3 --keep-embers` cools a fire+ tail to grey smoke and keeps its embers; `--ramp-fade t0,t1` blends back to the clip's own colours late in life.++Verified starting points:++| Effect | flipbook | grade |+|---|---|---|+| water column (rise, hold, collapse) | `--grid 8 7 --cell 224 --cell-h 400 --frames 0:110:2 --pad 1.03 --mask-power 3 --radius .47 --floor .1 --gain 1.25` | `--erode .18 --erode-pow 2 --tail-fade 8 --highlight 4` + a 4-step blue ramp |+| fireball loop | `--grid 8 5 --cell 256 --frames 40:79:1 --box ... --radius .46 --floor .05 --gain 1.15` | `--erode 0 --tail-fade 0 --highlight 1.5` + a 4-step fire ramp |+| fire burst → smoke | `--grid 8 8 --cell 256 --start 24 --end 100 --box ... --radius .47 --feather .1 --floor .1 --gain 1.15` | `--erode .2 --erode-pow 2 --late-gamma .5 --late-alpha 1.4 --smoke .42,.39,.38 --smoke-start .3 --keep-embers --tail-fade 10 --late-blur 1.5 --ramp-fade .35,.6` |++## Effekseer / Godot: `video_body`++```python+video_body('Fire body (video)', 'T_Burst_8x8_graded', grid=(8, 8), size=3.4, frame_length=2, delay=7)+video_body('Geyser', 'T_Geyser_8x7_graded', grid=(8, 7), size=4.0, column=224/400, root_inset=.09) # Y-axis billboard from its base+```++One particle plays every cell once (`loop=True` for orbs). The sheet is alpha-blended and left white: a colour on it+would tint the clip's own values. `frame_length=2` plays a 24 fps clip about 1.25× faster than generated, which+tightens the model's timing. Combined mode: keep the recipe's flash, glow, sparks, rings, cracks and haze and replace+only the painted billows with `video_body`; the shipped fire explosion becomes a combined effect by swapping its three+billow layers for one `video_body` at `delay=7`.++## Unity (URP)++```sh+vfx unity-install <UnityProject> # package into Packages/, procedural textures into Assets/VfxSkill+vfx unity-export <sheet.png> <UnityProject> # sheet + .flipbook.json (grid, cell, measured bottom inset)+```++In Unity 6 (URP): **VFX Skill → 1. Setup shared materials → 2. Create element skill from flipbooks → 3. Build demo+scene**, then Play (on-screen buttons cast each skill; keys 1–9 too when the legacy Input Manager is enabled). Agents can skip the window: write a spec and run Unity in+batch mode —++```json+{"name": "Water Column", "delivery": "Eruption",+ "theme": {"r": 0.25, "g": 0.6, "b": 1, "a": 1}, "dark": {"r": 0.03, "g": 0.14, "b": 0.4, "a": 1},+ "orb": "Assets/VfxSkill/Flipbooks/Water_Orb.png", "body": "Assets/VfxSkill/Flipbooks/Water_Column.png",+ "extra": "CrownSplash", "contact": "FoamRing", "trail": "Droplets", "linger": "Drip"}+```++```sh+Unity -batchmode -projectPath <UnityProject> -executeMethod VfxSkill.EditorTools.CreateElementSkill.FromCommandLine -vfxSpec /abs/path/spec.json -quit+```++Pass the spec as an absolute path (Unity resolves relative paths against the project). The command creates the+materials and profile, validates it (a missing material fails the run) and rebuilds the demo scene.++Each skill is one `ElementProfile` asset (Create → VfxSkill → Element Profile): materials, delivery+(`Projectile` flies, `Instant` connects like lightning, `Eruption` bursts from the ground under the target and lifts+it), trail, impact extra, contact accent, linger and hit feel. A new element is a new asset, not new code; only a new+kind of motion needs a new enum value and its case in `ElementSkill`. Call `ElementSkill.Play(target)` from the game;+targets implement `IElementHitReceiver` (`DemoTarget` is a reference reaction with knockback, squash, lift and flash).++Import rules (applied automatically to `Assets/VfxSkill/Flipbooks/` and any texture with a `.flipbook.json`): no+mipmaps (the gutter does not survive low mips), never rescaled to a power of two (8×7 sheets would shift every cell),+4096 on desktop, 2048 ASTC on mobile. The body material's `_Tiles` holds the grid; a looping orb uses `_Flip`+(cols, rows, fps). Hit-stop freezes particles: no hit-stop while a video body is on screen — a projectile burst uses+`hitStop = 0` and sells the hit with growth and shake; an eruption may stop briefly on the dive, before its column starts.+`vfx unity-install --force` replaces the package but keeps Unity's `.meta` files, so scenes and materials keep their+scripts and shaders.++## Pitfalls++| Symptom | Cause | Fix |+|---|---|---|+| a hard line or square edge in a cell | the clip crossed the frame, or the crop is too tight | say "never leaves the frame" in the prompt; larger `--pad`; rounded-box mask |+| the sheet flickers or jitters | per-frame crop | the shared `auto` crop, or `--box` |+| the burst pops on at full size | the clip starts open | skip the opening frames; grow it in the engine (`size_curve`, `_Grow`) |+| a white blob for the first frames | an opening flash in the clip | start after it; the engine's flash layer gives the contact |+| a column floats above the ground | the sheet has empty rows under the root | the sidecar's `bottom_inset`: Unity sets `columnRootInset` from it; Effekseer: `video_body(..., root_inset=...)` |+| everything looks like the video, not like the game | no grade | one ramp per element, the same steps for every sheet of that element |+| "atomic bomb" explosions | the model's default | name it in the prompt: not a mushroom cloud, no smoke column |+| cells smear at a distance | mipmaps on a gutter sheet | the import rules turn them off; Effekseer: keep the sheet's own size |++Check the video model's terms for commercial use before shipping its output; clips and sheets you generate belong in+your project, not in this skill.diff --git a/skills/effekseer-vfx/scripts/vfxkit/cli.py b/skills/effekseer-vfx/scripts/vfxkit/cli.pyindex 29e0a90..25093f4 100644--- a/skills/effekseer-vfx/scripts/vfxkit/cli.py+++ b/skills/effekseer-vfx/scripts/vfxkit/cli.py@@ -46,6 +46,37 @@ def parser():a.add_argument('source'); a.add_argument('output'); a.add_argument('--size', type=int, default=256)a.add_argument('--color', action='store_true', help='keep colour (straight RGBA) instead of a white mask')a.add_argument('--grid', type=int, nargs=2, metavar=('COLS', 'ROWS'), help='flipbook sheet: keep the cell layout instead of cropping')+ a = sub.add_parser('video-first-frame', help='place a generated element image on pure black at the size the video should start from (+ a black last frame)')+ a.add_argument('source'); a.add_argument('output'); a.add_argument('--width', type=int, default=1024); a.add_argument('--height', type=int, default=1024)+ a.add_argument('--fill', type=float, default=.35, help='longest side of the element / shorter side of the canvas')+ a.add_argument('--anchor', choices=['center', 'bottom'], default='center')+ a = sub.add_parser('video-timeline', help='labelled frames (24 fps numbering) of a generated clip, to pick the span for a flipbook')+ a.add_argument('video'); a.add_argument('--step', type=int, default=2)+ a = sub.add_parser('video-flipbook', help='generated clip on black → straight-alpha flipbook sheet with masked cells and transparent gutters')+ a.add_argument('video'); a.add_argument('output'); a.add_argument('--grid', type=int, nargs=2, metavar=('COLS', 'ROWS'), default=(8, 8))+ a.add_argument('--cell', type=int, default=256); a.add_argument('--cell-h', type=int, default=0, help='cell height (tall columns); default = --cell')+ a.add_argument('--start', type=int, default=-1); a.add_argument('--end', type=int, default=-1)+ a.add_argument('--frames', help="exact frames 'start:end:step' (count must equal COLS*ROWS)")+ a.add_argument('--crop', choices=['auto', 'full'], default='auto'); a.add_argument('--box', help="manual crop 'cx,cy,half_width' in pixels")+ a.add_argument('--pad', type=float, default=1.04); a.add_argument('--radius', type=float, default=.38); a.add_argument('--feather', type=float, default=.12)+ a.add_argument('--mask-power', type=float, default=2.0, help='2 round mask, 3-5 rounded box (tall columns, wide splashes)')+ a.add_argument('--floor', type=float, default=.06); a.add_argument('--gain', type=float, default=1.3); a.add_argument('--gutter', type=int, default=6)+ a.add_argument('--prompt', help='the video prompt that made the clip (recorded in vfx/video_prompts.json)'); a.add_argument('--prompt-file')+ a = sub.add_parser('unity-install', help='copy the Unity URP flipbook runtime into <UnityProject>/Packages and write its procedural textures')+ a.add_argument('unity_project'); a.add_argument('--force', action='store_true', help='replace an existing copy of the package')+ a = sub.add_parser('unity-export', help='copy a processed flipbook sheet into a Unity project with its grid sidecar')+ a.add_argument('sheet'); a.add_argument('unity_project'); a.add_argument('--grid', nargs=2, type=int, metavar=('COLS', 'ROWS'))+ a.add_argument('--name', help='file name in Assets/VfxSkill/Flipbooks (default: the sheet\'s)')+ a = sub.add_parser('video-grade', help='one value ramp per element over a keyed flipbook: erode haze, cel-step colour, fade the tail, cool to smoke')+ a.add_argument('source'); a.add_argument('output'); a.add_argument('--grid', type=int, nargs=2, metavar=('COLS', 'ROWS'), default=(8, 8))+ a.add_argument('--ramp', help="'pos:r,g,b;...' (0..1 colours) from dark rim to hot core"); a.add_argument('--erode', type=float, default=.22)+ a.add_argument('--erode-pow', type=float, default=1.5); a.add_argument('--tail-fade', type=int, default=6); a.add_argument('--highlight', type=float, default=0)+ a.add_argument('--ramp-fade', help="'t0,t1': blend back to the clip's own colours"); a.add_argument('--smoke', help="'r,g,b' tail smoke colour")+ a.add_argument('--smoke-start', type=float, default=.4); a.add_argument('--keep-embers', action='store_true')+ a.add_argument('--late-gamma', type=float, default=1.0); a.add_argument('--late-alpha', type=float, default=1.0); a.add_argument('--alpha-gamma', type=float, default=1.0)+ a.add_argument('--late-blur', type=float, default=0); a.add_argument('--body-mask', type=float, default=0)+ a.add_argument('--open', type=int, default=0, dest='open_px'); a.add_argument('--open-until', type=float, default=1.0)+ a.add_argument('--cut-below', type=float); a.add_argument('--cut-from', type=float, default=0)for name, text in [('brief-validate', 'check vfx/briefs/<ID>.json against the recipe'), ('effect-context', 'brief, build state, latest evidence and recent rounds of one effect')]:a = sub.add_parser(name, help=text); a.add_argument('id')a = sub.add_parser('build', help='compile effects through EffekseerCore (runs lint first)')@@ -174,6 +205,24 @@ def run(args):if c == 'process-texture':from effekseer_ai.resources import process_texturereturn process_texture(args.source, args.output, args.size, mask=not args.color, grid=tuple(args.grid) if args.grid else None)+ if c.startswith('video-'):+ from . import video+ if c == 'video-first-frame':+ return video.first_frame(args.source, args.output, args.width, args.height, args.fill, args.anchor)+ if c == 'video-timeline':+ return video.timeline(args.video, args.step)+ if c == 'video-flipbook':+ return video.flipbook(args.video, args.output, args.grid[0], args.grid[1], args.cell, args.cell_h, args.start, args.end, args.frames,+ args.crop, args.box, args.pad, args.radius, args.feather, args.mask_power, args.floor, args.gain, args.gutter,+ prompt=args.prompt, prompt_file=args.prompt_file)+ return video.grade(args.source, args.output, args.grid[0], args.grid[1], args.ramp, args.erode, args.erode_pow, args.tail_fade, args.highlight,+ args.ramp_fade, args.smoke, args.smoke_start, args.keep_embers, args.late_gamma, args.late_alpha, args.alpha_gamma,+ args.late_blur, args.body_mask, args.open_px, args.open_until, args.cut_below, args.cut_from)+ if c.startswith('unity-'):+ from . import unity+ if c == 'unity-install':+ return unity.install(args.unity_project, args.force)+ return unity.export(args.sheet, args.unity_project, args.grid, args.name)if c in ('brief-validate', 'effect-context', 'effect-verify', 'review-submit'):from . import evidence, briefsif c == 'brief-validate':@@ -314,7 +363,7 @@ def run(args):# Commands that work before `vfx init`: they create the workspace, read only the skill, or take explicit file paths.-WITHOUT_WORKSPACE = {'doctor', 'init', 'examples', 'rubric', 'layer-schema', 'process-texture', 'core'}+WITHOUT_WORKSPACE = {'doctor', 'init', 'examples', 'rubric', 'layer-schema', 'process-texture', 'core', 'unity-install', 'unity-export'}def main(argv=None):@@ -344,7 +393,7 @@ def main(argv=None):'Run the command from the game project, pass --project <game project>, or run vfx init there first.'}}, ensure_ascii=False))return 2try:- if args.command not in ('doctor', 'examples', 'rubric', 'layer-schema', 'process-texture'):+ if args.command not in ('doctor', 'examples', 'rubric', 'layer-schema', 'process-texture', 'unity-install', 'unity-export'):from .workflow import project_lockwith project_lock():result = run(args)diff --git a/skills/effekseer-vfx/scripts/vfxkit/lint.py b/skills/effekseer-vfx/scripts/vfxkit/lint.pyindex 2ab43ec..d0aa2e5 100644--- a/skills/effekseer-vfx/scripts/vfxkit/lint.py+++ b/skills/effekseer-vfx/scripts/vfxkit/lint.py@@ -46,8 +46,10 @@ def release_frames(recipe):def documented_textures():from .textures import masks,EXTRA_PROCEDURAL- path=ROOT/'vfx/texture_prompts.json'- prompts=json.loads(path.read_text())['prompts'] if path.is_file() else []+ prompts=[]+ for name in ('texture_prompts.json','video_prompts.json'): # painted by an image model, or keyed from a video-model clip+ path=ROOT/'vfx'/name+ prompts+=json.loads(path.read_text(encoding='utf-8'))['prompts'] if path.is_file() else []return set(masks(8))|EXTRA_PROCEDURAL, {p['id'] for p in prompts}def stem(value):return Path(value).stem if value else None@@ -131,7 +133,7 @@ def lint(recipe,known=None):for layer in layers:for key in TEXTURE_KEYS:name=stem(layer.get(key))- if name and name not in procedural|painted:errors.append(f"{layer['name']}.{key}: {name} is neither a math primitive nor recorded in vfx/texture_prompts.json")+ if name and name not in procedural|painted:errors.append(f"{layer['name']}.{key}: {name} is neither a math primitive nor recorded in vfx/texture_prompts.json or vfx/video_prompts.json")if name and not (ROOT/f'vfx/textures/processed/{name}.png').is_file():errors.append(f"{layer['name']}.{key}: vfx/textures/processed/{name}.png is missing")# The compiler multiplies a size/scale curve by a fixed start scale; a random size range with a curve crashes the build.random_scale=isinstance(layer.get('size'),(list,tuple)) or any(isinstance(v,(list,tuple)) for v in layer.get('scale_start') or [])diff --git a/skills/effekseer-vfx/scripts/vfxkit/primitives.py b/skills/effekseer-vfx/scripts/vfxkit/primitives.pyindex 281e605..e16231d 100644--- a/skills/effekseer-vfx/scripts/vfxkit/primitives.py+++ b/skills/effekseer-vfx/scripts/vfxkit/primitives.py@@ -170,6 +170,29 @@ def billow(name,stops,size,life,count=1,frames=16,texture='T_ExplosionSheet01',greturn sprite(name,texture,**ramp(*stops),count=count,life=life,size=size,flipbook=dict(x=grid[0],y=grid[1],frame_length=max(1,round((max(life) if isinstance(life,(list,tuple)) else life)/frames)),loop='Once'),rotation=[0,0,[-180,180]],billboard='RotatedBillboard',fade_in=0,fade_out=4) | kw+def video_body(name,texture,grid=(8,8),size=2.0,frame_length=2,delay=0,column=None,loop=False,start=0,root_inset=0,**kw):+ """A video-model flipbook (`vfx video-flipbook` + `vfx video-grade`) as the effect's body: one particle plays every+ cell once, so the clip's own motion (a column rising and collapsing, fire boiling into smoke) is the shape change.++ The sheet is painted colour with straight alpha, so it is alpha-blended and left white (a colour ramp would tint+ the clip's own light and dark values). frame_length is game frames (60 FPS) per cell: 2 plays a 24 FPS clip about+ 1.25x faster than it was generated, which tightens AI timing. column=<cell width/height> stands the sheet up as a+ Y-axis billboard growing from its base (pillars, geysers); size is then the height, and root_inset (the sheet's empty+ gap under the root as a fraction of the cell height: `bottom_inset` from `vfx unity-export`) sinks it so the root+ touches the ground. Procedural layers (flash, glow,+ sparks, rings, decals) add the core, the secondary motion and the ground around it."""+ cols,rows=grid; frames=cols*rows-start+ base=dict(count=1,life=frames*frame_length,delay=delay,blend='Blend',fade_in=0,fade_out=max(2,frame_length*3),+ flipbook=dict(x=cols,y=rows,frame_length=frame_length,loop='Loop' if loop else 'Once',start=start))+ if column:+ base.update(billboard='YAxisFixed',pivot='bottom',scale_start=[size*column,size,1])+ if root_inset:base['position']=[0,-size*root_inset,0]+ else:+ # Clips usually start at full size (the generated burst is already open); snap it up from a third in ~6 frames so the+ # contact still reads as an explosion instead of a picture switching on.+ base.update(billboard='Billboard',size=size,size_curve=[[0,.35],[5,1],[100,1.06]])+ return sprite(name,texture,WHITE,**base)|kw+def heat_haze(name,size,life=30,delay=0,strength=.6,**kw):"""Screen-space refraction (BackDistortion): bends whatever is behind it, the cue that sells heat and force."""return sprite(name,'T_DistortHaze01',WHITE,material='BackDistortion',distortion=strength,life=life,delay=delay,size=size,size_curve=[[0,.5],[25,1],[100,1.2]],diff --git a/skills/effekseer-vfx/scripts/vfxkit/unity.py b/skills/effekseer-vfx/scripts/vfxkit/unity.pynew file mode 100644index 0000000..c9c3ada--- /dev/null+++ b/skills/effekseer-vfx/scripts/vfxkit/unity.py@@ -0,0 +1,250 @@+"""Unity pipeline: the same flipbooks, played by a small URP runtime instead of Effekseer.++ install copy the com.vfx-skill.flipbook package into <UnityProject>/Packages/ and write the procedural textures it+ needs (flash, smoke, drops, flow noise, ground decal and the distance masks the mesh shells erode) into+ Assets/VfxSkill/Generated/Textures. Everything is drawn from math here: nothing painted ships with the skill.+ export copy a processed sheet into Assets/VfxSkill/Flipbooks/ with a .flipbook.json sidecar (grid, cell size,+ source) so the import rules and the "Create element skill" window read its grid without guessing.++In Unity: VFX Skill → 1. Setup shared materials → 2. Create element skill from flipbooks → 3. Build demo scene.+"""+import json+import shutil+from pathlib import Path++import numpy as np+from PIL import Image, ImageFilter++from .ownership import guard+from .paths import ASSETS++PACKAGE = ASSETS / 'unity/com.vfx-skill.flipbook'+TEXTURES = 'Assets/VfxSkill/Generated/Textures'+FLIPBOOKS = 'Assets/VfxSkill/Flipbooks'+++def _project(path):+ root = Path(path).expanduser().resolve()+ if not (root / 'Assets').is_dir() or not (root / 'ProjectSettings').is_dir():+ raise ValueError(f'{root} is not a Unity project (expected Assets/ and ProjectSettings/)')+ return root+++# ------------------------------------------------------------------ procedural textures+def _save(path, rgb, alpha, root):+ rgb = np.clip(np.broadcast_to(rgb, alpha.shape + (3,)) if np.ndim(rgb) < 3 else rgb, 0, 1)+ img = np.dstack([rgb, np.clip(alpha, 0, 1)])+ guard(path, root)+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.fromarray((img * 255 + 0.5).astype(np.uint8)).save(path)+ return path.name+++def _mask(path, m, root):+ """Greyscale distance mask in alpha (imported as linear data)."""+ return _save(path, np.ones(3), np.asarray(m, dtype=np.float64), root)+++def _inner_gradient(binary, radius, power=0.7):+ """Binary shape → interior gradient (an approximate distance field). A higher power keeps less area near 1, so+ the shell's white core is smaller and erosion thins the shape gradually instead of dropping it all at once."""+ b = np.asarray(Image.fromarray((binary * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(float(radius)))) / 255.0+ g = np.clip((b - 0.5) * 2, 0, 1) * binary+ return np.clip(g / max(g.max(), 1e-6), 0, 1) ** power+++def _periodic(w, k, rng):+ x = np.linspace(0, 2 * np.pi, w, endpoint=False)+ n = sum(rng.uniform(0.3, 1) / f * np.sin(f * x + rng.uniform(0, 6.28)) for f in range(1, k + 1))+ return n / np.abs(n).max()+++def _tile_noise(n, octaves, rng, base=4):+ """Tileable value noise in 0–1: random lattices sampled with wrap-around, smoothly interpolated."""+ out, amp, total = np.zeros((n, n)), 1.0, 0.0+ for o in range(octaves):+ cells = base * 2 ** o+ lat = rng.random((cells, cells))+ t = np.arange(n) * cells / n+ i0 = t.astype(int) % cells; i1 = (i0 + 1) % cells+ f = t - np.floor(t); f = f * f * (3 - 2 * f)+ a = lat[i0][:, i0] * (1 - f)[None, :] + lat[i0][:, i1] * f[None, :]+ b = lat[i1][:, i0] * (1 - f)[None, :] + lat[i1][:, i1] * f[None, :]+ out += amp * (a * (1 - f)[:, None] + b * f[:, None]); total += amp; amp *= 0.5+ return out / total+++def _polar(n):+ yy, xx = np.mgrid[0:n, 0:n]+ dx, dy = (xx - n / 2 + 0.5) / (n / 2), (yy - n / 2 + 0.5) / (n / 2)+ return np.hypot(dx, dy), np.arctan2(dy, dx)+++def _blob(n, rng, lobes=7, rough=0.12, base=0.62):+ """A soft-edged irregular puff: radius wobbles with angle, edge noise breaks the outline."""+ r, th = _polar(n)+ reach = base + sum(rng.uniform(0.02, 0.07) * np.sin(k * th + rng.uniform(0, 6.28)) for k in range(2, lobes))+ edge = (_tile_noise(n, 4, rng, 6) - 0.5) * rough+ return np.clip((reach + edge - r) / 0.06, 0, 1)+++def _sheet(cells, cols):+ n = cells[0].shape[0]; rows = (len(cells) + cols - 1) // cols+ out = np.zeros((rows * n, cols * n) + cells[0].shape[2:])+ for i, c in enumerate(cells):+ out[(i // cols) * n:(i // cols + 1) * n, (i % cols) * n:(i % cols + 1) * n] = c+ return out+++def textures(project, seed=7):+ """Write every texture the package's shared materials and mesh shells sample. Deterministic for a seed."""+ root = _project(project)+ out = root / TEXTURES+ rng = np.random.default_rng(seed)+ written = []++ r, th = _polar(256) # contact flash: hot centre, fast falloff, 6 faint rays+ rays = 0.25 * np.abs(np.cos(th * 3)) ** 8 * np.clip(1 - r, 0, 1)+ written.append(_save(out / 'T_Flash.png', np.ones(3), np.clip(1 - r, 0, 1) ** 2.4 + rays, root))++ cells = [] # smoke 2×2: neutral puffs, coloured by particle colour+ for _ in range(4):+ a = _blob(256, rng, rough=0.22, base=0.6)+ shade = 0.72 + 0.28 * np.clip(1 - _polar(256)[0] * 0.9, 0, 1) * _tile_noise(256, 3, rng, 3)+ cells.append(np.dstack([shade, shade, shade, a * (0.55 + 0.45 * _tile_noise(256, 4, rng, 4))]))+ s = _sheet(cells, 2); written.append(_save(out / 'T_Smoke_2x2.png', s[..., :3], s[..., 3], root))++ cells = [] # drops 2×2: round beads, dark-edged, one highlight+ for i in range(4):+ n = 128; r2, _ = _polar(n)+ a = _blob(n, rng, lobes=4, rough=0.05, base=0.5 + 0.08 * (i % 2))+ yy, xx = np.mgrid[0:n, 0:n]+ hl = np.hypot(xx - n * 0.38, yy - n * 0.36) < n * 0.09+ v = np.where(hl, 1.0, 0.62 + 0.38 * np.clip(1 - r2 * 1.4, 0, 1))+ cells.append(np.dstack([v, v, v, a]))+ s = _sheet(cells, 2); written.append(_save(out / 'T_Drop_2x2.png', s[..., :3], s[..., 3], root))++ noise = np.dstack([_tile_noise(256, 5, rng, 4) for _ in range(3)]) # flow noise: RGB, tileable, linear+ written.append(_save(out / 'T_FlowNoise.png', noise, np.ones((256, 256)), root))++ a = _blob(256, rng, lobes=11, rough=0.35, base=0.66) # ground decal: splat with broken edge and drops round it+ for _ in range(14):+ cx, cy, rad = rng.uniform(20, 236), rng.uniform(20, 236), rng.uniform(3, 9)+ yy, xx = np.mgrid[0:256, 0:256]+ a = np.maximum(a, (np.hypot(xx - cx, yy - cy) < rad).astype(float))+ written.append(_save(out / 'T_Decal.png', np.ones(3), a * (0.7 + 0.3 * _tile_noise(256, 4, rng, 5)), root))++ # Distance masks for StylizedShell (core / body / dark rim by threshold, eroded over life).+ W, H = 512, 256 # crown: U-tileable splash wall with spikes, holes, drops+ yy, xx = np.mgrid[0:H, 0:W]+ v = 1 - yy / (H - 1); u = xx / W; spikes = 7+ heights = rng.uniform(0.62, 0.95, spikes)+ hi = heights[(u * spikes).astype(int) % spikes]+ spike = 0.36 + (hi - 0.36) * np.clip(1 - np.abs((u * spikes) % 1.0 - 0.5) * 2.2, 0, 1) ** 1.6+ crown = (v < spike + _periodic(W, 9, rng)[xx] * 0.03).astype(float)+ for _ in range(10):+ cx, cy, rad = rng.uniform(0, W), rng.uniform(0.42, 0.62) * H, rng.uniform(7, 14)+ crown[np.hypot(((xx - cx + W / 2) % W) - W / 2, (H - 1 - yy) - cy) < rad] = 0+ for _ in range(16):+ i = rng.integers(0, spikes)+ cx, cy, rad = (i + 0.5 + rng.normal(0, 0.06)) / spikes * W, (heights[i] + rng.uniform(0.04, 0.12)) * H, rng.uniform(5, 10)+ crown[np.hypot(((xx - cx + W / 2) % W) - W / 2, (H - 1 - yy) - cy) < rad] = 1+ written.append(_mask(out / 'T_MaskCrown.png', _inner_gradient(np.roll(crown, W // 2, 1), 12, 1.25), root))++ W, H = 1024, 128 # ribbon: long band, pointed ends, two cracks, ragged edge+ yy, xx = np.mgrid[0:H, 0:W]+ u, v = xx / (W - 1), yy / (H - 1)+ width = np.sin(np.pi * u) ** 0.8 * (0.40 + 0.05 * np.sin(u * 23)) * (1 + 0.12 * _periodic(W, 24, rng)[xx] * u)+ wob = 0.05 * np.sin(u * 17 + 1.2) + 0.03 * np.sin(u * 41)+ band = (np.abs(v - 0.5 - wob * np.sin(np.pi * u)) < width).astype(float)+ for c, w0 in ((0.38, 0.018), (0.6, 0.012)):+ band[(np.abs(v - c - 0.03 * np.sin(u * 13 + c * 9)) < w0 * (0.4 + u)) & (u > 0.25)] = 0+ written.append(_mask(out / 'T_MaskRibbon.png', _inner_gradient(band, 10, 1.5), root))++ v = np.linspace(0, 1, 32)[:, None] * np.ones((1, 256)) # bolt strip: cross-section, ridge 1 → edges 0+ written.append(_mask(out / 'T_MaskBoltStrip.png', np.clip(1 - np.abs(v - 0.5) * 2, 0, 1) ** 1.3, root))++ r, th = _polar(256); spikes = 9 # contact star: uneven many-pointed burst+ amp = rng.uniform(0.55, 1.0, spikes)+ k = (th / (2 * np.pi) * spikes) % 1.0+ reach = 0.3 + (amp[((th + np.pi) / (2 * np.pi) * spikes).astype(int) % spikes] - 0.3) * np.clip(1 - np.abs(k - 0.5) * 2, 0, 1) ** 1.1+ written.append(_mask(out / 'T_MaskHitStar.png', _inner_gradient((r < reach * 0.95).astype(float), 12, 1.3), root))++ ring = ((r > 0.7 + 0.03 * np.sin(th * 7)) & (r < 0.86 + 0.03 * np.sin(th * 5 + 1))).astype(float) # impact ring with a gap+ ring[(np.sin(th * 2 + 0.7) > 0.94) & (r > 0.6)] = 0+ written.append(_mask(out / 'T_MaskRing.png', _inner_gradient(ring, 6, 1.0), root))+ return {'folder': str(out), 'textures': written}+++# ------------------------------------------------------------------ commands+def install(project, force=False):+ """Copy the package into Packages/ (Unity picks embedded packages up without editing the manifest) and write the+ procedural textures (always rewritten: they are generated). An existing package copy is replaced only with force, so+ local edits are never lost silently."""+ root = _project(project)+ dest = root / 'Packages' / PACKAGE.name+ guard(dest, root)+ if dest.exists() and not force:+ state = 'kept (pass --force to replace it with the skill\'s version)'+ else:+ # Unity identifies scripts, shaders and assets by the GUIDs in the .meta files it generated: keep them, or every+ # scene and material that uses the package loses its scripts ("Missing script") and shaders (pink).+ metas = {m.relative_to(dest): m.read_bytes() for m in dest.rglob('*.meta')} if dest.exists() else {}+ if dest.exists():+ shutil.rmtree(dest)+ shutil.copytree(PACKAGE, dest, ignore=shutil.ignore_patterns('*.meta', '.DS_Store'))+ for rel, data in metas.items():+ if (dest / rel).with_suffix('').exists():+ guard(dest / rel, root).write_bytes(data)+ state = 'updated (asset GUIDs kept)' if metas else 'installed'+ tex = textures(root)+ version = json.loads((PACKAGE / 'package.json').read_text())['version']+ return {'ok': True, 'package': str(dest), 'version': version, 'package_state': state, **tex,+ 'next': ['Open the project in Unity (6000.0+, URP).', 'VFX Skill → 1. Setup shared materials',+ f'vfx unity-export <sheet.png> {root} for each flipbook', 'VFX Skill → 2. Create element skill from flipbooks',+ 'VFX Skill → 3. Build demo scene, then Play']}+++def export(sheet, project, grid=None, name=None):+ """Copy one processed sheet into the Unity project with its grid sidecar."""+ root = _project(project)+ src = Path(sheet).expanduser().resolve()+ if not src.is_file():+ raise FileNotFoundError(src)+ if grid is None: # video-flipbook / video-grade record every sheet's grid+ from .video import PROMPTS+ entries = json.loads(PROMPTS.read_text(encoding='utf-8')).get('prompts', []) if PROMPTS.is_file() else []+ entry = next((e for e in entries if e.get('id') == src.stem), {})+ grid = entry.get('grid') or entry.get('params', {}).get('grid')+ if not grid:+ raise ValueError('pass --grid COLS ROWS (no grid found for this sheet)')+ cols, rows = int(grid[0]), int(grid[1])+ w, h = Image.open(src).size+ if w % cols or h % rows:+ raise ValueError(f'{src.name} is {w}×{h}: not divisible into a {cols}×{rows} grid')+ if name and (Path(name).name != name or name in ('.', '..')):+ raise ValueError(f'--name must be a plain file name, not {name!r}')+ dest = root / FLIPBOOKS / f'{name or src.stem}.png'+ guard(dest, root)+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(src, dest)+ side = dest.with_suffix('.flipbook.json')+ guard(side, root)+ inset = bottom_inset(src, cols, rows)+ side.write_text(json.dumps({'grid': [cols, rows], 'cell': [w // cols, h // rows], 'frames': cols * rows, 'bottom_inset': inset, 'source': src.name}, indent=2) + '\n', encoding='utf-8')+ return {'ok': True, 'sheet': str(dest), 'sidecar': str(side), 'grid': [cols, rows], 'cell': [w // cols, h // rows], 'bottom_inset': inset}+++def bottom_inset(sheet, cols, rows, alpha=0.25):+ """How far the drawn shape stays above each cell's bottom edge (fraction of the cell height, gutter included), taken+ low across the cells that have content. A column played from its base sinks by this much so its root touches the+ ground instead of floating with a strip of dry floor below it."""+ a = np.asarray(Image.open(sheet).convert('RGBA'))[..., 3] / 255.0+ h, w = a.shape[0] // rows, a.shape[1] // cols+ gaps = []+ for r in range(rows):+ for c in range(cols):+ filled = np.nonzero((a[r * h:(r + 1) * h, c * w:(c + 1) * w] > alpha).any(axis=1))[0]+ if len(filled):+ gaps.append((h - 1 - filled[-1]) / h)+ return round(float(np.percentile(gaps, 10)), 4) if gaps else 0.0diff --git a/skills/effekseer-vfx/scripts/vfxkit/video.py b/skills/effekseer-vfx/scripts/vfxkit/video.pynew file mode 100644index 0000000..826a45e--- /dev/null+++ b/skills/effekseer-vfx/scripts/vfxkit/video.py@@ -0,0 +1,413 @@+"""Video-model flipbooks: a generated clip on black becomes a straight-alpha sheet the engines play frame by frame.++An image model paints one frame; a video model (image-to-video with a first and a last frame) also paints the motion:+a water column that rises, holds and collapses, fire that turns to smoke. Those continuous changes of shape are what+layered primitives cannot draw. This module turns such a clip into a sheet and gives every sheet the same look:++ timeline labelled frames of the clip, to pick the span that carries the effect+ flipbook decode at a fixed rate, luminance key on black, one shared crop for every frame (no jitter), a noisy+ round or rounded-box mask per cell (never a square edge), a fully transparent gutter round every cell,+ and a hard failure if any cell border still has alpha+ grade re-colour by density with one value ramp per element (dark rim → body → light → hot core), erode the+ haze that keying leaves behind, fade the last cells to zero, optionally cool the tail to smoke+ first_frame put a generated element image on pure black at the size and place the clip should start from++Originals stay in vfx/videos/ and vfx/textures/generated/; sheets go to vfx/textures/processed/; contact sheets and+the parameters of every run go to vfx/work/video/ so a sheet can be rebuilt exactly.+"""+import json+import math+import shutil+import subprocess+import tempfile+from pathlib import Path++import numpy as np+from PIL import Image, ImageDraw, ImageFilter++from .ownership import guard+from .paths import ROOT, WORK++REPORTS = WORK / 'video'+PROMPTS = ROOT / 'vfx/video_prompts.json' # every video-made texture, with the clip, its prompt and the exact parameters+FPS = 24 # every clip is decoded at one rate: generated clips often have variable frame rates+++# ------------------------------------------------------------------ helpers+def _ffmpeg():+ exe = shutil.which('ffmpeg')+ if not exe:+ raise RuntimeError('ffmpeg was not found on PATH; install it (brew install ffmpeg, winget install ffmpeg)')+ return exe+++def _decode(video, folder, fps=FPS):+ video = Path(video).resolve()+ if not video.is_file():+ raise FileNotFoundError(video)+ subprocess.run([_ffmpeg(), '-loglevel', 'error', '-i', str(video), '-vf', f'fps={fps}', str(Path(folder) / 'f_%04d.png')], check=True)+ files = sorted(Path(folder).glob('f_*.png'))+ if not files:+ raise ValueError(f'{video} decoded to no frames')+ return files+++def _png(path):+ """Append .png unless it is already there: names may contain dots (T_Hit.v2, T_Burst_1.5)."""+ return path if path.suffix.lower() == '.png' else path.with_name(path.name + '.png')+++def _in_project(path, default):+ """A relative path that starts with vfx/ is project-relative; a bare name lands in `default`."""+ path = Path(path)+ if path.is_absolute():+ return path+ return ROOT / path if path.parts[:1] == ('vfx',) else ROOT / default / path+++def _resolve_output(output):+ """Bare names land in vfx/textures/processed/; every write must stay inside the project."""+ return guard(_png(_in_project(output, 'vfx/textures/processed')), ROOT)+++def _resolve_sheet(source):+ """A sheet given as a path, a project path (vfx/...) or the bare name of a processed texture."""+ path = Path(source)+ for candidate in (path, _png(path), _png(_in_project(path, 'vfx/textures/processed'))):+ if candidate.is_file():+ return candidate.resolve()+ raise FileNotFoundError(f'no sheet {source} (looked in vfx/textures/processed/ too)')+++def _portable(path):+ """Project-relative when inside the project, else the file name only: the record is meant for version control and+ must not carry user names or home folders."""+ path = Path(path).resolve()+ return path.relative_to(ROOT).as_posix() if path.is_relative_to(ROOT) else path.name+++def _report_dir():+ REPORTS.mkdir(parents=True, exist_ok=True)+ return guard(REPORTS / 'x', ROOT).parent+++def record(texture_id, entry):+ """Upsert one texture's provenance into vfx/video_prompts.json (lint accepts textures recorded here)."""+ data = json.loads(PROMPTS.read_text(encoding='utf-8')) if PROMPTS.is_file() else {'note': 'Textures made from generated video clips: '+ 'the clip, the prompt that made it and the parameters that rebuild the sheet exactly.', 'prompts': []}+ data['prompts'] = [p for p in data['prompts'] if p.get('id') != texture_id] + [{'id': texture_id, **entry}]+ guard(PROMPTS, ROOT).parent.mkdir(parents=True, exist_ok=True)+ PROMPTS.write_text(json.dumps(data, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')+++def _prompt_text(prompt=None, prompt_file=None):+ if prompt_file:+ return Path(prompt_file).read_text(encoding='utf-8').strip()+ return prompt+++def _smoothstep(a, b, x):+ t = np.clip((x - a) / (b - a), 0, 1)+ return t * t * (3 - 2 * t)+++def _key(path, floor, gain, dehaze):+ """Black → alpha. The median of a thin border ring is the frame's haze; it is subtracted before keying, and+ colour is un-premultiplied so thin glows keep their hue instead of turning grey."""+ img = np.asarray(Image.open(path).convert('RGB'), np.float32) / 255+ h, w = img.shape[:2]+ b = max(2, int(min(h, w) * .06))+ ring = np.concatenate([img[:b].reshape(-1, 3), img[-b:].reshape(-1, 3), img[:, :b].reshape(-1, 3), img[:, -b:].reshape(-1, 3)])+ haze = np.median(ring, axis=0) * dehaze+ img = np.clip((img - haze) / np.maximum(1 - haze, 1e-3), 0, 1)+ al = np.clip((img.max(-1) - floor) / (1 - floor) * gain, 0, 1) ** .9+ rgb = np.clip(img * gain / np.maximum(al, 1e-3)[..., None], 0, 1) * (al[..., None] > .002)+ return np.dstack([rgb, al])+++def _sheet(img, path, width=1024, bg=(95, 120, 150)):+ """The sheet over a mid blue-grey: keyed edges, haze and dark rims are all visible against it."""+ back = Image.new('RGBA', img.size, bg + (255,))+ back.alpha_composite(img)+ back.convert('RGB').resize((width, round(width * img.height / img.width))).save(path, quality=88)+++def _parse_frames(spec, total):+ a, b, s = (int(v) for v in spec.split(':'))+ if s < 1 or a < 0 or b >= total or a > b:+ raise ValueError(f'--frames {spec}: need start:end:step inside 0..{total - 1}')+ return list(range(a, b + 1, s))+++# ------------------------------------------------------------------ timeline+def timeline(video, step=2, columns=10):+ """Every `step`-th frame (24 fps numbering, the same numbers `flipbook` takes) in a labelled grid."""+ tmp = Path(tempfile.mkdtemp())+ try:+ files = _decode(video, tmp)+ picks = list(range(0, len(files), max(1, step)))+ first = Image.open(files[0])+ tw = 160; th = round(tw * first.height / first.width)+ rows = math.ceil(len(picks) / columns)+ grid = Image.new('RGB', (tw * columns, th * rows))+ draw = ImageDraw.Draw(grid)+ for k, i in enumerate(picks):+ x, y = (k % columns) * tw, (k // columns) * th+ grid.paste(Image.open(files[i]).convert('RGB').resize((tw, th)), (x, y))+ draw.rectangle((x, y, x + 34, y + 14), fill=(0, 0, 0)); draw.text((x + 3, y + 1), str(i), fill=(255, 230, 0))+ out = _report_dir() / f'{Path(video).stem}_timeline.jpg'+ grid.save(out, quality=88)+ return {'ok': True, 'video': _portable(video), 'frames': len(files), 'fps': FPS, 'size': [first.width, first.height],+ 'timeline': str(out), 'note': 'pick the span that carries the effect; skip opening white flashes and frames that fill the whole picture'}+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+++# ------------------------------------------------------------------ flipbook+def flipbook(video, output, cols=8, rows=8, cell=256, cell_h=0, start=-1, end=-1, frames=None, crop='auto', box=None,+ pad=1.04, radius=.38, feather=.12, mask_power=2.0, floor=.06, gain=1.3, gutter=6, dehaze=1.0, prompt=None, prompt_file=None):+ """Decode → key → shared crop → masked cells with transparent gutters → one sheet (cols × rows cells of cell × cell_h).++ `frames` 'a:b:s' picks exact 24 fps frames (len must equal cols*rows); otherwise `start`..`end` (auto: the span with+ visible content) is sampled evenly. `crop` 'auto' takes the union bounding box of every picked frame (padded by `pad`)+ at the cell's aspect; `box` 'cx,cy,half_width' (pixels) sets it by hand when stray sparks inflate the union.+ `mask_power` 2 is a round mask, 3-5 a rounded box for tall or wide shapes that touch the cell's top and bottom."""+ out = _resolve_output(output)+ cell_h = cell_h or cell+ n = cols * rows+ if min(cols, rows) < 1 or cell < 32 or cell_h < 32 or gutter < 2:+ raise ValueError('need cols, rows ≥ 1, cells ≥ 32 px and a gutter of at least 2 px')+ if cols * cell > 4096 or rows * cell_h > 4096:+ raise ValueError(f'sheet {cols * cell}×{rows * cell_h} exceeds 4096 px; use smaller cells or fewer frames')+ tmp = Path(tempfile.mkdtemp())+ try:+ files = _decode(video, tmp)+ if frames:+ pick = _parse_frames(frames, len(files))+ if len(pick) != n:+ raise ValueError(f'--frames gives {len(pick)} frames, the sheet has {n} cells')+ s, e = pick[0], pick[-1]+ else:+ cover = np.array([float((np.asarray(Image.open(f).convert('L'), np.float32) / 255 > floor + .04).mean()) for f in files])+ active = np.where(cover > max(cover.max() * .02, 1e-4))[0]+ if start >= len(files) or end >= len(files):+ raise ValueError(f'--start/--end beyond the clip: it has {len(files)} frames at {FPS} fps (0..{len(files) - 1})')+ s = start if start >= 0 else int(active[0]) if len(active) else 0+ e = end if end >= 0 else int(active[-1]) if len(active) else len(files) - 1+ if e <= s:+ raise ValueError(f'empty span {s}..{e}')+ pick = [round(s + i * (e - s) / max(n - 1, 1)) for i in range(n)]+ keyed = [_key(files[i], floor, gain, dehaze) for i in pick]+ H, W = keyed[0].shape[:2]+ asp = cell_h / cell+ if box:+ cx, cy, hw = (float(v) for v in str(box).split(','))+ elif crop == 'auto':+ union = np.zeros((H, W), bool)+ for fr in keyed:+ union |= fr[..., 3] > .03+ ys, xs = np.where(union)+ if not len(xs):+ raise ValueError('no visible pixels in the picked span; lower --floor or check the clip')+ cy, cx = (ys.min() + ys.max()) / 2, (xs.min() + xs.max()) / 2+ hw = max((xs.max() - xs.min()) / 2, (ys.max() - ys.min()) / 2 / asp) * pad+ hw = min(hw, W / 2, H / 2 / asp)+ cy = float(np.clip(cy, hw * asp, H - hw * asp)); cx = float(np.clip(cx, hw, W - hw))+ else:+ hw = min(W / 2, H / 2 / asp); cx, cy = W / 2, H / 2+ hh = hw * asp+ crop_box = (int(cx - hw), int(cy - hh), int(cx + hw), int(cy + hh))+ inner_w, inner_h = cell - 2 * gutter, cell_h - 2 * gutter+ wob = .04+ limit = .5 - 1.5 / min(inner_w, inner_h) # the mask (noise and feather included) stays inside the cell+ clamped = radius + wob + feather / 2 > limit+ if clamped:+ radius = limit - wob - feather / 2+ yy = np.linspace(0, 1, inner_h)[:, None] * np.ones((1, inner_w)); xx = np.ones((inner_h, 1)) * np.linspace(0, 1, inner_w)[None, :]+ r = (np.abs(xx - .5) ** mask_power + np.abs(yy - .5) ** mask_power) ** (1 / mask_power)+ th = np.arctan2(yy - .5, xx - .5)+ sheet = Image.new('RGBA', (cell * cols, cell_h * rows))+ for k, fr in enumerate(keyed):+ im = Image.fromarray((fr * 255 + .5).astype(np.uint8)).crop(crop_box).resize((inner_w, inner_h), Image.Resampling.LANCZOS)+ arr = np.asarray(im, np.float32).copy()+ ph = k * .07 # the edge noise drifts slowly, so the border never reads as a fixed shape+ w = wob * (.47 * np.sin(5 * th + 1.3 + ph) + .33 * np.sin(9 * th + 4.1 - ph * 1.7) + .2 * np.sin(17 * th + .6 + ph * 2.3))+ m = np.clip((radius + w - r) / feather + .5, 0, 1)+ arr[..., 3] *= m * m * (3 - 2 * m)+ sheet.paste(Image.fromarray(arr.astype(np.uint8)), ((k % cols) * cell + gutter, (k // cols) * cell_h + gutter))+ alpha = np.asarray(sheet)[..., 3]+ bad = [k for k in range(n) if max(alpha[(k // cols) * cell_h:(k // cols) * cell_h + 2, (k % cols) * cell:(k % cols + 1) * cell].max(),+ alpha[(k // cols + 1) * cell_h - 2:(k // cols + 1) * cell_h, (k % cols) * cell:(k % cols + 1) * cell].max(),+ alpha[(k // cols) * cell_h:(k // cols + 1) * cell_h, (k % cols) * cell:(k % cols) * cell + 2].max(),+ alpha[(k // cols) * cell_h:(k // cols + 1) * cell_h, (k % cols + 1) * cell - 2:(k % cols + 1) * cell].max()) > 0]+ if bad:+ raise ValueError(f'cell borders are not transparent in cells {bad[:8]}: raise --gutter or lower --radius')+ out.parent.mkdir(parents=True, exist_ok=True)+ sheet.save(out)+ rep = _report_dir()+ contact = rep / f'{out.stem}_sheet.jpg'+ _sheet(sheet, contact)+ info = {'ok': True, 'video': _portable(video), 'output': str(out), 'grid': [cols, rows], 'cell': [cell, cell_h],+ 'sheet_size': [cell * cols, cell_h * rows], 'frames_total': len(files), 'fps': FPS, 'span': [s, e], 'picked': pick,+ 'duration_s': round((e - s + 1) / FPS, 3), 'crop_box': list(crop_box), 'gutter': gutter, 'radius': round(radius, 3),+ 'radius_clamped': bool(clamped), 'mask_power': mask_power, 'contact_sheet': str(contact),+ 'params': {'floor': floor, 'gain': gain, 'pad': pad, 'feather': feather, 'dehaze': dehaze, 'box': box, 'crop': crop}}+ (rep / f'{out.stem}.json').write_text(json.dumps(info, indent=1))+ text = _prompt_text(prompt, prompt_file)+ record(out.stem, {'kind': 'video flipbook', 'video': info['video'], 'prompt': text, 'grid': [cols, rows], 'cell': [cell, cell_h],+ 'frames': pick, 'crop_box': list(crop_box), 'params': info['params'] | {'mask_power': mask_power, 'radius': info['radius'], 'gutter': gutter},+ 'source': 'video generation model (image-to-video, first frame + black last frame); keyed with vfx video-flipbook'})+ if not text:+ info['warning'] = 'no --prompt/--prompt-file: record the video prompt so the clip can be made again'+ return info+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+++# ------------------------------------------------------------------ grade+def _ramp(spec):+ stops = []+ for part in spec.split(';'):+ k, c = part.split(':')+ rgb = [float(v) for v in c.split(',')]+ if len(rgb) != 3:+ raise ValueError(f'ramp stop {part!r}: need position:r,g,b')+ stops.append((float(k), np.array(rgb)))+ return sorted(stops, key=lambda x: x[0])+++def _eval(stops, d):+ ks = [k for k, _ in stops]+ return np.stack([np.interp(d, ks, [c[i] for _, c in stops]) for i in range(3)], -1)+++def grade(source, output, cols=8, rows=8, ramp=None, erode=.22, erode_pow=1.5, tail_fade=6, highlight=0.0, ramp_fade=None,+ smoke=None, smoke_start=.4, keep_embers=False, late_gamma=1.0, late_alpha=1.0, alpha_gamma=1.0, late_blur=0.0, body_mask=0.0,+ open_px=0, open_until=1.0, cut_below=None, cut_from=0.0):+ """Re-colour a keyed sheet cell by cell (t = cell / last cell).++ - `erode`/`erode_pow`: the alpha threshold rises over time, so thin haze goes first and the structure last;+ `tail_fade` brings the last cells linearly to zero (no pop when the particle dies).+ - `ramp` 'pos:r,g,b;...' maps density (alpha × luminance) to the element's value ramp; close stops give hard+ cel steps. `highlight` keeps white only on fine detail (spray, glints). `ramp_fade` 't0,t1' blends back to the+ clip's own colours later in the sheet (a clip's grey smoke and embers usually read better than a re-colour).+ - `smoke`/`smoke_start` cool the tail towards one smoke colour; `keep_embers` leaves saturated orange-red pixels of+ the clip alone. Dark smoke turns transparent in a luminance key: `late_gamma` < 1 thickens only the late cells+ (a whole-sheet `alpha_gamma` grows a dark halo round bright fire); `late_alpha` multiplies late alpha.+ - `late_blur` softens late cells into one mass; `body_mask` removes strands thinner than its blur radius (dripping+ sparks under a fireball) while bodies keep round edges; `open_px` is a morphological opening for the early cells;+ `cut_below` fades everything below a cell height (0 top .. 1 bottom) from `cut_from` on."""+ src = _resolve_sheet(source)+ out = _resolve_output(output)+ if src == out.resolve():+ raise ValueError('output cannot overwrite the source sheet')+ im = np.asarray(Image.open(src).convert('RGBA')).astype(np.float64) / 255+ H, W = im.shape[0] // rows, im.shape[1] // cols+ if H * rows != im.shape[0] or W * cols != im.shape[1]:+ raise ValueError(f'{im.shape[1]}×{im.shape[0]} does not divide into {cols}×{rows} cells')+ stops = _ramp(ramp) if ramp else None+ smoke_rgb = np.array([float(v) for v in smoke.split(',')]) if smoke else None+ fade = [float(v) for v in ramp_fade.split(',')] if ramp_fade else None+ total = cols * rows+ res = im.copy()+ yy = np.linspace(0, 1, H)[:, None] * np.ones((1, W))+ for k in range(total):+ t = k / max(total - 1, 1)+ y, x = (k // cols) * H, (k % cols) * W+ c = im[y:y + H, x:x + W]+ rgb, al = c[..., :3], c[..., 3]+ f = .02 + erode * t ** erode_pow if total > 1 else 0.0+ a2 = np.clip((al - f) / (1 - f), 0, 1)+ if body_mask > 0:+ bm = np.asarray(Image.fromarray((a2 * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(float(body_mask)))).astype(np.float64) / 255+ peak = max(np.percentile(bm, 99.5), 1e-3)+ a2 = a2 * _smoothstep(.22 * peak, .42 * peak, bm)+ if open_px > 0 and t <= open_until:+ size = open_px * 2 + 1+ o = Image.fromarray((a2 * 255).astype(np.uint8))+ a2 = np.minimum(a2, np.asarray(o.filter(ImageFilter.MinFilter(size)).filter(ImageFilter.MaxFilter(size))).astype(np.float64) / 255)+ if alpha_gamma != 1.0:+ a2 = a2 ** alpha_gamma+ if late_gamma != 1.0:+ a2 = a2 ** (1 + (late_gamma - 1) * _smoothstep(smoke_start, .7, t))+ if late_alpha != 1.0:+ a2 = np.clip(a2 * (1 + (late_alpha - 1) * _smoothstep(smoke_start, .8, t)), 0, 1)+ if cut_below is not None and t >= cut_from:+ a2 = a2 * (1 - _smoothstep(cut_below - .04, cut_below + .06, yy))+ if tail_fade > 0 and total > 1 and k >= total - tail_fade:+ a2 = a2 * (total - 1 - k) / tail_fade+ lum = rgb @ np.array([.3, .55, .15])+ if stops is not None:+ body = _eval(stops, np.clip(a2 * (.5 + .5 * lum), 0, 1))+ if highlight > 0:+ blur = np.asarray(Image.fromarray((lum * a2 * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(5))).astype(np.float64) / 255+ hp = np.clip((lum * a2 - blur) * highlight, 0, 1)[..., None]+ body = body * (1 - hp) + stops[-1][1] * hp+ if fade:+ w = _smoothstep(fade[0], fade[1], t)+ body = body * (1 - w) + rgb * w+ rgb = body+ if smoke_rgb is not None:+ s = _smoothstep(smoke_start, .85, t)+ l2 = rgb @ np.array([.3, .55, .15])+ sm = np.full(a2.shape, .85 * s)+ if keep_embers:+ o = c[..., :3]+ sm = sm * (1 - np.clip((o[..., 0] - o[..., 2] - .3) * 3, 0, 1))+ rgb = rgb * (1 - sm[..., None]) + smoke_rgb * (.7 + .5 * l2[..., None]) * sm[..., None]+ if late_blur > 0:+ rad = float(late_blur * _smoothstep(smoke_start + .1, .85, t)) # newer Pillow rejects a numpy scalar radius+ if rad > .3:+ pm = np.dstack([np.clip(rgb, 0, 1) * a2[..., None], a2])+ b = np.asarray(Image.fromarray((pm * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(rad))).astype(np.float64) / 255+ a2 = np.clip(b[..., 3] * 1.15, 0, 1)+ rgb = b[..., :3] / np.maximum(b[..., 3:4], 1e-3)+ res[y:y + H, x:x + W, :3] = np.clip(rgb, 0, 1)+ res[y:y + H, x:x + W, 3] = a2+ for k in range(rows * cols): # blur and dilation can reach the gutter: keep every cell border transparent, like the flipbook+ y, x = (k // cols) * H, (k % cols) * W+ for sl in ((slice(y, y + 2), slice(x, x + W)), (slice(y + H - 2, y + H), slice(x, x + W)), (slice(y, y + H), slice(x, x + 2)), (slice(y, y + H), slice(x + W - 2, x + W))):+ res[sl + (3,)] = 0+ out.parent.mkdir(parents=True, exist_ok=True)+ final = Image.fromarray((res * 255 + .5).astype(np.uint8))+ final.save(out)+ contact = _report_dir() / f'{out.stem}_sheet.jpg'+ _sheet(final, contact, bg=(150, 190, 120))+ params = {'source': _portable(src), 'grid': [cols, rows], 'ramp': ramp, 'erode': erode, 'erode_pow': erode_pow, 'tail_fade': tail_fade,+ 'highlight': highlight, 'ramp_fade': ramp_fade, 'smoke': smoke, 'smoke_start': smoke_start, 'keep_embers': keep_embers,+ 'late_gamma': late_gamma, 'late_alpha': late_alpha, 'alpha_gamma': alpha_gamma, 'late_blur': late_blur, 'body_mask': body_mask,+ 'open_px': open_px, 'open_until': open_until, 'cut_below': cut_below, 'cut_from': cut_from}+ (_report_dir() / f'{out.stem}.grade.json').write_text(json.dumps(params, indent=1))+ record(out.stem, {'kind': 'graded video flipbook', 'from': src.stem, 'params': params, 'source': 'vfx video-grade of ' + src.stem})+ return {'ok': True, 'output': str(out), 'contact_sheet': str(contact), 'grid': [cols, rows], 'cell': [W, H],+ 'note': 'check the contact sheet: bodies keep colour on a bright background, the last cells are clean'}+++# ------------------------------------------------------------------ first frame+def first_frame(source, output, width=1024, height=1024, fill=.35, anchor='center', floor=.04):+ """Crop a generated element image on black and place it on a pure black canvas of the clip's size.++ `fill` is the longest side of the element as a fraction of the canvas's shorter side: small, so the motion has room+ and never leaves the frame. `anchor` 'bottom' puts it near the bottom edge (an eruption that rises)."""+ src = Path(source).resolve()+ out = guard(_png(_in_project(output, 'vfx/videos/frames')), ROOT)+ img = np.asarray(Image.open(src).convert('RGB')).astype(np.float64) / 255+ ys, xs = np.where(img.max(-1) > floor + .04)+ if not len(ys):+ raise ValueError('no visible content above the black floor')+ crop = img[ys.min():ys.max() + 1, xs.min():xs.max() + 1]+ crop = np.where(crop.max(-1, keepdims=True) > floor, crop, 0)+ h, w = crop.shape[:2]+ s = fill * min(width, height) / max(h, w)+ el = Image.fromarray((crop * 255).astype(np.uint8)).resize((max(1, round(w * s)), max(1, round(h * s))), Image.Resampling.LANCZOS)+ canvas = Image.new('RGB', (width, height))+ x = (width - el.width) // 2+ y = (height - el.height) // 2 if anchor == 'center' else height - el.height - round(height * .08)+ canvas.paste(el, (x, y))+ out.parent.mkdir(parents=True, exist_ok=True)+ canvas.save(out)+ last = out.with_name(f'black_{width}x{height}.png')+ if not last.exists():+ Image.new('RGB', (width, height)).save(guard(last, ROOT))+ return {'ok': True, 'first_frame': str(out), 'last_frame': str(last), 'size': [width, height], 'element_size': [el.width, el.height],+ 'note': 'use first_frame as the first frame and the black image as the last frame of an image-to-video generation'}diff --git a/tests/test_privacy.py b/tests/test_privacy.pyindex c64900d..bd6d319 100644--- a/tests/test_privacy.py+++ b/tests/test_privacy.py@@ -34,7 +34,9 @@ CREDENTIAL = re.compile(r'(?:sk-[A-Za-z0-9_-]{20,}|sk-ant-[A-Za-z0-9_-]{10,}|gh[# PNG chunks that carry pixels only; text, EXIF, XMP and ICC profiles (which can name a person or a machine) do not.PNG_SIGNATURE = b'\x89PNG\r\n\x1a\n'PNG_PIXEL_CHUNKS = {b'IHDR', b'PLTE', b'tRNS', b'IDAT', b'IEND', b'gAMA', b'cHRM', b'sRGB', b'sBIT', b'pHYs'}-REVIEWED_BINARY_SUFFIXES = {'.png'}+REVIEWED_BINARY_SUFFIXES = {'.png', '.jpg'}+# JPEG segments that carry pixels only; APP1 (EXIF, XMP), APP2 (ICC), APP13 (IPTC) and comments can name a person or a machine.+JPEG_PIXEL_MARKERS = {0xC0, 0xC1, 0xC2, 0xC4, 0xDB, 0xDD, 0xE0}def files():@@ -46,7 +48,7 @@ def files():def publisher_allowed(path):relative = path.relative_to(PACKAGE).as_posix()return relative in ('LICENSE', 'skills/effekseer-vfx/LICENSE', 'skills/vfx-review/LICENSE',- '.claude-plugin/plugin.json', '.claude-plugin/marketplace.json') or (+ '.claude-plugin/plugin.json', '.claude-plugin/marketplace.json', 'docs/brand/README.md') or ('/' not in relative and path.name.upper().startswith('README'))@@ -99,10 +101,30 @@ def png_metadata(data):return extra+def jpeg_metadata(data):+ """Names of JPEG segments beyond pixel data (JFIF header, tables, frame and scan are fine)."""+ if not data.startswith(b'\xff\xd8'):+ return ['not a JPEG']+ extra, offset = [], 2+ while offset + 4 <= len(data):+ if data[offset] != 0xFF:+ return extra + ['broken segment structure']+ marker = data[offset + 1]+ if marker == 0xDA: # start of scan: entropy-coded pixels follow+ return extra+ length = struct.unpack('>H', data[offset + 2:offset + 4])[0]+ if marker not in JPEG_PIXEL_MARKERS:+ extra.append(f'segment 0x{marker:02X}')+ offset += 2 + length+ return extra + ['no scan']++def file_hits(path, terms=()):data = path.read_bytes()if path.suffix.lower() == '.png':return png_metadata(data)+ if path.suffix.lower() == '.jpg':+ return jpeg_metadata(data)try:text = data.decode('utf-8')except UnicodeDecodeError:diff --git a/tests/test_video.py b/tests/test_video.pynew file mode 100644index 0000000..ce71cb8--- /dev/null+++ b/tests/test_video.py@@ -0,0 +1,160 @@+"""Video-model flipbooks and the Unity pipeline, on a synthetic clip (a disc that grows and fades on black).++No video model, Effekseer Core or Unity is needed: ffmpeg encodes the clip, and the Unity commands write into a folder+that only has to look like a Unity project.+"""+import json+import shutil+import subprocess+from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from conftest import PROJECT, cli_env++requires_ffmpeg = pytest.mark.skipif(not shutil.which('ffmpeg'), reason='ffmpeg is not on PATH')++[email protected](scope='module')+def clip(tmp_path_factory):+ """48 frames at 24 fps: black, a warm disc grows to the middle of the clip, then shrinks and fades to black."""+ folder = tmp_path_factory.mktemp('clip')+ yy, xx = np.mgrid[0:256, 0:256]+ r = np.hypot(xx - 128, yy - 128)+ for i in range(48):+ t = i / 47+ size = 90 * np.sin(np.pi * t) ** 0.7+ a = np.clip((size - r) / 8, 0, 1) * (1 - max(0, t - 0.7) / 0.3)+ img = np.dstack([a * 255, a * 180, a * 60]).astype(np.uint8)+ Image.fromarray(img).save(folder / f'f_{i:03d}.png')+ video = folder / 'disc.mp4'+ subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-framerate', '24', '-i', str(folder / 'f_%03d.png'),+ '-pix_fmt', 'yuv420p', '-c:v', 'libx264', '-crf', '12', str(video)], check=True)+ return video+++@requires_ffmpeg+def test_flipbook_makes_a_gutter_sheet_and_records_the_prompt(clip):+ from vfxkit import video+ info = video.flipbook(clip, 'T_TestDisc_4x4', cols=4, rows=4, cell=64, gutter=6, prompt='a warm disc grows and fades on black')+ sheet = np.asarray(Image.open(info['output']).convert('RGBA'))+ assert sheet.shape[:2] == (256, 256)+ alpha = sheet[..., 3]+ for k in range(4): # every cell border is fully transparent+ assert alpha[k * 64, :].max() == 0 and alpha[:, k * 64].max() == 0+ assert alpha.max() > 200 # and the cells hold the disc+ entry = next(p for p in json.loads((PROJECT / 'vfx/video_prompts.json').read_text())['prompts'] if p['id'] == 'T_TestDisc_4x4')+ assert entry['grid'] == [4, 4] and 'warm disc' in entry['prompt']+++@requires_ffmpeg+def test_grade_fades_the_tail_and_lint_accepts_recorded_sheets(clip):+ from vfxkit import video, lint+ video.flipbook(clip, 'T_TestDisc_4x4', cols=4, rows=4, cell=64)+ src = PROJECT / 'vfx/textures/processed/T_TestDisc_4x4.png'+ info = video.grade(src, 'T_TestDisc_4x4_graded', cols=4, rows=4, ramp='0:.4,.05,.03;.5:.95,.35,.06;1:1,.95,.75', tail_fade=4)+ graded = np.asarray(Image.open(info['output']).convert('RGBA'))+ assert graded.shape == np.asarray(Image.open(src).convert('RGBA')).shape+ assert graded[192:, 192:, 3].max() == 0 # the last cell is faded to nothing+ _, documented = lint.documented_textures()+ assert {'T_TestDisc_4x4', 'T_TestDisc_4x4_graded'} <= documented+++def test_first_frame_puts_the_element_on_black_and_writes_a_black_last_frame(tmp_path):+ from vfxkit import video+ src = tmp_path / 'element.png'+ img = np.zeros((300, 300, 3), np.uint8); img[100:200, 120:180] = (40, 150, 255)+ Image.fromarray(img).save(src)+ info = video.first_frame(src, 'test_first.png', width=512, height=512, fill=.4)+ first = np.asarray(Image.open(info['first_frame']).convert('RGB'))+ assert first.shape == (512, 512, 3) and first[0, 0].max() == 0 and first.max() > 100+ assert np.asarray(Image.open(info['last_frame'])).max() == 0+++def test_video_body_plays_every_cell_once_or_stands_as_a_column():+ from vfxkit.primitives import video_body+ burst = video_body('Body', 'T_Burst_8x8', grid=(8, 8), size=3, frame_length=2, delay=7)+ assert burst['life'] == 128 and burst['delay'] == 7 and burst['blend'] == 'Blend'+ assert burst['flipbook']['x'] == 8 and burst['flipbook']['loop'] == 'Once' and burst['billboard'] == 'Billboard'+ column = video_body('Column', 'T_Column_8x7', grid=(8, 7), size=4, column=.56, loop=True)+ assert column['billboard'] == 'YAxisFixed' and column['flipbook']['loop'] == 'Loop'+ assert column['scale_start'][:2] == pytest.approx([4 * .56, 4])+++def fake_unity(tmp_path):+ root = tmp_path / 'Game'+ (root / 'Assets').mkdir(parents=True); (root / 'ProjectSettings').mkdir()+ return root+++def test_unity_install_copies_the_package_and_draws_its_textures(tmp_path):+ from vfxkit import unity+ root = fake_unity(tmp_path)+ info = unity.install(root)+ package = root / 'Packages/com.vfx-skill.flipbook'+ assert json.loads((package / 'package.json').read_text())['name'] == 'com.vfx-skill.flipbook'+ assert (package / 'Runtime/ElementSkill.cs').is_file() and (package / 'Editor/CreateElementSkill.cs').is_file()+ textures = root / 'Assets/VfxSkill/Generated/Textures'+ for name in ('T_Flash', 'T_Smoke_2x2', 'T_Drop_2x2', 'T_FlowNoise', 'T_Decal', 'T_MaskCrown', 'T_MaskRibbon',+ 'T_MaskBoltStrip', 'T_MaskHitStar', 'T_MaskRing'):+ assert np.asarray(Image.open(textures / f'{name}.png'))[..., 3].max() > 0, name+ assert info['package_state'] == 'installed'+ (package / 'Runtime/Local.cs').write_text('// a local edit')+ assert unity.install(root)['package_state'].startswith('kept') and (package / 'Runtime/Local.cs').exists()+ unity.install(root, force=True)+ assert not (package / 'Runtime/Local.cs').exists()+ with pytest.raises(ValueError, match='not a Unity project'):+ unity.install(tmp_path)+++def test_unity_export_writes_the_grid_sidecar_and_stays_inside_the_project(tmp_path):+ from vfxkit import unity+ root = fake_unity(tmp_path)+ sheet = tmp_path / 'T_Column_4x2.png'+ a = np.zeros((200, 160), np.uint8)+ for c in range(4):+ for r in range(2):+ a[r * 100 + 10:r * 100 + 80, c * 40 + 8:c * 40 + 32] = 255 # 20 empty rows under each shape+ Image.fromarray(np.dstack([a, a, a, a])).save(sheet)+ info = unity.export(sheet, root, grid=(4, 2), name='Column')+ side = json.loads((root / 'Assets/VfxSkill/Flipbooks/Column.flipbook.json').read_text())+ assert side['grid'] == [4, 2] and side['cell'] == [40, 100] and info['bottom_inset'] == pytest.approx(.2)+ with pytest.raises(ValueError, match='grid'):+ unity.export(sheet, root, grid=(3, 2))+ with pytest.raises(ValueError, match='plain file name'):+ unity.export(sheet, root, grid=(4, 2), name='../../../../escaped')+++def test_unity_commands_need_no_workspace(tmp_path):+ root = fake_unity(tmp_path)+ run = subprocess.run([__import__('sys').executable, '-m', 'vfxkit', 'unity-install', str(root)], capture_output=True, text=True,+ cwd=tmp_path, env=cli_env(VFX_PROJECT=''), timeout=120)+ assert run.returncode == 0, run.stdout + run.stderr+ assert json.loads(run.stdout)['ok'] and not (tmp_path / 'vfx').exists()+++@requires_ffmpeg+def test_paths_names_and_bounds_from_review(clip):+ from vfxkit import video+ # a project path and a bare name land in the same file; names with dots keep their dots+ a = video.flipbook(clip, 'vfx/textures/processed/T_Path.v2', cols=2, rows=2, cell=64)+ assert Path(a['output']) == PROJECT / 'vfx/textures/processed/T_Path.v2.png'+ g = video.grade('T_Path.v2', 'T_Path.v2_graded', cols=2, rows=2, late_blur=5, tail_fade=0)+ alpha = np.asarray(Image.open(g['output']).convert('RGBA'))[..., 3]+ assert alpha[:2].max() == 0 and alpha[:, 62:66].max() == 0 # blur never reaches the cell borders+ entry = next(p for p in json.loads((PROJECT / 'vfx/video_prompts.json').read_text(encoding='utf-8'))['prompts'] if p['id'] == 'T_Path.v2_graded')+ assert entry['params']['source'] == 'vfx/textures/processed/T_Path.v2.png' # never an absolute local path+ with pytest.raises(ValueError, match='beyond the clip'):+ video.flipbook(clip, 'T_Bad', cols=2, rows=2, cell=64, end=500)+++def test_unity_force_keeps_meta_guids(tmp_path):+ from vfxkit import unity+ root = fake_unity(tmp_path)+ unity.install(root)+ meta = root / 'Packages/com.vfx-skill.flipbook/Runtime/ElementSkill.cs.meta'+ meta.write_text('fileFormatVersion: 2\nguid: 0123456789abcdef0123456789abcdef\n')+ assert 'GUIDs kept' in unity.install(root, force=True)['package_state']+ assert '0123456789abcdef' in meta.read_text()