# fusionKit
**Combine two things into a hybrid by rules: two towers of different races become a hybrid tower, two swords merge into a better sword, fire + water makes steam.** One data table describes the set; fusionKit works out every combination deterministically, lets players do it through one of six interaction styles (mouse, touch and gamepad), plays one of seven combine effects in both parents' colours, and routes every combination through one authority in multiplayer so every player sees the same result.
Version **1.0.4** (`Fusion.VERSION`).
**1.0.4:** world picking works while the panel is open. The panel holds the pointer as a menu, so the engine reported every press as the UI's and `pickAt` was never asked; a press over no widget now counts as on the map (checked with mouse and touch drags between towers in Arts TD). With a pad connected, the panel now tries to start focus on the first card instead of the close button (the engine may keep its own pad focus; the `radial` style needs no focus at all and is the pad route Arts TD uses).
**1.0.3:** a game ref given as a string (a tower's entity id, for example) now goes through the set's `resolve` before it is taken as an item id. Before, every string was returned as-is, so world-space games whose refs are entity ids saw "Nothing to combine" in every style. A string that names one of the set's items is still that item.
## Install
1. Install `fusionKit.package` from the ZeroMind panel or by guid: `zeromind_install guid=<fusionKit package guid>` (in the shell: `zero zeromind installAsset <guid>`). It brings **juiceKit** along (particles, light, camera shake, screen glow).
2. `local Fusion = require("fusionKit.api")`
3. Define a set, then call `Fusion.combine` (pure) or `Fusion.request` (multiplayer) or `Fusion.open` (the UI).
```lua
local Fusion = require("fusionKit.api")
Fusion.defineSet("towers", {
items = {
{ id = "ink", name = "Ink Tower", tags = { race = "ink" }, tier = 1,
stats = { dmg = 10, range = 4, rate = 1 }, traits = { "splash" },
look = { media = "ink" }, color = { 0.1, 0.1, 0.15 }, prefix = "Inky", suffix = "Blot" },
{ id = "water", name = "Watercolor Tower", tags = { race = "watercolor" }, tier = 1,
stats = { dmg = 6, range = 6, rate = 2 }, traits = { "slow" },
look = { media = "watercolor" }, color = { 0.3, 0.6, 1 }, prefix = "Washed", suffix = "Bloom" },
},
recipes = {
{ a = "ink", b = "water", result = { id = "sumi", name = "Sumi-e Sage", tier = 3,
stats = { dmg = 30, range = 8 }, traits = { "splash", "slow", "bleed" } },
discovery = "Ink bleeds into wet paper: the old masters' way." },
},
auto = { name = "{^a.tags.race} {^b.tags.race} Tower",
stats = { dmg = "avg", range = "max", rate = "sumScaled(0.6)" },
traits = "union", tierBonus = 1 },
rules = { allowSameTag = false, maxTier = 5,
cost = function(a, b) return (a.tier + b.tier) * 25 end },
})
local result, reason = Fusion.combine("towers", "ink", "water")
```
## The rules model
**Items** are tables: `id` (required, string), `name`, `tags` (a map such as `{ race = "ink" }`; a value may be a list), `tier` (default 1), `stats` (numbers), `traits` (strings), `look` (any table, passed through untouched), and optionally `color` ({r,g,b} 0-1 or 0-255, used by effects and the UI; `look.color` works too), `prefix` / `suffix` (name parts), `icon` (a short glyph for the UI).
What a pair turns into is decided in this order:
1. **Recipe**: an explicit hand-made pair (order does not matter) gives its `result` table, marked `special = true`, with `discovery` text. Recipe results are items too and combine further. A recipe may have its own `cost`.
2. **Merge equals**: two identical items give one of tier + 1. Name `"<base> II"`, `"III"`… (or `merge.name` template/function), stats by `merge.stats` per stat with `merge.defaultStat` (default `"scaled(1.5)"`). Turn it off with `merge = false`.
3. **Auto mix** for any other pair:
- name: `auto.name` as a function `fn(a, b)`, or a template string with `{a.name}`, `{b.suffix}`, `{a.tags.race}`, `{base}`, `{tier}`, `{roman}` (`{^...}` capitalises). Default: `a.prefix .. " " .. b.suffix` when either has name parts, else `"<A>-<B>"`.
- stats: per-stat rules in `auto.stats`, the rest by `auto.defaultStat` (default `"avg"`). Rules: `avg`, `max`, `min`, `sum`, `product`, `pickA`, `pickB`, `sumScaled(k)`, `avgScaled(k)`, `maxScaled(k)`, a number (constant) or `fn(va, vb, a, b, statName)`. `auto.round = n` rounds to n decimals.
- traits: `"union"` (default), `"intersection"`, `"pickA"`, `"pickB"`, `"none"` or `fn(a, b)`.
- tags: merged; a key where they differ becomes a list (`race = { "ink", "watercolor" }`).
- `tier = max(a.tier, b.tier) + auto.tierBonus` (default 1), `parents = { a.id, b.id }`, `look = { a.look, b.look }` so the game can draw it in both media, `colors = { colorA, colorB }`, `hybrid = true`.
- order: by default A+B == B+A (canonical order by id). `auto.order = "asGiven"` lets the first argument dominate (`pickA` is the dragged tower).
- `auto.post = fn(result, a, b)` edits the result last. `auto = false` allows recipes only.
**Conditions** (`rules`): `allowSameTag = false` refuses pairs sharing a tag value (`sameTagKeys = { "race" }` limits which keys count), `maxTier`, `locked = { {"a","b"}, ... }` or `fn(a,b)`, `allowHybridInputs = false`, `mergeEquals = false`, `canCombine = fn(a, b, ctx, result) -> ok, reason`, and `cost = number | fn(a, b, kind)`. A `ctx.gold` below the cost refuses with `"cost"`.
**Reasons** are short codes (`unknownSet`, `unknownItem`, `sameItem`, `sameTag`, `tierCap`, `locked`, `noRecipe`, `hybridInput`, `cost`, `denied`, or your own); `Fusion.reasonText(code)` gives a sentence for the UI.
**Results** carry `id, name, tags, tier, stats, traits, look, color, colors, parents, special, kind ("recipe"|"auto"|"merge"), cost, discovery`. Results are deterministic: the same set and pair give the same table on every peer, every time.
## API (`require("fusionKit.api")`)
```lua
Fusion.defineSet(setId, def) -- def = { items, recipes, auto, merge, rules, resolve }
Fusion.combine(setId, a, b, ctx?) -> result | nil, reason -- pure, deterministic
Fusion.preview(setId, a, b, ctx?) -> result | nil, reason -- same, for UI
Fusion.canCombine(setId, a, b, ctx?) -> bool, reason, cost
Fusion.request(setId, aRef, bRef, ctx) -> requestId -- multiplayer: asks the authority
Fusion.onCombined(fn(event)) -> unsubscribe -- event = { set, a, b, aRef, bRef, result, player, ctx, special, kind, cost, effect, position, newDiscovery, localCtx }
Fusion.onDenied(fn(deny)) -- deny = { set, a, b, reason, text, player } (on the requesting peer)
Fusion.setValidator(setId | "*", fn(request, result) -> ok, reason) -- authority-side: charge gold, check ownership
Fusion.discover(setId, player, resultId) -> isNew
Fusion.discovered(setId, player) -> { ids } ; Fusion.isDiscovered(setId, player, id)
Fusion.onDiscover(fn({ set, player, id, item, text }))
Fusion.exportDiscoveries(setId?) -> table ; Fusion.importDiscoveries(t, replace?) -- saving
Fusion.setStyle(id) / Fusion.getStyle() / Fusion.styles()
Fusion.setEffect(id) / Fusion.getEffect() / Fusion.effects()
Fusion.playEffect(id, pos, colorA, colorB, opts?) -- this peer only
Fusion.open(opts) / Fusion.close() / Fusion.isOpen()
Fusion.allPairs(setId, opts?) -> { { a, b, result, reason, special } } -- a codex; opts.includeRefused, includeEquals, includeDerived
Fusion.partners(setId, a, candidates?, ctx?) -> { { ref, result } } -- what a can combine with
Fusion.item(setId, id), Fusion.items(setId), Fusion.recipes(setId), Fusion.colorOf(item)
Fusion.VERSION
```
`a` / `b` are item ids, `{ item = id, ... }` tables, or any game ref (a tower entity) that the set's `resolve = fn(ref) -> itemId` turns into an id. The ref is passed back untouched as `event.aRef` / `event.bRef` so your game knows which towers to remove.
`player` is anything: a peer id, a player, an entity, or a string such as `"team:red"`. `ctx.team` also records the discovery for `"team:<team>"`.
## Interaction styles (`Fusion.setStyle(id)`)
| id | what the player does |
|---|---|
| `recipeList` | A recipe book: pick a recipe, ingredients you have are lit green, undiscovered results can show `???` (`opts.hideUndiscovered`), then Combine. |
| `autoMix` | Select any two cards, see the preview (A + B = result with stats and cost), press Combine. |
| `mergeEquals` | Tap two identical cards, or drag one onto its twin; cards with a twin show `x2`, non-matching ones dim. |
| `dragOnto` | Drag one card onto another (the line under the grid previews the result while you drag). With `opts.pickAt`, press on a tower in the world and release over another. |
| `forge` | A two-slot forge with a large preview of the result in the middle, then Forge. |
| `radial` | Pick a base; a ring of compatible partners appears around it. On a pad hold **LB**, aim the left stick, release to fuse. |
Every style works with mouse, touch and gamepad: the panel holds the pointer, so the d-pad / left stick moves focus between cards and buttons and **A (south)** presses, **B (east)** backs out.
```lua
Fusion.setStyle("forge")
Fusion.open({
set = "towers",
items = { "ink", "water", "ink" }, -- a list: the panel manages it (combined pairs are replaced by the result)
-- or items = function() return myTowerRefs end -- a provider: your game owns the list
pickAt = function(screenPos) return towerUnder(screenPos) end, -- world objects (optional)
positionOf = function(ref) return ref.position end, -- where the effect plays
gold = function() return myGold end,
player = myPlayerId, ctx = { team = "red" },
onConfirm = nil, -- optional: fn(aRef, bRef, preview, ctx) to do the request yourself
theme = "arcane", -- "arcane" | "parchment" | "neon" | "ink" | { base = "neon", accent = "#ff0" }
title = "Fuse Towers", hideUndiscovered = true, onClose = fn,
})
```
The screen is owned by a **FusionPanel** component (spawned for you when the scene has none) so its clicks have a home.
## Combine effects (`Fusion.setEffect(id)`)
Each effect takes the two parents' colours, plays juiceKit particles tinted with them, a coloured light, a small camera shake (play mode), a screen glow and its own synthesized sound. Special (recipe) results add confetti and a discovery chime.
| id | what it looks like |
|---|---|
| `swirl` | Two coloured streams spiral inward and fuse in a ring of light. |
| `flash` | A white burst with both colours as sparks and a screen flash. |
| `smelt` | Two molten drops pour from above into a glowing crucible of fire and smoke. |
| `inkSplash` | Dark ink blots splash out in both colours and drip into a puddle. |
| `sparkle` | A shower of glittering stars and confetti in both colours. |
| `shatterReform` | Both parts shatter into pixel shards, then reform in a rising column. |
| `paintMix` | Two paint streams arc in from the sides and swirl into the mixed colour. |
`Fusion.request` plays the effect on every peer at `ctx.position`; `ctx.effect = false` skips it, `ctx.effect = "flash"` overrides it for one request.
## Multiplayer
- Put the **FusionHost** component on one synced entity in your scene. Its owner is the authority: `Fusion.request` from any peer is sent there, validated (rules, `ctx.gold`, your `setValidator`), computed, and the result is broadcast. Every peer then runs `onCombined`, records the discovery and plays the same effect.
- Without a FusionHost, or offline, each peer is its own authority (single-player just works).
- FusionHost keeps the session's discoveries in a synced field, so a player who joins late sees what was found. Its `style` / `effect` fields set the starting style and effect from the scene.
- `onCombined` runs on every peer: do the world change (remove the two towers, place the hybrid) only where you own it, e.g. `if Fusion.isAuthority() then ... end`, or on the owner of the towers.
- Saving: `Fusion.exportDiscoveries()` is a plain table for runtime_data or a save kit; `importDiscoveries` loads it.
## Tests
`zero tests run fusionKit` (Luau: `tools.use("tests", "run", { suite = "fusionKit" })`): recipes vs auto mix, determinism and order, `asGiven`, naming templates, every stat rule, same tag, merge equals, tier cap, locked pairs, custom conditions, costs, hybrids of hybrids, `allPairs`, the discovery registry and save round trip, the local request flow and validators, and the style/effect switches.
## Gallery
The world's startup scene `scenes/gallery.scene` shows all six styles and all seven effects with an elements set (fire, water, earth, air and their recipes): press the buttons along the bottom, or let it cycle.
## Known limits
- The pad ring (`radial`) reads pad slot 1; other styles use the engine's menu navigation, which every pad drives.
- `Fusion.request` broadcasts (the engine's `multiplayer.send` has no direct send); requests are small, but a game sending dozens per second should batch.
- Effects are cosmetic and per peer; a peer that joins mid-effect does not see it.
- World picking (`pickAt`) uses the primary pointer: on touch, one finger.
- The juiceKit `palette` option used to tint effects is in juiceKit 1.2.11 (sent upstream as a pull request, and shipped with this package); with an older juiceKit the effects play in juiceKit's own colours.