# Dropping to Clay

> Writing Clay's own elements in the same frame as rmp::ui, for what the small API does not have — and the rules about ids, strings and images that make it work.

Source: https://omardev29.github.io/rmp-docs/manual/raylib/clay.html

`rmp::ui` is a small surface over [Clay](https://github.com/nicbarker/clay), the layout engine underneath it. When a screen needs something that surface does not have — an element floating at an exact spot, an aspect ratio, a clip container shaped your way — you do not have to give up `rmp::ui` to get it. Include `<clay.h>` and write Clay between `rmp::ui::begin()` and `rmp::ui::end()`: your elements join the same tree, are laid out in the same pass and are drawn by the same renderer.

It is the same bargain as the rest of the framework. `rmp::assets` does not stop you calling `LoadTexture()`, and `rmp::ui` does not stop you calling Clay.

## Clay, next to rmp::ui

Clay is on the include path of every target and is never included for you: no Clay type, macro or enum appears in `rmp/ui.h`, so a game that does not ask for it never sees it. A file that wants it says so:

```cpp
#include <rmp/scene.h>
#include <rmp/ui.h>

#include <clay.h> // the layout engine itself: not included for you

class InventoryScene : public rmp::Scene {
    void _draw() override {
        rmp::ui::begin();
        rmp::ui::text("Inventory");

        // a row of four slots, which rmp::ui has no primitive for
        CLAY(CLAY_ID("hotbar"), { .layout = { .padding = CLAY_PADDING_ALL(8),
                                              .childGap = 8,
                                              .layoutDirection = CLAY_LEFT_TO_RIGHT },
                                  .backgroundColor = { 30, 30, 38, 255 } }) {
            for (int i = 0; i < 4; ++i) {
                CLAY(CLAY_IDI("hotbar-slot", i),
                     { .layout = { .sizing = { .width = CLAY_SIZING_FIXED(48),
                                               .height = CLAY_SIZING_FIXED(48) } },
                       .backgroundColor = { 44, 44, 56, 255 } }) {}
            }
        }

        if (rmp::ui::button("Close")) rmp::Scene::pop();
        rmp::ui::end();
    }
};
```

The text, the row and the button are one layout, in the order they were declared. [`rmp::ui::begin()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#begin) and [`rmp::ui::end()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#end) are Clay's own begin and end, with the framework's input, scale and drawing around them, so never call `Clay_BeginLayout()` or `Clay_EndLayout()` yourself. Clay itself is started by the first `rmp::ui::begin()` of the game, sized by `[ui] max_elements`, and your elements count towards that ceiling with the framework's.

## The example

`examples/ui/03_clay_direct` is the whole technique in one file: Clay's macros in the same frame as `rmp::ui`, a strip shaped like a tab — its top corners rounded, its bottom ones square, a border along one side — an image, ids in a loop and a hover query. It is written with [`RMP_ENTRY_POINT`](https://omardev29.github.io/rmp-docs/reference/macros.html#RMP_ENTRY_POINT) rather than scenes, so it opens its own window and its own frame; in a game with scenes, the part between `begin()` and `end()` goes in a scene's `_draw()` exactly as it is. The framework's CI builds and boots it on every run, and compiles it with MSVC as well, because Clay's macros are designated initialisers inside a `for` block — the shape MSVC is fussiest about.

[examples/ui/03_clay_direct/src/main.cpp](https://github.com/omardev29/raylib_multiplatform/blob/982bf2a1e307c49776bff84211260703b8de6895/examples/ui/03_clay_direct/src/main.cpp#L1-L141)

```cpp
// ---------------------------------------------------------------------------
// examples/ui/03_clay_direct/src/main.cpp
//
// THE ESCAPE HATCH: using Clay's own API directly, alongside rmp::ui.
//
// rmp::ui is a small, opinionated surface over Clay — enough for menus, HUDs
// and dialogs without ever mentioning a coordinate. When you want something it
// does not expose yet (floating elements placed where you choose, aspect
// ratios, per-corner radii, a border on one side, an explicit z-index), you do
// not have to wait for us and you do not have to give up rmp::ui to get it.
// (Clipping and scrolling it does expose: rmp::ui::scroll().)
//
// It is the same bargain as the rest of the framework: rmp::assets does not stop
// you calling LoadTexture, and rmp::ui does not stop you calling Clay. Or
// rlgl. Or raw OpenGL, for that matter.
//
//   #include <clay.h>
//
// and write Clay between rmp::ui::begin() and rmp::ui::end(). Your elements go
// into the same tree, get laid out in the same pass and drawn by the same
// renderer.
//
// Two things to know and then you are on your own:
//
//   * begin() has already opened two elements — a root that fills the screen
//     and a column that centres its contents. Yours become children of that
//     column. If you want to escape it, use Clay's floating elements.
//   * Clay does NOT copy strings. CLAY_STRING() on a literal is fine forever;
//     anything built at runtime must stay alive until end() has returned. This
//     is the one footgun rmp::ui::text() removes for you by copying.
//
// Run it: `rmp example 03_clay_direct`.
// ---------------------------------------------------------------------------

#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/scene.h>
#include <rmp/ui.h>

#include <clay.h> // the escape hatch: not included for you on purpose

class ClayScene : public rmp::Scene {
public:
    void _ready() override { _logo = rmp::assets::load_texture("rabbit.png"); }

    void _draw() override {
        // A copy of the raylib struct, alive for this frame. The handle below
        // is the owner; this is what Clay is allowed to point at.
        Texture2D logo_tex = _logo;

        rmp::ui::begin();

        // --- the normal API ---------------------------------------------------
        rmp::ui::text("Inventory");

        // --- and Clay, in the same frame --------------------------------------
        //
        // A horizontal strip of slots, which rmp::ui has no primitive for yet.
        // CLAY_AUTO_ID is the version without an explicit id; CLAY(CLAY_ID("x"),
        // ...) is the one to use when you want to ask Clay about the element later
        // with Clay_PointerOver or Clay_GetElementData.
        //
        // It is shaped like a tab, which rmp::ui cannot do either: each corner has
        // its own radius, and the border is on one side only.
        CLAY_AUTO_ID(
            { .layout = { .sizing = { .width = CLAY_SIZING_FIT(0),
                                      .height = CLAY_SIZING_FIT(0) },
                          .padding = CLAY_PADDING_ALL(10),
                          .childGap = 10,
                          .layoutDirection = CLAY_LEFT_TO_RIGHT },
              .backgroundColor = { 30, 30, 38, 255 },
              .cornerRadius = { .topLeft = 18,
                                .topRight = 18,
                                .bottomLeft = 0,
                                .bottomRight = 0 },
              .border = { .color = { 88, 120, 245, 255 }, .width = { .bottom = 3 } } }) {
            for (int i = 0; i < 4; ++i) {
                // CLAY_IDI gives each slot in a loop its own identity without
                // building a string per element.
                CLAY(CLAY_IDI("slot", i),
                     { .layout = { .sizing = { .width = CLAY_SIZING_FIXED(64),
                                               .height = CLAY_SIZING_FIXED(64) } },
                       .backgroundColor = { 44, 44, 56, 255 },
                       .cornerRadius = CLAY_CORNER_RADIUS(6) }) {
                    // Images: point imageData at a Texture2D you own and keep
                    // alive for the frame. Our renderer draws it stretched to the
                    // element's box, untinted. A tint is a Color* in userData; a
                    // backgroundColor is NOT a tint -- Clay draws it as a rectangle
                    // after the image, which paints a flat square over it.
                    if (i == 0) {
                        CLAY_AUTO_ID(
                            { .layout = { .sizing = { .width = CLAY_SIZING_GROW(0),
                                                      .height = CLAY_SIZING_GROW(0) } },
                              .image = { .imageData = &logo_tex } }) {}
                    }
                }
            }
        }

        // Hover, straight from Clay. Note it reads the PREVIOUS frame's geometry,
        // exactly like rmp::ui::button() does — the layout for this frame does not
        // exist until end().
        if (Clay_PointerOver(CLAY_IDI("slot", 0))) {
            rmp::ui::text("slot 1", { .color = rmp::ui::ColorRole::PRIMARY });
        }

        // Back to the normal API, still the same frame.
        if (rmp::ui::button("Close")) rmp::app::quit();

        rmp::ui::end();
    }

private:
    // The owning handle. Clay wants a Texture2D* that stays valid for the
    // frame, so _draw() copies the raylib struct out for exactly that long.
    rmp::Texture _logo;
};

RMP_GAME(ClayScene);

// ---------------------------------------------------------------------------
// What our renderer understands
// ---------------------------------------------------------------------------
//
//   RECTANGLE      background colour + each corner's own radius
//   BORDER         colour + each side's own width + each corner's own radius
//   TEXT           drawn with the UI font; fontId is ignored, there is one font
//   IMAGE          imageData as a Texture2D*; userData as a Color* tint, or
//                  null for none (a backgroundColor covers the image: see above)
//   SCISSOR_START  clipping, so Clay's clip/scroll containers work
//   SCISSOR_END
//
// CUSTOM commands are not handled. If you need them, src/rmp/ui/render.cpp is
// one short file, and adding a case is the intended way to extend it.
//
// AND THE LIMITS. Doing this ties your code to a specific version of Clay
// (0.14, pinned in thirdparty/FROZEN_VERSIONS.md). rmp::ui exists partly so
// that most code does not carry that dependency — Clay is pre-1.0 and its API
// has moved between minor versions. That is a fair trade for a feature you need
// today; it is a bad trade for a button.
```

## Where your elements go

`rmp::ui::begin()` has already opened two elements by the time your first `CLAY()` runs: a root that fills the window, and inside it a column that fits its contents and centres them. Your elements are children of that column, beside the framework's widgets. The placement you give `begin()` — `rmp::ui::begin({ .placement =
rmp::ui::Align::TOP_LEFT })` — moves that column, and your elements with it. With `rmp::ui::begin({ .grow = true })` the column fills the window instead, less the padding, so an element of yours sized with `CLAY_SIZING_GROW` reaches its edges; see [filling the window](https://omardev29.github.io/rmp-docs/manual/modules/ui-layout.html#filling-the-window).

To get out of the column, float. An element with `.floating.attachTo =
CLAY_ATTACH_TO_ROOT` is placed by its `.offset` from the corner of the window, whatever the column is doing:

```cpp
rmp::ui::begin();
rmp::ui::text("Paused");

CLAY(CLAY_ID("build-badge"), { .layout = { .padding = CLAY_PADDING_ALL(6) },
                               .backgroundColor = { 200, 60, 60, 255 },
                               .floating = { .offset = { 16, 16 },
                                             .attachTo = CLAY_ATTACH_TO_ROOT } }) {
    CLAY_TEXT(CLAY_STRING("BETA"),
              CLAY_TEXT_CONFIG({ .textColor = { 255, 255, 255, 255 }, .fontSize = 16 }));
}

rmp::ui::end();
```

Clay's own designated initialisers follow the rule every C++20 one does: the fields in the order the struct declares them. `.layout` before `.backgroundColor` before `.floating`, and inside `.layout`, `.sizing`, `.padding`, `.childGap`, `.childAlignment`, `.layoutDirection`. Out of order is a compile error, not a warning.

## Ids

Every element gets the id you give it, and the id is how you ask Clay about it later:

| Spelling | For |
|---|---|
| `CLAY(CLAY_ID("wallet"), ...)` | One element with a name of its own. |
| `CLAY(CLAY_IDI("slot", i), ...)` | One of many, in a loop, without building a string per element. |
| `CLAY_AUTO_ID(...)` | An element you will never ask about. |

Three rules follow from how they are made.

- **Ask with the macro you made it with.** `CLAY_ID("x")` and `CLAY_IDI("x", 0)` are two different ids: Clay hashes them differently even at index 0, so an element made with one is never found with the other. The example asks `Clay_PointerOver(CLAY_IDI("slot", 0))` about the element it made with `CLAY_IDI("slot", i)`.
- **Use labels no rmp::ui control in the scene uses.** `rmp::ui` names its elements by their label through `Clay_GetElementIdWithIndex()` — the function behind `CLAY_IDI` — counting each label's occurrences and giving each scene that draws UI a block of indices of its own. In the first such scene of a frame that block starts at 0, so `CLAY_IDI("Close", 0)` there is the id `rmp::ui::button("Close")` already has.
- **One id, one element, per frame.** Two elements with the same id are Clay's error, and the framework prints each kind of Clay error once rather than every frame, in Clay's own words after `UI: clay: …`. With `[dev] strict = true` the first one stops a debug build where it happened.

## Strings

Clay does not copy strings. It keeps the pointer it is given and reads it while the layout is computed and drawn, which is inside `rmp::ui::end()`. `rmp::ui::text()` takes that problem away by copying what it is given into a frame arena first — which is why `rmp::ui::text(std::to_string(score))` is safe — but a string you hand to Clay yourself is your responsibility:

- `CLAY_STRING("BETA")` on a literal is fine forever: a literal lives as long as the program.
- A string built at run time has to stay alive until `rmp::ui::end()` returns. A `std::string` declared in `_draw()` before `rmp::ui::begin()` does; a temporary made inside the `CLAY_TEXT()` call does not.

```cpp
int coins = 120;

void _draw() override {
    // alive until _draw() returns, which is after end()
    const std::string label = "Coins: " + std::to_string(coins);
    const Clay_String text{ .isStaticallyAllocated = false,
                            .length = static_cast<int32_t>(label.size()),
                            .chars = label.c_str() };

    rmp::ui::begin();
    CLAY(CLAY_ID("wallet"), { .layout = { .padding = CLAY_PADDING_ALL(8) },
                              .backgroundColor = { 30, 30, 38, 255 } }) {
        CLAY_TEXT(text, CLAY_TEXT_CONFIG({ .textColor = { 255, 220, 120, 255 },
                                           .fontSize = 24 }));
    }
    rmp::ui::end();
}
```

Text is measured and drawn with the interface's font — the one `[ui] font` names, or raylib's built-in font when it is empty — whatever `.fontId` says. The `.fontSize` is in pixels, and the spacing between letters is a tenth of it, the same as `rmp::ui`'s own text, and a font of your own is rasterised at exactly that size for your text as it is for theirs.

## Images

An image element points `.image.imageData` at a `Texture2D` — raylib's struct, not an [`rmp::Texture`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp.html#Texture) — that stays alive until `rmp::ui::end()` returns. The renderer draws it stretched to the element's box. The example does it the safe way: it keeps the `rmp::Texture` that owns the picture, and copies the raylib struct out of it into a local for the frame.

The tint is the part that is easy to write wrong. It travels in `.userData`, as a pointer to a `Color`; a null `userData` draws the picture untinted. It is not `.backgroundColor`: Clay emits a rectangle for any element with a background colour, *after* the element's image, so a colour put there is painted straight over the picture.

```cpp
rmp::Texture face;                // owns the picture
Color hurt{ 255, 120, 120, 255 }; // a member: alive for as long as the scene

void _ready() override { face = rmp::assets::load_texture("rabbit.png"); }

void _draw() override {
    Texture2D frame_face = face; // the raylib struct, for this frame

    rmp::ui::begin();
    CLAY(CLAY_ID("portrait"),
         { .layout = { .sizing = { .width = CLAY_SIZING_FIXED(96 * rmp::ui::scale()),
                                   .height = CLAY_SIZING_FIXED(96 * rmp::ui::scale()) } },
           .image = { .imageData = &frame_face },
           .userData = &hurt }) {}
    rmp::ui::end();
}
```

[`rmp::ui::image()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#image) does all of this for you, copying the struct into the frame arena and carrying its [`tint`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#ImageOptions-tint) the same way; drop to Clay for an image only when it has to sit somewhere `rmp::ui` cannot put it.

## Sizes are pixels

Every number you give Clay is a pixel of the window. Every number you give `rmp::ui` is a design unit — a pixel at the `[window]` resolution — which it multiplies by [`rmp::ui::scale()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#scale) on the way to Clay, so a menu is the same size on a laptop and on a 4K screen. Clay elements of your own do not get that for free. Multiply by `rmp::ui::scale()`, as the portrait above does, and they grow and shrink with the rest of the interface; leave it out, and they stay the same number of pixels on every screen.

## Hover and the pointer

`Clay_PointerOver()` answers from the previous frame's layout, exactly as `rmp::ui::button()` does: this frame's layout does not exist until `end()`. The framework hands Clay the pointer at the end of each scene's layout, and for a scene whose input a scene above it has taken, it hands Clay a position no element can contain — so `Clay_PointerOver()` is false under a pause menu, the same as every `rmp::ui` widget there.

Clay keeps one pointer state, and the last `rmp::ui::end()` of a frame is what sets it. With two scenes describing UI in the same frame, ask Clay about the pointer only in the upper one.

Your elements count for [`rmp::ui::wants_pointer()`](https://omardev29.github.io/rmp-docs/reference/namespaces/rmp-ui.html#wants_pointer) the same as the framework's own. It is answered from what each `end()` drew: the pointer over an element of yours with a background colour, a border or an image, or over a clip container, is over the interface, and the game's mouse actions go quiet there. Text alone is not, and neither is whatever a clip container has clipped away.

## What the renderer draws

Clay does not draw: it produces a list of commands, and `src/rmp/ui/render.cpp` turns them into raylib calls, in Clay's z order. It understands these, and the elements you write get exactly what the framework's own get:

| Command | Drawn as |
|---|---|
| `RECTANGLE` | The background colour, each corner rounded by its own radius. |
| `BORDER` | The border colour, each side at its own width, each corner rounded by its own radius. |
| `TEXT` | The interface's font, at the element's size and colour. |
| `IMAGE` | `imageData` as a `Texture2D`, stretched to the box, tinted by a `Color` in `userData`. |
| `SCISSOR_START`, `SCISSOR_END` | Clipping, so Clay's clip and scroll containers work. |

Each radius is taken on its own and held to half the box's shorter side, so a radius too big for the box cannot turn it inside out. A box with four equal corners and four equal sides — everything `rmp::ui` draws — goes through raylib's own rounded-rectangle calls; any other shape is drawn by the renderer itself, such as a tab rounded only along the top with a border along the bottom:

```cpp
rmp::ui::begin();
CLAY(CLAY_ID("tab"), { .layout = { .padding = CLAY_PADDING_ALL(10) },
                       .backgroundColor = { 30, 30, 38, 255 },
                       .cornerRadius = { .topLeft = 18, .topRight = 18 },
                       .border = { .color = { 88, 120, 245, 255 }, .width = { .bottom = 3 } } }) {
    CLAY_TEXT(CLAY_STRING("Items"),
              CLAY_TEXT_CONFIG({ .textColor = { 255, 255, 255, 255 }, .fontSize = 20 }));
}
rmp::ui::end();
```

Anything else Clay can emit — `CUSTOM` elements, overlay colours — is not drawn. The renderer is one short file, and adding a case to it is the intended way to extend it.

## What it costs

The Clay in `thirdparty/clay/clay.h` is pinned at 0.14 in `thirdparty/FROZEN_VERSIONS.md`, carries one marked patch so that it builds with NetBSD's compiler, and does not move unless someone decides it should. Clay is not at 1.0, and its API has changed between minor versions. Code written against `rmp::ui` does not depend on any of that — it never names a Clay type — while code that drops to Clay is tied to the version it was written for.

That is a fair trade for a feature a screen needs today, and a poor one for a button. Reach for Clay for the element `rmp::ui` cannot make, and keep everything around it in `rmp::ui`.
