Managed Graphics & Audio
App-owned resources, automatic frame lifetimes, cameras, shaders, render targets, music, and one-shot sound.
The guide below is generated from the maintained vraylib/MANAGED.md manual. Start with this API for application code, then use the native reference for lower-level raylib, raymath, and rlgl calls. See Graphics Showcase for runnable projects and acceptance commands.
Import vraylib/vraylib.vy to get a hybrid API: an App owns resources and frames, resource objects expose methods, and drawing primitives remain concise module functions. The native raylib/raymath/rlgl calls are also available.
Start with an application
app(width,height,title) defaults to 60 FPS, a resizable window and VSync. app_options(width,height,title,fps,flags) selects explicit raylib flags. session(asset_root) creates the same App without opening graphics, useful for CPU image processing. A headless loop needs limit(n) or an explicit stop(). Only one managed application/context owner may be live at once.
frame() completes the previous frame, reclaims its transient arena data, updates streamed music, resizes screen-following targets, and starts a new frame. It returns false on window exit, stop(), or the configured frame limit. end_frame() finishes a frame explicitly; close() aborts any unfinished frame and releases the application's resources and contexts. Both close operations on already-released resource tokens and App.close are idempotent.
Deferring a native window close
app.defer_close(true) lets the application confirm a titlebar/exit-key close before ending its loop. It is off by default. While enabled, a native close request keeps frame() running and queues a pending event. After frame(), call app.close_requested() to consume that event: it returns true once, then false until a new native close event arrives. An unread event survives subsequent frames; multiple requests coalesce into one pending flag. Continue the normal drawing/end cycle on Cancel so raylib polls events and resets the backend's native close flag.
On accepted Save/Discard, use app.stop() or app.close(); on Cancel, continue the loop. Disabling deferred close clears its pending event and restores normal native-close termination. Repeatedly enabling it does not clear a pending event. stop(), the frame limit, and loss of the live window always terminate frame(), even with deferred close enabled. close_requested() only consumes session state; it does not call WindowShouldClose() again. Headless sessions have no native close event.
Recovering short errors in a frame
app.transient_errors(true) enters a nested, opt-in recovery scope; balance each entry with app.transient_errors(false), usually in finally. Enabling requires an active managed frame. Only successful configuration calls change nesting. Frame completion, rollover, application closure and shutdown reset that nesting.
While enabled, thrown strings shorter than 1024 bytes are copied into a static rotating 64-slot store, independent of frame rewinds. Each promotion (including a rethrow) consumes a slot; the latest 64 promotions remain readable, including after application closure. Do not retain these strings for long-lived history: later promotions overwrite their slots. Longer strings and structured exceptions retain the normal persistent-copy behavior.
Catch entry restores abandoned nested-region checkpoints, persistent-region depths and @zeroed/@deterministic zero-mode depth before catch/finally runs, preserving scopes that enclose the handler. Exception payload allocations remain live until an enclosing arena rewind; this is not a general eager region-memory unwinder.
Let App own the loop
run(update,draw) invokes named compiled Vyne functions with the App argument, opens/closes window drawing for draw, and closes the application on success or failure. Headless sessions invoke both callbacks without opening drawing passes. It returns the completed frame count. These are ordinary Vyne calls, not C callbacks. Named function values and callable parameters use the compiler's boxed ABI; callback arity/type errors are catchable. Use stop() for loop exit.
Typed, shared resources
Factories return Texture, Image, Model, Font, Shader, Camera, Music, and RenderTarget value wrappers. Internally each wrapper carries stable tokens. Copying a wrapper shares the underlying resource; it does not duplicate ownership. valid() checks the session and generation. Early close() is available, and dependent resources must be released before resources they reference.
App loads cache by resolved path and resource kind. Repeating a load returns the same token. Closing it invalidates aliases and removes the cache entry, so a later load creates a fresh resource. Cache paths, uniform names, ownership and pass state are stored persistently, even when first populated inside a frame. Changing assets(root) affects subsequent path resolution. Absolute paths are accepted. Relative roots are relative to the process working directory.
| App factory | Result / purpose |
|---|---|
load_texture(path) | Checked GPU texture; width, height, draw, close |
texture(image) | Upload a checked same-session Image; the GPU Texture survives source image closure |
load_image(path), image(w,h,color) | CPU image; resize, save, close |
load_model(path), cube(texture), plane(texture,w,length) | Model; material count, shader/texture assignment and drawing |
load_font(path), load_font_size(path,size) | Font; draw(text,position,size,tint), measure(text,size) |
load_shader(vertex_or_null,fragment) | Custom shader; rejects default fallback on compilation failure |
camera(position,target,fovy), first_person(), orbit(position,target) | Persistent mutable camera |
music(path,volume) | Looping streamed audio; automatically updated every frame |
load_sound(path) | Cached one-shot Sound with play, stop, playing, volume, close |
target(w,h), screen_target() | Fixed-size or window-following render target |
Model/camera/target drawing requires an open App window. Image sessions need no graphics or audio device. Music has valid, play, pause, volume and close; if no audio device can open, it returns an unavailable Music token (valid=false). Missing files and failed resource/shader loads produce descriptive exceptions.
load_font_size(path,size) accepts raster sizes 1..512 and caches by resolved path and size, separately from load_font(path). It requests printable ASCII, Latin-1, Latin Extended-A/B, Azerbaijani schwa (Əə) and combining diacritics, then applies bilinear atlas filtering. Actual coverage depends on the font file; missing glyphs use raylib's fallback. font.measure(text,size) returns Vector2 dimensions using the same 1.0 spacing as font.draw, including multiline text.
camera.set_orthographic(size) preserves position, target and up, switches projection to CAMERA_ORTHOGRAPHIC, and sets the positive vertical view size in fovy.
Texture regions and procedural assets
draw_region(source,destination,origin,rotation,tint) exposes scaled/cropped/ rotated drawing without manually extracting a resource token. It validates the texture and requires an active managed drawing surface. app.drawing() reports that state. Borrowed target.texture() views use logical top-left source coordinates, like Texture.draw, and follow target storage replacement. Keep the logical wrapper rather than caching its raw attachment handle.
Fixed native saturation
app.saturation(drive,mode) adds a built-in mixed stereo processor after audio has opened. Drive is 0..1; mode 0 is normalized soft/tanh saturation and mode 1 is hard clipping. Zero drive detaches it. Invalid settings throw; if no audio device is ready, enabling returns false. saturation_attached() and saturation_blocks() expose diagnostics. Sound volume is clamped to 0..1. The callback reads one packed lock-free atomic configuration and uses no allocation, locks, logging or Vyne code. App/audio shutdown detaches it before destroying streams. Arbitrary foreign/Vyne audio callbacks remain unavailable.
Named shader uniforms
set supports Float64/Float32 scalars, Int64/Bool scalars, numeric vectors of 1..4 components (arrays or Vector2/3/4), and Matrix values. Use floating literals for GLSL floats; 1 is an int and 1.0 is a float. set_ints selects integer vector uniforms. set_texture selects sampler uniforms and retains dependencies. Locations are queried once per shader/name; warm updates use stack scratch storage, so users do not allocate uniform buffers. Missing or optimized-out uniforms throw a named-operation error rather than silently disabling an effect. uniform_queries() provides diagnostic verification of the cache.
Render targets, passes and cameras
Targets, cameras and shaders expose begin/end and with_draw(callback). The latter invokes a zero-argument named function and pairs the pass using try/finally. Passes are tracked in LIFO order and unwound when a frame or App closes, including exceptions. A drawing surface must precede camera/shader passes; nested targets or same-kind passes are rejected rather than corrupting raylib's state. Keep raw begin/end calls outside managed pass composition.
Target present handles render-texture orientation. texture() returns a borrowed, non-owning logical view that follows target resizing; its close() does not release the target. resize(w,h) replaces storage while preserving the target token. screen_target() follows the window at the next frame boundary. Managed shader samplers are refreshed when their shader pass begins, so a cached sampler continues to reference a resized logical target. Resizing active targets is rejected. Managed model texture assignments also refresh after replacement. Raw attachment references used by low-level model/material APIs must be detached before replacing storage; native_handle() is an explicit escape hatch whose returned attachment handle is invalidated by resize.
Camera methods include position, set_position, set_height, move, look, view, ray, update, begin/end and with_draw. view() returns a checked Camera3D snapshot; ray(screen_position) produces a picking Ray and requires a live application window. Both returned records are frame-local snapshots, not persistent mutable camera state. First-person update normalizes diagonal WASD input and uses App.dt; orbit uses raylib's orbital controller. Speed and sensitivity are wrapper value fields that can be configured before updating. Collision, crouching, jumping and scene-specific physics remain application logic, as demonstrated by the full bodycam example. camera.billboard(texture,position,size,tint) draws a checked managed texture in the active 3D pass. Sector Shift demonstrates this with sector-specific fog.
Shader authoring and floating-point pipelines
App.compile_shader(vertex_source, fragment_source) builds an uncached GLSL candidate and returns ShaderBuild { shader, success, log }. A syntax/link failure returns a zero shader token and owned bounded driver diagnostics, preserving the caller's last-good program. Invalid arguments/context and allocation failures throw. Null vertex source uses the standard GLSL 330 vertex stage.
Shader.uniforms() reports active rows [name, GL_type, array_length, location]. set_typed(name, GL_type, values) validates reflected scalar/vector/array/mat4 uploads, including exact Int32/bool values. Optimized-out uniforms are absent; uniform-block members and unsupported types are explicitly diagnosed. Samplers use set_texture; passing null clears a managed sampler binding.
Model.draw_material(transform, shader, material_slot, tint) temporarily overrides the selected material slot without changing shared geometry/material storage. Set every instance's uniforms before its draw: program uniforms are shared state, not model-owned parameter instances.
App.float_target(w,h) owns an RGBA32F target. format, read_pixels and read_pixel preserve unquantized negative/HDR values with top-left coordinates. copy_from(source) performs an exact replacement blit; draw_from(source,shader) runs a replacement fullscreen pass without inherited alpha blending. Resize and these operations restore relevant GL framebuffer/texture/pixel-transfer state. Same-target sampling/writing is rejected. App.can_release(tokens) and release_bank(tokens) preflight entire owned banks before destructive release.
Readback/reflection/log returns follow the caller's arena lifetime. Copy retained data into document/evaluation owners. The APIs use desktop GL 3.3 and the graphics thread; they do not provide compute shaders or automatic GLSL differentiation. See SHADER_STUDIO.md for supported GL enums, formats, budgets, sampler restrictions, ownership and fault tests. VMGE's Shader Studio demonstrates code/graph authoring, typed parameter exposure, immutable scene materials, editable pipeline passes, float/reference capture and an explicit fitting extension API.
Region and exception rules
The managed frame is a transient arena scope. Avoid keeping new strings, arrays, maps or boxed records from one frame into the next. Native resources loaded during a frame survive because the session owns their native storage; thin primitive-token wrappers can be copied, and cached assets can be retrieved again in the next frame. Long-lived application containers should be created before the loop; use explicit region.commit for arena data that must escape.
Start managed frames outside @persistent regions. Balanced nested ordinary regions are fine. An exceptional nested persistent region is exited during frame cleanup so its allocator routing and commit lock do not remain active. The frame exception hook promotes string/array/map/struct error data into the commit arena before throw propagation. Consequently errors remain readable after App.close or automatic run cleanup; their copies live until program teardown. Shared and cyclic array/map/struct error graphs are copied with identity tracking. Frame scopes bound allocation lifetimes, not a guarantee of zero allocations.
Diagnostics and examples
App exposes frames, dt, elapsed, width, height, resources, passes, drawing, uniform_queries, valid, limit, fps and stop. The full bodycam example now uses typed assets, managed frames/music, named uniforms and resizing targets. The small desktop showcase demonstrates a managed orbit camera. VMGE in examples/projects/vmge/ demonstrates a persistent editable cube map, procedural/original assets, camera-ray picking, texture regions and a playable fog/VHS/scanline pipeline. Its README covers controls, paths and acceptance.
The original low-level facade and the pinned API coverage/capability limits remain documented in README.md.