diff --git a/skills/create-2d-physics/SECURITY.md b/skills/create-2d-physics/SECURITY.md new file mode 100644 index 0000000..a9f0529 --- /dev/null +++ b/skills/create-2d-physics/SECURITY.md @@ -0,0 +1,16 @@ +# Security notes: create-2d-physics + +This skill has the agent run C# inside the user's open Unity Editor through `unity command eval`. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. Where a named `unity command` covers a step, the skill uses that instead of `eval`. | + +## Mitigations + +- **Only the user's own Editor.** `unity command eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. +- **Capability gate.** `eval` is only available when the project's Pipeline package provides it. +- **No remote code.** The agent runs C# it writes from this skill's own recipes. Nothing downloaded from outside is executed. +- **Named commands first.** When a dedicated `unity command` covers a step, the skill uses it instead of `eval`. diff --git a/skills/create-2d-physics/SKILL.md b/skills/create-2d-physics/SKILL.md new file mode 100644 index 0000000..2ad7e0f --- /dev/null +++ b/skills/create-2d-physics/SKILL.md @@ -0,0 +1,78 @@ +--- +name: create-2d-physics +description: "Creates and fixes Unity 2D physics across both systems: 2D Physics Core and the legacy Rigidbody 2D system. Make sure to use this skill for any 2D physics question, even if the user doesn't mention either system by name. Not for 3D physics." +allowed-tools: WebFetch, WebSearch +metadata: + version: 0.3.0 + support: "https://unity.com/support-services" +--- + +# Create and fix Unity 2D physics + +Do not weigh 3D physics options. If evidence shows the user means 3D, say so and stop. + +Prefer `WebFetch` over `WebSearch` — faster and lands on the exact reference. Only fetch what you need. Replace `` with the following before fetching: +- **docs.unity.com**: The Unity version, e.g. `6000.7`. Pages are markdown — URLs end in `.md`. +- **Package on docs.unity3d.com**: The package version, e.g. `@1.1`. Check `Packages/manifest.json` if unsure. + +## Important + +- Use the unity cli (`unity command --format json`) and the `unity-cli` and `unity-pipeline` skills for each step. +- Don't use `using` directives or unqualified types in the `snippet` for `eval`. The compiler reads using `UnityEngine` and a bare AssetDatabase, Volume, or Object causes errors (CS0246 / CS0103 / CS0104). `return` what you want to read; it arrives at `data.result.result`. +- Create a restore point you can roll back to if your changes fail. +- Do only what's asked. Don't change unrelated assets or files. +- Avoid long explanations. +- Never leave verification code in the user's script; never build logging or settle-detection they didn't ask for. See [Final step](#final-step). +- Never reflect over types to discover an API — fetch the member page instead. The system probe is the one exception. + +## Step 0: Which physics system + +Unity has two 2D physics systems. They share no code and never interact. Identify which one before writing any physics code — an answer from the wrong system compiles, runs, and does nothing. + +Check the request, scene and existing scripts against the table below. Components are the reliable signal — check scene and existing scripts first. Check the user's request wording too: "add a collider" is component language, "spawn a thousand" is script language. + +| Signal | System | +| --- | --- | +| Physics Pose, Area, Constraint or Simulation components | Core components, 6000.7+ with the package | +| Rigidbody 2D, Collider 2D, Joint 2D, Effector 2D | Legacy | +| `Unity.U2D.Physics` or `UnityEngine.LowLevelPhysics2D` types in script | Core in script | +| `Rigidbody2D`, `Collider2D`, `Physics2D` types | Legacy | +| Both present | Separate simulations. Say so, treat separately | +| No signal | Stop and ask, offering the three routes above | + +Key: +- Legacy = Rigidbody 2D and Collider 2D components. +- Core components = Physics Pose and Physics Area, requiring `com.unity.2d.physics` and Unity 6000.7+. +- Core in script = `Unity.U2D.Physics` API, no package needed. + +If still unsure which systems are installed, run the probe. If the route is still unknown, stop and ask — offer all three routes and never choose for the user: + +Probe: +``` +unity command eval --code 'var r = ""; foreach (var n in new[] { "UnityEngine.Rigidbody2D", "Unity.U2D.Physics.PhysicsWorld", "UnityEngine.LowLevelPhysics2D.PhysicsWorld", "Unity.U2D.Physics.PhysicsPose" }) { var f = false; foreach (var a in System.AppDomain.CurrentDomain.GetAssemblies()) if (a.GetType(n) != null) f = true; r += f + ","; } return r;' +``` +The Probe returns: legacy present, Core as `Unity.U2D.Physics`, Core as `UnityEngine.LowLevelPhysics2D`, Core components present. Core exists if either Core value is true; the true one gives the namespace. `false` rules that route out. + +## System reference + +Once you know the route, read the matching reference before acting: +- [2D Physics Core reference](references/2d-physics-core.md) - components, configuring them, creating bodies in script, ownership, and the full Core topic map. +- [Legacy 2D physics reference](references/legacy-2d-physics.md) - the legacy manual topic map. + +## Worked examples + +Prefer in order: the C# example on the type or member page you are using; existing project scripts (match their style); the sample project at `https://github.com/Unity-Technologies/PhysicsExamples2D`. Check all three before inventing a pattern. + +## Final step + +Do the following checks: + +1. Check the project has zero console errors. Use `console_status` for counts. +2. Stop there unless the user asked you to prove it works or you suspect a specific fault. +3. If you do enter Play mode, do it once only to chase a fault you already suspect. Read the world through `eval` rather than adding logging. Take no screenshots as they take too much time. + +If a check fails, go back and reread the docs pages in the matching reference to find out what you missed. + +## Final report + +Short checklist: what you changed and why, which physics system you used, anything left for the user to decide or do. diff --git a/skills/create-2d-physics/references/2d-physics-core.md b/skills/create-2d-physics/references/2d-physics-core.md new file mode 100644 index 0000000..62390ad --- /dev/null +++ b/skills/create-2d-physics/references/2d-physics-core.md @@ -0,0 +1,142 @@ +# 2D Physics Core + +- [Step 0](#step-0) — when to read before acting +- [Configuring a component](#configuring-a-component) +- [Creating in script](#creating-in-script) +- [Ownership](#ownership) +- [What you are likely to get wrong](#what-you-are-likely-to-get-wrong) +- [Manual: 2D Physics Core](#manual-2d-physics-core) +- [Scripting reference](#scripting-reference) +- [Package documentation](#package-documentation) + +The engine API is a built-in module — no package needed. The Physics Pose, Area and Constraint **components** come from `com.unity.2d.physics`, requiring 6000.7+. Check `Packages/manifest.json` before suggesting a component; if absent, offer to add it using the `unity-package-management` skill. + +A component is not the physics object. It owns a body, shape or joint — operate on that owned object. Read/write it, apply forces, query it, handle contacts (from a worker thread if needed). See [Physics Pose and Physics Area components](https://docs.unity.com/en-us/engine//manual/unity2d/2d-physics-api/create-objects/pose-and-area.md). + +The components use only the public API, by design, so nothing is component-only — a plain MonoBehaviour driving the engine API always works. Never say a case is unsupported. For many shapes or nested areas, Physics Area Composite already exists. + +Within Core: components for scene-authored objects, script for bulk runtime creation. The modules `com.unity.modules.physics2d` and `com.unity.modules.physicscore2d` are on by default; only matter if stripped. Version sets the namespace, not which system exists — the [Unity 6.5 upgrade guide](https://docs.unity3d.com//Documentation/Manual/UpgradeGuideUnity65.html) covers the rename. Only the components require 6000.7. + +## Step 0 + +Before you go forward with a workflow or diagnosis: + +1. Open and read the documentation page(s) from the [Manual](#manual-2d-physics-core) or [Scripting reference](#scripting-reference) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +Always use versioned URLs — unversioned links resolve to the current release, not the project's version. + +Core script type pages are an exception: the API only changed namespace, so the version only decides whether to write `Unity.U2D.Physics` or `UnityEngine.LowLevelPhysics2D`. Use the project's version when known, otherwise 6000.7. + +Most tasks (apply force or impulse, move a body, read velocity, add a component) need no reading — just do it. + +Exceptions that always require reading first: +- **Setting component values**: fetch the type page per [Configuring a component](#configuring-a-component). +- **Creating a body in script**: read the two pages in [Creating in script](#creating-in-script). +- **Any member you cannot name with confidence**: read one page. Never read more than two pages for a single task. + +## Configuring a component + +Follow these rules for configuring a component: + +- Never write serialized fields — the serialized names differ from public names. Drive everything through public properties and methods via `eval`. +- Definition and geometry are separate: a pose's body settings live in its definition; an area's shape is its geometry. Configure them independently. A change to either needs its apply call before it takes effect — the type page states which one. +- Before configuring any component, fetch its API page and use only members it lists. Read the installed version from `Packages/manifest.json` (major.minor, e.g. `1.1`), then fetch: +`https://docs.unity3d.com/Packages/com.unity.2d.physics@/api/Unity.U2D.Physics..html` + +One page per type covers all members. If a member is missing, treat it as undocumented, not absent. + +## Creating in script + +Before creating a Core body in script, read these two pages and follow their examples. Set `type` on the definition explicitly. + +- `https://docs.unity.com/en-us/engine//script-reference/unity/u2d/physics/physicsbodydefinition.md` +- `https://docs.unity.com/en-us/engine//script-reference/unity/u2d/physics/physicsbody.md` + +Use the project's version, or 6000.7 if unknown. On 6000.3–6000.4 the namespace is `UnityEngine.LowLevelPhysics2D`, e.g. `.../script-reference/unityengine/lowlevelphysics2d/physicsbody.md`. + +Script types — joints, geometry, queries, and everything else — are engine types in the main scripting reference only. Never look for them in the `com.unity.2d.physics` package docs. + +## Ownership + +Core only. Applies to worlds, bodies, shapes, chains and joints. + +Owner-gated calls state it on their page, as [PhysicsBody.Destroy](https://docs.unity.com/en-us/engine//script-reference/unity/u2d/physics/physicsbody/destroy.md) does. The owner key argument defaults to zero (matches objects with no owner); `SetOwner` is different — there, zero creates a new key. A refusal logs a warning rather than throwing. + +Create a key and own what you create. Queries return objects you did not create — deleting one you merely found is the mistake ownership prevents. Script-created objects are yours to destroy; component-created ones need the component removed; the default world is engine-owned and cannot be removed. + +## What you are likely to get wrong + +Core's API is young and was renamed — your recall is unreliable. Legacy's page locations were reorganised — your recall of URLs is stale. Nothing carries over between systems unverified. + +| Your likely assumption | Actually | +| --- | --- | +| Legacy manual pages are flat, like `class-Rigidbody2D.html` | Reorganised under family folders: `2d-physics/rigidbody-2d/`, `2d-physics/collider-2d/` | +| A Core component holds the state, as Rigidbody 2D does | It owns a body, shape or joint. Operate on the owned object | +| The namespace is `UnityEngine.LowLevelPhysics2D` | 6000.4 and earlier. From 6000.5 it is `Unity.U2D.Physics` | +| Box2D v2 naming and semantics apply to Core | It is Box2D v3. Most older forum answers describe v2 | +| Angles are in radians, as Box2D uses | Read the property page. Hinge angles are documented in degrees | +| Core collision layers are a 32-bit mask | 64 layers in Core, 32 in legacy | +| Some behaviour is component-only | None is | +| A user's own component needs wiring to work with Unity's | None. All interaction is engine-side | +| Any handle can be destroyed | Only what you own. See [Ownership](#ownership) | +| You must create a world first | `PhysicsWorld.defaultWorld` exists in an empty scene | +| Debug visuals need gizmos or `Debug.DrawLine` | Core has a physics renderer with automatic and explicit draw calls. Never hand-roll it | +| A method exists because the other system has one like it | Confirm on its own page | +| `bodyType` and `RigidbodyType2D` set body type | Obsolete. Use `type` with `PhysicsBody.BodyType` | +| A newly created body has a known default type | Do not assume — set `.type` explicitly. falls/thrown/bounces → Dynamic; ground/wall/anchor → Static | +| "add a circle/capsule/polygon/segment area" means the dedicated component | Could be that or Primitive with `shapeType` — same shape, two routes. Prefer dedicated when fixed at authoring time; Primitive only if it must switch at runtime. Chain Segment has no dedicated component | + +## Manual: 2D Physics Core + +Base: `https://docs.unity.com/en-us/engine//manual/unity2d/2d-physics-api/`. Pages are `.md`. The landing page is `https://docs.unity.com/en-us/engine//manual/unity2d/2d-physics-api.md` — contents. + +Paths below are relative to the base: +- `introduction.md` — what it is, component-to-object mapping +- `get-started.md` — first scene with components +- `create-objects.md` — Physics Pose and Physics Area components. Children in `create-objects/`: `pose-and-area.md`, `physics-object.md`, `add-sprite.md`, `debug-drawing.md` (Scene view editing, rendering modes) +- `connect-objects.md` — joints. Children in `connect-objects/`: `joints.md`, `create-constraint.md`, `constraint-events.md` +- `properties.md` — definitions, pinned properties, custom data, global settings. Children in `properties/`: `definitions.md`, `pin-properties.md`, `custom-data.md`, `class-physics-core-settings2d.md`, `preferences-window-reference.md` +- `interactions.md` — collisions, contacts, triggers, filtering (queries are `PhysicsWorld` cast/overlap methods in the scripting reference). Children in `interactions/`: `introduction.md`, `collisions-enable.md`, `collision-handle.md` + +Read in full before acting (outside this skill's scope): `worlds.md`, `3d-planes.md`, `multithreading.md`. + +Component reference pages follow a pattern — build them: +- Body: `create-objects/reference-body.md` +- Area: `create-objects/reference-area-.md` (capsule, circle, composite, contour, path, polygon, primitive, segment, sprite) +- Joint: `connect-objects/reference-joint-.md` (distance, fixed, hinge, relative, slider, wheel) +- Constraint: `connect-objects/reference-constraint-ignore.md` +- Simulation: `worlds/reference-simulation-component.md` +- Assets: `worlds/reference-world.md` (Physics Simulation Definition), `worlds/reference-simulation-asset.md` (Physics Simulation World) + +This manual covers components. For joint structs, definitions, geometry, queries, math, events and destruction — use the scripting reference. + +## Scripting reference + +Build the URL — do not search for member pages. Names are lowercase. + +Base: `https://docs.unity.com/en-us/engine//script-reference/` + +| You want | Pattern | Example | +| --- | --- | --- | +| Legacy type in `UnityEngine` | `unityengine/.md` | `unityengine/rigidbody2d.md` | +| Core namespace (lists types) | `unity/u2d/physics.md` | | +| Core type | `unity/u2d/physics/.md` | `unity/u2d/physics/physicsbody.md` | +| Core type, 6000.3–6000.4 | `unityengine/lowlevelphysics2d/.md` | `unityengine/lowlevelphysics2d/physicsbody.md` | +| Method, property, field or nested type | `/.md` | `unity/u2d/physics/physicsbody/createshape.md`, `unity/u2d/physics/physicsbody/linearvelocity.md` | +| A joint in script | Start at `unity/u2d/physics/physicsjoint.md`, then `physicsjoint` and `physicsjointdefinition` | `unity/u2d/physics/physicshingejoint.md` | + +A type page lists members; a method page lists every overload. Units, ranges and defaults are on property pages. A 404 means the name is wrong, or that version's docs aren't published — fetch the type page and read its members, or try an adjacent version. + +For the Core renderer: start at `unity/u2d/physics/physicsworld/renderingmode.md`, `unity/u2d/physics/physicscoresettings2d.md`, and `physicsworld` draw methods: `drawgeometry`, `drawshapeproxy`, `drawqueryresult`, `drawlinestrip`, `drawshapes`. + +## Package documentation + +Package API pages are live only — not local files. Fetch using the version from `Packages/manifest.json`: +`https://docs.unity3d.com/Packages/com.unity.2d.physics@/api/Unity.U2D.Physics..html` + +Package manual pages are local: `/Library/PackageCache/com.unity.2d.physics@*/Documentation~/`. Read only `.md` files in that subfolder. + +The `api/index.html` listing fetches as nothing — go straight to a named type page. diff --git a/skills/create-2d-physics/references/legacy-2d-physics.md b/skills/create-2d-physics/references/legacy-2d-physics.md new file mode 100644 index 0000000..b35a3b7 --- /dev/null +++ b/skills/create-2d-physics/references/legacy-2d-physics.md @@ -0,0 +1,28 @@ +# Legacy 2D physics + +Relative paths in this file resolve to the skill directory — the folder that holds the `SKILL.md` for this skill. + +## Step 0 + +Before you go forward with a workflow or diagnosis: + +1. Open and read the [documentation page(s)](#manual-legacy-2d-physics) that cover the specific subject related to what you intend to do or fix and check if you've missed anything. +2. Name the file(s) you read in your response. + +This is because your training knowledge about Unity might be out of date, incorrect, or for the wrong Unity version. + +## Manual: legacy 2D physics + +Base: `https://docs.unity.com/en-us/engine//manual/unity2d/`. Pages are `.md`. + +`2d-physics.md` is the contents page. Landing pages, relative to the base: `2d-physics/rigidbody-2d.md`, `2d-physics/collider-2d.md`, `2d-physics/effectors-2d.md`, `2d-physics/2d-joints.md`, `2d-physics/physics-2d-profiler.md`, plus flat `2d-physics/constant-force-2d-reference.md` and `2d-physics/physics-material-2d-reference.md`. + +Each landing page has a folder of the same name listing its children — follow those rather than guessing leaf names. + +## Scripting reference + +Legacy types live in the main scripting reference as `unityengine/.md`, e.g. `https://docs.unity.com/en-us/engine//script-reference/unityengine/rigidbody2d.md`. See the [Scripting reference](2d-physics-core.md#scripting-reference) table in the Core reference for the full URL pattern, including how it differs from Core types. + +## What you are likely to get wrong + +Legacy's page locations were reorganised — your recall of URLs is stale. Legacy manual pages are not flat like `class-Rigidbody2D.html`; they're reorganised under family folders: `2d-physics/rigidbody-2d/`, `2d-physics/collider-2d/`. Core collision layers use a 64-bit mask; legacy uses 32. diff --git a/skills/create-tile-palette-or-rule-tiles/SKILL.md b/skills/create-tile-palette-or-rule-tiles/SKILL.md new file mode 100644 index 0000000..e3210e0 --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/SKILL.md @@ -0,0 +1,12 @@ +--- +name: create-tile-palette-or-rule-tiles +description: Create a 2D tile palette from sprites or textures, or change which tile Unity paints based on surrounding tiles. Make sure to use this skill when the user wants to create tile palettes or self-connecting tiles, even if they don't explicitly ask about tile palettes or tile assets. +--- + +# Create a tile palette + +Pick the matching reference doc based on what the user wants, then follow it: + +- **Tile Palette** — [references/palette-create.md](references/palette-create.md) — when the user wants to organize tiles for 2D level design or create a new rectangular, hexagonal, isometric, or isometric Z as Y grid layout. +- **Blank/empty RuleTile** (no sprites provided) — [references/ruletile-createempty.md](references/ruletile-createempty.md) — when the user wants a blank RuleTile (rectangular grid), HexagonalRuleTile, or IsometricRuleTile for custom rule configuration and has not provided or referenced any sprites. +- **RuleTile built from existing sprites** (sprites, terrain art, edge tiles provided) — [references/ruletile-createfromsegment.md](references/ruletile-createfromsegment.md) — when the user wants tiles that autotile as they paint, or a RuleTile built from existing terrain or edge sprites so tiles connect correctly. diff --git a/skills/create-tile-palette-or-rule-tiles/references/hexagonalruletile.md b/skills/create-tile-palette-or-rule-tiles/references/hexagonalruletile.md new file mode 100644 index 0000000..7cc492b --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/references/hexagonalruletile.md @@ -0,0 +1,71 @@ +# Skill: Advanced Hexagonal RuleTile Creation + +This skill provides a template and logic for creating complex `HexagonalRuleTiles`. Use this to programmatically generate or manually configure new Hexagonal RuleTiles for pointy-top hex grids. + +## Hexagonal Tile Rule Pattern (Pointy Top) + +A Hexagonal RuleTile uses 6 possible neighbor directions. These neighbors are defined as follows: + +### Neighbor Directions and Coordinate Mappings + +For a tile at `(x, y, 0)`, the 6 neighbors are at: +1. **North-West (NW)**: `(-1, 1, 0)` +2. **North (N)**: `(0, 1, 0)` +3. **East (E)**: `(1, 0, 0)` +4. **South-West (SW)**: `(-1, -1, 0)` +5. **South (S)**: `(0, -1, 0)` +6. **West (W)**: `(-1, 0, 0)` + +### Legend: +- `.`: **This** (Type 1) +- `X`: **Any** (Type 0) +- **Fixed**: Rule is applied exactly as defined. +- **MirrorX**: Rule is applied as defined and mirrored across the X-axis. + +## Full Tiling Rules Template + +The hexagonal tile set uses **MirrorX** and **Fixed** transforms. **Rotated** is not used in this specific set. + +| Rule ID | Neighbor Configurations (Pos: Type) | Transform | Description | +|:--------|:------------------------------------| :--- | :--- | +| 0 | NW:., N:., E:., SW:., S:., W:. | Fixed | Full 6-neighbor surrounded | +| 1 | NW:., W:., SW:., S:., E:. | MirrorX | 5-neighbor surrounded | +| 2 | NW:., W:., E:., SW:., N:. | MirrorX | 5-neighbor surrounded variant | +| 3 | N:., NW:., W:., SW:., S:. | MirrorX | 5-neighbor surrounded variant | +| 4 | W:., SW:., S:., E:. | Fixed | 4-neighbor connectivity | +| 5 | W:., NW:., N:., E:. | Fixed | 4-neighbor connectivity | +| 6 | NW:., W:., SW:., S:. | MirrorX | 4-neighbor corner/edge | +| 7 | NW:., W:., SW:., N:. | MirrorX | 4-neighbor corner/edge | +| 8 | NW:., SW:., W:., E:. | MirrorX | 4-neighbor bridge | +| 9 | NW:., W:., E:., S:. | MirrorX | 4-neighbor connectivity | +| 10 | NW:., SW:., S:., E:. | MirrorX | 4-neighbor connectivity | +| 11 | NW:., N:., S:., SW:. | Fixed | 4-neighbor vertical-ish | +| 12 | N:., NW:., W:., S:. | Fixed | 4-neighbor horizontal-ish | +| 13 | W:., SW:., S:. | MirrorX | 3-neighbor corner | +| 14 | NW:., W:., SW:. | MirrorX | 3-neighbor flat edge | +| 15 | W:., NW:., N:. | MirrorX | 3-neighbor corner | +| 16 | NW:., N:., S:. | MirrorX | 3-neighbor T-junction | +| 17 | W:., SW:., E:. | MirrorX | 3-neighbor T-junction | +| 18 | W:., N:., SW:. | MirrorX | 3-neighbor wide corner | +| 19 | E:., NW:., SW:. | MirrorX | 3-neighbor wide corner | +| 20 | NW:., W:., E:. | MirrorX | 3-neighbor wide corner | +| 21 | SW:., S:., NW:. | MirrorX | 3-neighbor variant | +| 22 | W:., NW:., S:. | MirrorX | 3-neighbor variant | +| 23 | NW:., W:. | Fixed | 2-neighbor edge | +| 24 | W:., SW:. | Fixed | 2-neighbor edge | +| 25 | SW:., S:. | Fixed | 2-neighbor edge | +| 26 | E:., S:. | Fixed | 2-neighbor edge | +| 27 | N:., E:. | Fixed | 2-neighbor edge | +| 28 | NW:., N:. | Fixed | 2-neighbor edge | +| 29 | W:., E:. | MirrorX | 2-neighbor opposite bridge | +| 30 | N:., SW:. | MirrorX | 2-neighbor long bridge | +| 31 | W:., S:. | MirrorX | 2-neighbor acute corner | +| 32 | E:., NW:. | MirrorX | 2-neighbor long bridge variant | +| 33 | N:., S:. | MirrorX | 2-neighbor vertical bridge | +| 34 | N:. | MirrorX | Single neighbor North | +| 35 | E:. | MirrorX | Single neighbor East | +| 36 | S:. | MirrorX | Single neighbor South | +| 37 | all 6 surrounding positions: X | Fixed | Default / No-neighbor | + +#### Usage +When applying this skill to a new texture set, first ensure the texture is sliced into sprites matching these 38 logical configurations. Then, run a script using the description to map the sprites to each rule. Ensure that HexagonalRuleTile has all 38 TilingRules listed in the template. \ No newline at end of file diff --git a/skills/create-tile-palette-or-rule-tiles/references/palette-create.md b/skills/create-tile-palette-or-rule-tiles/references/palette-create.md new file mode 100644 index 0000000..d89e0bf --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/references/palette-create.md @@ -0,0 +1,38 @@ +# Tilemap Palette Creation + +Requires package: `com.unity.2d.tilemap` >=1.0.0 + +## Workflow + +### Step 1: Parameter Gathering +WAIT for the user to specify the following parameters if not already provided: +- **Palette Name**: The name of the asset. +- **Grid Type**: Rectangular, Hexagonal, or Isometric. +- **Cell Size**: Optional (defaults based on Grid Type). +- **Sort Axis**: Required for Isometric palettes. + +### Step 2: Asset Creation +Utilise `UnityEditor.Tilemaps.GridPaletteUtility.CreateNewPalette` to create the Tile Palette asset. + +## Branching Logic (Grid Types) + +### Path A: Rectangular +- Use **Automatic** cell sizing. Use cell size: `(1, 1, 0)` as a default. + +### Path B: Hexagonal +- Use cell size: `(0.8659766, 1, 1)`. + +### Path C: Isometric +- Use cell size: `(1, 0.5, 1)`. +- Use a **Custom Sort Axis** with value `(0, 0, 1)`. + +### Path D: Isometric Z As Y +- Use cell size: `(1, 0.5, 1)`. +- Use a **Custom Sort Axis** with value `(0, 0, 1)`. + +## Post-Creation +Ensure that there is a `GridPalette` as a sub-asset of the Tile Palette asset. + +## References + +Code Template: "../scripts/CreatePaletteTemplate.cs" \ No newline at end of file diff --git a/skills/create-tile-palette-or-rule-tiles/references/ruletile-createempty.md b/skills/create-tile-palette-or-rule-tiles/references/ruletile-createempty.md new file mode 100644 index 0000000..7d9ad39 --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/references/ruletile-createempty.md @@ -0,0 +1,35 @@ +# Tilemap RuleTile Create Empty + +Use ONLY when the user wants a blank RuleTile, HexagonalRuleTile, or IsometricRuleTile for custom rule configuration AND has not provided or referenced any sprites. If the user mentions existing sprites, terrain art, edge tiles, or a tiles folder, use [ruletile-createfromsegment.md](ruletile-createfromsegment.md) instead, never this. + +Requires packages: `com.unity.2d.tilemap` >=1.0.0, `com.unity.2d.tilemap.extras` >=4.0.0 + +## Workflow + +### Step 1: Verify No Sprite Inputs +**WAIT** - Confirm that no Sprites or Spritesheets were specified by the user. This skill is only for empty RuleTiles. If there are Sprites or Spritesheets specified by the user, use [ruletile-createfromsegment.md](ruletile-createfromsegment.md) instead. + +### Step 2: Determine RuleTile Type +Identify which RuleTile type to create based on user request: +- **RuleTile**: Standard rectangular grid +- **HexagonalRuleTile**: Hexagonal grid layout +- **IsometricRuleTile**: Isometric grid layout + +### Step 3: Create Empty TilingRules +For each TilingRule, ensure the Sprite array has one `null` entry. + +## Branching Logic (RuleTile Types) + +### Path A: RuleTile +- Use template from [ruletile.md](ruletile.md). + +### Path B: HexagonalRuleTile +- Use template from [hexagonalruletile.md](hexagonalruletile.md). + +### Path C: IsometricRuleTile +- Create empty rules with appropriate neighbor positions for isometric layout. + +## Important Notes + +- **TilingRuleOutput.Neighbor.This**: Use to identify RuleTiles that are the same (matching neighbors). +- **TilingRuleOutput.Neighbor.NotThis**: Do NOT use unless explicitly specified by the user to ignore a Tile at a certain position. \ No newline at end of file diff --git a/skills/create-tile-palette-or-rule-tiles/references/ruletile-createfromsegment.md b/skills/create-tile-palette-or-rule-tiles/references/ruletile-createfromsegment.md new file mode 100644 index 0000000..8dba0b8 --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/references/ruletile-createfromsegment.md @@ -0,0 +1,212 @@ +# Tilemap RuleTile Create From Segment + +Use when the user wants tiles that auto-tile (autotile) as they paint, wants a RuleTile built from existing terrain or edge sprites, or asks to make sprites "tile correctly" or "connect properly". Also converts sprite-segment-3x3grid output patterns into Unity RuleTile TilingRules: 3x3 grid text patterns (X, ., *) become TilingRule neighbor configurations, mapping '.' to 'This' rules and 'X' to 'DontCare', sorted by specificity (more 'This' rules first). Sprites must be provided as input. + +Requires packages: `com.unity.2d.tilemap` >=1.0.0, `com.unity.2d.tilemap.extras` >=4.0.0 + +## Purpose + +This skill creates Unity RuleTile TilingRules by first analyzing sprites using the `sprite-segment-3x3grid` skill, then converting the resulting text patterns into neighbor rule configurations. The user must specify Sprites or a Spritesheet input. + +## Workflow + +``` +Step 1: sprite-segment-3x3grid Step 2: Create TilingRules ++--------------------------+ +--------------------------+ +| Analyze each Sprite | | Parse text patterns | +| using color matching | -> | Map to neighbor rules | +| Output: text pattern | | Sort by specificity | ++--------------------------+ +--------------------------+ +``` + +**CRITICAL**: Always run the `sprite-segment-3x3grid` skill first on each Sprite to generate the text pattern. + +## Step 1: Apply sprite-segment-3x3grid (Required) + +For each Sprite in your texture, analyze it with `sprite-segment-3x3grid`: + +```csharp +string pattern = SpriteSegment3x3Grid.AnalyzeSpriteGrid(sprite, matchThreshold: 0.75f); +``` + +### Pattern Output Format + +Single-line text pattern: `[TopRow] / [MiddleRow] / [BottomRow]` + +Each row contains 3 characters separated by spaces: +- `X` - Cell does NOT meet match threshold +- `.` - Cell MEETS match threshold (matches center color) +- `*` - Center cell (the tile itself) + +Example: `X X X / X * X / . . .` + +## Step 2: Create TilingRules from Patterns + +### Symbol to Rule Mapping + +| Symbol | RuleTile Neighbor | Value | Behavior | +|--------|-------------------|-------|-----------------------------------------------| +| `.` | `This` | 1 | Neighbor must be an instance of this RuleTile | +| `X` | `DontCare` | 0 | Position not added to neighbors list | +| `*` | (center) | N/A | Ignored - represents the tile itself | + +**Note**: "DontCare" is not an explicit constant. A position is "don't care" when it is simply not included in the `m_Neighbors` and `m_NeighborPositions` lists. + +### Neighbor Position Mapping + +``` +Grid Layout: Unity Vector3Int positions: +[0] [1] [2] (Top) (-1,1,0) (0,1,0) (1,1,0) +[3] [*] [5] (Middle) (-1,0,0) --- (1,0,0) +[6] [7] [8] (Bottom) (-1,-1,0) (0,-1,0) (1,-1,0) +``` + +| Index | Position | Vector3Int | +|-------|--------------|----------------| +| 0 | Top-Left | `(-1, 1, 0)` | +| 1 | Top | `(0, 1, 0)` | +| 2 | Top-Right | `(1, 1, 0)` | +| 3 | Left | `(-1, 0, 0)` | +| 4 | Center | (skipped) | +| 5 | Right | `(1, 0, 0)` | +| 6 | Bottom-Left | `(-1, -1, 0)` | +| 7 | Bottom | `(0, -1, 0)` | +| 8 | Bottom-Right | `(1, -1, 0)` | + +## Pattern Filtering + +By default, detected patterns that do not match any entry in the Common Tile Patterns table are discarded. Only the 47 known patterns are kept. This prevents unexpected or noisy rules from appearing in the final RuleTile. + +If the user explicitly asks to keep non-standard patterns, set `filterToKnownPatterns: false` to bypass this filtering. + +## Deduplication + +Duplicate TilingRules with identical neighbor configurations are automatically removed. When multiple sprites produce the same pattern, only the first sprite encountered is kept. + +## Rule Sorting + +Rules are sorted by specificity (number of `This` rules) in descending order. More specific rules are evaluated first. + +| This Count | Example Pattern | Priority | +|------------|---------------------------------|----------| +| 8 | `. . . / . * . / . . .` | First | +| 5 | `. . . / . * . / X X X` | ... | +| 3 | `X X X / X * X / . . .` | ... | +| 0 | `X X X / X * X / X X X` | Last | + +## Sprite Assignment + +Each TilingRule is assigned at most 1 Sprite: +- Set `m_Output` to `TilingRuleOutput.OutputSprite.Single` +- Assign the sprite to `m_Sprites[0]` + +The RuleTile's `m_DefaultSprite` is set to the sprite from the bottom-most (least specific) rule. Since rules are sorted by specificity descending, this is the last rule in the list. This sprite is used when no TilingRule matches. + +## Algorithm Summary + +1. **For each Sprite**: Run `sprite-segment-3x3grid` and store the pattern +2. **Filter**: Discard patterns not in Common Tile Patterns (unless user opts out) +3. **Deduplicate**: Remove duplicate patterns (first sprite wins) +4. **Parse**: Split by ` / ` for rows, then by space for cells +5. **Extract Neighbors**: `.` -> add position with `This` (1); `X` -> skip +6. **Create TilingRule**: Populate `m_Neighbors` and `m_NeighborPositions` +7. **Assign Sprite**: Set single sprite output +8. **Sort**: Order by specificity descending +9. **Apply**: Add sorted rules to RuleTile asset +10. **Default Sprite**: Set `m_DefaultSprite` to the last (least specific) rule's sprite + +## Scripts + +Implementation and usage examples are in the `scripts/` folder: + +| File | Description | +|------|-------------| +| [`TilemapRuleTileCreateFromSegment.cs`](../scripts/TilemapRuleTileCreateFromSegment.cs) | Core implementation with `CreateRuleTileFromSprites`, `CreateTilingRuleFromPattern`, `ParsePattern`, and `ApplyRulesToTile` | +| [`RuleTileGenerator.cs`](../scripts/RuleTileGenerator.cs) | Editor window example (`Tools > Generate RuleTile from Sprites`) | +| [`ManualWorkflowExample.cs`](../scripts/ManualWorkflowExample.cs) | Manual two-step workflow for finer control over analysis | + +### Quick Usage + +```csharp +// Get sprites and create rules in one call +var rules = TilemapRuleTileCreateFromSegment.CreateRuleTileFromSprites( + sprites, matchThreshold: 0.75f, colorTolerance: 0.04f); + +// Apply to RuleTile +var ruleTile = ScriptableObject.CreateInstance(); +TilemapRuleTileCreateFromSegment.ApplyRulesToTile(ruleTile, rules); +``` + +## Common Tile Patterns + +| Tile Type | Pattern | This Count | +|------------------------------------------------------|----------------------------------|------------| +| Fully surrounded (inner tile) | `. . . / . * . / . . .` | 8 | +| Top left corner missing | `X . . / . * . / . . .` | 7 | +| Top right corner missing | `. . X / . * . / . . .` | 7 | +| Bottom left corner missing | `. . . / . * . / X . .` | 7 | +| Bottom right corner missing | `. . . / . * . / . . X` | 7 | +| Top corners missing | `X . X / . * . / . . .` | 6 | +| Bottom corners missing | `. . . / . * . / X . X` | 6 | +| Left corners missing | `X . . / . * . / X . .` | 6 | +| Right corners missing | `. . X / . * . / . . X` | 6 | +| Top Left and Bottom Right diagonal corners missing | `X . . / . * . / . . X` | 6 | +| Top Right and Bottom Left diagonal corners missing | `. . X / . * . / X . .` | 6 | +| Top Left, Top Right and Bottom Left corners missing | `X . X / . * . / X . .` | 5 | +| Top Left, Top Right and Bottom Right corners missing | `X . X / . * . / . . X` | 5 | +| Top Left, Bottom Left and Bottom Right corners missing | `X . . / . * . / X . X` | 5 | +| Top Right, Bottom Left and Bottom Right corners missing | `. . X / . * . / X . X` | 5 | +| Cross Section | `X . X / . * . / X . X` | 4 | +| Flat edge (Bottom) | `X X X / . * . / . . .` | 5 | +| Flat edge (Top) | `. . . / . * . / X X X` | 5 | +| Flat edge (Left) | `. . X / . * X / . . X` | 5 | +| Flat edge (Right) | `X . . / X * . / X . .` | 5 | +| L-Shape, Point Right | `X X X / . * . / . . X` | 4 | +| L-Shape, Point Bottom | `. . X / . * X / X . X` | 3 | +| L-Shape, Point Left | `X . . / . * . / X X X` | 4 | +| L-Shape, Point Top | `X . X / X * . / X . .` | 3 | +| L-Shape Inverse, Point Left | `X X X / . * . / X . .` | 4 | +| L-Shape Inverse, Point Bottom | `X . . / X * . / X . X` | 3 | +| L-Shape Inverse, Point Right | `. . X / . * . / X X X` | 4 | +| L-Shape Inverse, Point Top | `X . X / . * . / . . X` | 5 | +| T-Shape, face down | `X X X / . * . / X . X` | 3 | +| T-Shape, face top | `X . X / . * . / X X X` | 3 | +| T-Shape, face left | `X . X / . * X / X . X` | 3 | +| T-Shape, face right | `X . X / X * . / X . X` | 3 | +| Horizontal bridge | `X X X / . * . / X X X` | 2 | +| Vertical bridge | `X . X / X * X / X . X` | 2 | +| Corner piece, Bottom Right | `X X X / X * . / X . .` | 3 | +| Corner piece, Bottom Left | `X X X / . * X / . . X` | 3 | +| Corner piece, Top Left | `. . X / . * X / X X X` | 3 | +| Corner piece, Top Right | `X . . / X * . / X X X` | 3 | +| Edge end, Bottom Right | `X X X / X * . / X . X` | 2 | +| Edge end, Bottom Left | `X X X / . * X / X . X` | 2 | +| Edge end, Top Left | `X . X / . * X / X X X` | 2 | +| Edge end, Top Right | `X . X / X * . / X X X` | 2 | +| Single isolated tile, Left | `X X X / . * X / X X X` | 1 | +| Single isolated tile, Right | `X X X / X * . / X X X` | 1 | +| Single isolated tile, Top | `X . X / X * X / X X X` | 1 | +| Single isolated tile, Bottom | `X X X / X * X / X . X` | 1 | +| Center | `X X X / X * X / X X X` | 0 | + +## Notes + +- Always run `sprite-segment-3x3grid` first -- this skill depends on its output +- Rules are evaluated in order; first matching rule wins +- A rule with 0 `This` conditions matches any configuration (use as fallback) +- The center cell (`*`) is always ignored in neighbor calculations +- Unity's RuleTile supports up to 8 neighbors in a standard 3x3 grid +- For hexagonal or isometric grids, use `HexagonalRuleTile` or `IsometricRuleTile` + +## Prerequisites + +- **`sprite-segment-3x3grid` skill**: generates the input patterns. It ships in this + same plugin as `sprite-segment-3x3grid`, so it is always available — invoke + it rather than treating it as an unmet dependency. +- **com.unity.2d.tilemap.extras package**: Required for RuleTile class + +## See Also + +- `sprite-segment-3x3grid` - required prerequisite; generates the input patterns +- `Packages/com.unity.2d.tilemap.extras/Runtime/Tiles/RuleTile/RuleTile.cs` for RuleTile implementation +- Unity Manual: [Rule Tile](https://docs.unity3d.com/Packages/com.unity.2d.tilemap.extras@latest) diff --git a/skills/create-tile-palette-or-rule-tiles/references/ruletile.md b/skills/create-tile-palette-or-rule-tiles/references/ruletile.md new file mode 100644 index 0000000..7c0621a --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/references/ruletile.md @@ -0,0 +1,90 @@ +# Skill: Advanced RuleTile Creation + +This skill provides a template and logic for creating complex `RuleTiles`. Use this guide to programmatically generate or manually configure new RuleTiles that follow consistent connectivity patterns. + +## Rule Tile Rule Pattern + +The following rules define the connectivity for a standard 2D top-down layout. Each rule checks for the presence (.) or absence (X) of a tile in its 3x3 neighborhood. Depending on the Spritesheets used, the Rule Tile can use Fixed Rule Transforms or Rotated Rule Transforms. Use Rotated Rule Transforms to reduce the number of Tiling Rules used. + +## Legend +- `.`: **This** (Tile must be present) +- `X`: **Any** (Does not matter) +- `*`: The tile itself (Center) + +### Tiling Rules Template for Fixed Rule Tiles + +| Rule ID | Neighbors (Top to Bottom, Left to Right) | Rule Transform | Description | +|:--------|:-----------------------------------------|:---------------|:--------------------------------------------------------| +| 0 | `. . .` / `. * .` / `. . .` | Fixed | Fully surrounded (inner tile) | +| 1 | `X . .` / `. * .` / `. . .` | Fixed | Top left corner missing | +| 2 | `. . X` / `. * .` / `. . .` | Fixed | Top right corner missing | +| 3 | `. . .` / `. * .` / `X . .` | Fixed | Bottom left corner missing | +| 4 | `. . .` / `. * .` / `. . X` | Fixed | Bottom right corner missing | +| 5 | `X . X` / `. * .` / `. . .` | Fixed | Top corners missing | +| 6 | `. . .` / `. * .` / `X . X` | Fixed | Bottom corners missing | +| 7 | `X . .` / `. * .` / `X . .` | Fixed | Left corners missing | +| 8 | `. . X` / `. * .` / `. . X` | Fixed | Right corners missing | +| 9 | `X . .` / `. * .` / `. . X` | Fixed | Top Left and Bottom Right diagonal corners missing | +| 10 | `. . X` / `. * .` / `X . .` | Fixed | Top Right and Bottom Left diagonal corners missing | +| 11 | `X . X` / `. * .` / `X . .` | Fixed | Top Left, Top Right and Bottom Left corners missing | +| 12 | `X . X` / `. * .` / `. . X` | Fixed | Top Left, Top Right and Bottom Right corners missing | +| 13 | `X . .` / `. * .` / `X . X` | Fixed | Top Left, Bottom Left and Bottom Right corners missing | +| 14 | `. . X` / `. * .` / `X . X` | Fixed | Top Right, Bottom Left and Bottom Right corners missing | +| 15 | `X . X` / `. * .` / `X . X` | Fixed | Cross Section | +| 16 | `X X X` / `. * .` / `. . .` | Fixed | Flat edge (Bottom) | +| 17 | `. . .` / `. * .` / `X X X` | Fixed | Flat edge (Top) | +| 18 | `. . X` / `. * X` / `. . X` | Fixed | Flat edge (Left) | +| 19 | `X . .` / `X * .` / `X . .` | Fixed | Flat edge (Right) | +| 20 | `X X X` / `. * .` / `. . X` | Fixed | L-Shape, Point Right | +| 21 | `. . X` / `. * X` / `X . X` | Fixed | L-Shape, Point Bottom | +| 22 | `X . .` / `. * .` / `X X X` | Fixed | L-Shape, Point Left | +| 23 | `X . X` / `X * .` / `X . .` | Fixed | L-Shape, Point Top | +| 24 | `X X X` / `. * .` / `X . .` | Fixed | L-Shape Inverse, Point Left | +| 25 | `X . .` / `X * .` / `X . X` | Fixed | L-Shape Inverse, Point Bottom | +| 26 | `. . X` / `. * .` / `X X X` | Fixed | L-Shape Inverse, Point Right | +| 27 | `X . X` / `. * .` / `. . X` | Fixed | L-Shape Inverse, Point Top | +| 28 | `X X X` / `. * .` / `X . X` | Fixed | T-Shape, face down | +| 29 | `X . X` / `. * .` / `X X X` | Fixed | T-Shape, face top | +| 30 | `X . X` / `. * X` / `X . X` | Fixed | T-Shape, face left | +| 31 | `X . X` / `X * .` / `X . X` | Fixed | T-Shape, face right | +| 32 | `X X X` / `. * .` / `X X X` | Fixed | Horizontal bridge | +| 33 | `X . X` / `X * X` / `X . X` | Fixed | Vertical bridge | +| 34 | `X X X` / `X * .` / `X . .` | Fixed | Corner piece, Bottom Right | +| 35 | `X X X` / `. * X` / `. . X` | Fixed | Corner piece, Bottom Left | +| 36 | `. . X` / `. * X` / `X X X` | Fixed | Corner piece, Top Left | +| 37 | `X . .` / `X * .` / `X X X` | Fixed | Corner piece, Top Right | +| 38 | `X X X` / `X * .` / `X . X` | Fixed | Edge end, Bottom Right | +| 39 | `X X X` / `. * X` / `X . X` | Fixed | Edge end, Bottom Left | +| 40 | `X . X` / `. * X` / `X X X` | Fixed | Edge end, Top Left | +| 41 | `X . X` / `X * .` / `X X X` | Fixed | Edge end, Top Right | +| 42 | `X X X` / `. * X` / `X X X` | Fixed | Single isolated tile, Left | +| 43 | `X X X` / `X * .` / `X X X` | Fixed | Single isolated tile, Right | +| 44 | `X . X` / `X * X` / `X X X` | Fixed | Single isolated tile, Top | +| 45 | `X X X` / `X * X` / `X . X` | Fixed | Single isolated tile, Bottom | +| 46 | `X X X` / `X * X` / `X X X` | Fixed | Center | + +#### Usage +When applying this skill to a new texture set, first ensure the texture is sliced into sprites matching these 47 logical configurations. Then, run a script using the description to map the sprites to each rule. Ensure that RuleTile has all 47 TilingRules listed in the template. + +### Tiling Rules Template for Rotated Rule Tiles + +| Rule ID | Neighbors (Top to Bottom, Left to Right) | Rule Transform | Description | +|:--------|:-----------------------------------------|:---------------|:------------------------------| +| 0 | `. . .` / `. * .` / `. . .` | Fixed | Fully surrounded (inner tile) | +| 1 | `X . .` / `. * .` / `. . .` | Rotated | One corner missing | +| 2 | `X . X` / `. * .` / `. . .` | Rotated | Two corners missing | +| 3 | `X . .` / `. * .` / `. . X` | Rotated | Two diagonal corners missing | +| 4 | `X . X` / `. * .` / `. . X` | Rotated | Three corners missing | +| 5 | `X . X` / `. * .` / `X . X` | Fixed | Cross Section | +| 6 | `X X X` / `. * .` / `. . .` | Rotated | Flat edge | +| 7 | `X X X` / `. * .` / `. . X` | Rotated | L-Shape | +| 8 | `X X X` / `. * .` / `X . .` | Rotated | L-Shape Inverse | +| 9 | `X X X` / `. * .` / `X . X` | Rotated | Isolated edge | +| 10 | `X X X` / `. * .` / `X X X` | Rotated | Vertical/Horizontal bridge | +| 11 | `X X X` / `X * .` / `X . .` | Rotated | Corner piece | +| 12 | `X X X` / `X * .` / `X . X` | Rotated | Edge end | +| 13 | `X X X` / `. * X` / `X X X` | Rotated | Single isolated tile | +| 14 | `X X X` / `X * X` / `X X X` | Fixed | Center | + +#### Usage +When applying this skill to a new texture set, first ensure the texture is sliced into sprites matching these 15 logical configurations. Then, run a script using the description to map the sprites to each rule. Ensure that RuleTile has all 15 TilingRules listed in the template. diff --git a/skills/create-tile-palette-or-rule-tiles/scripts/CreatePaletteTemplate.cs b/skills/create-tile-palette-or-rule-tiles/scripts/CreatePaletteTemplate.cs new file mode 100644 index 0000000..461f3ec --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/scripts/CreatePaletteTemplate.cs @@ -0,0 +1,148 @@ +// Code template for creating Tile Palettes using GridPaletteUtility.CreateNewPalette +// Reference: Packages/com.unity.2d.tilemap/Editor/GridPaletteUtility.cs + +using UnityEngine; +using UnityEditor.Tilemaps; + +namespace TilePaletteCreation +{ + public static class CreatePaletteTemplate + { + // CreateNewPalette signature: + // public static GameObject CreateNewPalette( + // string folderPath, + // string name, + // GridLayout.CellLayout layout, + // GridPalette.CellSizing cellSizing, + // Vector3 cellSize, + // GridLayout.CellSwizzle swizzle, + // TransparencySortMode sortMode, + // Vector3 sortAxis) + + /// + /// Creates a rectangular tile palette with automatic cell sizing. + /// + public static GameObject CreateRectangularPalette(string folderPath, string paletteName) + { + return GridPaletteUtility.CreateNewPalette( + folderPath, + paletteName, + GridLayout.CellLayout.Rectangle, + GridPalette.CellSizing.Automatic, + new Vector3(1f, 1f, 0f), + GridLayout.CellSwizzle.XYZ, + TransparencySortMode.Default, + new Vector3(0f, 0f, 1f)); + } + + /// + /// Creates a hexagonal tile palette (point-top orientation). + /// Uses the standard hexagonal cell size. + /// + public static GameObject CreateHexagonalPalette(string folderPath, string paletteName) + { + return GridPaletteUtility.CreateNewPalette( + folderPath, + paletteName, + GridLayout.CellLayout.Hexagon, + GridPalette.CellSizing.Manual, + new Vector3(0.8659766f, 1f, 1f), + GridLayout.CellSwizzle.XYZ, + TransparencySortMode.Default, + new Vector3(0f, 0f, 1f)); + } + + /// + /// Creates an isometric tile palette with custom sort axis. + /// + public static GameObject CreateIsometricPalette(string folderPath, string paletteName) + { + return GridPaletteUtility.CreateNewPalette( + folderPath, + paletteName, + GridLayout.CellLayout.Isometric, + GridPalette.CellSizing.Manual, + new Vector3(1f, 0.5f, 1f), + GridLayout.CellSwizzle.XYZ, + TransparencySortMode.CustomAxis, + new Vector3(0f, 0f, 1f)); + } + + /// + /// Creates an isometric Z as Y tile palette. + /// Used when Z position should affect Y sorting. + /// + public static GameObject CreateIsometricZAsYPalette(string folderPath, string paletteName) + { + return GridPaletteUtility.CreateNewPalette( + folderPath, + paletteName, + GridLayout.CellLayout.IsometricZAsY, + GridPalette.CellSizing.Manual, + new Vector3(1f, 0.5f, 1f), + GridLayout.CellSwizzle.XYZ, + TransparencySortMode.CustomAxis, + new Vector3(0f, 0f, 1f)); + } + + /// + /// Creates a tile palette with fully customizable parameters. + /// + /// Project-relative folder path (e.g., "Assets/Palettes") + /// Name of the palette asset + /// Grid cell layout type + /// Automatic or Manual cell sizing + /// Size of each cell in the grid + /// Cell coordinate swizzle + /// Transparency sort mode for rendering + /// Custom sort axis (used when sortMode is CustomAxis) + /// The created palette GameObject, or null if creation failed + public static GameObject CreateCustomPalette( + string folderPath, + string paletteName, + GridLayout.CellLayout layout, + GridPalette.CellSizing cellSizing, + Vector3 cellSize, + GridLayout.CellSwizzle swizzle, + TransparencySortMode sortMode, + Vector3 sortAxis) + { + return GridPaletteUtility.CreateNewPalette( + folderPath, + paletteName, + layout, + cellSizing, + cellSize, + swizzle, + sortMode, + sortAxis); + } + } +} + +// Parameter Reference: +// +// GridLayout.CellLayout: +// - Rectangle: Standard rectangular grid +// - Hexagon: Hexagonal grid +// - Isometric: Isometric grid +// - IsometricZAsY: Isometric grid where Z position affects Y sorting +// +// GridPalette.CellSizing: +// - Automatic: Cell size determined automatically from sprites +// - Manual: Cell size specified explicitly +// +// GridLayout.CellSwizzle: +// - XYZ: Standard coordinate system +// - XZY, YXZ, YZX, ZXY, ZYX: Various coordinate swizzles +// +// TransparencySortMode: +// - Default: Use default sorting +// - Perspective: Sort by perspective +// - Orthographic: Sort orthographically +// - CustomAxis: Sort along a custom axis +// +// Recommended Cell Sizes: +// - Rectangular: (1, 1, 0) with Automatic sizing +// - Hexagonal: (0.8659766, 1, 1) +// - Isometric: (1, 0.5, 1) diff --git a/skills/create-tile-palette-or-rule-tiles/scripts/ManualWorkflowExample.cs b/skills/create-tile-palette-or-rule-tiles/scripts/ManualWorkflowExample.cs new file mode 100644 index 0000000..3420c8c --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/scripts/ManualWorkflowExample.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +/// +/// Example: Manual two-step workflow for more control over the analysis step. +/// +public static class ManualWorkflowExample +{ + public static void RunManualWorkflow(List sprites, RuleTile myRuleTile, + bool filterToKnownPatterns = true) + { + // Step 1: Run sprite-segment-3x3grid on each sprite, filter, and deduplicate + var seenPatterns = new HashSet(); + var uniquePatterns = new List<(string pattern, Sprite sprite)>(); + + foreach (var sprite in sprites) + { + // Apply sprite-segment-3x3grid analysis + string pattern = SpriteSegment3x3Grid.AnalyzeSpriteGrid( + sprite, + matchThreshold: 0.75f, + colorTolerance: 0.04f + ); + + // Discard patterns not in the known set + if (filterToKnownPatterns && + !TilemapRuleTileCreateFromSegment.IsKnownPattern(pattern)) + { + Debug.Log($"Sprite '{sprite.name}' skipped (unknown pattern: {pattern})"); + continue; + } + + // Skip duplicates + if (seenPatterns.Contains(pattern)) + { + Debug.Log($"Sprite '{sprite.name}' skipped (duplicate pattern: {pattern})"); + continue; + } + + seenPatterns.Add(pattern); + Debug.Log($"Sprite '{sprite.name}' pattern: {pattern}"); + uniquePatterns.Add((pattern, sprite)); + } + + // Step 2: Create TilingRules from unique patterns + var rules = new List<(RuleTile.TilingRule rule, int specificity)>(); + foreach (var (pattern, sprite) in uniquePatterns) + { + var result = TilemapRuleTileCreateFromSegment.CreateTilingRuleFromPattern(pattern, sprite); + rules.Add(result); + } + + // Sort by specificity + rules.Sort((a, b) => b.specificity.CompareTo(a.specificity)); + + // Apply to RuleTile + var sortedRules = rules.Select(r => r.rule).ToList(); + TilemapRuleTileCreateFromSegment.ApplyRulesToTile(myRuleTile, sortedRules); + + Debug.Log($"Created {sortedRules.Count} unique rules from {sprites.Count} sprites"); + } +} diff --git a/skills/create-tile-palette-or-rule-tiles/scripts/RuleTileGenerator.cs b/skills/create-tile-palette-or-rule-tiles/scripts/RuleTileGenerator.cs new file mode 100644 index 0000000..d5069a5 --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/scripts/RuleTileGenerator.cs @@ -0,0 +1,61 @@ +using System.Linq; +using UnityEditor; +using UnityEngine; + +public class RuleTileGenerator : EditorWindow +{ + float m_MatchThreshold = 0.75f; + + [MenuItem("Tools/Generate RuleTile from Sprites")] + static void ShowWindow() + { + GetWindow("RuleTile Generator"); + } + + void OnGUI() + { + GUILayout.Label("Match Threshold", EditorStyles.boldLabel); + m_MatchThreshold = EditorGUILayout.Slider(m_MatchThreshold, 0.5f, 0.9f); + + if (GUILayout.Button("Generate from Selected Texture")) + GenerateRuleTile(); + } + + void GenerateRuleTile() + { + var texture = Selection.activeObject as Texture2D; + if (texture == null) + { + Debug.LogError("Please select a Texture2D asset"); + return; + } + + // Get sprites from texture + string path = AssetDatabase.GetAssetPath(texture); + var sprites = AssetDatabase.LoadAllAssetsAtPath(path).OfType().ToList(); + + if (sprites.Count == 0) + { + Debug.LogError("No sprites found in texture. Ensure texture is sliced."); + return; + } + + // Complete workflow: sprite-segment-3x3grid -> TilingRules + var rules = TilemapRuleTileCreateFromSegment.CreateRuleTileFromSprites( + sprites, + matchThreshold: m_MatchThreshold + ); + + // Create and save RuleTile asset + var ruleTile = ScriptableObject.CreateInstance(); + TilemapRuleTileCreateFromSegment.ApplyRulesToTile(ruleTile, rules); + + string savePath = path.Replace(".png", "_RuleTile.asset") + .Replace(".jpg", "_RuleTile.asset"); + AssetDatabase.CreateAsset(ruleTile, savePath); + AssetDatabase.SaveAssets(); + + Debug.Log($"Created RuleTile with {rules.Count} rules at {savePath}"); + Selection.activeObject = ruleTile; + } +} diff --git a/skills/create-tile-palette-or-rule-tiles/scripts/TilemapRuleTileCreateFromSegment.cs b/skills/create-tile-palette-or-rule-tiles/scripts/TilemapRuleTileCreateFromSegment.cs new file mode 100644 index 0000000..daadc0e --- /dev/null +++ b/skills/create-tile-palette-or-rule-tiles/scripts/TilemapRuleTileCreateFromSegment.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +/// +/// Creates RuleTile TilingRules by first applying sprite-segment-3x3grid analysis, +/// then converting the text patterns to neighbor configurations. +/// +public static class TilemapRuleTileCreateFromSegment +{ + /// + /// Grid position to Unity neighbor Vector3Int mapping. + /// Index 4 (center) is not included as it's not a neighbor. + /// + static readonly Dictionary k_GridIndexToPosition = new() + { + { 0, new Vector3Int(-1, 1, 0) }, // Top-Left + { 1, new Vector3Int(0, 1, 0) }, // Top + { 2, new Vector3Int(1, 1, 0) }, // Top-Right + { 3, new Vector3Int(-1, 0, 0) }, // Left + // 4 is center, skipped + { 5, new Vector3Int(1, 0, 0) }, // Right + { 6, new Vector3Int(-1, -1, 0) }, // Bottom-Left + { 7, new Vector3Int(0, -1, 0) }, // Bottom + { 8, new Vector3Int(1, -1, 0) }, // Bottom-Right + }; + + /// + /// The 47 known tile patterns from the Common Tile Patterns table. + /// Patterns not in this set are discarded by default. + /// + static readonly HashSet k_KnownPatterns = new() + { + ". . . / . * . / . . .", // Fully surrounded + "X . . / . * . / . . .", // Top left corner missing + ". . X / . * . / . . .", // Top right corner missing + ". . . / . * . / X . .", // Bottom left corner missing + ". . . / . * . / . . X", // Bottom right corner missing + "X . X / . * . / . . .", // Top corners missing + ". . . / . * . / X . X", // Bottom corners missing + "X . . / . * . / X . .", // Left corners missing + ". . X / . * . / . . X", // Right corners missing + "X . . / . * . / . . X", // Top Left and Bottom Right diagonal + ". . X / . * . / X . .", // Top Right and Bottom Left diagonal + "X . X / . * . / X . .", // Top Left, Top Right, Bottom Left + "X . X / . * . / . . X", // Top Left, Top Right, Bottom Right + "X . . / . * . / X . X", // Top Left, Bottom Left, Bottom Right + ". . X / . * . / X . X", // Top Right, Bottom Left, Bottom Right + "X . X / . * . / X . X", // Cross Section + "X X X / . * . / . . .", // Flat edge (Bottom) + ". . . / . * . / X X X", // Flat edge (Top) + ". . X / . * X / . . X", // Flat edge (Left) + "X . . / X * . / X . .", // Flat edge (Right) + "X X X / . * . / . . X", // L-Shape, Point Right + ". . X / . * X / X . X", // L-Shape, Point Bottom + "X . . / . * . / X X X", // L-Shape, Point Left + "X . X / X * . / X . .", // L-Shape, Point Top + "X X X / . * . / X . .", // L-Shape Inverse, Point Left + "X . . / X * . / X . X", // L-Shape Inverse, Point Bottom + ". . X / . * . / X X X", // L-Shape Inverse, Point Right + "X . X / . * . / . . X", // L-Shape Inverse, Point Top + "X X X / . * . / X . X", // T-Shape, face down + "X . X / . * . / X X X", // T-Shape, face top + "X . X / . * X / X . X", // T-Shape, face left + "X . X / X * . / X . X", // T-Shape, face right + "X X X / . * . / X X X", // Horizontal bridge + "X . X / X * X / X . X", // Vertical bridge + "X X X / X * . / X . .", // Corner piece, Bottom Right + "X X X / . * X / . . X", // Corner piece, Bottom Left + ". . X / . * X / X X X", // Corner piece, Top Left + "X . . / X * . / X X X", // Corner piece, Top Right + "X X X / X * . / X . X", // Edge end, Bottom Right + "X X X / . * X / X . X", // Edge end, Bottom Left + "X . X / . * X / X X X", // Edge end, Top Left + "X . X / X * . / X X X", // Edge end, Top Right + "X X X / . * X / X X X", // Single isolated tile, Left + "X X X / X * . / X X X", // Single isolated tile, Right + "X . X / X * X / X X X", // Single isolated tile, Top + "X X X / X * X / X . X", // Single isolated tile, Bottom + "X X X / X * X / X X X", // Center + }; + + /// + /// Creates a RuleTile from sprites by first running sprite-segment-3x3grid analysis. + /// This is the main entry point that implements the complete workflow. + /// Duplicate patterns are automatically removed (first sprite wins). + /// Patterns not in the known 47 Common Tile Patterns are discarded by default. + /// + /// Sprites to analyze and create rules for + /// Match threshold for sprite-segment-3x3grid (0.5, 0.75, or 0.9) + /// Color tolerance for sprite-segment-3x3grid + /// If true (default), discard patterns not in Common Tile Patterns + /// Sorted list of unique TilingRules (most specific first) + public static List CreateRuleTileFromSprites( + IEnumerable sprites, + float matchThreshold = 0.75f, + float colorTolerance = 0.04f, + bool filterToKnownPatterns = true) + { + var rules = new List<(RuleTile.TilingRule rule, int specificity, string pattern)>(); + var seenPatterns = new HashSet(); + + foreach (var sprite in sprites) + { + // Step 1: Always run sprite-segment-3x3grid first + string pattern = SpriteSegment3x3Grid.AnalyzeSpriteGrid(sprite, matchThreshold, colorTolerance); + + // Step 2: Discard patterns not in the known set + if (filterToKnownPatterns && !k_KnownPatterns.Contains(pattern)) + { + Debug.Log($"Sprite '{sprite.name}' skipped (unknown pattern: {pattern})"); + continue; + } + + // Step 3: Skip duplicate patterns (keep first sprite only) + if (seenPatterns.Contains(pattern)) + continue; + + seenPatterns.Add(pattern); + + // Step 4: Create TilingRule from the pattern + var (rule, specificity) = CreateTilingRuleFromPattern(pattern, sprite); + rules.Add((rule, specificity, pattern)); + } + + // Sort by specificity (descending) - more 'This' rules first + rules.Sort((a, b) => b.specificity.CompareTo(a.specificity)); + + return rules.Select(r => r.rule).ToList(); + } + + /// + /// Returns true if the pattern is one of the 47 known Common Tile Patterns. + /// + public static bool IsKnownPattern(string pattern) => k_KnownPatterns.Contains(pattern); + + /// + /// Creates a single TilingRule from a sprite-segment-3x3grid output pattern. + /// + /// Pattern string from sprite-segment-3x3grid, e.g., "X X X / X * X / . . ." + /// Sprite to assign to this rule + /// Tuple of (TilingRule, specificity count) + public static (RuleTile.TilingRule rule, int specificity) CreateTilingRuleFromPattern(string pattern, Sprite sprite) + { + var cells = ParsePattern(pattern); + var neighbors = new List(); + var neighborPositions = new List(); + int specificity = 0; + + for (int i = 0; i < 9; i++) + { + // Skip center cell + if (i == 4) + continue; + + string cell = cells[i]; + + // Map '.' to 'This' rule + // Map 'X' to DontCare (don't add position) + if (cell == ".") + { + neighbors.Add(RuleTile.TilingRuleOutput.Neighbor.This); + neighborPositions.Add(k_GridIndexToPosition[i]); + specificity++; + } + // 'X' is implicitly DontCare - position not added + } + + var rule = new RuleTile.TilingRule + { + m_Neighbors = neighbors, + m_NeighborPositions = neighborPositions, + m_Sprites = new[] { sprite }, + m_Output = RuleTile.TilingRuleOutput.OutputSprite.Single, + m_ColliderType = Tile.ColliderType.Sprite, + m_RuleTransform = RuleTile.TilingRuleOutput.Transform.Fixed, + }; + + return (rule, specificity); + } + + /// + /// Parses a sprite-segment-3x3grid output pattern into an array of 9 cell values. + /// + /// Pattern string, e.g., "X X X / X * X / . . ." + /// Array of 9 cell strings in order: top-left to bottom-right + public static string[] ParsePattern(string pattern) + { + var rows = pattern.Split(new[] { " / " }, StringSplitOptions.None); + if (rows.Length != 3) + throw new ArgumentException($"Pattern must have 3 rows, got {rows.Length}: {pattern}"); + + var cells = new string[9]; + for (int row = 0; row < 3; row++) + { + var rowCells = rows[row].Split(' '); + if (rowCells.Length != 3) + throw new ArgumentException($"Row {row} must have 3 cells, got {rowCells.Length}: {rows[row]}"); + + for (int col = 0; col < 3; col++) + { + cells[row * 3 + col] = rowCells[col]; + } + } + + return cells; + } + + /// + /// Applies generated rules to a RuleTile asset. + /// Sets the default sprite to the last rule's sprite (least specific / bottom-most match). + /// + /// Target RuleTile to configure + /// Sorted list of TilingRules to apply + public static void ApplyRulesToTile(RuleTile ruleTile, List rules) + { + ruleTile.m_TilingRules.Clear(); + ruleTile.m_TilingRules.AddRange(rules); + + // Use the bottom-most (least specific) rule's sprite as the default + if (rules.Count > 0 && rules[rules.Count - 1].m_Sprites.Length > 0) + ruleTile.m_DefaultSprite = rules[rules.Count - 1].m_Sprites[0]; + } +}