From d66d7177161ebae4c40710fc548fd0c014fb0d47 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:29:14 +0700 Subject: [PATCH 1/7] Queue generic structs and array lengths, after the core lane and not beside it --- NEXT.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/NEXT.md b/NEXT.md index 2b67a48..197ffe5 100644 --- a/NEXT.md +++ b/NEXT.md @@ -1,3 +1,56 @@ +## Queued, decided by the author: generic structs and generic array lengths + +**Sequenced after the core generics lane, not beside it.** Both change `Types.t`, which that lane is inside. + +The author's question settled it: Odin has both, and the normal way to write them is together. +`core/math/linalg/extended.odin:488` binds three things in one pattern — + +```odin +is_nan_array :: proc(x: $A/[$N]$T) -> (out: [N]bool) where IS_FLOAT(T) +``` + +`A` is the array type, `N` its length, `T` its element, and `[N]bool` in the *return* type uses `N`, so the result +is an array of the same length as the argument. And `core/container/small_array/small_array.odin:23` is the generic +struct over both, with a predicate over a **value** rather than a type: + +```odin +Small_Array :: struct($N: int, $T: typeid) where N >= 0 { ... } +``` + +### Why they are one project + +`Types.Named` is a bare string with no parameters and `Types.Array` is `int64 * t`. Either feature means `Types.t` +gains a parameterised case, and `Types.t` is consumed by `emit.ml`'s layout calculator, `x86.ml`, `render.ml`, the +DWARF path and the map key-pair emitter. **Same price for one as for both**, which is the whole reason to do them +together. + +What the spike measured for the length half specifically: `Ast.len` is `Lint | Lname`, so `$n` parses today with no +reader or parser change — the same free ride the type sigil got. Everything after that is the expensive part. +`bind_ty` gains a length-binding case (`Array (n, p)` against `Array (m, a)` binds `n := m`), `mangle_ty` gains a +number, and `array_len` has to answer "a variable" rather than failing — which means the checker's compile-time +constant folding has to accept that a length can stay symbolic until instantiation. + +### The motivating case, and it is not `$n` on its own + +`$n` alone buys little. `swap!` does not need it — it takes a slice and two indices, and the length is a runtime +field. Nor does a `pop` from a `Vec`. The case that wants both is **a fixed-capacity array with a count and no +allocation**, which is Odin's `Small_Array` and a good fit for a game that refuses to allocate in a frame: + +```lisp +(defvar enemies (Small-Array 64 Enemy)) +``` + +`PORTING.md`'s recommendation for the game's state was fixed arrays with counts held in `defvar` globals, kept +deliberately away from `Vec` so nothing is move-only. `(Small-Array $n $t)` is that pattern with a type behind it +instead of two variables kept in step by hand. That is the argument for building this, and it is stronger than +"Odin has it". + +### Also worth deciding when it is built + +Odin's `where N >= 0` is a predicate over a **value**, not a type. The `where` mechanism just decided here takes +type predicates (`ordered?`, `copyable?`). Whether it also takes value predicates over a length parameter is a +separate question and should be answered deliberately rather than falling out of the implementation. + ## To discuss: two decisions parked during the ownership discussion Both came out of the lane that closed the enum-layout and constant-checking gaps. Its work is sound and committed; From 2957804ebc3c27c3838741f7abdb3731f71056f6 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:32:38 +0700 Subject: [PATCH 2/7] The header ships with the package, so the check is not optional any more vendor/raylib/web/ is gitignored, so the header a build-web.sh tree happens to have never appears in a git worktree. Every parallel lane that touched bindings was checking against nothing and was not told. One went looking and used a copy out of ~/.local/share/Trash, which happened to be byte-identical. A check that silently does not run is worse than no check. raylib.h is 128K and now sits beside the package it describes. The argument for ?${FLAN_RAYLIB_H} was that requiring a header would make a build need raylib-devel, and that dissolves when the header is committed here. There is no variable to export any more; to check against a different header, edit the line or replace the file. Measured, because always-on has to be paid by every build: a warm build of raylib-font.flan is 0.10-0.11s against a 0.10s baseline. The header read is cached and keyed like the object cache, so this is under the noise. Verified it fires by putting f64 where raylib says int and watching an ordinary build refuse, naming the tracked header. --- vendor/raylib/headers | 31 +- vendor/raylib/raylib-5.5.h | 1708 ++++++++++++++++++++++++++++++++++++ 2 files changed, 1726 insertions(+), 13 deletions(-) create mode 100644 vendor/raylib/raylib-5.5.h diff --git a/vendor/raylib/headers b/vendor/raylib/headers index cc92c18..85cbbf6 100644 --- a/vendor/raylib/headers +++ b/vendor/raylib/headers @@ -24,13 +24,19 @@ # agrees with it by construction. That is also why the hand-written lines # were kept rather than replaced by generated ones. # -# Why it is still optional. A build needs libraylib linkable and *not* -# raylib-devel installed, which is a property worth keeping; requiring a header -# would take it from everyone to give the check to whoever has one. Before the -# bindings were committed this marker also decided how many bindings a build -# got, which was the real cost of it being opt-in; it no longer decides that, -# and all it now withholds is a check that regeneration has already run once. -# Same shape as ${FLAN_RAYLIB_WEB} in `link`, and for the same reason. +# Why it is no longer optional. It used to be `?${FLAN_RAYLIB_H}`, and the +# argument was that a build needs libraylib linkable and *not* raylib-devel +# installed, so requiring a header would take that property from everyone to +# give the check to whoever had one. **That argument dissolved when the header +# was committed here**: nobody needs raylib-devel to have it, because it ships +# with the repository. +# +# What being optional actually cost was found the hard way. `vendor/raylib/web/` +# is gitignored, so the header a `build-web.sh` tree happens to have never +# appears in a git worktree — and every parallel lane that touched bindings was +# therefore checking against nothing and not being told. One of them went +# looking and used a copy out of `~/.local/share/Trash`, which happened to be +# byte-identical. A check that silently does not run is worse than no check. # # The version must match the shared library `link` names — 5.5, libraylib.so.550. # Reading one version's header while linking another's library is exactly the @@ -38,11 +44,10 @@ # described: against a 5.1-dev header, regeneration reports ten differences # that are all real and writes nothing. # -# export FLAN_RAYLIB_H=/path/to/raylib-5.5/src/raylib.h -# -# vendor/raylib/build-web.sh already clones that exact tag to build the browser -# archive, so a tree that has built for web has the matching header at -# vendor/raylib/web/raylib-5.5/src/raylib.h. +# To check against a different header — a newer raylib, or a system one — edit +# this line or replace the file. There is no environment variable for it any +# more: the point of committing the header is that every tree checks against +# the same one without anybody exporting anything. # # To see what regeneration would produce without writing anything: # @@ -52,4 +57,4 @@ # are called — is `bindings` beside this file. See its comments for why a # committed generated file needs a config at all. # -?${FLAN_RAYLIB_H} +raylib-5.5.h diff --git a/vendor/raylib/raylib-5.5.h b/vendor/raylib/raylib-5.5.h new file mode 100644 index 0000000..a26b8ce --- /dev/null +++ b/vendor/raylib/raylib-5.5.h @@ -0,0 +1,1708 @@ +/********************************************************************************************** +* +* raylib v5.5 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) +* +* FEATURES: +* - NO external dependencies, all required libraries included with raylib +* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, +* MacOS, Haiku, Android, Raspberry Pi, DRM native, HTML5. +* - Written in plain C code (C99) in PascalCase/camelCase notation +* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3, ES2, ES3 - choose at compile) +* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] +* - Multiple Fonts formats supported (TTF, OTF, FNT, BDF, Sprite fonts) +* - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) +* - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! +* - Flexible Materials system, supporting classic maps and PBR maps +* - Animated 3D models supported (skeletal bones animation) (IQM, M3D, GLTF) +* - Shaders support, including Model shaders and Postprocessing shaders +* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] +* - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, QOA, XM, MOD) +* - VR stereo rendering with configurable HMD device parameters +* - Bindings to multiple programming languages available! +* +* NOTES: +* - One default Font is loaded on InitWindow()->LoadFontDefault() [core, text] +* - One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2) +* - One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2) +* - One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2) +* +* DEPENDENCIES (included): +* [rcore][GLFW] rglfw (Camilla Löwy - github.com/glfw/glfw) for window/context management and input +* [rcore][RGFW] rgfw (ColleagueRiley - github.com/ColleagueRiley/RGFW) for window/context management and input +* [rlgl] glad/glad_gles2 (David Herberth - github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading +* [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management +* +* OPTIONAL DEPENDENCIES (included): +* [rcore] msf_gif (Miles Fogle) for GIF recording +* [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm +* [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm +* [rcore] rprand (Ramon Snatamaria) for pseudo-random numbers generation +* [rtextures] qoi (Dominic Szablewski - https://phoboslab.org) for QOI image manage +* [rtextures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) +* [rtextures] stb_image_write (Sean Barret) for image writing (BMP, TGA, PNG, JPG) +* [rtextures] stb_image_resize2 (Sean Barret) for image resizing algorithms +* [rtextures] stb_perlin (Sean Barret) for Perlin Noise image generation +* [rtext] stb_truetype (Sean Barret) for ttf fonts loading +* [rtext] stb_rect_pack (Sean Barret) for rectangles packing +* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation +* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) +* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) +* [rmodels] m3d (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) +* [rmodels] vox_loader (Johann Nadalutti) for models loading (VOX) +* [raudio] dr_wav (David Reid) for WAV audio file loading +* [raudio] dr_flac (David Reid) for FLAC audio file loading +* [raudio] dr_mp3 (David Reid) for MP3 audio file loading +* [raudio] stb_vorbis (Sean Barret) for OGG audio loading +* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading +* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading +* [raudio] qoa (Dominic Szablewski - https://phoboslab.org) for QOA audio manage +* +* +* LICENSE: zlib/libpng +* +* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, +* BSD-like license that allows static linking with closed source software: +* +* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) +* +* 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. +* +**********************************************************************************************/ + +#ifndef RAYLIB_H +#define RAYLIB_H + +#include // Required for: va_list - Only used by TraceLogCallback + +#define RAYLIB_VERSION_MAJOR 5 +#define RAYLIB_VERSION_MINOR 5 +#define RAYLIB_VERSION_PATCH 0 +#define RAYLIB_VERSION "5.5" + +// Function specifiers in case library is build/used as a shared library +// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll +// NOTE: visibility("default") attribute makes symbols "visible" when compiled with -fvisibility=hidden +#if defined(_WIN32) + #if defined(__TINYC__) + #define __declspec(x) __attribute__((x)) + #endif + #if defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) + #elif defined(USE_LIBTYPE_SHARED) + #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) + #endif +#else + #if defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __attribute__((visibility("default"))) // We are building as a Unix shared library (.so/.dylib) + #endif +#endif + +#ifndef RLAPI + #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) +#endif + +//---------------------------------------------------------------------------------- +// Some basic Defines +//---------------------------------------------------------------------------------- +#ifndef PI + #define PI 3.14159265358979323846f +#endif +#ifndef DEG2RAD + #define DEG2RAD (PI/180.0f) +#endif +#ifndef RAD2DEG + #define RAD2DEG (180.0f/PI) +#endif + +// Allow custom memory allocators +// NOTE: Require recompiling raylib sources +#ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) +#endif +#ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) +#endif +#ifndef RL_REALLOC + #define RL_REALLOC(ptr,sz) realloc(ptr,sz) +#endif +#ifndef RL_FREE + #define RL_FREE(ptr) free(ptr) +#endif + +// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) +// Plain structures in C++ (without constructors) can be initialized with { } +// This is called aggregate initialization (C++11 feature) +#if defined(__cplusplus) + #define CLITERAL(type) type +#else + #define CLITERAL(type) (type) +#endif + +// Some compilers (mostly macos clang) default to C++98, +// where aggregate initialization can't be used +// So, give a more clear error stating how to fix this +#if !defined(_MSC_VER) && (defined(__cplusplus) && __cplusplus < 201103L) + #error "C++11 or later is required. Add -std=c++11" +#endif + +// NOTE: We set some defines with some data types declared by raylib +// Other modules (raymath, rlgl) also require some of those types, so, +// to be able to use those other modules as standalone (not depending on raylib) +// this defines are very useful for internal check and avoid type (re)definitions +#define RL_COLOR_TYPE +#define RL_RECTANGLE_TYPE +#define RL_VECTOR2_TYPE +#define RL_VECTOR3_TYPE +#define RL_VECTOR4_TYPE +#define RL_QUATERNION_TYPE +#define RL_MATRIX_TYPE + +// Some Basic Colors +// NOTE: Custom raylib color palette for amazing visuals on WHITE background +#define LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray +#define GRAY CLITERAL(Color){ 130, 130, 130, 255 } // Gray +#define DARKGRAY CLITERAL(Color){ 80, 80, 80, 255 } // Dark Gray +#define YELLOW CLITERAL(Color){ 253, 249, 0, 255 } // Yellow +#define GOLD CLITERAL(Color){ 255, 203, 0, 255 } // Gold +#define ORANGE CLITERAL(Color){ 255, 161, 0, 255 } // Orange +#define PINK CLITERAL(Color){ 255, 109, 194, 255 } // Pink +#define RED CLITERAL(Color){ 230, 41, 55, 255 } // Red +#define MAROON CLITERAL(Color){ 190, 33, 55, 255 } // Maroon +#define GREEN CLITERAL(Color){ 0, 228, 48, 255 } // Green +#define LIME CLITERAL(Color){ 0, 158, 47, 255 } // Lime +#define DARKGREEN CLITERAL(Color){ 0, 117, 44, 255 } // Dark Green +#define SKYBLUE CLITERAL(Color){ 102, 191, 255, 255 } // Sky Blue +#define BLUE CLITERAL(Color){ 0, 121, 241, 255 } // Blue +#define DARKBLUE CLITERAL(Color){ 0, 82, 172, 255 } // Dark Blue +#define PURPLE CLITERAL(Color){ 200, 122, 255, 255 } // Purple +#define VIOLET CLITERAL(Color){ 135, 60, 190, 255 } // Violet +#define DARKPURPLE CLITERAL(Color){ 112, 31, 126, 255 } // Dark Purple +#define BEIGE CLITERAL(Color){ 211, 176, 131, 255 } // Beige +#define BROWN CLITERAL(Color){ 127, 106, 79, 255 } // Brown +#define DARKBROWN CLITERAL(Color){ 76, 63, 47, 255 } // Dark Brown + +#define WHITE CLITERAL(Color){ 255, 255, 255, 255 } // White +#define BLACK CLITERAL(Color){ 0, 0, 0, 255 } // Black +#define BLANK CLITERAL(Color){ 0, 0, 0, 0 } // Blank (Transparent) +#define MAGENTA CLITERAL(Color){ 255, 0, 255, 255 } // Magenta +#define RAYWHITE CLITERAL(Color){ 245, 245, 245, 255 } // My own White (raylib logo) + +//---------------------------------------------------------------------------------- +// Structures Definition +//---------------------------------------------------------------------------------- +// Boolean type +#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum bool { false = 0, true = !false } bool; + #define RL_BOOL_TYPE +#endif + +// Vector2, 2 components +typedef struct Vector2 { + float x; // Vector x component + float y; // Vector y component +} Vector2; + +// Vector3, 3 components +typedef struct Vector3 { + float x; // Vector x component + float y; // Vector y component + float z; // Vector z component +} Vector3; + +// Vector4, 4 components +typedef struct Vector4 { + float x; // Vector x component + float y; // Vector y component + float z; // Vector z component + float w; // Vector w component +} Vector4; + +// Quaternion, 4 components (Vector4 alias) +typedef Vector4 Quaternion; + +// Matrix, 4x4 components, column major, OpenGL style, right-handed +typedef struct Matrix { + float m0, m4, m8, m12; // Matrix first row (4 components) + float m1, m5, m9, m13; // Matrix second row (4 components) + float m2, m6, m10, m14; // Matrix third row (4 components) + float m3, m7, m11, m15; // Matrix fourth row (4 components) +} Matrix; + +// Color, 4 components, R8G8B8A8 (32bit) +typedef struct Color { + unsigned char r; // Color red value + unsigned char g; // Color green value + unsigned char b; // Color blue value + unsigned char a; // Color alpha value +} Color; + +// Rectangle, 4 components +typedef struct Rectangle { + float x; // Rectangle top-left corner position x + float y; // Rectangle top-left corner position y + float width; // Rectangle width + float height; // Rectangle height +} Rectangle; + +// Image, pixel data stored in CPU memory (RAM) +typedef struct Image { + void *data; // Image raw data + int width; // Image base width + int height; // Image base height + int mipmaps; // Mipmap levels, 1 by default + int format; // Data format (PixelFormat type) +} Image; + +// Texture, tex data stored in GPU memory (VRAM) +typedef struct Texture { + unsigned int id; // OpenGL texture id + int width; // Texture base width + int height; // Texture base height + int mipmaps; // Mipmap levels, 1 by default + int format; // Data format (PixelFormat type) +} Texture; + +// Texture2D, same as Texture +typedef Texture Texture2D; + +// TextureCubemap, same as Texture +typedef Texture TextureCubemap; + +// RenderTexture, fbo for texture rendering +typedef struct RenderTexture { + unsigned int id; // OpenGL framebuffer object id + Texture texture; // Color buffer attachment texture + Texture depth; // Depth buffer attachment texture +} RenderTexture; + +// RenderTexture2D, same as RenderTexture +typedef RenderTexture RenderTexture2D; + +// NPatchInfo, n-patch layout info +typedef struct NPatchInfo { + Rectangle source; // Texture source rectangle + int left; // Left border offset + int top; // Top border offset + int right; // Right border offset + int bottom; // Bottom border offset + int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1 +} NPatchInfo; + +// GlyphInfo, font characters glyphs info +typedef struct GlyphInfo { + int value; // Character value (Unicode) + int offsetX; // Character offset X when drawing + int offsetY; // Character offset Y when drawing + int advanceX; // Character advance position X + Image image; // Character image data +} GlyphInfo; + +// Font, font texture and GlyphInfo array data +typedef struct Font { + int baseSize; // Base size (default chars height) + int glyphCount; // Number of glyph characters + int glyphPadding; // Padding around the glyph characters + Texture2D texture; // Texture atlas containing the glyphs + Rectangle *recs; // Rectangles in texture for the glyphs + GlyphInfo *glyphs; // Glyphs info data +} Font; + +// Camera, defines position/orientation in 3d space +typedef struct Camera3D { + Vector3 position; // Camera position + Vector3 target; // Camera target it looks-at + Vector3 up; // Camera up vector (rotation over its axis) + float fovy; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic + int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC +} Camera3D; + +typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D + +// Camera2D, defines position/orientation in 2d space +typedef struct Camera2D { + Vector2 offset; // Camera offset (displacement from target) + Vector2 target; // Camera target (rotation and zoom origin) + float rotation; // Camera rotation in degrees + float zoom; // Camera zoom (scaling), should be 1.0f by default +} Camera2D; + +// Mesh, vertex data and vao/vbo +typedef struct Mesh { + int vertexCount; // Number of vertices stored in arrays + int triangleCount; // Number of triangles stored (indexed or not) + + // Vertex attributes data + float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + float *texcoords2; // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + unsigned short *indices; // Vertex indices (in case vertex data comes indexed) + + // Animation vertex data + float *animVertices; // Animated vertex positions (after bones transformations) + float *animNormals; // Animated normals (after bones transformations) + unsigned char *boneIds; // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) + float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) + Matrix *boneMatrices; // Bones animated transformation matrices + int boneCount; // Number of bones + + // OpenGL identifiers + unsigned int vaoId; // OpenGL Vertex Array Object id + unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data) +} Mesh; + +// Shader +typedef struct Shader { + unsigned int id; // Shader program id + int *locs; // Shader locations array (RL_MAX_SHADER_LOCATIONS) +} Shader; + +// MaterialMap +typedef struct MaterialMap { + Texture2D texture; // Material map texture + Color color; // Material map color + float value; // Material map value +} MaterialMap; + +// Material, includes shader and maps +typedef struct Material { + Shader shader; // Material shader + MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS) + float params[4]; // Material generic parameters (if required) +} Material; + +// Transform, vertex transformation data +typedef struct Transform { + Vector3 translation; // Translation + Quaternion rotation; // Rotation + Vector3 scale; // Scale +} Transform; + +// Bone, skeletal animation bone +typedef struct BoneInfo { + char name[32]; // Bone name + int parent; // Bone parent +} BoneInfo; + +// Model, meshes, materials and animation data +typedef struct Model { + Matrix transform; // Local transform matrix + + int meshCount; // Number of meshes + int materialCount; // Number of materials + Mesh *meshes; // Meshes array + Material *materials; // Materials array + int *meshMaterial; // Mesh material number + + // Animation data + int boneCount; // Number of bones + BoneInfo *bones; // Bones information (skeleton) + Transform *bindPose; // Bones base transformation (pose) +} Model; + +// ModelAnimation +typedef struct ModelAnimation { + int boneCount; // Number of bones + int frameCount; // Number of animation frames + BoneInfo *bones; // Bones information (skeleton) + Transform **framePoses; // Poses array by frame + char name[32]; // Animation name +} ModelAnimation; + +// Ray, ray for raycasting +typedef struct Ray { + Vector3 position; // Ray position (origin) + Vector3 direction; // Ray direction (normalized) +} Ray; + +// RayCollision, ray hit information +typedef struct RayCollision { + bool hit; // Did the ray hit something? + float distance; // Distance to the nearest hit + Vector3 point; // Point of the nearest hit + Vector3 normal; // Surface normal of hit +} RayCollision; + +// BoundingBox +typedef struct BoundingBox { + Vector3 min; // Minimum vertex box-corner + Vector3 max; // Maximum vertex box-corner +} BoundingBox; + +// Wave, audio wave data +typedef struct Wave { + unsigned int frameCount; // Total number of frames (considering channels) + unsigned int sampleRate; // Frequency (samples per second) + unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) + void *data; // Buffer data pointer +} Wave; + +// Opaque structs declaration +// NOTE: Actual structs are defined internally in raudio module +typedef struct rAudioBuffer rAudioBuffer; +typedef struct rAudioProcessor rAudioProcessor; + +// AudioStream, custom audio stream +typedef struct AudioStream { + rAudioBuffer *buffer; // Pointer to internal data used by the audio system + rAudioProcessor *processor; // Pointer to internal data processor, useful for audio effects + + unsigned int sampleRate; // Frequency (samples per second) + unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) +} AudioStream; + +// Sound +typedef struct Sound { + AudioStream stream; // Audio stream + unsigned int frameCount; // Total number of frames (considering channels) +} Sound; + +// Music, audio stream, anything longer than ~10 seconds should be streamed +typedef struct Music { + AudioStream stream; // Audio stream + unsigned int frameCount; // Total number of frames (considering channels) + bool looping; // Music looping enable + + int ctxType; // Type of music context (audio filetype) + void *ctxData; // Audio context data, depends on type +} Music; + +// VrDeviceInfo, Head-Mounted-Display device parameters +typedef struct VrDeviceInfo { + int hResolution; // Horizontal resolution in pixels + int vResolution; // Vertical resolution in pixels + float hScreenSize; // Horizontal size in meters + float vScreenSize; // Vertical size in meters + float eyeToScreenDistance; // Distance between eye and display in meters + float lensSeparationDistance; // Lens separation distance in meters + float interpupillaryDistance; // IPD (distance between pupils) in meters + float lensDistortionValues[4]; // Lens distortion constant parameters + float chromaAbCorrection[4]; // Chromatic aberration correction parameters +} VrDeviceInfo; + +// VrStereoConfig, VR stereo rendering configuration for simulator +typedef struct VrStereoConfig { + Matrix projection[2]; // VR projection matrices (per eye) + Matrix viewOffset[2]; // VR view offset matrices (per eye) + float leftLensCenter[2]; // VR left lens center + float rightLensCenter[2]; // VR right lens center + float leftScreenCenter[2]; // VR left screen center + float rightScreenCenter[2]; // VR right screen center + float scale[2]; // VR distortion scale + float scaleIn[2]; // VR distortion scale in +} VrStereoConfig; + +// File path list +typedef struct FilePathList { + unsigned int capacity; // Filepaths max entries + unsigned int count; // Filepaths entries count + char **paths; // Filepaths entries +} FilePathList; + +// Automation event +typedef struct AutomationEvent { + unsigned int frame; // Event frame + unsigned int type; // Event type (AutomationEventType) + int params[4]; // Event parameters (if required) +} AutomationEvent; + +// Automation event list +typedef struct AutomationEventList { + unsigned int capacity; // Events max entries (MAX_AUTOMATION_EVENTS) + unsigned int count; // Events entries count + AutomationEvent *events; // Events entries +} AutomationEventList; + +//---------------------------------------------------------------------------------- +// Enumerators Definition +//---------------------------------------------------------------------------------- +// System/Window config flags +// NOTE: Every bit registers one state (use it with bit masks) +// By default all flags are set to 0 +typedef enum { + FLAG_VSYNC_HINT = 0x00000040, // Set to try enabling V-Sync on GPU + FLAG_FULLSCREEN_MODE = 0x00000002, // Set to run program in fullscreen + FLAG_WINDOW_RESIZABLE = 0x00000004, // Set to allow resizable window + FLAG_WINDOW_UNDECORATED = 0x00000008, // Set to disable window decoration (frame and buttons) + FLAG_WINDOW_HIDDEN = 0x00000080, // Set to hide window + FLAG_WINDOW_MINIMIZED = 0x00000200, // Set to minimize window (iconify) + FLAG_WINDOW_MAXIMIZED = 0x00000400, // Set to maximize window (expanded to monitor) + FLAG_WINDOW_UNFOCUSED = 0x00000800, // Set to window non focused + FLAG_WINDOW_TOPMOST = 0x00001000, // Set to window always on top + FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized + FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer + FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI + FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED + FLAG_BORDERLESS_WINDOWED_MODE = 0x00008000, // Set to run program in borderless windowed mode + FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X + FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D) +} ConfigFlags; + +// Trace log level +// NOTE: Organized by priority level +typedef enum { + LOG_ALL = 0, // Display all logs + LOG_TRACE, // Trace logging, intended for internal use only + LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds + LOG_INFO, // Info logging, used for program execution info + LOG_WARNING, // Warning logging, used on recoverable failures + LOG_ERROR, // Error logging, used on unrecoverable failures + LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) + LOG_NONE // Disable logging +} TraceLogLevel; + +// Keyboard keys (US keyboard layout) +// NOTE: Use GetKeyPressed() to allow redefining +// required keys for alternative layouts +typedef enum { + KEY_NULL = 0, // Key: NULL, used for no key pressed + // Alphanumeric keys + KEY_APOSTROPHE = 39, // Key: ' + KEY_COMMA = 44, // Key: , + KEY_MINUS = 45, // Key: - + KEY_PERIOD = 46, // Key: . + KEY_SLASH = 47, // Key: / + KEY_ZERO = 48, // Key: 0 + KEY_ONE = 49, // Key: 1 + KEY_TWO = 50, // Key: 2 + KEY_THREE = 51, // Key: 3 + KEY_FOUR = 52, // Key: 4 + KEY_FIVE = 53, // Key: 5 + KEY_SIX = 54, // Key: 6 + KEY_SEVEN = 55, // Key: 7 + KEY_EIGHT = 56, // Key: 8 + KEY_NINE = 57, // Key: 9 + KEY_SEMICOLON = 59, // Key: ; + KEY_EQUAL = 61, // Key: = + KEY_A = 65, // Key: A | a + KEY_B = 66, // Key: B | b + KEY_C = 67, // Key: C | c + KEY_D = 68, // Key: D | d + KEY_E = 69, // Key: E | e + KEY_F = 70, // Key: F | f + KEY_G = 71, // Key: G | g + KEY_H = 72, // Key: H | h + KEY_I = 73, // Key: I | i + KEY_J = 74, // Key: J | j + KEY_K = 75, // Key: K | k + KEY_L = 76, // Key: L | l + KEY_M = 77, // Key: M | m + KEY_N = 78, // Key: N | n + KEY_O = 79, // Key: O | o + KEY_P = 80, // Key: P | p + KEY_Q = 81, // Key: Q | q + KEY_R = 82, // Key: R | r + KEY_S = 83, // Key: S | s + KEY_T = 84, // Key: T | t + KEY_U = 85, // Key: U | u + KEY_V = 86, // Key: V | v + KEY_W = 87, // Key: W | w + KEY_X = 88, // Key: X | x + KEY_Y = 89, // Key: Y | y + KEY_Z = 90, // Key: Z | z + KEY_LEFT_BRACKET = 91, // Key: [ + KEY_BACKSLASH = 92, // Key: '\' + KEY_RIGHT_BRACKET = 93, // Key: ] + KEY_GRAVE = 96, // Key: ` + // Function keys + KEY_SPACE = 32, // Key: Space + KEY_ESCAPE = 256, // Key: Esc + KEY_ENTER = 257, // Key: Enter + KEY_TAB = 258, // Key: Tab + KEY_BACKSPACE = 259, // Key: Backspace + KEY_INSERT = 260, // Key: Ins + KEY_DELETE = 261, // Key: Del + KEY_RIGHT = 262, // Key: Cursor right + KEY_LEFT = 263, // Key: Cursor left + KEY_DOWN = 264, // Key: Cursor down + KEY_UP = 265, // Key: Cursor up + KEY_PAGE_UP = 266, // Key: Page up + KEY_PAGE_DOWN = 267, // Key: Page down + KEY_HOME = 268, // Key: Home + KEY_END = 269, // Key: End + KEY_CAPS_LOCK = 280, // Key: Caps lock + KEY_SCROLL_LOCK = 281, // Key: Scroll down + KEY_NUM_LOCK = 282, // Key: Num lock + KEY_PRINT_SCREEN = 283, // Key: Print screen + KEY_PAUSE = 284, // Key: Pause + KEY_F1 = 290, // Key: F1 + KEY_F2 = 291, // Key: F2 + KEY_F3 = 292, // Key: F3 + KEY_F4 = 293, // Key: F4 + KEY_F5 = 294, // Key: F5 + KEY_F6 = 295, // Key: F6 + KEY_F7 = 296, // Key: F7 + KEY_F8 = 297, // Key: F8 + KEY_F9 = 298, // Key: F9 + KEY_F10 = 299, // Key: F10 + KEY_F11 = 300, // Key: F11 + KEY_F12 = 301, // Key: F12 + KEY_LEFT_SHIFT = 340, // Key: Shift left + KEY_LEFT_CONTROL = 341, // Key: Control left + KEY_LEFT_ALT = 342, // Key: Alt left + KEY_LEFT_SUPER = 343, // Key: Super left + KEY_RIGHT_SHIFT = 344, // Key: Shift right + KEY_RIGHT_CONTROL = 345, // Key: Control right + KEY_RIGHT_ALT = 346, // Key: Alt right + KEY_RIGHT_SUPER = 347, // Key: Super right + KEY_KB_MENU = 348, // Key: KB menu + // Keypad keys + KEY_KP_0 = 320, // Key: Keypad 0 + KEY_KP_1 = 321, // Key: Keypad 1 + KEY_KP_2 = 322, // Key: Keypad 2 + KEY_KP_3 = 323, // Key: Keypad 3 + KEY_KP_4 = 324, // Key: Keypad 4 + KEY_KP_5 = 325, // Key: Keypad 5 + KEY_KP_6 = 326, // Key: Keypad 6 + KEY_KP_7 = 327, // Key: Keypad 7 + KEY_KP_8 = 328, // Key: Keypad 8 + KEY_KP_9 = 329, // Key: Keypad 9 + KEY_KP_DECIMAL = 330, // Key: Keypad . + KEY_KP_DIVIDE = 331, // Key: Keypad / + KEY_KP_MULTIPLY = 332, // Key: Keypad * + KEY_KP_SUBTRACT = 333, // Key: Keypad - + KEY_KP_ADD = 334, // Key: Keypad + + KEY_KP_ENTER = 335, // Key: Keypad Enter + KEY_KP_EQUAL = 336, // Key: Keypad = + // Android key buttons + KEY_BACK = 4, // Key: Android back button + KEY_MENU = 5, // Key: Android menu button + KEY_VOLUME_UP = 24, // Key: Android volume up button + KEY_VOLUME_DOWN = 25 // Key: Android volume down button +} KeyboardKey; + +// Add backwards compatibility support for deprecated names +#define MOUSE_LEFT_BUTTON MOUSE_BUTTON_LEFT +#define MOUSE_RIGHT_BUTTON MOUSE_BUTTON_RIGHT +#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE + +// Mouse buttons +typedef enum { + MOUSE_BUTTON_LEFT = 0, // Mouse button left + MOUSE_BUTTON_RIGHT = 1, // Mouse button right + MOUSE_BUTTON_MIDDLE = 2, // Mouse button middle (pressed wheel) + MOUSE_BUTTON_SIDE = 3, // Mouse button side (advanced mouse device) + MOUSE_BUTTON_EXTRA = 4, // Mouse button extra (advanced mouse device) + MOUSE_BUTTON_FORWARD = 5, // Mouse button forward (advanced mouse device) + MOUSE_BUTTON_BACK = 6, // Mouse button back (advanced mouse device) +} MouseButton; + +// Mouse cursor +typedef enum { + MOUSE_CURSOR_DEFAULT = 0, // Default pointer shape + MOUSE_CURSOR_ARROW = 1, // Arrow shape + MOUSE_CURSOR_IBEAM = 2, // Text writing cursor shape + MOUSE_CURSOR_CROSSHAIR = 3, // Cross shape + MOUSE_CURSOR_POINTING_HAND = 4, // Pointing hand cursor + MOUSE_CURSOR_RESIZE_EW = 5, // Horizontal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NS = 6, // Vertical resize/move arrow shape + MOUSE_CURSOR_RESIZE_NWSE = 7, // Top-left to bottom-right diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NESW = 8, // The top-right to bottom-left diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_ALL = 9, // The omnidirectional resize/move cursor shape + MOUSE_CURSOR_NOT_ALLOWED = 10 // The operation-not-allowed shape +} MouseCursor; + +// Gamepad buttons +typedef enum { + GAMEPAD_BUTTON_UNKNOWN = 0, // Unknown button, just for error checking + GAMEPAD_BUTTON_LEFT_FACE_UP, // Gamepad left DPAD up button + GAMEPAD_BUTTON_LEFT_FACE_RIGHT, // Gamepad left DPAD right button + GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button + GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button + GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Circle, Xbox: B) + GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) + GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Square, Xbox: X) + GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button + GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (first), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button + GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) + GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) + GAMEPAD_BUTTON_MIDDLE_RIGHT, // Gamepad center buttons, right one (i.e. PS3: Start) + GAMEPAD_BUTTON_LEFT_THUMB, // Gamepad joystick pressed button left + GAMEPAD_BUTTON_RIGHT_THUMB // Gamepad joystick pressed button right +} GamepadButton; + +// Gamepad axis +typedef enum { + GAMEPAD_AXIS_LEFT_X = 0, // Gamepad left stick X axis + GAMEPAD_AXIS_LEFT_Y = 1, // Gamepad left stick Y axis + GAMEPAD_AXIS_RIGHT_X = 2, // Gamepad right stick X axis + GAMEPAD_AXIS_RIGHT_Y = 3, // Gamepad right stick Y axis + GAMEPAD_AXIS_LEFT_TRIGGER = 4, // Gamepad back trigger left, pressure level: [1..-1] + GAMEPAD_AXIS_RIGHT_TRIGGER = 5 // Gamepad back trigger right, pressure level: [1..-1] +} GamepadAxis; + +// Material map index +typedef enum { + MATERIAL_MAP_ALBEDO = 0, // Albedo material (same as: MATERIAL_MAP_DIFFUSE) + MATERIAL_MAP_METALNESS, // Metalness material (same as: MATERIAL_MAP_SPECULAR) + MATERIAL_MAP_NORMAL, // Normal material + MATERIAL_MAP_ROUGHNESS, // Roughness material + MATERIAL_MAP_OCCLUSION, // Ambient occlusion material + MATERIAL_MAP_EMISSION, // Emission material + MATERIAL_MAP_HEIGHT, // Heightmap material + MATERIAL_MAP_CUBEMAP, // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_IRRADIANCE, // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_PREFILTER, // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_BRDF // Brdf material +} MaterialMapIndex; + +#define MATERIAL_MAP_DIFFUSE MATERIAL_MAP_ALBEDO +#define MATERIAL_MAP_SPECULAR MATERIAL_MAP_METALNESS + +// Shader location index +typedef enum { + SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position + SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 + SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 + SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal + SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent + SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color + SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection + SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) + SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection + SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) + SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal + SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view + SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color + SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color + SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color + SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) + SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) + SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal + SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness + SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion + SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission + SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height + SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap + SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance + SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter + SHADER_LOC_MAP_BRDF, // Shader location: sampler2d texture: brdf + SHADER_LOC_VERTEX_BONEIDS, // Shader location: vertex attribute: boneIds + SHADER_LOC_VERTEX_BONEWEIGHTS, // Shader location: vertex attribute: boneWeights + SHADER_LOC_BONE_MATRICES // Shader location: array of matrices uniform: boneMatrices +} ShaderLocationIndex; + +#define SHADER_LOC_MAP_DIFFUSE SHADER_LOC_MAP_ALBEDO +#define SHADER_LOC_MAP_SPECULAR SHADER_LOC_MAP_METALNESS + +// Shader uniform data type +typedef enum { + SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float + SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) + SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) + SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) + SHADER_UNIFORM_INT, // Shader uniform type: int + SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) + SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) + SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) + SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d +} ShaderUniformDataType; + +// Shader attribute data types +typedef enum { + SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float + SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) + SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) + SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) +} ShaderAttributeDataType; + +// Pixel formats +// NOTE: Support depends on OpenGL version and platform +typedef enum { + PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) + PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) + PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp + PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp + PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp + PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) + PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) + PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) + PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) + PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp + PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp +} PixelFormat; + +// Texture parameters: filter mode +// NOTE 1: Filtering considers mipmaps if available in the texture +// NOTE 2: Filter is accordingly set for minification and magnification +typedef enum { + TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation + TEXTURE_FILTER_BILINEAR, // Linear filtering + TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) + TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x + TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x + TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x +} TextureFilter; + +// Texture parameters: wrap mode +typedef enum { + TEXTURE_WRAP_REPEAT = 0, // Repeats texture in tiled mode + TEXTURE_WRAP_CLAMP, // Clamps texture to edge pixel in tiled mode + TEXTURE_WRAP_MIRROR_REPEAT, // Mirrors and repeats the texture in tiled mode + TEXTURE_WRAP_MIRROR_CLAMP // Mirrors and clamps to border the texture in tiled mode +} TextureWrap; + +// Cubemap layouts +typedef enum { + CUBEMAP_LAYOUT_AUTO_DETECT = 0, // Automatically detect layout type + CUBEMAP_LAYOUT_LINE_VERTICAL, // Layout is defined by a vertical line with faces + CUBEMAP_LAYOUT_LINE_HORIZONTAL, // Layout is defined by a horizontal line with faces + CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR, // Layout is defined by a 3x4 cross with cubemap faces + CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE // Layout is defined by a 4x3 cross with cubemap faces +} CubemapLayout; + +// Font type, defines generation method +typedef enum { + FONT_DEFAULT = 0, // Default font generation, anti-aliased + FONT_BITMAP, // Bitmap font generation, no anti-aliasing + FONT_SDF // SDF font generation, requires external shader +} FontType; + +// Color blending modes (pre-defined) +typedef enum { + BLEND_ALPHA = 0, // Blend textures considering alpha (default) + BLEND_ADDITIVE, // Blend textures adding colors + BLEND_MULTIPLIED, // Blend textures multiplying colors + BLEND_ADD_COLORS, // Blend textures adding colors (alternative) + BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) + BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha + BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) + BLEND_CUSTOM_SEPARATE // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) +} BlendMode; + +// Gesture +// NOTE: Provided as bit-wise flags to enable only desired gestures +typedef enum { + GESTURE_NONE = 0, // No gesture + GESTURE_TAP = 1, // Tap gesture + GESTURE_DOUBLETAP = 2, // Double tap gesture + GESTURE_HOLD = 4, // Hold gesture + GESTURE_DRAG = 8, // Drag gesture + GESTURE_SWIPE_RIGHT = 16, // Swipe right gesture + GESTURE_SWIPE_LEFT = 32, // Swipe left gesture + GESTURE_SWIPE_UP = 64, // Swipe up gesture + GESTURE_SWIPE_DOWN = 128, // Swipe down gesture + GESTURE_PINCH_IN = 256, // Pinch in gesture + GESTURE_PINCH_OUT = 512 // Pinch out gesture +} Gesture; + +// Camera system modes +typedef enum { + CAMERA_CUSTOM = 0, // Camera custom, controlled by user (UpdateCamera() does nothing) + CAMERA_FREE, // Camera free mode + CAMERA_ORBITAL, // Camera orbital, around target, zoom supported + CAMERA_FIRST_PERSON, // Camera first person + CAMERA_THIRD_PERSON // Camera third person +} CameraMode; + +// Camera projection +typedef enum { + CAMERA_PERSPECTIVE = 0, // Perspective projection + CAMERA_ORTHOGRAPHIC // Orthographic projection +} CameraProjection; + +// N-patch layout +typedef enum { + NPATCH_NINE_PATCH = 0, // Npatch layout: 3x3 tiles + NPATCH_THREE_PATCH_VERTICAL, // Npatch layout: 1x3 tiles + NPATCH_THREE_PATCH_HORIZONTAL // Npatch layout: 3x1 tiles +} NPatchLayout; + +// Callbacks to hook some internal functions +// WARNING: These callbacks are intended for advanced users +typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages +typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, int *dataSize); // FileIO: Load binary data +typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, int dataSize); // FileIO: Save binary data +typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data +typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data + +//------------------------------------------------------------------------------------ +// Global Variables Definition +//------------------------------------------------------------------------------------ +// It's lonely here... + +//------------------------------------------------------------------------------------ +// Window and Graphics Device Functions (Module: core) +//------------------------------------------------------------------------------------ + +#if defined(__cplusplus) +extern "C" { // Prevents name mangling of functions +#endif + +// Window-related functions +RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context +RLAPI void CloseWindow(void); // Close window and unload OpenGL context +RLAPI bool WindowShouldClose(void); // Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) +RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully +RLAPI bool IsWindowFullscreen(void); // Check if window is currently fullscreen +RLAPI bool IsWindowHidden(void); // Check if window is currently hidden +RLAPI bool IsWindowMinimized(void); // Check if window is currently minimized +RLAPI bool IsWindowMaximized(void); // Check if window is currently maximized +RLAPI bool IsWindowFocused(void); // Check if window is currently focused +RLAPI bool IsWindowResized(void); // Check if window has been resized last frame +RLAPI bool IsWindowState(unsigned int flag); // Check if one specific window flag is enabled +RLAPI void SetWindowState(unsigned int flags); // Set window configuration state using flags +RLAPI void ClearWindowState(unsigned int flags); // Clear window configuration state flags +RLAPI void ToggleFullscreen(void); // Toggle window state: fullscreen/windowed, resizes monitor to match window resolution +RLAPI void ToggleBorderlessWindowed(void); // Toggle window state: borderless windowed, resizes window to match monitor resolution +RLAPI void MaximizeWindow(void); // Set window state: maximized, if resizable +RLAPI void MinimizeWindow(void); // Set window state: minimized, if resizable +RLAPI void RestoreWindow(void); // Set window state: not minimized/maximized +RLAPI void SetWindowIcon(Image image); // Set icon for window (single image, RGBA 32bit) +RLAPI void SetWindowIcons(Image *images, int count); // Set icon for window (multiple images, RGBA 32bit) +RLAPI void SetWindowTitle(const char *title); // Set title for window +RLAPI void SetWindowPosition(int x, int y); // Set window position on screen +RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window +RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +RLAPI void SetWindowMaxSize(int width, int height); // Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) +RLAPI void SetWindowSize(int width, int height); // Set window dimensions +RLAPI void SetWindowOpacity(float opacity); // Set window opacity [0.0f..1.0f] +RLAPI void SetWindowFocused(void); // Set window focused +RLAPI void *GetWindowHandle(void); // Get native window handle +RLAPI int GetScreenWidth(void); // Get current screen width +RLAPI int GetScreenHeight(void); // Get current screen height +RLAPI int GetRenderWidth(void); // Get current render width (it considers HiDPI) +RLAPI int GetRenderHeight(void); // Get current render height (it considers HiDPI) +RLAPI int GetMonitorCount(void); // Get number of connected monitors +RLAPI int GetCurrentMonitor(void); // Get current monitor where window is placed +RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position +RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor) +RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor) +RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres +RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres +RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate +RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor +RLAPI Vector2 GetWindowScaleDPI(void); // Get window scale DPI factor +RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the specified monitor +RLAPI void SetClipboardText(const char *text); // Set clipboard text content +RLAPI const char *GetClipboardText(void); // Get clipboard text content +RLAPI Image GetClipboardImage(void); // Get clipboard image content +RLAPI void EnableEventWaiting(void); // Enable waiting for events on EndDrawing(), no automatic event polling +RLAPI void DisableEventWaiting(void); // Disable waiting for events on EndDrawing(), automatic events polling + +// Cursor-related functions +RLAPI void ShowCursor(void); // Shows cursor +RLAPI void HideCursor(void); // Hides cursor +RLAPI bool IsCursorHidden(void); // Check if cursor is not visible +RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) +RLAPI void DisableCursor(void); // Disables cursor (lock cursor) +RLAPI bool IsCursorOnScreen(void); // Check if cursor is on the screen + +// Drawing-related functions +RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) +RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing +RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) +RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D) +RLAPI void EndMode2D(void); // Ends 2D mode with custom camera +RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D) +RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode +RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture +RLAPI void EndTextureMode(void); // Ends drawing to render texture +RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing +RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) +RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom) +RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) +RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing) +RLAPI void EndScissorMode(void); // End scissor mode +RLAPI void BeginVrStereoMode(VrStereoConfig config); // Begin stereo rendering (requires VR simulator) +RLAPI void EndVrStereoMode(void); // End stereo rendering (requires VR simulator) + +// VR stereo config functions for VR simulator +RLAPI VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device); // Load VR stereo config for VR simulator device parameters +RLAPI void UnloadVrStereoConfig(VrStereoConfig config); // Unload VR stereo config + +// Shader management functions +// NOTE: Shader functionality is not available on OpenGL 1.1 +RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations +RLAPI Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations +RLAPI bool IsShaderValid(Shader shader); // Check if a shader is valid (loaded on GPU) +RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location +RLAPI void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType); // Set shader uniform value +RLAPI void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count); // Set shader uniform value vector +RLAPI void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture); // Set shader uniform value for texture (sampler2d) +RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) + +// Screen-space-related functions +#define GetMouseRay GetScreenToWorldRay // Compatibility hack for previous raylib versions +RLAPI Ray GetScreenToWorldRay(Vector2 position, Camera camera); // Get a ray trace from screen position (i.e mouse) +RLAPI Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height); // Get a ray trace from screen position (i.e mouse) in a viewport +RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position +RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position +RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position +RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position +RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) +RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix + +// Timing-related functions +RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) +RLAPI float GetFrameTime(void); // Get time in seconds for last frame drawn (delta time) +RLAPI double GetTime(void); // Get elapsed time in seconds since InitWindow() +RLAPI int GetFPS(void); // Get current FPS + +// Custom frame control functions +// NOTE: Those functions are intended for advanced users that want full control over the frame processing +// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() +// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL +RLAPI void SwapScreenBuffer(void); // Swap back buffer with front buffer (screen drawing) +RLAPI void PollInputEvents(void); // Register all input events +RLAPI void WaitTime(double seconds); // Wait for some time (halt program execution) + +// Random values generation functions +RLAPI void SetRandomSeed(unsigned int seed); // Set the seed for the random number generator +RLAPI int GetRandomValue(int min, int max); // Get a random value between min and max (both included) +RLAPI int *LoadRandomSequence(unsigned int count, int min, int max); // Load random values sequence, no values repeated +RLAPI void UnloadRandomSequence(int *sequence); // Unload random values sequence + +// Misc. functions +RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format) +RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS) +RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available) + +// NOTE: Following functions implemented in module [utils] +//------------------------------------------------------------------ +RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) +RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level +RLAPI void *MemAlloc(unsigned int size); // Internal memory allocator +RLAPI void *MemRealloc(void *ptr, unsigned int size); // Internal memory reallocator +RLAPI void MemFree(void *ptr); // Internal memory free + +// Set custom callbacks +// WARNING: Callbacks setup is intended for advanced users +RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log +RLAPI void SetLoadFileDataCallback(LoadFileDataCallback callback); // Set custom file binary data loader +RLAPI void SetSaveFileDataCallback(SaveFileDataCallback callback); // Set custom file binary data saver +RLAPI void SetLoadFileTextCallback(LoadFileTextCallback callback); // Set custom file text data loader +RLAPI void SetSaveFileTextCallback(SaveFileTextCallback callback); // Set custom file text data saver + +// Files management functions +RLAPI unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) +RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData() +RLAPI bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write), returns true on success +RLAPI bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName); // Export data to code (.h), returns true on success +RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string +RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText() +RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success +//------------------------------------------------------------------ + +// File system functions +RLAPI bool FileExists(const char *fileName); // Check if file exists +RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists +RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (including point: .png, .wav) +RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h) +RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png') +RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string +RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) +RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string) +RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string) +RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) +RLAPI const char *GetApplicationDirectory(void); // Get the directory of the running application (uses static string) +RLAPI int MakeDirectory(const char *dirPath); // Create directories (including full path requested), returns 0 on success +RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success +RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory +RLAPI bool IsFileNameValid(const char *fileName); // Check if fileName is valid for the platform/OS +RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths +RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan. Use 'DIR' in the filter string to include directories in the result +RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths +RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window +RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths +RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths +RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) + +// Compression/Encoding functionality +RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree() +RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // Decompress data (DEFLATE algorithm), memory must be MemFree() +RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree() +RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree() +RLAPI unsigned int ComputeCRC32(unsigned char *data, int dataSize); // Compute CRC32 hash code +RLAPI unsigned int *ComputeMD5(unsigned char *data, int dataSize); // Compute MD5 hash code, returns static int[4] (16 bytes) +RLAPI unsigned int *ComputeSHA1(unsigned char *data, int dataSize); // Compute SHA1 hash code, returns static int[5] (20 bytes) + + +// Automation events functionality +RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS +RLAPI void UnloadAutomationEventList(AutomationEventList list); // Unload automation events list from file +RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file +RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to +RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording +RLAPI void StartAutomationEventRecording(void); // Start recording automation events (AutomationEventList must be set) +RLAPI void StopAutomationEventRecording(void); // Stop recording automation events +RLAPI void PlayAutomationEvent(AutomationEvent event); // Play a recorded automation event + +//------------------------------------------------------------------------------------ +// Input Handling Functions (Module: core) +//------------------------------------------------------------------------------------ + +// Input-related functions: keyboard +RLAPI bool IsKeyPressed(int key); // Check if a key has been pressed once +RLAPI bool IsKeyPressedRepeat(int key); // Check if a key has been pressed again +RLAPI bool IsKeyDown(int key); // Check if a key is being pressed +RLAPI bool IsKeyReleased(int key); // Check if a key has been released once +RLAPI bool IsKeyUp(int key); // Check if a key is NOT being pressed +RLAPI int GetKeyPressed(void); // Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty +RLAPI int GetCharPressed(void); // Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty +RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) + +// Input-related functions: gamepads +RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available +RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id +RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once +RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed +RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once +RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed +RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed +RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad +RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis +RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) +RLAPI void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration); // Set gamepad vibration for both motors (duration in seconds) + +// Input-related functions: mouse +RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once +RLAPI bool IsMouseButtonDown(int button); // Check if a mouse button is being pressed +RLAPI bool IsMouseButtonReleased(int button); // Check if a mouse button has been released once +RLAPI bool IsMouseButtonUp(int button); // Check if a mouse button is NOT being pressed +RLAPI int GetMouseX(void); // Get mouse position X +RLAPI int GetMouseY(void); // Get mouse position Y +RLAPI Vector2 GetMousePosition(void); // Get mouse position XY +RLAPI Vector2 GetMouseDelta(void); // Get mouse delta between frames +RLAPI void SetMousePosition(int x, int y); // Set mouse position XY +RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset +RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling +RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger +RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y +RLAPI void SetMouseCursor(int cursor); // Set mouse cursor + +// Input-related functions: touch +RLAPI int GetTouchX(void); // Get touch position X for touch point 0 (relative to screen size) +RLAPI int GetTouchY(void); // Get touch position Y for touch point 0 (relative to screen size) +RLAPI Vector2 GetTouchPosition(int index); // Get touch position XY for a touch point index (relative to screen size) +RLAPI int GetTouchPointId(int index); // Get touch point identifier for given index +RLAPI int GetTouchPointCount(void); // Get number of touch points + +//------------------------------------------------------------------------------------ +// Gestures and Touch Handling Functions (Module: rgestures) +//------------------------------------------------------------------------------------ +RLAPI void SetGesturesEnabled(unsigned int flags); // Enable a set of gestures using flags +RLAPI bool IsGestureDetected(unsigned int gesture); // Check if a gesture have been detected +RLAPI int GetGestureDetected(void); // Get latest detected gesture +RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in seconds +RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector +RLAPI float GetGestureDragAngle(void); // Get gesture drag angle +RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta +RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle + +//------------------------------------------------------------------------------------ +// Camera System Functions (Module: rcamera) +//------------------------------------------------------------------------------------ +RLAPI void UpdateCamera(Camera *camera, int mode); // Update camera position for selected mode +RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, float zoom); // Update camera movement/rotation + +//------------------------------------------------------------------------------------ +// Basic Shapes Drawing Functions (Module: shapes) +//------------------------------------------------------------------------------------ +// Set texture and rectangle to be used on shapes drawing +// NOTE: It can be useful when using basic shapes and one single font, +// defining a font char white rectangle would allow drawing everything in a single draw call +RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing +RLAPI Texture2D GetShapesTexture(void); // Get texture that is used for shapes drawing +RLAPI Rectangle GetShapesTextureRectangle(void); // Get texture source rectangle that is used for shapes drawing + +// Basic shapes drawing functions +RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel using geometry [Can be slow, use with care] +RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel using geometry (Vector version) [Can be slow, use with care] +RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line +RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (using gl lines) +RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line (using triangles/quads) +RLAPI void DrawLineStrip(const Vector2 *points, int pointCount, Color color); // Draw lines sequence (using gl lines) +RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw line segment cubic-bezier in-out interpolation +RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle +RLAPI void DrawCircleSector(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw a piece of a circle +RLAPI void DrawCircleSectorLines(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw circle sector outline +RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color inner, Color outer); // Draw a gradient-filled circle +RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) +RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline +RLAPI void DrawCircleLinesV(Vector2 center, float radius, Color color); // Draw circle outline (Vector version) +RLAPI void DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse +RLAPI void DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse outline +RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring +RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring outline +RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle +RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) +RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle +RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters +RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color top, Color bottom); // Draw a vertical-gradient-filled rectangle +RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color left, Color right); // Draw a horizontal-gradient-filled rectangle +RLAPI void DrawRectangleGradientEx(Rectangle rec, Color topLeft, Color bottomLeft, Color topRight, Color bottomRight); // Draw a gradient-filled rectangle with custom vertex colors +RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline +RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters +RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges +RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle lines with rounded edges +RLAPI void DrawRectangleRoundedLinesEx(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline +RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) +RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) +RLAPI void DrawTriangleFan(const Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) +RLAPI void DrawTriangleStrip(const Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points +RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) +RLAPI void DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a polygon outline of n sides +RLAPI void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, float lineThick, Color color); // Draw a polygon outline of n sides with extended parameters + +// Splines drawing functions +RLAPI void DrawSplineLinear(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Linear, minimum 2 points +RLAPI void DrawSplineBasis(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: B-Spline, minimum 4 points +RLAPI void DrawSplineCatmullRom(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Catmull-Rom, minimum 4 points +RLAPI void DrawSplineBezierQuadratic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] +RLAPI void DrawSplineBezierCubic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] +RLAPI void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color); // Draw spline segment: Linear, 2 points +RLAPI void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: B-Spline, 4 points +RLAPI void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: Catmull-Rom, 4 points +RLAPI void DrawSplineSegmentBezierQuadratic(Vector2 p1, Vector2 c2, Vector2 p3, float thick, Color color); // Draw spline segment: Quadratic Bezier, 2 points, 1 control point +RLAPI void DrawSplineSegmentBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float thick, Color color); // Draw spline segment: Cubic Bezier, 2 points, 2 control points + +// Spline segment point evaluation functions, for a given t [0.0f .. 1.0f] +RLAPI Vector2 GetSplinePointLinear(Vector2 startPos, Vector2 endPos, float t); // Get (evaluate) spline point: Linear +RLAPI Vector2 GetSplinePointBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: B-Spline +RLAPI Vector2 GetSplinePointCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: Catmull-Rom +RLAPI Vector2 GetSplinePointBezierQuad(Vector2 p1, Vector2 c2, Vector2 p3, float t); // Get (evaluate) spline point: Quadratic Bezier +RLAPI Vector2 GetSplinePointBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float t); // Get (evaluate) spline point: Cubic Bezier + +// Basic shapes collision detection functions +RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles +RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles +RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle +RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2); // Check if circle collides with a line created betweeen two points [p1] and [p2] +RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle +RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle +RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle +RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] +RLAPI bool CheckCollisionPointPoly(Vector2 point, const Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices +RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference +RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision + +//------------------------------------------------------------------------------------ +// Texture Loading and Drawing Functions (Module: textures) +//------------------------------------------------------------------------------------ + +// Image loading functions +// NOTE: These functions do not require GPU access +RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) +RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data +RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) +RLAPI Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames); // Load image sequence from memory buffer +RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' +RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data +RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) +RLAPI bool IsImageValid(Image image); // Check if an image is valid (data and parameters) +RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) +RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success +RLAPI unsigned char *ExportImageToMemory(Image image, const char *fileType, int *fileSize); // Export image to memory buffer +RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success + +// Image generation functions +RLAPI Image GenImageColor(int width, int height, Color color); // Generate image: plain color +RLAPI Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end); // Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient +RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient +RLAPI Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer); // Generate image: square gradient +RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked +RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise +RLAPI Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale); // Generate image: perlin noise +RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm, bigger tileSize means bigger cells +RLAPI Image GenImageText(int width, int height, const char *text); // Generate image: grayscale image from text data + +// Image manipulation functions +RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) +RLAPI Image ImageFromImage(Image image, Rectangle rec); // Create an image from another image piece +RLAPI Image ImageFromChannel(Image image, int selectedChannel); // Create an image from a selected channel of another image (GRAYSCALE) +RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) +RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint); // Create an image from text (custom sprite font) +RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format +RLAPI void ImageToPOT(Image *image, Color fill); // Convert image to POT (power-of-two) +RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle +RLAPI void ImageAlphaCrop(Image *image, float threshold); // Crop image depending on alpha value +RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); // Clear alpha channel to desired color +RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image +RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel +RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation +RLAPI void ImageKernelConvolution(Image *image, const float *kernel, int kernelSize); // Apply custom square convolution kernel to image +RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) +RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) +RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color +RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image +RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) +RLAPI void ImageFlipVertical(Image *image); // Flip image vertically +RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally +RLAPI void ImageRotate(Image *image, int degrees); // Rotate image by input angle in degrees (-359 to 359) +RLAPI void ImageRotateCW(Image *image); // Rotate image clockwise 90deg +RLAPI void ImageRotateCCW(Image *image); // Rotate image counter-clockwise 90deg +RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint +RLAPI void ImageColorInvert(Image *image); // Modify image color: invert +RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale +RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) +RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) +RLAPI void ImageColorReplace(Image *image, Color color, Color replace); // Modify image color: replace color +RLAPI Color *LoadImageColors(Image image); // Load color data from image as a Color array (RGBA - 32bit) +RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount); // Load colors palette from image as a Color array (RGBA - 32bit) +RLAPI void UnloadImageColors(Color *colors); // Unload color data loaded with LoadImageColors() +RLAPI void UnloadImagePalette(Color *colors); // Unload colors palette loaded with LoadImagePalette() +RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle +RLAPI Color GetImageColor(Image image, int x, int y); // Get image pixel color at (x, y) position + +// Image drawing functions +// NOTE: Image software-rendering functions (CPU) +RLAPI void ImageClearBackground(Image *dst, Color color); // Clear image background with given color +RLAPI void ImageDrawPixel(Image *dst, int posX, int posY, Color color); // Draw pixel within an image +RLAPI void ImageDrawPixelV(Image *dst, Vector2 position, Color color); // Draw pixel within an image (Vector version) +RLAPI void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw line within an image +RLAPI void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color); // Draw line within an image (Vector version) +RLAPI void ImageDrawLineEx(Image *dst, Vector2 start, Vector2 end, int thick, Color color); // Draw a line defining thickness within an image +RLAPI void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color); // Draw a filled circle within an image +RLAPI void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color); // Draw a filled circle within an image (Vector version) +RLAPI void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color); // Draw circle outline within an image +RLAPI void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color); // Draw circle outline within an image (Vector version) +RLAPI void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color); // Draw rectangle within an image +RLAPI void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color); // Draw rectangle within an image (Vector version) +RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color); // Draw rectangle within an image +RLAPI void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color); // Draw rectangle lines within an image +RLAPI void ImageDrawTriangle(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle within an image +RLAPI void ImageDrawTriangleEx(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color c1, Color c2, Color c3); // Draw triangle with interpolated colors within an image +RLAPI void ImageDrawTriangleLines(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline within an image +RLAPI void ImageDrawTriangleFan(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points within an image (first vertex is the center) +RLAPI void ImageDrawTriangleStrip(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points within an image +RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint); // Draw a source image within a destination image (tint applied to source) +RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) within an image (destination) +RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text (custom sprite font) within an image (destination) + +// Texture loading functions +// NOTE: These functions require GPU access +RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) +RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data +RLAPI TextureCubemap LoadTextureCubemap(Image image, int layout); // Load cubemap from image, multiple image cubemap layouts supported +RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) +RLAPI bool IsTextureValid(Texture2D texture); // Check if a texture is valid (loaded in GPU) +RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) +RLAPI bool IsRenderTextureValid(RenderTexture2D target); // Check if a render texture is valid (loaded in GPU) +RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) +RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data +RLAPI void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels); // Update GPU texture rectangle with new data + +// Texture configuration functions +RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture +RLAPI void SetTextureFilter(Texture2D texture, int filter); // Set texture scaling filter mode +RLAPI void SetTextureWrap(Texture2D texture, int wrap); // Set texture wrapping mode + +// Texture drawing functions +RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D +RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 +RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters +RLAPI void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle +RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draw a part of a texture defined by a rectangle with 'pro' parameters +RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely + +// Color/pixel related functions +RLAPI bool ColorIsEqual(Color col1, Color col2); // Check if two colors are equal +RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f +RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color (0xRRGGBBAA) +RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] +RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] +RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] +RLAPI Color ColorFromHSV(float hue, float saturation, float value); // Get a Color from HSV values, hue [0..360], saturation/value [0..1] +RLAPI Color ColorTint(Color color, Color tint); // Get color multiplied with another color +RLAPI Color ColorBrightness(Color color, float factor); // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f +RLAPI Color ColorContrast(Color color, float contrast); // Get color with contrast correction, contrast values between -1.0f and 1.0f +RLAPI Color ColorAlpha(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f +RLAPI Color ColorAlphaBlend(Color dst, Color src, Color tint); // Get src alpha-blended into dst color with tint +RLAPI Color ColorLerp(Color color1, Color color2, float factor); // Get color lerp interpolation between two colors, factor [0.0f..1.0f] +RLAPI Color GetColor(unsigned int hexValue); // Get Color structure from hexadecimal value +RLAPI Color GetPixelColor(void *srcPtr, int format); // Get Color from a source pixel pointer of certain format +RLAPI void SetPixelColor(void *dstPtr, Color color, int format); // Set color formatted into destination pixel pointer +RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes for certain format + +//------------------------------------------------------------------------------------ +// Font Loading and Text Drawing Functions (Module: text) +//------------------------------------------------------------------------------------ + +// Font loading/unloading functions +RLAPI Font GetFontDefault(void); // Get the default Font +RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM) +RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character set, font size is provided in pixels height +RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style) +RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf' +RLAPI bool IsFontValid(Font font); // Check if a font is valid (font data loaded, WARNING: GPU texture not checked) +RLAPI GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount, int type); // Load font data for further use +RLAPI Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info +RLAPI void UnloadFontData(GlyphInfo *glyphs, int glyphCount); // Unload font chars info data (RAM) +RLAPI void UnloadFont(Font font); // Unload font from GPU memory (VRAM) +RLAPI bool ExportFontAsCode(Font font, const char *fileName); // Export font as code file, returns true on success + +// Text drawing functions +RLAPI void DrawFPS(int posX, int posY); // Draw current FPS +RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) +RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters +RLAPI void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint); // Draw text using Font and pro parameters (rotation) +RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint) +RLAPI void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint); // Draw multiple character (codepoint) + +// Text font info functions +RLAPI void SetTextLineSpacing(int spacing); // Set vertical line spacing when drawing with line-breaks +RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font +RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font +RLAPI int GetGlyphIndex(Font font, int codepoint); // Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found +RLAPI GlyphInfo GetGlyphInfo(Font font, int codepoint); // Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found +RLAPI Rectangle GetGlyphAtlasRec(Font font, int codepoint); // Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found + +// Text codepoints management functions (unicode characters) +RLAPI char *LoadUTF8(const int *codepoints, int length); // Load UTF-8 text encoded from codepoints array +RLAPI void UnloadUTF8(char *text); // Unload UTF-8 text encoded from codepoints array +RLAPI int *LoadCodepoints(const char *text, int *count); // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter +RLAPI void UnloadCodepoints(int *codepoints); // Unload codepoints data from memory +RLAPI int GetCodepointCount(const char *text); // Get total number of codepoints in a UTF-8 encoded string +RLAPI int GetCodepoint(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI int GetCodepointPrevious(const char *text, int *codepointSize); // Get previous codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter) + +// Text strings management functions (no UTF-8 strings, only byte chars) +// NOTE: Some strings allocate memory internally for returned strings, just be careful! +RLAPI int TextCopy(char *dst, const char *src); // Copy one string to another, returns bytes copied +RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal +RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending +RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) +RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string +RLAPI char *TextReplace(const char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) +RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) +RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter +RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings +RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! +RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string +RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string +RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string +RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string +RLAPI const char *TextToSnake(const char *text); // Get Snake case notation version of provided string +RLAPI const char *TextToCamel(const char *text); // Get Camel case notation version of provided string + +RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) +RLAPI float TextToFloat(const char *text); // Get float value from text (negative values not supported) + +//------------------------------------------------------------------------------------ +// Basic 3d Shapes Drawing Functions (Module: models) +//------------------------------------------------------------------------------------ + +// Basic geometric 3D shapes drawing functions +RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space +RLAPI void DrawPoint3D(Vector3 position, Color color); // Draw a point in 3D space, actually a small line +RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space +RLAPI void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) +RLAPI void DrawTriangleStrip3D(const Vector3 *points, int pointCount, Color color); // Draw a triangle strip defined by points +RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube +RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) +RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires +RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) +RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere +RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters +RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires +RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone +RLAPI void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder with base at startPos and top at endPos +RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires +RLAPI void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder wires with base at startPos and top at endPos +RLAPI void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw a capsule with the center of its sphere caps at startPos and endPos +RLAPI void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw capsule wireframe with the center of its sphere caps at startPos and endPos +RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ +RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line +RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) + +//------------------------------------------------------------------------------------ +// Model 3d Loading and Drawing Functions (Module: models) +//------------------------------------------------------------------------------------ + +// Model management functions +RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) +RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) +RLAPI bool IsModelValid(Model model); // Check if a model is valid (loaded in GPU, VAO/VBOs) +RLAPI void UnloadModel(Model model); // Unload model (including meshes) from memory (RAM and/or VRAM) +RLAPI BoundingBox GetModelBoundingBox(Model model); // Compute model bounding box limits (considers all meshes) + +// Model drawing functions +RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) +RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters +RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) +RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters +RLAPI void DrawModelPoints(Model model, Vector3 position, float scale, Color tint); // Draw a model as points +RLAPI void DrawModelPointsEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model as points with extended parameters +RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) +RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float scale, Color tint); // Draw a billboard texture +RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint); // Draw a billboard texture defined by source +RLAPI void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint); // Draw a billboard texture defined by source and rotation + +// Mesh management functions +RLAPI void UploadMesh(Mesh *mesh, bool dynamic); // Upload mesh vertex data in GPU and provide VAO/VBO ids +RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset); // Update mesh vertex data in GPU for a specific buffer index +RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU +RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform +RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms +RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits +RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents +RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success +RLAPI bool ExportMeshAsCode(Mesh mesh, const char *fileName); // Export mesh as code file (.h) defining multiple arrays of vertex attributes + +// Mesh generation functions +RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh +RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) +RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh +RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) +RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) +RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh +RLAPI Mesh GenMeshCone(float radius, float height, int slices); // Generate cone/pyramid mesh +RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh +RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh +RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data +RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data + +// Material loading/unloading functions +RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file +RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +RLAPI bool IsMaterialValid(Material material); // Check if a material is valid (shader assigned, map textures loaded in GPU) +RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) +RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh + +// Model animations loading/unloading functions +RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount); // Load model animations from file +RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose (CPU) +RLAPI void UpdateModelAnimationBones(Model model, ModelAnimation anim, int frame); // Update model animation mesh bone matrices (GPU skinning) +RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data +RLAPI void UnloadModelAnimations(ModelAnimation *animations, int animCount); // Unload animation array data +RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match + +// Collision detection functions +RLAPI bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2); // Check collision between two spheres +RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Check collision between two bounding boxes +RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Check collision between box and sphere +RLAPI RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius); // Get collision info between ray and sphere +RLAPI RayCollision GetRayCollisionBox(Ray ray, BoundingBox box); // Get collision info between ray and box +RLAPI RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform); // Get collision info between ray and mesh +RLAPI RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle +RLAPI RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4); // Get collision info between ray and quad + +//------------------------------------------------------------------------------------ +// Audio Loading and Playing Functions (Module: audio) +//------------------------------------------------------------------------------------ +typedef void (*AudioCallback)(void *bufferData, unsigned int frames); + +// Audio device management functions +RLAPI void InitAudioDevice(void); // Initialize audio device and context +RLAPI void CloseAudioDevice(void); // Close the audio device and context +RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully +RLAPI void SetMasterVolume(float volume); // Set master volume (listener) +RLAPI float GetMasterVolume(void); // Get master volume (listener) + +// Wave/Sound loading/unloading functions +RLAPI Wave LoadWave(const char *fileName); // Load wave data from file +RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav' +RLAPI bool IsWaveValid(Wave wave); // Checks if wave data is valid (data loaded and parameters) +RLAPI Sound LoadSound(const char *fileName); // Load sound from file +RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data +RLAPI Sound LoadSoundAlias(Sound source); // Create a new sound that shares the same sample data as the source sound, does not own the sound data +RLAPI bool IsSoundValid(Sound sound); // Checks if a sound is valid (data loaded and buffers initialized) +RLAPI void UpdateSound(Sound sound, const void *data, int sampleCount); // Update sound buffer with new data +RLAPI void UnloadWave(Wave wave); // Unload wave data +RLAPI void UnloadSound(Sound sound); // Unload sound +RLAPI void UnloadSoundAlias(Sound alias); // Unload a sound alias (does not deallocate sample data) +RLAPI bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success +RLAPI bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success + +// Wave/Sound management functions +RLAPI void PlaySound(Sound sound); // Play a sound +RLAPI void StopSound(Sound sound); // Stop playing a sound +RLAPI void PauseSound(Sound sound); // Pause a sound +RLAPI void ResumeSound(Sound sound); // Resume a paused sound +RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing +RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) +RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) +RLAPI void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.5 is center) +RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave +RLAPI void WaveCrop(Wave *wave, int initFrame, int finalFrame); // Crop a wave to defined frames range +RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format +RLAPI float *LoadWaveSamples(Wave wave); // Load samples data from wave as a 32bit float data array +RLAPI void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples() + +// Music management functions +RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file +RLAPI Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize); // Load music stream from data +RLAPI bool IsMusicValid(Music music); // Checks if a music stream is valid (context and buffers initialized) +RLAPI void UnloadMusicStream(Music music); // Unload music stream +RLAPI void PlayMusicStream(Music music); // Start music playing +RLAPI bool IsMusicStreamPlaying(Music music); // Check if music is playing +RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming +RLAPI void StopMusicStream(Music music); // Stop music playing +RLAPI void PauseMusicStream(Music music); // Pause music playing +RLAPI void ResumeMusicStream(Music music); // Resume playing paused music +RLAPI void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds) +RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) +RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) +RLAPI void SetMusicPan(Music music, float pan); // Set pan for a music (0.5 is center) +RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) +RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) + +// AudioStream management functions +RLAPI AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data) +RLAPI bool IsAudioStreamValid(AudioStream stream); // Checks if an audio stream is valid (buffers initialized) +RLAPI void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory +RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int frameCount); // Update audio stream buffers with data +RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill +RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream +RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream +RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream +RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing +RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream +RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) +RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) +RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan for audio stream (0.5 is centered) +RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams +RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data + +RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as 'float' +RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream + +RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as 'float' +RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline + +#if defined(__cplusplus) +} +#endif + +#endif // RAYLIB_H From 68625a535e70278247b43e73b0acca92e615bf03 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:34:19 +0700 Subject: [PATCH 3/7] A bindings gap stops a build, and says which file to edit --- lib/load.ml | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/lib/load.ml b/lib/load.ml index 3e110d5..6c5d7e9 100644 --- a/lib/load.ml +++ b/lib/load.ml @@ -877,17 +877,33 @@ let rec import ~seen ~open_ ~loc alias dir = in List.iter (fun (x : Cimport.const_diff) -> - (* Only the findings that are the *library* contradicting the - package stop a build. A [defenum] nobody mapped and a rule - that reaches nothing are about the package's own - `bindings` file, and they gate `flan generate-c`, which is - where that file is edited — telling a lane that added an - enum to go and fix a config, in a message shaped like "the - layout is wrong", is the wrong thing to stop a build - with. *) - if not x.Cimport.cmapping then - fail (Option.value ~default:loc (cloc x.Cimport.cname)) - "the package disagrees with %s: %s" h x.Cimport.cwhy) + (* Both kinds stop a build, and they are worded differently + because they are different accusations. + + [cmapping = false] is the library contradicting the + package: a value that is one number here and another + there. [cmapping = true] is the package's own `bindings` + file not covering something — a [defenum] nobody mapped, + a rule that reaches nothing. + + The second was gated to `flan generate-c` at first, on the + argument that stopping a build over a config file is the + wrong stop. The objection was really to the *wording*: it + arrived wrapped in "the package disagrees with the + header", which describes a layout bug and sends the reader + to the wrong file. Gating it instead meant an unchecked + enum member — exactly the silent wrongness the header read + exists to catch — went unreported on every ordinary build, + and "remember to run generate-c" is the same shape as + "remember to check the header by eye", which is what this + replaced. So: still fatal, and the wording names the file + and both ways out. *) + let at = Option.value ~default:loc (cloc x.Cimport.cname) in + if x.Cimport.cmapping then + fail at "%s" x.Cimport.cwhy + else + fail at "the package disagrees with %s: %s" h + x.Cimport.cwhy) (Cimport.check_constants ~config ~enums ~consts:pconsts dump); r) (header_specs ~loc dir) From d7ceec448eba0acf2e48b3147edb41ba44afc060 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:42:49 +0700 Subject: [PATCH 4/7] Ten more raylib examples, and the three small structs 3D needed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three shapes, two text, three textures, one models and one core, picked for binding surface rather than for how they look. shapes-basic-shapes brings in six draw families nothing had called — the circle and rectangle gradients, the triangles, all three poly draws — and is the first call in the corpus to pass two Colors or three Vector2s at once. shapes-collision-area is get-collision-rec, the only binding that takes two Rectangles and answers a third, on a frame path. shapes-following-eyes is the raymath gap measured rather than worked around: every line of it is vector arithmetic written without a vector library, the way the C writes it. text-input-box drains get-char-pressed's queue, which no example had read, and needed a MouseCursor defenum for set-mouse-cursor. text-writing-anim replaces TextSubtext — unbindable, it answers a pointer into a rotating static buffer — with (string (slice b 0 n)), which is the same operation without the shared state. textures-image-generation runs nine Gen* calls and the gen/upload/unload-image path, all procedural, no file on disk. textures-fog-of-war needed a TextureFilter defenum: the smooth fog edge is entirely :bilinear on a 25x15 render texture, and it is also the first draw-texture-pro with a negative source height. textures-mouse-painting is the same render texture used as a document rather than as scratch, plus the round trip back off the GPU — load-image-from-texture, image-flip-vertical, export-image — which nothing had run. models-box-collisions is the counterexample to "a models example is a binding exercise": nothing in it is a Model, and one BoundingBox defstruct un-refuses four functions. core-3d-picking is the only caller anywhere for Ray and RayCollision, and picking is the inverse of the get-world-to-screen the corpus already had. Added to vendor/raylib: defstructs BoundingBox, Ray and RayCollision; defenums MouseCursor and TextureFilter with their mapping lines in bindings; hand-written declare-c for SetMouseCursor, SetTextureFilter, DrawCubeV, DrawSphere, DrawSphereWires, DrawRay and GetScreenToWorldRay, each excluded from the generated half on the rule bindings already states. generated.flan regenerated against raylib 5.5: 272 declarations, 117 refused, every defstruct, hand-written declare-c and mapped constant agreeing with the header. --- examples/core-3d-picking.flan | 157 +++++++++++++++ examples/models-box-collisions.flan | 133 ++++++++++++ examples/shapes-basic-shapes.flan | 102 ++++++++++ examples/shapes-collision-area.flan | 129 ++++++++++++ examples/shapes-following-eyes.flan | 103 ++++++++++ examples/text-input-box.flan | 140 +++++++++++++ examples/text-writing-anim.flan | 76 +++++++ examples/textures-fog-of-war.flan | 197 ++++++++++++++++++ examples/textures-image-generation.flan | 130 ++++++++++++ examples/textures-mouse-painting.flan | 255 ++++++++++++++++++++++++ vendor/raylib/bindings | 23 +++ vendor/raylib/generated.flan | 13 +- vendor/raylib/raylib.flan | 84 ++++++++ 13 files changed, 1537 insertions(+), 5 deletions(-) create mode 100644 examples/core-3d-picking.flan create mode 100644 examples/models-box-collisions.flan create mode 100644 examples/shapes-basic-shapes.flan create mode 100644 examples/shapes-collision-area.flan create mode 100644 examples/shapes-following-eyes.flan create mode 100644 examples/text-input-box.flan create mode 100644 examples/text-writing-anim.flan create mode 100644 examples/textures-fog-of-war.flan create mode 100644 examples/textures-image-generation.flan create mode 100644 examples/textures-mouse-painting.flan diff --git a/examples/core-3d-picking.flan b/examples/core-3d-picking.flan new file mode 100644 index 0000000..d96d561 --- /dev/null +++ b/examples/core-3d-picking.flan @@ -0,0 +1,157 @@ +;;;; raylib [core] example - 3d picking +;;;; +;;;; examples/core/core_3d_picking.c. The one `core` example in this batch, +;;;; and it is here for surface and not for category: it is the only example +;;;; anywhere upstream that uses Ray and RayCollision without also loading a +;;;; Model, so it is the only way those two structs get a caller at all. +;;;; +;;;; Picking is the round trip the corpus was missing. core-world-screen.flan +;;;; already runs get-world-to-screen — a point in the scene to a pixel. This +;;;; is the inverse and it is a different shape: a pixel does not name a +;;;; point, it names a *line* through the scene, which is what a Ray is, and +;;;; the answer to "what did I click on" is where that line first meets +;;;; something, which is what a RayCollision is. Two structs the package could +;;;; not describe, for one operation that cannot be written without them. +;;;; +;;;; What was added, all in vendor/raylib/raylib.flan: +;;;; +;;;; - `Ray` — two Vector3s, origin and direction. +;;;; - `RayCollision` — a C `bool`, a float and two Vector3s. This is the +;;;; one of the three new structs a layout check can actually fail: +;;;; `hit` is one byte and `distance` is four, so there are three padding +;;;; bytes between them that a permutation destroys. BoundingBox's two +;;;; Vector3s are interchangeable and nothing would catch swapping them. +;;;; - `BoundingBox` — shared with examples/models-box-collisions.flan. +;;;; - get-screen-to-world-ray and draw-ray, hand-written beside +;;;; get-world-to-screen and the cube draws for the reasons `bindings` +;;;; gives: the first reads the same camera as its inverse, and the second +;;;; is inside a frame. +;;;; +;;;; get-ray-collision-box came free out of the generated half the moment Ray +;;;; and BoundingBox existed, along with the sphere, triangle and quad forms. +;;;; get-ray-collision-mesh is still refused and will stay refused: Mesh owns +;;;; seven arrays and a GPU handle, and describing it is a different job. +;;;; +;;;; raylib 5.5 renamed GetMouseRay to GetScreenToWorldRay and left the old +;;;; name as a #define. A #define is not a symbol, so there is nothing to bind +;;;; it to and nothing lost by not trying. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defvar camera rl/Camera3D) + +(defvar cube-position rl/Vector3) +(defvar cube-size rl/Vector3) + +;; The picking ray, kept between frames because draw-ray draws it every frame +;; whether or not it hit anything — that is how the example shows where the +;; click went. +(defvar ray rl/Ray) +(defvar collision rl/RayCollision) + +;; The same centre/size to min/max conversion as in +;; examples/models-box-collisions.flan. Written out here rather than shared +;; because an example is a single file the reader can follow end to end, and +;; a two-file port for eight expressions would cost more than it saves. +(defn box-around [centre rl/Vector3 size rl/Vector3] rl/BoundingBox + (rl/BoundingBox + {.min (rl/Vector3 {.x (- (.x centre) (/ (.x size) 2.0)) + .y (- (.y centre) (/ (.y size) 2.0)) + .z (- (.z centre) (/ (.z size) 2.0))}) + .max (rl/Vector3 {.x (+ (.x centre) (/ (.x size) 2.0)) + .y (+ (.y centre) (/ (.y size) 2.0)) + .z (+ (.z centre) (/ (.z size) 2.0))})})) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [core] example - 3d picking") + (defer (rl/close-window)) + + (set camera (rl/Camera3D {.position (rl/Vector3 {.x 10.0 .y 10.0 .z 10.0}) + .target (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0}) + .up (rl/Vector3 {.x 0.0 .y 1.0 .z 0.0}) + .fovy 45.0 + .projection :perspective})) + + (set cube-position (rl/Vector3 {.x 0.0 .y 1.0 .z 0.0})) + (set cube-size (rl/Vector3 {.x 2.0 .y 2.0 .z 2.0})) + + ;; Both start zeroed, which is the C's `= { 0 }`. A zero Ray draws as a + ;; degenerate line at the origin and a zero RayCollision has hit false, so + ;; neither needs a "not yet" flag beside it. + (set ray (rl/Ray {.position (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0}) + .direction (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0})})) + (set collision (rl/RayCollision {.hit false .distance 0.0 + .point (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0}) + .normal (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0})})) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update. The first-person controls only run while the cursor is + ;; captured, which is what the right button toggles — otherwise the mouse + ;; could not be used to aim at anything. + (when (rl/cursor-hidden?) (rl/update-camera (addr camera) :first-person)) + + (when (rl/mouse-button-pressed? :right) + (if (rl/cursor-hidden?) (rl/enable-cursor) (rl/disable-cursor))) + + (when (rl/mouse-button-pressed? :left) + (if (not (.hit collision)) + ;; The pixel under the pointer, as a line through the scene, tested + ;; against the cube's bounds. + (do + (set ray (rl/get-screen-to-world-ray (rl/get-mouse-position) camera)) + (set collision + (rl/get-ray-collision-box ray (box-around cube-position cube-size)))) + ;; A second click deselects. Only `hit` is cleared; the ray stays put + ;; and keeps being drawn, as in the C. + (set (.hit collision) false))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/begin-mode-3d camera) + + (if (.hit collision) + (do + (rl/draw-cube cube-position (.x cube-size) (.y cube-size) (.z cube-size) + rl/red) + (rl/draw-cube-wires cube-position (.x cube-size) (.y cube-size) + (.z cube-size) rl/maroon) + ;; A slightly larger wireframe around the selection, which is the + ;; whole visual feedback of the example. + (rl/draw-cube-wires cube-position (+ (.x cube-size) 0.2) + (+ (.y cube-size) 0.2) (+ (.z cube-size) 0.2) + rl/green)) + (do + (rl/draw-cube cube-position (.x cube-size) (.y cube-size) (.z cube-size) + rl/gray) + (rl/draw-cube-wires cube-position (.x cube-size) (.y cube-size) + (.z cube-size) rl/darkgray))) + + ;; raylib draws the ray a thousand units long, so it reads as a line + ;; crossing the scene rather than as a segment with an end. + (rl/draw-ray ray rl/maroon) + (rl/draw-grid 10 1.0) + + (rl/end-mode-3d) + + (rl/draw-text "Try clicking on the box with your mouse!" 240 10 20 + rl/darkgray) + + (when (.hit collision) + (rl/draw-text "BOX SELECTED" + (/ (- screen-width (rl/measure-text "BOX SELECTED" 30)) 2) + (i32 (* (f32 screen-height) 0.1)) 30 rl/green)) + + (rl/draw-text "Right click mouse to toggle camera controls" 10 430 10 + rl/gray) + + (rl/draw-fps 10 10) + + (rl/end-drawing))) diff --git a/examples/models-box-collisions.flan b/examples/models-box-collisions.flan new file mode 100644 index 0000000..74ab36f --- /dev/null +++ b/examples/models-box-collisions.flan @@ -0,0 +1,133 @@ +;;;; raylib [models] example - box collisions +;;;; +;;;; examples/models/models_box_collisions.c. The previous lane's finding was +;;;; that the whole models category is refused by the importer for want of a +;;;; defstruct, and that a models example is therefore mostly a binding +;;;; exercise. That is true of the twenty that load a Model — but not of this +;;;; one, which is why it is here: nothing in it is a Model, a Mesh or a +;;;; Material. It is two cubes, a sphere and one aggregate the package did not +;;;; describe. +;;;; +;;;; That aggregate is BoundingBox, and it is two Vector3s and nothing else — +;;;; no owned pointer, no array, no lifetime. One `defstruct` in +;;;; vendor/raylib/raylib.flan un-refuses four raylib functions at once +;;;; (CheckCollisionBoxes, CheckCollisionBoxSphere, DrawBoundingBox and +;;;; GetRayCollisionBox), and that is the cheapest widening of the 3D surface +;;;; available anywhere in the tree. Ray and RayCollision went in beside it +;;;; for examples/core-3d-picking.flan and for the same reason. +;;;; +;;;; So the answer to "is a models example just a binding exercise" is: the +;;;; ones that need Model are, and this one is the counterexample. What +;;;; separates them is not the category, it is whether the struct owns memory. +;;;; +;;;; What it also exercises, and what needed hand-writing rather than +;;;; generating: draw-cube-v, draw-sphere and draw-sphere-wires. All three +;;;; were in the generated half already, and all three moved to the +;;;; hand-written one here on `bindings`'s own rule — they are inside a frame, +;;;; in an example that ships in examples/. draw-cube-v in particular was +;;;; named there as generated *because nothing called it*; something calls it +;;;; now. +;;;; +;;;; The collision maths is written twice in the C, once per test, building +;;;; the player's box inline both times. It is a function here for the reason +;;;; the eyes example gives: two copies of the same eight expressions cannot +;;;; be checked against each other by reading them. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defvar camera rl/Camera3D) + +(defvar player-position rl/Vector3) +(defvar player-size rl/Vector3) +(defvar player-color rl/Color) + +(defvar enemy-box-pos rl/Vector3) +(defvar enemy-box-size rl/Vector3) +(defvar enemy-sphere-pos rl/Vector3) + +(defconst enemy-sphere-size f32 1.5) + +;; A box centred on `centre` with the given extents. raylib's BoundingBox is +;; min-corner/max-corner, not centre/size, and every collision call in the +;; family takes the corner form — so this is the conversion the C writes out +;; longhand at each of its two call sites. +(defn box-around [centre rl/Vector3 size rl/Vector3] rl/BoundingBox + (rl/BoundingBox + {.min (rl/Vector3 {.x (- (.x centre) (/ (.x size) 2.0)) + .y (- (.y centre) (/ (.y size) 2.0)) + .z (- (.z centre) (/ (.z size) 2.0))}) + .max (rl/Vector3 {.x (+ (.x centre) (/ (.x size) 2.0)) + .y (+ (.y centre) (/ (.y size) 2.0)) + .z (+ (.z centre) (/ (.z size) 2.0))})})) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [models] example - box collisions") + (defer (rl/close-window)) + + ;; The C writes this camera as a brace initialiser with a trailing 0 for the + ;; projection, which is CAMERA_PERSPECTIVE. Named here, because the defenum + ;; exists precisely so that the 0 does not have to be remembered. + (set camera (rl/Camera3D {.position (rl/Vector3 {.x 0.0 .y 10.0 .z 10.0}) + .target (rl/Vector3 {.x 0.0 .y 0.0 .z 0.0}) + .up (rl/Vector3 {.x 0.0 .y 1.0 .z 0.0}) + .fovy 45.0 + .projection :perspective})) + + (set player-position (rl/Vector3 {.x 0.0 .y 1.0 .z 2.0})) + (set player-size (rl/Vector3 {.x 1.0 .y 2.0 .z 1.0})) + (set player-color rl/green) + + (set enemy-box-pos (rl/Vector3 {.x -4.0 .y 1.0 .z 0.0})) + (set enemy-box-size (rl/Vector3 {.x 2.0 .y 2.0 .z 2.0})) + (set enemy-sphere-pos (rl/Vector3 {.x 4.0 .y 0.0 .z 0.0})) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update. The arrow keys move on the XZ plane, and the C's else-if chain + ;; means only one direction applies per frame — diagonal movement is not + ;; possible, deliberately. + (cond + (rl/key-down? :right) (set (.x player-position) (+ (.x player-position) 0.2)) + (rl/key-down? :left) (set (.x player-position) (- (.x player-position) 0.2)) + (rl/key-down? :down) (set (.z player-position) (+ (.z player-position) 0.2)) + (rl/key-down? :up) (set (.z player-position) (- (.z player-position) 0.2))) + + (let [player-box (box-around player-position player-size) + hit (or (rl/check-collision-boxes player-box + (box-around enemy-box-pos enemy-box-size)) + (rl/check-collision-box-sphere player-box enemy-sphere-pos + enemy-sphere-size))] + (set player-color (if hit rl/red rl/green))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/begin-mode-3d camera) + + (rl/draw-cube enemy-box-pos (.x enemy-box-size) (.y enemy-box-size) + (.z enemy-box-size) rl/gray) + (rl/draw-cube-wires enemy-box-pos (.x enemy-box-size) (.y enemy-box-size) + (.z enemy-box-size) rl/darkgray) + + ;; draw-sphere is draw-sphere-ex at 16 rings and 16 slices; the wires form + ;; takes them because the tessellation is only visible in the wireframe. + (rl/draw-sphere enemy-sphere-pos enemy-sphere-size rl/gray) + (rl/draw-sphere-wires enemy-sphere-pos enemy-sphere-size 16 16 rl/darkgray) + + (rl/draw-cube-v player-position player-size player-color) + + (rl/draw-grid 10 1.0) + + (rl/end-mode-3d) + + (rl/draw-text "Move player with arrow keys to collide" 220 40 20 rl/gray) + + (rl/draw-fps 10 10) + + (rl/end-drawing))) diff --git a/examples/shapes-basic-shapes.flan b/examples/shapes-basic-shapes.flan new file mode 100644 index 0000000..1f6c667 --- /dev/null +++ b/examples/shapes-basic-shapes.flan @@ -0,0 +1,102 @@ +;;;; raylib [shapes] example - basic shapes drawing +;;;; +;;;; examples/shapes/shapes_basic_shapes.c. Ported first of the shapes batch +;;;; because it is the widest single file in the category: six draw families +;;;; the corpus had never called — draw-circle-gradient, the two rectangle +;;;; gradients, draw-triangle and draw-triangle-lines, and all three of the +;;;; poly draws — in one frame, beside the four the core examples already +;;;; exercise. Every one of them came out of the generated half of the +;;;; bindings and none needed a new line anywhere; that is the result worth +;;;; recording, because the whole point of a committed generated.flan is that +;;;; a build with no FLAN_RAYLIB_H set can draw with all of it. +;;;; +;;;; What it is actually a test of. The gradient calls are the first thing in +;;;; the corpus to pass *two* Colors in one call, and draw-triangle is the +;;;; first to pass three Vector2s. A struct argument crosses the FFI by +;;;; pointer into a generated shim (vendor/raylib/raylib.flan's header note), +;;;; so the arity of that copying is what a call with several small structs in +;;;; a row puts under load. Nothing here can be asserted headless — every line +;;;; needs a GL context — so the check is the link and the screen, which is +;;;; what the Shapes comment in raylib.flan already says about this family. +;;;; +;;;; The one deliberate difference from the C: the C writes `screenWidth/4*2` +;;;; and `screenWidth/4.0f*3.0f` for the same column and gets 400 and 600 out +;;;; of integer and float division respectively. Both are written here as the +;;;; arithmetic they are, in the type the call wants, rather than copied with +;;;; a cast on the end — `(/ screen-width 5)` is an i32 division for the i32 +;;;; parameters of draw-circle, and the poly centre is built from f32 +;;;; literals because a Vector2 holds f32. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +;; The three columns the C lays the shapes out in. The middle one is +;; screenWidth/4*2 and the right one screenWidth/4*3, which is 400 and 600. +(defconst col-left 160) ; screen-width / 5 +(defconst col-mid 400) +(defconst col-right 600) + +(defvar rotation f32) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [shapes] example - basic shapes drawing") + (defer (rl/close-window)) + + (set rotation 0.0) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update. The polygons spin; nothing else moves. + (set rotation (+ rotation 0.2)) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/draw-text "some basic shapes available on raylib" 20 20 20 rl/darkgray) + + ;; Circles. The gradient one takes an inner and an outer colour and is the + ;; first call in the corpus to pass two Colors at once. + (rl/draw-circle col-left 120 35.0 rl/darkblue) + (rl/draw-circle-gradient col-left 220 60.0 rl/green rl/skyblue) + (rl/draw-circle-lines col-left 340 80.0 rl/darkblue) + + ;; Rectangles. draw-rectangle-gradient-h runs the colour left to right; + ;; the -v form runs it top to bottom and the -ex form takes all four + ;; corners. The C uses the horizontal one here. + (rl/draw-rectangle (- col-mid 60) 100 120 60 rl/red) + (rl/draw-rectangle-gradient-h (- col-mid 90) 170 180 130 rl/maroon rl/gold) + ;; raylib draws this with quads internally rather than with lines, which + ;; is why its thickness does not follow the line width anywhere. + (rl/draw-rectangle-lines (- col-mid 40) 320 80 60 rl/orange) + + ;; Triangles. raylib wants the three vertices in counter-clockwise order + ;; and draws nothing at all for a clockwise one, so the order here is not + ;; cosmetic. + (rl/draw-triangle (rl/Vector2 {.x 600.0 .y 80.0}) + (rl/Vector2 {.x 540.0 .y 150.0}) + (rl/Vector2 {.x 660.0 .y 150.0}) + rl/violet) + + (rl/draw-triangle-lines (rl/Vector2 {.x 600.0 .y 160.0}) + (rl/Vector2 {.x 580.0 .y 230.0}) + (rl/Vector2 {.x 620.0 .y 230.0}) + rl/darkblue) + + ;; Polygons, all three at the same centre and the same rotation, at three + ;; radii, so the filled hexagon sits inside the two outlines. + (let [centre (rl/Vector2 {.x (f32 col-right) .y 330.0})] + (rl/draw-poly centre 6 80.0 rotation rl/brown) + (rl/draw-poly-lines centre 6 90.0 rotation rl/brown) + (rl/draw-poly-lines-ex centre 6 85.0 rotation 6.0 rl/beige)) + + ;; The C draws every LINES-based shape together so raylib can batch them + ;; into one pass. This last line is part of that comment and not an + ;; afterthought, so it stays where the C has it. + (rl/draw-line 18 42 (- screen-width 18) 42 rl/black) + + (rl/end-drawing))) diff --git a/examples/shapes-collision-area.flan b/examples/shapes-collision-area.flan new file mode 100644 index 0000000..4fdf73d --- /dev/null +++ b/examples/shapes-collision-area.flan @@ -0,0 +1,129 @@ +;;;; raylib [shapes] example - collision area +;;;; +;;;; examples/shapes/shapes_collision_area.c. Picked for one call: +;;;; get-collision-rec, which is the only binding in the package that takes +;;;; two Rectangles and answers a third. Everything else in the corpus that +;;;; crosses a struct either passes one in (Camera2D, Color) or gets one back +;;;; (get-mouse-position, fade) — this is the first per-frame call doing both +;;;; at once, and the returned struct comes back through the shim's `out` +;;;; pointer rather than in registers, which is a different lowering again. +;;;; +;;;; It is also the only headless-adjacent thing in the file: both +;;;; collision-recs? and get-collision-rec are pure arithmetic over their +;;;; arguments and need no window at all. The acceptance table already asserts +;;;; the pair; what this adds is the same two calls on a frame path with one +;;;; rectangle driven by the mouse, where a permuted Rectangle would put the +;;;; green overlap patch somewhere the two boxes are not. +;;;; +;;;; Both TextFormats go through examples/digits.flan the way the core ports +;;;; do it: draw the literal part, then the number at x plus its width. + +(import rl "vendor:raylib") +(import d "digits.flan") + +(defconst screen-width 800) +(defconst screen-height 450) + +;; The top strip the collision message is drawn into, and the floor box B is +;; not allowed above. +(defconst screen-upper-limit 40) + +(defvar box-a rl/Rectangle) ; moves by itself, bounces off the sides +(defvar box-b rl/Rectangle) ; follows the mouse +(defvar box-collision rl/Rectangle) ; their overlap, valid only while touching +(defvar box-a-speed-x i32) +(defvar paused bool) +(defvar collision bool) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [shapes] example - collision area") + (defer (rl/close-window)) + + (set box-a (rl/Rectangle {.x 10.0 + .y (- (/ (f32 screen-height) 2.0) 50.0) + .width 200.0 .height 100.0})) + (set box-a-speed-x 4) + + (set box-b (rl/Rectangle {.x (- (/ (f32 screen-width) 2.0) 30.0) + .y (- (/ (f32 screen-height) 2.0) 30.0) + .width 60.0 .height 60.0})) + + ;; A fresh Rectangle is four zeroes, which is the C's `= { 0 }`. It is never + ;; drawn before the first collision sets it. + (set box-collision (rl/Rectangle {.x 0.0 .y 0.0 .width 0.0 .height 0.0})) + + (set paused false) + (set collision false) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update + (when (not paused) + (set (.x box-a) (+ (.x box-a) (f32 box-a-speed-x)))) + + ;; Bounce at either edge. The test is on the far edge going right and on + ;; the near one going left, so the box reverses on whichever it reaches. + (when (or (>= (+ (.x box-a) (.width box-a)) (f32 (rl/get-screen-width))) + (<= (.x box-a) 0.0)) + (set box-a-speed-x (* box-a-speed-x -1))) + + ;; Box B is centred on the mouse and then clamped back inside the play + ;; area — which is the window minus the top strip. + (set (.x box-b) (- (f32 (rl/get-mouse-x)) (/ (.width box-b) 2.0))) + (set (.y box-b) (- (f32 (rl/get-mouse-y)) (/ (.height box-b) 2.0))) + + (if (>= (+ (.x box-b) (.width box-b)) (f32 (rl/get-screen-width))) + (set (.x box-b) (- (f32 (rl/get-screen-width)) (.width box-b))) + (when (<= (.x box-b) 0.0) (set (.x box-b) 0.0))) + + (if (>= (+ (.y box-b) (.height box-b)) (f32 (rl/get-screen-height))) + (set (.y box-b) (- (f32 (rl/get-screen-height)) (.height box-b))) + (when (<= (.y box-b) (f32 screen-upper-limit)) + (set (.y box-b) (f32 screen-upper-limit)))) + + (set collision (rl/collision-recs? box-a box-b)) + + ;; Only meaningful while they touch: raylib answers a zero rectangle for + ;; two boxes that do not, and the C leaves the previous one in place + ;; rather than reading that back. This follows it. + (when collision (set box-collision (rl/get-collision-rec box-a box-b))) + + (when (rl/key-pressed? :space) (set paused (not paused))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/draw-rectangle 0 0 screen-width screen-upper-limit + (if collision rl/red rl/black)) + + (rl/draw-rectangle-rec box-a rl/gold) + (rl/draw-rectangle-rec box-b rl/blue) + + (when collision + ;; The overlap itself, drawn over both boxes. This patch landing + ;; anywhere other than where the gold and the blue cross is what a + ;; permuted Rectangle would look like. + (rl/draw-rectangle-rec box-collision rl/lime) + + (rl/draw-text "COLLISION!" + (- (/ (rl/get-screen-width) 2) + (/ (rl/measure-text "COLLISION!" 20) 2)) + (- (/ screen-upper-limit 2) 10) 20 rl/black) + + ;; The C's TextFormat("Collision Area: %i", ...). Both dimensions are + ;; truncated to int before multiplying, as the C's two casts do. + (let [x (- (/ (rl/get-screen-width) 2) 100) + y (+ screen-upper-limit 10)] + (set x (+ x (d/draw-piece "Collision Area: " x y 20 rl/black))) + (d/draw-int (* (i32 (.width box-collision)) (i32 (.height box-collision))) + x y 20 rl/black))) + + (rl/draw-text "Press SPACE to PAUSE/RESUME" 20 (- screen-height 35) 20 + rl/lightgray) + + (rl/draw-fps 10 10) + + (rl/end-drawing))) diff --git a/examples/shapes-following-eyes.flan b/examples/shapes-following-eyes.flan new file mode 100644 index 0000000..d30c9d6 --- /dev/null +++ b/examples/shapes-following-eyes.flan @@ -0,0 +1,103 @@ +;;;; raylib [shapes] example - following eyes +;;;; +;;;; examples/shapes/shapes_following_eyes.c. Ported for the thing it needs +;;;; that raylib does not supply: the whole update is vector arithmetic — +;;;; subtract two points, take the angle, walk back out along it — and every +;;;; one of those steps is raymath. raymath is `static inline` in +;;;; raymath.h, so Vector2Subtract and Vector2Angle have no symbol in +;;;; libraylib at all and there is nothing for declare-c to bind. NEXT.md +;;;; names this as one of the three open gaps. +;;;; +;;;; What that costs here is nothing, because the C does not use raymath +;;;; either — it writes the four subtractions out and calls atan2f, cosf and +;;;; sinf from libm, and Flan's prelude already declares all three as +;;;; atan2-f32, cos-f32 and sin-f32. So this file is the *measurement* of the +;;;; gap rather than a workaround for it: an example whose every line is +;;;; vector maths, written without a vector library, in the same shape the C +;;;; has. It reads fine. A Vector2Add would have saved two lines in the whole +;;;; file. +;;;; +;;;; The raylib call it does exercise is collision-point-circle?, which no +;;;; ported example had called, on a frame path, with the point coming +;;;; straight out of get-mouse-position — one struct out of raylib and back +;;;; into it untouched. +;;;; +;;;; The eye geometry, since the C hides it in a subtraction: the iris is +;;;; pinned inside a circle of (sclera - iris) radius about the sclera's +;;;; centre, so the iris disc is tangent to the sclera's edge at the extreme +;;;; rather than hanging over it. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defconst sclera-radius f32 80.0) +(defconst iris-radius f32 24.0) + +(defvar sclera-left rl/Vector2) +(defvar sclera-right rl/Vector2) +(defvar iris-left rl/Vector2) +(defvar iris-right rl/Vector2) + +;; One eye's pupil, given where the mouse is and where the eye is. Answers the +;; mouse position unchanged while it is inside the eye, and the point on the +;; limit circle in that direction when it is outside. +;; +;; The C repeats this block twice with different variables; it is one function +;; here because the two copies are identical and a difference between them +;; would be invisible. +(defn track [mouse rl/Vector2 centre rl/Vector2] rl/Vector2 + (let [limit (- sclera-radius iris-radius)] + (if (rl/collision-point-circle? mouse centre limit) + mouse + ;; Outside: the direction from the eye to the mouse, and then `limit` + ;; units back out along it. atan2 then cos/sin rather than a normalise, + ;; because that is what the C does and because it needs no guard for a + ;; zero-length vector — atan2(0,0) is 0 and the pupil sits at the right + ;; of the eye, which is unreachable anyway since (0,0) is inside. + (let [dx (- (.x mouse) (.x centre)) + dy (- (.y mouse) (.y centre)) + angle (atan2-f32 dy dx)] + (rl/Vector2 {.x (+ (.x centre) (* limit (cos-f32 angle))) + .y (+ (.y centre) (* limit (sin-f32 angle)))}))))) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [shapes] example - following eyes") + (defer (rl/close-window)) + + ;; The C reads these off get-screen-width/get-screen-height after the window + ;; is open rather than off the constants, and so does this: on a high-DPI + ;; display the two can differ. + (set sclera-left (rl/Vector2 {.x (- (/ (f32 (rl/get-screen-width)) 2.0) 100.0) + .y (/ (f32 (rl/get-screen-height)) 2.0)})) + (set sclera-right (rl/Vector2 {.x (+ (/ (f32 (rl/get-screen-width)) 2.0) 100.0) + .y (/ (f32 (rl/get-screen-height)) 2.0)})) + (set iris-left sclera-left) + (set iris-right sclera-right) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update + (let [mouse (rl/get-mouse-position)] + (set iris-left (track mouse sclera-left)) + (set iris-right (track mouse sclera-right))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + ;; White of the eye, iris, pupil — in that order, each over the last. + (rl/draw-circle-v sclera-left sclera-radius rl/lightgray) + (rl/draw-circle-v iris-left iris-radius rl/brown) + (rl/draw-circle-v iris-left 10.0 rl/black) + + (rl/draw-circle-v sclera-right sclera-radius rl/lightgray) + (rl/draw-circle-v iris-right iris-radius rl/darkgreen) + (rl/draw-circle-v iris-right 10.0 rl/black) + + (rl/draw-fps 10 10) + + (rl/end-drawing))) diff --git a/examples/text-input-box.flan b/examples/text-input-box.flan new file mode 100644 index 0000000..8a4cb91 --- /dev/null +++ b/examples/text-input-box.flan @@ -0,0 +1,140 @@ +;;;; raylib [text] example - input box +;;;; +;;;; examples/text/text_input_box.c. Two things in this file exist nowhere +;;;; else in the corpus. +;;;; +;;;; The first is get-char-pressed. Everything ported so far reads input as +;;;; state — key-down?, key-pressed?, the mouse position — and this is the +;;;; only example that drains a *queue*: raylib buffers the characters the +;;;; platform produced since the last frame, already through the keyboard +;;;; layout and the dead keys, and hands them back one at a time until it +;;;; answers 0. The loop that empties it is the point of the example, and a +;;;; program that read the queue once per frame instead would silently drop +;;;; the second character of a fast pair. It is a plain i32 out of the +;;;; generated bindings; nothing needed adding for it. +;;;; +;;;; The second is set-mouse-cursor, which needed a new defenum. raylib's +;;;; header says `int cursor` and means one of eleven MOUSE_CURSOR_ values, so +;;;; the Flan face is `MouseCursor` — hand-written in raylib.flan beside the +;;;; other cursor calls, excluded from the generated half, and mapped in +;;;; `bindings` so the eleven members are checked against the header. See the +;;;; comment there: this call is made on every frame off a hover test, and the +;;;; failure an i32 would allow is not a crash but a pointer in the wrong +;;;; shape, which nothing reports. +;;;; +;;;; The text buffer, and what it says about strings. The C keeps a +;;;; `char name[MAX_INPUT_CHARS + 1]` and maintains the NUL itself; here it is +;;;; a `[9 u8]` with no terminator, and every use is `(string (slice name 0 +;;;; letter-count))`. A Flan string is a pointer and a length, and the shim +;;;; that calls DrawText copies it and NUL-terminates the copy +;;;; (lib/shim.ml) — so the extra byte the C needs has no counterpart here and +;;;; the buffer is exactly as long as the characters it can hold. The two +;;;; draws and the measure all take the same slice, so they cannot disagree +;;;; about where the text ends. +;;;; +;;;; Dropped from the C: its IsAnyKeyPressed helper, which is defined at the +;;;; bottom of the file and called from nowhere. + +(import rl "vendor:raylib") +(import d "digits.flan") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defconst max-input-chars 9) + +;; No +1: see the header comment. There is no NUL to leave room for. +(defvar name [9 u8]) +(defvar letter-count i32) + +(defvar text-box rl/Rectangle) +(defvar mouse-on-text bool) +(defvar frames-counter i32) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [text] example - input box") + (defer (rl/close-window)) + + (set name (array max-input-chars u8)) + (set letter-count 0) + + (set text-box (rl/Rectangle {.x (- (/ (f32 screen-width) 2.0) 100.0) + .y 180.0 .width 225.0 .height 50.0})) + (set mouse-on-text false) + (set frames-counter 0) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update + (set mouse-on-text + (rl/collision-point-rec? (rl/get-mouse-position) text-box)) + + (if mouse-on-text + (do + (rl/set-mouse-cursor :ibeam) + + ;; Drain the character queue. raylib answers 0 when it is empty, and + ;; more than one character can arrive in a single frame — holding a + ;; key with the platform's repeat on is the ordinary way that happens. + (let [key (rl/get-char-pressed)] + (while (> key 0) + ;; 32..125 is the printable ASCII range the C accepts. Anything + ;; outside it — an accented letter, a control character — is + ;; dropped rather than stored, because the buffer is bytes and a + ;; codepoint above 127 would need more than one of them. + (when (and (>= key 32) (<= key 125) (< letter-count max-input-chars)) + (set (at name letter-count) (u8 key)) + (set letter-count (+ letter-count 1))) + (set key (rl/get-char-pressed)))) + + (when (rl/key-pressed? :backspace) + (set letter-count (- letter-count 1)) + (when (< letter-count 0) (set letter-count 0)))) + (rl/set-mouse-cursor :default)) + + ;; The blink phase only runs while the box has focus, so the underscore is + ;; always visible on the frame the pointer arrives. + (if mouse-on-text + (set frames-counter (+ frames-counter 1)) + (set frames-counter 0)) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/draw-text "PLACE MOUSE OVER INPUT BOX!" 240 140 20 rl/gray) + + (rl/draw-rectangle-rec text-box rl/lightgray) + (rl/draw-rectangle-lines (i32 (.x text-box)) (i32 (.y text-box)) + (i32 (.width text-box)) (i32 (.height text-box)) + (if mouse-on-text rl/red rl/darkgray)) + + (let [typed (string (slice name 0 letter-count))] + (rl/draw-text typed (+ (i32 (.x text-box)) 5) (+ (i32 (.y text-box)) 8) + 40 rl/maroon) + + ;; The C's TextFormat("INPUT CHARS: %i/%i", ...), reassembled out of + ;; examples/digits.flan the way the other ports do it. `typed` is a view + ;; of `name` and not of the runtime's shared format buffer, so it + ;; survives the two numbers being formatted — which a value from + ;; i64->bytes would not. + (let [x 315] + (set x (+ x (d/draw-piece "INPUT CHARS: " x 250 20 rl/darkgray))) + (set x (+ x (d/draw-int letter-count x 250 20 rl/darkgray))) + (set x (+ x (d/draw-piece "/" x 250 20 rl/darkgray))) + (d/draw-int max-input-chars x 250 20 rl/darkgray)) + + (when mouse-on-text + (if (< letter-count max-input-chars) + ;; Twenty frames on, twenty frames off, at the pen position after + ;; whatever has been typed. + (when (= (% (/ frames-counter 20) 2) 0) + (rl/draw-text "_" + (+ (i32 (.x text-box)) 8 (rl/measure-text typed 40)) + (+ (i32 (.y text-box)) 12) 40 rl/maroon)) + (rl/draw-text "Press BACKSPACE to delete chars..." 230 300 20 + rl/gray)))) + + (rl/end-drawing))) diff --git a/examples/text-writing-anim.flan b/examples/text-writing-anim.flan new file mode 100644 index 0000000..3d67c54 --- /dev/null +++ b/examples/text-writing-anim.flan @@ -0,0 +1,76 @@ +;;;; raylib [text] example - text writing anim +;;;; +;;;; examples/text/text_writing_anim.c. Sixty lines of C whose whole substance +;;;; is one call this package cannot bind: +;;;; +;;;; DrawText(TextSubtext(message, 0, framesCounter/10), ...) +;;;; +;;;; TextSubtext is in raylib.h and is not in the bindings, on the rule +;;;; raylib.flan states for the whole Text* family: it answers a `char *` into +;;;; a rotating static buffer, and declare-c refuses a returned pointer to +;;;; memory the caller does not own. There is no missing line to add — the +;;;; binding would be wrong at any signature. +;;;; +;;;; And it does not matter, because Flan has the operation as a primitive. +;;;; `(slice a lo hi)` takes a view of an array, `(string b)` reinterprets the +;;;; bytes as a string at no cost, and `(string (slice message 0 n))` is +;;;; TextSubtext with the static buffer removed — no copy, no shared state, no +;;;; rotation to run out of. Porting the example is therefore how the gap gets +;;;; *closed* rather than reported: the C's workaround for not having slices +;;;; is the thing Flan did not need. +;;;; +;;;; The one place they differ, and it is why the clamp below is here rather +;;;; than in the C: TextSubtext clips its length to the string, so the C can +;;;; pass a counter that runs past the end for ever and see nothing happen. +;;;; `slice` does not clip — an out-of-range bound is an error, and a bound +;;;; computed at run time is checked at run time — so the length has to be +;;;; brought inside the string before the call. That is a better failure than +;;;; the C's, and it costs one `min`. +;;;; +;;;; The message is a `[u8]` and not a `string` because `slice` takes an array +;;;; or a slice; `(bytes "…")` is the bridge in the other direction from +;;;; `(string …)` and costs nothing either. The embedded newline is written as +;;;; an escape, and raylib's draw-text breaks the line on it. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defconst message + "This sample illustrates a text writing\nanimation effect! Check it out! ;)") + +(defvar frames-counter i32) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [text] example - text writing anim") + (defer (rl/close-window)) + + (set frames-counter 0) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update. Holding space runs the counter eight times faster; enter starts + ;; it over. + (if (rl/key-down? :space) + (set frames-counter (+ frames-counter 8)) + (set frames-counter (+ frames-counter 1))) + + (when (rl/key-pressed? :enter) (set frames-counter 0)) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + ;; One character every ten frames. The clamp is the whole difference from + ;; the C — see the header comment. + (let [b (bytes message) + n (min (i32 (len b)) (/ frames-counter 10))] + (rl/draw-text (string (slice b 0 n)) 210 160 20 rl/maroon)) + + (rl/draw-text "PRESS [ENTER] to RESTART!" 240 260 20 rl/lightgray) + (rl/draw-text "HOLD [SPACE] to SPEED UP!" 239 300 20 rl/lightgray) + + (rl/end-drawing))) diff --git a/examples/textures-fog-of-war.flan b/examples/textures-fog-of-war.flan new file mode 100644 index 0000000..d17879f --- /dev/null +++ b/examples/textures-fog-of-war.flan @@ -0,0 +1,197 @@ +;;;; raylib [textures] example - fog of war +;;;; +;;;; examples/textures/textures_fog_of_war.c. Picked because it is the only +;;;; example in the whole upstream tree where a *texture filter* is the point +;;;; rather than a detail. The fog is drawn into a render texture one pixel +;;;; per tile — 25 by 15 — and then stretched to 800x450 on the way to the +;;;; screen, and the smooth edge between seen and unseen is entirely the +;;;; bilinear sampler doing the interpolation. With the default :point filter +;;;; the same program draws 32-pixel squares. +;;;; +;;;; That is what needed adding: `TextureFilter`, a new defenum in +;;;; vendor/raylib/raylib.flan, with set-texture-filter moved from the +;;;; generated half to the hand-written one and mapped in `bindings` so its +;;;; six members are checked against raylib.h. The header says `int filter` +;;;; and there is nothing in an `int` to say that 1 is the interesting value; +;;;; `:bilinear` says it. +;;;; +;;;; The three other things it exercises, none of which needed a line: +;;;; +;;;; - A render texture used as a *scratch surface* rather than as a +;;;; post-processing pass. core-scissor-test clipped the real framebuffer; +;;;; this draws a whole second frame into a 25x15 target and then samples +;;;; it. begin-texture-mode/end-texture-mode were already bound. +;;;; - draw-texture-pro with a NEGATIVE source height. A render texture's +;;;; rows come out of GL bottom-up, so every program that samples one has +;;;; to flip it, and raylib's convention for that is a source rectangle +;;;; with a negative height rather than a separate flag. Nothing in the +;;;; corpus had passed one. A Rectangle whose `height` field had been +;;;; permuted with `width` would draw the fog mirrored and the wrong way +;;;; up at once. +;;;; - clear-background with `blank` — alpha 0 — inside a texture mode, so +;;;; the untouched parts of the fog target are transparent and the map +;;;; shows through. +;;;; +;;;; The C's Map struct with its two calloc'd `unsigned char *` is two `[375 +;;;; u8]` globals here. The dimensions are compile-time constants in the C +;;;; too (the #defines and the two assignments right after), so nothing is +;;;; lost by fixing them, and a global cannot hold a Vec in any case +;;;; (PORTING.md §3). 375 is 25*15, written out because Flan's array length +;;;; must be a literal. + +(import rl "vendor:raylib") +(import d "digits.flan") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defconst map-tile-size 32) +(defconst player-size 16) + +;; How far the player sees, in tiles. The C's loop runs from -this to +this +;; exclusive, so the lit patch is 2*this tiles across and not 2*this+1 — an +;; asymmetry in the original that is kept rather than tidied, because tidying +;; it would change the picture. +(defconst player-tile-visibility 2) + +(defconst tiles-x 25) +(defconst tiles-y 15) + +;; 0 or 1, picked once: which of the two blues a tile is drawn in. +(defvar tile-ids [375 u8]) + +;; 0 = never seen (solid black), 1 = visible now (no fog), 2 = seen before +;; (mostly black). The three-way state is why this is a byte per tile and not +;; a bit. +(defvar tile-fog [375 u8]) + +(defvar player-position rl/Vector2) +(defvar player-tile-x i32) +(defvar player-tile-y i32) + +(defvar fog-of-war rl/RenderTexture2D) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [textures] example - fog of war") + (defer (rl/close-window)) + + (set tile-ids (array 375 u8)) + (set tile-fog (array 375 u8)) + + (dotimes [i (* tiles-x tiles-y)] + (set (at tile-ids i) (u8 (rl/get-random-value 0 1)))) + + (set player-position (rl/Vector2 {.x 180.0 .y 130.0})) + (set player-tile-x 0) + (set player-tile-y 0) + + ;; One texel per tile. The stretch to full size on draw is where the + ;; smoothing happens, which is why the target is this small on purpose. + (set fog-of-war (rl/load-render-texture tiles-x tiles-y)) + (defer (rl/unload-render-texture fog-of-war)) + + (rl/set-texture-filter (.texture fog-of-war) :bilinear) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update + (when (rl/key-down? :right) (set (.x player-position) (+ (.x player-position) 5.0))) + (when (rl/key-down? :left) (set (.x player-position) (- (.x player-position) 5.0))) + (when (rl/key-down? :down) (set (.y player-position) (+ (.y player-position) 5.0))) + (when (rl/key-down? :up) (set (.y player-position) (- (.y player-position) 5.0))) + + ;; Keep the player inside the tilemap. The far edge is measured against + ;; the player's far side, which is why player-size is subtracted. + (let [max-x (f32 (- (* tiles-x map-tile-size) player-size)) + max-y (f32 (- (* tiles-y map-tile-size) player-size))] + (set (.x player-position) (clamp (.x player-position) 0.0 max-x)) + (set (.y player-position) (clamp (.y player-position) 0.0 max-y))) + + ;; Everything lit on the previous frame drops to "seen before". The lit + ;; tiles are then set back to 1 below, so a tile still in view never + ;; spends a frame dimmed. + (dotimes [i (* tiles-x tiles-y)] + (when (= (at tile-fog i) 1) (set (at tile-fog i) 2))) + + ;; Which tile the player's centre is standing on. + (set player-tile-x + (i32 (/ (+ (.x player-position) (f32 (/ map-tile-size 2))) + (f32 map-tile-size)))) + (set player-tile-y + (i32 (/ (+ (.y player-position) (f32 (/ map-tile-size 2))) + (f32 map-tile-size)))) + + ;; Light the square around the player, skipping anything off the map. + ;; Without that test this reads and writes outside the array, which in the + ;; C is undefined and here is a bounds trap — the same bug, reported. + (let [y (- player-tile-y player-tile-visibility)] + (while (< y (+ player-tile-y player-tile-visibility)) + (let [x (- player-tile-x player-tile-visibility)] + (while (< x (+ player-tile-x player-tile-visibility)) + (when (and (>= x 0) (< x tiles-x) (>= y 0) (< y tiles-y)) + (set (at tile-fog (+ (* y tiles-x) x)) 1)) + (set x (+ x 1)))) + (set y (+ y 1)))) + + ;; Draw the fog into its own little target first, at one pixel per tile. + ;; blank is alpha 0, so a tile that is neither unseen nor remembered + ;; leaves nothing behind and the map below shows through unmodified. + (rl/begin-texture-mode fog-of-war) + (rl/clear-background rl/blank) + (dotimes [y tiles-y] + (dotimes [x tiles-x] + ;; A tile in view (1) draws nothing at all and stays transparent. + (let [f (at tile-fog (+ (* y tiles-x) x))] + (when (!= f 1) + (rl/draw-rectangle x y 1 1 + (if (= f 0) rl/black (rl/fade rl/black 0.8))))))) + (rl/end-texture-mode) + + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + ;; The map itself, in full size. + (dotimes [y tiles-y] + (dotimes [x tiles-x] + (rl/draw-rectangle (* x map-tile-size) (* y map-tile-size) + map-tile-size map-tile-size + (if (= (at tile-ids (+ (* y tiles-x) x)) 0) + rl/blue + (rl/fade rl/blue 0.9))) + (rl/draw-rectangle-lines (* x map-tile-size) (* y map-tile-size) + map-tile-size map-tile-size + (rl/fade rl/darkblue 0.5)))) + + (rl/draw-rectangle-v player-position + (rl/Vector2 {.x (f32 player-size) .y (f32 player-size)}) + rl/red) + + ;; The fog, stretched over the whole map. The negative source height is + ;; the flip — see the header comment. + (rl/draw-texture-pro + (.texture fog-of-war) + (rl/Rectangle {.x 0.0 .y 0.0 + .width (f32 (.width (.texture fog-of-war))) + .height (- 0.0 (f32 (.height (.texture fog-of-war))))}) + (rl/Rectangle {.x 0.0 .y 0.0 + .width (f32 (* tiles-x map-tile-size)) + .height (f32 (* tiles-y map-tile-size))}) + (rl/Vector2 {.x 0.0 .y 0.0}) + 0.0 + rl/white) + + ;; The C's TextFormat("Current tile: [%i,%i]", ...). Each number is drawn + ;; before the next is formatted, which examples/digits.flan requires: + ;; both share one static buffer in the runtime. + (let [x 10] + (set x (+ x (d/draw-piece "Current tile: [" x 10 20 rl/raywhite))) + (set x (+ x (d/draw-int player-tile-x x 10 20 rl/raywhite))) + (set x (+ x (d/draw-piece "," x 10 20 rl/raywhite))) + (set x (+ x (d/draw-int player-tile-y x 10 20 rl/raywhite))) + (d/draw-piece "]" x 10 20 rl/raywhite)) + + (rl/draw-text "ARROW KEYS to move" 10 (- screen-height 25) 20 rl/raywhite) + + (rl/end-drawing))) diff --git a/examples/textures-image-generation.flan b/examples/textures-image-generation.flan new file mode 100644 index 0000000..af9616e --- /dev/null +++ b/examples/textures-image-generation.flan @@ -0,0 +1,130 @@ +;;;; raylib [textures] example - procedural images generation +;;;; +;;;; examples/textures/textures_image_generation.c. The strongest single pick +;;;; in the textures category and the reason is arithmetic: eight of the nine +;;;; textures come from a Gen* call that no program in this tree had ever +;;;; made, and none of the nine needs a file on disk. Every other textures +;;;; example loads a .png out of its resources directory; this one builds all +;;;; of its pixels. +;;;; +;;;; What it puts under load that nothing else does. An Image is the one +;;;; struct in raylib.flan that carries a pointer to memory raylib owns — +;;;; `data (Ptr u8)` — and it is returned by value, so every one of these nine +;;;; calls hands back a 24-byte aggregate through the shim's out-pointer with +;;;; a live heap block inside it. The corpus had crossed an Image before +;;;; (image-from-image has a headless acceptance case) but never nine in a row +;;;; and never on the load-then-upload-then-free path a real program uses: +;;;; gen, load-texture-from-image to get it onto the GPU, unload-image to give +;;;; the CPU copy back. Getting that order wrong is a leak rather than a +;;;; crash, which is exactly the sort of thing a ported example is for. +;;;; +;;;; Nothing needed adding. All nine generators and load-texture-from-image +;;;; came out of the generated half of the bindings; the only parameter that +;;;; looks like it wants an enum is gen-image-gradient-linear's `direction`, +;;;; which is an angle in degrees and not a flag, so an i32 is its true face. +;;;; +;;;; The C's `switch (currentTexture)` is a `cond` here. Flan has no switch +;;;; and the chain reads the same; the C's `default: break` is the `else` +;;;; branch (`:else`), unreachable because the index is taken modulo the count. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +;; Nine and not eight: the linear gradient appears three times, at three +;; angles, because a vertical, a horizontal and a diagonal gradient are the +;; same generator with a different `direction`. +(defconst num-textures 9) + +(defvar textures [9 rl/Texture2D]) +(defvar current-texture i32) + +;; Generate on the CPU, upload, drop the pixels. The texture holds a GL name +;; and nothing of the Image, so the CPU copy can go as soon as the upload is +;; done — which is why the C frees all nine in a block immediately after the +;; nine uploads and this does it one at a time. Holding all nine 800x450 RGBA +;; images at once would be 14 MB for no reason. +;; +;; A top-level defn and not a local closure: Flan's `fn` takes its types from +;; the position it is written in, so it needs a parameter of (Fn [T ...] R) to +;; land in, and a `let` binding is not one. +(defn upload [img rl/Image] rl/Texture2D + (let [t (rl/load-texture-from-image img)] + (rl/unload-image img) + t)) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [textures] example - procedural images generation") + (defer (rl/close-window)) + + (set textures (array num-textures rl/Texture2D)) + + ;; 0 degrees runs the gradient top to bottom, 90 left to right, 45 corner + ;; to corner. + (set (at textures 0) + (upload (rl/gen-image-gradient-linear screen-width screen-height 0 + rl/red rl/blue))) + (set (at textures 1) + (upload (rl/gen-image-gradient-linear screen-width screen-height 90 + rl/red rl/blue))) + (set (at textures 2) + (upload (rl/gen-image-gradient-linear screen-width screen-height 45 + rl/red rl/blue))) + ;; density 0 means the falloff reaches the edge of the image. + (set (at textures 3) + (upload (rl/gen-image-gradient-radial screen-width screen-height 0.0 + rl/white rl/black))) + (set (at textures 4) + (upload (rl/gen-image-gradient-square screen-width screen-height 0.0 + rl/white rl/black))) + ;; 32 checks each way, so each square is 25 by 14 pixels. + (set (at textures 5) + (upload (rl/gen-image-checked screen-width screen-height 32 32 + rl/red rl/blue))) + ;; `factor` is the fraction of pixels that come out white. + (set (at textures 6) + (upload (rl/gen-image-white-noise screen-width screen-height 0.5))) + (set (at textures 7) + (upload (rl/gen-image-perlin-noise screen-width screen-height 50 50 4.0))) + ;; `tile-size` is the cell spacing, in pixels. + (set (at textures 8) + (upload (rl/gen-image-cellular screen-width screen-height 32))) + + (defer (dotimes [i num-textures] (rl/unload-texture (at textures i)))) + + (set current-texture 0) + + (rl/set-target-fps 60) + + (until (rl/window-should-close?) + ;; Update + (when (or (rl/mouse-button-pressed? :left) (rl/key-pressed? :right)) + (set current-texture (% (+ current-texture 1) num-textures))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + (rl/draw-texture (at textures current-texture) 0 0 rl/white) + + (rl/draw-rectangle 30 400 325 30 (rl/fade rl/skyblue 0.5)) + (rl/draw-rectangle-lines 30 400 325 30 (rl/fade rl/white 0.5)) + (rl/draw-text "MOUSE LEFT BUTTON to CYCLE PROCEDURAL TEXTURES" + 40 410 10 rl/white) + + ;; The C's switch. Each label is positioned so its right edge lands in the + ;; same place, which is why the x differs per line. + (cond + (= current-texture 0) (rl/draw-text "VERTICAL GRADIENT" 560 10 20 rl/raywhite) + (= current-texture 1) (rl/draw-text "HORIZONTAL GRADIENT" 540 10 20 rl/raywhite) + (= current-texture 2) (rl/draw-text "DIAGONAL GRADIENT" 540 10 20 rl/raywhite) + (= current-texture 3) (rl/draw-text "RADIAL GRADIENT" 580 10 20 rl/lightgray) + (= current-texture 4) (rl/draw-text "SQUARE GRADIENT" 580 10 20 rl/lightgray) + (= current-texture 5) (rl/draw-text "CHECKED" 680 10 20 rl/raywhite) + (= current-texture 6) (rl/draw-text "WHITE NOISE" 640 10 20 rl/red) + (= current-texture 7) (rl/draw-text "PERLIN NOISE" 640 10 20 rl/red) + :else (rl/draw-text "CELLULAR" 670 10 20 rl/raywhite)) + + (rl/end-drawing))) diff --git a/examples/textures-mouse-painting.flan b/examples/textures-mouse-painting.flan new file mode 100644 index 0000000..03cb3b2 --- /dev/null +++ b/examples/textures-mouse-painting.flan @@ -0,0 +1,255 @@ +;;;; raylib [textures] example - mouse painting +;;;; +;;;; examples/textures/textures_mouse_painting.c. The one example in the +;;;; category that takes a picture back OFF the GPU and writes it to disk, and +;;;; that round trip is why it is here: +;;;; +;;;; load-image-from-texture → image-flip-vertical → export-image +;;;; +;;;; Nothing in the corpus had run it. image-from-image has a headless +;;;; acceptance case and sand.flan loads images the other way, but the path +;;;; that reads a render target's pixels back into CPU memory, corrects for +;;;; GL's bottom-up rows and encodes a PNG had never been exercised at all. +;;;; All three came out of the generated half of the bindings; nothing needed +;;;; adding for this file. +;;;; +;;;; The flip is the same fact as the negative source height in +;;;; examples/textures-fog-of-war.flan, met from the other side: on screen the +;;;; canvas is drawn with a negative-height source rectangle so GL's bottom-up +;;;; rows come out the right way up, and on save there is no source rectangle +;;;; to negate, so the pixels are turned over in memory instead. A program +;;;; that did one and not the other would show a correct picture and save an +;;;; upside-down one — which is exactly the bug the C's comment warns about. +;;;; +;;;; The other thing this puts under load is the render texture as *persistent +;;;; state*. The fog-of-war target is rebuilt from nothing every frame; this +;;;; one is the document — it is cleared once before the loop and every stroke +;;;; after that accumulates in it. Between the two the corpus has both ways a +;;;; render texture gets used. +;;;; +;;;; Two deviations from the C, both in the same place and both deliberate. +;;;; The C computes colorMouseHover with a `for` whose `else` clause resets it +;;;; on every miss and whose `break` leaves it set on a hit, so the value that +;;;; survives depends on the loop exiting early — it works, but only because +;;;; of the break. Here the reset is before the loop and the loop only ever +;;;; sets it, which is the same result said plainly. And "no colour hovered" +;;;; is -1 in both, tested with `>= 0` before it is used as an index. + +(import rl "vendor:raylib") + +(defconst screen-width 800) +(defconst screen-height 450) + +(defconst max-colors-count 23) + +;; The palette strip along the top. colors[0] is also the canvas's clear +;; colour and the "eraser", which is why raywhite is first and not simply +;; another entry. +(defvar colors [23 rl/Color]) +(defvar colors-recs [23 rl/Rectangle]) + +(defvar color-selected i32) +(defvar color-selected-prev i32) +(defvar color-mouse-hover i32) +(defvar brush-size f32) +(defvar mouse-was-pressed bool) + +(defvar btn-save-rec rl/Rectangle) +(defvar btn-save-mouse-hover bool) +(defvar show-save-message bool) +(defvar save-message-counter i32) + +(defvar target rl/RenderTexture2D) + +(defn main [] () + (rl/init-window screen-width screen-height + "raylib [textures] example - mouse painting") + (defer (rl/close-window)) + + (set colors (array max-colors-count rl/Color)) + (set (at colors 0) rl/raywhite) + (set (at colors 1) rl/yellow) + (set (at colors 2) rl/gold) + (set (at colors 3) rl/orange) + (set (at colors 4) rl/pink) + (set (at colors 5) rl/red) + (set (at colors 6) rl/maroon) + (set (at colors 7) rl/green) + (set (at colors 8) rl/lime) + (set (at colors 9) rl/darkgreen) + (set (at colors 10) rl/skyblue) + (set (at colors 11) rl/blue) + (set (at colors 12) rl/darkblue) + (set (at colors 13) rl/purple) + (set (at colors 14) rl/violet) + (set (at colors 15) rl/darkpurple) + (set (at colors 16) rl/beige) + (set (at colors 17) rl/brown) + (set (at colors 18) rl/darkbrown) + (set (at colors 19) rl/lightgray) + (set (at colors 20) rl/gray) + (set (at colors 21) rl/darkgray) + (set (at colors 22) rl/black) + + ;; 30 wide with a 2-pixel gap, starting 10 from the left. + (set colors-recs (array max-colors-count rl/Rectangle)) + (dotimes [i max-colors-count] + (set (at colors-recs i) + (rl/Rectangle {.x (+ 10.0 (* 32.0 (f32 i))) + .y 10.0 .width 30.0 .height 30.0}))) + + (set color-selected 0) + (set color-selected-prev 0) + (set color-mouse-hover 0) + (set brush-size 20.0) + (set mouse-was-pressed false) + + (set btn-save-rec (rl/Rectangle {.x 750.0 .y 10.0 .width 40.0 .height 30.0})) + (set btn-save-mouse-hover false) + (set show-save-message false) + (set save-message-counter 0) + + ;; The canvas. It is the document, not a scratch buffer: nothing clears it + ;; again until the user presses C. + (set target (rl/load-render-texture screen-width screen-height)) + (defer (rl/unload-render-texture target)) + + (rl/begin-texture-mode target) + (rl/clear-background (at colors 0)) + (rl/end-texture-mode) + + ;; 120 and not 60: the stroke is a circle stamped at the mouse position once + ;; per frame, so the gaps between stamps during a fast drag are a function + ;; of the frame rate. The C's comment says as much. + (rl/set-target-fps 120) + + (until (rl/window-should-close?) + ;; Update + (let [mouse-pos (rl/get-mouse-position)] + (if (rl/key-pressed? :right) + (set color-selected (+ color-selected 1)) + (when (rl/key-pressed? :left) + (set color-selected (- color-selected 1)))) + (set color-selected (clamp color-selected 0 (- max-colors-count 1))) + + ;; Which swatch the pointer is over, or -1. See the header comment: the + ;; reset is here rather than in an else branch inside the loop. + (set color-mouse-hover -1) + (dotimes [i max-colors-count] + (when (rl/collision-point-rec? mouse-pos (at colors-recs i)) + (set color-mouse-hover i) + (break))) + + (when (and (>= color-mouse-hover 0) (rl/mouse-button-pressed? :left)) + (set color-selected color-mouse-hover) + (set color-selected-prev color-selected)) + + (set brush-size (clamp (+ brush-size (* (rl/get-mouse-wheel-move) 5.0)) + 2.0 50.0)) + + (when (rl/key-pressed? :c) + (rl/begin-texture-mode target) + (rl/clear-background (at colors 0)) + (rl/end-texture-mode)) + + ;; Paint. The gesture test is what makes the example work on a + ;; touchscreen, where there is no mouse button to hold. + (when (or (rl/mouse-button-down? :left) + (= (rl/get-gesture-detected) :drag)) + (rl/begin-texture-mode target) + ;; Above y=50 is the palette strip, and a stroke there would paint + ;; under the toolbar where it could never be seen. + (when (> (.y mouse-pos) 50.0) + (rl/draw-circle (i32 (.x mouse-pos)) (i32 (.y mouse-pos)) + brush-size (at colors color-selected))) + (rl/end-texture-mode)) + + ;; Right button erases, which is painting in the clear colour. The + ;; selected swatch is parked while the button is held so the toolbar + ;; shows what is being drawn, and restored on release. + (if (rl/mouse-button-down? :right) + (do + (when (not mouse-was-pressed) + (set color-selected-prev color-selected) + (set color-selected 0)) + (set mouse-was-pressed true) + (rl/begin-texture-mode target) + (when (> (.y mouse-pos) 50.0) + (rl/draw-circle (i32 (.x mouse-pos)) (i32 (.y mouse-pos)) + brush-size (at colors 0))) + (rl/end-texture-mode)) + (when (and (rl/mouse-button-released? :right) mouse-was-pressed) + (set color-selected color-selected-prev) + (set mouse-was-pressed false))) + + (set btn-save-mouse-hover (rl/collision-point-rec? mouse-pos btn-save-rec)) + + ;; The round trip. See the header comment for why the flip is here and + ;; not on the draw. + (when (or (and btn-save-mouse-hover (rl/mouse-button-released? :left)) + (rl/key-pressed? :s)) + (let [image (rl/load-image-from-texture (.texture target))] + (rl/image-flip-vertical (addr image)) + (rl/export-image image "my_amazing_texture_painting.png") + (rl/unload-image image)) + (set show-save-message true)) + + (when show-save-message + (set save-message-counter (+ save-message-counter 1)) + (when (> save-message-counter 240) + (set show-save-message false) + (set save-message-counter 0))) + + ;; Draw + (rl/begin-drawing) + (rl/clear-background rl/raywhite) + + ;; The canvas, flipped by the negative source height. + (rl/draw-texture-rec (.texture target) + (rl/Rectangle {.x 0.0 .y 0.0 + .width (f32 (.width (.texture target))) + .height (- 0.0 (f32 (.height (.texture target))))}) + (rl/Vector2 {.x 0.0 .y 0.0}) + rl/white) + + ;; The brush preview, drawn on the screen and not into the canvas. + (when (> (.y mouse-pos) 50.0) + (if (rl/mouse-button-down? :right) + (rl/draw-circle-lines (i32 (.x mouse-pos)) (i32 (.y mouse-pos)) + brush-size rl/gray) + (rl/draw-circle (rl/get-mouse-x) (rl/get-mouse-y) + brush-size (at colors color-selected)))) + + ;; The toolbar, over the canvas. + (rl/draw-rectangle 0 0 (rl/get-screen-width) 50 rl/raywhite) + (rl/draw-line 0 50 (rl/get-screen-width) 50 rl/lightgray) + + (dotimes [i max-colors-count] + (rl/draw-rectangle-rec (at colors-recs i) (at colors i))) + ;; The first swatch is raywhite on raywhite, so it needs an outline to + ;; be visible at all. + (rl/draw-rectangle-lines 10 10 30 30 rl/lightgray) + + (when (>= color-mouse-hover 0) + (rl/draw-rectangle-rec (at colors-recs color-mouse-hover) + (rl/fade rl/white 0.6))) + + (let [r (at colors-recs color-selected)] + (rl/draw-rectangle-lines-ex + (rl/Rectangle {.x (- (.x r) 2.0) .y (- (.y r) 2.0) + .width (+ (.width r) 4.0) .height (+ (.height r) 4.0)}) + 2.0 rl/black)) + + (rl/draw-rectangle-lines-ex btn-save-rec 2.0 + (if btn-save-mouse-hover rl/red rl/black)) + (rl/draw-text "SAVE!" 755 20 10 + (if btn-save-mouse-hover rl/red rl/black)) + + (when show-save-message + (rl/draw-rectangle 0 0 (rl/get-screen-width) (rl/get-screen-height) + (rl/fade rl/raywhite 0.8)) + (rl/draw-rectangle 0 150 (rl/get-screen-width) 80 rl/black) + (rl/draw-text "IMAGE SAVED: my_amazing_texture_painting.png" + 150 180 20 rl/raywhite)) + + (rl/end-drawing)))) diff --git a/vendor/raylib/bindings b/vendor/raylib/bindings index 8d01bb6..39dd78f 100644 --- a/vendor/raylib/bindings +++ b/vendor/raylib/bindings @@ -115,6 +115,27 @@ exclude SetExitKey exclude UpdateCamera exclude GetWorldToScreen +# The second batch of ported examples widened both halves of that split, and +# each of these is here for one of the two reasons above and no new one. +# +# - SetMouseCursor and SetTextureFilter take an `int` in the header and one +# of a closed set of names in fact, so their Flan face is a defenum and +# not the C signature — the same trade SetExitKey makes. +# - DrawCubeV, DrawSphere, DrawSphereWires and DrawRay are inside a frame, +# in examples/models-box-collisions.flan and examples/core-3d-picking.flan. +# draw-cube-v moving here is the one place this batch *narrows* the split +# the paragraph above names: it was generated because nothing called it, +# and something calls it now. +# - GetScreenToWorldRay goes with GetWorldToScreen for the reason given +# there. They are inverses over the same camera. +exclude SetMouseCursor +exclude SetTextureFilter +exclude DrawCubeV +exclude DrawSphere +exclude DrawSphereWires +exclude DrawRay +exclude GetScreenToWorldRay + # ── What the package's constants are called in C ──────────────────── # # enum every member of that defenum @@ -146,6 +167,8 @@ enum CameraMode CAMERA_ enum GamepadButton GAMEPAD_BUTTON_ enum GamepadAxis GAMEPAD_AXIS_ enum Gesture GESTURE_ +enum MouseCursor MOUSE_CURSOR_ +enum TextureFilter TEXTURE_FILTER_ # raylib writes GESTURE_DOUBLETAP as one word where every other member of that # enum is underscored. This is the narrow exception and not a general escape diff --git a/vendor/raylib/generated.flan b/vendor/raylib/generated.flan index e68a5e5..35a7cbc 100644 --- a/vendor/raylib/generated.flan +++ b/vendor/raylib/generated.flan @@ -60,6 +60,7 @@ (declare-c begin-blend-mode [mode i32] "BeginBlendMode") (declare-c end-blend-mode [] "EndBlendMode") (declare-c end-vr-stereo-mode [] "EndVrStereoMode") +(declare-c get-screen-to-world-ray-ex [position Vector2 camera Camera3D width i32 height i32] Ray "GetScreenToWorldRayEx") (declare-c get-world-to-screen-ex [position Vector3 camera Camera3D width i32 height i32] Vector2 "GetWorldToScreenEx") (declare-c swap-screen-buffer [] "SwapScreenBuffer") (declare-c poll-input-events [] "PollInputEvents") @@ -106,7 +107,6 @@ (declare-c set-mouse-offset [offset-x i32 offset-y i32] "SetMouseOffset") (declare-c set-mouse-scale [scale-x f32 scale-y f32] "SetMouseScale") (declare-c get-mouse-wheel-move-v [] Vector2 "GetMouseWheelMoveV") -(declare-c set-mouse-cursor [cursor i32] "SetMouseCursor") (declare-c update-camera-pro [camera (Ptr Camera3D) movement Vector3 rotation Vector3 zoom f32] "UpdateCameraPro") (declare-c draw-line-strip [points (Ptr Vector2) point-count i32 color Color] "DrawLineStrip") (declare-c draw-line-bezier [start-pos Vector2 end-pos Vector2 thick f32 color Color] "DrawLineBezier") @@ -206,7 +206,6 @@ (declare-c update-texture [texture Texture2D pixels (Ptr u8)] "UpdateTexture") (declare-c update-texture-rec [texture Texture2D rec Rectangle pixels (Ptr u8)] "UpdateTextureRec") (declare-c gen-texture-mipmaps [texture (Ptr Texture2D)] "GenTextureMipmaps") -(declare-c set-texture-filter [texture Texture2D filter i32] "SetTextureFilter") (declare-c set-texture-wrap [texture Texture2D wrap i32] "SetTextureWrap") (declare-c color-is-equal [col-1 Color col-2 Color] bool "ColorIsEqual") (declare-c color-to-int [color Color] i32 "ColorToInt") @@ -247,11 +246,8 @@ (declare-c draw-circle-3d [center Vector3 radius f32 rotation-axis Vector3 rotation-angle f32 color Color] "DrawCircle3D") (declare-c draw-triangle-3d [v-1 Vector3 v-2 Vector3 v-3 Vector3 color Color] "DrawTriangle3D") (declare-c draw-triangle-strip-3d [points (Ptr Vector3) point-count i32 color Color] "DrawTriangleStrip3D") -(declare-c draw-cube-v [position Vector3 size Vector3 color Color] "DrawCubeV") (declare-c draw-cube-wires-v [position Vector3 size Vector3 color Color] "DrawCubeWiresV") -(declare-c draw-sphere [center-pos Vector3 radius f32 color Color] "DrawSphere") (declare-c draw-sphere-ex [center-pos Vector3 radius f32 rings i32 slices i32 color Color] "DrawSphereEx") -(declare-c draw-sphere-wires [center-pos Vector3 radius f32 rings i32 slices i32 color Color] "DrawSphereWires") (declare-c draw-cylinder [position Vector3 radius-top f32 radius-bottom f32 height f32 slices i32 color Color] "DrawCylinder") (declare-c draw-cylinder-ex [start-pos Vector3 end-pos Vector3 start-radius f32 end-radius f32 sides i32 color Color] "DrawCylinderEx") (declare-c draw-cylinder-wires [position Vector3 radius-top f32 radius-bottom f32 height f32 slices i32 color Color] "DrawCylinderWires") @@ -259,10 +255,17 @@ (declare-c draw-capsule [start-pos Vector3 end-pos Vector3 radius f32 slices i32 rings i32 color Color] "DrawCapsule") (declare-c draw-capsule-wires [start-pos Vector3 end-pos Vector3 radius f32 slices i32 rings i32 color Color] "DrawCapsuleWires") (declare-c draw-plane [center-pos Vector3 size Vector2 color Color] "DrawPlane") +(declare-c draw-bounding-box [box BoundingBox color Color] "DrawBoundingBox") (declare-c draw-billboard [camera Camera3D texture Texture2D position Vector3 scale f32 tint Color] "DrawBillboard") (declare-c draw-billboard-rec [camera Camera3D texture Texture2D source Rectangle position Vector3 size Vector2 tint Color] "DrawBillboardRec") (declare-c draw-billboard-pro [camera Camera3D texture Texture2D source Rectangle position Vector3 up Vector3 size Vector2 origin Vector2 rotation f32 tint Color] "DrawBillboardPro") (declare-c check-collision-spheres [center-1 Vector3 radius-1 f32 center-2 Vector3 radius-2 f32] bool "CheckCollisionSpheres") +(declare-c check-collision-boxes [box-1 BoundingBox box-2 BoundingBox] bool "CheckCollisionBoxes") +(declare-c check-collision-box-sphere [box BoundingBox center Vector3 radius f32] bool "CheckCollisionBoxSphere") +(declare-c get-ray-collision-sphere [ray Ray center Vector3 radius f32] RayCollision "GetRayCollisionSphere") +(declare-c get-ray-collision-box [ray Ray box BoundingBox] RayCollision "GetRayCollisionBox") +(declare-c get-ray-collision-triangle [ray Ray p-1 Vector3 p-2 Vector3 p-3 Vector3] RayCollision "GetRayCollisionTriangle") +(declare-c get-ray-collision-quad [ray Ray p-1 Vector3 p-2 Vector3 p-3 Vector3 p-4 Vector3] RayCollision "GetRayCollisionQuad") (declare-c load-wave-from-memory [file-type string file-data (Ptr u8) data-size i32] Wave "LoadWaveFromMemory") (declare-c update-sound [sound Sound data (Ptr u8) sample-count i32] "UpdateSound") (declare-c export-wave-as-code [wave Wave file-name string] bool "ExportWaveAsCode") diff --git a/vendor/raylib/raylib.flan b/vendor/raylib/raylib.flan index 47eae98..4d69d6b 100644 --- a/vendor/raylib/raylib.flan +++ b/vendor/raylib/raylib.flan @@ -158,6 +158,22 @@ (declare-c hide-cursor [] "HideCursor") (declare-c cursor-hidden? [] bool "IsCursorHidden") +;; The shape the pointer takes. raylib's SetMouseCursor says `int` and means +;; one of these eleven, so the Flan face is the enum for the same reason +;; set-exit-key takes a Key: the call is made every frame from a hover test, +;; and `(rl/set-mouse-cursor :ibeam)` is checked against the members where an +;; i32 would take any number at all — including the one off-by-one that picks +;; the arrow instead of the I-beam and looks like nothing at all went wrong. +;; +;; All eleven are here and not a subset, unlike Key: the enum is closed and +;; eleven members is the whole of it. +(defenum MouseCursor + [default 0 arrow 1 ibeam 2 crosshair 3 pointing-hand 4 + resize-ew 5 resize-ns 6 resize-nwse 7 resize-nesw 8 resize-all 9 + not-allowed 10]) + +(declare-c set-mouse-cursor [cursor MouseCursor] "SetMouseCursor") + ;; ── Colours ───────────────────────────────────────────────────────── ;; ;; A Color is four bytes in RGBA order, so it is *not* the little-endian @@ -352,10 +368,57 @@ [position Vector3 width f32 height f32 length f32 color Color] "DrawCubeWires") +(declare-c draw-cube-v [position Vector3 size Vector3 color Color] "DrawCubeV") + +;; DrawSphere is DrawSphereEx with rings and slices fixed at 16; the wires +;; form takes them because the wireframe is the only place the tessellation is +;; visible. Both are here rather than generated for the reason above: they are +;; inside a frame, in an example that ships in examples/. +(declare-c draw-sphere + [center Vector3 radius f32 color Color] + "DrawSphere") +(declare-c draw-sphere-wires + [center Vector3 radius f32 rings i32 slices i32 color Color] + "DrawSphereWires") + ;; `slices` squares each way from the origin, `spacing` world units apart, on ;; the XZ plane. (declare-c draw-grid [slices i32 spacing f32] "DrawGrid") +;; ── Rays and boxes ────────────────────────────────────────────────── +;; +;; Three small aggregates, added together because the picking call produces +;; all three: a Ray goes in, a BoundingBox says what to test it against, and +;; a RayCollision comes back. Every field is read off raylib.h 5.5 and every +;; one of them is a Vector3 or a scalar — there is no owned memory anywhere +;; here, which is exactly what separates these three from Model and Mesh, and +;; why these could be described and those still cannot. +;; +;; What the layout check can and cannot say about them, on the same rule the +;; Camera3D note states: BoundingBox's two Vector3s are the same type, so a +;; permuted BoundingBox has the identical layout and nothing would catch it. +;; RayCollision is the opposite and is the one worth having checked — `hit` is +;; a C `bool`, one byte, and `distance` is a float, so the three padding bytes +;; between them are a real claim about the struct that a permutation breaks. +(defstruct BoundingBox [min Vector3 max Vector3]) +(defstruct Ray [position Vector3 direction Vector3]) +(defstruct RayCollision + [hit bool distance f32 point Vector3 normal Vector3]) + +;; The inverse of get-world-to-screen above, and hand-written beside it for +;; the reason stated there: the two read the same camera and the same window +;; dimensions, so they belong to the same half of the file. raylib 5.5 keeps +;; GetMouseRay as a #define onto this name; the define is not a symbol and +;; there is nothing to bind it to. +(declare-c get-screen-to-world-ray + [position Vector2 camera Camera3D] Ray + "GetScreenToWorldRay") + +;; Per-frame and inside BeginMode3D, like the cube draws. raylib draws the +;; ray as a line a thousand units long, so it is a debugging aid and not +;; geometry with an end. +(declare-c draw-ray [ray Ray color Color] "DrawRay") + ;; ── Shapes ────────────────────────────────────────────────────────── ;; ;; Rectangle intersection, which raylib computes from all four fields in @@ -459,6 +522,27 @@ (declare-c unload-texture [texture Texture2D] "UnloadTexture") +;; How a texture is sampled when it is drawn at anything other than its own +;; size. The header says `int` on SetTextureFilter and means one of these six. +;; +;; The value of the enum face here is not a typo caught at the call site so +;; much as a *readable* one: the fog-of-war example renders its fog into a +;; 25x15 render texture and scales it to 800x450, and the entire visual point +;; of the example is that `:bilinear` smooths the tile edges where the +;; default `:point` would show 32-pixel squares. A bare `1` in that call says +;; nothing; the member name says the whole thing. +;; +;; TEXTURE_FILTER_ANISOTROPIC_* are the mipmapped modes and need a texture +;; with mipmaps generated, which nothing here makes — they are listed because +;; the enum is closed, not because anything calls them. +(defenum TextureFilter + [point 0 bilinear 1 trilinear 2 + anisotropic-4x 3 anisotropic-8x 4 anisotropic-16x 5]) + +(declare-c set-texture-filter + [texture Texture2D filter TextureFilter] + "SetTextureFilter") + (declare-c draw-texture [texture Texture2D x i32 y i32 tint Color] "DrawTexture") From 10edda6de40245e61a24a174d7f03b6302521da7 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:46:00 +0700 Subject: [PATCH 5/7] Two comments in vendor/raylib that this batch made false MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cursor block said DisableCursor is 'what nothing here needs'; core-3d-picking toggles it from the right mouse button. Enable/DisableCursor stay generated — they take no arguments, so there is no Flan face to improve, which is the same rule that leaves GetMouseX there — but the sentence had to go. And bindings named draw-cube-v as one of its three deliberately-generated variants, which it no longer is. The paragraph now says what happened to it rather than asserting the opposite of the exclude list below it. --- vendor/raylib/bindings | 17 ++++++++++------- vendor/raylib/raylib.flan | 6 +++++- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/vendor/raylib/bindings b/vendor/raylib/bindings index 39dd78f..325dee7 100644 --- a/vendor/raylib/bindings +++ b/vendor/raylib/bindings @@ -90,13 +90,16 @@ exclude IsWindowReady # generated i32 would take. GetWorldToScreen goes with BeginMode3D # because they read the same camera. # -# What this line splits, and deliberately: draw-cube is here and draw-cube-v -# is generated, get-world-to-screen is here and get-world-to-screen-ex is -# generated, update-camera is here and update-camera-pro is generated. Every -# other family in raylib.flan — the texture draws, the circle draws — sits -# together, so the split is worth naming: what is hand-written is what the -# ported examples call, and hand-writing the variants as well would widen the -# half that has to be maintained by hand for nothing the examples ask for. +# What this line splits, and deliberately: get-world-to-screen is here and +# get-world-to-screen-ex is generated, update-camera is here and +# update-camera-pro is generated. (draw-cube-v was named here as the third +# such pair and no longer is — see the DrawCubeV line further down, which is +# what happens to a split of this kind when an example starts calling the +# other half.) Every other family in raylib.flan — the texture draws, the +# circle draws — sits together, so the split is worth naming: what is +# hand-written is what the ported examples call, and hand-writing the variants +# as well would widen the half that has to be maintained by hand for nothing +# the examples ask for. # # What is deliberately NOT here: the window-state family (IsWindowState, # SetWindowState, ClearWindowState, ToggleFullscreen, Minimize/Maximize/ diff --git a/vendor/raylib/raylib.flan b/vendor/raylib/raylib.flan index 4d69d6b..62622ae 100644 --- a/vendor/raylib/raylib.flan +++ b/vendor/raylib/raylib.flan @@ -153,7 +153,11 @@ ;; The cursor's visibility is window state and not input, but it is read and ;; written by the same code that reads the mouse, so it sits here. ;; hide-cursor only hides it; it does not lock it to the window, which is -;; what raylib's separate DisableCursor does and which nothing here needs. +;; what raylib's separate DisableCursor does. Those two — DisableCursor and +;; EnableCursor — are in the generated half rather than here: they take no +;; arguments at all, so there is no Flan face for a hand-written line to +;; improve, which is the same rule that leaves GetMouseX there. +;; examples/core-3d-picking.flan toggles them from the right mouse button. (declare-c show-cursor [] "ShowCursor") (declare-c hide-cursor [] "HideCursor") (declare-c cursor-hidden? [] bool "IsCursorHidden") From 3e6886831d76c701847bb29b69e54645deaba9ae Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:51:31 +0700 Subject: [PATCH 6/7] Queue the pointer-length question, with the three examples it blocks --- NEXT.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/NEXT.md b/NEXT.md index 197ffe5..4eeb59e 100644 --- a/NEXT.md +++ b/NEXT.md @@ -1,3 +1,29 @@ +## Queued: a pointer from C needs a length before it can be indexed + +**Sequenced after the generics lane**, which holds `lib/check.ml`. + +`indexed` in `lib/check.ml` accepts `Array` and `Slice` only, so a `(Ptr T)` that came back from C is readable at +element 0 through `deref` and nowhere else. Confirmed empirically rather than inferred: +`(at (.recs (rl/get-font-default)) 0)` answers `(Ptr rl/Rectangle) cannot be indexed`. + +**It blocks real work now**, which is why it moved from a note to a queue entry. Three upstream examples are +unportable — `text_rectangle_bounds` (walks `font.recs[i]` and `font.glyphs[i]`), `text_codepoints_loading` +(`LoadCodepoints` returns `int*`) and `textures_image_processing` (`LoadImageColors` returns `Color*`) — and the +first of those is the only *procedural* font example, so the whole hand-written `Font` surface has no example +caller. Every other text example needs a TTF on disk. + +The problem is that C hands back a pointer and no length. Two shapes: + +1. **`(slice-from-ptr p n)`** — the caller states the length and owns being right about it. Honest, one form, and + the unsafety is written at the site where somebody had to know the answer anyway. It is the same trust + `declare-c` already extends. +2. **A per-binding declaration naming which argument carries the count.** raylib's convention is an out-parameter + (`LoadCodepoints(text, &count)`), so the information usually *is* there. This makes the binding carry it once + instead of every call site repeating it, and it fits the existing `bindings` file. It does not cover + `font.recs`, where the count is a sibling *field* (`font.glyphCount`) rather than an argument. + +They are not exclusive, and 2 does not cover every case, so 1 is probably the floor whatever else is built. + ## Queued, decided by the author: generic structs and generic array lengths **Sequenced after the core generics lane, not beside it.** Both change `Types.t`, which that lane is inside. From 19353648a01732c1a7e3655a793f5266379bf609 Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Sun, 13 Sep 2026 14:59:32 +0700 Subject: [PATCH 7/7] The game's state is fixed arrays with counts, so the verdict stops being conditional --- PORTING.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/PORTING.md b/PORTING.md index bf1158e..132eacc 100644 --- a/PORTING.md +++ b/PORTING.md @@ -267,6 +267,15 @@ the state type. `sand.flan` is already written that way. The frame rollback is t piece that needs to touch the state, and the game can supply `snapshot`/`restore` as two more callbacks. +> **Settled by the author, 2026-09-13: fixed arrays with counts.** The first branch below. So the +> conditional verdict in this section is now unconditional: the state fits in `defvar` globals, the +> engine takes only `(Fn [] ())` callbacks and never names a state type, generics stays off this +> game's critical path, and `drop` is not needed for this version. Nothing in the language had to be +> built for it — fixed arrays, counts and slices all already work. What is left is writing the game. +> +> Carry forward the one flag §3 raises: the next version, with several tilesets and several atlases, +> grows straight into `drop` and into `(Vec T)` where `T` owns a `Vec`. + **This verdict is conditional, and the condition is one decision.** Both it and the globals workaround above hang on the same pivot, so it is worth stating once, flatly: *nothing in this game's state needs to be move-only.* Make the inner collections fixed