Compare commits

...

23 Commits

Author SHA1 Message Date
Stowy
c200c4eb38
Merge be99977da6 into 01d3ab127f 2025-01-20 20:27:37 +01:00
Nic Barker
01d3ab127f Update odin bindings for new text measurement API
Some checks failed
CMake on multiple platforms / build (Release, cl, cl, windows-latest) (push) Has been cancelled
CMake on multiple platforms / build (Release, clang, clang++, ubuntu-latest) (push) Has been cancelled
CMake on multiple platforms / build (Release, gcc, g++, ubuntu-latest) (push) Has been cancelled
2025-01-20 11:39:59 +13:00
Nic Barker
326325ffaf
[Core] Convert measureText pointer to value string slice (#214) 2025-01-20 11:27:22 +13:00
Daniel Collin
e8025cc254
SetMesureText and SetQueryScrollOffset takes userData (#212) 2025-01-20 10:59:02 +13:00
Stowy
be99977da6 Added linux bindings 2025-01-09 23:51:58 +01:00
Stowy
f950d317c9 Updated raylib-jai module 2025-01-09 22:56:44 +01:00
Stowy
c44d6b9309 Merge branch 'main' into jai-bindings 2025-01-09 22:53:10 +01:00
Stowy
2cfab84034 Added readme and documentation in module.jai 2025-01-09 22:38:17 +01:00
Stowy
31bf0ad2dd Fixed paths 2025-01-09 22:38:17 +01:00
Stowy
f8b13b5978 Updated to latest clay and moved files to be like in the odin bindings 2025-01-09 22:38:17 +01:00
Stowy
9bc743fd12 Added missing procedures 2025-01-09 22:38:16 +01:00
Stowy
672927d387 Finished first version of the bindings with working demo !! 2025-01-09 22:38:16 +01:00
Stowy
b7e1d69ca6 Continuing example and still working on adaption the CLAY macro 2025-01-09 22:38:16 +01:00
Stowy
e9522005db Changed the UI proc to be like the one in the Odin bindings 2025-01-09 22:38:16 +01:00
Stowy
409bf1c3bf Continued clay bindings 2025-01-09 22:38:16 +01:00
Stowy
f0fec168a2 Finished Raylib renderer and continued demo 2025-01-09 22:38:16 +01:00
Stowy
bc31e8d332 Removed private elements from bindings 2025-01-09 22:38:16 +01:00
Stowy
697adce4a9 Fixed wrong command when building in debug 2025-01-09 22:38:16 +01:00
Stowy
1936afd184 Updated Raylib jai bindings and switch example project to clay video demo 2025-01-09 22:38:16 +01:00
Stowy
678bcf2ad0 Replaced raylib bindings with custom ones 2025-01-09 22:38:16 +01:00
Stowy
11e3f91220 Start of clay website example 2025-01-09 22:38:16 +01:00
Stowy
eb1ee390bb Simplified bindings generation 2025-01-09 22:38:16 +01:00
Stowy
4699018599 Added first version of Jai bindings 2025-01-09 22:38:16 +01:00
43 changed files with 12736 additions and 44 deletions

5
bindings/jai/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.build/
main.exe
main.pdb
main.rdi
main

116
bindings/jai/README.md Normal file
View File

@ -0,0 +1,116 @@
### Jai Language Bindings
This directory contains bindings for the [Jai](https://jai.community/t/overview-of-jai/128) programming language, as well as an example implementation of the Clay demo from the video in Jai.
If you haven't taken a look at the [full documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md), it's recommended that you take a look there first to familiarise yourself with the general concepts. This README is abbreviated and applies to using clay in Jai specifically.
The **most notable difference** between the C API and the Jai bindings is the use of for statements to create the scope for declaring child elements. This is done using some [for_expansion](https://jai.community/t/loops/147) magic.
When using the equivalent of the [Element Macros](https://github.com/nicbarker/clay/blob/main/README.md#element-macros):
```C
// C form of element macros
// Parent element with 8px of padding
CLAY(CLAY_LAYOUT({ .padding = 8 })) {
// Child element 1
CLAY_TEXT(CLAY_STRING("Hello World"), CLAY_TEXT_CONFIG({ .fontSize = 16 }));
// Child element 2 with red background
CLAY(CLAY_RECTANGLE({ .color = COLOR_RED })) {
// etc
}
}
```
```Jai
// Jai form of element macros
// Parent element with 8px of padding
for Clay.Element(Clay.Layout(.{padding = 8})) {
// Child element 1
Clay.Text("Hello World", Clay.TextConfig(.{fontSize = 16}));
// Child element 2 with red background
for Clay.Element(Clay.Rectangle(.{color = COLOR_RED})) {
// etc
}
}
```
> [!WARNING]
> For now, the Jai and Odin bindings are missing the OnHover() and Hovered() functions.
> You can you PointerOver instead, an example of that is in `examples/introducing_clay_video_demo`.
### Quick Start
1. Download the clay-jai directory and copy it into your modules folder.
```Jai
Clay :: #import "clay-jai";
```
1. 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()](https://github.com/nicbarker/clay/blob/main/README.md#clay_createarenawithcapacityandmemory), and initialize it with [Clay.Initialize()](https://github.com/nicbarker/clay/blob/main/README.md#clay_initialize).
```Jai
clay_required_memory := Clay.MinMemorySize();
memory := alloc(clay_required_memory);
clay_memory := Clay.CreateArenaWithCapacityAndMemory(clay_required_memory, memory);
Clay.Initialize(
clay_memory,
Clay.Dimensions.{cast(float, GetScreenWidth()), cast(float, GetScreenHeight())},
.{handle_clay_errors, 0}
);
```
3. Provide a `measure_text(text, config)` proc marked with `#c_call` with [Clay.SetMeasureTextFunction(function)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setmeasuretextfunction) so that clay can measure and wrap text.
```Jai
// Example measure text function
measure_text :: (text: *Clay.String, config: *Clay.TextElementConfig) -> Clay.Dimensions #c_call {
}
// Tell clay how to measure text
Clay.SetMeasureTextFunction(measure_text)
```
4. **Optional** - Call [Clay.SetPointerPosition(pointerPosition)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setpointerposition) if you want to use mouse interactions.
```Jai
// Update internal pointer position for handling mouseover / click / touch events
Clay.SetPointerPosition(.{ mousePositionX, mousePositionY })
```
5. Call [Clay.BeginLayout(screenWidth, screenHeight)](https://github.com/nicbarker/clay/blob/main/README.md#clay_beginlayout) and declare your layout using the provided macros.
```Jai
// An example function to begin the "root" of your layout tree
CreateLayout :: () -> Clay.RenderCommandArray {
Clay.BeginLayout(windowWidth, windowHeight);
for Clay.Element(
Clay.ID("OuterContainer"),
Clay.Layout(.{
sizing = .{Clay.SizingGrow(), Clay.SizingGrow()},
padding = .{16, 16},
childGap = 16
}),
Clay.Rectangle(.{color = .{250, 250, 255, 255}}),
) {
// ...
}
}
```
1. Call [Clay.EndLayout()](https://github.com/nicbarker/clay/blob/main/README.md#clay_endlayout) and process the resulting [Clay.RenderCommandArray](https://github.com/nicbarker/clay/blob/main/README.md#clay_rendercommandarray) in your choice of renderer.
```Jai
render_commands: Clay.RenderCommandArray = Clay.EndLayout();
for 0..render_commands.length - 1 {
render_command := Clay.RenderCommandArray_Get(*render_commands, cast(s32) it);
if #complete render_command.commandType == {
case .RECTANGLE;
DrawRectangle(render_command.boundingBox, render_command.config.rectangleElementConfig.color)
// ... Implement handling of other command types
}
}
```
Please see the [full C documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md) for API details. All public C functions and Macros have Jai binding equivalents, generally of the form `CLAY_RECTANGLE` (C) -> `Clay.Rectangle` (Jai)

1
bindings/jai/clay-jai/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
source/clay.h

View File

@ -0,0 +1,164 @@
AT_COMPILE_TIME :: true;
SOURCE_PATH :: "source";
DECLARATIONS_TO_OMIT :: string.[
// These have custom declaration in module.jai
"Clay_Vector2",
"Clay__ElementConfigType",
"Clay__AlignClay__ElementConfigType",
"Clay_Border",
"Clay__AlignClay_Border",
"Clay_BorderElementConfig",
"Clay__AlignClay_BorderElementConfig",
// These are not supported yet
"Clay_OnHover",
"Clay_Hovered",
];
#if AT_COMPILE_TIME {
#if !#exists(JAILS_DIAGNOSTICS_BUILD) {
#run,stallable {
Compiler.set_build_options_dc(.{do_output=false});
options := Compiler.get_build_options();
args := options.compile_time_command_line;
if !generate_bindings(args, options.minimum_os_version) {
Compiler.compiler_set_workspace_status(.FAILED);
}
}
}
} else {
#import "System";
main :: () {
set_working_directory(path_strip_filename(get_path_of_running_executable()));
if !generate_bindings(get_command_line_arguments(), #run get_build_options().minimum_os_version) {
exit(1);
}
}
}
generate_bindings :: (args: [] string, minimum_os_version: type_of(Compiler.Build_Options.minimum_os_version)) -> bool {
compile := array_find(args, "-compile");
compile_debug := array_find(args, "-debug");
could_copy := FileUtils.copy_file("../../../clay.h", "source/clay.h");
if !could_copy then return false;
defer if !compile_debug then File.file_delete("source/clay.h");
if compile {
source_file := tprint("%/clay.c", SOURCE_PATH);
success := true;
#if OS == .WINDOWS {
// TODO try to use BuildCpp module again
File.make_directory_if_it_does_not_exist("windows", true);
command := ifx compile_debug {
write_string("Compiling debug...\n");
Process.break_command_into_strings("clang -g -gcodeview -c source\\clay.c");
} else {
write_string("Compiling release...\n");
Process.break_command_into_strings("clang -O3 -c source\\clay.c");
}
result := Process.run_command(..command, capture_and_return_output=true, print_captured_output=true);
if result.exit_code != 0 then return false;
defer File.file_delete("clay.o");
write_string("Linking...\n");
command = Process.break_command_into_strings("llvm-ar -rcs windows/clay.lib clay.o");
result = Process.run_command(..command, capture_and_return_output=true, print_captured_output=true);
if result.exit_code != 0 then return false;
} else #if OS == .LINUX {
File.make_directory_if_it_does_not_exist("linux", true);
could_build := BuildCpp.build_cpp_static_lib("linux/clay", "source/clay.c",
debug = compile_debug,
);
assert(could_build);
} else {
// TODO MacOS
assert(false);
}
if !success then return false;
write_string("Succesfully built clay\n");
}
output_filename: string;
options: Generator.Generate_Bindings_Options;
{
write_string("Generating bindings...\n");
using options;
#if OS == .WINDOWS {
array_add(*libpaths, "windows");
output_filename = "windows.jai";
} else #if OS == .LINUX {
array_add(*libpaths, "linux");
output_filename = "linux.jai";
} else {
assert(false);
}
array_add(*libnames, "clay");
array_add(*include_paths, SOURCE_PATH);
array_add(*source_files, tprint("%/clay.h", SOURCE_PATH));
array_add(*strip_prefixes, "Clay_");
auto_detect_enum_prefixes = true;
log_stripped_declarations = true;
generate_compile_time_struct_checks = true;
visitor = clay_visitor;
}
could_generate := Generator.generate_bindings(options, output_filename);
return could_generate;
}
clay_visitor :: (decl: *Generator.Declaration, parent_decl: *Generator.Declaration) -> Generator.Declaration_Visit_Result {
if !parent_decl {
if array_find(DECLARATIONS_TO_OMIT, decl.name) {
decl.decl_flags |= .OMIT_FROM_OUTPUT;
return .STOP;
}
// We don't want the align and wrapper strucs
if String.begins_with(decl.name, "Clay__Align") || String.ends_with(decl.name, "Wrapper") {
decl.decl_flags |= .OMIT_FROM_OUTPUT;
return .STOP;
}
if String.begins_with(decl.name, "Clay__") {
// The way bindings generator strip prefixes mean that something like `Clay__Foo` will be turned to `Foo`
// but what we want is `_Foo`
decl.output_name = String.slice(decl.name, 5, decl.name.count - 5);
}
}
return .RECURSE;
}
#scope_file
using Basic :: #import "Basic";
Generator :: #import "Bindings_Generator";
Compiler :: #import "Compiler";
File :: #import "File";
FileUtils :: #import "File_Utilities";
BuildCpp :: #import "BuildCpp";
Process :: #import "Process";
String :: #import "String";
#if OS == .WINDOWS {
Windows :: #import "Windows";
WindowsResources :: #import "Windows_Resources";
getenv :: Windows.getenv;
} else {
Posix :: #import "POSIX";
getenv :: Posix.getenv;
}

View File

@ -0,0 +1,711 @@
//
// This file was auto-generated using the following command:
//
// jai generate.jai - -compile
//
// Utility Structs -------------------------
// Note: Clay_String is not guaranteed to be null terminated. It may be if created from a literal C string,
// but it is also used to represent slices.
String :: struct {
length: s32;
chars: *u8;
}
_StringArray :: struct {
capacity: s32;
length: s32;
internalArray: *String;
}
Context :: struct {}
Arena :: struct {
nextAllocation: u64;
capacity: u64;
memory: *u8;
}
Dimensions :: struct {
width: float;
height: float;
}
Color :: struct {
r: float;
g: float;
b: float;
a: float;
}
BoundingBox :: struct {
x: float;
y: float;
width: float;
height: float;
}
// baseId + offset = id
ElementId :: struct {
id: u32;
offset: u32;
baseId: u32;
stringId: String;
}
CornerRadius :: struct {
topLeft: float;
topRight: float;
bottomLeft: float;
bottomRight: float;
}
LayoutDirection :: enum u8 {
LEFT_TO_RIGHT :: 0;
TOP_TO_BOTTOM :: 1;
CLAY_LEFT_TO_RIGHT :: LEFT_TO_RIGHT;
CLAY_TOP_TO_BOTTOM :: TOP_TO_BOTTOM;
}
LayoutAlignmentX :: enum u8 {
LEFT :: 0;
RIGHT :: 1;
CENTER :: 2;
CLAY_ALIGN_X_LEFT :: LEFT;
CLAY_ALIGN_X_RIGHT :: RIGHT;
CLAY_ALIGN_X_CENTER :: CENTER;
}
LayoutAlignmentY :: enum u8 {
TOP :: 0;
BOTTOM :: 1;
CENTER :: 2;
CLAY_ALIGN_Y_TOP :: TOP;
CLAY_ALIGN_Y_BOTTOM :: BOTTOM;
CLAY_ALIGN_Y_CENTER :: CENTER;
}
_SizingType :: enum u8 {
FIT :: 0;
GROW :: 1;
PERCENT :: 2;
FIXED :: 3;
CLAY__SIZING_TYPE_FIT :: FIT;
CLAY__SIZING_TYPE_GROW :: GROW;
CLAY__SIZING_TYPE_PERCENT :: PERCENT;
CLAY__SIZING_TYPE_FIXED :: FIXED;
}
ChildAlignment :: struct {
x: LayoutAlignmentX;
y: LayoutAlignmentY;
}
SizingMinMax :: struct {
min: float;
max: float;
}
SizingAxis :: struct {
size: union {
minMax: SizingMinMax;
percent: float;
};
type: _SizingType;
}
Sizing :: struct {
width: SizingAxis;
height: SizingAxis;
}
Padding :: struct {
x: u16;
y: u16;
}
LayoutConfig :: struct {
sizing: Sizing;
padding: Padding;
childGap: u16;
childAlignment: ChildAlignment;
layoutDirection: LayoutDirection;
}
CLAY_LAYOUT_DEFAULT: LayoutConfig #elsewhere clay;
// Rectangle
// NOTE: Not declared in the typedef as an ifdef inside macro arguments is UB
RectangleElementConfig :: struct {
color: Color;
cornerRadius: CornerRadius;
}
// Text
TextElementConfigWrapMode :: enum u32 {
WORDS :: 0;
NEWLINES :: 1;
NONE :: 2;
CLAY_TEXT_WRAP_WORDS :: WORDS;
CLAY_TEXT_WRAP_NEWLINES :: NEWLINES;
CLAY_TEXT_WRAP_NONE :: NONE;
}
TextElementConfig :: struct {
textColor: Color;
fontId: u16;
fontSize: u16;
letterSpacing: u16;
lineHeight: u16;
wrapMode: TextElementConfigWrapMode;
}
// Image
ImageElementConfig :: struct {
imageData: *void;
sourceDimensions: Dimensions;
}
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;
CLAY_ATTACH_POINT_LEFT_TOP :: LEFT_TOP;
CLAY_ATTACH_POINT_LEFT_CENTER :: LEFT_CENTER;
CLAY_ATTACH_POINT_LEFT_BOTTOM :: LEFT_BOTTOM;
CLAY_ATTACH_POINT_CENTER_TOP :: CENTER_TOP;
CLAY_ATTACH_POINT_CENTER_CENTER :: CENTER_CENTER;
CLAY_ATTACH_POINT_CENTER_BOTTOM :: CENTER_BOTTOM;
CLAY_ATTACH_POINT_RIGHT_TOP :: RIGHT_TOP;
CLAY_ATTACH_POINT_RIGHT_CENTER :: RIGHT_CENTER;
CLAY_ATTACH_POINT_RIGHT_BOTTOM :: RIGHT_BOTTOM;
}
FloatingAttachPoints :: struct {
element: FloatingAttachPointType;
parent: FloatingAttachPointType;
}
PointerCaptureMode :: enum u32 {
CAPTURE :: 0;
PASSTHROUGH :: 1;
CLAY_POINTER_CAPTURE_MODE_CAPTURE :: CAPTURE;
CLAY_POINTER_CAPTURE_MODE_PASSTHROUGH :: PASSTHROUGH;
}
FloatingElementConfig :: struct {
offset: Vector2;
expand: Dimensions;
zIndex: u16;
parentId: u32;
attachment: FloatingAttachPoints;
pointerCaptureMode: PointerCaptureMode;
}
// Custom
CustomElementConfig :: struct {
customData: *void;
}
// Scroll
ScrollElementConfig :: struct {
horizontal: bool;
vertical: bool;
}
ElementConfigUnion :: union {
rectangleElementConfig: *RectangleElementConfig;
textElementConfig: *TextElementConfig;
imageElementConfig: *ImageElementConfig;
floatingElementConfig: *FloatingElementConfig;
customElementConfig: *CustomElementConfig;
scrollElementConfig: *ScrollElementConfig;
borderElementConfig: *BorderElementConfig;
}
ElementConfig :: struct {
type: ElementConfigType;
config: ElementConfigUnion;
}
// Miscellaneous Structs & Enums ---------------------------------
ScrollContainerData :: struct {
// Note: This is a pointer to the real internal scroll position, mutating it may cause a change in final layout.
// Intended for use with external functionality that modifies scroll position, such as scroll bars or auto scrolling.
scrollPosition: *Vector2;
scrollContainerDimensions: Dimensions;
contentDimensions: Dimensions;
config: ScrollElementConfig;
found: bool;
}
RenderCommandType :: enum u8 {
NONE :: 0;
RECTANGLE :: 1;
BORDER :: 2;
TEXT :: 3;
IMAGE :: 4;
SCISSOR_START :: 5;
SCISSOR_END :: 6;
CUSTOM :: 7;
CLAY_RENDER_COMMAND_TYPE_NONE :: NONE;
CLAY_RENDER_COMMAND_TYPE_RECTANGLE :: RECTANGLE;
CLAY_RENDER_COMMAND_TYPE_BORDER :: BORDER;
CLAY_RENDER_COMMAND_TYPE_TEXT :: TEXT;
CLAY_RENDER_COMMAND_TYPE_IMAGE :: IMAGE;
CLAY_RENDER_COMMAND_TYPE_SCISSOR_START :: SCISSOR_START;
CLAY_RENDER_COMMAND_TYPE_SCISSOR_END :: SCISSOR_END;
CLAY_RENDER_COMMAND_TYPE_CUSTOM :: CUSTOM;
}
RenderCommand :: struct {
boundingBox: BoundingBox;
config: ElementConfigUnion;
text: String; // TODO I wish there was a way to avoid having to have this on every render command
id: u32;
commandType: RenderCommandType;
}
RenderCommandArray :: struct {
capacity: s32;
length: s32;
internalArray: *RenderCommand;
}
PointerDataInteractionState :: enum u32 {
PRESSED_THIS_FRAME :: 0;
PRESSED :: 1;
RELEASED_THIS_FRAME :: 2;
RELEASED :: 3;
CLAY_POINTER_DATA_PRESSED_THIS_FRAME :: PRESSED_THIS_FRAME;
CLAY_POINTER_DATA_PRESSED :: PRESSED;
CLAY_POINTER_DATA_RELEASED_THIS_FRAME :: RELEASED_THIS_FRAME;
CLAY_POINTER_DATA_RELEASED :: RELEASED;
}
PointerData :: struct {
position: Vector2;
state: PointerDataInteractionState;
}
ErrorType :: enum u32 {
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;
CLAY_ERROR_TYPE_TEXT_MEASUREMENT_FUNCTION_NOT_PROVIDED :: TEXT_MEASUREMENT_FUNCTION_NOT_PROVIDED;
CLAY_ERROR_TYPE_ARENA_CAPACITY_EXCEEDED :: ARENA_CAPACITY_EXCEEDED;
CLAY_ERROR_TYPE_ELEMENTS_CAPACITY_EXCEEDED :: ELEMENTS_CAPACITY_EXCEEDED;
CLAY_ERROR_TYPE_TEXT_MEASUREMENT_CAPACITY_EXCEEDED :: TEXT_MEASUREMENT_CAPACITY_EXCEEDED;
CLAY_ERROR_TYPE_DUPLICATE_ID :: DUPLICATE_ID;
CLAY_ERROR_TYPE_FLOATING_CONTAINER_PARENT_NOT_FOUND :: FLOATING_CONTAINER_PARENT_NOT_FOUND;
CLAY_ERROR_TYPE_INTERNAL_ERROR :: INTERNAL_ERROR;
}
ErrorData :: struct {
errorType: ErrorType;
errorText: String;
userData: u64;
}
ErrorHandler :: struct {
errorHandlerFunction: #type (errorText: ErrorData) -> void #c_call;
userData: u64;
}
// Function Forward Declarations ---------------------------------
// Public API functions ---
MinMemorySize :: () -> u32 #foreign clay "Clay_MinMemorySize";
CreateArenaWithCapacityAndMemory :: (capacity: u32, offset: *void) -> Arena #foreign clay "Clay_CreateArenaWithCapacityAndMemory";
SetPointerState :: (position: Vector2, pointerDown: bool) -> void #foreign clay "Clay_SetPointerState";
Initialize :: (arena: Arena, layoutDimensions: Dimensions, errorHandler: ErrorHandler) -> *Context #foreign clay "Clay_Initialize";
GetCurrentContext :: () -> *Context #foreign clay "Clay_GetCurrentContext";
SetCurrentContext :: (_context: *Context) -> void #foreign clay "Clay_SetCurrentContext";
UpdateScrollContainers :: (enableDragScrolling: bool, scrollDelta: Vector2, deltaTime: float) -> void #foreign clay "Clay_UpdateScrollContainers";
SetLayoutDimensions :: (dimensions: Dimensions) -> void #foreign clay "Clay_SetLayoutDimensions";
BeginLayout :: () -> void #foreign clay "Clay_BeginLayout";
EndLayout :: () -> RenderCommandArray #foreign clay "Clay_EndLayout";
GetElementId :: (idString: String) -> ElementId #foreign clay "Clay_GetElementId";
GetElementIdWithIndex :: (idString: String, index: u32) -> ElementId #foreign clay "Clay_GetElementIdWithIndex";
PointerOver :: (elementId: ElementId) -> bool #foreign clay "Clay_PointerOver";
GetScrollContainerData :: (id: ElementId) -> ScrollContainerData #foreign clay "Clay_GetScrollContainerData";
SetMeasureTextFunction :: (measureTextFunction: #type (text: *String, config: *TextElementConfig) -> Dimensions #c_call) -> void #foreign clay "Clay_SetMeasureTextFunction";
SetQueryScrollOffsetFunction :: (queryScrollOffsetFunction: #type (elementId: u32) -> Vector2 #c_call) -> void #foreign clay "Clay_SetQueryScrollOffsetFunction";
RenderCommandArray_Get :: (array: *RenderCommandArray, index: s32) -> *RenderCommand #foreign clay "Clay_RenderCommandArray_Get";
SetDebugModeEnabled :: (enabled: bool) -> void #foreign clay "Clay_SetDebugModeEnabled";
IsDebugModeEnabled :: () -> bool #foreign clay "Clay_IsDebugModeEnabled";
SetCullingEnabled :: (enabled: bool) -> void #foreign clay "Clay_SetCullingEnabled";
GetMaxElementCount :: () -> s32 #foreign clay "Clay_GetMaxElementCount";
SetMaxElementCount :: (maxElementCount: s32) -> void #foreign clay "Clay_SetMaxElementCount";
GetMaxMeasureTextCacheWordCount :: () -> s32 #foreign clay "Clay_GetMaxMeasureTextCacheWordCount";
SetMaxMeasureTextCacheWordCount :: (maxMeasureTextCacheWordCount: s32) -> void #foreign clay "Clay_SetMaxMeasureTextCacheWordCount";
// Internal API functions required by macros
_OpenElement :: () -> void #foreign clay "Clay__OpenElement";
_CloseElement :: () -> void #foreign clay "Clay__CloseElement";
_StoreLayoutConfig :: (config: LayoutConfig) -> *LayoutConfig #foreign clay "Clay__StoreLayoutConfig";
_ElementPostConfiguration :: () -> void #foreign clay "Clay__ElementPostConfiguration";
_AttachId :: (id: ElementId) -> void #foreign clay "Clay__AttachId";
_AttachLayoutConfig :: (config: *LayoutConfig) -> void #foreign clay "Clay__AttachLayoutConfig";
_AttachElementConfig :: (config: ElementConfigUnion, type: ElementConfigType) -> void #foreign clay "Clay__AttachElementConfig";
_StoreRectangleElementConfig :: (config: RectangleElementConfig) -> *RectangleElementConfig #foreign clay "Clay__StoreRectangleElementConfig";
_StoreTextElementConfig :: (config: TextElementConfig) -> *TextElementConfig #foreign clay "Clay__StoreTextElementConfig";
_StoreImageElementConfig :: (config: ImageElementConfig) -> *ImageElementConfig #foreign clay "Clay__StoreImageElementConfig";
_StoreFloatingElementConfig :: (config: FloatingElementConfig) -> *FloatingElementConfig #foreign clay "Clay__StoreFloatingElementConfig";
_StoreCustomElementConfig :: (config: CustomElementConfig) -> *CustomElementConfig #foreign clay "Clay__StoreCustomElementConfig";
_StoreScrollElementConfig :: (config: ScrollElementConfig) -> *ScrollElementConfig #foreign clay "Clay__StoreScrollElementConfig";
_StoreBorderElementConfig :: (config: BorderElementConfig) -> *BorderElementConfig #foreign clay "Clay__StoreBorderElementConfig";
_HashString :: (key: String, offset: u32, seed: u32) -> ElementId #foreign clay "Clay__HashString";
_OpenTextElement :: (text: String, textConfig: *TextElementConfig) -> void #foreign clay "Clay__OpenTextElement";
_GetParentElementId :: () -> u32 #foreign clay "Clay__GetParentElementId";
_debugViewHighlightColor: Color #elsewhere clay "Clay__debugViewHighlightColor";
_debugViewWidth: u32 #elsewhere clay "Clay__debugViewWidth";
#scope_file
#import "Basic"; // For assert
clay :: #library,no_dll "linux/clay";
#run {
{
instance: String;
assert(((cast(*void)(*instance.length)) - cast(*void)(*instance)) == 0, "String.length has unexpected offset % instead of 0", ((cast(*void)(*instance.length)) - cast(*void)(*instance)));
assert(size_of(type_of(String.length)) == 4, "String.length has unexpected size % instead of 4", size_of(type_of(String.length)));
assert(((cast(*void)(*instance.chars)) - cast(*void)(*instance)) == 8, "String.chars has unexpected offset % instead of 8", ((cast(*void)(*instance.chars)) - cast(*void)(*instance)));
assert(size_of(type_of(String.chars)) == 8, "String.chars has unexpected size % instead of 8", size_of(type_of(String.chars)));
assert(size_of(String) == 16, "String has size % instead of 16", size_of(String));
}
{
instance: _StringArray;
assert(((cast(*void)(*instance.capacity)) - cast(*void)(*instance)) == 0, "_StringArray.capacity has unexpected offset % instead of 0", ((cast(*void)(*instance.capacity)) - cast(*void)(*instance)));
assert(size_of(type_of(_StringArray.capacity)) == 4, "_StringArray.capacity has unexpected size % instead of 4", size_of(type_of(_StringArray.capacity)));
assert(((cast(*void)(*instance.length)) - cast(*void)(*instance)) == 4, "_StringArray.length has unexpected offset % instead of 4", ((cast(*void)(*instance.length)) - cast(*void)(*instance)));
assert(size_of(type_of(_StringArray.length)) == 4, "_StringArray.length has unexpected size % instead of 4", size_of(type_of(_StringArray.length)));
assert(((cast(*void)(*instance.internalArray)) - cast(*void)(*instance)) == 8, "_StringArray.internalArray has unexpected offset % instead of 8", ((cast(*void)(*instance.internalArray)) - cast(*void)(*instance)));
assert(size_of(type_of(_StringArray.internalArray)) == 8, "_StringArray.internalArray has unexpected size % instead of 8", size_of(type_of(_StringArray.internalArray)));
assert(size_of(_StringArray) == 16, "_StringArray has size % instead of 16", size_of(_StringArray));
}
{
instance: Arena;
assert(((cast(*void)(*instance.nextAllocation)) - cast(*void)(*instance)) == 0, "Arena.nextAllocation has unexpected offset % instead of 0", ((cast(*void)(*instance.nextAllocation)) - cast(*void)(*instance)));
assert(size_of(type_of(Arena.nextAllocation)) == 8, "Arena.nextAllocation has unexpected size % instead of 8", size_of(type_of(Arena.nextAllocation)));
assert(((cast(*void)(*instance.capacity)) - cast(*void)(*instance)) == 8, "Arena.capacity has unexpected offset % instead of 8", ((cast(*void)(*instance.capacity)) - cast(*void)(*instance)));
assert(size_of(type_of(Arena.capacity)) == 8, "Arena.capacity has unexpected size % instead of 8", size_of(type_of(Arena.capacity)));
assert(((cast(*void)(*instance.memory)) - cast(*void)(*instance)) == 16, "Arena.memory has unexpected offset % instead of 16", ((cast(*void)(*instance.memory)) - cast(*void)(*instance)));
assert(size_of(type_of(Arena.memory)) == 8, "Arena.memory has unexpected size % instead of 8", size_of(type_of(Arena.memory)));
assert(size_of(Arena) == 24, "Arena has size % instead of 24", size_of(Arena));
}
{
instance: Dimensions;
assert(((cast(*void)(*instance.width)) - cast(*void)(*instance)) == 0, "Dimensions.width has unexpected offset % instead of 0", ((cast(*void)(*instance.width)) - cast(*void)(*instance)));
assert(size_of(type_of(Dimensions.width)) == 4, "Dimensions.width has unexpected size % instead of 4", size_of(type_of(Dimensions.width)));
assert(((cast(*void)(*instance.height)) - cast(*void)(*instance)) == 4, "Dimensions.height has unexpected offset % instead of 4", ((cast(*void)(*instance.height)) - cast(*void)(*instance)));
assert(size_of(type_of(Dimensions.height)) == 4, "Dimensions.height has unexpected size % instead of 4", size_of(type_of(Dimensions.height)));
assert(size_of(Dimensions) == 8, "Dimensions has size % instead of 8", size_of(Dimensions));
}
{
instance: Color;
assert(((cast(*void)(*instance.r)) - cast(*void)(*instance)) == 0, "Color.r has unexpected offset % instead of 0", ((cast(*void)(*instance.r)) - cast(*void)(*instance)));
assert(size_of(type_of(Color.r)) == 4, "Color.r has unexpected size % instead of 4", size_of(type_of(Color.r)));
assert(((cast(*void)(*instance.g)) - cast(*void)(*instance)) == 4, "Color.g has unexpected offset % instead of 4", ((cast(*void)(*instance.g)) - cast(*void)(*instance)));
assert(size_of(type_of(Color.g)) == 4, "Color.g has unexpected size % instead of 4", size_of(type_of(Color.g)));
assert(((cast(*void)(*instance.b)) - cast(*void)(*instance)) == 8, "Color.b has unexpected offset % instead of 8", ((cast(*void)(*instance.b)) - cast(*void)(*instance)));
assert(size_of(type_of(Color.b)) == 4, "Color.b has unexpected size % instead of 4", size_of(type_of(Color.b)));
assert(((cast(*void)(*instance.a)) - cast(*void)(*instance)) == 12, "Color.a has unexpected offset % instead of 12", ((cast(*void)(*instance.a)) - cast(*void)(*instance)));
assert(size_of(type_of(Color.a)) == 4, "Color.a has unexpected size % instead of 4", size_of(type_of(Color.a)));
assert(size_of(Color) == 16, "Color has size % instead of 16", size_of(Color));
}
{
instance: BoundingBox;
assert(((cast(*void)(*instance.x)) - cast(*void)(*instance)) == 0, "BoundingBox.x has unexpected offset % instead of 0", ((cast(*void)(*instance.x)) - cast(*void)(*instance)));
assert(size_of(type_of(BoundingBox.x)) == 4, "BoundingBox.x has unexpected size % instead of 4", size_of(type_of(BoundingBox.x)));
assert(((cast(*void)(*instance.y)) - cast(*void)(*instance)) == 4, "BoundingBox.y has unexpected offset % instead of 4", ((cast(*void)(*instance.y)) - cast(*void)(*instance)));
assert(size_of(type_of(BoundingBox.y)) == 4, "BoundingBox.y has unexpected size % instead of 4", size_of(type_of(BoundingBox.y)));
assert(((cast(*void)(*instance.width)) - cast(*void)(*instance)) == 8, "BoundingBox.width has unexpected offset % instead of 8", ((cast(*void)(*instance.width)) - cast(*void)(*instance)));
assert(size_of(type_of(BoundingBox.width)) == 4, "BoundingBox.width has unexpected size % instead of 4", size_of(type_of(BoundingBox.width)));
assert(((cast(*void)(*instance.height)) - cast(*void)(*instance)) == 12, "BoundingBox.height has unexpected offset % instead of 12", ((cast(*void)(*instance.height)) - cast(*void)(*instance)));
assert(size_of(type_of(BoundingBox.height)) == 4, "BoundingBox.height has unexpected size % instead of 4", size_of(type_of(BoundingBox.height)));
assert(size_of(BoundingBox) == 16, "BoundingBox has size % instead of 16", size_of(BoundingBox));
}
{
instance: ElementId;
assert(((cast(*void)(*instance.id)) - cast(*void)(*instance)) == 0, "ElementId.id has unexpected offset % instead of 0", ((cast(*void)(*instance.id)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementId.id)) == 4, "ElementId.id has unexpected size % instead of 4", size_of(type_of(ElementId.id)));
assert(((cast(*void)(*instance.offset)) - cast(*void)(*instance)) == 4, "ElementId.offset has unexpected offset % instead of 4", ((cast(*void)(*instance.offset)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementId.offset)) == 4, "ElementId.offset has unexpected size % instead of 4", size_of(type_of(ElementId.offset)));
assert(((cast(*void)(*instance.baseId)) - cast(*void)(*instance)) == 8, "ElementId.baseId has unexpected offset % instead of 8", ((cast(*void)(*instance.baseId)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementId.baseId)) == 4, "ElementId.baseId has unexpected size % instead of 4", size_of(type_of(ElementId.baseId)));
assert(((cast(*void)(*instance.stringId)) - cast(*void)(*instance)) == 16, "ElementId.stringId has unexpected offset % instead of 16", ((cast(*void)(*instance.stringId)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementId.stringId)) == 16, "ElementId.stringId has unexpected size % instead of 16", size_of(type_of(ElementId.stringId)));
assert(size_of(ElementId) == 32, "ElementId has size % instead of 32", size_of(ElementId));
}
{
instance: CornerRadius;
assert(((cast(*void)(*instance.topLeft)) - cast(*void)(*instance)) == 0, "CornerRadius.topLeft has unexpected offset % instead of 0", ((cast(*void)(*instance.topLeft)) - cast(*void)(*instance)));
assert(size_of(type_of(CornerRadius.topLeft)) == 4, "CornerRadius.topLeft has unexpected size % instead of 4", size_of(type_of(CornerRadius.topLeft)));
assert(((cast(*void)(*instance.topRight)) - cast(*void)(*instance)) == 4, "CornerRadius.topRight has unexpected offset % instead of 4", ((cast(*void)(*instance.topRight)) - cast(*void)(*instance)));
assert(size_of(type_of(CornerRadius.topRight)) == 4, "CornerRadius.topRight has unexpected size % instead of 4", size_of(type_of(CornerRadius.topRight)));
assert(((cast(*void)(*instance.bottomLeft)) - cast(*void)(*instance)) == 8, "CornerRadius.bottomLeft has unexpected offset % instead of 8", ((cast(*void)(*instance.bottomLeft)) - cast(*void)(*instance)));
assert(size_of(type_of(CornerRadius.bottomLeft)) == 4, "CornerRadius.bottomLeft has unexpected size % instead of 4", size_of(type_of(CornerRadius.bottomLeft)));
assert(((cast(*void)(*instance.bottomRight)) - cast(*void)(*instance)) == 12, "CornerRadius.bottomRight has unexpected offset % instead of 12", ((cast(*void)(*instance.bottomRight)) - cast(*void)(*instance)));
assert(size_of(type_of(CornerRadius.bottomRight)) == 4, "CornerRadius.bottomRight has unexpected size % instead of 4", size_of(type_of(CornerRadius.bottomRight)));
assert(size_of(CornerRadius) == 16, "CornerRadius has size % instead of 16", size_of(CornerRadius));
}
{
instance: ChildAlignment;
assert(((cast(*void)(*instance.x)) - cast(*void)(*instance)) == 0, "ChildAlignment.x has unexpected offset % instead of 0", ((cast(*void)(*instance.x)) - cast(*void)(*instance)));
assert(size_of(type_of(ChildAlignment.x)) == 1, "ChildAlignment.x has unexpected size % instead of 1", size_of(type_of(ChildAlignment.x)));
assert(((cast(*void)(*instance.y)) - cast(*void)(*instance)) == 1, "ChildAlignment.y has unexpected offset % instead of 1", ((cast(*void)(*instance.y)) - cast(*void)(*instance)));
assert(size_of(type_of(ChildAlignment.y)) == 1, "ChildAlignment.y has unexpected size % instead of 1", size_of(type_of(ChildAlignment.y)));
assert(size_of(ChildAlignment) == 2, "ChildAlignment has size % instead of 2", size_of(ChildAlignment));
}
{
instance: SizingMinMax;
assert(((cast(*void)(*instance.min)) - cast(*void)(*instance)) == 0, "SizingMinMax.min has unexpected offset % instead of 0", ((cast(*void)(*instance.min)) - cast(*void)(*instance)));
assert(size_of(type_of(SizingMinMax.min)) == 4, "SizingMinMax.min has unexpected size % instead of 4", size_of(type_of(SizingMinMax.min)));
assert(((cast(*void)(*instance.max)) - cast(*void)(*instance)) == 4, "SizingMinMax.max has unexpected offset % instead of 4", ((cast(*void)(*instance.max)) - cast(*void)(*instance)));
assert(size_of(type_of(SizingMinMax.max)) == 4, "SizingMinMax.max has unexpected size % instead of 4", size_of(type_of(SizingMinMax.max)));
assert(size_of(SizingMinMax) == 8, "SizingMinMax has size % instead of 8", size_of(SizingMinMax));
}
{
instance: SizingAxis;
assert(((cast(*void)(*instance.size)) - cast(*void)(*instance)) == 0, "SizingAxis.size has unexpected offset % instead of 0", ((cast(*void)(*instance.size)) - cast(*void)(*instance)));
assert(size_of(type_of(SizingAxis.size)) == 8, "SizingAxis.size has unexpected size % instead of 8", size_of(type_of(SizingAxis.size)));
assert(((cast(*void)(*instance.type)) - cast(*void)(*instance)) == 8, "SizingAxis.type has unexpected offset % instead of 8", ((cast(*void)(*instance.type)) - cast(*void)(*instance)));
assert(size_of(type_of(SizingAxis.type)) == 1, "SizingAxis.type has unexpected size % instead of 1", size_of(type_of(SizingAxis.type)));
assert(size_of(SizingAxis) == 12, "SizingAxis has size % instead of 12", size_of(SizingAxis));
}
{
instance: Sizing;
assert(((cast(*void)(*instance.width)) - cast(*void)(*instance)) == 0, "Sizing.width has unexpected offset % instead of 0", ((cast(*void)(*instance.width)) - cast(*void)(*instance)));
assert(size_of(type_of(Sizing.width)) == 12, "Sizing.width has unexpected size % instead of 12", size_of(type_of(Sizing.width)));
assert(((cast(*void)(*instance.height)) - cast(*void)(*instance)) == 12, "Sizing.height has unexpected offset % instead of 12", ((cast(*void)(*instance.height)) - cast(*void)(*instance)));
assert(size_of(type_of(Sizing.height)) == 12, "Sizing.height has unexpected size % instead of 12", size_of(type_of(Sizing.height)));
assert(size_of(Sizing) == 24, "Sizing has size % instead of 24", size_of(Sizing));
}
{
instance: Padding;
assert(((cast(*void)(*instance.x)) - cast(*void)(*instance)) == 0, "Padding.x has unexpected offset % instead of 0", ((cast(*void)(*instance.x)) - cast(*void)(*instance)));
assert(size_of(type_of(Padding.x)) == 2, "Padding.x has unexpected size % instead of 2", size_of(type_of(Padding.x)));
assert(((cast(*void)(*instance.y)) - cast(*void)(*instance)) == 2, "Padding.y has unexpected offset % instead of 2", ((cast(*void)(*instance.y)) - cast(*void)(*instance)));
assert(size_of(type_of(Padding.y)) == 2, "Padding.y has unexpected size % instead of 2", size_of(type_of(Padding.y)));
assert(size_of(Padding) == 4, "Padding has size % instead of 4", size_of(Padding));
}
{
instance: LayoutConfig;
assert(((cast(*void)(*instance.sizing)) - cast(*void)(*instance)) == 0, "LayoutConfig.sizing has unexpected offset % instead of 0", ((cast(*void)(*instance.sizing)) - cast(*void)(*instance)));
assert(size_of(type_of(LayoutConfig.sizing)) == 24, "LayoutConfig.sizing has unexpected size % instead of 24", size_of(type_of(LayoutConfig.sizing)));
assert(((cast(*void)(*instance.padding)) - cast(*void)(*instance)) == 24, "LayoutConfig.padding has unexpected offset % instead of 24", ((cast(*void)(*instance.padding)) - cast(*void)(*instance)));
assert(size_of(type_of(LayoutConfig.padding)) == 4, "LayoutConfig.padding has unexpected size % instead of 4", size_of(type_of(LayoutConfig.padding)));
assert(((cast(*void)(*instance.childGap)) - cast(*void)(*instance)) == 28, "LayoutConfig.childGap has unexpected offset % instead of 28", ((cast(*void)(*instance.childGap)) - cast(*void)(*instance)));
assert(size_of(type_of(LayoutConfig.childGap)) == 2, "LayoutConfig.childGap has unexpected size % instead of 2", size_of(type_of(LayoutConfig.childGap)));
assert(((cast(*void)(*instance.childAlignment)) - cast(*void)(*instance)) == 30, "LayoutConfig.childAlignment has unexpected offset % instead of 30", ((cast(*void)(*instance.childAlignment)) - cast(*void)(*instance)));
assert(size_of(type_of(LayoutConfig.childAlignment)) == 2, "LayoutConfig.childAlignment has unexpected size % instead of 2", size_of(type_of(LayoutConfig.childAlignment)));
assert(((cast(*void)(*instance.layoutDirection)) - cast(*void)(*instance)) == 32, "LayoutConfig.layoutDirection has unexpected offset % instead of 32", ((cast(*void)(*instance.layoutDirection)) - cast(*void)(*instance)));
assert(size_of(type_of(LayoutConfig.layoutDirection)) == 1, "LayoutConfig.layoutDirection has unexpected size % instead of 1", size_of(type_of(LayoutConfig.layoutDirection)));
assert(size_of(LayoutConfig) == 36, "LayoutConfig has size % instead of 36", size_of(LayoutConfig));
}
{
instance: RectangleElementConfig;
assert(((cast(*void)(*instance.color)) - cast(*void)(*instance)) == 0, "RectangleElementConfig.color has unexpected offset % instead of 0", ((cast(*void)(*instance.color)) - cast(*void)(*instance)));
assert(size_of(type_of(RectangleElementConfig.color)) == 16, "RectangleElementConfig.color has unexpected size % instead of 16", size_of(type_of(RectangleElementConfig.color)));
assert(((cast(*void)(*instance.cornerRadius)) - cast(*void)(*instance)) == 16, "RectangleElementConfig.cornerRadius has unexpected offset % instead of 16", ((cast(*void)(*instance.cornerRadius)) - cast(*void)(*instance)));
assert(size_of(type_of(RectangleElementConfig.cornerRadius)) == 16, "RectangleElementConfig.cornerRadius has unexpected size % instead of 16", size_of(type_of(RectangleElementConfig.cornerRadius)));
assert(size_of(RectangleElementConfig) == 32, "RectangleElementConfig has size % instead of 32", size_of(RectangleElementConfig));
}
{
instance: TextElementConfig;
assert(((cast(*void)(*instance.textColor)) - cast(*void)(*instance)) == 0, "TextElementConfig.textColor has unexpected offset % instead of 0", ((cast(*void)(*instance.textColor)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.textColor)) == 16, "TextElementConfig.textColor has unexpected size % instead of 16", size_of(type_of(TextElementConfig.textColor)));
assert(((cast(*void)(*instance.fontId)) - cast(*void)(*instance)) == 16, "TextElementConfig.fontId has unexpected offset % instead of 16", ((cast(*void)(*instance.fontId)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.fontId)) == 2, "TextElementConfig.fontId has unexpected size % instead of 2", size_of(type_of(TextElementConfig.fontId)));
assert(((cast(*void)(*instance.fontSize)) - cast(*void)(*instance)) == 18, "TextElementConfig.fontSize has unexpected offset % instead of 18", ((cast(*void)(*instance.fontSize)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.fontSize)) == 2, "TextElementConfig.fontSize has unexpected size % instead of 2", size_of(type_of(TextElementConfig.fontSize)));
assert(((cast(*void)(*instance.letterSpacing)) - cast(*void)(*instance)) == 20, "TextElementConfig.letterSpacing has unexpected offset % instead of 20", ((cast(*void)(*instance.letterSpacing)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.letterSpacing)) == 2, "TextElementConfig.letterSpacing has unexpected size % instead of 2", size_of(type_of(TextElementConfig.letterSpacing)));
assert(((cast(*void)(*instance.lineHeight)) - cast(*void)(*instance)) == 22, "TextElementConfig.lineHeight has unexpected offset % instead of 22", ((cast(*void)(*instance.lineHeight)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.lineHeight)) == 2, "TextElementConfig.lineHeight has unexpected size % instead of 2", size_of(type_of(TextElementConfig.lineHeight)));
assert(((cast(*void)(*instance.wrapMode)) - cast(*void)(*instance)) == 24, "TextElementConfig.wrapMode has unexpected offset % instead of 24", ((cast(*void)(*instance.wrapMode)) - cast(*void)(*instance)));
assert(size_of(type_of(TextElementConfig.wrapMode)) == 4, "TextElementConfig.wrapMode has unexpected size % instead of 4", size_of(type_of(TextElementConfig.wrapMode)));
assert(size_of(TextElementConfig) == 28, "TextElementConfig has size % instead of 28", size_of(TextElementConfig));
}
{
instance: ImageElementConfig;
assert(((cast(*void)(*instance.imageData)) - cast(*void)(*instance)) == 0, "ImageElementConfig.imageData has unexpected offset % instead of 0", ((cast(*void)(*instance.imageData)) - cast(*void)(*instance)));
assert(size_of(type_of(ImageElementConfig.imageData)) == 8, "ImageElementConfig.imageData has unexpected size % instead of 8", size_of(type_of(ImageElementConfig.imageData)));
assert(((cast(*void)(*instance.sourceDimensions)) - cast(*void)(*instance)) == 8, "ImageElementConfig.sourceDimensions has unexpected offset % instead of 8", ((cast(*void)(*instance.sourceDimensions)) - cast(*void)(*instance)));
assert(size_of(type_of(ImageElementConfig.sourceDimensions)) == 8, "ImageElementConfig.sourceDimensions has unexpected size % instead of 8", size_of(type_of(ImageElementConfig.sourceDimensions)));
assert(size_of(ImageElementConfig) == 16, "ImageElementConfig has size % instead of 16", size_of(ImageElementConfig));
}
{
instance: FloatingAttachPoints;
assert(((cast(*void)(*instance.element)) - cast(*void)(*instance)) == 0, "FloatingAttachPoints.element has unexpected offset % instead of 0", ((cast(*void)(*instance.element)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingAttachPoints.element)) == 1, "FloatingAttachPoints.element has unexpected size % instead of 1", size_of(type_of(FloatingAttachPoints.element)));
assert(((cast(*void)(*instance.parent)) - cast(*void)(*instance)) == 1, "FloatingAttachPoints.parent has unexpected offset % instead of 1", ((cast(*void)(*instance.parent)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingAttachPoints.parent)) == 1, "FloatingAttachPoints.parent has unexpected size % instead of 1", size_of(type_of(FloatingAttachPoints.parent)));
assert(size_of(FloatingAttachPoints) == 2, "FloatingAttachPoints has size % instead of 2", size_of(FloatingAttachPoints));
}
{
instance: FloatingElementConfig;
assert(((cast(*void)(*instance.offset)) - cast(*void)(*instance)) == 0, "FloatingElementConfig.offset has unexpected offset % instead of 0", ((cast(*void)(*instance.offset)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.offset)) == 8, "FloatingElementConfig.offset has unexpected size % instead of 8", size_of(type_of(FloatingElementConfig.offset)));
assert(((cast(*void)(*instance.expand)) - cast(*void)(*instance)) == 8, "FloatingElementConfig.expand has unexpected offset % instead of 8", ((cast(*void)(*instance.expand)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.expand)) == 8, "FloatingElementConfig.expand has unexpected size % instead of 8", size_of(type_of(FloatingElementConfig.expand)));
assert(((cast(*void)(*instance.zIndex)) - cast(*void)(*instance)) == 16, "FloatingElementConfig.zIndex has unexpected offset % instead of 16", ((cast(*void)(*instance.zIndex)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.zIndex)) == 2, "FloatingElementConfig.zIndex has unexpected size % instead of 2", size_of(type_of(FloatingElementConfig.zIndex)));
assert(((cast(*void)(*instance.parentId)) - cast(*void)(*instance)) == 20, "FloatingElementConfig.parentId has unexpected offset % instead of 20", ((cast(*void)(*instance.parentId)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.parentId)) == 4, "FloatingElementConfig.parentId has unexpected size % instead of 4", size_of(type_of(FloatingElementConfig.parentId)));
assert(((cast(*void)(*instance.attachment)) - cast(*void)(*instance)) == 24, "FloatingElementConfig.attachment has unexpected offset % instead of 24", ((cast(*void)(*instance.attachment)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.attachment)) == 2, "FloatingElementConfig.attachment has unexpected size % instead of 2", size_of(type_of(FloatingElementConfig.attachment)));
assert(((cast(*void)(*instance.pointerCaptureMode)) - cast(*void)(*instance)) == 28, "FloatingElementConfig.pointerCaptureMode has unexpected offset % instead of 28", ((cast(*void)(*instance.pointerCaptureMode)) - cast(*void)(*instance)));
assert(size_of(type_of(FloatingElementConfig.pointerCaptureMode)) == 4, "FloatingElementConfig.pointerCaptureMode has unexpected size % instead of 4", size_of(type_of(FloatingElementConfig.pointerCaptureMode)));
assert(size_of(FloatingElementConfig) == 32, "FloatingElementConfig has size % instead of 32", size_of(FloatingElementConfig));
}
{
instance: CustomElementConfig;
assert(((cast(*void)(*instance.customData)) - cast(*void)(*instance)) == 0, "CustomElementConfig.customData has unexpected offset % instead of 0", ((cast(*void)(*instance.customData)) - cast(*void)(*instance)));
assert(size_of(type_of(CustomElementConfig.customData)) == 8, "CustomElementConfig.customData has unexpected size % instead of 8", size_of(type_of(CustomElementConfig.customData)));
assert(size_of(CustomElementConfig) == 8, "CustomElementConfig has size % instead of 8", size_of(CustomElementConfig));
}
{
instance: ScrollElementConfig;
assert(((cast(*void)(*instance.horizontal)) - cast(*void)(*instance)) == 0, "ScrollElementConfig.horizontal has unexpected offset % instead of 0", ((cast(*void)(*instance.horizontal)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollElementConfig.horizontal)) == 1, "ScrollElementConfig.horizontal has unexpected size % instead of 1", size_of(type_of(ScrollElementConfig.horizontal)));
assert(((cast(*void)(*instance.vertical)) - cast(*void)(*instance)) == 1, "ScrollElementConfig.vertical has unexpected offset % instead of 1", ((cast(*void)(*instance.vertical)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollElementConfig.vertical)) == 1, "ScrollElementConfig.vertical has unexpected size % instead of 1", size_of(type_of(ScrollElementConfig.vertical)));
assert(size_of(ScrollElementConfig) == 2, "ScrollElementConfig has size % instead of 2", size_of(ScrollElementConfig));
}
{
instance: ElementConfigUnion;
assert(((cast(*void)(*instance.rectangleElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.rectangleElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.rectangleElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.rectangleElementConfig)) == 8, "ElementConfigUnion.rectangleElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.rectangleElementConfig)));
assert(((cast(*void)(*instance.textElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.textElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.textElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.textElementConfig)) == 8, "ElementConfigUnion.textElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.textElementConfig)));
assert(((cast(*void)(*instance.imageElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.imageElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.imageElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.imageElementConfig)) == 8, "ElementConfigUnion.imageElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.imageElementConfig)));
assert(((cast(*void)(*instance.floatingElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.floatingElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.floatingElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.floatingElementConfig)) == 8, "ElementConfigUnion.floatingElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.floatingElementConfig)));
assert(((cast(*void)(*instance.customElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.customElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.customElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.customElementConfig)) == 8, "ElementConfigUnion.customElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.customElementConfig)));
assert(((cast(*void)(*instance.scrollElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.scrollElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.scrollElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.scrollElementConfig)) == 8, "ElementConfigUnion.scrollElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.scrollElementConfig)));
assert(((cast(*void)(*instance.borderElementConfig)) - cast(*void)(*instance)) == 0, "ElementConfigUnion.borderElementConfig has unexpected offset % instead of 0", ((cast(*void)(*instance.borderElementConfig)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfigUnion.borderElementConfig)) == 8, "ElementConfigUnion.borderElementConfig has unexpected size % instead of 8", size_of(type_of(ElementConfigUnion.borderElementConfig)));
assert(size_of(ElementConfigUnion) == 8, "ElementConfigUnion has size % instead of 8", size_of(ElementConfigUnion));
}
{
instance: ElementConfig;
assert(((cast(*void)(*instance.type)) - cast(*void)(*instance)) == 0, "ElementConfig.type has unexpected offset % instead of 0", ((cast(*void)(*instance.type)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfig.type)) == 1, "ElementConfig.type has unexpected size % instead of 1", size_of(type_of(ElementConfig.type)));
assert(((cast(*void)(*instance.config)) - cast(*void)(*instance)) == 8, "ElementConfig.config has unexpected offset % instead of 8", ((cast(*void)(*instance.config)) - cast(*void)(*instance)));
assert(size_of(type_of(ElementConfig.config)) == 8, "ElementConfig.config has unexpected size % instead of 8", size_of(type_of(ElementConfig.config)));
assert(size_of(ElementConfig) == 16, "ElementConfig has size % instead of 16", size_of(ElementConfig));
}
{
instance: ScrollContainerData;
assert(((cast(*void)(*instance.scrollPosition)) - cast(*void)(*instance)) == 0, "ScrollContainerData.scrollPosition has unexpected offset % instead of 0", ((cast(*void)(*instance.scrollPosition)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollContainerData.scrollPosition)) == 8, "ScrollContainerData.scrollPosition has unexpected size % instead of 8", size_of(type_of(ScrollContainerData.scrollPosition)));
assert(((cast(*void)(*instance.scrollContainerDimensions)) - cast(*void)(*instance)) == 8, "ScrollContainerData.scrollContainerDimensions has unexpected offset % instead of 8", ((cast(*void)(*instance.scrollContainerDimensions)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollContainerData.scrollContainerDimensions)) == 8, "ScrollContainerData.scrollContainerDimensions has unexpected size % instead of 8", size_of(type_of(ScrollContainerData.scrollContainerDimensions)));
assert(((cast(*void)(*instance.contentDimensions)) - cast(*void)(*instance)) == 16, "ScrollContainerData.contentDimensions has unexpected offset % instead of 16", ((cast(*void)(*instance.contentDimensions)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollContainerData.contentDimensions)) == 8, "ScrollContainerData.contentDimensions has unexpected size % instead of 8", size_of(type_of(ScrollContainerData.contentDimensions)));
assert(((cast(*void)(*instance.config)) - cast(*void)(*instance)) == 24, "ScrollContainerData.config has unexpected offset % instead of 24", ((cast(*void)(*instance.config)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollContainerData.config)) == 2, "ScrollContainerData.config has unexpected size % instead of 2", size_of(type_of(ScrollContainerData.config)));
assert(((cast(*void)(*instance.found)) - cast(*void)(*instance)) == 26, "ScrollContainerData.found has unexpected offset % instead of 26", ((cast(*void)(*instance.found)) - cast(*void)(*instance)));
assert(size_of(type_of(ScrollContainerData.found)) == 1, "ScrollContainerData.found has unexpected size % instead of 1", size_of(type_of(ScrollContainerData.found)));
assert(size_of(ScrollContainerData) == 32, "ScrollContainerData has size % instead of 32", size_of(ScrollContainerData));
}
{
instance: RenderCommand;
assert(((cast(*void)(*instance.boundingBox)) - cast(*void)(*instance)) == 0, "RenderCommand.boundingBox has unexpected offset % instead of 0", ((cast(*void)(*instance.boundingBox)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommand.boundingBox)) == 16, "RenderCommand.boundingBox has unexpected size % instead of 16", size_of(type_of(RenderCommand.boundingBox)));
assert(((cast(*void)(*instance.config)) - cast(*void)(*instance)) == 16, "RenderCommand.config has unexpected offset % instead of 16", ((cast(*void)(*instance.config)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommand.config)) == 8, "RenderCommand.config has unexpected size % instead of 8", size_of(type_of(RenderCommand.config)));
assert(((cast(*void)(*instance.text)) - cast(*void)(*instance)) == 24, "RenderCommand.text has unexpected offset % instead of 24", ((cast(*void)(*instance.text)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommand.text)) == 16, "RenderCommand.text has unexpected size % instead of 16", size_of(type_of(RenderCommand.text)));
assert(((cast(*void)(*instance.id)) - cast(*void)(*instance)) == 40, "RenderCommand.id has unexpected offset % instead of 40", ((cast(*void)(*instance.id)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommand.id)) == 4, "RenderCommand.id has unexpected size % instead of 4", size_of(type_of(RenderCommand.id)));
assert(((cast(*void)(*instance.commandType)) - cast(*void)(*instance)) == 44, "RenderCommand.commandType has unexpected offset % instead of 44", ((cast(*void)(*instance.commandType)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommand.commandType)) == 1, "RenderCommand.commandType has unexpected size % instead of 1", size_of(type_of(RenderCommand.commandType)));
assert(size_of(RenderCommand) == 48, "RenderCommand has size % instead of 48", size_of(RenderCommand));
}
{
instance: RenderCommandArray;
assert(((cast(*void)(*instance.capacity)) - cast(*void)(*instance)) == 0, "RenderCommandArray.capacity has unexpected offset % instead of 0", ((cast(*void)(*instance.capacity)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommandArray.capacity)) == 4, "RenderCommandArray.capacity has unexpected size % instead of 4", size_of(type_of(RenderCommandArray.capacity)));
assert(((cast(*void)(*instance.length)) - cast(*void)(*instance)) == 4, "RenderCommandArray.length has unexpected offset % instead of 4", ((cast(*void)(*instance.length)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommandArray.length)) == 4, "RenderCommandArray.length has unexpected size % instead of 4", size_of(type_of(RenderCommandArray.length)));
assert(((cast(*void)(*instance.internalArray)) - cast(*void)(*instance)) == 8, "RenderCommandArray.internalArray has unexpected offset % instead of 8", ((cast(*void)(*instance.internalArray)) - cast(*void)(*instance)));
assert(size_of(type_of(RenderCommandArray.internalArray)) == 8, "RenderCommandArray.internalArray has unexpected size % instead of 8", size_of(type_of(RenderCommandArray.internalArray)));
assert(size_of(RenderCommandArray) == 16, "RenderCommandArray has size % instead of 16", size_of(RenderCommandArray));
}
{
instance: PointerData;
assert(((cast(*void)(*instance.position)) - cast(*void)(*instance)) == 0, "PointerData.position has unexpected offset % instead of 0", ((cast(*void)(*instance.position)) - cast(*void)(*instance)));
assert(size_of(type_of(PointerData.position)) == 8, "PointerData.position has unexpected size % instead of 8", size_of(type_of(PointerData.position)));
assert(((cast(*void)(*instance.state)) - cast(*void)(*instance)) == 8, "PointerData.state has unexpected offset % instead of 8", ((cast(*void)(*instance.state)) - cast(*void)(*instance)));
assert(size_of(type_of(PointerData.state)) == 4, "PointerData.state has unexpected size % instead of 4", size_of(type_of(PointerData.state)));
assert(size_of(PointerData) == 12, "PointerData has size % instead of 12", size_of(PointerData));
}
{
instance: ErrorData;
assert(((cast(*void)(*instance.errorType)) - cast(*void)(*instance)) == 0, "ErrorData.errorType has unexpected offset % instead of 0", ((cast(*void)(*instance.errorType)) - cast(*void)(*instance)));
assert(size_of(type_of(ErrorData.errorType)) == 4, "ErrorData.errorType has unexpected size % instead of 4", size_of(type_of(ErrorData.errorType)));
assert(((cast(*void)(*instance.errorText)) - cast(*void)(*instance)) == 8, "ErrorData.errorText has unexpected offset % instead of 8", ((cast(*void)(*instance.errorText)) - cast(*void)(*instance)));
assert(size_of(type_of(ErrorData.errorText)) == 16, "ErrorData.errorText has unexpected size % instead of 16", size_of(type_of(ErrorData.errorText)));
assert(((cast(*void)(*instance.userData)) - cast(*void)(*instance)) == 24, "ErrorData.userData has unexpected offset % instead of 24", ((cast(*void)(*instance.userData)) - cast(*void)(*instance)));
assert(size_of(type_of(ErrorData.userData)) == 8, "ErrorData.userData has unexpected size % instead of 8", size_of(type_of(ErrorData.userData)));
assert(size_of(ErrorData) == 32, "ErrorData has size % instead of 32", size_of(ErrorData));
}
{
instance: ErrorHandler;
assert(((cast(*void)(*instance.errorHandlerFunction)) - cast(*void)(*instance)) == 0, "ErrorHandler.errorHandlerFunction has unexpected offset % instead of 0", ((cast(*void)(*instance.errorHandlerFunction)) - cast(*void)(*instance)));
assert(size_of(type_of(ErrorHandler.errorHandlerFunction)) == 8, "ErrorHandler.errorHandlerFunction has unexpected size % instead of 8", size_of(type_of(ErrorHandler.errorHandlerFunction)));
assert(((cast(*void)(*instance.userData)) - cast(*void)(*instance)) == 8, "ErrorHandler.userData has unexpected offset % instead of 8", ((cast(*void)(*instance.userData)) - cast(*void)(*instance)));
assert(size_of(type_of(ErrorHandler.userData)) == 8, "ErrorHandler.userData has unexpected size % instead of 8", size_of(type_of(ErrorHandler.userData)));
assert(size_of(ErrorHandler) == 16, "ErrorHandler has size % instead of 16", size_of(ErrorHandler));
}
}

Binary file not shown.

View File

@ -0,0 +1,296 @@
/*
These bindings adapt the CLAY macro using some for_expansion trickery, allowing a syntax similar to the one in the Odin bindings.
I'll try to explain here why I did it that way.
In Odin, they can mark the procedure with deferred_none, allowing to call a proc after the current one, which works well with ifs.
@(require_results, deferred_none = _CloseElement)
UI :: proc(configs: ..TypedConfig) -> bool {}
You can then use it like so :
if UI(Layout(), etc..) {Children ...}
So I tried to replicate this in Jai. The first thing I did was to try making a macro returning a bool with a backticked defer in it.
UI :: (configs: ..TypedConfig) -> bool #must #expand {
`defer EndElement();
return true;
}
But this doesn't work if you have two elements side to side, as the end of the first element will be called after the start and the end of the second one.
Another option used in these bindings : https://github.com/nick-celestin-zizic/clay-jai is to have that defer like above and have the macro return nothing. You can then use it like that :
{ UI(Layout()); Children(); }
But I'm not a big fan of that since it's possible to forget the scope braces or to put the children before the element.
TODO This part is wrong... delete it and write the code that works
Another option to consider is to pass a code block to a macro that puts it between the start and the end.
UI :: (id: ElementId, layout: LayoutConfig, configs: ..ElementConfig, $code: Code) {
OpenElement();
...
#insert code;
CloseElement();
}
UI(..., #code {
Children();
});
However this prevents to refer to variables from the previous scope, and it's also a bit akward to type.
The final solution I found, inspired by the fact that CLAY uses a for loop behind the scene, was to use Jai's for_expansions.
Here is how it works :
InternalElementConfigArray :: struct {
configs: [] TypedConfig;
}
Element :: (configs: ..TypedConfig) -> InternalElementConfigArray #expand {
return .{configs};
}
for_expansion :: (configs_array: InternalElementConfigArray, body: Code, _: For_Flags) #expand {
Jai forces the definition of these
`it_index := 0;
`it := 0;
_OpenElement();
...
#insert body;
_CloseElement();
}
As you can see it's kinda similar to the previous one, but doesn't have the limitation on refering to variable from the calling scope.
Element builds an InternalElementConfigArray that has an array to the TypedConfigs, which will be passed to the for_expansion when placed after a for (this is a Jai feature).
This then allows to write something like :
for Element(Layout()) { Children(); }
With the downside that it's not obvious why the for is there before reading the documentation.
*/
Vector2 :: Math.Vector2;
ElementConfigType :: enum u8 {
NONE :: 0;
RECTANGLE :: 1;
BORDER_CONTAINER :: 2;
FLOATING_CONTAINER :: 4;
SCROLL_CONTAINER :: 8;
IMAGE :: 16;
TEXT :: 32;
CUSTOM :: 64;
CLAY__ELEMENT_CONFIG_TYPE_NONE :: NONE;
CLAY__ELEMENT_CONFIG_TYPE_RECTANGLE :: RECTANGLE;
CLAY__ELEMENT_CONFIG_TYPE_BORDER_CONTAINER :: BORDER_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_FLOATING_CONTAINER :: FLOATING_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_SCROLL_CONTAINER :: SCROLL_CONTAINER;
CLAY__ELEMENT_CONFIG_TYPE_IMAGE :: IMAGE;
CLAY__ELEMENT_CONFIG_TYPE_TEXT :: TEXT;
CLAY__ELEMENT_CONFIG_TYPE_CUSTOM :: CUSTOM;
// Jai bindings specific types, please don't assume any value in those
// a it might change if the enums above overlap with it
// TODO Check if these values need to be powers of two
ID :: 250;
LAYOUT :: 251;
}
// This is passed to UI so that we can omit layout
TypedConfig :: struct {
type: ElementConfigType;
config: *void;
id: ElementId;
}
BorderData :: struct {
width: u32;
color: Color;
}
BorderElementConfig :: struct {
left: BorderData;
right: BorderData;
top: BorderData;
bottom: BorderData;
betweenChildren: BorderData;
cornerRadius: CornerRadius;
}
make_string :: (str: string) -> String {
clay_string := String.{cast(s32, str.count), str.data};
return clay_string;
}
global_counter := 0;
for_expansion :: (configs_array: InternalElementConfigArray, body: Code, _: For_Flags) #expand {
// Jai forces the definition of these
`it_index := 0;
`it := 0;
_OpenElement();
for config : configs_array.configs {
if config.type == {
case .ID;
_AttachId(config.id);
case .LAYOUT;
_AttachLayoutConfig(cast(*LayoutConfig, config.config));
case;
// config.config is a *void, it stores the address of the pointer that is stored in the union
// as ElementConfigUnion is a union of structs. We can't cast pointers directly to structs,
// we first cast the address of the *void and then dereference it.
// Maybe there's a cast modifier to avoid this, but I don't know it (no_check and trunc didn't work).
_AttachElementConfig(cast(*ElementConfigUnion, *config.config).*, config.type);
}
}
_ElementPostConfiguration();
#insert body;
_CloseElement();
}
Element :: (configs: ..TypedConfig) -> InternalElementConfigArray #expand {
return .{configs};
}
ID :: (label: string, index: u32 = 0) -> TypedConfig {
return .{type = .ID, id = _HashString(make_string(label), index, 0)};
}
Layout :: (config: LayoutConfig) -> TypedConfig {
return .{type = .LAYOUT, config = _StoreLayoutConfig(config)};
}
Rectangle :: (config: RectangleElementConfig) -> TypedConfig {
return .{
type = .RECTANGLE,
config = _StoreRectangleElementConfig(config)
};
}
Floating :: (config: FloatingElementConfig) -> TypedConfig {
return .{type = .FLOATING_CONTAINER, config = _StoreFloatingElementConfig(config)};
}
Scroll :: (config: ScrollElementConfig) -> TypedConfig {
return .{type = .SCROLL_CONTAINER, config = _StoreScrollElementConfig(config)};
}
Image :: (config: ImageElementConfig) -> TypedConfig {
return .{type = .IMAGE, config = _StoreImageElementConfig(config)};
}
Custom :: (config: CustomElementConfig) -> TypedConfig {
return .{type = .CUSTOM, config = _StoreCustomElementConfig(config)};
}
Border :: (config: BorderElementConfig) -> TypedConfig {
return .{type = .BORDER, _StoreBorderElementConfig(config)};
}
BorderOutside :: (outside_borders: BorderData) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(BorderElementConfig.{
left = outside_borders,
right = outside_borders,
top = outside_borders,
bottom = outside_borders,
}),
};
}
BorderOutsideRadius :: (outside_borders: BorderData, radius: float) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = outside_borders,
right = outside_borders,
top = outside_borders,
bottom = outside_borders,
cornerRadius = .{radius, radius, radius, radius},
})
};
}
BorderAll :: (all_borders: BorderData) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = all_borders,
right = all_borders,
top = all_borders,
bottom = all_borders,
betweenChildren = all_borders,
})
};
}
BorderAllRadius :: (all_borders: BorderData, radius: float) -> TypedConfig {
return .{
type = .BORDER,
config = _StoreBorderElementConfig(.{
left = all_borders,
right = all_borders,
top = all_borders,
bottom = all_borders,
cornerRadius = .{radius, radius, radius, radius},
})
};
}
CornerRadiusAll :: (radius: float) -> CornerRadius {
return .{radius, radius, radius, radius};
}
Text :: (text: string, config: *TextElementConfig) {
_OpenTextElement(make_string(text), config);
}
TextConfig :: (config: TextElementConfig) -> *TextElementConfig {
return _StoreTextElementConfig(config);
}
SizingFit :: (size_min_max: SizingMinMax) -> SizingAxis {
return .{type = .FIT, size = .{minMax = size_min_max}};
}
SizingGrow :: (size_min_max: SizingMinMax = .{}) -> SizingAxis {
return .{type = .GROW, size = .{minMax = size_min_max}};
}
SizingFixed :: (size: float) -> SizingAxis {
return .{type = .FIXED, size = .{minMax = .{size, size}}};
}
SizingPercent :: (size_percent: float) -> SizingAxis {
return .{type = .PERCENT, size = .{percent = size_percent}};
}
GetElementId :: (str: string) -> ElementId {
return GetElementId(make_string(str));
}
#scope_module
Math :: #import "Math";
Compiler :: #import "Compiler";
ProgramPrint :: #import "Program_Print";
InternalElementConfigArray :: struct {
configs: [] TypedConfig;
}
#if OS == .WINDOWS {
#load "windows.jai";
} else #if OS == .LINUX {
#load "linux.jai";
} else {
assert(false);
}

View File

@ -0,0 +1,2 @@
#define CLAY_IMPLEMENTATION
#include "clay.h"

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -0,0 +1,241 @@
RaylibFont :: struct {
font_id: u16;
font: Raylib.Font;
}
g_raylib_fonts: [10]RaylibFont;
to_raylib_color :: (color: Clay.Color) -> Raylib.Color {
return .{cast(u8) color.r, cast(u8) color.g, cast(u8) color.b, cast(u8) color.a};
}
raylib_measure_text :: (text: *Clay.String, config: *Clay.TextElementConfig) -> Clay.Dimensions #c_call {
text_size := Clay.Dimensions.{0, 0};
max_text_width: float = 0;
line_text_width: float = 0;
text_height := cast(float)config.fontSize;
font_to_use := g_raylib_fonts[config.fontId].font;
if text.length > 0 {
for 0..(text.length - 1) {
if text.chars[it] == #char "\n" {
max_text_width = c_max(max_text_width, line_text_width);
line_text_width = 0;
continue;
}
index := cast(s32, text.chars[it]) - 32;
if font_to_use.glyphs[index].advanceX != 0 {
line_text_width += cast(float) font_to_use.glyphs[index].advanceX;
} else {
line_text_width += (font_to_use.recs[index].width + cast(float) font_to_use.glyphs[index].offsetX);
}
}
}
max_text_width = c_max(max_text_width, line_text_width);
text_size.width = max_text_width / 2;
text_size.height = text_height;
return text_size;
}
raylib_initialize :: (width: s32, height: s32, $$title: string, flags: Raylib.ConfigFlags) {
c_string_title: *u8;
#if is_constant(title) {
// Constant strings in Jai are null-terminated
c_string_title = title.data;
} else {
c_string_title = to_c_string(title);
}
Raylib.SetConfigFlags(flags);
Raylib.InitWindow(width, height, c_string_title);
}
clay_raylib_render :: (render_commands: Clay.RenderCommandArray) {
for 0..render_commands.length - 1 {
render_command := Clay.RenderCommandArray_Get(*render_commands, cast(s32) it);
bounding_box := render_command.boundingBox;
if #complete render_command.commandType == {
case .NONE;
case .TEXT;
text := string.{
cast(s64) render_command.text.length,
render_command.text.chars,
};
c_string_text := temp_c_string(text);
font_to_use: Raylib.Font = g_raylib_fonts[render_command.config.textElementConfig.fontId].font;
Raylib.DrawTextEx(
font_to_use,
c_string_text,
.{bounding_box.x, bounding_box.y},
cast(float) render_command.config.textElementConfig.fontSize,
cast(float) render_command.config.textElementConfig.letterSpacing,
to_raylib_color(render_command.config.textElementConfig.textColor),
);
case .IMAGE;
// TODO image handling
image_texture := cast(*Raylib.Texture2D, render_command.config.imageElementConfig.imageData).*;
Raylib.DrawTextureEx(
image_texture,
.{bounding_box.x, bounding_box.y},
0,
bounding_box.width / cast(float) image_texture.width,
Raylib.WHITE
);
case .SCISSOR_START;
Raylib.BeginScissorMode(
cast(s32, round(bounding_box.x)),
cast(s32, round(bounding_box.y)),
cast(s32, round(bounding_box.width)),
cast(s32, round(bounding_box.height)),
);
case .SCISSOR_END;
Raylib.EndScissorMode();
case .RECTANGLE;
config := render_command.config.rectangleElementConfig;
if config.cornerRadius.topLeft > 0 {
radius := (config.cornerRadius.topLeft * 2.0) / min(bounding_box.width, bounding_box.height);
Raylib.DrawRectangleRounded(
.{bounding_box.x, bounding_box.y, bounding_box.width, bounding_box.height},
radius,
8,
to_raylib_color(config.color),
);
} else {
Raylib.DrawRectangle(
cast(s32, bounding_box.x),
cast(s32, bounding_box.y),
cast(s32, bounding_box.width),
cast(s32, bounding_box.height),
to_raylib_color(config.color),
);
}
case .BORDER;
config := render_command.config.borderElementConfig;
// Left border
if config.left.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x)),
cast(s32, round(bounding_box.y + config.cornerRadius.topLeft)),
cast(s32, config.left.width),
cast(s32, round(bounding_box.height - config.cornerRadius.topLeft - config.cornerRadius.bottomLeft)),
to_raylib_color(config.right.color),
);
}
// Right border
if config.right.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + bounding_box.width - cast(float, config.right.width))),
cast(s32, round(bounding_box.y + config.cornerRadius.topRight)),
cast(s32, config.right.width),
cast(s32, round(bounding_box.height - config.cornerRadius.topRight - config.cornerRadius.bottomRight)),
to_raylib_color(config.right.color),
);
}
// Top border
if config.top.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + config.cornerRadius.topLeft)),
cast(s32, round(bounding_box.y)),
cast(s32, round(bounding_box.width - config.cornerRadius.topLeft - config.cornerRadius.topRight)),
cast(s32, config.top.width),
to_raylib_color(config.right.color),
);
}
// Bottom border
if config.bottom.width > 0 {
Raylib.DrawRectangle(
cast(s32, round(bounding_box.x + config.cornerRadius.bottomLeft)),
cast(s32, round(bounding_box.y + bounding_box.height - cast(float, config.bottom.width))),
cast(s32, round(bounding_box.width - config.cornerRadius.bottomLeft - config.cornerRadius.bottomRight)),
cast(s32, config.top.width),
to_raylib_color(config.right.color),
);
}
if config.cornerRadius.topLeft > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + config.cornerRadius.topLeft),
round(bounding_box.y + config.cornerRadius.topLeft),
},
round(config.cornerRadius.topLeft - cast(float, config.top.width)),
config.cornerRadius.topLeft,
180,
270,
10,
to_raylib_color(config.top.color),
);
}
if config.cornerRadius.topRight > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + bounding_box.width - config.cornerRadius.topRight),
round(bounding_box.y + config.cornerRadius.topRight),
},
round(config.cornerRadius.topRight - cast(float, config.top.width)),
config.cornerRadius.topRight,
270,
360,
10,
to_raylib_color(config.top.color),
);
}
if config.cornerRadius.bottomLeft > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + config.cornerRadius.bottomLeft),
round(bounding_box.y + bounding_box.height - config.cornerRadius.bottomLeft),
},
round(config.cornerRadius.bottomLeft - cast(float, config.bottom.width)),
config.cornerRadius.bottomLeft,
90,
180,
10,
to_raylib_color(config.bottom.color),
);
}
if config.cornerRadius.bottomRight > 0 {
Raylib.DrawRing(
.{
round(bounding_box.x + bounding_box.width - config.cornerRadius.bottomRight),
round(bounding_box.y + bounding_box.height - config.cornerRadius.bottomRight),
},
round(config.cornerRadius.bottomRight - cast(float, config.bottom.width)),
config.cornerRadius.bottomRight,
0.1,
90,
10,
to_raylib_color(config.bottom.color),
);
}
case .CUSTOM;
}
}
}
#scope_file
round :: (x: float) -> float {
rounded_int := cast(int, x + 0.5 * ifx x < 0 then -1 else 1);
return cast(float, rounded_int);
}
c_max :: (a: $T, b: T) -> T #c_call {
if b < a return a;
return b;
}

View File

@ -0,0 +1,293 @@
using Basic :: #import "Basic";
Clay :: #import,file "../../clay-jai/module.jai";
Raylib :: #import "raylib-jai";
for_expansion :: Clay.for_expansion;;
#load "clay_renderer_raylib.jai";
FONT_ID_BODY_16 :: 0;
COLOR_WHITE :: Clay.Color.{255, 255, 255, 255};
window_width: s32 = 1024;
window_height: s32 = 768;
Document :: struct {
title: string;
contents: string;
}
documents :: Document.[
.{"Squirrels", "The Secret Life of Squirrels: Nature's Clever Acrobats\nSquirrels are often overlooked creatures, dismissed as mere park inhabitants or backyard nuisances. Yet, beneath their fluffy tails and twitching noses lies an intricate world of cunning, agility, and survival tactics that are nothing short of fascinating. As one of the most common mammals in North America, squirrels have adapted to a wide range of environments from bustling urban centers to tranquil forests and have developed a variety of unique behaviors that continue to intrigue scientists and nature enthusiasts alike.\n\nMaster Tree Climbers\nAt the heart of a squirrel's skill set is its impressive ability to navigate trees with ease. Whether they're darting from branch to branch or leaping across wide gaps, squirrels possess an innate talent for acrobatics. Their powerful hind legs, which are longer than their front legs, give them remarkable jumping power. With a tail that acts as a counterbalance, squirrels can leap distances of up to ten times the length of their body, making them some of the best aerial acrobats in the animal kingdom.\nBut it's not just their agility that makes them exceptional climbers. Squirrels' sharp, curved claws allow them to grip tree bark with precision, while the soft pads on their feet provide traction on slippery surfaces. Their ability to run at high speeds and scale vertical trunks with ease is a testament to the evolutionary adaptations that have made them so successful in their arboreal habitats.\n\nFood Hoarders Extraordinaire\nSquirrels are often seen frantically gathering nuts, seeds, and even fungi in preparation for winter. While this behavior may seem like instinctual hoarding, it is actually a survival strategy that has been honed over millions of years. Known as \"scatter hoarding,\" squirrels store their food in a variety of hidden locations, often burying it deep in the soil or stashing it in hollowed-out tree trunks.\nInterestingly, squirrels have an incredible memory for the locations of their caches. Research has shown that they can remember thousands of hiding spots, often returning to them months later when food is scarce. However, they don't always recover every stash some forgotten caches eventually sprout into new trees, contributing to forest regeneration. This unintentional role as forest gardeners highlights the ecological importance of squirrels in their ecosystems.\n\nThe Great Squirrel Debate: Urban vs. Wild\nWhile squirrels are most commonly associated with rural or wooded areas, their adaptability has allowed them to thrive in urban environments as well. In cities, squirrels have become adept at finding food sources in places like parks, streets, and even garbage cans. However, their urban counterparts face unique challenges, including traffic, predators, and the lack of natural shelters. Despite these obstacles, squirrels in urban areas are often observed using human infrastructure such as buildings, bridges, and power lines as highways for their acrobatic escapades.\nThere is, however, a growing concern regarding the impact of urban life on squirrel populations. Pollution, deforestation, and the loss of natural habitats are making it more difficult for squirrels to find adequate food and shelter. As a result, conservationists are focusing on creating squirrel-friendly spaces within cities, with the goal of ensuring these resourceful creatures continue to thrive in both rural and urban landscapes.\n\nA Symbol of Resilience\nIn many cultures, squirrels are symbols of resourcefulness, adaptability, and preparation. Their ability to thrive in a variety of environments while navigating challenges with agility and grace serves as a reminder of the resilience inherent in nature. Whether you encounter them in a quiet forest, a city park, or your own backyard, squirrels are creatures that never fail to amaze with their endless energy and ingenuity.\nIn the end, squirrels may be small, but they are mighty in their ability to survive and thrive in a world that is constantly changing. So next time you spot one hopping across a branch or darting across your lawn, take a moment to appreciate the remarkable acrobat at work a true marvel of the natural world."},
.{"Lorem Ipsum", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."},
.{"Vacuum Instructions", "Chapter 3: Getting Started - Unpacking and Setup\n\nCongratulations on your new SuperClean Pro 5000 vacuum cleaner! In this section, we will guide you through the simple steps to get your vacuum up and running. Before you begin, please ensure that you have all the components listed in the \"Package Contents\" section on page 2.\n\n1. Unboxing Your Vacuum\nCarefully remove the vacuum cleaner from the box. Avoid using sharp objects that could damage the product. Once removed, place the unit on a flat, stable surface to proceed with the setup. Inside the box, you should find:\n\n The main vacuum unit\n A telescoping extension wand\n A set of specialized cleaning tools (crevice tool, upholstery brush, etc.)\n A reusable dust bag (if applicable)\n A power cord with a 3-prong plug\n A set of quick-start instructions\n\n2. Assembling Your Vacuum\nBegin by attaching the extension wand to the main body of the vacuum cleaner. Line up the connectors and twist the wand into place until you hear a click. Next, select the desired cleaning tool and firmly attach it to the wand's end, ensuring it is securely locked in.\n\nFor models that require a dust bag, slide the bag into the compartment at the back of the vacuum, making sure it is properly aligned with the internal mechanism. If your vacuum uses a bagless system, ensure the dust container is correctly seated and locked in place before use.\n\n3. Powering On\nTo start the vacuum, plug the power cord into a grounded electrical outlet. Once plugged in, locate the power switch, usually positioned on the side of the handle or body of the unit, depending on your model. Press the switch to the \"On\" position, and you should hear the motor begin to hum. If the vacuum does not power on, check that the power cord is securely plugged in, and ensure there are no blockages in the power switch.\n\nNote: Before first use, ensure that the vacuum filter (if your model has one) is properly installed. If unsure, refer to \"Section 5: Maintenance\" for filter installation instructions."},
.{"Article 4", "Article 4"},
.{"Article 5", "Article 5"},
];
to_jai_string :: (str: Clay.String) -> string {
return .{data = str.chars, count = cast(s64, str.length)};
}
handle_clay_errors :: (error_data: Clay.ErrorData) #c_call {
push_context {
log_error(
"Clay Error [%]: % | %",
error_data.errorType,
to_jai_string(error_data.errorText),
error_data.userData
);
}
}
render_header_button :: (text: string) {
for Clay.Element(
Clay.Layout(.{padding = .{16, 8}}),
Clay.Rectangle(.{
color = .{140, 140, 140, 255},
cornerRadius = .{5, 5, 5, 5},
})
) {
Clay.Text(text, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
}
}
render_dropdown_menu_item :: (text: string) {
for Clay.Element(
Clay.Layout(.{padding = .{16, 16}})
) {
Clay.Text(text, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
}
}
selected_document_index : int = 0;
main :: () {
flags := Raylib.ConfigFlags.WINDOW_RESIZABLE | .MSAA_4X_HINT | .VSYNC_HINT;
raylib_initialize(1024, 768, "Introducing Clay Demo", flags);
// For some reason, on linux, this is 8 bytes off ???
clay_required_memory := Clay.MinMemorySize() + 8;
memory := alloc(clay_required_memory);
clay_memory := Clay.CreateArenaWithCapacityAndMemory(clay_required_memory, memory);
Clay.Initialize(
clay_memory,
Clay.Dimensions.{cast(float, Raylib.GetScreenWidth()), cast(float, Raylib.GetScreenHeight())},
.{handle_clay_errors, 0}
);
Clay.SetMeasureTextFunction(raylib_measure_text);
g_raylib_fonts[FONT_ID_BODY_16] = .{
FONT_ID_BODY_16,
Raylib.LoadFontEx("resources/Roboto-Regular.ttf", 48, null, 400),
};
Raylib.SetTextureFilter(g_raylib_fonts[FONT_ID_BODY_16].font.texture, .BILINEAR);
while !Raylib.WindowShouldClose() {
Clay.SetLayoutDimensions(.{
cast(float, Raylib.GetScreenWidth()),
cast(float, Raylib.GetScreenHeight()),
});
mouse_position := Raylib.GetMousePosition();
scroll_delta := Raylib.GetMouseWheelMoveV();
Clay.SetPointerState(mouse_position, Raylib.IsMouseButtonDown(0));
Clay.UpdateScrollContainers(true, scroll_delta, Raylib.GetFrameTime());
layout_expand := Clay.Sizing.{
Clay.SizingGrow(),
Clay.SizingGrow(),
};
content_background_config := Clay.RectangleElementConfig.{
color = .{90, 90, 90, 255},
cornerRadius = .{8, 8, 8, 8},
};
Clay.BeginLayout();
for Clay.Element(
Clay.ID("OuterContainer"),
Clay.Rectangle(.{color = .{43, 41, 51, 255}}),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
sizing = layout_expand,
padding = .{16, 16},
childGap = 16,
}),
) {
for Clay.Element(
Clay.ID("HeaderBar"),
Clay.Rectangle(content_background_config),
Clay.Layout(.{
sizing = .{
height = Clay.SizingFixed(60),
width = Clay.SizingGrow(),
},
padding = .{16, 16},
childGap = 16,
childAlignment = .{
y = .CENTER,
}
}),
) {
for Clay.Element(
Clay.ID("FileButton"),
Clay.Layout(.{padding = .{16, 8}}),
Clay.Rectangle(.{
color = .{140, 140, 140, 255},
cornerRadius = .{5, 5, 5, 5},
}),
) {
Clay.Text("File", Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 16,
textColor = COLOR_WHITE,
}));
file_menu_visible := Clay.PointerOver(Clay.GetElementId("FileButton")) ||
Clay.PointerOver(Clay.GetElementId("FileMenu"));
if file_menu_visible {
for Clay.Element(
Clay.ID("FileMenu"),
Clay.Floating(.{attachment = .{parent = .LEFT_BOTTOM}}),
Clay.Layout(.{padding = .{0, 8}})
) {
for Clay.Element(
Clay.Layout(.{
layoutDirection=.TOP_TO_BOTTOM,
sizing = .{width = Clay.SizingFixed(200)}
}),
Clay.Rectangle(.{
color = .{40, 40, 40, 255},
cornerRadius = .{8, 8, 8, 8}
})
) {
// Render dropdown items here
render_dropdown_menu_item("New");
render_dropdown_menu_item("Open");
render_dropdown_menu_item("Close");
}
}
}
}
// Render header buttons
render_header_button("Edit");
for Clay.Element(Clay.Layout(.{
sizing = .{Clay.SizingGrow(), Clay.SizingGrow()}})) {}
render_header_button("Upload");
render_header_button("Media");
render_header_button("Support");
}
for Clay.Element(
Clay.ID("LowerContent"),
Clay.Layout(.{sizing = layout_expand, childGap = 16}),
) {
for Clay.Element(
Clay.ID("Sidebar"),
Clay.Rectangle(content_background_config),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
padding = .{16, 16},
childGap = 8,
sizing = .{
width = Clay.SizingFixed(250),
height = Clay.SizingGrow(),
}
})
) {
for document : documents {
sidebar_button_layout := Clay.LayoutConfig.{
sizing = .{width = Clay.SizingGrow()},
padding = .{16, 16},
};
if it_index == selected_document_index {
for Clay.Element(
Clay.Layout(sidebar_button_layout),
Clay.Rectangle(.{
color = .{120, 120, 120, 255},
cornerRadius = .{8, 8, 8, 8},
})
) {
Clay.Text(document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 20,
textColor = COLOR_WHITE,
}));
}
} else {
id := tprint("Parnets %", it_index);
is_hovered := Clay.PointerOver(Clay.GetElementId(id));
if is_hovered && Raylib.IsMouseButtonPressed(0) {
selected_document_index = it_index;
}
for Clay.Element(
Clay.ID(id)
) {
for Clay.Element(
Clay.Layout(sidebar_button_layout),
ifx is_hovered then Clay.Rectangle(.{
color = .{120, 120, 120, 120},
cornerRadius = .{8, 8, 8, 8},
}) else .{}
) {
Clay.Text(document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 20,
textColor = COLOR_WHITE
}));
}
}
}
}
}
for Clay.Element(
Clay.ID("MainContent"),
Clay.Rectangle(content_background_config),
Clay.Scroll(.{vertical = true}),
Clay.Layout(.{
layoutDirection = .TOP_TO_BOTTOM,
childGap = 16,
padding = .{16, 16},
sizing = layout_expand,
}),
) {
selected_document := documents[selected_document_index];
Clay.Text(selected_document.title, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 24,
textColor = COLOR_WHITE,
}));
Clay.Text(selected_document.contents, Clay.TextConfig(.{
fontId = FONT_ID_BODY_16,
fontSize = 24,
textColor = COLOR_WHITE
}));
}
}
}
render_commands := Clay.EndLayout();
Raylib.BeginDrawing();
Raylib.ClearBackground(Raylib.BLACK);
clay_raylib_render(render_commands);
Raylib.EndDrawing();
reset_temporary_storage();
}
}

View File

@ -0,0 +1,4 @@
.build
.vscode
raylib/
.DS_Store

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,148 @@
Vector2 :: Math.Vector2;
Vector3 :: Math.Vector3;
Vector4 :: Math.Vector4;
Quaternion :: Math.Quaternion;
Matrix :: Math.Matrix4;
PI :: Math.PI;
LIGHTGRAY :: Color.{ 200, 200, 200, 255 };
GRAY :: Color.{ 130, 130, 130, 255 };
DARKGRAY :: Color.{ 80, 80, 80, 255 };
YELLOW :: Color.{ 253, 249, 0, 255 };
GOLD :: Color.{ 255, 203, 0, 255 };
ORANGE :: Color.{ 255, 161, 0, 255 };
PINK :: Color.{ 255, 109, 194, 255 };
RED :: Color.{ 230, 41, 55, 255 };
MAROON :: Color.{ 190, 33, 55, 255 };
GREEN :: Color.{ 0, 228, 48, 255 };
LIME :: Color.{ 0, 158, 47, 255 };
DARKGREEN :: Color.{ 0, 117, 44, 255 };
SKYBLUE :: Color.{ 102, 191, 255, 255 };
BLUE :: Color.{ 0, 121, 241, 255 };
DARKBLUE :: Color.{ 0, 82, 172, 255 };
PURPLE :: Color.{ 200, 122, 255, 255 };
VIOLET :: Color.{ 135, 60, 190, 255 };
DARKPURPLE :: Color.{ 112, 31, 126, 255 };
BEIGE :: Color.{ 211, 176, 131, 255 };
BROWN :: Color.{ 127, 106, 79, 255 };
DARKBROWN :: Color.{ 76, 63, 47, 255 };
WHITE :: Color.{ 255, 255, 255, 255 };
BLACK :: Color.{ 0, 0, 0, 255 };
BLANK :: Color.{ 0, 0, 0, 0 };
MAGENTA :: Color.{ 255, 0, 255, 255 };
RAYWHITE :: Color.{ 245, 245, 245, 255 };
GetGamepadButtonPressed :: () -> GamepadButton #foreign raylib;
IsMouseButtonPressed :: (button: MouseButton) -> bool { return IsMouseButtonPressed(cast(s32) button); }
IsMouseButtonDown :: (button: MouseButton) -> bool { return IsMouseButtonDown(cast(s32) button); }
IsMouseButtonReleased :: (button: MouseButton) -> bool { return IsMouseButtonReleased(cast(s32) button); }
IsMouseButtonUp :: (button: MouseButton) -> bool { return IsMouseButtonUp(cast(s32) button); }
IsKeyPressed :: (key: KeyboardKey) -> bool { return IsKeyPressed(cast(s32) key); }
IsKeyPressedRepeat :: (key: KeyboardKey) -> bool { return IsKeyPressedRepeat(cast(s32) key); }
IsKeyDown :: (key: KeyboardKey) -> bool { return IsKeyDown(cast(s32) key); }
IsKeyReleased :: (key: KeyboardKey) -> bool { return IsKeyReleased(cast(s32) key); }
IsKeyUp :: (key: KeyboardKey) -> bool { return IsKeyUp(cast(s32) key); }
SetExitKey :: (key: KeyboardKey) -> void { return SetExitKey(cast(s32) key); }
SetConfigFlags :: (flags: ConfigFlags) -> void { return SetConfigFlags(cast(u32) flags); }
SetGesturesEnabled :: (flags: Gesture) -> void { return SetGesturesEnabled(cast(u32) flags); }
IsGestureDetected :: (gesture: Gesture) -> bool { return IsGestureDetected(cast(u32) gesture); }
IsWindowState :: (flag: ConfigFlags) -> bool { return IsWindowState(cast(u32) flag); }
SetWindowState :: (flags: ConfigFlags) -> void { return SetWindowState(cast(u32) flags); }
ClearWindowState :: (flags: ConfigFlags) -> void { return ClearWindowState(cast(u32) flags); }
UpdateCamera :: (camera: *Camera, mode: CameraMode) -> void { return UpdateCamera(camera, cast(s32) mode); }
SetTraceLogLevel :: (logLevel: TraceLogLevel) -> void { return SetTraceLogLevel(cast(s32) logLevel); }
TraceLog :: (logLevel: TraceLogLevel, text: string, __args: ..Any) { TraceLog(cast(s32) logLevel, text, __args); }
SetShaderValue :: (shader: Shader, locIndex: s32, value: *void, uniformType: ShaderUniformDataType) -> void {
return SetShaderValue(shader, locIndex, value, cast(s32) uniformType);
}
SetShaderValueV :: (shader: Shader, locIndex: s32, value: *void, uniformType: ShaderUniformDataType, count: s32) -> void {
return SetShaderValue(shader, locIndex, value, cast(s32) uniformType, count);
}
IsGamepadButtonPressed :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonPressed(gamepad, cast(s32) button); }
IsGamepadButtonDown :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonDown(gamepad, cast(s32) button); }
IsGamepadButtonReleased :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonReleased(gamepad, cast(s32) button); }
IsGamepadButtonUp :: (gamepad: s32, button: GamepadButton) -> bool { return IsGamepadButtonUp(gamepad, cast(s32) button); }
GetGamepadAxisMovement :: (gamepad: s32, axis: GamepadAxis) -> float { return GetGamepadAxisMovement(gamepad, cast(s32) axis); }
SetTextureFilter :: (texture: Texture2D, filter: TextureFilter) -> void { return SetTextureFilter(texture, cast(s32) filter); }
SetTextureWrap :: (texture: Texture2D, wrap: TextureWrap) -> void { return SetTextureWrap(textuer, cast(s32) wrap); }
BeginBlendMode :: (mode: BlendMode) -> void { return BeginBlendMode(cast(s32) mode); }
ImageFormat :: (image: *Image, newFormat: PixelFormat) -> void { return ImageFormat(image, cast(s32) newFormat); }
LoadImageRaw :: (fileName: *u8, width: s32, height: s32, format: PixelFormat, headerSize: s32) -> Image {
return LoadImageRaw(fileName, width, height, cast(s32) format, headerSize);
}
LoadFontData :: (fileData: *u8, dataSize: s32, fontSize: s32, codepoints: *s32, codepointCount: s32, type: FontType) -> *GlyphInfo {
return LoadFontData(fileData, dataSize, fontSize, codepoints, codepointCount, cast(s32) type);
}
SetMouseCursor :: (cursor: MouseCursor) -> void { return SetMouseCursor(cast(s32) cursor); }
LoadTexture :: (data: *void, width: s32, height: s32, format: PixelFormat, mipmapCount: s32) -> u32 {
return LoadTexture(data, width, height, cast(s32) format, mipmapCount);
}
FramebufferAttach :: (fboId: u32, texId: u32, attachType: FramebufferAttachType, texType: FramebufferAttachTextureType, mipLevel: s32) -> void {
return FramebufferAttach(fbiId, texId, cast(s32) attachType, cast(s32) texType, mipLevel);
}
SetUniform :: (locIndex: s32, value: *void, uniformType: ShaderUniformDataType, count: s32) -> void { return SetUniform(locIndex, value, cast(s32) uniformType, count); }
SetMaterialTexture :: (material: *Material, mapType: MaterialMapIndex, texture: Texture2D) -> void { return SetMaterialTexture(material, mapType, texture); }
Camera3D :: struct {
position: Vector3; // Camera position
target: Vector3; // Camera target it looks-at
up: Vector3; // Camera up vector (rotation over its axis)
fovy: float; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic
projection: CameraProjection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC
}
TraceLogCallback :: #type (logLevel: TraceLogLevel, text: *u8, args: .. Any) #c_call;
#scope_module
#if OS == .WINDOWS {
user32 :: #system_library,link_always "user32";
gdi32 :: #system_library,link_always "gdi32";
shell32 :: #system_library,link_always "shell32";
winmm :: #system_library,link_always "winmm";
raylib :: #library,no_dll "windows/raylib";
#load "windows.jai";
} else #if OS == .LINUX {
math :: #system_library,link_always "m";
raylib :: #library,no_dll "linux/raylib";
#load "linux.jai";
} else #if OS == .MACOS {
#system_library,link_always "Cocoa";
#system_library,link_always "OpenGL";
#system_library,link_always "CoreGraphics";
#system_library,link_always "AppKit";
#system_library,link_always "IOKit";
raylib :: #library,no_dll "macos/raylib";
#load "macos.jai";
} else {
assert(false);
}
#import "Basic";
Math :: #import "Math";

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@ cp ../../clay.h clay.c;
# Intel Mac
clang -c -DCLAY_IMPLEMENTATION -o clay.o -static -target x86_64-apple-darwin clay.c -fPIC && ar r clay-odin/macos/clay.a clay.o;
# ARM Mac
clang -c -DCLAY_IMPLEMENTATION -o clay.o -static clay.c -fPIC && ar r clay-odin/macos-arm64/clay.a clay.o;
clang -c -DCLAY_IMPLEMENTATION -g -o clay.o -static clay.c -fPIC && ar r clay-odin/macos-arm64/clay.a clay.o;
# x64 Windows
clang -c -DCLAY_IMPLEMENTATION -o clay-odin/windows/clay.lib -target x86_64-pc-windows-msvc -fuse-ld=llvm-lib -static clay.c;
# Linux

View File

@ -22,6 +22,12 @@ String :: struct {
chars: [^]c.char,
}
StringSlice :: struct {
length: c.int32_t,
chars: [^]c.char,
baseChars: [^]c.char,
}
Vector2 :: [2]c.float
Dimensions :: struct {
@ -305,7 +311,7 @@ foreign Clay {
PointerOver :: proc(id: ElementId) -> bool ---
GetElementId :: proc(id: String) -> ElementId ---
GetScrollContainerData :: proc(id: ElementId) -> ScrollContainerData ---
SetMeasureTextFunction :: proc(measureTextFunction: proc "c" (text: ^String, config: ^TextElementConfig) -> Dimensions) ---
SetMeasureTextFunction :: proc(measureTextFunction: proc "c" (text: StringSlice, config: ^TextElementConfig, userData: uintptr) -> Dimensions, userData: uintptr) ---
RenderCommandArray_Get :: proc(array: ^ClayArray(RenderCommand), index: i32) -> ^RenderCommand ---
SetDebugModeEnabled :: proc(enabled: bool) ---
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -493,8 +493,8 @@ main :: proc() {
minMemorySize: u32 = clay.MinMemorySize()
memory := make([^]u8, minMemorySize)
arena: clay.Arena = clay.CreateArenaWithCapacityAndMemory(minMemorySize, memory)
clay.SetMeasureTextFunction(measureText)
clay.Initialize(arena, {cast(f32)raylib.GetScreenWidth(), cast(f32)raylib.GetScreenHeight()}, { handler = errorHandler })
clay.SetMeasureTextFunction(measureText, 0)
raylib.SetConfigFlags({.VSYNC_HINT, .WINDOW_RESIZABLE, .WINDOW_HIGHDPI, .MSAA_4X_HINT})
raylib.InitWindow(windowWidth, windowHeight, "Raylib Odin Example")

View File

@ -16,7 +16,7 @@ clayColorToRaylibColor :: proc(color: clay.Color) -> raylib.Color {
raylibFonts := [10]RaylibFont{}
measureText :: proc "c" (text: ^clay.String, config: ^clay.TextElementConfig) -> clay.Dimensions {
measureText :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfig, userData: uintptr) -> clay.Dimensions {
// Measure string size for Font
textSize: clay.Dimensions = {0, 0}

41
clay.h
View File

@ -1,4 +1,4 @@
// VERSION: 0.11
// VERSION: 0.12
/*
NOTE: In order to use this library you must define
@ -191,6 +191,13 @@ CLAY__TYPEDEF(Clay__StringArray, struct {
Clay_String *internalArray;
});
CLAY__TYPEDEF(Clay_StringSlice, struct {
int32_t length;
const char *chars;
// The source string / char* that this slice was derived from
const char *baseChars;
});
typedef struct Clay_Context Clay_Context;
CLAY__TYPEDEF(Clay_Arena, struct {
@ -527,8 +534,8 @@ bool Clay_Hovered(void);
void Clay_OnHover(void (*onHoverFunction)(Clay_ElementId elementId, Clay_PointerData pointerData, intptr_t userData), intptr_t userData);
bool Clay_PointerOver(Clay_ElementId elementId);
Clay_ScrollContainerData Clay_GetScrollContainerData(Clay_ElementId id);
void Clay_SetMeasureTextFunction(Clay_Dimensions (*measureTextFunction)(Clay_String *text, Clay_TextElementConfig *config));
void Clay_SetQueryScrollOffsetFunction(Clay_Vector2 (*queryScrollOffsetFunction)(uint32_t elementId));
void Clay_SetMeasureTextFunction(Clay_Dimensions (*measureTextFunction)(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData), uintptr_t userData);
void Clay_SetQueryScrollOffsetFunction(Clay_Vector2 (*queryScrollOffsetFunction)(uint32_t elementId, uintptr_t userData), uintptr_t userData);
Clay_RenderCommand * Clay_RenderCommandArray_Get(Clay_RenderCommandArray* array, int32_t index);
void Clay_SetDebugModeEnabled(bool enabled);
bool Clay_IsDebugModeEnabled(void);
@ -1407,6 +1414,8 @@ struct Clay_Context {
uint32_t debugSelectedElementId;
uint32_t generation;
uintptr_t arenaResetOffset;
uintptr_t mesureTextUserData;
uintptr_t queryScrollOffsetUserData;
Clay_Arena internalArena;
// Layout Elements / Render Commands
Clay_LayoutElementArray layoutElements;
@ -1480,11 +1489,11 @@ Clay_String Clay__WriteStringToCharBuffer(Clay__CharArray *buffer, Clay_String s
}
#ifdef CLAY_WASM
__attribute__((import_module("clay"), import_name("measureTextFunction"))) Clay_Dimensions Clay__MeasureText(Clay_String *text, Clay_TextElementConfig *config);
__attribute__((import_module("clay"), import_name("queryScrollOffsetFunction"))) Clay_Vector2 Clay__QueryScrollOffset(uint32_t elementId);
__attribute__((import_module("clay"), import_name("measureTextFunction"))) Clay_Dimensions Clay__MeasureText(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData);
__attribute__((import_module("clay"), import_name("queryScrollOffsetFunction"))) Clay_Vector2 Clay__QueryScrollOffset(uint32_t elementId, uintptr_t userData);
#else
Clay_Dimensions (*Clay__MeasureText)(Clay_String *text, Clay_TextElementConfig *config);
Clay_Vector2 (*Clay__QueryScrollOffset)(uint32_t elementId);
Clay_Dimensions (*Clay__MeasureText)(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData);
Clay_Vector2 (*Clay__QueryScrollOffset)(uint32_t elementId, uintptr_t userData);
#endif
Clay_LayoutElement* Clay__GetOpenLayoutElement(void) {
@ -1699,7 +1708,7 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
float lineWidth = 0;
float measuredWidth = 0;
float measuredHeight = 0;
float spaceWidth = Clay__MeasureText(&CLAY__SPACECHAR, config).width;
float spaceWidth = Clay__MeasureText(CLAY__INIT(Clay_StringSlice) { .length = 1, .chars = CLAY__SPACECHAR.chars, .baseChars = CLAY__SPACECHAR.chars }, config, context->mesureTextUserData).width;
Clay__MeasuredWord tempWord = { .next = -1 };
Clay__MeasuredWord *previousWord = &tempWord;
while (end < text->length) {
@ -1716,8 +1725,7 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
char current = text->chars[end];
if (current == ' ' || current == '\n') {
int32_t length = end - start;
Clay_String word = { .length = length, .chars = &text->chars[start] };
Clay_Dimensions dimensions = Clay__MeasureText(&word, config);
Clay_Dimensions dimensions = Clay__MeasureText(CLAY__INIT(Clay_StringSlice) { .length = length, .chars = &text->chars[start], .baseChars = text->chars }, config, context->mesureTextUserData);
measuredHeight = CLAY__MAX(measuredHeight, dimensions.height);
if (current == ' ') {
dimensions.width += spaceWidth;
@ -1739,8 +1747,7 @@ Clay__MeasureTextCacheItem *Clay__MeasureTextCached(Clay_String *text, Clay_Text
end++;
}
if (end - start > 0) {
Clay_String lastWord = { .length = end - start, .chars = &text->chars[start] };
Clay_Dimensions dimensions = Clay__MeasureText(&lastWord, config);
Clay_Dimensions dimensions = Clay__MeasureText(CLAY__INIT(Clay_StringSlice) { .length = end - start, .chars = &text->chars[start], .baseChars = text->chars }, config, context->mesureTextUserData);
Clay__AddMeasuredWord(CLAY__INIT(Clay__MeasuredWord) { .startOffset = start, .length = end - start, .width = dimensions.width, .next = -1 }, previousWord);
lineWidth += dimensions.width;
measuredHeight = CLAY__MAX(measuredHeight, dimensions.height);
@ -1902,7 +1909,7 @@ void Clay__ElementPostConfiguration(void) {
scrollOffset = Clay__ScrollContainerDataInternalArray_Add(&context->scrollContainerDatas, CLAY__INIT(Clay__ScrollContainerDataInternal){.layoutElement = openLayoutElement, .scrollOrigin = {-1,-1}, .elementId = openLayoutElement->id, .openThisFrame = true});
}
if (context->externalScrollHandlingEnabled) {
scrollOffset->scrollPosition = Clay__QueryScrollOffset(scrollOffset->elementId);
scrollOffset->scrollPosition = Clay__QueryScrollOffset(scrollOffset->elementId, context->queryScrollOffsetUserData);
}
break;
}
@ -3678,11 +3685,15 @@ Clay_Arena Clay_CreateArenaWithCapacityAndMemory(uint32_t capacity, void *offset
}
#ifndef CLAY_WASM
void Clay_SetMeasureTextFunction(Clay_Dimensions (*measureTextFunction)(Clay_String *text, Clay_TextElementConfig *config)) {
void Clay_SetMeasureTextFunction(Clay_Dimensions (*measureTextFunction)(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData), uintptr_t userData) {
Clay_Context* context = Clay_GetCurrentContext();
Clay__MeasureText = measureTextFunction;
context->mesureTextUserData = userData;
}
void Clay_SetQueryScrollOffsetFunction(Clay_Vector2 (*queryScrollOffsetFunction)(uint32_t elementId)) {
void Clay_SetQueryScrollOffsetFunction(Clay_Vector2 (*queryScrollOffsetFunction)(uint32_t elementId, uintptr_t userData), uintptr_t userData) {
Clay_Context* context = Clay_GetCurrentContext();
Clay__QueryScrollOffset = queryScrollOffsetFunction;
context->queryScrollOffsetUserData = userData;
}
#endif

View File

@ -299,7 +299,10 @@ int main(int argc, char *argv[]) {
fprintf(stderr, "Error: could not load font: %s\n", TTF_GetError());
return 1;
}
SDL2_fonts[FONT_ID_BODY_16] = (SDL2_Font) {
SDL2_Font fonts[1] = {};
fonts[FONT_ID_BODY_16] = (SDL2_Font) {
.fontId = FONT_ID_BODY_16,
.font = font,
};
@ -315,12 +318,13 @@ int main(int argc, char *argv[]) {
uint64_t totalMemorySize = Clay_MinMemorySize();
Clay_Arena clayMemory = Clay_CreateArenaWithCapacityAndMemory(totalMemorySize, malloc(totalMemorySize));
Clay_SetMeasureTextFunction(SDL2_MeasureText);
int windowWidth = 0;
int windowHeight = 0;
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
Clay_Initialize(clayMemory, (Clay_Dimensions) { (float)windowWidth, (float)windowHeight }, (Clay_ErrorHandler) { HandleClayErrors });
Clay_SetMeasureTextFunction(SDL2_MeasureText, (uintptr_t)&fonts);
Uint64 NOW = SDL_GetPerformanceCounter();
Uint64 LAST = 0;
double deltaTime = 0;
@ -361,7 +365,7 @@ int main(int argc, char *argv[]) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
Clay_SDL2_Render(renderer, renderCommands);
Clay_SDL2_Render(renderer, renderCommands, fonts);
SDL_RenderPresent(renderer);
}

View File

@ -4,7 +4,7 @@ cmake_minimum_required(VERSION 3.27)
project(clay_examples_sdl3_simple_demo C)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -Wall -Werror")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -O3")
include(FetchContent)

View File

@ -21,12 +21,12 @@ typedef struct app_state {
SDL_Renderer *renderer;
} AppState;
static inline Clay_Dimensions SDL_MeasureText(Clay_String *text, Clay_TextElementConfig *config)
static inline Clay_Dimensions SDL_MeasureText(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData)
{
TTF_Font *font = gFonts[config->fontId];
int width, height;
if (!TTF_GetStringSize(font, text->chars, text->length, &width, &height)) {
if (!TTF_GetStringSize(font, text.chars, text.length, &width, &height)) {
SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to measure text: %s", SDL_GetError());
}
@ -114,8 +114,8 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
int width, height;
SDL_GetWindowSize(state->window, &width, &height);
Clay_SetMeasureTextFunction(SDL_MeasureText);
Clay_Initialize(clayMemory, (Clay_Dimensions) { (float) width, (float) height }, (Clay_ErrorHandler) { HandleClayErrors });
Clay_SetMeasureTextFunction(SDL_MeasureText, 0);
*appstate = state;
return SDL_APP_CONTINUE;

View File

@ -314,7 +314,7 @@
const importObject = {
clay: {
measureTextFunction: (addressOfDimensions, textToMeasure, addressOfConfig) => {
measureTextFunction: (addressOfDimensions, textToMeasure, addressOfConfig, userData) => {
let stringLength = memoryDataView.getUint32(textToMeasure, true);
let pointerToString = memoryDataView.getUint32(textToMeasure + 4, true);
let textConfig = readStructAtAddress(addressOfConfig, textConfigDefinition);

View File

@ -314,7 +314,7 @@
const importObject = {
clay: {
measureTextFunction: (addressOfDimensions, textToMeasure, addressOfConfig) => {
measureTextFunction: (addressOfDimensions, textToMeasure, addressOfConfig, userData) => {
let stringLength = memoryDataView.getUint32(textToMeasure, true);
let pointerToString = memoryDataView.getUint32(textToMeasure + 4, true);
let textConfig = readStructAtAddress(addressOfConfig, textConfigDefinition);

View File

@ -84,7 +84,7 @@ int main(void) {
.width = GetScreenWidth(),
.height = GetScreenHeight()
}, (Clay_ErrorHandler) { HandleClayErrors }); // This final argument is new since the video was published
Clay_SetMeasureTextFunction(Raylib_MeasureText);
Clay_SetMeasureTextFunction(Raylib_MeasureText, 0);
Raylib_fonts[FONT_ID_BODY_16] = (Raylib_Font) {
.font = LoadFontEx("resources/Roboto-Regular.ttf", 48, 0, 400),
.fontId = FONT_ID_BODY_16

View File

@ -247,7 +247,7 @@ int main(void) {
.height = GetScreenHeight() / 2
}, (Clay_ErrorHandler) { HandleClayErrors }); // This final argument is new since the video was published
Clay_SetMeasureTextFunction(Raylib_MeasureText);
Clay_SetMeasureTextFunction(Raylib_MeasureText, 0);
Raylib_fonts[FONT_ID_BODY_16] = (Raylib_Font) {
.font = LoadFontEx("resources/Roboto-Regular.ttf", 48, 0, 400),
.fontId = FONT_ID_BODY_16

View File

@ -218,8 +218,8 @@ void HandleClayErrors(Clay_ErrorData errorData) {
int main(void) {
uint64_t totalMemorySize = Clay_MinMemorySize();
Clay_Arena clayMemory = Clay_CreateArenaWithCapacityAndMemory(totalMemorySize, malloc(totalMemorySize));
Clay_SetMeasureTextFunction(Raylib_MeasureText);
Clay_Initialize(clayMemory, (Clay_Dimensions) { (float)GetScreenWidth(), (float)GetScreenHeight() }, (Clay_ErrorHandler) { HandleClayErrors });
Clay_SetMeasureTextFunction(Raylib_MeasureText, 0);
Clay_Raylib_Initialize(1024, 768, "Clay - Raylib Renderer Example", FLAG_VSYNC_HINT | FLAG_WINDOW_RESIZABLE | FLAG_WINDOW_HIGHDPI | FLAG_MSAA_4X_HINT);
profilePicture = LoadTextureFromImage(LoadImage("resources/profile-picture.png"));
Raylib_fonts[FONT_ID_BODY_24] = (Raylib_Font) {

View File

@ -12,13 +12,14 @@ typedef struct
TTF_Font *font;
} SDL2_Font;
static SDL2_Font SDL2_fonts[1];
static Clay_Dimensions SDL2_MeasureText(Clay_String *text, Clay_TextElementConfig *config)
static Clay_Dimensions SDL2_MeasureText(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData)
{
TTF_Font *font = SDL2_fonts[config->fontId].font;
char *chars = (char *)calloc(text->length + 1, 1);
memcpy(chars, text->chars, text->length);
SDL2_Font *fonts = (SDL2_Font*)userData;
TTF_Font *font = fonts[config->fontId].font;
char *chars = (char *)calloc(text.length + 1, 1);
memcpy(chars, text.chars, text.length);
int width = 0;
int height = 0;
if (TTF_SizeUTF8(font, chars, &width, &height) < 0) {
@ -34,7 +35,7 @@ static Clay_Dimensions SDL2_MeasureText(Clay_String *text, Clay_TextElementConfi
SDL_Rect currentClippingRectangle;
static void Clay_SDL2_Render(SDL_Renderer *renderer, Clay_RenderCommandArray renderCommands)
static void Clay_SDL2_Render(SDL_Renderer *renderer, Clay_RenderCommandArray renderCommands, SDL2_Font *fonts)
{
for (uint32_t i = 0; i < renderCommands.length; i++)
{
@ -60,7 +61,7 @@ static void Clay_SDL2_Render(SDL_Renderer *renderer, Clay_RenderCommandArray ren
Clay_String text = renderCommand->text;
char *cloned = (char *)calloc(text.length + 1, 1);
memcpy(cloned, text.chars, text.length);
TTF_Font* font = SDL2_fonts[config->fontId].font;
TTF_Font* font = fonts[config->fontId].font;
SDL_Surface *surface = TTF_RenderUTF8_Blended(font, cloned, (SDL_Color) {
.r = (Uint8)config->textColor.r,
.g = (Uint8)config->textColor.g,

View File

@ -83,7 +83,7 @@ static inline char *Clay_Cairo__NullTerminate(Clay_String *str) {
}
// Measure text using cairo's *toy* text API.
static inline Clay_Dimensions Clay_Cairo_MeasureText(Clay_String *str, Clay_TextElementConfig *config) {
static inline Clay_Dimensions Clay_Cairo_MeasureText(Clay_String *str, Clay_TextElementConfig *config, uintptr_t userData) {
// Edge case: Clay computes the width of a whitespace character
// once. Cairo does not factor in whitespaces when computing text
// extents, this edge-case serves as a short-circuit to introduce

View File

@ -89,7 +89,7 @@ Ray GetScreenToWorldPointWithZDistance(Vector2 position, Camera camera, int scre
uint32_t measureCalls = 0;
static inline Clay_Dimensions Raylib_MeasureText(Clay_String *text, Clay_TextElementConfig *config) {
static inline Clay_Dimensions Raylib_MeasureText(Clay_StringSlice text, Clay_TextElementConfig *config, uintptr_t userData) {
measureCalls++;
// Measure string size for Font
Clay_Dimensions textSize = { 0 };
@ -101,14 +101,14 @@ static inline Clay_Dimensions Raylib_MeasureText(Clay_String *text, Clay_TextEle
Font fontToUse = Raylib_fonts[config->fontId].font;
float scaleFactor = config->fontSize/(float)fontToUse.baseSize;
for (int i = 0; i < text->length; ++i)
for (int i = 0; i < text.length; ++i)
{
if (text->chars[i] == '\n') {
if (text.chars[i] == '\n') {
maxTextWidth = fmax(maxTextWidth, lineTextWidth);
lineTextWidth = 0;
continue;
}
int index = text->chars[i] - 32;
int index = text.chars[i] - 32;
if (fontToUse.glyphs[index].advanceX != 0) lineTextWidth += fontToUse.glyphs[index].advanceX;
else lineTextWidth += (fontToUse.recs[index].width + fontToUse.glyphs[index].offsetX);
}