second pass

This commit is contained in:
johan0A 2025-01-14 00:07:44 +01:00
parent f6a86434e2
commit 3cf1e2c74e
13 changed files with 407 additions and 884 deletions

View file

@ -14,9 +14,9 @@ This README is abbreviated and applies to using clay in Zig specifically: If you
The **most notable difference** between the C API and the Zig bindings is that opening and closing the scope for declaring child elements must be done "manually" using 2 function calls.
other changes include:
other differences include:
- minor naming changes
- ability to initialize a parameter by calling a function that is part of its type's namespace for example `.fixed()` or `.layout()`
- ability to initialize a parameter by calling a function that is part of its type's namespace for example `.fixed()` or `.Layout()`
- ability to initialize a parameter by using a public constant that is part of its type's namespace for example `.grow`
- clay.singleElem() is available to create a clay element without creating a scope
@ -40,7 +40,7 @@ CLAY(
In Zig:
```Zig
if (clay.OPEN(&.{ // first function call to open the scope
clay.UI(&.{ // function call to open the scope
.ID("SideBar"),
.layout(.{
.direction = .TOP_TO_BOTTOM,
@ -50,10 +50,9 @@ if (clay.OPEN(&.{ // first function call to open the scope
.child_gap = 16,
}),
.rectangle(.{ .color = light_grey }),
})) {
defer clay.CLOSE(); // defered second function call to close the scope
})({
// Child elements here
}
});
```
## install
@ -81,10 +80,12 @@ compile_step.root_module.addImport("zclay", zclay_dep.module("zclay"));
2. Ask clay for how much static memory it needs using [clay.minMemorySize()](https://github.com/nicbarker/clay/blob/main/README.md#clay_minmemorysize), create an Arena for it to use with [clay.createArenaWithCapacityAndMemory(minMemorySize, memory)](https://github.com/nicbarker/clay/blob/main/README.md#clay_createarenawithcapacityandmemory), and initialize it with [clay.Initialize(arena)](https://github.com/nicbarker/clay/blob/main/README.md#clay_initialize).
```zig
const min_memory_size: u32 = clay.minMemorySize();
const min_memory_size: u32 = cl.minMemorySize();
const memory = try allocator.alloc(u8, min_memory_size);
defer allocator.free(memory);
const arena: clay.Arena = clay.createArenaWithCapacityAndMemory(min_memory_size, @ptrCast(memory));
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(memory);
_ = cl.initialize(arena, .{ .h = 1000, .w = 1000 }, .{});
cl.setMeasureTextFunction(renderer.measureText);
```
3. Provide a `measureText(text, config)` function with [clay.setMeasureTextFunction(function)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setmeasuretextfunction) so that clay can measure and wrap text.
@ -113,71 +114,66 @@ clay.setPointerState(.{
5. Call [clay.BeginLayout(screenWidth, screenHeight)](https://github.com/nicbarker/clay/blob/main/README.md#clay_beginlayout) and declare your layout using the provided functions.
```Zig
const light_grey: clay.Color = .{ 224, 215, 210, 255 };
const red: clay.Color = .{ 168, 66, 28, 255 };
const orange: clay.Color = .{ 225, 138, 50, 255 };
const white: clay.Color = .{ 250, 250, 255, 255 };
const light_grey: cl.Color = .{ 224, 215, 210, 255 };
const red: cl.Color = .{ 168, 66, 28, 255 };
const orange: cl.Color = .{ 225, 138, 50, 255 };
const white: cl.Color = .{ 250, 250, 255, 255 };
// Layout config is just a struct that can be declared statically, or inline
const sidebar_item_layout: clay.LayoutConfig = .{ .sizing = .{ .w = .grow, .h = .fixed(50) } };
const sidebar_item_layout: cl.LayoutConfig = .{ .sizing = .{ .w = .grow, .h = .fixed(50) } };
// Re-useable components are just normal functions
fn sidebarItemComponent(index: usize) void {
clay.singleElem(&.{
cl.UI(&.{
.IDI("SidebarBlob", @intCast(index)),
.layout(sidebar_item_layout),
.rectangle(.{ .color = orange }),
});
})({});
}
// An example function to begin the "root" of your layout tree
fn createLayout(profile_picture: *const rl.Texture2D) clay.ClayArray(clay.RenderCommand) {
clay.beginLayout();
if (clay.OPEN(&.{
fn createLayout(profile_picture: *const rl.Texture2D) cl.ClayArray(cl.RenderCommand) {
cl.beginLayout();
cl.UI(&.{
.ID("OuterContainer"),
.layout(.{ .direction = .LEFT_TO_RIGHT, .sizing = .grow, .padding = .all(16), .child_gap = 16 }),
.rectangle(.{ .color = white }),
})) {
defer clay.CLOSE();
if (clay.OPEN(&.{
})({
cl.UI(&.{
.ID("SideBar"),
.layout(.{
.direction = .TOP_TO_BOTTOM,
.sizing = .{ .h = .grow, .w = .fixed(300) },
.padding = .all(16),
.child_gap = 16,
.child_alignment = .{ .x = .CENTER, .y = .TOP },
.child_gap = 16,
}),
.rectangle(.{ .color = light_grey }),
})) {
defer clay.CLOSE();
if (clay.OPEN(&.{
})({
cl.UI(&.{
.ID("ProfilePictureOuter"),
.rectangle(.{ .color = red }),
.layout(.{ .sizing = .{ .w = .grow }, .padding = .all(16), .child_alignment = .{ .x = .LEFT, .y = .CENTER }, .child_gap = 16 }),
})) {
defer clay.CLOSE();
clay.singleElem(&.{
.rectangle(.{ .color = red }),
})({
cl.UI(&.{
.ID("ProfilePicture"),
.layout(.{ .sizing = .{ .h = .fixed(60), .w = .fixed(60) } }),
.image(.{ .source_dimensions = .{ .h = 60, .w = 60 }, .image_data = @ptrCast(profile_picture) }),
});
clay.text("Clay - UI Library", clay.Config.text(.{ .font_size = 24, .color = light_grey }));
}
})({});
cl.text("Clay - UI Library", .text(.{ .font_size = 24, .color = light_grey }));
});
for (0..5) |i| sidebarItemComponent(i);
}
});
if (clay.OPEN(&.{
cl.UI(&.{
.ID("MainContent"),
.layout(.{ .sizing = .grow }),
.rectangle(.{ .color = light_grey }),
})) {
defer clay.CLOSE();
})({
//...
}
}
return clay.endLayout();
});
});
return cl.endLayout();
}
```
@ -191,8 +187,8 @@ while (i < render_commands.length) : (i += 1) {
const render_command = clay.renderCommandArrayGet(render_commands, @intCast(i));
const bounding_box = render_command.bounding_box;
switch (render_command.command_type) {
.None => {},
.Text => {
.none => {},
.text => {
...
```

View file

@ -3,8 +3,8 @@
.version = "0.0.0",
.dependencies = .{
.clay = .{
.url = "https://github.com/nicbarker/clay/archive/refs/tags/v0.12.tar.gz",
.hash = "122055df7dec6a04ca71af24026f3e7a00b41f39c17c763ef6086adb2eddab3ac17d",
.url = "https://github.com/nicbarker/clay/archive/afba9f0de668c0b63fd94fbd62adb66485b9bc13.tar.gz",
.hash = "122032ed1ca5afaf896850aae7e1f007bf6cbc1d81bc981ed32ccbe0d932674f25f7",
},
},
.paths = .{

View file

@ -1,86 +0,0 @@
const std = @import("std");
const B = std.Build;
pub fn build(b: *B) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
{
const exe = b.addExecutable(.{
.name = "debug",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
addDependencies(exe, b, target, optimize);
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
{
const exe_unit_tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
addDependencies(exe_unit_tests, b, target, optimize);
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_exe_unit_tests.step);
}
{
const exe_check = b.addExecutable(.{
.name = "check",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
addDependencies(exe_check, b, target, optimize);
const tests_check = b.addTest(.{
.name = "check",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
addDependencies(tests_check, b, target, optimize);
const check = b.step("check", "Check if exe and tests compile");
check.dependOn(&exe_check.step);
check.dependOn(&tests_check.step);
}
}
fn addDependencies(
compile_step: *B.Step.Compile,
b: *B,
target: B.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
) void {
const zclay_dep = b.dependency("zclay", .{
.target = target,
.optimize = optimize,
});
const zclay = zclay_dep.module("zclay");
compile_step.root_module.addImport("zclay", zclay);
const raylib_dep = b.dependency("raylib-zig", .{
.target = target,
.optimize = optimize,
});
const raylib = raylib_dep.module("raylib");
compile_step.root_module.addImport("raylib", raylib);
const raylib_artifact = raylib_dep.artifact("raylib");
compile_step.linkLibrary(raylib_artifact);
}

View file

@ -1,20 +0,0 @@
.{
.name = "zig-exe-template",
.version = "0.0.0",
.dependencies = .{
.zclay = .{
.path = "../../",
},
.@"raylib-zig" = .{
.url = "https://github.com/Not-Nik/raylib-zig/archive/35332edacf2e03236220f12a8dd3410b1c39d9eb.tar.gz",
.hash = "1220c34fe472645e173a7168eb513ca8343af3c3f61b618daedda30ec3932b002637",
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
"LICENSE",
"README.md",
},
}

View file

@ -1,154 +0,0 @@
const std = @import("std");
const rl = @import("raylib");
const cl = @import("zclay");
const renderer = @import("raylib_render_clay.zig");
const FONT_ID_BODY_30 = 6;
const COLOR_LIGHT = cl.Color{ 244, 235, 230, 255 };
const COLOR_LIGHT_HOVER = cl.Color{ 224, 215, 210, 255 };
const COLOR_BUTTON_HOVER = cl.Color{ 238, 227, 225, 255 };
const COLOR_BROWN = cl.Color{ 61, 26, 5, 255 };
const COLOR_RED = cl.Color{ 168, 66, 28, 255 };
const COLOR_RED_HOVER = cl.Color{ 148, 46, 8, 255 };
const COLOR_ORANGE = cl.Color{ 225, 138, 50, 255 };
const COLOR_BLUE = cl.Color{ 111, 173, 162, 255 };
const COLOR_TEAL = cl.Color{ 111, 173, 162, 255 };
const COLOR_BLUE_DARK = cl.Color{ 2, 32, 82, 255 };
const COLOR_ZIG_LOGO = cl.Color{ 247, 164, 29, 255 };
// Colors for top stripe
const COLORS_TOP_BORDER = [_]cl.Color{
.{ 240, 213, 137, 255 },
.{ 236, 189, 80, 255 },
.{ 225, 138, 50, 255 },
.{ 223, 110, 44, 255 },
.{ 168, 66, 28, 255 },
};
const border_data = cl.BorderData{ .width = 2, .color = COLOR_RED };
var window_height: isize = 0;
var window_width: isize = 0;
fn LandingPageBlob_(index: u32, font_size: u16, font_id: u16, color: cl.Color, max_width: f32, text: []const u8) void {
// std.debug.print("\nBLOB START\n", .{});
if (cl.OPEN(&.{
.IDI("HeroBlob", index),
.layout(.{ .sizing = .{ .w = .growMinMax(.{ .max = max_width }) }, .padding = .all(16), .child_gap = 16, .child_alignment = .{ .y = .CENTER } }),
.border(.outside(color, 2, 0)),
})) {
defer cl.CLOSE();
cl.text(text, cl.Config.text(.{ .font_size = font_size, .font_id = font_id, .color = color }));
}
// std.debug.print("BLOB END\n\n", .{});
}
fn LandingPageBlob(index: u32, font_size: u16, font_id: u16, color: cl.Color, max_width: f32, text: []const u8) void {
// std.debug.print("\nBLOB START\n", .{});
cl.UI(&.{
.IDI("HeroBlob", index),
.layout(.{ .sizing = .{ .w = .growMinMax(.{ .max = max_width }) }, .padding = .all(16), .child_gap = 16, .child_alignment = .{ .y = .CENTER } }),
.border(.outside(color, 2, 0)),
})({
cl.text(text, cl.Config.text(.{ .font_size = font_size, .font_id = font_id, .color = color }));
});
// std.debug.print("BLOB END\n\n", .{});
}
fn createLayout() cl.ClayArray(cl.RenderCommand) {
cl.beginLayout();
// cl.UI(&.{
// .ID("ScrollContainerBackgroundRectangle"),
// .scroll(.{ .vertical = true }),
// .layout(.{ .sizing = .grow, .direction = .TOP_TO_BOTTOM, .child_gap = 10 }),
// .rectangle(.{ .color = COLOR_LIGHT }),
// })({
// LandingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 510, "The official Clay website recreated with zclay: clay-zig-bindings");
// @call(.always_inline, LandingPageBlob, .{ 2, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 510, "The official Clay website recreated with zclay: clay-zig-bindings" });
// });
if (cl.OPEN(&.{
.ID("ScrollContainerBackgroundRectangle"),
.scroll(.{ .vertical = true }),
.layout(.{ .sizing = .grow, .direction = .TOP_TO_BOTTOM, .child_gap = 10 }),
.rectangle(.{ .color = COLOR_LIGHT }),
})) {
defer cl.CLOSE();
// LandingPageBlob_(1, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 510, "The official Clay website recreated with zclay: clay-zig-bindings");
// std.debug.print("\n==\n\n", .{});
@call(.always_inline, LandingPageBlob_, .{ 2, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 510, "The official Clay website recreated with zclay: clay-zig-bindings" });
}
return cl.endLayout();
}
fn loadFont(file_data: ?[]const u8, font_id: u16, font_size: i32) void {
renderer.raylib_fonts[font_id] = rl.loadFontFromMemory(".ttf", file_data, font_size * 2, null);
rl.setTextureFilter(renderer.raylib_fonts[font_id].?.texture, .bilinear);
}
fn loadImage(comptime path: [:0]const u8) rl.Texture2D {
const texture = rl.loadTextureFromImage(rl.loadImageFromMemory(@ptrCast(std.fs.path.extension(path)), @embedFile(path)));
rl.setTextureFilter(texture, .bilinear);
return texture;
}
pub fn main() anyerror!void {
const allocator = std.heap.page_allocator;
// init clay
const min_memory_size: u32 = cl.minMemorySize();
const memory = try allocator.alloc(u8, min_memory_size);
defer allocator.free(memory);
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(min_memory_size, @ptrCast(memory));
cl.initialize(arena, .{ .h = 1000, .w = 1000 });
cl.setMeasureTextFunction(renderer.measureText);
// init raylib
rl.setConfigFlags(.{
.msaa_4x_hint = true,
.window_resizable = true,
});
rl.initWindow(1000, 1000, "Raylib zig Example");
rl.setWindowMinSize(300, 100);
rl.setTargetFPS(60);
// load assets
loadFont(@embedFile("resources/Quicksand-Semibold.ttf"), FONT_ID_BODY_30, 30);
var debug_mode_enabled = false;
while (!rl.windowShouldClose()) {
if (rl.isKeyPressed(.d)) {
debug_mode_enabled = !debug_mode_enabled;
cl.setDebugModeEnabled(debug_mode_enabled);
}
window_width = rl.getScreenWidth();
window_height = rl.getScreenHeight();
const mouse_pos = rl.getMousePosition();
cl.setPointerState(.{
.x = mouse_pos.x,
.y = mouse_pos.y,
}, rl.isMouseButtonDown(.left));
const scroll_delta = rl.getMouseWheelMoveV().multiply(.{ .x = 6, .y = 6 });
cl.updateScrollContainers(
false,
.{ .x = scroll_delta.x, .y = scroll_delta.y },
rl.getFrameTime(),
);
cl.setLayoutDimensions(.{
.w = @floatFromInt(window_width),
.h = @floatFromInt(window_height),
});
var render_commands = createLayout();
rl.beginDrawing();
renderer.clayRaylibRender(&render_commands, allocator);
rl.endDrawing();
// @panic("");
}
}

View file

@ -1,234 +0,0 @@
const std = @import("std");
const rl = @import("raylib");
const cl = @import("zclay");
const math = std.math;
pub fn clayColorToRaylibColor(color: cl.Color) rl.Color {
return rl.Color{
.r = @intFromFloat(color[0]),
.g = @intFromFloat(color[1]),
.b = @intFromFloat(color[2]),
.a = @intFromFloat(color[3]),
};
}
pub var raylib_fonts: [10]?rl.Font = .{null} ** 10;
pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), allocator: std.mem.Allocator) void {
var i: usize = 0;
while (i < render_commands.length) : (i += 1) {
const render_command = cl.renderCommandArrayGet(render_commands, @intCast(i));
const bounding_box = render_command.bounding_box;
switch (render_command.command_type) {
.None => {},
.Text => {
const text = render_command.text.chars[0..@intCast(render_command.text.length)];
const cloned = allocator.dupeZ(c_char, text) catch unreachable;
defer allocator.free(cloned);
const fontToUse: rl.Font = raylib_fonts[render_command.config.text_element_config.font_id].?;
rl.setTextLineSpacing(render_command.config.text_element_config.line_height);
rl.drawTextEx(
fontToUse,
@ptrCast(@alignCast(cloned.ptr)),
rl.Vector2{ .x = bounding_box.x, .y = bounding_box.y },
@floatFromInt(render_command.config.text_element_config.font_size),
@floatFromInt(render_command.config.text_element_config.letter_spacing),
clayColorToRaylibColor(render_command.config.text_element_config.color),
);
},
.Image => {
const image_texture: *const rl.Texture2D = @ptrCast(
@alignCast(render_command.config.image_element_config.image_data),
);
rl.drawTextureEx(
image_texture.*,
rl.Vector2{ .x = bounding_box.x, .y = bounding_box.y },
0,
bounding_box.width / @as(f32, @floatFromInt(image_texture.width)),
rl.Color.white,
);
},
.ScissorStart => {
rl.beginScissorMode(
@intFromFloat(math.round(bounding_box.x)),
@intFromFloat(math.round(bounding_box.y)),
@intFromFloat(math.round(bounding_box.width)),
@intFromFloat(math.round(bounding_box.height)),
);
},
.ScissorEnd => rl.endScissorMode(),
.Rectangle => {
const config = render_command.config.rectangle_element_config;
if (config.corner_radius.top_left > 0) {
const radius: f32 = (config.corner_radius.top_left * 2) / @min(bounding_box.width, bounding_box.height);
rl.drawRectangleRounded(
rl.Rectangle{
.x = bounding_box.x,
.y = bounding_box.y,
.width = bounding_box.width,
.height = bounding_box.height,
},
radius,
8,
clayColorToRaylibColor(config.color),
);
} else {
rl.drawRectangle(
@intFromFloat(bounding_box.x),
@intFromFloat(bounding_box.y),
@intFromFloat(bounding_box.width),
@intFromFloat(bounding_box.height),
clayColorToRaylibColor(config.color),
);
}
},
.Border => {
const config = render_command.config.border_element_config;
if (config.left.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x)),
@intFromFloat(math.round(bounding_box.y + config.corner_radius.top_left)),
@intCast(config.left.width),
@intFromFloat(math.round(bounding_box.height - config.corner_radius.top_left - config.corner_radius.bottom_left)),
clayColorToRaylibColor(config.left.color),
);
}
if (config.right.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x + bounding_box.width - @as(f32, @floatFromInt(config.right.width)))),
@intFromFloat(math.round(bounding_box.y + config.corner_radius.top_right)),
@intCast(config.right.width),
@intFromFloat(math.round(bounding_box.height - config.corner_radius.top_right - config.corner_radius.bottom_right)),
clayColorToRaylibColor(config.right.color),
);
}
if (config.top.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x + config.corner_radius.top_left)),
@intFromFloat(math.round(bounding_box.y)),
@intFromFloat(math.round(bounding_box.width - config.corner_radius.top_left - config.corner_radius.top_right)),
@intCast(config.top.width),
clayColorToRaylibColor(config.top.color),
);
}
if (config.bottom.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x + config.corner_radius.bottom_left)),
@intFromFloat(math.round(bounding_box.y + bounding_box.height - @as(f32, @floatFromInt(config.bottom.width)))),
@intFromFloat(math.round(bounding_box.width - config.corner_radius.bottom_left - config.corner_radius.bottom_right)),
@intCast(config.bottom.width),
clayColorToRaylibColor(config.bottom.color),
);
}
if (config.corner_radius.top_left > 0) {
rl.drawRing(
rl.Vector2{
.x = math.round(bounding_box.x + config.corner_radius.top_left),
.y = math.round(bounding_box.y + config.corner_radius.top_left),
},
math.round(config.corner_radius.top_left - @as(f32, @floatFromInt(config.top.width))),
config.corner_radius.top_left,
180,
270,
10,
clayColorToRaylibColor(config.top.color),
);
}
if (config.corner_radius.top_right > 0) {
rl.drawRing(
rl.Vector2{
.x = math.round(bounding_box.x + bounding_box.width - config.corner_radius.top_right),
.y = math.round(bounding_box.y + config.corner_radius.top_right),
},
math.round(config.corner_radius.top_right - @as(f32, @floatFromInt(config.top.width))),
config.corner_radius.top_right,
270,
360,
10,
clayColorToRaylibColor(config.top.color),
);
}
if (config.corner_radius.bottom_left > 0) {
rl.drawRing(
rl.Vector2{
.x = math.round(bounding_box.x + config.corner_radius.bottom_left),
.y = math.round(bounding_box.y + bounding_box.height - config.corner_radius.bottom_left),
},
math.round(config.corner_radius.bottom_left - @as(f32, @floatFromInt(config.top.width))),
config.corner_radius.bottom_left,
90,
180,
10,
clayColorToRaylibColor(config.bottom.color),
);
}
if (config.corner_radius.bottom_right > 0) {
rl.drawRing(
rl.Vector2{
.x = math.round(bounding_box.x + bounding_box.width - config.corner_radius.bottom_right),
.y = math.round(bounding_box.y + bounding_box.height - config.corner_radius.bottom_right),
},
math.round(config.corner_radius.bottom_right - @as(f32, @floatFromInt(config.top.width))),
config.corner_radius.bottom_right,
0.1,
90,
10,
clayColorToRaylibColor(config.bottom.color),
);
}
},
.Custom => {
// Implement custom element rendering here
},
}
}
}
pub fn measureText(clay_text: []const u8, config: *cl.TextElementConfig) cl.Dimensions {
const font = raylib_fonts[config.font_id].?;
const text: []const u8 = clay_text;
const font_size: f32 = @floatFromInt(config.font_size);
const letter_spacing: f32 = @floatFromInt(config.letter_spacing);
const line_height = config.line_height;
var temp_byte_counter: usize = 0;
var byte_counter: usize = 0;
var text_width: f32 = 0.0;
var temp_text_width: f32 = 0.0;
var text_height: f32 = font_size;
const scale_factor: f32 = font_size / @as(f32, @floatFromInt(font.baseSize));
var utf8 = std.unicode.Utf8View.initUnchecked(text).iterator();
while (utf8.nextCodepoint()) |codepoint| {
byte_counter += std.unicode.utf8CodepointSequenceLength(codepoint) catch 1;
const index: usize = @intCast(
rl.getGlyphIndex(font, @as(i32, @intCast(codepoint))),
);
if (codepoint != '\n') {
if (font.glyphs[index].advanceX != 0) {
text_width += @floatFromInt(font.glyphs[index].advanceX);
} else {
text_width += font.recs[index].width + @as(f32, @floatFromInt(font.glyphs[index].offsetX));
}
} else {
if (temp_text_width < text_width) temp_text_width = text_width;
byte_counter = 0;
text_width = 0;
text_height += font_size + @as(f32, @floatFromInt(line_height));
}
if (temp_byte_counter < byte_counter) temp_byte_counter = byte_counter;
}
if (temp_text_width < text_width) temp_text_width = text_width;
std.debug.print("\"{s}\" => .w = {d}\n", .{ clay_text, temp_text_width * scale_factor + (@as(f32, @floatFromInt(temp_byte_counter)) - 1) * letter_spacing });
return cl.Dimensions{
.h = text_height,
.w = temp_text_width * scale_factor + (@as(f32, @floatFromInt(temp_byte_counter)) - 1) * letter_spacing,
};
}

View file

@ -54,7 +54,7 @@ const border_data = cl.BorderData{ .width = 2, .color = COLOR_RED };
var window_height: isize = 0;
var window_width: isize = 0;
fn LandingPageBlob(index: u32, font_size: u16, font_id: u16, color: cl.Color, image_size: f32, max_width: f32, text: []const u8, image: *rl.Texture2D) void {
fn landingPageBlob(index: u32, font_size: u16, font_id: u16, color: cl.Color, image_size: f32, max_width: f32, text: []const u8, image: *rl.Texture2D) void {
cl.UI(&.{
.IDI("HeroBlob", index),
.layout(.{ .sizing = .{ .w = .growMinMax(.{ .max = max_width }) }, .padding = .all(16), .child_gap = 16, .child_alignment = .{ .y = .CENTER } }),
@ -65,7 +65,7 @@ fn LandingPageBlob(index: u32, font_size: u16, font_id: u16, color: cl.Color, im
.layout(.{ .sizing = .{ .w = .fixed(image_size) } }),
.image(.{ .image_data = image, .source_dimensions = .{ .w = 128, .h = 128 } }),
})({});
cl.text(text, cl.Config.text(.{ .font_size = font_size, .font_id = font_id, .color = color }));
cl.text(text, .text(.{ .font_size = font_size, .font_id = font_id, .color = color }));
});
}
@ -90,7 +90,7 @@ fn landingPageDesktop() void {
}),
.border(.{ .left = border_data, .right = border_data }),
})({
LandingPageBlob(0, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 64, 510, "The official Clay website recreated with zclay: clay-zig-bindings", &zig_logo_image6);
landingPageBlob(0, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 64, 510, "The official Clay website recreated with zclay: clay-zig-bindings", &zig_logo_image6);
cl.UI(&.{
.ID("ClayPresentation"),
@ -106,12 +106,12 @@ fn landingPageDesktop() void {
})({
cl.text(
"Clay is a flex-box style UI auto layout library in C, with declarative syntax and microsecond performance.",
cl.Config.text(.{ .font_size = 56, .font_id = FONT_ID_TITLE_56, .color = COLOR_RED }),
.text(.{ .font_size = 56, .font_id = FONT_ID_TITLE_56, .color = COLOR_RED }),
);
cl.UI(&.{ .ID("ClayPresentation_Spacer"), .layout(.{ .sizing = .{ .w = .grow, .h = .fixed(32) } }) })({});
cl.text(
"Clay is laying out this webpage right now!",
cl.Config.text(.{ .font_size = 36, .font_id = FONT_ID_BODY_36, .color = COLOR_ORANGE }),
.text(.{ .font_size = 36, .font_id = FONT_ID_BODY_36, .color = COLOR_ORANGE }),
);
});
@ -119,11 +119,11 @@ fn landingPageDesktop() void {
.ID("HeroImageOuter"),
.layout(.{ .sizing = .{ .w = .percent(0.45) }, .direction = .TOP_TO_BOTTOM, .child_alignment = .{ .x = .CENTER }, .child_gap = 16 }),
})({
LandingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_5, 32, 480, "High performance", &checkImage5);
LandingPageBlob(2, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_4, 32, 480, "Flexbox-style responsive layout", &checkImage4);
LandingPageBlob(3, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_3, 32, 480, "Declarative syntax", &checkImage3);
LandingPageBlob(4, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_2, 32, 480, "Single .h file for C/C++", &checkImage2);
LandingPageBlob(5, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_1, 32, 480, "Compile to 15kb .wasm", &checkImage1);
landingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_5, 32, 480, "High performance", &checkImage5);
landingPageBlob(2, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_4, 32, 480, "Flexbox-style responsive layout", &checkImage4);
landingPageBlob(3, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_3, 32, 480, "Declarative syntax", &checkImage3);
landingPageBlob(4, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_2, 32, 480, "Single .h file for C/C++", &checkImage2);
landingPageBlob(5, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_1, 32, 480, "Compile to 15kb .wasm", &checkImage1);
});
});
});
@ -141,19 +141,19 @@ fn landingPageMobile() void {
.child_gap = 16,
}),
})({
LandingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 64, 510, "The official Clay website recreated with zclay: clay-zig-bindings", &zig_logo_image6);
landingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_ZIG_LOGO, 64, 510, "The official Clay website recreated with zclay: clay-zig-bindings", &zig_logo_image6);
cl.UI(&.{
.ID("LeftText"),
.layout(.{ .sizing = .{ .w = .grow }, .direction = .TOP_TO_BOTTOM, .child_gap = 8 }),
})({
cl.text(
"Clay is a flex-box style UI auto layout library in C, with declarative syntax and microsecond performance.",
cl.Config.text(.{ .font_size = 56, .font_id = FONT_ID_TITLE_56, .color = COLOR_RED }),
.text(.{ .font_size = 56, .font_id = FONT_ID_TITLE_56, .color = COLOR_RED }),
);
cl.UI(&.{ .ID("LeftText_Spacer"), .layout(.{ .sizing = .{ .w = .grow, .h = .fixed(32) } }) })({});
cl.text(
"Clay is laying out this webpage .right now!",
cl.Config.text(.{ .font_size = 36, .font_id = FONT_ID_BODY_36, .color = COLOR_ORANGE }),
.text(.{ .font_size = 36, .font_id = FONT_ID_BODY_36, .color = COLOR_ORANGE }),
);
});
@ -161,11 +161,11 @@ fn landingPageMobile() void {
.ID("HeroImageOuter"),
.layout(.{ .sizing = .{ .w = .grow }, .direction = .TOP_TO_BOTTOM, .child_alignment = .{ .x = .CENTER }, .child_gap = 16 }),
})({
LandingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_5, 32, 480, "High performance", &checkImage5);
LandingPageBlob(2, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_4, 32, 480, "Flexbox-style responsive layout", &checkImage4);
LandingPageBlob(3, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_3, 32, 480, "Declarative syntax", &checkImage3);
LandingPageBlob(4, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_2, 32, 480, "Single .h file for C/C++", &checkImage2);
LandingPageBlob(5, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_1, 32, 480, "Compile to 15kb .wasm", &checkImage1);
landingPageBlob(1, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_5, 32, 480, "High performance", &checkImage5);
landingPageBlob(2, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_4, 32, 480, "Flexbox-style responsive layout", &checkImage4);
landingPageBlob(3, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_3, 32, 480, "Declarative syntax", &checkImage3);
landingPageBlob(4, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_2, 32, 480, "Single .h file for C/C++", &checkImage2);
landingPageBlob(5, 30, FONT_ID_BODY_30, COLOR_BLOB_BORDER_1, 32, 480, "Compile to 15kb .wasm", &checkImage1);
});
});
}
@ -399,7 +399,7 @@ fn rendererPage(title_text_config: cl.TextElementConfig, width_sizing: cl.Sizing
.text(.{ .font_size = 28, .font_id = FONT_ID_BODY_36, .color = COLOR_RED }),
);
cl.text(
"There's even an HTML renderer - you're looking at it .right now!",
"There's even an HTML renderer - you're looking at it right now!",
.text(.{ .font_size = 28, .font_id = FONT_ID_BODY_36, .color = COLOR_RED }),
);
});
@ -468,7 +468,7 @@ fn createLayout(lerp_value: f32) cl.ClayArray(cl.RenderCommand) {
.child_gap = 24,
}),
})({
cl.text("Clay", cl.Config.text(.{
cl.text("Clay", .text(.{
.font_id = FONT_ID_BODY_24,
.font_size = 24,
.color = .{ 61, 26, 5, 255 },
@ -477,10 +477,10 @@ fn createLayout(lerp_value: f32) cl.ClayArray(cl.RenderCommand) {
if (!mobileScreen) {
cl.UI(&.{ .ID("LinkExamplesInner"), .layout(.{}), .rectangle(.{ .color = .{ 0, 0, 0, 0 } }) })({
cl.text("Examples", cl.Config.text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }));
cl.text("Examples", .text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }));
});
cl.UI(&.{ .ID("LinkDocsOuter"), .layout(.{}), .rectangle(.{ .color = .{ 0, 0, 0, 0 } }) })({
cl.text("Docs", cl.Config.text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }));
cl.text("Docs", .text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }));
});
}
@ -495,7 +495,7 @@ fn createLayout(lerp_value: f32) cl.ClayArray(cl.RenderCommand) {
})({
cl.text(
"Github",
cl.Config.text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }),
.text(.{ .font_id = FONT_ID_BODY_24, .font_size = 24, .color = .{ 61, 26, 5, 255 } }),
);
});
});
@ -550,8 +550,8 @@ pub fn main() anyerror!void {
const min_memory_size: u32 = cl.minMemorySize();
const memory = try allocator.alloc(u8, min_memory_size);
defer allocator.free(memory);
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(min_memory_size, @ptrCast(memory));
cl.initialize(arena, .{ .h = 1000, .w = 1000 });
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(memory);
_ = cl.initialize(arena, .{ .h = 1000, .w = 1000 }, .{});
cl.setMeasureTextFunction(renderer.measureText);
// init raylib

View file

@ -20,25 +20,25 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
const render_command = cl.renderCommandArrayGet(render_commands, @intCast(i));
const bounding_box = render_command.bounding_box;
switch (render_command.command_type) {
.None => {},
.Text => {
.none => {},
.text => {
const text = render_command.text.chars[0..@intCast(render_command.text.length)];
const cloned = allocator.dupeZ(c_char, text) catch unreachable;
const cloned = allocator.dupeZ(u8, text) catch unreachable;
defer allocator.free(cloned);
const fontToUse: rl.Font = raylib_fonts[render_command.config.text_element_config.font_id].?;
rl.setTextLineSpacing(render_command.config.text_element_config.line_height);
const fontToUse: rl.Font = raylib_fonts[render_command.config.text_config.font_id].?;
rl.setTextLineSpacing(render_command.config.text_config.line_height);
rl.drawTextEx(
fontToUse,
@ptrCast(@alignCast(cloned.ptr)),
rl.Vector2{ .x = bounding_box.x, .y = bounding_box.y },
@floatFromInt(render_command.config.text_element_config.font_size),
@floatFromInt(render_command.config.text_element_config.letter_spacing),
clayColorToRaylibColor(render_command.config.text_element_config.color),
@floatFromInt(render_command.config.text_config.font_size),
@floatFromInt(render_command.config.text_config.letter_spacing),
clayColorToRaylibColor(render_command.config.text_config.color),
);
},
.Image => {
.image => {
const image_texture: *const rl.Texture2D = @ptrCast(
@alignCast(render_command.config.image_element_config.image_data),
@alignCast(render_command.config.image_config.image_data),
);
rl.drawTextureEx(
image_texture.*,
@ -48,7 +48,7 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
rl.Color.white,
);
},
.ScissorStart => {
.scissor_start => {
rl.beginScissorMode(
@intFromFloat(math.round(bounding_box.x)),
@intFromFloat(math.round(bounding_box.y)),
@ -56,9 +56,9 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
@intFromFloat(math.round(bounding_box.height)),
);
},
.ScissorEnd => rl.endScissorMode(),
.Rectangle => {
const config = render_command.config.rectangle_element_config;
.scissor_end => rl.endScissorMode(),
.rectangle => {
const config = render_command.config.rectangle_config;
if (config.corner_radius.top_left > 0) {
const radius: f32 = (config.corner_radius.top_left * 2) / @min(bounding_box.width, bounding_box.height);
rl.drawRectangleRounded(
@ -82,8 +82,8 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
);
}
},
.Border => {
const config = render_command.config.border_element_config;
.border => {
const config = render_command.config.border_config;
if (config.left.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x)),
@ -178,7 +178,7 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
);
}
},
.Custom => {
.custom => {
// Implement custom element rendering here
},
}

View file

@ -12,23 +12,22 @@ const sidebar_item_layout: cl.LayoutConfig = .{ .sizing = .{ .w = .grow, .h = .f
// Re-useable components are just normal functions
fn sidebarItemComponent(index: usize) void {
cl.singleElem(&.{
cl.UI(&.{
.IDI("SidebarBlob", @intCast(index)),
.layout(sidebar_item_layout),
.rectangle(.{ .color = orange }),
});
})({});
}
// An example function to begin the "root" of your layout tree
fn createLayout(profile_picture: *const rl.Texture2D) cl.ClayArray(cl.RenderCommand) {
cl.beginLayout();
if (cl.OPEN(&.{
cl.UI(&.{
.ID("OuterContainer"),
.layout(.{ .direction = .LEFT_TO_RIGHT, .sizing = .grow, .padding = .all(16), .child_gap = 16 }),
.rectangle(.{ .color = white }),
})) {
defer cl.CLOSE();
if (cl.OPEN(&.{
})({
cl.UI(&.{
.ID("SideBar"),
.layout(.{
.direction = .TOP_TO_BOTTOM,
@ -38,34 +37,31 @@ fn createLayout(profile_picture: *const rl.Texture2D) cl.ClayArray(cl.RenderComm
.child_gap = 16,
}),
.rectangle(.{ .color = light_grey }),
})) {
defer cl.CLOSE();
if (cl.OPEN(&.{
})({
cl.UI(&.{
.ID("ProfilePictureOuter"),
.layout(.{ .sizing = .{ .w = .grow }, .padding = .all(16), .child_alignment = .{ .x = .LEFT, .y = .CENTER }, .child_gap = 16 }),
.rectangle(.{ .color = red }),
})) {
defer cl.CLOSE();
cl.singleElem(&.{
})({
cl.UI(&.{
.ID("ProfilePicture"),
.layout(.{ .sizing = .{ .h = .fixed(60), .w = .fixed(60) } }),
.image(.{ .source_dimensions = .{ .h = 60, .w = 60 }, .image_data = @ptrCast(profile_picture) }),
});
cl.text("Clay - UI Library", cl.Config.text(.{ .font_size = 24, .color = light_grey }));
}
})({});
cl.text("Clay - UI Library", .text(.{ .font_size = 24, .color = light_grey }));
});
for (0..5) |i| sidebarItemComponent(i);
}
});
if (cl.OPEN(&.{
cl.UI(&.{
.ID("MainContent"),
.layout(.{ .sizing = .grow }),
.rectangle(.{ .color = light_grey }),
})) {
defer cl.CLOSE();
})({
//...
}
}
});
});
return cl.endLayout();
}
@ -87,8 +83,8 @@ pub fn main() anyerror!void {
const min_memory_size: u32 = cl.minMemorySize();
const memory = try allocator.alloc(u8, min_memory_size);
defer allocator.free(memory);
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(min_memory_size, @ptrCast(memory));
cl.initialize(arena, .{ .h = 1000, .w = 1000 });
const arena: cl.Arena = cl.createArenaWithCapacityAndMemory(memory);
_ = cl.initialize(arena, .{ .h = 1000, .w = 1000 }, .{});
cl.setMeasureTextFunction(renderer.measureText);
// init raylib

View file

@ -20,25 +20,25 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
const render_command = cl.renderCommandArrayGet(render_commands, @intCast(i));
const bounding_box = render_command.bounding_box;
switch (render_command.command_type) {
.None => {},
.Text => {
.none => {},
.text => {
const text = render_command.text.chars[0..@intCast(render_command.text.length)];
const cloned = allocator.dupeZ(c_char, text) catch unreachable;
const cloned = allocator.dupeZ(u8, text) catch unreachable;
defer allocator.free(cloned);
const fontToUse: rl.Font = raylib_fonts[render_command.config.text_element_config.font_id].?;
rl.setTextLineSpacing(render_command.config.text_element_config.line_height);
const fontToUse: rl.Font = raylib_fonts[render_command.config.text_config.font_id].?;
rl.setTextLineSpacing(render_command.config.text_config.line_height);
rl.drawTextEx(
fontToUse,
@ptrCast(@alignCast(cloned.ptr)),
rl.Vector2{ .x = bounding_box.x, .y = bounding_box.y },
@floatFromInt(render_command.config.text_element_config.font_size),
@floatFromInt(render_command.config.text_element_config.letter_spacing),
clayColorToRaylibColor(render_command.config.text_element_config.color),
@floatFromInt(render_command.config.text_config.font_size),
@floatFromInt(render_command.config.text_config.letter_spacing),
clayColorToRaylibColor(render_command.config.text_config.color),
);
},
.Image => {
.image => {
const image_texture: *const rl.Texture2D = @ptrCast(
@alignCast(render_command.config.image_element_config.image_data),
@alignCast(render_command.config.image_config.image_data),
);
rl.drawTextureEx(
image_texture.*,
@ -48,7 +48,7 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
rl.Color.white,
);
},
.ScissorStart => {
.scissor_start => {
rl.beginScissorMode(
@intFromFloat(math.round(bounding_box.x)),
@intFromFloat(math.round(bounding_box.y)),
@ -56,9 +56,9 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
@intFromFloat(math.round(bounding_box.height)),
);
},
.ScissorEnd => rl.endScissorMode(),
.Rectangle => {
const config = render_command.config.rectangle_element_config;
.scissor_end => rl.endScissorMode(),
.rectangle => {
const config = render_command.config.rectangle_config;
if (config.corner_radius.top_left > 0) {
const radius: f32 = (config.corner_radius.top_left * 2) / @min(bounding_box.width, bounding_box.height);
rl.drawRectangleRounded(
@ -82,8 +82,8 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
);
}
},
.Border => {
const config = render_command.config.border_element_config;
.border => {
const config = render_command.config.border_config;
if (config.left.width > 0) {
rl.drawRectangle(
@intFromFloat(math.round(bounding_box.x)),
@ -178,7 +178,7 @@ pub fn clayRaylibRender(render_commands: *cl.ClayArray(cl.RenderCommand), alloca
);
}
},
.Custom => {
.custom => {
// Implement custom element rendering here
},
}
@ -227,6 +227,6 @@ pub fn measureText(clay_text: []const u8, config: *cl.TextElementConfig) cl.Dime
return cl.Dimensions{
.h = text_height,
.w = temp_text_width * scale_factor + @as(f32, @floatFromInt(temp_byte_counter - 1)) * letter_spacing,
.w = temp_text_width * scale_factor + (@as(f32, @floatFromInt(temp_byte_counter)) - 1) * letter_spacing,
};
}

View file

@ -4,48 +4,70 @@ const builtin = @import("builtin");
/// for direct calls to the clay c library
pub const cdefs = struct {
// TODO: should use @extern instead but zls does not yet support it well and that is more important
extern "c" fn Clay_MinMemorySize() u32;
extern "c" fn Clay_CreateArenaWithCapacityAndMemory(capacity: u32, offset: [*c]u8) Arena;
extern "c" fn Clay_SetPointerState(position: Vector2, pointer_down: bool) void;
extern "c" fn Clay_Initialize(arena: Arena, layout_dimensions: Dimensions) void;
extern "c" fn Clay_UpdateScrollContainers(is_pointer_active: bool, scroll_delta: Vector2, delta_time: f32) void;
extern "c" fn Clay_SetLayoutDimensions(dimensions: Dimensions) void;
extern "c" fn Clay_BeginLayout() void;
extern "c" fn Clay_EndLayout() ClayArray(RenderCommand);
extern "c" fn Clay_PointerOver(id: ElementId) bool;
extern "c" fn Clay_GetElementId(id: String) ElementId;
extern "c" fn Clay_GetScrollContainerData(id: ElementId) ScrollContainerData;
extern "c" fn Clay_SetMeasureTextFunction(measureTextFunction: *const fn (*String, *TextElementConfig) callconv(.C) Dimensions) void;
extern "c" fn Clay_RenderCommandArray_Get(array: *ClayArray(RenderCommand), index: i32) *RenderCommand;
extern "c" fn Clay_SetDebugModeEnabled(enabled: bool) void;
pub extern fn Clay_MinMemorySize() u32;
pub extern fn Clay_CreateArenaWithCapacityAndMemory(capacity: u32, offset: [*c]u8) Arena;
pub extern fn Clay_SetPointerState(position: Vector2, pointerDown: bool) void;
pub extern fn Clay_Initialize(arena: Arena, layoutDimensions: Dimensions, errorHandler: ErrorHandler) *Context;
pub extern fn Clay_GetCurrentContext() *Context;
pub extern fn Clay_SetCurrentContext(context: *Context) void;
pub extern fn Clay_UpdateScrollContainers(enableDragScrolling: bool, scrollDelta: Vector2, deltaTime: f32) void;
pub extern fn Clay_SetLayoutDimensions(dimensions: Dimensions) void;
pub extern fn Clay_BeginLayout() void;
pub extern fn Clay_EndLayout() ClayArray(RenderCommand);
pub extern fn Clay_GetElementId(idString: String) ElementId;
pub extern fn Clay_GetElementIdWithIndex(idString: String, index: u32) ElementId;
pub extern fn Clay_Hovered() bool;
pub extern fn Clay_OnHover(onHoverFunction: ?*const fn (ElementId, PointerData, isize) callconv(.c) void, userData: isize) void;
pub extern fn Clay_PointerOver(elementId: ElementId) bool;
pub extern fn Clay_GetScrollContainerData(id: ElementId) ScrollContainerData;
pub extern fn Clay_SetMeasureTextFunction(measureTextFunction: *const fn (*String, *TextElementConfig) callconv(.c) Dimensions) void;
pub extern fn Clay_SetQueryScrollOffsetFunction(queryScrollOffsetFunction: ?*const fn (u32) callconv(.c) Vector2) void;
pub extern fn Clay_RenderCommandArray_Get(array: *ClayArray(RenderCommand), index: i32) *RenderCommand;
pub extern fn Clay_SetDebugModeEnabled(enabled: bool) void;
pub extern fn Clay_IsDebugModeEnabled() bool;
pub extern fn Clay_SetCullingEnabled(enabled: bool) void;
pub extern fn Clay_GetMaxElementCount() i32;
pub extern fn Clay_SetMaxElementCount(maxElementCount: i32) void;
pub extern fn Clay_GetMaxMeasureTextCacheWordCount() i32;
pub extern fn Clay_SetMaxMeasureTextCacheWordCount(maxMeasureTextCacheWordCount: i32) void;
pub extern fn Clay_ResetMeasureTextCache() void;
extern "c" fn Clay__OpenElement() void;
extern "c" fn Clay__CloseElement() void;
extern "c" fn Clay__ElementPostConfiguration() void;
extern "c" fn Clay__OpenTextElement(text: String, textConfig: *TextElementConfig) void;
extern "c" fn Clay__AttachId(id: ElementId) void;
extern "c" fn Clay__AttachLayoutConfig(layoutConfig: *LayoutConfig) void;
extern "c" fn Clay__AttachElementConfig(config: *anyopaque, type: ElementConfigType) void;
extern "c" fn Clay__StoreLayoutConfig(config: LayoutConfig) *LayoutConfig;
extern "c" fn Clay__StoreRectangleElementConfig(config: RectangleElementConfig) *RectangleElementConfig;
extern "c" fn Clay__StoreTextElementConfig(config: TextElementConfig) *TextElementConfig;
extern "c" fn Clay__StoreImageElementConfig(config: ImageElementConfig) *ImageElementConfig;
extern "c" fn Clay__StoreFloatingElementConfig(config: FloatingElementConfig) *FloatingElementConfig;
extern "c" fn Clay__StoreCustomElementConfig(config: CustomElementConfig) *CustomElementConfig;
extern "c" fn Clay__StoreScrollElementConfig(config: ScrollElementConfig) *ScrollElementConfig;
extern "c" fn Clay__StoreBorderElementConfig(config: BorderElementConfig) *BorderElementConfig;
extern "c" fn Clay__HashString(toHash: String, index: u32, seed: u32) ElementId;
extern "c" fn Clay__GetOpenLayoutElementId() u32;
pub extern fn Clay__OpenElement() void;
pub extern fn Clay__CloseElement() void;
pub extern fn Clay__StoreLayoutConfig(config: LayoutConfig) *LayoutConfig;
pub extern fn Clay__ElementPostConfiguration() void;
pub extern fn Clay__AttachId(id: ElementId) void;
pub extern fn Clay__AttachLayoutConfig(config: *LayoutConfig) void;
pub extern fn Clay__AttachElementConfig(config: ElementConfigUnion, @"type": ElementConfigType) void;
pub extern fn Clay__StoreRectangleElementConfig(config: RectangleElementConfig) *RectangleElementConfig;
pub extern fn Clay__StoreTextElementConfig(config: TextElementConfig) *TextElementConfig;
pub extern fn Clay__StoreImageElementConfig(config: ImageElementConfig) *ImageElementConfig;
pub extern fn Clay__StoreFloatingElementConfig(config: FloatingElementConfig) *FloatingElementConfig;
pub extern fn Clay__StoreCustomElementConfig(config: CustomElementConfig) *CustomElementConfig;
pub extern fn Clay__StoreScrollElementConfig(config: ScrollElementConfig) *ScrollElementConfig;
pub extern fn Clay__StoreBorderElementConfig(config: BorderElementConfig) *BorderElementConfig;
pub extern fn Clay__HashString(key: String, offset: u32, seed: u32) ElementId;
pub extern fn Clay__OpenTextElement(text: String, textConfig: *TextElementConfig) void;
pub extern fn Clay__GetParentElementId() u32;
pub extern var CLAY_LAYOUT_DEFAULT: LayoutConfig;
pub extern var Clay__debugViewHighlightColor: Color;
pub extern var Clay__debugViewWidth: u32;
};
pub const EnumBackingType = u8;
pub const String = extern struct {
length: c_int,
chars: [*c]c_char,
length: i32,
chars: [*:0]const u8,
};
pub const Vector2 = extern struct {
x: f32,
y: f32,
pub const Context = opaque {};
pub const Arena = extern struct {
nextAllocation: usize,
capacity: usize,
memory: [*]u8,
};
pub const Dimensions = extern struct {
@ -53,13 +75,13 @@ pub const Dimensions = extern struct {
h: f32,
};
pub const Arena = extern struct {
label: String,
next_allocation: u64,
capacity: u64,
memory: [*c]c_char,
pub const Vector2 = extern struct {
x: f32,
y: f32,
};
pub const Color = [4]f32;
pub const BoundingBox = extern struct {
x: f32,
y: f32,
@ -67,7 +89,177 @@ pub const BoundingBox = extern struct {
height: f32,
};
pub const Color = [4]f32;
pub const SizingMinMax = extern struct {
min: f32 = 0,
max: f32 = 0,
};
const SizingConstraint = extern union {
minmax: SizingMinMax,
percent: f32,
};
pub const SizingAxis = extern struct {
// Note: `min` is used for CLAY_SIZING_PERCENT, slightly different to clay.h due to lack of C anonymous unions
size: SizingConstraint = .{ .minmax = .{} },
type: SizingType = .FIT,
pub const grow = SizingAxis{ .type = .GROW, .size = .{ .minmax = .{ .min = 0, .max = 0 } } };
pub const fit = SizingAxis{ .type = .FIT, .size = .{ .minmax = .{ .min = 0, .max = 0 } } };
pub fn growMinMax(size_minmax: SizingMinMax) SizingAxis {
return .{ .type = .GROW, .size = .{ .minmax = size_minmax } };
}
pub fn fitMinMax(size_minmax: SizingMinMax) SizingAxis {
return .{ .type = .FIT, .size = .{ .minmax = size_minmax } };
}
pub fn fixed(size: f32) SizingAxis {
return .{ .type = .FIXED, .size = .{ .minmax = .{ .max = size, .min = size } } };
}
pub fn percent(size_percent: f32) SizingAxis {
return .{ .type = .PERCENT, .size = .{ .percent = size_percent } };
}
};
pub const Sizing = extern struct {
/// width
w: SizingAxis = .{},
/// height
h: SizingAxis = .{},
pub const grow = Sizing{ .h = .grow, .w = .grow };
};
pub const Padding = extern struct {
x: u16 = 0,
y: u16 = 0,
pub fn all(size: u16) Padding {
return Padding{
.x = size,
.y = size,
};
}
};
pub const TextElementConfigWrapMode = enum(c_uint) {
words = 0,
newlines = 1,
none = 2,
};
pub const TextElementConfig = extern struct {
color: Color = .{ 0, 0, 0, 255 },
font_id: u16 = 0,
font_size: u16 = 20,
letter_spacing: u16 = 0,
line_height: u16 = 0,
wrap_mode: TextElementConfigWrapMode = .words,
};
pub const FloatingAttachPointType = enum(u8) {
LEFT_TOP = 0,
LEFT_CENTER = 1,
LEFT_BOTTOM = 2,
CENTER_TOP = 3,
CENTER_CENTER = 4,
CENTER_BOTTOM = 5,
RIGHT_TOP = 6,
RIGHT_CENTER = 7,
RIGHT_BOTTOM = 8,
};
pub const FloatingAttachPoints = extern struct {
element: FloatingAttachPointType,
parent: FloatingAttachPointType,
};
pub const PointerCaptureMode = enum(c_uint) {
CAPTURE = 0,
PASSTHROUGH = 1,
};
pub const FloatingElementConfig = extern struct {
offset: Vector2,
expand: Dimensions,
zIndex: u16,
parentId: u32,
attachment: FloatingAttachPoints,
pointerCaptureMode: PointerCaptureMode,
};
pub const Border = extern struct {
width: u32,
color: Color,
};
pub const ElementConfigUnion = extern union {
rectangle_config: *RectangleElementConfig,
text_config: *TextElementConfig,
image_config: *ImageElementConfig,
floating_config: *FloatingElementConfig,
custom_config: *CustomElementConfig,
scroll_config: *ScrollElementConfig,
border_config: *BorderElementConfig,
};
pub const ElementConfig = extern struct {
type: ElementConfigType,
config: ElementConfigUnion,
};
pub const RenderCommandType = enum(u8) {
none = 0,
rectangle = 1,
border = 2,
text = 3,
image = 4,
scissor_start = 5,
scissor_end = 6,
custom = 7,
};
pub const RenderCommandArray = extern struct {
capacity: i32,
length: i32,
internalArray: [*]RenderCommand,
};
pub const PointerDataInteractionState = enum(c_uint) {
pressed_this_frame = 0,
pressed = 1,
released_this_frame = 2,
released = 3,
};
pub const PointerData = extern struct {
position: Vector2,
state: PointerDataInteractionState,
};
pub const ErrorType = enum(c_uint) {
text_measurement_function_not_provided = 0,
arena_capacity_exceeded = 1,
elements_capacity_exceeded = 2,
text_measurement_capacity_exceeded = 3,
duplicate_id = 4,
floating_container_parent_not_found = 5,
internal_error = 6,
};
pub const ErrorData = extern struct {
errorType: ErrorType,
errorText: String,
userData: usize,
};
pub const ErrorHandler = extern struct {
error_handler_function: ?*const fn (ErrorData) callconv(.c) void = null,
user_data: usize = 0,
};
pub const CornerRadius = extern struct {
top_left: f32 = 0,
@ -97,50 +289,6 @@ pub const ElementId = extern struct {
string_id: String,
};
pub const EnumBackingType = u8;
pub const RenderCommandType = enum(EnumBackingType) {
None,
Rectangle,
Border,
Text,
Image,
ScissorStart,
ScissorEnd,
Custom,
};
pub const TextWrapMode = enum(EnumBackingType) {
Words,
Newlines,
None,
};
pub const FloatingAttachPointType = enum(EnumBackingType) {
LEFT_TOP,
LEFT_CENTER,
LEFT_BOTTOM,
CENTER_TOP,
CENTER_CENTER,
CENTER_BOTTOM,
RIGHT_TOP,
RIGHT_CENTER,
RIGHT_BOTTOM,
};
pub const FloatingAttachPoints = extern struct {
element: FloatingAttachPointType,
parent: FloatingAttachPointType,
};
pub const ElementConfigUnion = extern union {
rectangle_element_config: *RectangleElementConfig,
text_element_config: *TextElementConfig,
image_element_config: *ImageElementConfig,
custom_element_config: *CustomElementConfig,
border_element_config: *BorderElementConfig,
};
pub const RenderCommand = extern struct {
bounding_box: BoundingBox,
config: ElementConfigUnion,
@ -161,83 +309,32 @@ pub const ScrollContainerData = extern struct {
};
pub const SizingType = enum(EnumBackingType) {
FIT,
GROW,
PERCENT,
FIXED,
};
pub const SizingConstraintsMinMax = extern struct {
min: f32 = 0,
max: f32 = 0,
FIT = 0,
GROW = 1,
PERCENT = 2,
FIXED = 3,
};
pub const SizingConstraints = extern union {
size_minmax: SizingConstraintsMinMax,
size_minmax: SizingMinMax,
size_percent: f32,
};
pub const SizingAxis = extern struct {
// Note: `min` is used for CLAY_SIZING_PERCENT, slightly different to clay.h due to lack of C anonymous unions
constraints: SizingConstraints = .{ .size_minmax = .{} },
type: SizingType = .FIT,
pub const grow = SizingAxis{ .type = .GROW, .constraints = .{ .size_minmax = .{ .min = 0, .max = 0 } } };
pub const fit = SizingAxis{ .type = .FIT, .constraints = .{ .size_minmax = .{ .min = 0, .max = 0 } } };
pub fn growMinMax(size_minmax: SizingConstraintsMinMax) SizingAxis {
return .{ .type = .GROW, .constraints = .{ .size_minmax = size_minmax } };
}
pub fn fitMinMax(size_minmax: SizingConstraintsMinMax) SizingAxis {
return .{ .type = .FIT, .constraints = .{ .size_minmax = size_minmax } };
}
pub fn fixed(size: f32) SizingAxis {
return .{ .type = .FIXED, .constraints = .{ .size_minmax = .{ .max = size, .min = size } } };
}
pub fn percent(size_percent: f32) SizingAxis {
return .{ .type = .PERCENT, .constraints = .{ .size_percent = size_percent } };
}
};
pub const Sizing = extern struct {
/// width
w: SizingAxis = .{},
/// height
h: SizingAxis = .{},
pub const grow = Sizing{ .h = .grow, .w = .grow };
};
pub const Padding = extern struct {
x: u16 = 0,
y: u16 = 0,
pub fn all(size: u16) Padding {
return Padding{
.x = size,
.y = size,
};
}
};
pub const LayoutDirection = enum(EnumBackingType) {
LEFT_TO_RIGHT = 0,
TOP_TO_BOTTOM = 1,
};
pub const LayoutAlignmentX = enum(EnumBackingType) {
LEFT,
RIGHT,
CENTER,
LEFT = 0,
RIGHT = 1,
CENTER = 2,
};
pub const LayoutAlignmentY = enum(EnumBackingType) {
TOP,
BOTTOM,
CENTER,
TOP = 0,
BOTTOM = 1,
CENTER = 2,
};
pub const ChildAlignment = extern struct {
@ -306,28 +403,11 @@ pub const BorderElementConfig = extern struct {
}
};
pub const TextElementConfig = extern struct {
color: Color = .{ 0, 0, 0, 255 },
font_id: u16 = 0,
font_size: u16 = 20,
letter_spacing: u16 = 0,
line_height: u16 = 0,
wrap_mode: TextWrapMode = .Words,
};
pub const ImageElementConfig = extern struct {
image_data: *const anyopaque,
source_dimensions: Dimensions,
};
pub const FloatingElementConfig = extern struct {
offset: Vector2,
expand: Dimensions,
z_index: u16,
parent_id: u32,
attachment: FloatingAttachPoints,
};
pub const CustomElementConfig = extern struct {
custom_data: *anyopaque,
};
@ -338,52 +418,49 @@ pub const ScrollElementConfig = extern struct {
};
pub const ElementConfigType = enum(EnumBackingType) {
Rectangle = 1,
Border = 2,
Floating = 4,
Scroll = 8,
Image = 16,
Text = 32,
Custom = 64,
rectangle_config = 1,
border_config = 2,
floating_config = 4,
scroll_config = 8,
image_config = 16,
text_config = 32,
custom_config = 64,
// zig specific enum types
id,
Layout,
layout_config,
};
pub const Config = union(ElementConfigType) {
Rectangle: *RectangleElementConfig,
Border: *BorderElementConfig,
Floating: *FloatingElementConfig,
Scroll: *ScrollElementConfig,
Image: *ImageElementConfig,
Text: *TextElementConfig,
Custom: *CustomElementConfig,
rectangle_config: *RectangleElementConfig,
border_config: *BorderElementConfig,
floating_config: *FloatingElementConfig,
scroll_config: *ScrollElementConfig,
image_config: *ImageElementConfig,
text_config: *TextElementConfig,
custom_config: *CustomElementConfig,
id: ElementId,
Layout: *LayoutConfig,
layout_config: *LayoutConfig,
pub fn layout(config: LayoutConfig) Config {
return Config{ .Layout = cdefs.Clay__StoreLayoutConfig(config) };
}
pub fn rectangle(config: RectangleElementConfig) Config {
return Config{ .Rectangle = cdefs.Clay__StoreRectangleElementConfig(config) };
}
pub fn text(config: TextElementConfig) Config {
return Config{ .Text = cdefs.Clay__StoreTextElementConfig(config) };
}
pub fn image(config: ImageElementConfig) Config {
return Config{ .Image = cdefs.Clay__StoreImageElementConfig(config) };
}
pub fn floating(config: FloatingElementConfig) Config {
return Config{ .Floating = cdefs.Clay__StoreFloatingElementConfig(config) };
}
pub fn custom(config: CustomElementConfig) Config {
return Config{ .Custom = cdefs.Clay__StoreCustomElementConfig(config) };
}
pub fn scroll(config: ScrollElementConfig) Config {
return Config{ .Scroll = cdefs.Clay__StoreScrollElementConfig(config) };
return Config{ .rectangle_config = cdefs.Clay__StoreRectangleElementConfig(config) };
}
pub fn border(config: BorderElementConfig) Config {
return Config{ .Border = cdefs.Clay__StoreBorderElementConfig(config) };
return Config{ .border_config = cdefs.Clay__StoreBorderElementConfig(config) };
}
pub fn floating(config: FloatingElementConfig) Config {
return Config{ .floating_config = cdefs.Clay__StoreFloatingElementConfig(config) };
}
pub fn scroll(config: ScrollElementConfig) Config {
return Config{ .scroll_config = cdefs.Clay__StoreScrollElementConfig(config) };
}
pub fn image(config: ImageElementConfig) Config {
return Config{ .image_config = cdefs.Clay__StoreImageElementConfig(config) };
}
pub fn text(config: TextElementConfig) Config {
return Config{ .text_config = cdefs.Clay__StoreTextElementConfig(config) };
}
pub fn custom(config: CustomElementConfig) Config {
return Config{ .custom_config = cdefs.Clay__StoreCustomElementConfig(config) };
}
pub fn ID(string: []const u8) Config {
return Config{ .id = hashString(makeClayString(string), 0, 0) };
@ -391,10 +468,12 @@ pub const Config = union(ElementConfigType) {
pub fn IDI(string: []const u8, index: u32) Config {
return Config{ .id = hashString(makeClayString(string), index, 0) };
}
pub fn layout(config: LayoutConfig) Config {
return Config{ .layout_config = cdefs.Clay__StoreLayoutConfig(config) };
}
};
pub const minMemorySize = cdefs.Clay_MinMemorySize;
pub const createArenaWithCapacityAndMemory = cdefs.Clay_CreateArenaWithCapacityAndMemory;
pub const initialize = cdefs.Clay_Initialize;
pub const setLayoutDimensions = cdefs.Clay_SetLayoutDimensions;
pub const beginLayout = cdefs.Clay_BeginLayout;
@ -404,64 +483,27 @@ pub const renderCommandArrayGet = cdefs.Clay_RenderCommandArray_Get;
pub const setDebugModeEnabled = cdefs.Clay_SetDebugModeEnabled;
pub const hashString = cdefs.Clay__HashString;
pub fn createArenaWithCapacityAndMemory(buffer: []u8) Arena {
return cdefs.Clay_CreateArenaWithCapacityAndMemory(@intCast(buffer.len), buffer.ptr);
}
pub inline fn UI(configs: []const Config) fn (void) void {
std.debug.print("-> OPEN ELEMENT\n", .{});
cdefs.Clay__OpenElement();
for (configs) |config| {
switch (config) {
.Layout => |layoutConf| {
std.debug.print("LAYOUT CONF: {}\n", .{layoutConf});
cdefs.Clay__AttachLayoutConfig(layoutConf);
},
.layout_config => |layoutConf| cdefs.Clay__AttachLayoutConfig(layoutConf),
.id => |id| cdefs.Clay__AttachId(id),
inline else => |elem_config| {
std.debug.print("elem_config CONF: {}\n", .{elem_config});
cdefs.Clay__AttachElementConfig(@ptrCast(elem_config), config);
},
inline else => |elem_config, tag| cdefs.Clay__AttachElementConfig(@unionInit(ElementConfigUnion, @tagName(tag), elem_config), config),
}
}
std.debug.print("-> POST ELEMENT\n", .{});
cdefs.Clay__ElementPostConfiguration();
return struct {
fn f(_: void) void {
std.time.sleep(1000);
std.debug.print("-> CLOSE ELEMENT\n", .{});
cdefs.Clay__CloseElement();
}
}.f;
}
pub fn OPEN(configs: []const Config) bool {
std.debug.print("-> OPEN ELEMENT\n", .{});
cdefs.Clay__OpenElement();
for (configs) |config| {
switch (config) {
.Layout => |layoutConf| {
std.debug.print("LAYOUT CONF: {}\n", .{layoutConf});
cdefs.Clay__AttachLayoutConfig(layoutConf);
},
.id => |id| cdefs.Clay__AttachId(id),
inline else => |elem_config| {
std.debug.print("elem_config CONF: {}\n", .{elem_config});
cdefs.Clay__AttachElementConfig(@ptrCast(elem_config), config);
},
}
}
std.debug.print("-> POST ELEMENT\n", .{});
cdefs.Clay__ElementPostConfiguration();
return true;
}
pub fn CLOSE() void {
std.debug.print("-> CLOSE ELEMENT\n", .{});
cdefs.Clay__CloseElement();
}
pub fn singleElem(configs: []const Config) void {
_ = OPEN(configs);
CLOSE();
}
pub fn endLayout() ClayArray(RenderCommand) {
return cdefs.Clay_EndLayout();
}
@ -490,8 +532,7 @@ pub fn makeClayString(string: []const u8) String {
}
pub fn text(string: []const u8, config: Config) void {
// std.debug.print("TEXT 2 conf: {}\n", .{config.Text});
cdefs.Clay__OpenTextElement(makeClayString(string), config.Text);
cdefs.Clay__OpenTextElement(makeClayString(string), config.text_config);
}
pub fn ID(string: []const u8) ElementId {

View file

@ -1,16 +0,0 @@
const std = @import("std");
fn CLOSE(_: void) void {
std.debug.print("CLOSE\n", .{});
}
inline fn UI() fn (void) void {
std.debug.print("OPEN\n", .{});
return CLOSE;
}
pub fn main() !void {
UI()({
std.debug.print("INSIDE\n", .{});
});
}