Onlay: plain C99, weighted tracks, gaps, and #23's padding

A fork of randrew/layout, which is unmaintained and excellent. Three things
were needed by a declarative UI built on it, and one had to be fixed before
any of them could be built at all.

C99 EVERYWHERE. Upstream stores a rect in a GCC vector_size type and falls
back, on MSVC, to a C++ class with operator[] - which forces the whole library
to be compiled as C++ on that toolchain. Both are replaced by a struct holding
an array. The algorithm still indexes by dimension; the only change to the API
is that a rect is read as r.v[0] rather than r[0].

WEIGHTED TRACKS. lay_set_weight gives a filling item its share of the leftover
relative to its siblings, where upstream splits it equally. Weight 0 reads as
1, so an item that says nothing behaves as it did. A size on a weighted item is
a floor rather than a size, which makes one rule out of what CSS spells as
three: a fixed track, a minimum that grows, and a fraction.

GAPS. lay_set_gap puts space between an item's children without putting it
outside them - a row of three has two gaps and no leading or trailing one. It
applies down a wrapped row's lines as well as along them, and it is counted
when a container is sized to its contents, which a container was not: it came
out exactly one gap per child too short.

PADDING, from randrew/layout#23 by codecat, merged and then ported onto the
struct rect. A margin is space outside an item and a padding is space inside
it. The PR is carried as its own commit so its authorship stays where it
belongs.

The upstream tests are not carried: test_layout.c assumes the vector rect.
test_onlay.c replaces them and checks the arithmetic against numbers taken
from a running application rather than from this library - a login card,
weighted columns, floors that grow, template rows, and padding told apart from
margin on both halves, because a padding that only inset the children would
pass a test that looked at the children alone.

Every change is marked // ONLAY: in the source with the reason beside it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-10 21:38:16 +02:00
co-authored by Claude Opus 5
parent e020032601
commit a20a3cca7b
14 changed files with 606 additions and 2885 deletions
+4
View File
@@ -6,6 +6,10 @@ Blendish - Blender 2.5 UI based theming functions for NanoVG
Copyright (c) 2014 Leonard Ritter <leonard.ritter@duangle.com>
Onlay - a fork of the above, converted to plain C99 and extended
Copyright (c) 2026 Roman Chojnacki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
+81
View File
@@ -0,0 +1,81 @@
# Onlay
A 2D layout engine in C99. It computes rectangles and does nothing else — it
draws nothing, owns no widgets, handles no input, and knows nothing about the
program using it.
A fork of [randrew/layout](https://github.com/randrew/layout), which is itself
a rewrite of the layout engine from
[oui](https://bitbucket.org/duangle/oui-blendish). The original is excellent
and unmaintained; this fork exists to build as C99 on every compiler and to
add the three things a declarative UI needed.
```c
lay_context ctx;
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 256);
lay_id card = lay_item(&ctx);
lay_set_size_xy(&ctx, card, 420, 354);
lay_set_contain(&ctx, card, LAY_COLUMN | LAY_START);
lay_set_paddings_ltrb(&ctx, card, 24, 24, 24, 24);
lay_set_gap(&ctx, card, 10);
lay_id row = lay_item(&ctx);
lay_set_behave(&ctx, row, LAY_HFILL);
lay_set_weight(&ctx, row, 2.0f); /* twice a sibling's share */
lay_insert(&ctx, card, row);
lay_run_context(&ctx);
lay_vec4 r = lay_get_rect(&ctx, row); /* r.v[0..3] is x, y, w, h */
lay_destroy_context(&ctx);
```
Single header. `#define LAY_IMPLEMENTATION` in exactly one translation unit.
`#define LAY_FLOAT 1` for float coordinates instead of `int16_t`.
## What is different from randrew/layout
**It is C99 everywhere.** Upstream stores rects in a GCC `vector_size` type and
falls back to a C++ class with `operator[]` on MSVC — which forces the whole
library to be compiled as C++ on that toolchain. Both are replaced by a struct
holding an array. The algorithm still indexes by dimension, and the only change
to the API is that a rect is read as `r.v[0]` rather than `r[0]`.
**Weighted tracks.** `lay_set_weight(ctx, item, w)` gives a filling item its
share of the leftover space relative to its siblings, where upstream splits it
equally. Weight 0 reads as 1, so an item that says nothing behaves as before. A
size set on a weighted item is a floor rather than a size: "at least 80 wide,
then grow" is `lay_set_size_xy(..., 80, h)` with `LAY_HFILL`. That is one rule
covering what CSS spells as three — a fixed track, a minimum that grows, and a
fraction.
**Gaps.** `lay_set_gap(ctx, item, n)` puts space between an item's children
without putting it outside them, so a row of three has two gaps and no leading
or trailing one. It applies down a wrapped row's lines as well as along them,
and it is counted when a container is sized to its contents — otherwise a
container came out exactly one gap per child too short.
**Padding**, from [randrew/layout#23](https://github.com/randrew/layout/pull/23)
by [codecat](https://github.com/codecat), ported onto the struct rect. A margin
is space outside an item and a padding is space inside it: a padding insets the
rect an item lays its children into, and is added when that item is sized to
its contents.
Every change is marked `// ONLAY:` in the source with the reason next to it.
## Tests
`test_onlay.c` builds standalone and checks the arithmetic against numbers
taken from a running application rather than from this library — a login card,
weighted columns, floors that grow, template rows, and padding against margin.
Upstream's own `test_layout.c` is not carried: it assumes the vector rect.
```
cc -DLAY_FLOAT=1 -o onlaytest test_onlay.c && ./onlaytest
```
## Licence
MIT, as upstream. See `LICENSE` — the original copyright is Andrew Richards's
and is unchanged.
-281
View File
@@ -1,281 +0,0 @@
#include <stdio.h>
#define SOKOL_IMPL
#include "sokol_time.h"
#undef SOKOL_IMPL
#define LAY_IMPLEMENTATION
#include "layout.h"
#undef LAY_IMPLEMENTATION
#ifdef _WIN32
#include <windows.h>
LONG WINAPI LayTestUnhandledExceptionFilter(EXCEPTION_POINTERS* ExceptionInfo)
{
fputs("Exception", stdout);
fflush(stdout);
// TODO Do useful stuff
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
/*
int sprint_vec4(char* str, lay_vec4 v)
{
return sprintf(str, "%d, %d, %d, %d", v[0], v[1], v[2], v[3]);
}
int print_vec4(lay_vec4 v)
{
return printf("%d, %d, %d, %d", v[0], v[1], v[2], v[3]);
}
int sprint_vec2(char* str, lay_vec2 v)
{
return sprintf(str, "%d, %d", v[0], v[1]);
}
int sprint_item_info(char* str, lay_context *ctx, lay_id item)
{
int offs = 0;
lay_vec4 item_rect = lay_get_rect(ctx, item);
lay_vec4 item_margins = lay_get_margins(ctx, item);
lay_vec2 item_size = lay_get_size(ctx, item);
offs += sprintf(str + offs, "rect: ");
offs += sprint_vec4(str + offs, item_rect);
offs += sprintf(str + offs, " | margins: ");
offs += sprint_vec4(str + offs, item_margins);
offs += sprintf(str + offs, " | size: ");
offs += sprint_vec2(str + offs, item_size);
return offs;
}
*/
#define LTEST_TRUE(cond) \
if (cond) {} \
else { \
printf("Failed test at line %d in %s\n", __LINE__, __func__); \
fflush(stdout); \
abort(); \
}
#define LTEST_FALSE(cond) \
if (cond) { \
printf("Failed test at line %d in %s\n", __LINE__, __func__); \
fflush(stdout); \
abort(); \
} \
else {}
#define LTEST_DECLARE(testname) \
static void test_##testname(lay_context *ctx)
// vec4 equals test
#define LTEST_VEC4EQ(vecvar, x, y, z, w) \
LTEST_TRUE(vecvar[0] == x && vecvar[1] == y && vecvar[2] == z && vecvar[3] == w)
#define LTEST_VEC4UNEQ(vecvar, x, y, z, w) \
LTEST_FALSE(vecvar[0] == x && vecvar[1] == y && vecvar[2] == z && vecvar[3] == w)
static inline void benchmark_nested(lay_context *ctx)
{
const size_t num_rows = 5;
// one of the rows is "fake" and will have 0 units tall height
const size_t num_rows_with_height = num_rows - 1;
lay_id root = lay_item(ctx);
// main_child is a column that contains rows, and those rows
// will contain columns.
lay_id main_child = lay_item(ctx);
lay_set_size_xy(ctx, root,
70,
// 10 units extra size above and below for main_child
// margin
(num_rows_with_height * 10 + 2 * 10)
);
lay_set_margins_ltrb(ctx, main_child, 10, 10, 10, 10);
lay_set_contain(ctx, main_child, LAY_COLUMN);
lay_insert(ctx, root, main_child);
lay_set_behave(ctx, main_child, LAY_FILL);
lay_id *rows = (lay_id*)calloc(num_rows, sizeof(lay_id));
// auto-filling columns-in-row, each one should end up being
// 10 units wide
rows[0] = lay_item(ctx);
lay_set_contain(ctx, rows[0], LAY_ROW);
lay_set_behave(ctx, rows[0], LAY_FILL);
lay_id cols1[5];
// hmm so both the row and its child columns need to be set to
// fill? which means main_child also needs to be set to fill?
for (size_t i = 0; i < 5; ++i) {
lay_id col = lay_item(ctx);
// fill empty space
lay_set_behave(ctx, col, LAY_FILL);
lay_insert(ctx, rows[0], col);
cols1[i] = col;
}
rows[1] = lay_item(ctx);
lay_set_contain(ctx, rows[1], LAY_ROW);
lay_set_behave(ctx, rows[1], LAY_VFILL);
lay_id cols2[5];
for (size_t i = 0; i < 5; ++i) {
lay_id col = lay_item(ctx);
// fixed-size horizontally, fill vertically
lay_set_size_xy(ctx, col, 10, 0);
lay_set_behave(ctx, col, LAY_VFILL);
lay_insert(ctx, rows[1], col);
cols2[i] = col;
}
// these columns have an inner item which sizes them
rows[2] = lay_item(ctx);
lay_set_contain(ctx, rows[2], LAY_ROW);
lay_id cols3[2];
for (size_t i = 0; i < 2; ++i) {
lay_id col = lay_item(ctx);
lay_id inner_sizer = lay_item(ctx);
// only the second one will have height
lay_set_size_xy(ctx, inner_sizer, 25, 10 * (lay_scalar)i);
// align to bottom, only should make a difference for
// first item
lay_set_behave(ctx, col, LAY_BOTTOM);
lay_insert(ctx, col, inner_sizer);
lay_insert(ctx, rows[2], col);
cols3[i] = col;
}
// row 4 should end up being 0 units tall after layout
rows[3] = lay_item(ctx);
lay_set_contain(ctx, rows[3], LAY_ROW);
lay_set_behave(ctx, rows[3], LAY_HFILL);
lay_id cols4[99];
for (size_t i = 0; i < 99; ++i) {
lay_id col = lay_item(ctx);
lay_insert(ctx, rows[3], col);
cols4[i] = col;
}
// row 5 should be 10 pixels tall after layout, and each of
// its columns should be 1 pixel wide
rows[4] = lay_item(ctx);
lay_set_contain(ctx, rows[4], LAY_ROW);
lay_set_behave(ctx, rows[4], LAY_FILL);
lay_id cols5[50];
for (size_t i = 0; i < 50; ++i) {
lay_id col = lay_item(ctx);
lay_set_behave(ctx, col, LAY_FILL);
lay_insert(ctx, rows[4], col);
cols5[i] = col;
}
for (size_t i = 0; i < num_rows; ++i) {
lay_insert(ctx, main_child, rows[i]);
}
// Repeat the run and tests multiple times to make sure we get the expected
// results each time. The original version of oui would overwrite its input
// state (intentionally) with the output state, so the context's input data
// (margins, size) had to be "rebuilt" by the client code by doing a reset
// and then filling it back up for each run. 'lay' does not have that
// restriction.
//
// This is one of the more complex tests, so it's a good
// choice for testing multiple runs of the same context.
for (uint32_t run_n = 0; run_n < 5; ++run_n) {
//printf(" Iteration #%d\n", run_n + 1);
lay_run_context(ctx);
LTEST_VEC4EQ(lay_get_rect(ctx, main_child), 10, 10, 50, 40);
// These rows should all be 10 units in height
LTEST_VEC4EQ(lay_get_rect(ctx, rows[0]), 10, 10, 50, 10);
LTEST_VEC4EQ(lay_get_rect(ctx, rows[1]), 10, 20, 50, 10);
LTEST_VEC4EQ(lay_get_rect(ctx, rows[2]), 10, 30, 50, 10);
// this row should have 0 height
LTEST_VEC4EQ(lay_get_rect(ctx, rows[3]), 10, 40, 50, 0);
LTEST_VEC4EQ(lay_get_rect(ctx, rows[4]), 10, 40, 50, 10);
for (int16_t i = 0; i < 5; ++i) {
lay_vec4 r = lay_get_rect(ctx, cols1[i]);
// each of these should be 10 units wide, and stacked
// horizontally
LTEST_VEC4EQ(r, 10 + 10 * i, 10, 10, 10);
}
// the cols in the second row are similar to first row
for (int16_t i = 0; i < 5; ++i) {
lay_vec4 r = lay_get_rect(ctx, cols2[i]);
LTEST_VEC4EQ(r, 10 + 10 * i, 20, 10, 10);
}
// leftmost (first of two items), aligned to bottom of row, 0
// units tall
LTEST_VEC4EQ(lay_get_rect(ctx, cols3[0]), 10, 40, 25, 0);
// rightmost (second of two items), same height as row, which
// is 10 units tall
LTEST_VEC4EQ(lay_get_rect(ctx, cols3[1]), 35, 30, 25, 10);
// these should all have size 0 and be in the middle of the
// row
for (int16_t i = 0; i < 99; ++i) {
lay_vec4 r = lay_get_rect(ctx, cols4[i]);
LTEST_VEC4EQ(r, 25 + 10, 40, 0, 0);
}
// these should all be 1 unit wide and 10 units tall
for (int16_t i = 0; i < 50; ++i) {
lay_vec4 r = lay_get_rect(ctx, cols5[i]);
LTEST_VEC4EQ(r, 10 + i, 40, 1, 10);
}
}
free(rows);
}
// Call in main to run a test by name
//
// Resets string buffer and lay context before running test
#define LBENCH_RUN(testname) \
lay_reset_context(&ctx); \
printf(" * " #testname "\n");
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
#ifdef _WIN32
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter(LayTestUnhandledExceptionFilter);
#endif
stm_setup();
lay_context ctx;
lay_init_context(&ctx);
printf("Running benchmarks\n");
//LBENCH_RUN(benchmark_nested);
uint64_t total_perfc = 0;
const uint32_t num_runs = 100000;
uint64_t *run_times = (uint64_t*)calloc(num_runs, sizeof(uint64_t));
for (uint32_t run_n = 0; run_n < num_runs; ++run_n) {
lay_reset_context(&ctx);
uint64_t t1 = stm_now();
//printf(" * " #testname "\n");
benchmark_nested(&ctx);
uint64_t diff = stm_since(t1);
total_perfc += diff;
run_times[run_n] = diff;
//double seconds = perf_seconds(freq, diff);
//printf("Run %d: %f microsecs\n", run_n + 1, seconds * 1000000.0);
}
double avg = stm_us(total_perfc) / (double)num_runs;
printf("Average time: %f usecs", avg);
free(run_times);
lay_destroy_context(&ctx);
return 0;
}
-171
View File
@@ -1,171 +0,0 @@
local action = _ACTION or ""
newaction {
trigger = "clean",
description = "Clean everything",
execute = function ()
os.rmdir("./build")
end
}
newaction {
trigger = "asm",
description = "Emit GCC assembly output for a file",
-- Hard-coded for windows+gmake, probably has shell quote bugs
execute = function ()
os.execute("gcc -ggdb1 -Ofast -S -fno-stack-check -fno-dwarf2-cfi-asm -fno-asynchronous-unwind-tables -masm=intel -march=nehalem -fverbose-asm -DNDEBUG " .. _ARGS[1])
end
}
newoption {
trigger = "coords",
value = "coordtype",
description = "Use either integer or floating point for coordinates and sizes",
allowed = {
{ "integer", "16-bit signed integer" },
{ "float", "32-bit floating point" },
}
}
local targetDir = path.join("./build", _ACTION, "bin")
function incl_luajit()
configuration {}
includedirs {
"./thirdparty/LuaJIT-2.0.0/src",
}
-- Note: you will need to manually rebuild LuaJIT with the correct
-- compiler (mingw, msvc) first
libdirs {
"./thirdparty/LuaJIT-2.0.0/src",
}
-- lua51.dll
links { "lua51" }
end
function as_console_app()
kind "ConsoleApp"
-- Needed in mingw when building console app, genie/premake
-- automatically adds this for WindowedApp.
links { "gdi32" }
end
function as_shared_lib()
kind "SharedLib"
end
function lay_project(project_name, as_build_type, src_file)
project(project_name)
platforms { "x32", "x64" }
-- kind "ConsoleApp"
-- kind "WindowedApp"
language "C"
-- regular
--files { "**.h", "**.c" }
files { "**.h", src_file }
if _ACTION == "vs2015" or _ACTION == "vs2017" then
-- Build as C++ even with .c filename extension, because we
-- need [] operator for our vector types (GCC provides this in
-- C with vector_size special attribute, but need operator
-- overload in C++)
options { "ForceCpp" }
end
configuration {}
flags { "ExtraWarnings" }
targetdir(targetDir)
as_build_type()
configuration { "float" }
defines { "LAY_FLOAT=1" }
configuration { "vs*", "windows" }
defines { "_CRT_SECURE_NO_WARNINGS" }
buildoptions {
-- Disable "unreferenced formal parameter" warning
"-wd4100"
}
configuration { "gmake", "windows" }
-- Nehalem chips were released in 2008, and include SSE4.
--
-- Note that gcc -Q --help=target -march=nehalem (or whatever other
-- arch) will not correctly display the enabled/disabled flags for
-- stuff like SSE, etc. This is a known problem with gcc (it's on
-- their bug tracker). -march=native, however, will show the
-- enabled/disabled flags correctly.
buildoptions {
"-std=c99",
"-Wno-unused-parameter",
-- We want strict overflow on regardless of optimization level,
-- because it will change program semantics.
"-fstrict-overflow",
"-fstrict-aliasing",
"-Wstrict-aliasing=3",
"-march=nehalem"
}
configuration "Debug or Develop"
flags { "Symbols" }
configuration { "Debug" }
defines { "DEBUG" }
configuration { "Debug", "gmake" }
buildoptions {
"-ggdb",
"-fstack-protector-strong",
}
-- need to manually link -lssp for stack protector stuff
links { "ssp" }
configuration { "Develop or Release", "gmake" }
-- Remove some extra junk from the asm we don't need
buildoptions {
"-fno-stack-check",
"-fno-dwarf2-cfi-asm",
"-fno-asynchronous-unwind-tables",
}
configuration "Release"
defines { "NDEBUG", "WIN32_LEAN_AND_MEAN", "VC_EXTRALEAN" }
flags {
"Optimize",
"NoBufferSecurityCheck",
"NoWinRT",
"NoFramePointer",
}
windowstargetplatformversion "7"
configuration { "Release", "gmake" }
buildoptions {
"-Ofast",
"-fuse-linker-plugin",
"-flto",
"-fno-fat-lto-objects"
}
linkoptions {
"-flto",
"-fuse-linker-plugin",
"-s"
}
-- SSE2 in msvc must be explicitly enabled when building 32-bit. In
-- x64, /arch:SSE2 will produce a compiler warning, because it's
-- redundant (SSE2 always available in x64).
configuration { "Release or Develop", "x32" }
flags { "EnableSSE2" }
-- msvc builds are forced to C++, and we always want to disable
-- exceptions and RTTI.
configuration { "vs*" }
flags { "NoExceptions", "NoRTTI" }
configuration { "Release", "vs*" }
flags { "FloatFast" }
end
solution "layout"
location ( "build/" .. action )
configurations { "Debug", "Develop", "Release" }
lay_project("tests", as_console_app, "test_layout.c")
lay_project("benchmark", as_console_app, "benchmark_layout.c")
lay_project("luamodule", as_shared_lib, "luamodule_layout.c")
incl_luajit()
configuration {}
targetname("layout")
-294
View File
@@ -1,294 +0,0 @@
#define LAY_IMPLEMENTATION
#include "layout.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "lauxlib.h"
#ifdef __cplusplus
}
#endif
#if LAY_FLOAT == 1
#define LUALAY_CHECK_SCALAR luaL_checknumber
#define LUALAY_PUSH_SCALAR lua_pushnumber
#else
#define LUALAY_CHECK_SCALAR luaL_checkinteger
#define LUALAY_PUSH_SCALAR lua_pushinteger
#endif
int lualay_context_new(lua_State* L)
{
lua_settop(L, 0);
lay_context *ctx = (lay_context*)lua_newuserdata(L, sizeof(lay_context));
lay_init_context(ctx);
luaL_getmetatable(L, "Layout");
lua_setmetatable(L, -2);
return 1;
}
lay_context *lualay_context_check(lua_State *L)
{
void *ud = luaL_checkudata(L, 1, "Layout");
luaL_argcheck(L, ud != NULL, 1, "`Layout` expected");
return (lay_context*)ud;
}
lay_id lualay_id_check(lua_State *L, lay_context *ctx, int pos)
{
int n = (int)luaL_checkinteger(L, pos);
luaL_argcheck(L, n >= 0, pos, "Item id must be non-negative");
luaL_argcheck(L, (lay_id)n <= ctx->count, pos, "Item id is not in valid range for layout context");
return (lay_id)n;
}
lay_id lualay_id_check_notinserted(lua_State* L, lay_context *ctx, int pos)
{
lay_id id = lualay_id_check(L, ctx, pos);
const lay_item_t* pitem = lay_get_item(ctx, id);
uint32_t inserted = pitem->flags & LAY_ITEM_INSERTED;
luaL_argcheck(L, !inserted, pos, "Item has already been inserted");
return id;
}
int lualay_context_gc(lua_State* L)
{
lay_context* ctx = lualay_context_check(L);
lay_destroy_context(ctx);
return 0;
}
int lualay_context_capacity(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lua_settop(L, 0);
lay_id cap = lay_items_capacity(ctx);
if (cap > (lay_id)INT_MAX)
lua_pushinteger(L, INT_MAX);
else
lua_pushinteger(L, (int)cap);
return 1;
}
int lualay_reserve_items_capacity(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
int n = (int)luaL_checkinteger(L, 2);
luaL_argcheck(L, n >= 0, 2, "Zero or positive integer capacity expected");
lay_reserve_items_capacity(ctx, (lay_id)n);
return 0;
}
int lualay_item_new(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lua_pushinteger(L, lay_item(ctx));
return 1;
}
int lualay_run_context(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_run_context(ctx);
return 0;
}
int lualay_reset_context(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_reset_context(ctx);
return 0;
}
int lualay_item_insert(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id parent = lualay_id_check(L, ctx, 2);
lay_id child = lualay_id_check_notinserted(L, ctx, 3);
lay_insert(ctx, parent, child);
return 0;
}
int lualay_item_append(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id earlier = lualay_id_check(L, ctx, 2);
lay_id later = lualay_id_check_notinserted(L, ctx, 3);
lay_append(ctx, earlier, later);
return 0;
}
int lualay_item_push(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id parent = lualay_id_check(L, ctx, 2);
lay_id child = lualay_id_check_notinserted(L, ctx, 3);
lay_push(ctx, parent, child);
return 0;
}
int lualay_item_size_set(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
lay_scalar w = (lay_scalar)LUALAY_CHECK_SCALAR(L, 3);
lay_scalar h = (lay_scalar)LUALAY_CHECK_SCALAR(L, 4);
lay_set_size_xy(ctx, item, w, h);
return 0;
}
int lualay_item_margins_set(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
lay_scalar l = (lay_scalar)LUALAY_CHECK_SCALAR(L, 3);
lay_scalar t = (lay_scalar)LUALAY_CHECK_SCALAR(L, 4);
lay_scalar r = (lay_scalar)LUALAY_CHECK_SCALAR(L, 5);
lay_scalar b = (lay_scalar)LUALAY_CHECK_SCALAR(L, 6);
lay_set_margins_ltrb(ctx, item, l, t, r, b);
return 0;
}
int lualay_get_rect(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
lay_vec4 rect = lay_get_rect(ctx, item);
LUALAY_PUSH_SCALAR(L, rect[0]);
LUALAY_PUSH_SCALAR(L, rect[1]);
LUALAY_PUSH_SCALAR(L, rect[2]);
LUALAY_PUSH_SCALAR(L, rect[3]);
return 4;
}
// TODO make varargs
int lualay_item_contain_set(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
uint32_t flags = 0;
const int n = lua_gettop(L);
for (int i = 3; i <= n; ++i) {
flags |= luaL_checkinteger(L, i);
luaL_argcheck(L, (flags & LAY_ITEM_BOX_MASK) == flags, i, "Invalid container flag");
}
lay_set_contain(ctx, item, flags);
return 0;
}
int lualay_item_behave_set(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
uint32_t flags = 0;
const int n = lua_gettop(L);
for (int i = 3; i <= n; ++i) {
flags |= luaL_checkinteger(L, i);
luaL_argcheck(L, (flags & LAY_ITEM_LAYOUT_MASK) == flags, i, "Invalid behavior flag");
}
lay_set_behave(ctx, item, flags);
return 0;
}
int lualay_item_next_sibling(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
lay_id id_next = lay_next_sibling(ctx, item);
lua_settop(L, 0);
// lay_id is uint32_t by default, and LAY_INVALID_ID is uint32_t max, so we
// need to check if it's out of range
if (id_next >= (lay_id)INT_MAX)
lua_pushinteger(L, -1);
else
lua_pushinteger(L, (lay_id)id_next);
return 1;
}
int lualay_item_first_child(lua_State* L)
{
lay_context *ctx = lualay_context_check(L);
lay_id item = lualay_id_check(L, ctx, 2);
lay_id id_child = lay_first_child(ctx, item);
lua_settop(L, 0);
if (id_child >= (lay_id)INT_MAX)
lua_pushinteger(L, -1);
else
lua_pushinteger(L, (lay_id)id_child);
return 1;
}
static const struct luaL_reg laylib[] = {
{"new", lualay_context_new},
{"run", lualay_run_context},
{"reset", lualay_reset_context},
{"capacity", lualay_context_capacity},
{"reserve", lualay_reserve_items_capacity},
{"item", lualay_item_new},
{"insert", lualay_item_insert},
{"append", lualay_item_append},
{"push", lualay_item_push},
{"set_size", lualay_item_size_set},
{"set_margins", lualay_item_margins_set},
{"set_contain", lualay_item_contain_set},
{"set_behave", lualay_item_behave_set},
{"rect", lualay_get_rect},
{"next_sibling", lualay_item_next_sibling},
{"first_child", lualay_item_first_child},
{"__gc", lualay_context_gc},
{NULL, NULL}
};
#ifdef __cplusplus
extern "C" __declspec(dllexport) int luaopen_layout(lua_State* L)
#else
__declspec(dllexport) int luaopen_layout(lua_State* L)
#endif
{
// TODO update existing if hot reloading
luaL_newmetatable(L, "Layout");
lua_pushvalue(L, -1);
lua_pushstring(L, "__index");
lua_pushvalue(L, -2);
lua_settable(L, -3);
luaL_openlib(L, NULL, laylib, 0);
lua_setglobal(L, "Layout");
// Set integer flag constants
#define LUALAY_VAL(flagsym, fieldname) \
lua_pushinteger(L, flagsym); \
lua_setfield(L, -2, "" #fieldname "");
LUALAY_VAL(LAY_ROW, ROW);
LUALAY_VAL(LAY_COLUMN, COLUMN);
LUALAY_VAL(LAY_LAYOUT, OVERLAY);
LUALAY_VAL(LAY_FLEX, FLEX);
LUALAY_VAL(LAY_NOWRAP, NOWRAP);
LUALAY_VAL(LAY_WRAP, WRAP);
LUALAY_VAL(LAY_START, START);
LUALAY_VAL(LAY_MIDDLE, MIDDLE);
LUALAY_VAL(LAY_END, END);
LUALAY_VAL(LAY_JUSTIFY, JUSTIFY);
LUALAY_VAL(LAY_LEFT, LEFT);
LUALAY_VAL(LAY_TOP, TOP);
LUALAY_VAL(LAY_RIGHT, RIGHT);
LUALAY_VAL(LAY_BOTTOM, BOTTOM);
LUALAY_VAL(LAY_HFILL, HFILL);
LUALAY_VAL(LAY_VFILL, VFILL);
LUALAY_VAL(LAY_HCENTER, HCENTER);
LUALAY_VAL(LAY_VCENTER, VCENTER);
LUALAY_VAL(LAY_CENTER, CENTER);
LUALAY_VAL(LAY_FILL, FILL);
LUALAY_VAL(LAY_BREAK, BREAK);
#undef LUALAY_VAL
// TODO flags for preventing being squished (HFIXED/VFIXED)
return 0;
}
+6
View File
@@ -0,0 +1,6 @@
/* onlay.c - the implementation, so onlay.h can be included anywhere.
*
* Onlay is a layout engine and nothing else: it computes rectangles and knows
* nothing about widgets, drawing or events. See onlay.h and README.md. */
#define LAY_IMPLEMENTATION
#include "onlay.h"
+184 -135
View File
@@ -47,54 +47,25 @@ typedef int16_t lay_scalar;
#define LAY_INVALID_ID UINT32_MAX
// GCC and Clang allow us to create vectors based on a type with the
// vector_size extension. This will allow us to access individual components of
// the vector via indexing operations.
#if defined(__GNUC__) || defined(__clang__)
// Using floats for coordinates takes up more space than using int16. 128 bits
// for a four-component vector.
#ifdef LAY_FLOAT
typedef float lay_vec4 __attribute__ ((__vector_size__ (16), aligned(4)));
typedef float lay_vec2 __attribute__ ((__vector_size__ (8), aligned(4)));
// Integer version uses 64 bits for a four-component vector.
#else
typedef int16_t lay_vec4 __attribute__ ((__vector_size__ (8), aligned(2)));
typedef int16_t lay_vec2 __attribute__ ((__vector_size__ (4), aligned(2)));
#endif // LAY_FLOAT
// Note that we're not actually going to make any explicit use of any
// platform's SIMD instructions -- we're just using the vector extension for
// more convenient syntax. Therefore, we can specify more relaxed alignment
// requirements. See the end of this file for some notes about this.
// MSVC doesn't have the vetor_size attribute, but we want convenient indexing
// operators for our layout logic code. Therefore, we force C++ compilation in
// MSVC, and use C++ operator overloading.
#elif defined(_MSC_VER)
struct lay_vec4 {
lay_scalar xyzw[4];
const lay_scalar& operator[](int index) const
{ return xyzw[index]; }
lay_scalar& operator[](int index)
{ return xyzw[index]; }
};
struct lay_vec2 {
lay_scalar xy[2];
const lay_scalar& operator[](int index) const
{ return xy[index]; }
lay_scalar& operator[](int index)
{ return xy[index]; }
};
#endif // __GNUC__/__clang__ or _MSC_VER
// ONLAY: upstream used GCC's vector_size extension here, and a C++ class with
// operator[] as the MSVC fallback - which forces the whole library to be
// compiled as C++ on that toolchain. Both are replaced by a struct holding an
// array, so the algorithm still indexes by dimension and this stays C99
// everywhere. Rects are read as r.v[0] rather than r[0]; that is the only
// change to the API.
typedef struct lay_vec4 { lay_scalar v[4]; } lay_vec4;
typedef struct lay_vec2 { lay_scalar v[2]; } lay_vec2;
typedef struct lay_item_t {
uint32_t flags;
lay_id first_child;
lay_id next_sibling;
lay_vec4 margins;
// ONLAY: from randrew/layout#23 by codecat, ported onto the struct vec.
lay_vec4 paddings;
lay_vec2 size;
lay_scalar gap; // ONLAY: see lay_set_gap
float weight; // ONLAY: see lay_set_weight
} lay_item_t;
typedef struct lay_context {
@@ -221,22 +192,19 @@ enum {
// which flag bits will be compared
LAY_ITEM_COMPARE_MASK = LAY_ITEM_BOX_MODEL_MASK
| (LAY_ITEM_LAYOUT_MASK & ~LAY_BREAK)
// ONLAY: cast so the expression does not mix two enum types (MSVC C5287)
| (LAY_ITEM_LAYOUT_MASK & ~(uint32_t)LAY_BREAK)
| LAY_USERMASK
};
LAY_STATIC_INLINE lay_vec4 lay_vec4_xyzw(lay_scalar x, lay_scalar y, lay_scalar z, lay_scalar w)
{
#if (defined(__GNUC__) || defined(__clang__)) && !defined(__cplusplus)
return (lay_vec4){x, y, z, w};
#else
lay_vec4 result;
result[0] = x;
result[1] = y;
result[2] = z;
result[3] = w;
result.v[0] = x;
result.v[1] = y;
result.v[2] = z;
result.v[3] = w;
return result;
#endif
}
// Call this on a context before using it. You must also call this on a context
@@ -356,6 +324,25 @@ LAY_EXPORT void lay_set_contain(lay_context *ctx, lay_id item, uint32_t flags);
// up all available vertical space inside of its parent.
LAY_EXPORT void lay_set_behave(lay_context *ctx, lay_id item, uint32_t flags);
// ONLAY: how much of the leftover space a filling item takes, relative to its
// filling siblings. The default of zero reads as one, so three children left
// alone still split the space three ways.
//
// A filling item's own size is a floor it keeps before any sharing happens, so
// "at least 80 pixels, then grow" is a size of 80 with LAY_HFILL set. One
// formula then covers proportional columns, fr-style grid tracks, and minimum
// widths alike:
//
// final = floor + leftover * weight / total_weight
// ONLAY: space left between this item's children, along the axis it stacks
// them on. Applies between children only, never outside the first or last -
// use margins or the container's own padding for that.
LAY_EXPORT void lay_set_gap(lay_context *ctx, lay_id item, lay_scalar gap);
LAY_EXPORT lay_scalar lay_get_gap(lay_context *ctx, lay_id item);
LAY_EXPORT void lay_set_weight(lay_context *ctx, lay_id item, float weight);
LAY_EXPORT float lay_get_weight(lay_context *ctx, lay_id item);
// Get the margins that were set by lay_set_margins. The _ltrb version writes
// the output values to the specified addresses instead of returning the values
// in a lay_vec4.
@@ -380,6 +367,10 @@ LAY_EXPORT void lay_get_paddings_ltrb(lay_context *ctx, lay_id item, lay_scalar
// Set the paddings on an item. The components of the vector are:
// 0: left, 1: top, 2: right, 3: bottom.
//
// A margin is space outside an item and a padding is space inside it: a
// container with paddings lays its children out in a rect inset by them, and
// reports itself that much larger when it is sized to its contents.
LAY_EXPORT void lay_set_paddings(lay_context *ctx, lay_id item, lay_vec4 ltrb);
// Same as lay_set_paddings, but the components are passed as separate arguments
@@ -395,8 +386,6 @@ LAY_STATIC_INLINE lay_item_t *lay_get_item(const lay_context *ctx, lay_id id)
return ctx->items + id;
}
// Get the id of first child of an item, if any. Returns LAY_INVALID_ID if there
// is no child.
LAY_STATIC_INLINE lay_id lay_first_child(const lay_context *ctx, lay_id id)
{
const lay_item_t *pitem = lay_get_item(ctx, id);
@@ -430,10 +419,10 @@ LAY_STATIC_INLINE void lay_get_rect_xywh(
{
LAY_ASSERT(id != LAY_INVALID_ID && id < ctx->count);
lay_vec4 rect = ctx->rects[id];
*x = rect[0];
*y = rect[1];
*width = rect[2];
*height = rect[3];
*x = rect.v[0];
*y = rect.v[1];
*width = rect.v[2];
*height = rect.v[3];
}
#undef LAY_EXPORT
@@ -695,8 +684,8 @@ void lay_get_size_xy(
{
lay_item_t *pitem = lay_get_item(ctx, item);
lay_vec2 size = pitem->size;
*x = size[0];
*y = size[1];
*x = size.v[0];
*y = size.v[1];
}
void lay_set_size(lay_context *ctx, lay_id item, lay_vec2 size)
@@ -704,11 +693,11 @@ void lay_set_size(lay_context *ctx, lay_id item, lay_vec2 size)
lay_item_t *pitem = lay_get_item(ctx, item);
pitem->size = size;
uint32_t flags = pitem->flags;
if (size[0] == 0)
if (size.v[0] == 0)
flags &= ~(uint32_t)LAY_ITEM_HFIXED;
else
flags |= LAY_ITEM_HFIXED;
if (size[1] == 0)
if (size.v[1] == 0)
flags &= ~(uint32_t)LAY_ITEM_VFIXED;
else
flags |= LAY_ITEM_VFIXED;
@@ -720,8 +709,8 @@ void lay_set_size_xy(
lay_scalar width, lay_scalar height)
{
lay_item_t *pitem = lay_get_item(ctx, item);
pitem->size[0] = width;
pitem->size[1] = height;
pitem->size.v[0] = width;
pitem->size.v[1] = height;
// Kinda redundant, whatever
uint32_t flags = pitem->flags;
if (width == 0)
@@ -735,6 +724,27 @@ void lay_set_size_xy(
pitem->flags = flags;
}
void lay_set_gap(lay_context *ctx, lay_id item, lay_scalar gap)
{
lay_get_item(ctx, item)->gap = gap;
}
lay_scalar lay_get_gap(lay_context *ctx, lay_id item)
{
return lay_get_item(ctx, item)->gap;
}
void lay_set_weight(lay_context *ctx, lay_id item, float weight)
{
LAY_ASSERT(weight >= 0.0f);
lay_get_item(ctx, item)->weight = weight;
}
float lay_get_weight(lay_context *ctx, lay_id item)
{
return lay_get_item(ctx, item)->weight;
}
void lay_set_behave(lay_context *ctx, lay_id item, uint32_t flags)
{
LAY_ASSERT((flags & LAY_ITEM_LAYOUT_MASK) == flags);
@@ -763,25 +773,10 @@ void lay_set_margins_ltrb(
// Alternative, uses rax and left-shift
//pitem->margins = (lay_vec4){l, t, r, b};
// Fewest instructions, but uses more addressed writes?
pitem->margins[0] = l;
pitem->margins[1] = t;
pitem->margins[2] = r;
pitem->margins[3] = b;
}
lay_vec4 lay_get_margins(lay_context *ctx, lay_id item)
{ return lay_get_item(ctx, item)->margins; }
void lay_get_margins_ltrb(
lay_context *ctx, lay_id item,
lay_scalar *l, lay_scalar *t, lay_scalar *r, lay_scalar *b)
{
lay_item_t *pitem = lay_get_item(ctx, item);
lay_vec4 margins = pitem->margins;
*l = margins[0];
*t = margins[1];
*r = margins[2];
*b = margins[3];
pitem->margins.v[0] = l;
pitem->margins.v[1] = t;
pitem->margins.v[2] = r;
pitem->margins.v[3] = b;
}
void lay_set_paddings(lay_context *ctx, lay_id item, lay_vec4 ltrb)
@@ -789,15 +784,16 @@ void lay_set_paddings(lay_context *ctx, lay_id item, lay_vec4 ltrb)
lay_item_t *pitem = lay_get_item(ctx, item);
pitem->paddings = ltrb;
}
void lay_set_paddings_ltrb(
lay_context *ctx, lay_id item,
lay_scalar l, lay_scalar t, lay_scalar r, lay_scalar b)
{
lay_item_t *pitem = lay_get_item(ctx, item);
pitem->paddings[0] = l;
pitem->paddings[1] = t;
pitem->paddings[2] = r;
pitem->paddings[3] = b;
pitem->paddings.v[0] = l;
pitem->paddings.v[1] = t;
pitem->paddings.v[2] = r;
pitem->paddings.v[3] = b;
}
lay_vec4 lay_get_paddings(lay_context *ctx, lay_id item)
@@ -809,10 +805,28 @@ void lay_get_paddings_ltrb(
{
lay_item_t *pitem = lay_get_item(ctx, item);
lay_vec4 paddings = pitem->paddings;
*l = paddings[0];
*t = paddings[1];
*r = paddings[2];
*b = paddings[3];
*l = paddings.v[0];
*t = paddings.v[1];
*r = paddings.v[2];
*b = paddings.v[3];
}
// Get the id of first child of an item, if any. Returns LAY_INVALID_ID if there
// is no child.
lay_vec4 lay_get_margins(lay_context *ctx, lay_id item)
{ return lay_get_item(ctx, item)->margins; }
void lay_get_margins_ltrb(
lay_context *ctx, lay_id item,
lay_scalar *l, lay_scalar *t, lay_scalar *r, lay_scalar *b)
{
lay_item_t *pitem = lay_get_item(ctx, item);
lay_vec4 margins = pitem->margins;
*l = margins.v[0];
*t = margins.v[1];
*r = margins.v[2];
*b = margins.v[3];
}
// TODO restrict item ptrs correctly
@@ -828,11 +842,11 @@ lay_scalar lay_calc_overlayed_size(
lay_item_t *pchild = lay_get_item(ctx, child);
lay_vec4 rect = ctx->rects[child];
// width = start margin + calculated width + end margin
lay_scalar child_size = rect[dim] + rect[2 + dim] + pchild->margins[wdim];
lay_scalar child_size = rect.v[dim] + rect.v[2 + dim] + pchild->margins.v[wdim];
need_size = lay_scalar_max(need_size, child_size);
child = pchild->next_sibling;
}
return pitem->paddings[dim] + pitem->paddings[wdim] + need_size;
return pitem->paddings.v[dim] + pitem->paddings.v[wdim] + need_size;
}
static LAY_FORCE_INLINE
@@ -843,13 +857,21 @@ lay_scalar lay_calc_stacked_size(
lay_item_t *LAY_RESTRICT pitem = lay_get_item(ctx, item);
lay_scalar need_size = 0;
lay_id child = pitem->first_child;
lay_id kids = 0; // ONLAY: for the gaps between them
while (child != LAY_INVALID_ID) {
lay_item_t *pchild = lay_get_item(ctx, child);
lay_vec4 rect = ctx->rects[child];
need_size += rect[dim] + rect[2 + dim] + pchild->margins[wdim];
need_size += rect.v[dim] + rect.v[2 + dim] + pchild->margins.v[wdim];
child = pchild->next_sibling;
kids++;
}
return pitem->paddings[dim] + pitem->paddings[wdim] + need_size;
// ONLAY: a gap sits between children, so it is part of what they need. It
// was applied when they were arranged and not when they were measured, so
// a container sized to its contents came out one gap per child too short
// and everything below it rode up by exactly that.
if (kids > 1 && pitem->gap > 0)
need_size += pitem->gap * (lay_scalar)(kids - 1);
return pitem->paddings.v[dim] + pitem->paddings.v[wdim] + need_size;
}
static LAY_FORCE_INLINE
@@ -860,6 +882,7 @@ lay_scalar lay_calc_wrapped_overlayed_size(
lay_item_t *LAY_RESTRICT pitem = lay_get_item(ctx, item);
lay_scalar need_size = 0;
lay_scalar need_size2 = 0;
lay_scalar breaks = 0; // ONLAY: for the gaps between lines
lay_id child = pitem->first_child;
while (child != LAY_INVALID_ID) {
lay_item_t *pchild = lay_get_item(ctx, child);
@@ -867,12 +890,19 @@ lay_scalar lay_calc_wrapped_overlayed_size(
if (pchild->flags & LAY_BREAK) {
need_size2 += need_size;
need_size = 0;
breaks++; // ONLAY: one fewer than the number of lines
}
lay_scalar child_size = rect[dim] + rect[2 + dim] + pchild->margins[wdim];
lay_scalar child_size = rect.v[dim] + rect.v[2 + dim] + pchild->margins.v[wdim];
need_size = lay_scalar_max(need_size, child_size);
child = pchild->next_sibling;
}
return pitem->paddings[dim] + pitem->paddings[wdim] + need_size2 + need_size;
// ONLAY: a gap separates one wrapped line from the next as well as one
// child from its sibling, so a container sized to its contents has to
// leave room for them. Without this a wrapping row came out exactly its
// lines tall and they touched.
if (pitem->gap > 0)
need_size2 += pitem->gap * breaks;
return pitem->paddings.v[dim] + pitem->paddings.v[wdim] + need_size2 + need_size;
}
// Equivalent to uiComputeWrappedStackedSize
@@ -884,18 +914,26 @@ lay_scalar lay_calc_wrapped_stacked_size(
lay_item_t *LAY_RESTRICT pitem = lay_get_item(ctx, item);
lay_scalar need_size = 0;
lay_scalar need_size2 = 0;
lay_id kids = 0; // ONLAY: children on the line being measured
lay_id child = pitem->first_child;
while (child != LAY_INVALID_ID) {
lay_item_t *pchild = lay_get_item(ctx, child);
lay_vec4 rect = ctx->rects[child];
if (pchild->flags & LAY_BREAK) {
// ONLAY: same rule as lay_calc_stacked_size, once per line
if (kids > 1 && pitem->gap > 0)
need_size += pitem->gap * (kids - 1);
need_size2 = lay_scalar_max(need_size2, need_size);
need_size = 0;
kids = 0;
}
need_size += rect[dim] + rect[2 + dim] + pchild->margins[wdim];
need_size += rect.v[dim] + rect.v[2 + dim] + pchild->margins.v[wdim];
kids++;
child = pchild->next_sibling;
}
return pitem->paddings[dim] + pitem->paddings[wdim] + lay_scalar_max(need_size2, need_size);
if (kids > 1 && pitem->gap > 0)
need_size += pitem->gap * (kids - 1);
return pitem->paddings.v[dim] + pitem->paddings.v[wdim] + lay_scalar_max(need_size2, need_size);
}
static void lay_calc_size(lay_context *ctx, lay_id item, int dim)
@@ -912,12 +950,12 @@ static void lay_calc_size(lay_context *ctx, lay_id item, int dim)
}
// Set the mutable rect output data to the starting input data
ctx->rects[item][dim] = pitem->margins[dim];
ctx->rects[item].v[dim] = pitem->margins.v[dim];
// If we have an explicit input size, just set our output size (which other
// calc_size and arrange procedures will use) to it.
if (pitem->size[dim] != 0) {
ctx->rects[item][2 + dim] = pitem->size[dim];
if (pitem->size.v[dim] != 0) {
ctx->rects[item].v[2 + dim] = pitem->size.v[dim];
return;
}
@@ -955,7 +993,7 @@ static void lay_calc_size(lay_context *ctx, lay_id item, int dim)
// Set our output data size. Will be used by parent calc_size procedures.,
// and by arrange procedures.
ctx->rects[item][2 + dim] = cal_size;
ctx->rects[item].v[2 + dim] = cal_size;
}
static LAY_FORCE_INLINE
@@ -966,15 +1004,18 @@ void lay_arrange_stacked(
lay_item_t *pitem = lay_get_item(ctx, item);
const uint32_t item_flags = pitem->flags;
const lay_scalar gap = pitem->gap; // RELAY
lay_vec4 rect = ctx->rects[item];
lay_scalar space = rect[2 + dim] - pitem->paddings[dim] - pitem->paddings[wdim];
lay_scalar space = rect.v[2 + dim] - pitem->paddings.v[dim]
- pitem->paddings.v[wdim];
float max_x2 = (float)(rect[dim] + space + pitem->paddings[dim]);
float max_x2 = (float)(rect.v[dim] + space + pitem->paddings.v[dim]);
lay_id start_child = pitem->first_child;
while (start_child != LAY_INVALID_ID) {
lay_scalar used = 0;
uint32_t count = 0; // count of fillers
float weight_total = 0.0f; // ONLAY: their weights, zero read as one
uint32_t squeezed_count = 0; // count of squeezable elements
uint32_t total = 0;
bool hardbreak = false;
@@ -990,13 +1031,17 @@ void lay_arrange_stacked(
const lay_vec4 child_margins = pchild->margins;
lay_vec4 child_rect = ctx->rects[child];
lay_scalar extend = used;
if (total) extend += gap; // ONLAY: between children, not outside them
if ((flags & LAY_HFILL) == LAY_HFILL) {
++count;
extend += child_rect[dim] + child_margins[wdim];
// ONLAY: reserve each filler's floor; see lay_set_weight.
weight_total += pchild->weight > 0.0f ? pchild->weight : 1.0f;
extend += child_rect.v[dim] + pchild->size.v[dim]
+ child_margins.v[wdim];
} else {
if ((fflags & LAY_ITEM_HFIXED) != LAY_ITEM_HFIXED)
++squeezed_count;
extend += child_rect[dim] + child_rect[2 + dim] + child_margins[wdim];
extend += child_rect.v[dim] + child_rect.v[2 + dim] + child_margins.v[wdim];
}
// wrap on end of line or manual flag
if (wrap && (
@@ -1022,7 +1067,7 @@ void lay_arrange_stacked(
if (extra_space > 0) {
if (count > 0)
filler = (float)extra_space / (float)count;
filler = (float)extra_space / weight_total; // ONLAY: per unit of weight
else if (total > 0) {
switch (item_flags & LAY_JUSTIFY) {
case LAY_JUSTIFY:
@@ -1057,7 +1102,7 @@ void lay_arrange_stacked(
eater = (float)extra_space / (float)squeezed_count;
// distribute width among items
float x = (float)rect[dim] + pitem->paddings[dim];
float x = (float)rect.v[dim] + pitem->paddings.v[dim];
float x1;
// second pass: distribute and rescale
child = start_child;
@@ -1070,25 +1115,27 @@ void lay_arrange_stacked(
const lay_vec4 child_margins = pchild->margins;
lay_vec4 child_rect = ctx->rects[child];
x += (float)child_rect[dim] + extra_margin;
x += (float)child_rect.v[dim] + extra_margin;
if ((flags & LAY_HFILL) == LAY_HFILL) // grow
x1 = x + filler;
// ONLAY: the item's floor, plus its share of what is left.
x1 = x + (float)pchild->size.v[dim]
+ filler * (pchild->weight > 0.0f ? pchild->weight : 1.0f);
else if ((fflags & LAY_ITEM_HFIXED) == LAY_ITEM_HFIXED)
x1 = x + (float)child_rect[2 + dim];
x1 = x + (float)child_rect.v[2 + dim];
else // squeeze
x1 = x + lay_float_max(0.0f, (float)child_rect[2 + dim] + eater);
x1 = x + lay_float_max(0.0f, (float)child_rect.v[2 + dim] + eater);
ix0 = (lay_scalar)x;
if (wrap)
ix1 = (lay_scalar)lay_float_min(max_x2 - (float)child_margins[wdim], x1);
ix1 = (lay_scalar)lay_float_min(max_x2 - (float)child_margins.v[wdim], x1);
else
ix1 = (lay_scalar)x1;
child_rect[dim] = ix0; // pos
child_rect[dim + 2] = ix1 - ix0; // size
child_rect.v[dim] = ix0; // pos
child_rect.v[dim + 2] = ix1 - ix0; // size
ctx->rects[child] = child_rect;
x = x1 + (float)child_margins[wdim];
x = x1 + (float)child_margins.v[wdim];
child = pchild->next_sibling;
extra_margin = spacer;
extra_margin = spacer + (float)gap; // ONLAY: gap joins the justify spacer
}
start_child = end_child;
@@ -1101,8 +1148,9 @@ void lay_arrange_overlay(lay_context *ctx, lay_id item, int dim)
const int wdim = dim + 2;
lay_item_t *pitem = lay_get_item(ctx, item);
const lay_vec4 rect = ctx->rects[item];
const lay_scalar offset = rect[dim] + pitem->paddings[dim];
const lay_scalar space = rect[2 + dim] - pitem->paddings[dim] - pitem->paddings[wdim];
const lay_scalar offset = rect.v[dim] + pitem->paddings.v[dim];
const lay_scalar space = rect.v[2 + dim] - pitem->paddings.v[dim]
- pitem->paddings.v[wdim];
lay_id child = pitem->first_child;
while (child != LAY_INVALID_ID) {
@@ -1113,19 +1161,19 @@ void lay_arrange_overlay(lay_context *ctx, lay_id item, int dim)
switch (b_flags & LAY_HFILL) {
case LAY_HCENTER:
child_rect[dim] += (space - child_rect[2 + dim]) / 2 - child_margins[wdim];
child_rect.v[dim] += (space - child_rect.v[2 + dim]) / 2 - child_margins.v[wdim];
break;
case LAY_RIGHT:
child_rect[dim] += space - child_rect[2 + dim] - child_margins[dim] - child_margins[wdim];
child_rect.v[dim] += space - child_rect.v[2 + dim] - child_margins.v[dim] - child_margins.v[wdim];
break;
case LAY_HFILL:
child_rect[2 + dim] = lay_scalar_max(0, space - child_rect[dim] - child_margins[wdim]);
child_rect.v[2 + dim] = lay_scalar_max(0, space - child_rect.v[dim] - child_margins.v[wdim]);
break;
default:
break;
}
child_rect[dim] += offset;
child_rect.v[dim] += offset;
ctx->rects[child] = child_rect;
child = pchild->next_sibling;
}
@@ -1144,24 +1192,24 @@ void lay_arrange_overlay_squeezed_range(
const uint32_t b_flags = (pitem->flags & LAY_ITEM_LAYOUT_MASK) >> dim;
const lay_vec4 margins = pitem->margins;
lay_vec4 rect = ctx->rects[item];
lay_scalar min_size = lay_scalar_max(0, space - rect[dim] - margins[wdim]);
lay_scalar min_size = lay_scalar_max(0, space - rect.v[dim] - margins.v[wdim]);
switch (b_flags & LAY_HFILL) {
case LAY_HCENTER:
rect[2 + dim] = lay_scalar_min(rect[2 + dim], min_size);
rect[dim] += (space - rect[2 + dim]) / 2 - margins[wdim];
rect.v[2 + dim] = lay_scalar_min(rect.v[2 + dim], min_size);
rect.v[dim] += (space - rect.v[2 + dim]) / 2 - margins.v[wdim];
break;
case LAY_RIGHT:
rect[2 + dim] = lay_scalar_min(rect[2 + dim], min_size);
rect[dim] = space - rect[2 + dim] - margins[wdim];
rect.v[2 + dim] = lay_scalar_min(rect.v[2 + dim], min_size);
rect.v[dim] = space - rect.v[2 + dim] - margins.v[wdim];
break;
case LAY_HFILL:
rect[2 + dim] = min_size;
rect.v[2 + dim] = min_size;
break;
default:
rect[2 + dim] = lay_scalar_min(rect[2 + dim], min_size);
rect.v[2 + dim] = lay_scalar_min(rect.v[2 + dim], min_size);
break;
}
rect[dim] += offset;
rect.v[dim] += offset;
ctx->rects[item] = rect;
item = pitem->next_sibling;
}
@@ -1173,7 +1221,7 @@ lay_scalar lay_arrange_wrapped_overlay_squeezed(
{
const int wdim = dim + 2;
lay_item_t *pitem = lay_get_item(ctx, item);
lay_scalar offset = ctx->rects[item][dim] + pitem->paddings[dim];
lay_scalar offset = ctx->rects[item].v[dim] + pitem->paddings.v[dim];
lay_scalar need_size = 0;
lay_id child = pitem->first_child;
lay_id start_child = child;
@@ -1181,12 +1229,12 @@ lay_scalar lay_arrange_wrapped_overlay_squeezed(
lay_item_t *pchild = lay_get_item(ctx, child);
if (pchild->flags & LAY_BREAK) {
lay_arrange_overlay_squeezed_range(ctx, dim, start_child, child, offset, need_size);
offset += need_size;
offset += need_size + pitem->gap; // ONLAY: between lines
start_child = child;
need_size = 0;
}
const lay_vec4 rect = ctx->rects[child];
lay_scalar child_size = rect[dim] + rect[2 + dim] + pchild->margins[wdim];
lay_scalar child_size = rect.v[dim] + rect.v[2 + dim] + pchild->margins.v[wdim];
need_size = lay_scalar_max(need_size, child_size);
child = pchild->next_sibling;
}
@@ -1205,7 +1253,7 @@ static void lay_arrange(lay_context *ctx, lay_id item, int dim)
if (dim != 0) {
lay_arrange_stacked(ctx, item, 1, true);
lay_scalar offset = lay_arrange_wrapped_overlay_squeezed(ctx, item, 0);
ctx->rects[item][2 + 0] = offset - ctx->rects[item][0];
ctx->rects[item].v[2 + 0] = offset - ctx->rects[item].v[0];
}
break;
case LAY_ROW | LAY_WRAP:
@@ -1223,8 +1271,9 @@ static void lay_arrange(lay_context *ctx, lay_id item, int dim)
const lay_vec4 rect = ctx->rects[item];
lay_arrange_overlay_squeezed_range(
ctx, dim, pitem->first_child, LAY_INVALID_ID,
rect[dim] + pitem->paddings[dim],
rect[2 + dim] - pitem->paddings[dim] - pitem->paddings[2 + dim]);
rect.v[dim] + pitem->paddings.v[dim],
rect.v[2 + dim] - pitem->paddings.v[dim]
- pitem->paddings.v[2 + dim]);
}
break;
default:
-272
View File
@@ -1,272 +0,0 @@
Layout
======
A simple/fast stacking box layout library. It's useful for calculating layouts
for things like 2D user interfaces. It compiles as C99 or C++. It's tested with
gcc (mingw64), VS2015, and clang/LLVM. You only need one file to use it in your
own project: [layout.h](layout.h).
![](https://raw.githubusercontent.com/wiki/randrew/layoutexample/ui_anim_small.gif)
Use Layout in Your Project
--------------------------
To use *Layout* in your own project, copy [layout.h](layout.h) into your
project's source tree and define `LAY_IMPLEMENTATION` in exactly one `.c` or
`.cpp` file that includes [layout.h](layout.h).
The includes in your one special file should look like this:
```C
#include ...
#include ...
#define LAY_IMPLEMENTATION
#include "layout.h"
```
All other files in your project should not define `LAY_IMPLEMENTATION`, and can
include [layout.h](layout.h) like normal.
Requirements and Extras
-----------------------
*Layout* has no external dependencies, but by default it does use `assert.h`,
`stdlib.h` and `string.h` for `assert`, `realloc` and `memset`. If your own
project does not or cannot use these, you can easily exchange them for
something else by using preprocessor definitions. See the section below about
the available [customizations](#customizations).
*Layout* can be built as C99 or C++ if you are using GCC or Clang, but must be
built as C++ if you are using MSVC. This requirement exists because the
*Layout* implementation code uses the `vector_size` extension in GCC and Clang,
which does not exist in MSVC. C++ operator overloading is used to simulate this
feature in MSVC. The code generated by all three compilers is not too different
-- the `vector_size` extension is used mostly to keep the syntax of the
implementation easier to read.
*Layout* is based on the nice library
[oui](https://bitbucket.org/duangle/oui-blendish) by
[duangle](https://twitter.com/duangle). Unlike *oui*, *Layout* does not handle
anything related to user input, focus, or UI state.
Building the tests and benchmarks is handled by the [tool.bash](tool.bash)
script, or by [GENie](https://github.com/bkaradzic/GENie). See the section
below about [building the tests and
benchmarks](#building-the-tests-and-benchmarks). There's also an example of
using *Layout* as a Lua `.dll` module. However, you don't need any of that to
use *Layout* in your own project.
Options
-------
You can choose to build *Layout* to use either integer (int16) or floating
point (float) coordinates. Integer is the default, because UI and other 2D
layouts do not often use units smaller than a single point when aligning and
positioning elements. You can choose to use floating point instead of integer
by defining `LAY_FLOAT`.
* `LAY_FLOAT`, when defined, will use `float` instead of `int16` for
coordinates.
In addition to the `LAY_FLOAT` preprocessor option, other behavior in *Layout*
can be customized by setting preprocessor definitions. Default behavior will be
used for undefined customizations.
* `LAY_ASSERT` will replace the use of `assert.h`'s `assert`
* `LAY_REALLOC` will replace the use of `stdlib.h`'s `realloc`
* `LAY_MEMSET` will replace the use of `string.h`'s `memset`
If you define `LAY_REALLOC`, you will also need to define `LAY_FREE`.
Example
=======
```C
// LAY_IMPLEMENTATION needs to be defined in exactly one .c or .cpp file that
// includes layout.h. All other files should not define it.
#define LAY_IMPLEMENTATION
#include "layout.h"
// Let's pretend we're creating some kind of GUI with a master list on the
// left, and the content view on the right.
// We first need one of these
lay_context ctx;
// And we need to initialize it
lay_init_context(&ctx);
// The context will automatically resize its heap buffer to grow as needed
// during use. But we can avoid multiple reallocations by reserving as much
// space as we'll need up-front. Don't worry, lay_init_context doesn't do any
// allocations, so this is our first and only alloc.
lay_reserve_items_capacity(&ctx, 1024);
// Create our root item. Items are just 2D boxes.
lay_id root = lay_item(&ctx);
// Let's pretend we have a window in our game or OS of some known dimension.
// We'll want to explicitly set our root item to be that size.
lay_set_size_xy(&ctx, root, 1280, 720);
// Set our root item to arrange its children in a row, left-to-right, in the
// order they are inserted.
lay_set_contain(&ctx, root, LAY_ROW);
// Create the item for our master list.
lay_id master_list = lay_item(&ctx);
lay_insert(&ctx, root, master_list);
// Our master list has a specific fixed width, but we want it to fill all
// available vertical space.
lay_set_size_xy(&ctx, master_list, 400, 0);
// We set our item's behavior within its parent to desire filling up available
// vertical space.
lay_set_behave(&ctx, master_list, LAY_VFILL);
// And we set it so that it will lay out its children in a column,
// top-to-bottom, in the order they are inserted.
lay_set_contain(&ctx, master_list, LAY_COLUMN);
lay_id content_view = lay_item(&ctx);
lay_insert(&ctx, root, content_view);
// The content view just wants to fill up all of the remaining space, so we
// don't need to set any size on it.
//
// We could just set LAY_FILL here instead of bitwise-or'ing LAY_HFILL and
// LAY_VFILL, but I want to demonstrate that this is how you combine flags.
lay_set_behave(&ctx, content_view, LAY_HFILL | LAY_VFILL);
// Normally at this point, we would probably want to create items for our
// master list and our content view and insert them. This is just a dumb fake
// example, so let's move on to finishing up.
// Run the context -- this does all of the actual calculations.
lay_run_context(&ctx);
// Now we can get the calculated size of our items as 2D rectangles. The four
// components of the vector represent x and y of the top left corner, and then
// the width and height.
lay_vec4 master_list_rect = lay_get_rect(&ctx, master_list);
lay_vec4 content_view_rect = lay_get_rect(&ctx, content_view);
// master_list_rect == { 0, 0, 400, 720}
// content_view_rect == {400, 0, 880, 720}
// If we're using an immediate-mode graphics library, we could draw our boxes
// with it now.
my_ui_library_draw_box_x_y_width_height(
master_list_rect[0],
master_list_rect[1],
master_list_rect[2],
master_list_rect[3]);
// You could also recursively go through the entire item hierarchy using
// lay_first_child and lay_next_sibling, or something like that.
// After you've used lay_run_context, the results should remain valid unless a
// reallocation occurs.
//
// However, while it's true that you could manually update the existing items
// in the context by using lay_set_size{_xy}, and then calling lay_run_context
// again, you might want to consider just rebuilding everything from scratch
// every frame. This is a lot easier to program than tedious fine-grained
// invalidation, and a context with thousands of items will probably still only
// take a handful of microseconds.
//
// There's no way to remove items -- once you create them and insert them,
// that's it. If we want to reset our context so that we can rebuild our layout
// tree from scratch, we use lay_reset_context:
lay_reset_context(&ctx);
// And now we could start over with creating the root item, inserting more
// items, etc. The reason we don't create a new context from scratch is that we
// want to reuse the buffer that was already allocated.
// But let's pretend we're shutting down our program -- we need to destroy our
// context.
lay_destroy_context(&ctx);
// The heap-allocated buffer is now freed. The context is now invalid for use
// until lay_init_context is called on it again.
```
Building the Tests and Benchmarks
=================================
ⓘ | None of this is necessary to use in your own project. These directions are only for building the tests and benchmarks programs, which you probably don't care about.
:---: | :---
If you have bash and are on a POSIX system, you can use the `tool.bash`
script to build *Layout*'s standalone tests and benchmarks programs. Run
`tool.bash` to see the options.
<h3>Using GENie</h3>
Instead of using the `tool.bash` script, you can use GENie to generate a Visual
Studio project file, or any of the other project and build system output types
it supports. The GENie generator also lets you build the example Lua module.
<details>
<summary>Directions for acquiring and using GENie</summary>
The [genie.lua](genie.lua) script is mostly tested on Windows, so if you use it
on another platform, you might need to tweak it.
You will first need to get (or make) a GENie binary and place it in your path
or at the root of this repository.
Download GENie
--------------
Linux:
https://github.com/bkaradzic/bx/raw/master/tools/bin/linux/genie
OSX:
https://github.com/bkaradzic/bx/raw/master/tools/bin/darwin/genie
Windows:
https://github.com/bkaradzic/bx/raw/master/tools/bin/windows/genie.exe
Visual Studio 2015/2017
-----------------------
```
genie.exe vs2015
start build/vs2015/layout.sln
```
Replace vs2015 with vs2017 if you want to use Visual Studio 2017.
GCC/MinGW/Clang
---------------
```
./genie gmake
```
and then run your `make` in the directory `build/gmake`. You will need to
specify a target and config. Here is an example for building the `tests` target
in Windows with the 64-bit release configuration using mingw64 in a bash-like
shell (for example, git bash):
```
./genie.exe gmake && mingw32-make.exe -C build/gmake tests config=release64
```
If you want to use float coordinates instead of integer, you can use an option in the build script which will define `LAY_FLOAT` for you:
```
./genie gmake --coords=float
```
or if you want to specify integer (the default):
```
./genie gmake --coords=integer
```
</details>
-1035
View File
File diff suppressed because it is too large Load Diff
+331
View File
@@ -0,0 +1,331 @@
/* test_onlay.c - Onlay against known-good geometry.
*
* The first case is not invented: it is Reaktor's login card, with the
* expected coordinates taken from the accessibility dump of the running
* application rather than from Onlay. If Onlay disagrees with those numbers it
* is Onlay that is wrong.
*
* The rest cover weighted tracks, which is the one piece of arithmetic Onlay
* adds to what it was forked from. */
#include <stdio.h>
#include <string.h>
#include "onlay.h"
static int g_fail;
static void
check(const char *what, int got, int expect)
{
int ok = got == expect;
if (!ok) g_fail++;
printf(" %-26s %5d expected %5d %s\n",
what, got, expect, ok ? "ok" : "MISMATCH");
}
/* --- the login card ------------------------------------------------------
* Card 420x354. Content inset by 22 horizontally and 18 vertically, rows
* stacked with a 15px gap. */
#define CARD_W 420
#define CARD_H 354
#define PAD_X 22
#define PAD_Y 18
#define ROW_GAP 15
static void
test_login_card(void)
{
static const struct { const char *name; int h, y; } rows[] = {
{ "brand row", 28, 18 },
{ "field", 38, 61 },
{ "continue with email", 40, 114 },
{ "or", 18, 169 },
{ "use a passkey", 40, 202 },
{ "use biometrics", 40, 257 },
{ "contact", 18, 312 },
};
const int n = (int)(sizeof(rows) / sizeof(rows[0]));
lay_context ctx;
lay_id card, col, kid[7];
int i;
puts(" Reaktor's login card, against the app's own accessibility dump");
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 64);
card = lay_item(&ctx);
lay_set_size_xy(&ctx, card, CARD_W, CARD_H);
lay_set_contain(&ctx, card, LAY_COLUMN);
col = lay_item(&ctx);
lay_set_behave(&ctx, col, LAY_FILL);
/* A container that does not say how to distribute slack centres it -
* LAY_MIDDLE is zero. Saying START is not optional. */
lay_set_contain(&ctx, col, LAY_COLUMN | LAY_START);
lay_set_margins_ltrb(&ctx, col, PAD_X, PAD_Y, PAD_X, PAD_Y);
/* The gap is the container's business, not each child's. Expressed as a
* margin on every row but the first, this produces the same seven
* coordinates - which is what makes it a test of gap rather than of the
* numbers. */
lay_set_gap(&ctx, col, ROW_GAP);
lay_insert(&ctx, card, col);
for (i = 0; i < n; i++) {
kid[i] = lay_item(&ctx);
lay_set_size_xy(&ctx, kid[i], 0, (lay_scalar)rows[i].h);
lay_set_behave(&ctx, kid[i], LAY_HFILL | LAY_TOP);
lay_insert(&ctx, col, kid[i]);
}
lay_run_context(&ctx);
for (i = 0; i < n; i++) {
lay_vec4 r = lay_get_rect(&ctx, kid[i]);
check(rows[i].name, (int)r.v[1], rows[i].y);
if (r.v[0] != PAD_X || r.v[2] != CARD_W - 2 * PAD_X) {
printf(" %-26s x=%d w=%d expected x=%d w=%d MISMATCH\n",
rows[i].name, (int)r.v[0], (int)r.v[2],
PAD_X, CARD_W - 2 * PAD_X);
g_fail++;
}
}
lay_destroy_context(&ctx);
}
/* --- proportional columns ------------------------------------------------
* What nk_layout_row_push(0.2f / 0.5f / 0.3f) means on the Layout page. */
static void
test_weighted_columns(void)
{
static const struct { float w; int expect_x, expect_w; } cols[] = {
{ 0.2f, 0, 60 },
{ 0.5f, 60, 150 },
{ 0.3f, 210, 90 },
};
const int n = 3;
lay_context ctx;
lay_id row, kid[3];
int i;
puts(" proportional columns: 0.2 / 0.5 / 0.3 of 300px");
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 16);
row = lay_item(&ctx);
lay_set_size_xy(&ctx, row, 300, 30);
lay_set_contain(&ctx, row, LAY_ROW | LAY_START);
for (i = 0; i < n; i++) {
kid[i] = lay_item(&ctx);
lay_set_behave(&ctx, kid[i], LAY_HFILL | LAY_TOP);
lay_set_weight(&ctx, kid[i], cols[i].w);
lay_insert(&ctx, row, kid[i]);
}
lay_run_context(&ctx);
for (i = 0; i < n; i++) {
lay_vec4 r = lay_get_rect(&ctx, kid[i]);
char label[32];
sprintf(label, "%.0f%% width", (double)(cols[i].w * 100.0f));
check(label, (int)r.v[2], cols[i].expect_w);
sprintf(label, "%.0f%% x", (double)(cols[i].w * 100.0f));
check(label, (int)r.v[0], cols[i].expect_x);
}
lay_destroy_context(&ctx);
}
/* --- a floor, then growth ------------------------------------------------
* nk_layout_row_template_push_variable(80): at least 80 pixels, then take an
* equal share of whatever is left. */
static void
test_minimum_then_grow(void)
{
lay_context ctx;
lay_id row, a, b;
lay_vec4 ra, rb;
puts(" a floor of 80 beside an unconstrained sibling, in 300px");
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 16);
row = lay_item(&ctx);
lay_set_size_xy(&ctx, row, 300, 30);
lay_set_contain(&ctx, row, LAY_ROW | LAY_START);
a = lay_item(&ctx);
lay_set_size_xy(&ctx, a, 80, 0); /* the floor */
lay_set_behave(&ctx, a, LAY_HFILL | LAY_TOP);
lay_insert(&ctx, row, a);
b = lay_item(&ctx);
lay_set_behave(&ctx, b, LAY_HFILL | LAY_TOP);
lay_insert(&ctx, row, b);
lay_run_context(&ctx);
ra = lay_get_rect(&ctx, a);
rb = lay_get_rect(&ctx, b);
/* 300 - 80 reserved = 220 shared two ways */
check("floored item width", (int)ra.v[2], 190);
check("sibling width", (int)rb.v[2], 110);
check("sibling x", (int)rb.v[0], 190);
lay_destroy_context(&ctx);
}
/* --- template rows, which is what "grid" means here ----------------------
* nk_layout_row_template_* defines column rules once and reuses them down the
* page: a fixed track, a "no narrower than 80, then grow" track, and a track
* that just grows. Onlay has no grid primitive and does not need one - rows
* that carry the same weights and floors put their columns in the same place,
* which is what makes a template a grid.
*
* This test exists to prove that, so that nothing is added to Onlay for it. */
static void
test_template_rows(void)
{
const int W = 500, COL_GAP = 10, ROW_GAP2 = 8, ROWS = 3;
lay_scalar want_x[3] = { 0, 130, 360 };
lay_scalar want_w[3] = { 120, 220, 140 };
lay_context ctx;
lay_id page, row, cell[3][3];
int r, c;
puts(" template rows: fixed 120 | floor 80 grow | grow, in 500px");
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 32);
page = lay_item(&ctx);
lay_set_size_xy(&ctx, page, W, 200);
lay_set_contain(&ctx, page, LAY_COLUMN | LAY_START);
lay_set_gap(&ctx, page, ROW_GAP2);
for (r = 0; r < ROWS; r++) {
row = lay_item(&ctx);
lay_set_behave(&ctx, row, LAY_HFILL);
lay_set_size_xy(&ctx, row, 0, 30);
lay_set_contain(&ctx, row, LAY_ROW | LAY_START);
lay_set_gap(&ctx, row, COL_GAP);
lay_insert(&ctx, page, row);
for (c = 0; c < 3; c++) {
cell[r][c] = lay_item(&ctx);
lay_insert(&ctx, row, cell[r][c]);
}
/* the template, identical in every row */
lay_set_size_xy(&ctx, cell[r][0], 120, 0); /* fixed */
lay_set_behave(&ctx, cell[r][0], LAY_TOP);
lay_set_size_xy(&ctx, cell[r][1], 80, 0); /* floor */
lay_set_behave(&ctx, cell[r][1], LAY_HFILL | LAY_TOP);
lay_set_behave(&ctx, cell[r][2], LAY_HFILL | LAY_TOP); /* grow */
}
lay_run_context(&ctx);
for (r = 0; r < ROWS; r++)
for (c = 0; c < 3; c++) {
lay_vec4 q = lay_get_rect(&ctx, cell[r][c]);
char label[40];
sprintf(label, "row %d col %d x", r, c);
check(label, (int)q.v[0], (int)want_x[c]);
sprintf(label, "row %d col %d w", r, c);
check(label, (int)q.v[2], (int)want_w[c]);
}
lay_destroy_context(&ctx);
}
/* Padding, from randrew/layout#23.
*
* A margin is space outside an item and a padding is space inside it, and the
* two are told apart by who moves: a margin moves the item, a padding moves
* the item's children and leaves the item where it was. Both halves are
* checked here, because a padding that only insets the children would still
* pass a test that looked at the children alone - the container has to report
* itself larger too, or a parent sizing to its contents will crop it. */
static void
test_padding(void)
{
lay_context ctx;
lay_id root, box, a, b;
lay_vec4 rb, ra, rr;
puts("a padding is space inside an item, not outside it");
lay_init_context(&ctx);
lay_reserve_items_capacity(&ctx, 16);
root = lay_item(&ctx);
lay_set_size_xy(&ctx, root, 200, 200);
box = lay_item(&ctx);
lay_set_contain(&ctx, box, LAY_ROW);
lay_set_behave(&ctx, box, LAY_LEFT | LAY_TOP);
lay_set_paddings_ltrb(&ctx, box, 10, 6, 10, 6);
lay_insert(&ctx, root, box);
a = lay_item(&ctx);
lay_set_size_xy(&ctx, a, 30, 20);
lay_insert(&ctx, box, a);
b = lay_item(&ctx);
lay_set_size_xy(&ctx, b, 40, 20);
lay_insert(&ctx, box, b);
lay_run_context(&ctx);
rb = lay_get_rect(&ctx, box);
ra = lay_get_rect(&ctx, a);
check("the box starts where its parent put it", (int)rb.v[0], 0);
check("the first child starts a left padding in", (int)ra.v[0], 10);
check("and a top padding down", (int)ra.v[1], 6);
/* 30 + 40 of children, and 10 either side. */
check("the box is as wide as its children plus both paddings",
(int)rb.v[2], 90);
/* The taller child is 20, and 6 above and below. */
check("and as tall as the tallest plus both", (int)rb.v[3], 32);
/* What it is not: a margin. Same numbers on the other field move the box
* itself and leave its inside alone. */
lay_set_paddings_ltrb(&ctx, box, 0, 0, 0, 0);
lay_set_margins_ltrb(&ctx, box, 10, 6, 10, 6);
lay_run_context(&ctx);
rr = lay_get_rect(&ctx, box);
ra = lay_get_rect(&ctx, a);
check("a margin of the same size moves the box instead",
(int)rr.v[0], 10);
check("and its first child sits flush inside it",
(int)ra.v[0], (int)rr.v[0]);
check("the box is only as wide as its children", (int)rr.v[2], 70);
/* And that the getter answers what the setter was given. */
{
lay_scalar l = 0, t = 0, r = 0, b2 = 0;
lay_set_paddings_ltrb(&ctx, box, 1, 2, 3, 4);
lay_get_paddings_ltrb(&ctx, box, &l, &t, &r, &b2);
check("what was set comes back: left", (int)l, 1);
check("top", (int)t, 2);
check("right", (int)r, 3);
check("bottom", (int)b2, 4);
}
lay_destroy_context(&ctx);
}
int
main(void)
{
printf("onlay: item %d bytes, rect %d bytes, scalar %d\n\n",
(int)sizeof(lay_item_t), (int)sizeof(lay_vec4),
(int)sizeof(lay_scalar));
test_login_card();
puts("");
test_weighted_columns();
puts("");
test_minimum_then_grow();
puts("");
test_template_rows();
puts("");
test_padding();
printf("\n%s\n", g_fail ? "FAILED" : "onlay: all checks passed");
return g_fail ? 1 : 0;
}
-22
View File
@@ -1,22 +0,0 @@
zlib/libpng license
Copyright (c) 2018 Andre Weissflog
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
-2
View File
@@ -1,2 +0,0 @@
Put LuaJIT-2.0.0 src here (thirdparty/Luajit-2.0.0) if you want to build the
Lua/LuaJIT module. Better solution for this needed.
-277
View File
@@ -1,277 +0,0 @@
#ifndef SOKOL_TIME_INCLUDED
/*
sokol_time.h -- simple cross-platform time measurement
Project URL: https://github.com/floooh/sokol
Do this:
#define SOKOL_IMPL
before you include this file in *one* C or C++ file to create the
implementation.
Optionally provide the following defines with your own implementations:
SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
SOKOL_API_DECL - public function declaration prefix (default: extern)
SOKOL_API_IMPL - public function implementation prefix (default: -)
If sokol_time.h is compiled as a DLL, define the following before
including the declaration or implementation:
SOKOL_DLL
On Windows, SOKOL_DLL will define SOKOL_API_DECL as __declspec(dllexport)
or __declspec(dllimport) as needed.
void stm_setup();
Call once before any other functions to initialize sokol_time
(this calls for instance QueryPerformanceFrequency on Windows)
uint64_t stm_now();
Get current point in time in unspecified 'ticks'. The value that
is returned has no relation to the 'wall-clock' time and is
not in a specific time unit, it is only useful to compute
time differences.
uint64_t stm_diff(uint64_t new, uint64_t old);
Computes the time difference between new and old. This will always
return a positive, non-zero value.
uint64_t stm_since(uint64_t start);
Takes the current time, and returns the elapsed time since start
(this is a shortcut for "stm_diff(stm_now(), start)")
uint64_t stm_laptime(uint64_t* last_time);
This is useful for measuring frame time and other recurring
events. It takes the current time, returns the time difference
to the value in last_time, and stores the current time in
last_time for the next call. If the value in last_time is 0,
the return value will be zero (this usually happens on the
very first call).
Use the following functions to convert a duration in ticks into
useful time units:
double stm_sec(uint64_t ticks);
double stm_ms(uint64_t ticks);
double stm_us(uint64_t ticks);
double stm_ns(uint64_t ticks);
Converts a tick value into seconds, milliseconds, microseconds
or nanoseconds. Note that not all platforms will have nanosecond
or even microsecond precision.
Uses the following time measurement functions under the hood:
Windows: QueryPerformanceFrequency() / QueryPerformanceCounter()
MacOS/iOS: mach_absolute_time()
emscripten: performance.now()
Linux+others: clock_gettime(CLOCK_MONOTONIC)
zlib/libpng license
Copyright (c) 2018 Andre Weissflog
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#define SOKOL_TIME_INCLUDED (1)
#include <stdint.h>
#ifndef SOKOL_API_DECL
#if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_IMPL)
#define SOKOL_API_DECL __declspec(dllexport)
#elif defined(_WIN32) && defined(SOKOL_DLL)
#define SOKOL_API_DECL __declspec(dllimport)
#else
#define SOKOL_API_DECL extern
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
SOKOL_API_DECL void stm_setup(void);
SOKOL_API_DECL uint64_t stm_now(void);
SOKOL_API_DECL uint64_t stm_diff(uint64_t new_ticks, uint64_t old_ticks);
SOKOL_API_DECL uint64_t stm_since(uint64_t start_ticks);
SOKOL_API_DECL uint64_t stm_laptime(uint64_t* last_time);
SOKOL_API_DECL double stm_sec(uint64_t ticks);
SOKOL_API_DECL double stm_ms(uint64_t ticks);
SOKOL_API_DECL double stm_us(uint64_t ticks);
SOKOL_API_DECL double stm_ns(uint64_t ticks);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // SOKOL_TIME_INCLUDED
/*-- IMPLEMENTATION ----------------------------------------------------------*/
#ifdef SOKOL_IMPL
#define SOKOL_TIME_IMPL_INCLUDED (1)
#include <string.h> /* memset */
#ifndef SOKOL_API_IMPL
#define SOKOL_API_IMPL
#endif
#ifndef SOKOL_ASSERT
#include <assert.h>
#define SOKOL_ASSERT(c) assert(c)
#endif
#ifndef _SOKOL_PRIVATE
#if defined(__GNUC__)
#define _SOKOL_PRIVATE __attribute__((unused)) static
#else
#define _SOKOL_PRIVATE static
#endif
#endif
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
typedef struct {
uint32_t initialized;
LARGE_INTEGER freq;
LARGE_INTEGER start;
} _stm_state_t;
#elif defined(__APPLE__) && defined(__MACH__)
#include <mach/mach_time.h>
typedef struct {
uint32_t initialized;
mach_timebase_info_data_t timebase;
uint64_t start;
} _stm_state_t;
#elif defined(__EMSCRIPTEN__)
#include <emscripten/emscripten.h>
typedef struct {
uint32_t initialized;
double start;
} _stm_state_t;
#else /* anything else, this will need more care for non-Linux platforms */
#ifdef ESP8266
// On the ESP8266, clock_gettime ignores the first argument and CLOCK_MONOTONIC isn't defined
#define CLOCK_MONOTONIC 0
#endif
#include <time.h>
typedef struct {
uint32_t initialized;
uint64_t start;
} _stm_state_t;
#endif
static _stm_state_t _stm;
/* prevent 64-bit overflow when computing relative timestamp
see https://gist.github.com/jspohr/3dc4f00033d79ec5bdaf67bc46c813e3
*/
#if defined(_WIN32) || (defined(__APPLE__) && defined(__MACH__))
_SOKOL_PRIVATE int64_t int64_muldiv(int64_t value, int64_t numer, int64_t denom) {
int64_t q = value / denom;
int64_t r = value % denom;
return q * numer + r * numer / denom;
}
#endif
#if defined(__EMSCRIPTEN__)
EM_JS(double, stm_js_perfnow, (void), {
return performance.now();
});
#endif
SOKOL_API_IMPL void stm_setup(void) {
memset(&_stm, 0, sizeof(_stm));
_stm.initialized = 0xABCDABCD;
#if defined(_WIN32)
QueryPerformanceFrequency(&_stm.freq);
QueryPerformanceCounter(&_stm.start);
#elif defined(__APPLE__) && defined(__MACH__)
mach_timebase_info(&_stm.timebase);
_stm.start = mach_absolute_time();
#elif defined(__EMSCRIPTEN__)
_stm.start = stm_js_perfnow();
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
_stm.start = (uint64_t)ts.tv_sec*1000000000 + (uint64_t)ts.tv_nsec;
#endif
}
SOKOL_API_IMPL uint64_t stm_now(void) {
SOKOL_ASSERT(_stm.initialized == 0xABCDABCD);
uint64_t now;
#if defined(_WIN32)
LARGE_INTEGER qpc_t;
QueryPerformanceCounter(&qpc_t);
now = int64_muldiv(qpc_t.QuadPart - _stm.start.QuadPart, 1000000000, _stm.freq.QuadPart);
#elif defined(__APPLE__) && defined(__MACH__)
const uint64_t mach_now = mach_absolute_time() - _stm.start;
now = int64_muldiv(mach_now, _stm.timebase.numer, _stm.timebase.denom);
#elif defined(__EMSCRIPTEN__)
double js_now = stm_js_perfnow() - _stm.start;
SOKOL_ASSERT(js_now >= 0.0);
now = (uint64_t) (js_now * 1000000.0);
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
now = ((uint64_t)ts.tv_sec*1000000000 + (uint64_t)ts.tv_nsec) - _stm.start;
#endif
return now;
}
SOKOL_API_IMPL uint64_t stm_diff(uint64_t new_ticks, uint64_t old_ticks) {
if (new_ticks > old_ticks) {
return new_ticks - old_ticks;
}
else {
return 1;
}
}
SOKOL_API_IMPL uint64_t stm_since(uint64_t start_ticks) {
return stm_diff(stm_now(), start_ticks);
}
SOKOL_API_IMPL uint64_t stm_laptime(uint64_t* last_time) {
SOKOL_ASSERT(last_time);
uint64_t dt = 0;
uint64_t now = stm_now();
if (0 != *last_time) {
dt = stm_diff(now, *last_time);
}
*last_time = now;
return dt;
}
SOKOL_API_IMPL double stm_sec(uint64_t ticks) {
return (double)ticks / 1000000000.0;
}
SOKOL_API_IMPL double stm_ms(uint64_t ticks) {
return (double)ticks / 1000000.0;
}
SOKOL_API_IMPL double stm_us(uint64_t ticks) {
return (double)ticks / 1000.0;
}
SOKOL_API_IMPL double stm_ns(uint64_t ticks) {
return (double)ticks;
}
#endif /* SOKOL_IMPL */
-396
View File
@@ -1,396 +0,0 @@
#!/usr/bin/env bash
set -eu -o pipefail
print_usage() {
cat <<EOF
Usage: tool.bash [options] command [args]
Commands:
build <config> <target>
Configs: debug, release
Targets: tests, bench
Output: build/<config>/<target>
clean
Removes build/
info
Prints information about the detected build environment.
Options:
-v Print important commands as they're executed.
-c <name> Use a specific compiler binary.
Default: \$CC, or cc
-t Use a particular C or C++ standard.
Default: c99 or c++11
-d Enable compiler safeguards like -fstack-protector.
You should probably do this if you plan to give the
compiled binary to other people.
--static Build static binary.
--pie Enable PIE (ASLR).
Note: --pie and --static cannot be mixed.
-s Print statistics about compile time and binary size.
-h or --help Print this message and exit.
EOF
}
os=
case $(uname -s | awk '{print tolower($0)}') in
linux*) os=linux;;
darwin*) os=mac;;
cygwin*) os=cygwin;;
*bsd*) os=bsd;;
*) os=unknown;;
esac
cc_exe="${CC:-cc}"
std=
verbose=0
protections_enabled=0
stats_enabled=0
pie_enabled=0
static_enabled=0
while getopts c:dhst:v-: opt_val; do
case "$opt_val" in
-)
case "$OPTARG" in
help) print_usage; exit 0;;
static) static_enabled=1;;
pie) pie_enabled=1;;
*)
echo "Unknown long option --$OPTARG" >&2
print_usage >&2
exit 1
;;
esac
;;
c) cc_exe="$OPTARG";;
d) protections_enabled=1;;
h) print_usage; exit 0;;
s) stats_enabled=1;;
t) std="$OPTARG";;
v) verbose=1;;
\?) print_usage >&2; exit 1;;
*) break;;
esac
done
arch=
case $(uname -m) in
x86_64) arch=x86_64;;
*) arch=unknown;;
esac
warn() {
echo "Warning: $*" >&2
}
fatal() {
echo "Error: $*" >&2
exit 1
}
script_error() {
echo "Script error: $*" >&2
exit 1
}
verbose_echo() {
if [[ $verbose = 1 ]]; then
echo "$@"
fi
"$@"
}
TIMEFORMAT='%3R'
last_time=
file_size() {
wc -c < "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
timed_stats() {
if [[ $stats_enabled = 1 ]]; then
{ last_time=$( { time "$@" 1>&3- 2>&4-; } 2>&1 ); } 3>&1 4>&2
else
"$@"
fi
}
version_string_normalized() {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}
if [[ ($os == bsd) || ($os == unknown) ]]; then
warn "Build script not tested on this platform"
fi
# This is not perfect by any means
cc_id=
cc_vers=
lld_detected=0
if cc_vers=$(echo -e '#ifndef __clang__\n#error Not found\n#endif\n__clang_major__.__clang_minor__.__clang_patchlevel__' | "$cc_exe" -E -xc - 2>/dev/null | tail -n 1 | tr -d '\040'); then
cc_id=clang
# Mac clang/llvm doesn't say the real version of clang. Just assume it's 3.9.0
if [[ $os == mac ]]; then
cc_vers=3.9.0
else
if command -v "lld" >/dev/null 2>&1; then
lld_detected=1
fi
fi
elif cc_vers=$(echo -e '#ifndef __GNUC__\n#error Not found\n#endif\n__GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__' | "$cc_exe" -E -xc - 2>/dev/null | tail -n 1 | tr -d '\040'); then
cc_id=gcc
fi
if [[ -z $cc_id ]]; then
warn "Failed to detect compiler type"
fi
if [[ -z $cc_vers ]]; then
warn "Failed to detect compiler version"
fi
# We always want std to be set to something, to avoid ambiguity. lang can be
# left empty, and won't be passed as an arg to the compiler if it's empty.
if [[ -z $std ]]; then
# Guess if desired std is C++ or C by default using name of compiler. Lame,
# but not much choice -- __cplusplus won't be defined if we try to use the
# preprocessor trick unless -x is specified, which defeats the purpose of
# seeing what the compiler's default behavior is.
case "$cc_exe" in
*++*) std='c++11';;
*) std='c99';;
esac
fi
lang=c
case "$std" in
*++*) lang=c++;;
esac
cc_vers_is_gte() {
if [[ $(version_string_normalized "$cc_vers") -ge $(version_string_normalized "$1") ]]; then
return 0
else
return 1
fi
}
cc_id_and_vers_gte() {
if [[ $cc_id == "$1" ]] && cc_vers_is_gte "$2"; then
return 0
else
return 1
fi
}
add() {
if [[ -z "${1:-}" ]]; then
script_error "At least one argument required for array add"
fi
local array_name
array_name=${1}
shift
eval "$array_name+=($(printf "'%s' " "$@"))"
}
concat() {
if [[ -z "${1:-}" || -z "${2:-}" ]]; then
script_error "Two arguments required for array concat"
fi
local lhs_name
local rhs_name
lhs_name=${1}
rhs_name=${2}
eval "$lhs_name+=(\"\${${rhs_name}[@]}\")"
}
try_make_dir() {
if ! [[ -e "$1" ]]; then
verbose_echo mkdir "$1"
elif ! [[ -d "$1" ]]; then
fatal "File $1 already exists but is not a directory"
fi
}
build_dir=build
build_target() {
local build_subdir
local cc_flags=()
local libraries=()
local source_files=()
local out_exe
add cc_flags "-x$lang" "-std=$std" -pipe -finput-charset=UTF-8 -Wall -Wpedantic -Wextra
if cc_id_and_vers_gte gcc 6.0.0 || cc_id_and_vers_gte clang 3.9.0; then
add cc_flags -Werror=implicit-function-declaration -Werror=implicit-int -Werror=incompatible-pointer-types -Werror=int-conversion
fi
if [[ $lang = c ]]; then
add cc_flags -Wstrict-prototypes
fi
if [[ $cc_id = clang ]]; then
# We use int16_t on the stack and in math expressions. With -Wconversion,
# GCC will be spammy about int16_t to and from int. Clang won't issue
# warnings in that manner. We can't fix this easily in the code because
# LAY_FLOAT can cause these types to be floating point instead.
add cc_flags -Wconversion
fi
if [[ $lld_detected = 1 ]]; then
add cc_flags -fuse-ld=lld
fi
if [[ $protections_enabled = 1 ]]; then
add cc_flags -D_FORTIFY_SOURCE=2 -fstack-protector-strong
fi
if [[ $pie_enabled = 1 ]]; then
add cc_flags -pie -fpie -Wl,-pie
# Only explicitly specify no-pie if cc version is new enough
elif cc_id_and_vers_gte gcc 6.0.0 || cc_id_and_vers_gte clang 6.0.0; then
add cc_flags -no-pie -fno-pie
fi
if [[ $static_enabled = 1 ]]; then
add cc_flags -static
fi
case "$1" in
debug)
build_subdir=debug
add cc_flags -DDEBUG -ggdb
# cygwin gcc doesn't seem to have this stuff, just elide for now
if [[ $os != cygwin ]]; then
if cc_id_and_vers_gte gcc 6.0.0 || cc_id_and_vers_gte clang 3.9.0; then
add cc_flags -fsanitize=address -fsanitize=undefined
fi
fi
if [[ $os = mac ]]; then
# Our mac clang does not have -Og
add cc_flags -O1
else
add cc_flags -Og
# needed if address is already specified? doesn't work on mac clang, at
# least
# add cc_flags -fsanitize=leak
fi
;;
release)
build_subdir=release
add cc_flags -DNDEBUG -O2 -g0
if [[ $protections_enabled != 1 ]]; then
add cc_flags -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -fno-stack-protector
fi
if [[ $os = mac ]]; then
# todo some stripping option
true
else
# -flto is good on both clang and gcc on Linux
add cc_flags -flto -s
fi
;;
*) fatal "Unknown build config \"$1\"";;
esac
case $arch in
x86_64)
case $cc_id in
gcc)
if cc_vers_is_gte 4.9; then
add cc_flags -march=nehalem
fi
;;
clang)
add cc_flags -march=nehalem
;;
esac
;;
esac
case "$2" in
test|tests)
add source_files test_layout.c
out_exe=lay_tests
;;
bench|benchmark)
add cc_flags -isystem thirdparty
add source_files benchmark_layout.c
case $os in
linux|cygwin*|*bsd*)
# librt and high-res posix timers on Linux (and BSD?)
add libraries -lrt
add cc_flags -D_POSIX_C_SOURCE=200809L
;;
esac
out_exe=lay_bench
;;
esac
try_make_dir "$build_dir"
try_make_dir "$build_dir/$build_subdir"
local out_path=$build_dir/$build_subdir/$out_exe
# bash versions quirk: empty arrays might give error on expansion, use +
# trick to avoid expanding second operand
verbose_echo timed_stats "$cc_exe" "${cc_flags[@]}" -o "$out_path" "${source_files[@]}" ${libraries[@]+"${libraries[@]}"}
if [[ $stats_enabled = 1 ]]; then
echo "time: $last_time"
echo "size: $(file_size "$out_path")"
fi
}
print_info() {
local linker_name
if [[ $lld_detected = 1 ]]; then
linker_name=LLD
else
linker_name=default
fi
cat <<EOF
Operating system: $os
Architecture: $arch
Compiler name: $cc_exe
Compiler type: $cc_id
Compiler version: $cc_vers
Linker: $linker_name
EOF
}
shift $((OPTIND - 1))
if [[ -z "${1:-}" ]]; then
echo "Error: Command required" >&2
print_usage >&2
exit 1
fi
case "$1" in
info)
if [[ "$#" -gt 1 ]]; then
fatal "Too many arguments for 'info'"
fi
print_info
exit 0
;;
build)
if [[ "$#" -lt 3 ]]; then
fatal "Too few arguments for 'build'"
fi
if [[ "$#" -gt 3 ]]; then
fatal "Too many arguments for 'build'"
fi
build_target "$2" "$3"
;;
clean)
if [[ -d "$build_dir" ]]; then
verbose_echo rm -rf "$build_dir"
fi
;;
battery)
configs=(
clang-7 c99 clang++-7 c++98 clang++-7 c++11
gcc c99 g++ c++98 g++ c++11
)
for (( i=0; i<${#configs[@]}; i+=2 )); do
echo "${configs[i]}" "${configs[i+1]}"
"$0" -c "${configs[i]}" -t "${configs[i+1]}" build debug tests
if test_out=$(build/debug/lay_tests); then
echo OK
else
echo "$test_out"
fatal "Test failed, stopping"
fi
done
;;
*) fatal "Unrecognized command $1";;
esac