### Clone and Run Example Source: https://nim2d.github.io/nim2d/getting-started Clone the nim2d repository and run an example to quickly verify your SDL3 installation and nim2d setup. ```bash $ git clone https://github.com/nim2d/nim2d $ cd nim2d $ nim c -r examples/snake.nim ``` -------------------------------- ### Install Box2D for Physics Module Source: https://nim2d.github.io/nim2d/getting-started Install the Box2D library if you plan to use the nim2d physics module. Installation methods vary by operating system. ```bash brew install box2d ``` ```bash sudo pacman -S box2d ``` -------------------------------- ### Install SDL3 on Arch Linux Source: https://nim2d.github.io/nim2d/getting-started Install SDL3 and its related libraries using pacman on Arch Linux. ```bash $ sudo pacman -S sdl3 sdl3_image sdl3_ttf sdl3_mixer ``` -------------------------------- ### Build SDL_mixer from source on Ubuntu Source: https://nim2d.github.io/nim2d/getting-started Build and install SDL_mixer from source on Ubuntu if it's not available via package manager. This process installs to /usr/local. ```bash $ sudo apt install build-essential git cmake ninja-build pkg-config libogg-dev libvorbis-dev $ git clone --depth 1 --branch release-3.2.4 https://github.com/libsdl-org/SDL_mixer $ cmake -S SDL_mixer -B SDL_mixer/build -G Ninja -DCMAKE_BUILD_TYPE=Release $ cmake --build SDL_mixer/build $ sudo cmake --install SDL_mixer/build $ sudo ldconfig ``` -------------------------------- ### Install nim2d via Nimble Source: https://nim2d.github.io/nim2d/getting-started Install the nim2d library into your system using the nimble package manager for use in your own projects. ```bash $ nimble install nim2d ``` -------------------------------- ### Install SDL3 on Ubuntu Source: https://nim2d.github.io/nim2d/getting-started Install SDL3 development packages on Ubuntu using apt. Note that SDL3_mixer may need to be built from source. ```bash $ sudo apt install libsdl3-dev libsdl3-image-dev libsdl3-ttf-dev ``` -------------------------------- ### Install SDL3 on macOS Source: https://nim2d.github.io/nim2d/getting-started Install SDL3 and its related libraries (image, ttf, mixer) using Homebrew on macOS. ```bash $ brew install sdl3 sdl3_image sdl3_ttf sdl3_mixer ``` -------------------------------- ### Install choosenim for Nim Source: https://nim2d.github.io/nim2d/getting-started Use choosenim to install and manage Nim versions on macOS and Linux. Ensure you have Nim 2.0 or newer. ```bash $ curl https://nim-lang.org/choosenim/init.sh -sSf | sh ``` -------------------------------- ### Install Box2D Source: https://nim2d.github.io/nim2d/physics Install Box2D using package managers like Homebrew for macOS or Pacman for Arch Linux. For other systems, build from source. ```bash brew install box2d # macOS sudo pacman -S box2d # Arch Linux ``` -------------------------------- ### Create and Start a New Thread Source: https://nim2d.github.io/nim2d/api/thread Starts a new background thread that executes the provided top-level procedure `fn`. The procedure must be marked with `{.thread.}` and cannot capture any variables. ```nim proc newThread(fn: proc () {.thread, nimcall.}): Thread2d ``` -------------------------------- ### Get OS and Processor Info Source: https://nim2d.github.io/nim2d/system Use `getOS` to get the operating system name and `getProcessorCount` to get the number of logical CPU cores. This is useful for platform-specific logic or displaying system information. ```nim echo "running on ", getOS(), " with ", getProcessorCount(), " cores" ``` -------------------------------- ### start Source: https://nim2d.github.io/nim2d/api/particlesystem Resumes particle emission after it has been stopped. ```APIDOC ## start ### Description Resume emitting after `stop`. ### Signature ```nim proc start(ps: ParticleSystem) ``` ### Parameters * `ps` (`ParticleSystem`) - The particle system to control. ``` -------------------------------- ### Get Operating System Name Source: https://nim2d.github.io/nim2d/api/system Retrieves the name of the current operating system. Examples include 'macOS', 'Linux', or 'Windows'. ```nim proc getOS(): string ``` -------------------------------- ### Create and Start a Dialogue Script Source: https://nim2d.github.io/nim2d/dialogue Defines a conversation script with nodes, speakers, pages, and choices. Initializes and starts the dialogue system with a default style. ```nim import nim2d import nim2d/dialogue var script = newScript() script.add Node(id: "start", speaker: "Guard", pages: @["Halt! Who goes there?"], choices: @[ choice("A friend.", "friend"), choice("None of your business.", "rude"), ]) script.add Node(id: "friend", speaker: "Guard", pages: @["Then pass."]) script.add Node(id: "rude", speaker: "Guard", pages: @["Watch your tongue."]) let dlg = newDialogue(script, defaultStyle(font)) dlg.start("start") ``` -------------------------------- ### play Source: https://nim2d.github.io/nim2d/api/audio Starts playing a source from the beginning. If the source is already playing, it will restart. ```APIDOC ## play ### Description Start the source from the beginning, or restart it if already playing. The loop count is set through the play options, because setting it on a stopped track has no lasting effect. ### Parameters - `src` (`Source`) ``` -------------------------------- ### newDialogue Source: https://nim2d.github.io/nim2d/api/dialogue Creates a new dialogue player with the specified script and style. The dialogue is drawn using the provided style. To start the dialogue, call the `start` method on the returned Dialogue object. ```APIDOC ## newDialogue ### Description Creates a new dialogue player with the specified script and style. The dialogue is drawn using the provided style. To start the dialogue, call the `start` method on the returned Dialogue object. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters * `script` (`Script`) * `style` (`Style`) * `reveal` (`Reveal`) ### Returns `Dialogue` - A new Dialogue object ready to be started. ``` -------------------------------- ### Play Sound Source Source: https://nim2d.github.io/nim2d/api/audio Starts playback of a sound source from the beginning. If the source is already playing, it restarts. ```nim proc play(src: Source) ``` -------------------------------- ### attach Source: https://nim2d.github.io/nim2d/api/camera Starts drawing through a specified camera, applying its transform to subsequent drawing operations. ```APIDOC ## attach ### Description Start drawing through `cam`. It pushes a transform so the world point the camera looks at lands in the center of the window, scaled by the zoom and turned by the rotation. Draw your world in world coordinates after this, then call `detach` to go back to plain screen coordinates. Pairs of attach and detach must match, the same way `push` and `pop` do. ### Parameters * `nim2d` (Nim2d) * `cam` (Camera) ``` -------------------------------- ### Basic Nim2D Program: Drawing a Circle Source: https://nim2d.github.io/nim2d/getting-started This snippet demonstrates the minimal structure for a Nim2D application. It initializes a window, sets up a draw callback to render a static circle, and starts the main loop. ```nim import nim2d let n2d = newNim2d("hello", 100, 100, 640, 480) n2d.draw = proc(nim2d: Nim2d) = nim2d.setColor(255, 120, 60) nim2d.circle(320, 240, 80, true) n2d.play() ``` -------------------------------- ### newSceneManager Source: https://nim2d.github.io/nim2d/api/scene Initializes a new SceneManager and hooks it into the engine's callbacks. It can optionally start with an initial scene. ```APIDOC ## newSceneManager Nim2d initial: Scene = nil ### Description Make a scene manager and point the engine's update, draw and input callbacks at it, so from here on the live scene receives them. Pass an `initial` scene to start with, or leave it out and `push` one yourself. An `initial` scene's `enter` runs during this call, before the manager is returned, so if that scene's `enter` needs to reach the manager, leave `initial` out and `push` it once the manager is assigned. ### Parameters - `nim2d` (Nim2d) - `initial` (Scene) ### Returns `SceneManager` ``` -------------------------------- ### Enable and Handle Text Input Source: https://nim2d.github.io/nim2d/input Start text input in the `nim2d.load` callback using `startTextInput`. The `nim2d.textinput` callback receives decoded UTF-8 strings, suitable for text buffers. ```nim n2d.load = proc(nim2d: Nim2d) = nim2d.startTextInput() n2d.textinput = proc(nim2d: Nim2d, text: string) = buffer.add text ``` -------------------------------- ### Rich Text Formatting Example Source: https://nim2d.github.io/nim2d/dialogue Demonstrates rich text formatting including bold, italic, outline, and hex color styling within a dialogue string. ```nim "The [#ff5555]dragon[/] **roars**. *You* feel [o]afraid[/]." ``` -------------------------------- ### play Source: https://nim2d.github.io/nim2d/api/nim2d Starts the main application loop, handling events, updates, and drawing until the window is closed or the application is quit. It also manages resource teardown. ```APIDOC ## proc play(nim2d: Nim2d) ### Description Run the main loop: dispatch events, call `update` and `draw` every frame, and keep going until the window closes or `running` is set to false. The `quit` callback runs once after the loop, then audio, the GPU and the window are torn down. An exit hook runs the same teardown if the program ends some other way, so a `system.quit` or an escaping exception still releases the device and window instead of leaking them. ### Parameters #### Path Parameters * `nim2d` (Nim2d) - ### Source src/nim2d.nim:372 ``` -------------------------------- ### beginContacts Source: https://nim2d.github.io/nim2d/api/physics Retrieves pairs of bodies that started touching during the last update. ```APIDOC ## beginContacts ### Description Pairs of bodies that started touching during the last `update`. Compare their `userData` to tell which is which. ### Parameters #### Path Parameters - `w` (World) - Description not available ### Returns `seq[Contact]` ``` -------------------------------- ### getDPIScale Source: https://nim2d.github.io/nim2d/api/window Gets the ratio of backing pixels to window points. ```APIDOC ## getDPIScale ### Description The ratio of backing pixels to window points. It is 1.0 on a normal display or when high-DPI is off, and 2.0 on a 2x display with high-DPI enabled. ### Parameters - **nim2d** (Nim2d) - Description not available ### Returns - **float** - The DPI scale factor. ``` -------------------------------- ### Start Text Input Events Source: https://nim2d.github.io/nim2d/api/keyboard Enables the reception of `textinput` events, which provide typed character data. Call this before attempting to capture text input. ```nim proc startTextInput(nim2d: Nim2d) ``` -------------------------------- ### nim2d Load Callback Source: https://nim2d.github.io/nim2d/api/nim2d Sets the callback that runs once when `play` starts, before the first frame. ```APIDOC ## load ### Description Sets the callback that runs once when `play` starts, before the first frame. ### Parameters - `n2d` (Nim2d) - Description not available - `p` (proc (nim2d: Nim2d)) - Description not available ``` -------------------------------- ### Configure SDL3 on Windows Source: https://nim2d.github.io/nim2d/getting-started Set up SDL3 on Windows by downloading prebuilt libraries and configuring environment variables. Ensure the bin directory is in your PATH. ```bash NIM2D_SDL_PREFIX=C:/sdl3 PATH=%PATH%;C:\sdl3\bin ``` -------------------------------- ### Get the Current Scene Source: https://nim2d.github.io/nim2d/api/scene The current procedure returns the scene at the top of the stack, or nil if the stack is empty. ```nim proc current(mgr: SceneManager): Scene ``` -------------------------------- ### Create and Configure a Camera Source: https://nim2d.github.io/nim2d/camera Initializes a new camera and sets its properties like position, zoom, and rotation. Import the camera module to use these functions. ```nim import nim2d import nim2d/camera let cam = newCamera() cam.lookAt(player.x, player.y) cam.move(40, 0) cam.zoom(1.5) cam.rotate(0.1) ``` -------------------------------- ### Get Time Since Initialization Source: https://nim2d.github.io/nim2d/api/timer Retrieves the high-resolution time in seconds since the SDL library was initialized. Use this for measuring elapsed time from the start of the application. ```nim proc getTime(): float ``` -------------------------------- ### loadLdtk Source: https://nim2d.github.io/nim2d/api/tilemap Reads an LDtk file, parses it, and loads its tileset images from the same folder. This is the one call an example or game needs. Raises IOError if the file cannot be read. ```APIDOC ## loadLdtk ### Description Reads an LDtk file, parses it, and loads its tileset images from the same folder. This is the one call an example or game needs. Raises IOError if the file cannot be read. ### Parameters - `nim2d` (`Nim2d`) - `path` (`string`) ### Returns `LdtkProject` ``` -------------------------------- ### Get Source Volume Source: https://nim2d.github.io/nim2d/api/audio Retrieves the current volume setting for a sound source. ```nim proc getVolume(src: Source): float ``` -------------------------------- ### Get Source Directory Path Source: https://nim2d.github.io/nim2d/api/filesystem Retrieves the absolute path of the read-only source directory. ```nim proc getSourceDirectory(fs: Filesystem): string ``` -------------------------------- ### initAudio Source: https://nim2d.github.io/nim2d/api/audio Initializes the audio system by opening the audio device and mixer. This is called automatically by `newNim2d`. If no audio device is available, audio remains off. ```APIDOC ## initAudio ### Description Open the audio device and the mixer. Called once by `newNim2d`. If no device is available it leaves audio off rather than failing, and it is safe to call again as a no-op. Audio reopens cleanly after `shutdownAudio`. ### Parameters - `nim2d` (`Nim2d`) ``` -------------------------------- ### Nim2D Animation: Moving Circle Source: https://nim2d.github.io/nim2d/getting-started This example shows how to create animation by using the `update` callback to modify a variable over time, which then influences the drawing in the `draw` callback. It also demonstrates setting a background color. ```nim import std/math import nim2d let n2d = newNim2d("loop", 100, 100, 640, 480, (20'u8, 22'u8, 30'u8, 255'u8)) var t = 0.0 n2d.load = proc(nim2d: Nim2d) = echo "starting" n2d.update = proc(nim2d: Nim2d, dt: float) = t += dt n2d.draw = proc(nim2d: Nim2d) = nim2d.setColor(120, 200, 255) nim2d.circle(320, 240, 80 + 24 * sin(t * 3), true) n2d.play() ``` -------------------------------- ### Create New Filesystem Source: https://nim2d.github.io/nim2d/api/filesystem Initializes a new Filesystem object. The source directory is set to the program's base path, and no save identity is configured initially. ```nim proc newFilesystem(): Filesystem ``` -------------------------------- ### newFilesystem Source: https://nim2d.github.io/nim2d/api/filesystem Creates a new Filesystem instance. The source directory is initialized to the program's base path, and no save identity is set initially. ```APIDOC ## newFilesystem Proc ``` proc newFilesystem(): Filesystem ``` Create a filesystem with the source directory set to the program's base path and no save identity yet. #### Returns `Filesystem` ``` -------------------------------- ### Get Clipboard Text Source: https://nim2d.github.io/nim2d/api/system Retrieves the current text content from the system clipboard. Returns an empty string if no text is present. ```nim proc getClipboardText(): string ``` -------------------------------- ### Initialize Audio System Source: https://nim2d.github.io/nim2d/api/audio Opens the audio device and mixer. This is called once by `newNim2d`. If no audio device is available, it safely leaves audio off. ```nim proc initAudio(nim2d: Nim2d) ``` -------------------------------- ### Load and Play Audio Sources Source: https://nim2d.github.io/nim2d/audio Load music as a streaming source and a sound effect as a static source. Set music to loop and play it. ```nim let music = n2d.newSource("music.ogg", stStream) let shot = n2d.newSource("shot.wav", stStatic) music.setLooping(true) music.play() ``` -------------------------------- ### Create and Evaluate Bezier Curves Source: https://nim2d.github.io/nim2d/math Define a `BezierCurve` using control points. Use `evaluate` to get a point at a specific parameter (0-1), `render` to sample the curve into points for drawing, and `derivative` to get the tangent. ```nim let curve = newBezierCurve(@[(0.0, 0.0), (120.0, 200.0), (300.0, 40.0)]) let mid = curve.evaluate(0.5) # the point halfway along nim2d.line(curve.render(40)) # draw it ``` -------------------------------- ### Begin Contacts Function Source: https://nim2d.github.io/nim2d/api/physics Returns a sequence of Contact objects representing pairs of bodies that have started touching during the last physics update. Useful for detecting new collisions. ```nim proc beginContacts(w: World): seq[Contact] ``` -------------------------------- ### Initialize SceneManager and Push First Scene Source: https://nim2d.github.io/nim2d/scene Demonstrates how to initialize a SceneManager with the Nim2D engine and push the initial scene onto the stack. This setup ensures the manager is ready before the first scene's enter method is called. ```nim var scenes: SceneManager # ... your scene types and their methods ... scenes = newSceneManager(n2d) scenes.push(TitleScene()) n2d.play() ``` -------------------------------- ### frameCount Source: https://nim2d.github.io/nim2d/api/animation Get the total number of frames in the animation. ```APIDOC ## frameCount ### Description How many frames the animation runs through. ### Parameters - `anim` (`Animation`) ### Returns `int` ``` -------------------------------- ### currentFrame Source: https://nim2d.github.io/nim2d/api/animation Get the index of the currently displayed frame. ```APIDOC ## currentFrame ### Description The index of the frame showing now, counting from zero. ### Parameters - `anim` (`Animation`) ### Returns `int` ``` -------------------------------- ### quad Source: https://nim2d.github.io/nim2d/api/animation Get the current frame of an animation as a Quad. ```APIDOC ## quad ### Description The current frame as a `Quad`. ### Parameters - `anim` (`Animation`) ### Returns `Quad` ``` -------------------------------- ### Define a Title Scene Source: https://nim2d.github.io/nim2d/scene Example of defining a Scene object for a title screen. It includes methods for initialization (enter), frame updates (update), drawing (draw), and input handling (keydown). ```nim import nim2d import nim2d/scene type TitleScene = ref object of Scene t: float method enter(s: TitleScene, n: Nim2d) = s.t = 0.0 method update(s: TitleScene, n: Nim2d, dt: float) = s.t += dt method draw(s: TitleScene, n: Nim2d) = n.clear(14, 16, 28) n.print("press Enter to play", 200, 280) method keydown(s: TitleScene, n: Nim2d, key: Key) = if key == Key.enter: scenes.switch(PlayScene()) ``` -------------------------------- ### translation Source: https://nim2d.github.io/nim2d/api/physics Gets the current translation of a prismatic joint. ```APIDOC ## translation ### Description Gets the current translation of a prismatic joint. ### Method ```nim proc translation(j: Joint): float ``` ### Parameters #### Path Parameters - **j** (Joint) - Description: The prismatic joint. #### Returns `float` - The current translation of the joint. ``` -------------------------------- ### angle Source: https://nim2d.github.io/nim2d/api/physics Gets the current angle of a revolute joint. ```APIDOC ## angle ### Description Gets the current angle of a revolute joint. ### Method ```nim proc angle(j: Joint): float ``` ### Parameters #### Path Parameters - **j** (Joint) - Description: The revolute joint. #### Returns `float` - The current angle of the joint. ``` -------------------------------- ### Create a New Camera Source: https://nim2d.github.io/nim2d/api/camera Initializes a new Camera object. Defaults to the origin (0,0) with no zoom or rotation. ```nim proc newCamera(x = 0.0; y = 0.0; scale = 1.0; rotation = 0.0): Camera ``` -------------------------------- ### gamepadAxis Source: https://nim2d.github.io/nim2d/api/gamepad Gets the current value of a gamepad axis. ```APIDOC ## gamepadAxis ### Description Axis value from -1 to 1 (triggers run 0 to 1). ### Parameters - `id` (GamepadId) - The ID of the gamepad. - `axis` (GamepadAxis) - The axis to query. ### Returns float - The value of the axis, ranging from -1.0 to 1.0 (or 0.0 to 1.0 for triggers). ``` -------------------------------- ### Create and Use a Custom Shader (GLSL/SPIR-V/MSL) Source: https://nim2d.github.io/nim2d/drawing Replace the fragment stage with a custom shader. Use `staticRead` to load SPIR-V and MSL blobs. The `send` method passes uniform data. Call `setShader` before drawing and `setShader()` to reset. ```nim const spv = staticRead("plasma.spv") const msl = staticRead("plasma.metal") let effect = n2d.newShader(spv, msl, uniformFloats = 4) n2d.draw = proc(nim2d: Nim2d) = effect.send([time.float32, w, h, 0]) nim2d.setShader(effect) nim2d.rectangle(0, 0, w, h, true) nim2d.setShader() ``` -------------------------------- ### getDesktopDimensions Source: https://nim2d.github.io/nim2d/api/window Gets the desktop resolution of the primary display. ```APIDOC ## getDesktopDimensions ### Description The desktop resolution of the primary display. ### Returns - **tuple[w, h: int32]** - A tuple containing the width and height of the desktop resolution. ``` -------------------------------- ### newThread Source: https://nim2d.github.io/nim2d/api/thread Starts a new background thread that executes a given procedure. The procedure must be a top-level proc marked with {.thread.} and cannot capture any variables. ```APIDOC ## newThread ### Description Starts a thread running the provided procedure `fn`. ### Parameters * `fn` (`proc () {.thread, nimcall.}`) - The procedure to run in the new thread. Must be a top-level proc with the `{.thread.}` pragma. ### Returns `Thread2d` - A handle to the newly created thread. ``` -------------------------------- ### Nim Release Build Source: https://nim2d.github.io/nim2d/shipping Use this command for a standard release build. It enables optimizations, sets panics to 'on' for clearer error messages, and strips debug symbols to reduce binary size. ```nim $ nim c -d:release --panics:on -d:strip mygame.nim ``` -------------------------------- ### getSize Source: https://nim2d.github.io/nim2d/api/window Gets the size of the drawable area in pixels. ```APIDOC ## getSize ### Description The size of the drawable area in pixels. ### Parameters - **nim2d** (Nim2d) - Description not available ### Returns - **tuple[w, h: int32]** - A tuple containing the width and height of the drawable area. ``` -------------------------------- ### getHeight Source: https://nim2d.github.io/nim2d/api/window Gets the height of the drawable area in pixels. ```APIDOC ## getHeight ### Description The height of the drawable area in pixels. ### Parameters - **nim2d** (Nim2d) - Description not available ### Returns - **int32** - The height of the drawable area in pixels. ``` -------------------------------- ### getWidth Source: https://nim2d.github.io/nim2d/api/window Gets the width of the drawable area in pixels. ```APIDOC ## getWidth ### Description The width of the drawable area in pixels. ### Parameters - **nim2d** (Nim2d) - Description not available ### Returns - **int32** - The width of the drawable area in pixels. ``` -------------------------------- ### startTextInput Source: https://nim2d.github.io/nim2d/api/keyboard Initiates the reception of text input events, allowing the application to capture typed characters. ```APIDOC ## startTextInput ### Description Initiates the reception of text input events, allowing the application to capture typed characters. ### Parameters * `nim2d` (Nim2d) - The Nim2d instance to associate with text input events. ``` -------------------------------- ### userData (get) Source: https://nim2d.github.io/nim2d/api/physics Retrieves the integer tag associated with a body. ```APIDOC ## userData (get) ### Description Retrieves the integer tag associated with a body. ### Method ```nim proc userData(b: Body): int ``` ### Parameters #### Path Parameters - **b** (Body) - Description: The body to query. #### Returns `int` - The integer tag set with `userData=`, or 0 if none was set. ``` -------------------------------- ### count Source: https://nim2d.github.io/nim2d/api/particlesystem Gets the current number of alive particles in the system. ```APIDOC ## count ### Description How many particles are alive right now. ### Signature ```nim proc count(ps: ParticleSystem): int ``` ### Parameters * `ps` (`ParticleSystem`) - The particle system to query. ### Returns `int` - The number of currently alive particles. ``` -------------------------------- ### Initialize Scheduler and Update Loop Source: https://nim2d.github.io/nim2d/schedule Import the schedule module and initialize a Scheduler. Update the scheduler once per frame with the delta time (dt) in your main update loop. ```nim import nim2d import nim2d/schedule let sched = newScheduler() n2d.update = proc(nim2d: Nim2d, dt: float) = sched.update(dt) ``` -------------------------------- ### Configure and Update a Particle System Source: https://nim2d.github.io/nim2d/drawing Set up a particle system for effects like smoke or fire. Configure emission rate, lifetime, speed, direction, acceleration, sizes, and colors. The system needs to be updated every frame. ```nim let ps = newParticleSystem() ps.setEmissionRate(200) ps.setParticleLifetime(0.5, 1.2) ps.setSpeed(100, 260) ps.setDirection(-PI / 2) ps.setSpread(0.6) ps.setLinearAcceleration(0, 300) ps.setSizes(8, 1) ps.setColors((255'u8, 200'u8, 80'u8, 255'u8), (255'u8, 60'u8, 40'u8, 0'u8)) ``` -------------------------------- ### Get Texture Height Source: https://nim2d.github.io/nim2d/api/image Retrieves the height of the texture in pixels. ```nim proc getHeight(t: Texture): int32 ``` -------------------------------- ### Get Texture Width Source: https://nim2d.github.io/nim2d/api/image Retrieves the width of the texture in pixels. ```nim proc getWidth(t: Texture): int32 ``` -------------------------------- ### Build Nim Game as GUI Application on Windows Source: https://nim2d.github.io/nim2d/shipping Use the `--app:gui` flag to build your Nim game as a windowed application without a console on Windows. This flag is specific to Windows and has no effect on other operating systems. ```bash $ nim c -d:release --panics:on -d:strip --app:gui mygame.nim ``` -------------------------------- ### Create New ParticleSystem Source: https://nim2d.github.io/nim2d/api/particlesystem Initializes a new particle system. Optionally takes a texture for particles and sets the maximum number of particles. ```nim proc newParticleSystem(texture: Texture = nil; maxParticles = 2000): ParticleSystem ``` -------------------------------- ### Get ImageData Height Source: https://nim2d.github.io/nim2d/api/imagedata Retrieves the height of the ImageData pixel buffer. ```nim proc getHeight(d: ImageData): int32 ``` -------------------------------- ### Get ImageData Width Source: https://nim2d.github.io/nim2d/api/imagedata Retrieves the width of the ImageData pixel buffer. ```nim proc getWidth(d: ImageData): int32 ``` -------------------------------- ### Create a new Scheduler Source: https://nim2d.github.io/nim2d/api/schedule Creates an empty scheduler. Advance it once per frame with `update`, and add timers with `after`, `every` and `during`. ```nim proc newScheduler(): Scheduler ``` -------------------------------- ### setColors Source: https://nim2d.github.io/nim2d/api/particlesystem Sets the start and end colors for particles, which fade over their lifetime. ```APIDOC ## setColors ### Description Each particle's color fades from start to end over its life. Fading the end alpha to 0 makes particles dissolve. ### Signature ```nim proc setColors(ps: ParticleSystem; startColor, endColor: Color) ``` ### Parameters * `ps` (`ParticleSystem`) - The particle system to configure. * `startColor` (`Color`) - The initial color of the particle. * `endColor` (`Color`) - The final color of the particle. ``` -------------------------------- ### Check Audio Availability Source: https://nim2d.github.io/nim2d/api/audio Returns true if an audio device was successfully opened. This is false on machines without sound output. ```nim proc audioAvailable(nim2d: Nim2d): bool ``` -------------------------------- ### setSizes Source: https://nim2d.github.io/nim2d/api/particlesystem Sets the start and end sizes for particles, which fade over their lifetime. ```APIDOC ## setSizes ### Description Each particle's size fades from start to end over its life. ### Signature ```nim proc setSizes(ps: ParticleSystem; startSize, endSize: float) ``` ### Parameters * `ps` (`ParticleSystem`) - The particle system to configure. * `startSize` (`float`) - The initial size of the particle. * `endSize` (`float`) - The final size of the particle. ``` -------------------------------- ### Get Total Frame Count Source: https://nim2d.github.io/nim2d/api/animation Returns the total number of frames in the animation. ```nim proc frameCount(anim: Animation): int ``` -------------------------------- ### Get Body Velocity Source: https://nim2d.github.io/nim2d/api/physics Retrieves the current linear velocity (x, y) of a body. ```nim proc velocity(b: Body): tuple[x, y: float] ``` -------------------------------- ### Get Body Angle Source: https://nim2d.github.io/nim2d/api/physics Retrieves the current rotation angle of a body in radians. ```nim proc angle(b: Body): float ``` -------------------------------- ### Get Texture Dimensions Source: https://nim2d.github.io/nim2d/api/image Retrieves both the width and height of the texture in pixels as a tuple. ```nim proc getDimensions(t: Texture): tuple[w, h: int32] ``` -------------------------------- ### Load New Sound Source Source: https://nim2d.github.io/nim2d/api/audio Loads a sound from a file, supporting WAV, OGG, MP3, FLAC, and tracker formats. If audio is off, controls on the returned source will do nothing. ```nim proc newSource(nim2d: Nim2d; filename: string; kind: SourceType = stStatic): Source ``` -------------------------------- ### Get Font Height Source: https://nim2d.github.io/nim2d/api/font Returns the total line height of the font in pixels. ```nim proc getHeight(font: Font): int ``` -------------------------------- ### Create Physics World and Bodies Source: https://nim2d.github.io/nim2d/physics Initialize a new physics world with gravity and add static and dynamic bodies with specified shapes and properties. Use meters for simulation units and scale for drawing. ```nim let world = newWorld(0.0, 10.0) let ground = world.newBody(8.0, 11.0, btStatic) ground.addBox(8.0, 0.5) let box = world.newBody(8.0, 2.0, btDynamic) box.addBox(0.5, 0.5, restitution = 0.3) ``` -------------------------------- ### getOS Source: https://nim2d.github.io/nim2d/api/system Retrieves the name of the operating system. ```APIDOC ## getOS ### Description The name of the operating system, like "macOS", "Linux" or "Windows". ### Returns `string` ``` -------------------------------- ### Get ImageData Dimensions Source: https://nim2d.github.io/nim2d/api/imagedata Retrieves both the width and height of the ImageData pixel buffer. ```nim proc getDimensions(d: ImageData): tuple[w, h: int32] ``` -------------------------------- ### Create a New SceneManager Source: https://nim2d.github.io/nim2d/api/scene Initialize a SceneManager, optionally with an initial scene. This also hooks the manager into the engine's update, draw, and input callbacks. ```nim proc newSceneManager(nim2d: Nim2d; initial: Scene = nil): SceneManager ``` -------------------------------- ### Open URL in Browser Source: https://nim2d.github.io/nim2d/api/system Attempts to open the specified URL in the system's default web browser. Returns false if the operation fails. ```nim proc openURL(url: string): bool ``` -------------------------------- ### Get Quad from SpriteSheet Source: https://nim2d.github.io/nim2d/api/animation Retrieves a specific cell from the SpriteSheet as a Quad, ready for drawing. ```APIDOC ## quad ### Description The cell at (col, row) as a `Quad`, ready to hand to a texture's `draw`. Columns and rows count from zero, left to right and top to bottom. ### Parameters * `sheet` (`SpriteSheet`) * `col` (`int`) * `row` (`int`) ### Returns `Quad` ``` -------------------------------- ### SpriteSheet Frame Count Source: https://nim2d.github.io/nim2d/api/animation Gets the total number of frames (cells) available in a SpriteSheet. ```APIDOC ## frameCount ### Description How many cells the sheet holds, columns times rows. ### Parameters * `sheet` (`SpriteSheet`) ### Returns `int` ``` -------------------------------- ### follow Source: https://nim2d.github.io/nim2d/api/camera Smoothly eases the camera towards a target position over a frame, with adjustable speed and delta time. ```APIDOC ## follow ### Description Ease the camera toward `target` over this frame instead of snapping to it, which gives a smooth trailing follow. `speed` sets how quickly it catches up, with higher being snappier. The step is scaled by `dt`, so the motion looks the same whatever the frame rate. ### Parameters * `cam` (Camera) * `target` (Vec2) * `dt` (float) * `speed` (auto) ``` -------------------------------- ### Load Tilesets Source: https://nim2d.github.io/nim2d/api/tilemap Loads each tileset's PNG into an image, resolving its path relative to the base directory. Skips tilesets without a path. Points every layer at its tileset image for self-contained drawing. ```nim proc loadTilesets(project: LdtkProject; nim2d: Nim2d; baseDir: string) ``` -------------------------------- ### Get Current Particle Count Source: https://nim2d.github.io/nim2d/api/particlesystem Returns the number of particles that are currently alive in the system. ```nim proc count(ps: ParticleSystem): int ``` -------------------------------- ### Get Processor Count Source: https://nim2d.github.io/nim2d/api/system Returns the number of logical CPU cores available on the system. ```nim proc getProcessorCount(): int ``` -------------------------------- ### Check Linked Libraries on macOS with otool Source: https://nim2d.github.io/nim2d/shipping Use the `otool -L` command to inspect the dynamic libraries your macOS executable is linked against. This helps identify the paths where the system expects to find libraries like SDL3. ```bash $ otool -L mygame /opt/homebrew/opt/sdl3/lib/libSDL3.0.dylib ... /opt/homebrew/opt/sdl3_image/lib/libSDL3_image.0.dylib ... ... ``` -------------------------------- ### tell Source: https://nim2d.github.io/nim2d/api/audio Retrieves the current playback position of the source in seconds. ```APIDOC ## tell ### Description The current playback position in seconds. ### Parameters - `src` (`Source`) ### Returns `float` ``` -------------------------------- ### setFullscreen Source: https://nim2d.github.io/nim2d/api/window Switches between fullscreen and windowed modes. ```APIDOC ## setFullscreen ### Description Switch between fullscreen and windowed. Fullscreen covers the whole display at its native resolution; `getWidth`/`getHeight` then report that size. On macOS this is a borderless full-display fullscreen, so it fills the screen under the menu bar or notch instead of leaving a strip. ### Parameters - **nim2d** (Nim2d) - Description not available - **fullscreen** (bool) - Whether to enable fullscreen mode. ``` -------------------------------- ### Get Body Position Source: https://nim2d.github.io/nim2d/api/physics Retrieves the current center position (x, y) of a body in the physics world. ```nim proc position(b: Body): tuple[x, y: float] ``` -------------------------------- ### createDirectory Source: https://nim2d.github.io/nim2d/api/filesystem Creates a directory and any missing parent directories within the save directory. ```APIDOC ## createDirectory ### Description Creates a directory and any missing parents inside the save directory. ### Parameters - **fs** (Filesystem) - Description not provided - **dir** (string) - The name of the directory to create. ``` -------------------------------- ### Push a Scene onto the Stack Source: https://nim2d.github.io/nim2d/api/scene Use push to add a new scene on top of the current one. The new scene's enter method is called, and the underlying scene continues to draw. ```nim proc push(mgr: SceneManager; scene: Scene) ``` -------------------------------- ### Get the Number of Scenes on the Stack Source: https://nim2d.github.io/nim2d/api/scene The count procedure returns the number of scenes currently in the stack. ```nim proc count(mgr: SceneManager): int ``` -------------------------------- ### duration Source: https://nim2d.github.io/nim2d/api/audio Gets the length of an audio source in seconds. Returns -1 if the duration is unknown or infinite. ```APIDOC ## duration ### Description Length of the sound in seconds, or -1 if unknown or infinite. ### Parameters * `src` (`Source`) ### Returns `float` ``` -------------------------------- ### Get Current Playback Position Source: https://nim2d.github.io/nim2d/api/audio Returns the current playback position of the sound source in seconds. ```nim proc tell(src: Source): float ``` -------------------------------- ### read Source: https://nim2d.github.io/nim2d/api/filesystem Reads the entire content of a file as a string. The search order is save directory, then source directory, then mounted directories. Raises an IOError if the file is not found. ```APIDOC ## read Proc ``` proc read(fs: Filesystem; name: string): string ``` Read a whole file as a string, searching the save directory, then the source directory and mounts. Raises IOError if not found. #### Parameters * `fs` (`Filesystem`) * `name` (`string`) #### Returns `string` ``` -------------------------------- ### Get Current Frame Index Source: https://nim2d.github.io/nim2d/api/animation Returns the index of the currently displayed animation frame. Indices are zero-based. ```nim proc currentFrame(anim: Animation): int ``` -------------------------------- ### window_shown Source: https://nim2d.github.io/nim2d/api/nim2d Set the callback for the window becoming visible. This function registers a procedure to be called when the application window is shown. ```APIDOC ## window_shown ### Description Set the callback for the window becoming visible. ### Parameters - `n2d` (Nim2d) - The Nim2d instance. - `p` (proc (nim2d: Nim2d)) - The callback procedure to execute when the window is shown. ``` -------------------------------- ### Get Level by Identifier Source: https://nim2d.github.io/nim2d/api/tilemap Retrieves the level with the specified identifier from the project. Returns nil if no level matches. ```nim proc level(project: LdtkProject; identifier: string): LdtkLevel ``` -------------------------------- ### Load LDtk Project Source: https://nim2d.github.io/nim2d/tilemap Loads an LDtk project file and its associated tileset images. Ensure the .ldtk file is in the application directory. Levels can be accessed by index or name. ```nim import nim2d import nim2d/tilemap let project = loadLdtk(n2d, getAppDir() / "cave.ldtk") let level = project.levels[0] # or project.level("Cave") ``` -------------------------------- ### Clipboard and URL Operations Source: https://nim2d.github.io/nim2d/system Interact with the system clipboard using `setClipboardText` and open links in the default browser with `openURL`. Ensure the clipboard is available and the URL is valid. ```nim setClipboardText("copied from the game") ``` -------------------------------- ### Create a New SpriteBatch Source: https://nim2d.github.io/nim2d/api/spritebatch Initializes a new SpriteBatch for drawing copies of a given texture. This is the first step before adding sprites to the batch. ```nim proc newSpriteBatch(image: Texture): SpriteBatch ``` -------------------------------- ### newNim2d (with background and options) Source: https://nim2d.github.io/nim2d/api/nim2d Opens a new window for the Nim2D application with a specified title, position, dimensions, and background color. Supports advanced options like high DPI, anti-aliasing, and stencil buffer. ```APIDOC ## proc newNim2d(title: string; x, y, width, height: cint; background: Color; highDpi = false; aa: int32 = 1; stencil = false): Nim2d ### Description Open a window and set up the engine. (x, y) is the window position and `background` the color it clears to each frame. `highDpi` asks for a backing buffer at the display's real pixel resolution, `aa = 2` renders each frame at twice the size and scales it down for anti-aliasing, and `stencil` builds the stencil machinery that `stencil` masking needs. ### Parameters #### Path Parameters * `title` (string) - * `x` (cint) - * `y` (cint) - * `width` (cint) - * `height` (cint) - * `background` (Color) - * `highDpi` (auto) - * `aa` (int32) - * `stencil` (auto) - #### Returns `Nim2d` ### Source src/nim2d.nim:254 ``` -------------------------------- ### Get Number Tween Value Source: https://nim2d.github.io/nim2d/api/tween Returns the current interpolated number value. Read this each frame to animate a property. ```nim func value(tw: Tween): float ``` -------------------------------- ### Dialogue Module Overview Source: https://nim2d.github.io/nim2d/api/dialogue This section provides an overview of the Dialogue module's core components and how to use them. It explains the structure of a conversation script, the rendering options, and the customization capabilities. ```APIDOC ## Dialogue Module This is an opt-in module, imported on its own with `import nim2d/dialogue`. The core engine does not pull it in. A conversation is a `Script`: nodes keyed by id, each with a speaker, an optional portrait, one or more pages of text, and choices that branch to other nodes. You build a script as plain Nim data (a parser for a file format could target the same shape later), hand it to `newDialogue`, and `start` it. Each frame the game calls `update` and `draw`, and routes keys through `handleKey`. Text is rich. A page is a string with a small markup the renderer understands: `*italic*` and `**bold**` as in markdown, plus bracket tags closed with `[/]` and nestable: `[b]` bold, `[i]` italic, `[o]` a per-character outline (a border on the glyphs, not the box), `[#ffcc00]` a hex color and `[gold]` a palette name. So `"The [#ff5555]dragon[/] **roars**. *You* feel [o]afraid[/]."` works. Two ways to render. The simple path is a `Style` record (a font set, a box, colors, padding) feeding the built-in renderer. The advanced path sets `Hooks` to take over the box, the text or the choices, any left nil falling back to the default, so a game can lay the message out however it likes while keeping the markup. ``` -------------------------------- ### Create a new canvas the size of the window Source: https://nim2d.github.io/nim2d/api/canvas This procedure creates an off-screen render target that matches the current window's dimensions. It's a convenient way to set up a canvas for full-window rendering. ```nim proc newCanvas(nim2d: Nim2d): Canvas ``` -------------------------------- ### Get Number Tween Progress Source: https://nim2d.github.io/nim2d/api/tween Returns the raw time fraction (0 to 1) of the tween before easing is applied. ```nim func progress(tw: Tween): float ``` -------------------------------- ### Get Entities by Identifier Source: https://nim2d.github.io/nim2d/api/tilemap Retrieves all entity instances with the given identifier across the level's entity layers. ```nim proc entities(level: LdtkLevel; identifier: string): seq[LdtkEntity] ``` -------------------------------- ### Get Font Ascent Source: https://nim2d.github.io/nim2d/api/font Retrieves the distance the font extends above the baseline in pixels. For bitmap fonts, this is the glyph height. ```nim proc getAscent(font: Font): int ``` -------------------------------- ### openGamepad Source: https://nim2d.github.io/nim2d/api/gamepad Opens a specific gamepad controller by its ID. ```APIDOC ## openGamepad ### Description Open a controller. The event loop calls this when one connects, so games normally never do. ### Parameters - `id` (GamepadId) - The ID of the gamepad to open. ``` -------------------------------- ### Get Pixel Color Source: https://nim2d.github.io/nim2d/api/imagedata Retrieves the Color of a specific pixel at coordinates (x, y). Raises IndexDefect if coordinates are out of bounds. ```nim proc getPixel(d: ImageData; x, y: int32): Color ``` -------------------------------- ### Push and Pop Scenes for Pausing Source: https://nim2d.github.io/nim2d/scene Illustrates using push and pop operations on the SceneManager. Pushing a PauseScene overlays the current game scene, and popping it returns to the game. ```nim scenes.push(PauseScene()) # over the game scenes.pop() # back to the game ``` -------------------------------- ### setTitle Source: https://nim2d.github.io/nim2d/api/window Sets the window's title. ```APIDOC ## setTitle ### Description Sets the window's title. ### Parameters - **nim2d** (Nim2d) - Description not available - **title** (string) - The desired title for the window. ``` -------------------------------- ### Get Revolute Joint Angle Source: https://nim2d.github.io/nim2d/api/physics Retrieves the current angular position of a revolute joint. This value represents the angle of the hinge. ```nim proc angle(j: Joint): float ``` -------------------------------- ### dispatch Source: https://nim2d.github.io/nim2d/api/events Routes a single SDL event to the matching engine callback. The 'play' loop invokes this for every pending event each frame. ```APIDOC ## dispatch ### Description Routes one SDL event to the matching engine callback. The `play` loop calls this for every pending event each frame. ### Parameters #### Path Parameters * `nim2d` (Nim2d) - Required - The Nim2d instance. * `evt` (SDL_Event) - Required - The SDL event to dispatch. ``` -------------------------------- ### Get Vector Tween Value Source: https://nim2d.github.io/nim2d/api/tween Returns the current interpolated Vec2 position. Use this to update an object's location. ```nim func value(tw: VecTween): Vec2 ``` -------------------------------- ### Get Vector Tween Progress Source: https://nim2d.github.io/nim2d/api/tween Returns the raw time fraction (0 to 1) of the vector tween before easing is applied. ```nim func progress(tw: VecTween): float ``` -------------------------------- ### Create Shader from Precompiled Blobs Source: https://nim2d.github.io/nim2d/api/shader Compile a fragment shader from precompiled SPIR-V (for Vulkan) and MSL (for Metal) blobs. This allows for cross-platform shader compatibility. The appropriate blob is selected based on the active backend. Ensure Vulkan is forced on Windows if using Direct3D 12 is not desired. ```nim proc newShader(nim2d: Nim2d; spirv, msl: string; uniformFloats = 0): Shader ``` -------------------------------- ### Get Entity Color Field Source: https://nim2d.github.io/nim2d/api/tilemap Retrieves a Color field from an entity, returning a default value if the field is missing or unset. ```nim proc getColor(e: LdtkEntity; field: string; default = (255'u8, 255'u8, 255'u8, 255'u8)): Color ``` -------------------------------- ### Get Entity Bool Field Source: https://nim2d.github.io/nim2d/api/tilemap Retrieves a Bool field from an entity, returning a default value if the field is missing or unset. ```nim proc getBool(e: LdtkEntity; field: string; default = false): bool ``` -------------------------------- ### Set Filesystem Identity (App Only) Source: https://nim2d.github.io/nim2d/api/filesystem Configures the save directory using only the application name, with an empty organization name. This is a convenience overload for setting the identity. ```nim proc setIdentity(fs: Filesystem; app: string) ``` -------------------------------- ### Get Entity Float Field Source: https://nim2d.github.io/nim2d/api/tilemap Retrieves a Float field from an entity, returning a default value if the field is missing or unset. ```nim proc getFloat(e: LdtkEntity; field: string; default = 0.0): float ```