User Interface
This section contains all functions that involve directly interacting with the user, be that by showing a window, checking the state of a key, or placing data onto the users clipboard. These handle generic input such as from the keyboard, and also generic output such as an alert box.
Window management notes:
- You can only have one NVGT window showing at a time.
- without an nvgt window, there is no way to capture keyboard and mouse input from the user.
- It is strongly advised to always put
wait(5);in your main loops. This prevents your game from hogging the CPU, and also prevents weird bugs with the game window sometimes freezing etc.
Classes
game_window
A window on the screen, with the settings of the operating system's windows and simple drawing of text, shapes and graphics.
game_window(const string&in title, uint w, uint h, uint flags = 0);
Arguments:
const string&in title: the title of the window, which screen readers speak when it gains focus.
uint w: the width of the window in screen coordinates.
uint h: the height of the window in screen coordinates.
uint flags = 0: a combination of values from the window_flags enum, such as WINDOW_FLAG_RESIZABLE.
Remarks:
Most games only need the main window, which show_window() creates and returns and the global window property refers to. NVGT's keyboard and mouse functions, is_window_active() and the other global window functions all work with the main window, which is drawn automatically every time wait() or refresh_window() is called. Creating a game_window directly makes an additional window, which must be drawn with present() and doesn't receive the main window's special handling.
Settings methods return true on success and false when the operating system doesn't support or refused the change. Positions and sizes are in screen coordinates, which on high resolution displays can differ from pixels, see pixel_density.
Drawing is done with clear(), the draw_ methods and render_graphic(), which draw into the window's renderer and are shown on the screen when the window is next presented. Windows start with a default font, so text can be drawn right away, or a different one can be given to the window as in @window.font = get_font("arial", 24);. If the platform offers no default font the font property is null and text isn't drawn until one is set.
On Linux, the main window is always created fullscreen at this time.
Example:
void main() {
game_window@ w = show_window("Drawing example");
w.clear(0, 0, 64);
w.draw_text("Hello from NVGT!", 20, 20, 255, 255, 255);
w.draw_rect(20, 70, 200, 40, 255, 128, 0, true);
w.draw_circle(320, 300, 60, 0, 200, 0, true);
w.draw_line(0, 400, 640, 400, 255, 255, 255);
uint64 size = w.measure_text("Hello from NVGT!");
screen_reader_output("The greeting is " + (size >> 32) + " pixels wide. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) wait(5);
}
Methods
clear
Fill the window with a color, erasing what was drawn.
bool game_window::clear(uint r, uint g, uint b);
Arguments:
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
bool: true on success, false if the window has no renderer.
Remarks:
Drawing usually starts with this each frame.
destroy_surface
Destroy the window's software surface.
bool game_window::destroy_surface();
Returns:
bool: true on success, false otherwise.
Remarks:
Most programs never need this. A window can be drawn to in two different ways. NVGT's own drawing methods, such as draw_rect() and draw_text(), use the window's renderer, which is the usual and recommended way. The other way, rarely used, is the software surface, a block of ordinary memory holding the window's pixels that a program fills in by itself and then copies to the screen with update_surface(). The surface is created the first time something asks for it, and a window can't use both the surface and the renderer at once. This function throws the surface away and frees its memory, after which the window carries on as usual. Nothing is changed on screen and the window remains open, and the renderer and the drawing methods that use it are unaffected. A fresh surface is made if one is requested again, and it must be, as an existing one becomes invalid whenever the window is resized. Calling it when the window has no surface is harmless.
draw_circle
Draw a circle.
void game_window::draw_circle(float cx, float cy, int radius, uint r, uint g, uint b, bool filled = false);
Arguments:
- float cx: the horizontal position of the center.
- float cy: the vertical position of the center.
- int radius: the radius.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
- bool filled = false: whether to fill the circle rather than only drawing its outline.
draw_line
Draw a line.
void game_window::draw_line(float x1, float y1, float x2, float y2, uint r, uint g, uint b);
Arguments:
- float x1: the horizontal position of the start.
- float y1: the vertical position of the start.
- float x2: the horizontal position of the end.
- float y2: the vertical position of the end.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
draw_menu
Draw a simple vertical menu, with each item centered on a position and the selected item highlighted.
void game_window::draw_menu(array<string>@ items, float x, float y);
Arguments:
- array
@ items: the text of the items. The selected item starts with an asterisk, which isn't drawn. - float x: the horizontal position the items are centered on.
- float y: the vertical position of the top of the first item.
Remarks:
This gives sighted players something to see while a menu is spoken. Nothing is drawn if the window has no font.
draw_rect
Draw a rectangle.
void game_window::draw_rect(float x, float y, float w, float h, uint r, uint g, uint b, bool filled = false);
Arguments:
- float x: the horizontal position of the top left corner.
- float y: the vertical position of the top left corner.
- float w: the width.
- float h: the height.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
- bool filled = false: whether to fill the rectangle rather than only drawing its outline.
draw_text
Draw a line of text with the window's font.
void game_window::draw_text(const string&in text, float x, float y, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw.
- float x: the horizontal position of the text's top left corner.
- float y: the vertical position of the text's top left corner.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Remarks:
Nothing is drawn if the window has no font, see the font property.
draw_text_wrapped
Draw text with the window's font, wrapping it onto further lines when it becomes too wide.
void game_window::draw_text_wrapped(const string&in text, float x, float y, int wrap_width, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw. Newlines start new lines.
- float x: the horizontal position of the text's top left corner.
- float y: the vertical position of the text's top left corner.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Remarks:
The alignment of the lines is the font's wrap_alignment.
flash
Flash the window's taskbar button to get the user's attention.
bool game_window::flash(uint operation);
Arguments:
- uint operation: what to do, a value of the window_flash_operation enum.
Returns:
bool: true on success, false otherwise.
Remarks:
This is useful to let a player know something happened while they were in another program, such as a match being found.
get_aspect_ratio
Get the range of aspect ratios the window's client area is kept within when resized.
bool game_window::get_aspect_ratio(float&out min_aspect, float&out max_aspect) const;
Arguments:
- float&out min_aspect: receives the smallest width divided by height, or 0 for no limit.
- float&out max_aspect: receives the largest width divided by height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
get_borders_size
Get the size of the window's decorations, such as its title bar, on each side of the client area.
bool game_window::get_borders_size(int&out top, int&out left, int&out bottom, int&out right) const;
Arguments:
- int&out top: receives the size of the top border, which includes the title bar.
- int&out left: receives the size of the left border.
- int&out bottom: receives the size of the bottom border.
- int&out right: receives the size of the right border.
Returns:
bool: true on success, false if the size isn't known, as can happen just after the window is created.
get_maximum_size
Get the largest size the window can be resized to.
bool game_window::get_maximum_size(int&out w, int&out h) const;
Arguments:
- int&out w: receives the maximum width, or 0 for no limit.
- int&out h: receives the maximum height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
get_minimum_size
Get the smallest size the window can be resized to.
bool game_window::get_minimum_size(int&out w, int&out h) const;
Arguments:
- int&out w: receives the minimum width, or 0 for no limit.
- int&out h: receives the minimum height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
get_position
Get the position of the window on the screen.
bool game_window::get_position(int&out x, int&out y) const;
Arguments:
- int&out x: receives the horizontal position of the window's top left corner, in screen coordinates.
- int&out y: receives the vertical position of the window's top left corner, in screen coordinates.
Returns:
bool: true on success, false otherwise.
get_size
Get the size of the window's client area, the part inside its borders.
bool game_window::get_size(int&out w, int&out h) const;
Arguments:
- int&out w: receives the width.
- int&out h: receives the height.
Returns:
bool: true on success, false otherwise.
Remarks:
The global get_window_width() and get_window_height() functions return the size of the main window.
get_size_in_pixels
Get the size of the window's client area in pixels, which on high resolution displays can be larger than its size in screen coordinates.
bool game_window::get_size_in_pixels(int&out w, int&out h) const;
Arguments:
- int&out w: receives the width in pixels.
- int&out h: receives the height in pixels.
Returns:
bool: true on success, false otherwise.
get_surface_vsync
Get the vertical sync of the window's software surface.
bool game_window::get_surface_vsync(int&out vsync) const;
Arguments:
- int&out vsync: receives the vertical sync, see set_surface_vsync().
Returns:
bool: true on success, false otherwise.
hide
Hide the window, removing it from the screen and the taskbar until it is shown again.
bool game_window::hide();
Returns:
bool: true on success, false otherwise.
maximize
Make the window as large as the screen allows, keeping its title bar and borders.
bool game_window::maximize();
Returns:
bool: true on success, false otherwise.
Remarks:
This only works for resizable windows.
measure_text
Measure how large a line of text is when drawn with the window's font.
uint64 game_window::measure_text(const string&in text) const;
Arguments:
- const string&in text: the text to measure.
Returns:
uint64: the width in the high 32 bits and the height in the low 32 bits, so size >> 32 is the width and size & 0xffffffff the height, or 0 if the window has no font.
measure_text_wrapped
Measure how large text is when drawn with draw_text_wrapped().
uint64 game_window::measure_text_wrapped(const string&in text, int wrap_width) const;
Arguments:
- const string&in text: the text to measure.
- int wrap_width: the width in pixels at which lines wrap.
Returns:
uint64: the width in the high 32 bits and the height in the low 32 bits, or 0 if the window has no font.
minimize
Minimize the window to the taskbar.
bool game_window::minimize();
Returns:
bool: true on success, false otherwise.
present
Show what has been drawn on the screen.
bool game_window::present();
Returns:
bool: true on success, false if the window has no renderer.
Remarks:
The main window is presented automatically when wait() or refresh_window() is called and something was drawn, so this is only needed for additional windows.
raise
Bring the window in front of other windows and give it the keyboard focus.
bool game_window::raise();
Returns:
bool: true on success, false otherwise.
Remarks:
Operating systems may refuse to take the focus from another program, and flash the window's taskbar button instead.
render_graphic
Draw an image.
bool game_window::render_graphic(graphic@ gfx, float x, float y);
Arguments:
- graphic@ gfx: the image to draw, such as one loaded with load_png() or rendered by a text_font.
- float x: the horizontal position of the image's top left corner.
- float y: the vertical position of the image's top left corner.
Returns:
bool: true on success, false otherwise.
restore
Restore a minimized or maximized window to its normal size and position.
bool game_window::restore();
Returns:
bool: true on success, false otherwise.
set_always_on_top
Set whether the window stays in front of other windows.
bool game_window::set_always_on_top(bool on_top);
Arguments:
- bool on_top: whether the window stays in front of other windows.
Returns:
bool: true on success, false otherwise.
set_aspect_ratio
Keep the window's client area within a range of aspect ratios when resized.
bool game_window::set_aspect_ratio(float min_aspect, float max_aspect);
Arguments:
- float min_aspect: the smallest width divided by height, or 0 for no limit.
- float max_aspect: the largest width divided by height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
Remarks:
For example, setting both to 16.0 / 9.0 keeps the window widescreen.
set_bordered
Set whether the window has a border and title bar.
bool game_window::set_bordered(bool bordered);
Arguments:
- bool bordered: whether the window has a border and title bar.
Returns:
bool: true on success, false otherwise.
set_fill_document
Set whether the window fills the whole page when running in a web browser.
bool game_window::set_fill_document(bool fill);
Arguments:
- bool fill: whether the window fills the whole page when running in a web browser.
Returns:
bool: true on success, false otherwise.
Remarks:
This does nothing at present. It only applies when a program runs inside a web page, which NVGT can't currently be compiled for, so on Windows, macOS, Linux and Android it always returns false and changes nothing. It exists in case NVGT gains WebAssembly support in the future, and if that never happens it may be removed, so there is no reason to use it in a game.
set_focusable
Set whether the window can receive the keyboard focus.
bool game_window::set_focusable(bool focusable);
Arguments:
- bool focusable: whether the window can receive the keyboard focus.
Returns:
bool: true on success, false otherwise.
set_fullscreen
Make the window fullscreen or return it to a normal window.
bool game_window::set_fullscreen(bool fullscreen);
Arguments:
- bool fullscreen: whether the window should be fullscreen.
Returns:
bool: true on success, false otherwise.
set_icon
Set the icon of the window, shown in its title bar and taskbar button.
bool game_window::set_icon(graphic@ icon);
Arguments:
- graphic@ icon: the image to use as the icon.
Returns:
bool: true on success, false otherwise.
set_keyboard_grab
Set whether the window grabs the keyboard, receiving system shortcuts such as Alt+Tab while it has the focus.
bool game_window::set_keyboard_grab(bool grabbed);
Arguments:
- bool grabbed: whether to grab the keyboard.
Returns:
bool: true on success, false otherwise.
Remarks:
Grabbing system shortcuts can stop screen reader users from leaving the game, so this should be used with great care.
set_maximum_size
Set the largest size the window can be resized to.
bool game_window::set_maximum_size(int w, int h);
Arguments:
- int w: the maximum width, or 0 for no limit.
- int h: the maximum height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
set_minimum_size
Set the smallest size the window can be resized to.
bool game_window::set_minimum_size(int w, int h);
Arguments:
- int w: the minimum width, or 0 for no limit.
- int h: the minimum height, or 0 for no limit.
Returns:
bool: true on success, false otherwise.
set_modal
Set whether the window is modal to the main window, keeping the user from interacting with the main window while it is shown.
bool game_window::set_modal(bool modal);
Arguments:
- bool modal: whether the window is modal to the main window, keeping the user from interacting with the main window while it is shown.
Returns:
bool: true on success, false otherwise.
set_mouse_grab
Set whether the window confines the mouse to itself.
bool game_window::set_mouse_grab(bool grabbed);
Arguments:
- bool grabbed: whether to confine the mouse to the window.
Returns:
bool: true on success, false otherwise.
set_mouse_relative_mode
Set whether the mouse is hidden and reports only how far it moves, rather than its position, which suits mouse look in first person games.
bool game_window::set_mouse_relative_mode(bool enabled);
Arguments:
- bool enabled: whether to enable relative mouse mode.
Returns:
bool: true on success, false otherwise.
Remarks:
The global mouse_relative_mode property does this for the main window.
set_opacity
Set how opaque the window is.
bool game_window::set_opacity(float opacity);
Arguments:
- float opacity: the opacity, from 0.0, invisible, to 1.0, fully opaque.
Returns:
bool: true on success, false if the operating system doesn't support window opacity.
set_position
Move the window.
bool game_window::set_position(int x, int y);
Arguments:
- int x: the new horizontal position of the window's top left corner, in screen coordinates measured from the left edge of the desktop.
- int y: the new vertical position of the window's top left corner, in screen coordinates measured from the top edge of the desktop.
Returns:
bool: true on success, false otherwise.
Remarks:
Positions are in screen coordinates rather than necessarily pixels, the same units as the window's size, where 0, 0 is the top left of the primary display. On high resolution displays a screen coordinate can cover more than one pixel. A window can be placed partly or wholly off the screen, and some systems, such as most Linux desktops using Wayland, don't allow programs to choose where their windows go, in which case this returns false.
set_progress_state
Set the state of the progress indicator shown on the window's taskbar button.
bool game_window::set_progress_state(uint state);
Arguments:
- uint state: a value of the window_progress_state enum.
Returns:
bool: true on success, false if the operating system has no such indicator.
Remarks:
This can show the progress of a download or level load while the game is in the background. See set_progress_value().
set_progress_value
Set how full the progress indicator on the window's taskbar button is.
bool game_window::set_progress_value(float value);
Arguments:
- float value: the progress, from 0.0 to 1.0.
Returns:
bool: true on success, false if the operating system has no such indicator.
Remarks:
This is only shown while the progress state is PROGRESS_STATE_NORMAL, PROGRESS_STATE_PAUSED or PROGRESS_STATE_ERROR.
set_resizable
Set whether the window can be resized by the user.
bool game_window::set_resizable(bool resizable);
Arguments:
- bool resizable: whether the window can be resized by the user.
Returns:
bool: true on success, false otherwise.
set_size
Resize the window's client area.
bool game_window::set_size(int w, int h);
Arguments:
- int w: the new width.
- int h: the new height.
Returns:
bool: true on success, false otherwise.
set_surface_vsync
Set the vertical sync of the window's software surface.
bool game_window::set_surface_vsync(int vsync);
Arguments:
- int vsync: 0 to disable vertical sync, 1 to synchronize with every refresh of the display, 2 with every second refresh and so on, or -1 for adaptive sync.
Returns:
bool: true on success, false otherwise.
set_title
Set the title of the window.
bool game_window::set_title(const string&in title);
Arguments:
- const string&in title: the new title.
Returns:
bool: true on success, false otherwise.
show
Show the window if it is hidden.
bool game_window::show();
Returns:
bool: true on success, false otherwise.
show_system_menu
Show the window's system menu, the one with commands such as move and close, at a position in the window.
bool game_window::show_system_menu(int x, int y);
Arguments:
- int x: the horizontal position of the menu relative to the window.
- int y: the vertical position of the menu relative to the window.
Returns:
bool: true on success, false if the operating system has no such menu.
sync
Wait for any pending changes to the window's state, such as a change of size, position or fullscreen, to be applied.
bool game_window::sync();
Returns:
bool: true on success, false otherwise.
Remarks:
Some operating systems apply such changes asynchronously, so this makes the window's properties up to date immediately. It returns false if the changes didn't complete within a short time.
update_surface
Copy the window's software surface to the screen.
bool game_window::update_surface();
Returns:
bool: true on success, false otherwise.
Remarks:
This is for software drawing to the window's surface rather than its renderer, which NVGT's drawing methods use. Most programs never need it, see destroy_surface() for how the two differ.
Properties
display_scale
The scale the user has chosen for content on the display the window is on, such as 1.5 for 150% scaling.
const float game_window::display_scale;
flags
The current state of the window as SDL window flags, which include the values of the window_flags enum.
const uint64 game_window::flags;
Remarks:
For example, (window.flags & WINDOW_FLAG_FULLSCREEN) != 0 tells whether the window is fullscreen.
font
The font text is drawn with by draw_text(), draw_text_wrapped() and draw_menu(), or null if the window has none.
text_font@ game_window::font;
Remarks:
Set it with a handle assignment, as in @window.font = get_font("arial", 24);. A window starts with a default font of the platform, Arial or a similar sans serif font where the system has one, so draw_text() works as soon as the window is shown without setting anything. If the platform has no suitable font this is null, which can be checked with window.font is null, and text isn't drawn until a font is set.
has_surface
Whether the window has a software surface, which games drawing through the renderer don't use.
const bool game_window::has_surface;
id
The numeric ID SDL (NVGT's underlying input and window management library) gives the window, unique among the windows of the program.
const uint game_window::id;
keyboard_grab
Whether the window grabs the keyboard, see set_keyboard_grab().
const bool game_window::keyboard_grab;
mouse_grab
Whether the window confines the mouse to itself.
const bool game_window::mouse_grab;
mouse_relative_mode
Whether the window is in relative mouse mode, see set_mouse_relative_mode().
const bool game_window::mouse_relative_mode;
native_window
The operating system's handle for the window, such as an HWND on Windows, for use with libraries that need it.
const uint64 game_window::native_window;
opacity
How opaque the window is, from 0.0 to 1.0.
const float game_window::opacity;
pixel_density
How many pixels there are for each screen coordinate, such as 2 on a high resolution Mac display.
const float game_window::pixel_density;
Remarks:
Multiply sizes in screen coordinates by this to get sizes in pixels.
pixel_format
The SDL pixel format of the window's surface.
const uint game_window::pixel_format;
progress_state
The state of the window's taskbar progress indicator, a value of the window_progress_state enum.
const uint game_window::progress_state;
progress_value
How full the window's taskbar progress indicator is, from 0.0 to 1.0.
const float game_window::progress_value;
renderer
The renderer the window draws with, which gives lower level access to drawing.
const graphics_renderer@ game_window::renderer;
title
The title of the window.
const string game_window::title;
Remarks:
Use set_title() to change it.
graphic
An image stored in memory, which can be created, loaded from a file, modified, saved and then drawn into a window or used as an icon.
graphic@ create_surface(int width, int height, pixel_format pixel_format);
Remarks:
The graphic class holds a block of pixels, called a surface. Graphics are reference types, so graphic@ handles share one image, and use duplicate() to make an independent copy. They are created with create_surface(), which makes a blank image, with the load_ functions, which read image files, or by the render_ methods of text_font, which draw text into a new image. A window draws one with game_window::render_graphic() and uses one as its icon with game_window::set_icon().
A graphic can't be created directly with a constructor, and each of the functions above returns null on failure instead of throwing an exception. Methods that return a bool return true on success and false on failure. A graphic stays valid until the last handle to it is released, and its pixels can't currently be read or written from the script.
Each pixel is stored in the pixel_format that was given when the image was created or loaded, and the width and height are in pixels. The pitch is the number of bytes in one row of pixels, which can be larger than the width multiplied by the size of a pixel, because rows are padded for speed.
The color, alpha and blend modes of a graphic control how it is combined with whatever it is drawn onto.
Example:
void main() {
// Create an image of 64 by 32 pixels, with a red, green, blue and alpha channel.
graphic@ image = create_surface(64, 32, PIXELFORMAT_ARGB8888);
alert("Created", image.width + " by " + image.height + " pixels, with " + image.pitch + " bytes per row.");
// Save it, then load it again.
string path = "graphic_example.png";
if (!image.save_png(path)) {
alert("Error", "Failed to save the image.");
return;
}
graphic@ loaded = load_png(path);
alert("Loaded", "Loaded back an image of " + loaded.width + " by " + loaded.height + " pixels.");
file_delete(path);
// A copy can be converted to another pixel format, or have its properties changed without affecting the original.
graphic@ opaque = loaded.convert(PIXELFORMAT_RGB24);
loaded.set_alpha_mod(128);
alert("Converted", "The converted image has " + opaque.pitch + " bytes per row, and the original has an alpha of " + loaded.get_alpha_mod() + ".");
}
Methods
convert
Make a copy of the image in another pixel format.
graphic@ graphic::convert(pixel_format pixel_format) const;
Arguments:
- pixel_format pixel_format: the format of the new image.
Returns:
graphic@: the converted copy, or null on failure. The original is not changed.
Remarks:
Converting to a format without an alpha channel discards the transparency.
duplicate
Make an independent copy of the image.
graphic@ graphic::duplicate() const;
Returns:
graphic@: the copy, or null on failure.
Remarks:
Unlike assigning a handle, which refers to the same image, changing the copy doesn't change the original. The pixel format and the color, alpha and blend modes are copied.
flip
Mirror the image in place.
bool graphic::flip(flip_mode mode);
Arguments:
- flip_mode mode: the direction to flip in, FLIP_HORIZONTAL to mirror left and right or FLIP_VERTICAL to mirror top and bottom.
Returns:
bool: true on success, or false if mode is FLIP_NONE, as there is nothing to do.
Remarks:
Both directions are used at once by casting the combined values, as in image.flip(flip_mode(FLIP_HORIZONTAL | FLIP_VERTICAL)), which rotates the image by half a turn.
get_alpha_mod
Get the opacity that is multiplied with the image when it is drawn.
uint graphic::get_alpha_mod() const;
Returns:
uint: the alpha, from 0 to 255.
get_blend_mode
Get how the image is combined with what it is drawn onto.
blend_mode graphic::get_blend_mode() const;
Returns:
blend_mode: the current blend mode.
get_color_mod
Get the color that is multiplied with the image when it is drawn.
bool graphic::get_color_mod(uint&out r, uint&out g, uint&out b) const;
Arguments:
- uint&out r: receives the red component.
- uint&out g: receives the green component.
- uint&out b: receives the blue component.
Returns:
bool: true on success.
lock
Lock the image so that its pixels can be accessed directly.
bool graphic::lock();
Returns:
bool: true on success.
Remarks:
Every successful lock should be followed by a call to unlock(). There are currently no methods to access the pixels of a graphic from script.
save_bmp
Save the image as a BMP file.
bool graphic::save_bmp(const string&in file) const;
Arguments:
- const string&in file: the path of the file to write.
Returns:
bool: true if the file was written, false otherwise.
Remarks:
An existing file is replaced.
save_png
Save the image as a PNG file.
bool graphic::save_png(const string&in file) const;
Arguments:
- const string&in file: the path of the file to write.
Returns:
bool: true if the file was written, false otherwise.
Remarks:
An existing file is replaced. PNG files are compressed without losing any information, which makes them the better choice for most images.
set_alpha_mod
Set an opacity that is multiplied with the image when it is drawn.
bool graphic::set_alpha_mod(uint alpha);
Arguments:
- uint alpha: the opacity from 0, which is fully transparent, to 255, which is fully opaque.
Returns:
bool: true on success.
Remarks:
The alpha of each pixel is multiplied by this value divided by 255. The default is 255. Values above 255 wrap around.
set_blend_mode
Set how the image is combined with what it is drawn onto.
bool graphic::set_blend_mode(blend_mode mode);
Arguments:
- blend_mode mode: the way to blend, see the blend_mode enum.
Returns:
bool: true on success.
Remarks:
The default is BLEND_MODE_BLEND for images with an alpha channel, and BLEND_MODE_NONE for those without.
set_color_mod
Set a color that is multiplied with the image when it is drawn.
bool graphic::set_color_mod(uint r, uint g, uint b);
Arguments:
- uint r: the red component, from 0 to 255.
- uint g: the green component, from 0 to 255.
- uint b: the blue component, from 0 to 255.
Returns:
bool: true on success.
Remarks:
Each color of the image is multiplied by the value of its channel divided by 255, so 255 leaves a channel unchanged and 0 removes it. The default is 255 for all three. Values above 255 are not clamped but wrap around, so 300 is treated as 44.
set_rle
Turn RLE acceleration on or off for the image.
bool graphic::set_rle(bool enabled);
Arguments:
- bool enabled: true to compress the image in memory so that drawing it is faster, false to turn this off.
Returns:
bool: true on success.
Remarks:
RLE (run length encoding) helps for images that have large areas of the same color or transparency, at the cost of some memory. It is turned off by default.
unlock
Unlock an image that was locked with lock().
void graphic::unlock();
Properties
height
The height of the image in pixels.
const int graphic::height;
is_valid
Whether the graphic holds an image.
const bool graphic::is_valid;
Remarks:
The functions that create graphics return null rather than an invalid graphic when they fail, so this is true for any graphic that your script receives.
pitch
The number of bytes in one row of pixels of the image.
const int graphic::pitch;
Remarks:
This is at least the width multiplied by the bytes per pixel of the format, but can be more because rows are padded.
width
The width of the image in pixels.
const int graphic::width;
system_tray
An icon in the system tray or notification area depending on what the host operating system offers, with a tooltip and a menu.
system_tray(const string&in tooltip, graphic@ icon = null);
Arguments:
const string&in tooltip: the text shown and spoken when the icon is focused or hovered over.
graphic@ icon = null: the image to show as the icon, or null for a default.
Remarks:
A tray icon lets a program be reached while its window is hidden, which suits games and tools that keep running in the background, such as a chat client waiting for messages. The icon stays in the tray until the system_tray object is destroyed.
The tray's menu, from the menu property, is shown when the user activates the icon. Items are added to it with system_tray_menu's insert methods. The icon and its menu are serviced by wait() and refresh_window(), which also call the item callbacks, so the script must keep calling one of them from the thread that created the tray. While it isn't, for example during a long computation or a sleep, activating the icon does nothing at all. No window is needed, a script can run from the tray alone as the example below does. Tray icons are supported at least on Windows, macOS and Linux desktops. The system_tray::valid property indicates whether the system tray icon could be created usually due to lack of underlying platform support, false if it couldn't.
Example:
bool running = true;
void on_exit(system_tray_menu_item@ item) { running = false; }
void on_speak(system_tray_menu_item@ item) { screen_reader_output("Hello from the system tray!", true); }
void on_mute(system_tray_menu_item@ item) { screen_reader_output(item.checked? "Muted" : "Unmuted", true); } // Checkboxes toggle themselves before their callback is called.
void main() {
system_tray tray("NVGT tray example");
if (!tray.valid) {
alert("Error", "System tray icons aren't supported here.");
return;
}
system_tray_menu@ menu = tray.menu;
menu.insert_item("Say hello", on_speak);
menu.insert_checkbox("Mute", false, on_mute);
system_tray_menu@ more = menu.insert_submenu("More").submenu;
more.insert_item("Disabled item", null, true);
menu.insert_separator();
menu.insert_item("Exit", on_exit);
while (running) wait(5);
}
Methods
set_icon
Change the tray icon's image.
void system_tray::set_icon(graphic@ icon);
Arguments:
- graphic@ icon: the image to show, or null for a default.
set_tooltip
Change the tray icon's tooltip.
void system_tray::set_tooltip(const string&in tooltip);
Arguments:
- const string&in tooltip: the text shown and spoken when the icon is focused or hovered over.
Properties
menu
The menu shown when the tray icon is activated, created the first time this is read.
const system_tray_menu@ system_tray::menu;
Remarks:
This is null if the tray icon isn't valid.
valid
Whether the tray icon was created, which fails where system tray icons aren't supported.
const bool system_tray::valid;
system_tray_menu
The menu of a system_tray icon, or a submenu of it, holding items, checkboxes, submenus and separators.
Remarks:
Menus can't be created directly. The menu of a tray icon comes from system_tray::menu, and a submenu from the submenu property of an item inserted with insert_submenu(). See system_tray for an example.
Methods
insert_checkbox
Add an item that can be checked or unchecked.
system_tray_menu_item@ system_tray_menu::insert_checkbox(const string&in label, bool checked = false, system_tray_callback@ callback = null, bool disabled = false, int pos = -1);
Arguments:
- const string&in label: the text of the item.
- bool checked = false: whether the item starts checked.
- system_tray_callback@ callback = null: the function to call when the item is chosen, which takes the item as its parameter.
- bool disabled = false: whether the item is shown but can't be chosen.
- int pos = -1: where to insert the item, counting from 0, or -1 to add it at the end.
Returns:
system_tray_menu_item@: the new item, or null if it couldn't be added.
Remarks:
Choosing the item toggles it before its callback is called, so the callback can read the item's checked property to find out its new state.
insert_item
Add an item that runs a callback when chosen.
system_tray_menu_item@ system_tray_menu::insert_item(const string&in label, system_tray_callback@ callback = null, bool disabled = false, int pos = -1);
Arguments:
- const string&in label: the text of the item.
- system_tray_callback@ callback = null: the function to call when the item is chosen, which takes the item as its parameter.
- bool disabled = false: whether the item is shown but can't be chosen.
- int pos = -1: where to insert the item, counting from 0, or -1 to add it at the end.
Returns:
system_tray_menu_item@: the new item, or null if it couldn't be added.
insert_separator
Add a separator line between items.
system_tray_menu_item@ system_tray_menu::insert_separator(int pos = -1);
Arguments:
- int pos = -1: where to insert the item, counting from 0, or -1 to add it at the end.
Returns:
system_tray_menu_item@: the separator, or null if it couldn't be added.
insert_submenu
Add an item that opens a submenu.
system_tray_menu_item@ system_tray_menu::insert_submenu(const string&in label, bool disabled = false, int pos = -1);
Arguments:
- const string&in label: the text of the item.
- bool disabled = false: whether the item is shown but can't be opened.
- int pos = -1: where to insert the item, counting from 0, or -1 to add it at the end.
Returns:
system_tray_menu_item@: the new item, or null if it couldn't be added. Its submenu property is the submenu to add items to.
remove_entry
Remove an item from the menu.
void system_tray_menu::remove_entry(system_tray_menu_item@ item);
Arguments:
- system_tray_menu_item@ item: the item to remove, which becomes invalid.
Properties
entries
The items of the menu that were added by the script.
const array<system_tray_menu_item@>@ system_tray_menu::entries;
entry_count
The number of items in the menu, counting separators and submenus.
const int system_tray_menu::entry_count;
system_tray_menu_item
An item of a system_tray_menu, such as a command, a checkbox, a submenu or a separator.
Remarks:
Items can't be created directly, they are returned by the insert methods of system_tray_menu. See system_tray for an example.
Methods
click
Choose the item as though the user had, running its callback and toggling a checkbox.
void system_tray_menu_item::click();
set_callback
Set the function called when the item is chosen.
void system_tray_menu_item::set_callback(system_tray_callback@ func);
Arguments:
- system_tray_callback@ func: the function, which takes the item as its parameter, or null for none.
Properties
checked
Whether a checkbox item is checked.
bool system_tray_menu_item::checked;
enabled
Whether the item can be chosen.
bool system_tray_menu_item::enabled;
label
The text of the item.
string system_tray_menu_item::label;
submenu
The submenu of an item inserted with insert_submenu(), or null for any other item.
const system_tray_menu@ system_tray_menu_item::submenu;
type
What kind of item this is, a value of the system_tray_menu_item_type enum.
const system_tray_menu_item_type system_tray_menu_item::type;
valid
Whether the item still exists, which becomes false after it was removed from its menu.
const bool system_tray_menu_item::valid;
text_font
A TrueType or OpenType font, for measuring text and drawing it into images or windows.
text_font(const string&in name, float size, uint style = FONT_STYLE_NORMAL);
Arguments:
const string&in name: the font to load, either the name of an installed font such as
arial, or the path to a .ttf file.float size: the size of the font in points.
uint style = FONT_STYLE_NORMAL: a combination of values from the font_style enum, such as FONT_STYLE_BOLD.
Remarks:
Fonts are found by name in the system's font directory, such as C:/Windows/Fonts on Windows, or the name can be a path to a font file, with or without its .ttf extension. If the font can't be found, every method fails, returning false, 0 or null, and family_name is empty.
get_font() is usually a better way to get a font, as it shares one object between everything that asks for the same font, size and style. A font is drawn into a window by giving it to game_window::font, and the render_ methods draw text into a new graphic in one of four ways: solid, which is fastest but has rough edges, blended, which is smooth over any background, shaded, which is smooth over a background color, and lcd, which uses subpixel rendering for LCD screens.
Text is UTF-8, and fallback fonts can supply the characters the font lacks, such as emoji or other scripts.
Example:
void main() {
text_font@ f = get_font("arial", 32);
if (f.family_name.empty()) {
alert("Error", "The font couldn't be loaded.");
return;
}
int w, h;
f.get_string_size("Hello from NVGT!", w, h);
f.style = FONT_STYLE_BOLD | FONT_STYLE_ITALIC;
alert("Font", f.family_name + " " + f.style_name + " at " + f.size + " points\nline height: " + f.height + ", ascent " + f.ascent + ", descent " + f.descent + "\nThe greeting measures " + w + " by " + h + " pixels.\nHas the letter A: " + f.has_glyph(65));
}
Methods
add_fallback_font
Add a font to supply the characters this font doesn't have.
bool text_font::add_fallback_font(text_font@ font);
Arguments:
- text_font@ font: the fallback font, which should be the same size.
Returns:
bool: true on success, false otherwise.
Remarks:
Fallback fonts are tried in the order they were added.
clear_fallback_fonts
Remove every fallback font.
void text_font::clear_fallback_fonts();
get_dpi
Get the display resolution the font's size is for.
bool text_font::get_dpi(int&out hdpi, int&out vdpi) const;
Arguments:
- int&out hdpi: receives the horizontal resolution in dots per inch.
- int&out vdpi: receives the vertical resolution in dots per inch.
Returns:
bool: true on success, false otherwise.
get_glyph_image
Get the image of a single character as the font stores it.
graphic@ text_font::get_glyph_image(uint ch) const;
Arguments:
- uint ch: the Unicode code point of the character.
Returns:
graphic@: the image, or null if the font has no such character.
get_glyph_metrics
Get the measurements of a character.
bool text_font::get_glyph_metrics(uint ch, int&out minx, int&out maxx, int&out miny, int&out maxy, int&out advance) const;
Arguments:
- uint ch: the Unicode code point of the character.
- int&out minx: receives the left edge of the glyph relative to where it is drawn.
- int&out maxx: receives the right edge of the glyph.
- int&out miny: receives the bottom of the glyph relative to the baseline.
- int&out maxy: receives the top of the glyph relative to the baseline.
- int&out advance: receives how far to move along before drawing the next character.
Returns:
bool: true on success, false if the font has no such character.
get_kerning_size
Get the kerning between two characters, how much closer or further apart they are drawn than usual.
bool text_font::get_kerning_size(uint prev_ch, uint ch, int&out kerning) const;
Arguments:
- uint prev_ch: the Unicode code point of the first character.
- uint ch: the Unicode code point of the second character.
- int&out kerning: receives the adjustment in pixels.
Returns:
bool: true on success, false otherwise.
get_string_size
Measure a line of text.
bool text_font::get_string_size(const string&in text, int&out w, int&out h) const;
Arguments:
- const string&in text: the text to measure.
- int&out w: receives the width in pixels.
- int&out h: receives the height in pixels.
Returns:
bool: true on success, false otherwise.
get_string_size_wrapped
Measure text wrapped onto lines no wider than a width.
bool text_font::get_string_size_wrapped(const string&in text, int wrap_width, int&out w, int&out h) const;
Arguments:
- const string&in text: the text to measure.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- int&out w: receives the width in pixels.
- int&out h: receives the height in pixels.
Returns:
bool: true on success, false otherwise.
has_glyph
Find out whether the font has a character.
bool text_font::has_glyph(uint codepoint);
Arguments:
- uint codepoint: the Unicode code point of the character, such as 65 for A.
Returns:
bool: true if the font, or one of its fallback fonts, has a glyph for the character.
measure_string
Find out how much of a line of text fits within a width.
bool text_font::measure_string(const string&in text, int max_width, int&out measured_width, int&out measured_length) const;
Arguments:
- const string&in text: the text to measure.
- int max_width: the width available in pixels.
- int&out measured_width: receives the width of the part that fits.
- int&out measured_length: receives the length in bytes of the part that fits.
Returns:
bool: true on success, false otherwise.
Remarks:
This is useful for cutting text off with an ellipsis or wrapping it yourself.
remove_fallback_font
Remove a fallback font.
bool text_font::remove_fallback_font(text_font@ font);
Arguments:
- text_font@ font: the fallback font to remove.
Returns:
bool: true if it was a fallback font of this one and was removed, false otherwise.
render_glyph_blended
Draw a single character into a new image with smooth edges over a transparent background.
graphic@ text_font::render_glyph_blended(uint ch, uint r, uint g, uint b);
Arguments:
- uint ch: the Unicode code point of the character.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
render_glyph_lcd
Draw a single character into a new image with subpixel smoothing over a background color.
graphic@ text_font::render_glyph_lcd(uint ch, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- uint ch: the Unicode code point of the character.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_glyph_shaded
Draw a single character into a new image with smooth edges over a background color.
graphic@ text_font::render_glyph_shaded(uint ch, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- uint ch: the Unicode code point of the character.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_glyph_solid
Draw a single character into a new image quickly, without smoothing its edges.
graphic@ text_font::render_glyph_solid(uint ch, uint r, uint g, uint b);
Arguments:
- uint ch: the Unicode code point of the character.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
render_text_blended
Draw a line of text into a new image with smooth edges over a transparent background.
graphic@ text_font::render_text_blended(const string&in text, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
Remarks:
This is the best looking way to draw text over anything, and is what game_window::draw_text() uses.
render_text_blended_wrapped
Draw text into a new image with smooth edges over a transparent background, wrapping it onto further lines.
graphic@ text_font::render_text_blended_wrapped(const string&in text, int wrap_width, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
render_text_lcd
Draw a line of text into a new image with subpixel smoothing for LCD screens, over a background color.
graphic@ text_font::render_text_lcd(const string&in text, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- const string&in text: the text to draw.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_text_lcd_wrapped
Draw text into a new image with subpixel smoothing over a background color, wrapping it onto further lines.
graphic@ text_font::render_text_lcd_wrapped(const string&in text, int wrap_width, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- const string&in text: the text to draw.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_text_shaded
Draw a line of text into a new image with smooth edges over a background color.
graphic@ text_font::render_text_shaded(const string&in text, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- const string&in text: the text to draw.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_text_shaded_wrapped
Draw text into a new image with smooth edges over a background color, wrapping it onto further lines.
graphic@ text_font::render_text_shaded_wrapped(const string&in text, int wrap_width, uint fg_r, uint fg_g, uint fg_b, uint bg_r, uint bg_g, uint bg_b);
Arguments:
- const string&in text: the text to draw.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- uint fg_r: the red component of the text color, from 0 to 255.
- uint fg_g: the green component of the text color.
- uint fg_b: the blue component of the text color.
- uint bg_r: the red component of the background color, from 0 to 255.
- uint bg_g: the green component of the background color.
- uint bg_b: the blue component of the background color.
Returns:
graphic@: the image, or null on failure.
render_text_solid
Draw a line of text into a new image quickly, without smoothing its edges.
graphic@ text_font::render_text_solid(const string&in text, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
render_text_solid_wrapped
Draw text into a new image quickly, wrapping it onto further lines when it becomes too wide.
graphic@ text_font::render_text_solid_wrapped(const string&in text, int wrap_width, uint r, uint g, uint b);
Arguments:
- const string&in text: the text to draw.
- int wrap_width: the width in pixels at which lines wrap, or 0 to only break lines at newlines.
- uint r: the red component of the color, from 0 to 255.
- uint g: the green component of the color, from 0 to 255.
- uint b: the blue component of the color, from 0 to 255.
Returns:
graphic@: the image, or null on failure.
set_direction
Set the direction text is laid out in.
bool text_font::set_direction(font_direction dir);
Arguments:
- font_direction dir: a value of the font_direction enum.
Returns:
bool: true on success, false otherwise.
Remarks:
Right to left is needed for scripts such as Arabic and Hebrew.
set_language
Set the language text is shaped for, which affects some scripts.
bool text_font::set_language(const string&in language_bcp47);
Arguments:
- const string&in language_bcp47: a BCP 47 language tag, such as
enorar-EG.
Returns:
bool: true on success, false otherwise.
set_outline
Draw text as outlines of a given thickness rather than solid.
bool text_font::set_outline(int outline);
Arguments:
- int outline: the thickness of the outline in pixels, or 0 for solid text.
Returns:
bool: true on success, false otherwise.
set_script
Set the script text is shaped for.
bool text_font::set_script(uint script);
Arguments:
- uint script: an ISO 15924 script code converted with font_string_to_tag(), such as
font_string_to_tag("Arab").
Returns:
bool: true on success, false otherwise.
set_sdf
Set whether glyphs are rendered as signed distance fields, which scale smoothly in shaders.
bool text_font::set_sdf(bool enabled);
Arguments:
- bool enabled: whether to render signed distance fields.
Returns:
bool: true on success, false otherwise.
set_size
Change the size of the font.
bool text_font::set_size(float ptsize);
Arguments:
- float ptsize: the new size in points.
Returns:
bool: true on success, false otherwise.
Remarks:
Fonts from get_font() are shared, so changing them changes them for everything using them. Use a font of a different size from get_font() instead, or create one with allow_caching set to false.
set_size_dpi
Change the size of the font for a display resolution.
bool text_font::set_size_dpi(float ptsize, int hdpi, int vdpi);
Arguments:
- float ptsize: the new size in points.
- int hdpi: the horizontal resolution in dots per inch.
- int vdpi: the vertical resolution in dots per inch.
Returns:
bool: true on success, false otherwise.
Properties
ascent
How far the font's glyphs rise above the baseline in pixels.
const int text_font::ascent;
descent
How far the font's glyphs drop below the baseline, as a negative number of pixels.
const int text_font::descent;
direction
The direction text is laid out in, a value of the font_direction enum.
const font_direction text_font::direction;
faces_count
The number of faces in the font file, such as the weights and styles of a font collection.
const int text_font::faces_count;
family_name
The family name of the font, such as Arial, or an empty string if the font couldn't be loaded.
const string text_font::family_name;
generation
A number that changes whenever a setting of the font that affects how text looks is changed, such as its size or style.
const uint text_font::generation;
Remarks:
Code that caches rendered text can compare this to find out when to render it again.
height
The maximum height of the font's glyphs in pixels.
const int text_font::height;
is_fixed_width
Whether every glyph of the font is the same width, as in a monospaced font.
const bool text_font::is_fixed_width;
is_scalable
Whether the font is scalable, as TrueType and OpenType fonts are, rather than a bitmap font.
const bool text_font::is_scalable;
kerning
Whether kerning is applied, adjusting the space between pairs of letters such as AV.
bool text_font::kerning;
Remarks:
This defaults to true.
line_skip
The distance in pixels from one line of text to the next.
int text_font::line_skip;
outline
The thickness of the outline text is drawn with, or 0 for solid text.
const int text_font::outline;
Remarks:
Use set_outline() to change it.
script
The script text is shaped for, as an ISO 15924 code that font_tag_to_string() converts to a string.
const uint text_font::script;
sdf
Whether glyphs are rendered as signed distance fields.
const bool text_font::sdf;
size
The size of the font in points.
const float text_font::size;
Remarks:
Use set_size() to change it.
style
The style of the font, a combination of values from the font_style enum.
uint text_font::style;
style_name
The style name of the loaded font face, such as Regular or Bold Italic.
const string text_font::style_name;
Remarks:
Styles applied with the style property don't change this, as they are synthesized rather than loaded from the font.
weight
The weight of the font, such as 400 for normal or 700 for bold.
const int text_font::weight;
wrap_alignment
How the lines of wrapped text are aligned, a value of the font_align enum.
font_align text_font::wrap_alignment;
Enums
blend_mode
The ways a graphic can be combined with the pixels it is drawn onto.
- BLEND_MODE_NONE: no blending, the destination is replaced.
dstRGBA = srcRGBA. - BLEND_MODE_BLEND: alpha blending.
dstRGB = (srcRGB * srcA) + (dstRGB * (1 - srcA))anddstA = srcA + (dstA * (1 - srcA)). - BLEND_MODE_BLEND_PREMULTIPLIED: alpha blending for colors that have already been multiplied by their alpha.
dstRGB = srcRGB + (dstRGB * (1 - srcA))anddstA = srcA + (dstA * (1 - srcA)). - BLEND_MODE_ADD: additive blending.
dstRGB = (srcRGB * srcA) + dstRGBanddstA = dstA. - BLEND_MODE_ADD_PREMULTIPLIED: additive blending for premultiplied colors.
dstRGB = srcRGB + dstRGBanddstA = dstA. - BLEND_MODE_MOD: color modulate.
dstRGB = srcRGB * dstRGBanddstA = dstA. - BLEND_MODE_MUL: color multiply.
dstRGB = (srcRGB * dstRGB) + (dstRGB * (1 - srcA))anddstA = dstA.
Remarks:
In the formulas, src is the graphic being drawn and dst is what it is drawn onto, with colors and alpha values ranging from 0 to 1.
flip_mode
The directions in which a graphic can be mirrored.
- FLIP_NONE: don't flip.
- FLIP_HORIZONTAL: mirror left and right.
- FLIP_VERTICAL: mirror top and bottom.
font_align
How the lines of wrapped text are aligned, set with text_font::wrap_alignment.
- FONT_ALIGN_LEFT: lines start at the left edge.
- FONT_ALIGN_CENTER: lines are centered.
- FONT_ALIGN_RIGHT: lines end at the right edge.
font_direction
Directions text can be laid out in, set with text_font::set_direction().
- FONT_DIRECTION_LTR: left to right, as in English.
- FONT_DIRECTION_RTL: right to left, as in Arabic and Hebrew.
- FONT_DIRECTION_TTB: top to bottom.
- FONT_DIRECTION_BTT: bottom to top.
font_hinting
Ways of adjusting the outlines of glyphs to the pixel grid. No method of text_font takes these values at this time.
- FONT_HINTING_NORMAL: normal hinting.
- FONT_HINTING_LIGHT: lighter hinting, which keeps the shapes of glyphs closer to their design.
- FONT_HINTING_MONO: strong hinting for text drawn without smoothing.
- FONT_HINTING_NONE: no hinting.
- FONT_HINTING_LIGHT_SUBPIXEL: light hinting for subpixel rendering.
font_style
Styles of a text_font, which can be combined with a verticle bar (| bitwise).
- FONT_STYLE_NORMAL: no styling.
- FONT_STYLE_BOLD: bold text.
- FONT_STYLE_ITALIC: italic text.
- FONT_STYLE_UNDERLINE: underlined text.
- FONT_STYLE_STRIKETHROUGH: struck through text.
Bold and italic are synthesized when the font has no bold or italic version, so loading the font's own bold or italic file looks better where there is one.
key_code
This is a complete list of possible keycodes in NVGT, as well as a short description of what they are. These are registered in the key_code enum, meaning you can use this type to pass any value listed here around though it is also safe to use unsigned integers.
Letter keys
- KEY_UNKNOWN: unknown.
- KEY_A: the A key.
- KEY_B: the B key.
- KEY_C: the C key.
- KEY_D: the D key.
- KEY_E: the E key.
- KEY_F: the F key.
- KEY_G: the G key.
- KEY_H: the H key.
- KEY_I: the I key.
- KEY_J: the J key.
- KEY_K: the K key.
- KEY_L: the L key.
- KEY_M: the M key.
- KEY_N: the N key.
- KEY_O: the O key.
- KEY_P: the P key.
- KEY_Q: the Q key.
- KEY_R: the R key.
- KEY_S: the S key.
- KEY_T: the T key.
- KEY_U: the U key.
- KEY_V: the V key.
- KEY_W: the W key.
- KEY_X: the X key.
- KEY_Y: the Y key.
- KEY_Z: the Z key.
Number keys
- KEY_1: the 1 key.
- KEY_2: the 2 key.
- KEY_3: the 3 key.
- KEY_4: the 4 key.
- KEY_5: the 5 key.
- KEY_6: the 6 key.
- KEY_7: the 7 key.
- KEY_8: the 8 key.
- KEY_9: the 9 key.
- KEY_0: the 0 key.
Special keys
- KEY_RETURN: the Return (or enter) key.
- KEY_ESCAPE: the Escape key.
- KEY_BACK: the Backspace key.
- KEY_TAB: the Tab key.
- KEY_SPACE: the Space key.
- KEY_MINUS: the Minus (dash) key.
- KEY_EQUALS: the Equals key.
- KEY_LEFTBRACKET: the Left Bracket key.
- KEY_RIGHTBRACKET: the Right Bracket key.
- KEY_BACKSLASH: the Backslash key.
- KEY_NONUSHASH: the Non-US Hash key.
- KEY_SEMICOLON: the Semicolon key.
- KEY_APOSTROPHE: the Apostrophe key.
- KEY_GRAVE: the Grave key.
- KEY_COMMA: the Comma key.
- KEY_PERIOD: the Period key.
- KEY_SLASH: the Slash key.
- KEY_CAPSLOCK: the Caps Lock key.
Function keys
- KEY_F1: the F1 key.
- KEY_F2: the F2 key.
- KEY_F3: the F3 key.
- KEY_F4: the F4 key.
- KEY_F5: the F5 key.
- KEY_F6: the F6 key.
- KEY_F7: the F7 key.
- KEY_F8: the F8 key.
- KEY_F9: the F9 key.
- KEY_F10: the F10 key.
- KEY_F11: the F11 key.
- KEY_F12: the F12 key.
- KEY_F13: the F13 key.
- KEY_F14: the F14 key.
- KEY_F15: the F15 key.
- KEY_F16: the F16 key.
- KEY_F17: the F17 key.
- KEY_F18: the F18 key.
- KEY_F19: the F19 key.
- KEY_F20: the F20 key.
- KEY_F21: the F21 key.
- KEY_F22: the F22 key.
- KEY_F23: the F23 key.
- KEY_F24: the F24 key.
Arrow keys
- KEY_RIGHT: the Right Arrow key.
- KEY_LEFT: the Left Arrow key.
- KEY_DOWN: the Down Arrow key.
- KEY_UP: the Up Arrow key.
Numpad keys
- KEY_NUMLOCKCLEAR: the Num Lock key.
- KEY_NUMPAD_DIVIDE: the numpad divide key.
- KEY_NUMPAD_MULTIPLY: the numpad multiply key.
- KEY_NUMPAD_MINUS: the numpad minus key.
- KEY_NUMPAD_PLUS: the numpad plus key.
- KEY_NUMPAD_ENTER: the numpad enter key.
- KEY_NUMPAD_1: the Numpad 1 key.
- KEY_NUMPAD_2: the Numpad 2 key.
- KEY_NUMPAD_3: the Numpad 3 key.
- KEY_NUMPAD_4: the Numpad 4 key.
- KEY_NUMPAD_5: the Numpad 5 key.
- KEY_NUMPAD_6: the Numpad 6 key.
- KEY_NUMPAD_7: the Numpad 7 key.
- KEY_NUMPAD_8: the Numpad 8 key.
- KEY_NUMPAD_9: the Numpad 9 key.
- KEY_NUMPAD_0: the Numpad 0 key.
- KEY_NUMPAD_PERIOD: the Numpad Period key.
Modifier keys
- KEY_LCTRL: the Left Control key.
- KEY_LSHIFT: the Left Shift key.
- KEY_LALT: the Left Alt key.
- KEY_LGUI: the left windows/command/super key (depending on platform).
- KEY_RCTRL: the Right Control key.
- KEY_RSHIFT: the Right Shift key.
- KEY_RALT: the Right Alt key.
- KEY_RGUI: the right windows/command/super key (depending on platform).
Miscellaneous keys
- KEY_MODE: the Mode key.
- KEY_APPLICATION: the Application key.
- KEY_POWER: the Power key.
- KEY_PRINTSCREEN: the Print Screen key.
- KEY_SCROLLLOCK: the Scroll Lock key.
- KEY_PAUSE: the Pause key.
- KEY_INSERT: the Insert key.
- KEY_HOME: the Home key.
- KEY_PAGEUP: the Page Up key.
- KEY_DELETE: the Delete key.
- KEY_END: the End key.
- KEY_PAGEDOWN: the Page Down key.
Media keys
- KEY_MUTE: the Mute key.
- KEY_VOLUMEUP: the Volume Up key.
- KEY_VOLUMEDOWN: the Volume Down key.
- KEY_MEDIA_NEXT_TRACK: the next track key.
- KEY_MEDIA_PREVIOUS_TRACK: the previous track key.
- KEY_MEDIA_STOP: the stop media key.
- KEY_MEDIA_PLAY: the play media key.
- KEY_MUTE: the mute key.
- KEY_MEDIA_SELECT: the media select key.
Browser and Application keys
- KEY_AC_SEARCH: the AC Search key.
- KEY_AC_HOME: the AC Home key.
- KEY_AC_BACK: the AC Back key.
- KEY_AC_FORWARD: the AC Forward key.
- KEY_AC_STOP: the AC Stop key.
- KEY_AC_REFRESH: the AC Refresh key.
- KEY_AC_BOOKMARKS: the AC Bookmarks key.
Additional keys
- KEY_MEDIA_EJECT: the eject key.
- KEY_SLEEP: the sleep key.
- KEY_MEDIA_REWIND: the media rewind key.
- KEY_MEDIA_FAST_FORWARD: the media fast forward key.
- KEY_SOFTLEFT: the Soft Left key.
- KEY_SOFTRIGHT: the Soft Right key.
- KEY_CALL: the Call key.
- KEY_ENDCALL: the End Call key.
- KEY_AC_SEARCH: the AC Search key.
- KEY_AC_HOME: the AC Home key.
- KEY_AC_BACK: the AC Back key.
- KEY_AC_FORWARD: the AC Forward key.
- KEY_AC_STOP: the AC Stop key.
- KEY_AC_REFRESH: the AC Refresh key.
- KEY_AC_BOOKMARKS: the AC Bookmarks key.
key_modifier
This is a complete list of supported key modifiers and their descriptions. These are registered in the key_modifier enum, so you can use that type to pass any value listed here around.
KEYMOD_NONE: no modifier.
KEYMOD_LSHIFT: left shift key.
KEYMOD_RSHIFT: right shift key.
KEYMOD_LCTRL: left control key.
KEYMOD_RCTRL: right control key.
KEYMOD_LALT: left alt key.
KEYMOD_RALT: right alt key.
KEYMOD_LGUI: left windows/command/super key (depending on platform).
KEYMOD_RGUI: right windows/command/super key (depends on platform).
KEYMOD_NUM: numlock key.
KEYMOD_CAPS: capslock key.
KEYMOD_MODE: input switch mode (only on certain keyboards).
KEYMOD_SCROLL: scroll lock key.
KEYMOD_CTRL: either control key.
KEYMOD_SHIFT: either shift key.
KEYMOD_ALT: either alt key.
KEYMOD_GUI: either windows/command/super key.
Example:
void main() {
show_window("Example");
wait(50); // Give the screen readers enough time to speak the window title before speaking.
screen_reader_output("Press alt+f4 to close this window.", true);
while (true) {
wait(5);
if (keyboard_modifiers & KEYMOD_ALT > 0 && key_pressed(KEY_F4))
exit();
}
}
message_box_flags
This is an enumeration of possible flags to be passed to the message_box(), alert(), question(), and similar functions.
- MESSAGE_BOX_ERROR: the message box should act like an error dialog.
- MESSAGE_BOX_WARNING: the message box should act like a warning dialog.
- MESSAGE_BOX_INFORMATION: the message box should act like an informative dialog.
- MESSAGE_BOX_BUTTONS_LEFT_TO_RIGHT: arrange the buttons in the dialog from left to right.
- MESSAGE_BOX_BUTTONS_RIGHT_TO_LEFT: arrange the buttons from right-to-left in the message box.
pixel_format
The ways the pixels of a graphic can be stored.
- PIXELFORMAT_UNKNOWN: no format. It can't be used to create an image.
- PIXELFORMAT_INDEX8: 8 bits per pixel, where each is the number of a color in a palette.
- PIXELFORMAT_RGB24: 24 bits per pixel, the bytes red, green and blue in that order, without alpha.
- PIXELFORMAT_BGR24: 24 bits per pixel, the bytes blue, green and red in that order, without alpha.
- PIXELFORMAT_XRGB8888: 32 bits per pixel, 8 unused bits then red, green and blue.
- PIXELFORMAT_XBGR8888: 32 bits per pixel, 8 unused bits then blue, green and red.
- PIXELFORMAT_ARGB8888: 32 bits per pixel, alpha then red, green and blue.
- PIXELFORMAT_RGBA8888: 32 bits per pixel, red, green, blue then alpha.
- PIXELFORMAT_ABGR8888: 32 bits per pixel, alpha then blue, green and red.
- PIXELFORMAT_BGRA8888: 32 bits per pixel, blue, green, red then alpha.
- PIXELFORMAT_RGBA32: the bytes red, green, blue and alpha in that order in memory.
- PIXELFORMAT_ARGB32: the bytes alpha, red, green and blue in that order in memory.
- PIXELFORMAT_BGRA32: the bytes blue, green, red and alpha in that order in memory.
- PIXELFORMAT_ABGR32: the bytes alpha, blue, green and red in that order in memory.
Remarks:
The 8888 formats store each pixel as one 32 bit number, with the channels named from its most significant bits to its least significant, so how the bytes are laid out in memory depends on the byte order of the computer. The formats ending in 32 are aliases of one of them that are chosen so that the bytes are in the order given, which on the little endian computers that NVGT runs on makes PIXELFORMAT_RGBA32 the same as PIXELFORMAT_ABGR8888, PIXELFORMAT_ARGB32 the same as PIXELFORMAT_BGRA8888, PIXELFORMAT_BGRA32 the same as PIXELFORMAT_ARGB8888 and PIXELFORMAT_ABGR32 the same as PIXELFORMAT_RGBA8888.
PIXELFORMAT_ARGB8888 is the format that most windows use, see game_window::pixel_format.
system_tray_menu_item_type
The possible types of a system_tray_menu_item.
- SYSTEM_TRAY_ITEM: an item that runs its callback when chosen.
- SYSTEM_TRAY_CHECKBOX: an item that can be checked or unchecked.
- SYSTEM_TRAY_SEPARATOR: a separator line between items.
- SYSTEM_TRAY_SUBMENU: an item that opens a submenu.
touch_device_type
These are the possible types of touch input devices.
- TOUCH_DEVICE_INVALID = -1: Returned if an invalid ID is passed to get_touch_device_type.
- TOUCH_DEVICE_DIRECT: A touch screen with window-relative coordinates.
- TOUCH_DEVICE_INDIRECT_ABSOLUTE: A trackpad with absolute device coordinates.
- TOUCH_DEVICE_INDIRECT_RELATIVE: A trackpad with screen cursor-relative coordinates.
window_flags
An enumeration of flags that can be used with the show_window function to control the window's appearance.
- WINDOW_FLAG_FULLSCREEN: The window will be in true fullscreen mode, taking up the entire screen.
- WINDOW_FLAG_RESIZABLE: The window will be resizable by the user.
- WINDOW_FLAG_MAXIMIZED: The window will be maximized to fill the screen, but will still have a title bar and borders.
- WINDOW_FLAG_MINIMIZED: The window will be created in a minimized state.
- WINDOW_FLAG_HIDDEN: The window will be hidden upon creation.
- WINDOW_FLAG_BORDERLESS: The window will have no border or title bar.
- WINDOW_FLAG_ALWAYS_ON_TOP: The window will always be on top of other windows.
window_flash_operation
What game_window::flash() does.
- FLASH_CANCEL: stop flashing.
- FLASH_BRIEFLY: flash the window's taskbar button briefly.
- FLASH_UNTIL_FOCUSED: flash the window's taskbar button until the user switches to the window.
window_progress_state
The states of the progress indicator on a window's taskbar button, set with game_window::set_progress_state().
- PROGRESS_STATE_INVALID: returned when the state can't be determined.
- PROGRESS_STATE_NONE: no progress indicator is shown.
- PROGRESS_STATE_INDETERMINATE: an indicator is shown that something is happening without saying how far along it is.
- PROGRESS_STATE_NORMAL: the progress value is shown normally.
- PROGRESS_STATE_PAUSED: the progress value is shown as paused.
- PROGRESS_STATE_ERROR: the progress value is shown as having failed.
Events
Besides polling functions such as key_pressed(), NVGT can notify your code when input arrives by calling functions you register with an event. Each event is a global property, such as on_key_press, that holds a list of listeners. Whenever the event happens, NVGT calls the listeners one at a time, in the order they appear in the list.
Events are delivered while NVGT processes input, which happens during calls such as wait() and refresh_window(). Polling and events can be used together: registering a listener doesn't stop functions like key_pressed() from working.
Adding listeners
A listener can be any of the following:
- A function or method that returns nothing. It is always called, and the event then continues to the next listener.
- A function or method that returns bool. If it returns true, the event is considered handled, and the listeners after it in the list are not called. If it returns false, the event continues to the next listener.
- An object of a class that implements the listener interface for the event, such as
engine_key_event_listenerfor key events. The class must have a method named after the event, for examplevoid on_key_press(int key)orbool on_key_press(int key), which follows the same rules as above.
Add a listener with the += operator, or with the insert() method, which also lets you choose its position in the list:
bool insert(listener@ listener, int index = -1);
An index of -1 adds the listener to the end of the list, while 0 makes it the first listener to be called. Both += and insert() return false if the listener is already in the list.
Removing listeners
Remove a listener with the -= operator or with remove(listener). You can also remove the listener at a given position with remove(uint index), or every listener with clear(). To find a listener's position in the list, use find(listener), which returns -1 if it is not in the list. The count property holds the number of listeners.
Object listeners and method listeners only hold a weak reference to their object, so being registered with an event doesn't keep an object alive. Once the object is destroyed, its listener is removed automatically the next time the event fires.
Available events
- Key events, which pass the key code as an int:
on_key_press,on_key_repeatandon_key_release. Their listener interface isengine_key_event_listener. - Text input:
on_characters, which passes the typed text as a string. Its listener interface isengine_character_event_listener. - Mouse button events, which pass the button and the number of clicks:
on_mouse_button_downandon_mouse_button_up. Their listener interface isengine_mouse_button_event_listener. - Mouse movement:
on_mouse_move, which passes the new position and how far the mouse moved. Its listener interface isengine_mouse_motion_event_listener. - Mouse wheel:
on_mouse_wheel, which passes how far the wheel scrolled. Its listener interface isengine_mouse_wheel_event_listener. - Touch events, which pass the touch device and a
touch_fingerstructure:on_touch_finger_down,on_touch_finger_upandon_touch_finger_cancel. Their listener interface isengine_touch_event_listener. - Touch movement:
on_touch_finger_move, which also passes how far the finger moved. Its listener interface isengine_touch_motion_event_listener.
on_characters
An event that is fired whenever the user types text.
engine_character_event on_characters;
Listener signatures:
bool callback(string character);
void callback(string character);
A class implementing engine_character_event_listener, with a
bool on_characters(string character)orvoid on_characters(string character)method.
Arguments passed to listeners:
- string character: the text that was typed, encoded as UTF-8.
Remarks:
Unlike the key events, this event receives the actual text produced by the keyboard, taking the keyboard layout, shift state and input methods into account. Although the argument is called character, it can contain more than one character, for example when an input method for Chinese or Japanese inserts a whole word at once.
Text input must be active for this event to fire. It is started automatically when your window is shown, except on platforms with a screen keyboard, where you need to call start_text_input() (see SCREEN_KEYBOARD_SUPPORTED).
The same text is also returned by get_characters(), so you can use either approach.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
string typed;
void on_text(string text) {
typed += text;
screen_reader_output(text, true);
}
void main() {
show_window("Example");
on_characters += on_text;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Type something, then press enter to hear all of it. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_RETURN)) {
screen_reader_output(typed.empty() ? "Nothing typed" : typed, true);
typed = "";
}
}
}
on_key_press
An event that is fired whenever a key is pressed down.
engine_key_event on_key_press;
Listener signatures:
bool callback(int key);
void callback(int key);
A class implementing engine_key_event_listener, with a
bool on_key_press(int key)orvoid on_key_press(int key)method.
Arguments passed to listeners:
- int key: the code of the key that was pressed, one of the values in the
key_codeenum.
Remarks:
This fires once when a key goes down. While the key is held, the operating system's key repeats fire on_key_repeat instead.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
bool on_key(int key) {
if (key == KEY_ESCAPE) exit();
screen_reader_output(get_key_name(key), true);
return true;
}
void main() {
show_window("Example");
on_key_press += on_key;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Press any key to hear its name, or escape to exit.", true);
while (true) wait(5);
}
on_key_release
An event that is fired whenever a key is released.
engine_key_event on_key_release;
Listener signatures:
bool callback(int key);
void callback(int key);
A class implementing engine_key_event_listener, with a
bool on_key_release(int key)orvoid on_key_release(int key)method.
Arguments passed to listeners:
- int key: the code of the key that was released, one of the values in the
key_codeenum.
Remarks:
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
class key_timer : engine_key_event_listener {
timer held;
void on_key_press(int key) {
if (key == KEY_SPACE) held.restart();
}
void on_key_release(int key) {
if (key == KEY_SPACE) screen_reader_output("Held for " + held.elapsed + " milliseconds", true);
}
}
void main() {
show_window("Example");
key_timer kt;
on_key_press += kt;
on_key_release += kt;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Hold and release space to hear how long you held it. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) wait(5);
on_key_press -= kt;
on_key_release -= kt;
}
on_key_repeat
An event that is fired each time the operating system repeats a key that is being held down.
engine_key_event on_key_repeat;
Listener signatures:
bool callback(int key);
void callback(int key);
A class implementing engine_key_event_listener, with a
bool on_key_repeat(int key)orvoid on_key_repeat(int key)method.
Arguments passed to listeners:
- int key: the code of the key being repeated, one of the values in the
key_codeenum.
Remarks:
The first press of a key fires on_key_press, not this event. The delay before repeating starts, and the speed of the repeats, come from the user's keyboard settings.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
int repeats = 0;
void on_repeat(int key) {
if (key == KEY_SPACE) repeats++;
}
void main() {
show_window("Example");
on_key_repeat += on_repeat;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Hold space, then release it to hear how many times it repeated. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_released(KEY_SPACE)) {
screen_reader_output(repeats + " repeats", true);
repeats = 0;
}
}
}
on_mouse_button_down
An event that is fired whenever a mouse button is pressed down.
engine_mouse_button_event on_mouse_button_down;
Listener signatures:
bool callback(int button, int clicks);
void callback(int button, int clicks);
A class implementing engine_mouse_button_event_listener, with a
bool on_mouse_button_down(int button, int clicks)orvoid on_mouse_button_down(int button, int clicks)method.
Arguments passed to listeners:
int button: the button that was pressed. 1 is the left button, 2 is the middle button, 3 is the right button, and 4 and 5 are the side buttons found on some mice. These are the same numbers used by
mouse_pressed().int clicks: 1 for a single click, 2 for a double click, and so on. The operating system decides how quickly clicks must follow each other to count together.
Remarks:
While this event is being handled, MOUSE_ABSOLUTE_X and MOUSE_ABSOLUTE_Y hold the position of the mouse at the time of the click.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
void on_click(int button, int clicks) {
string name = button == 1 ? "Left" : button == 2 ? "Middle" : button == 3 ? "Right" : "Button " + button;
screen_reader_output(name + (clicks == 2 ? " double click" : " click"), true);
}
void main() {
show_window("Example");
on_mouse_button_down += on_click;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Click or double click any mouse button, or press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) wait(5);
}
on_mouse_button_up
An event that is fired whenever a mouse button is released.
engine_mouse_button_event on_mouse_button_up;
Listener signatures:
bool callback(int button, int clicks);
void callback(int button, int clicks);
A class implementing engine_mouse_button_event_listener, with a
bool on_mouse_button_up(int button, int clicks)orvoid on_mouse_button_up(int button, int clicks)method.
Arguments passed to listeners:
int button: the button that was released. 1 is the left button, 2 is the middle button, 3 is the right button, and 4 and 5 are the side buttons found on some mice.
int clicks: 1 if this release ends a single click, 2 if it ends a double click, and so on.
Remarks:
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
class hold_timer : engine_mouse_button_event_listener {
timer held;
void on_mouse_button_down(int button, int clicks) {
if (button == 1) held.restart();
}
void on_mouse_button_up(int button, int clicks) {
if (button == 1) screen_reader_output("Held for " + held.elapsed + " milliseconds", true);
}
}
void main() {
show_window("Example");
hold_timer ht;
on_mouse_button_down += ht;
on_mouse_button_up += ht;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Hold and release the left mouse button to hear how long you held it. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) wait(5);
on_mouse_button_down -= ht;
on_mouse_button_up -= ht;
}
on_mouse_move
An event that is fired whenever the mouse moves.
engine_mouse_motion_event on_mouse_move;
Listener signatures:
bool callback(float x, float y, float relative_x, float relative_y);
void callback(float x, float y, float relative_x, float relative_y);
A class implementing engine_mouse_motion_event_listener, with a
bool on_mouse_move(float x, float y, float relative_x, float relative_y)orvoid on_mouse_move(...)method taking the same parameters.
Arguments passed to listeners:
float x: the new horizontal position of the mouse within your window, the same as
MOUSE_ABSOLUTE_X.float y: the new vertical position of the mouse within your window, the same as
MOUSE_ABSOLUTE_Y.float relative_x: how far the mouse moved horizontally since the last event. Positive values mean right.
float relative_y: how far the mouse moved vertically since the last event. Positive values mean down.
Remarks:
The relative values are the same movement that MOUSE_X and MOUSE_Y add up between calls to mouse_update(). Unless mouse_relative_mode is enabled, they stop reporting movement in a direction once the cursor reaches the edge of the window or screen.
This event can fire many times per second, so keep listeners quick.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
float facing = 0;
void on_move(float x, float y, float relative_x, float relative_y) {
facing = (facing + relative_x * 0.25) % 360;
if (facing < 0) facing += 360;
}
void main() {
show_window("Example");
on_mouse_move += on_move;
mouse_relative_mode = true;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Move the mouse left or right to turn, press space to hear your facing, or escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_SPACE)) screen_reader_output(round(facing, 0) + " degrees", true);
}
}
on_mouse_wheel
An event that is fired whenever the mouse wheel is scrolled.
engine_mouse_wheel_event on_mouse_wheel;
Listener signatures:
bool callback(float x, float y);
void callback(float x, float y);
A class implementing engine_mouse_wheel_event_listener, with a
bool on_mouse_wheel(float x, float y)orvoid on_mouse_wheel(float x, float y)method.
Arguments passed to listeners:
float x: how far the wheel scrolled horizontally, on mice and touchpads that support it. Positive values mean right.
float y: how far the wheel scrolled vertically. Positive values usually mean the wheel was scrolled away from the user.
Remarks:
If the operating system is set to reverse the scrolling direction, the signs are reversed as well. Some mice and touchpads scroll in fractions of a step. The vertical amount is also added to MOUSE_ABSOLUTE_Z.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
int volume = 50;
void on_wheel(float x, float y) {
if (y == 0) return;
volume = clamp(volume + (y > 0 ? 5 : -5), 0, 100);
screen_reader_output(volume + " percent", true);
}
void main() {
show_window("Example");
on_mouse_wheel += on_wheel;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Scroll the mouse wheel to change the volume, or press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) wait(5);
}
on_touch_finger_cancel
An event that is fired when a touch is interrupted instead of ending normally.
engine_touch_event on_touch_finger_cancel;
Listener signatures:
bool callback(uint64 device, const touch_finger& finger);
void callback(uint64 device, const touch_finger& finger);
A class implementing engine_touch_event_listener, with a
bool on_touch_finger_cancel(uint64 device, const touch_finger& finger)orvoid on_touch_finger_cancel(uint64 device, const touch_finger& finger)method.
Arguments passed to listeners:
uint64 device: the ID of the touch device.
const touch_finger& finger: the finger whose touch was canceled.
Remarks:
The operating system cancels a touch when something else takes it over, for example a system gesture or a notification appearing. When this happens, on_touch_finger_up is not fired for that finger, so treat this event as the end of the touch but don't act on it as if the user had finished a tap.
The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
void on_cancel(uint64 device, const touch_finger& finger) {
screen_reader_output("Touch canceled", true);
}
void main() {
show_window("Example");
on_touch_finger_cancel += on_cancel;
while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}
on_touch_finger_down
An event that is fired whenever a finger touches a touch device.
engine_touch_event on_touch_finger_down;
Listener signatures:
bool callback(uint64 device, const touch_finger& finger);
void callback(uint64 device, const touch_finger& finger);
A class implementing engine_touch_event_listener, with a
bool on_touch_finger_down(uint64 device, const touch_finger& finger)orvoid on_touch_finger_down(uint64 device, const touch_finger& finger)method.
Arguments passed to listeners:
uint64 device: the ID of the touch device, which can be passed to functions such as
get_touch_device_name()andquery_touch_device().const touch_finger& finger: the finger that touched the device. Its id stays the same until the finger is lifted, x and y are its position from 0 to 1 across the device, and pressure is how hard it is pressing.
Remarks:
The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
void on_down(uint64 device, const touch_finger& finger) {
screen_reader_output("Touched at " + round(finger.x * 100, 0) + " percent across, " + round(finger.y * 100, 0) + " percent down", true);
}
void main() {
show_window("Example");
on_touch_finger_down += on_down;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Touch the screen to hear where you touched it. Press escape or back to exit.", true);
while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}
on_touch_finger_move
An event that is fired whenever a finger moves while touching a touch device.
engine_touch_motion_event on_touch_finger_move;
Listener signatures:
bool callback(uint64 device, const touch_finger& finger, float relative_x, float relative_y);
void callback(uint64 device, const touch_finger& finger, float relative_x, float relative_y);
A class implementing engine_touch_motion_event_listener, with a
bool on_touch_finger_move(uint64 device, const touch_finger& finger, float relative_x, float relative_y)orvoid on_touch_finger_move(...)method taking the same parameters.
Arguments passed to listeners:
uint64 device: the ID of the touch device.
const touch_finger& finger: the finger that moved, with its new position.
float relative_x: how far the finger moved horizontally since the last event, from -1 to 1 across the device. Positive values mean right.
float relative_y: how far the finger moved vertically since the last event, from -1 to 1 across the device. Positive values mean down.
Remarks:
The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
float swipe_x = 0;
void on_move(uint64 device, const touch_finger& finger, float relative_x, float relative_y) {
swipe_x += relative_x;
}
void on_up(uint64 device, const touch_finger& finger) {
if (swipe_x > 0.2) screen_reader_output("Swiped right", true);
else if (swipe_x < -0.2) screen_reader_output("Swiped left", true);
swipe_x = 0;
}
void main() {
show_window("Example");
on_touch_finger_move += on_move;
on_touch_finger_up += on_up;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Swipe left or right. Press escape or back to exit.", true);
while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
}
on_touch_finger_up
An event that is fired whenever a finger is lifted from a touch device.
engine_touch_event on_touch_finger_up;
Listener signatures:
bool callback(uint64 device, const touch_finger& finger);
void callback(uint64 device, const touch_finger& finger);
A class implementing engine_touch_event_listener, with a
bool on_touch_finger_up(uint64 device, const touch_finger& finger)orvoid on_touch_finger_up(uint64 device, const touch_finger& finger)method.
Arguments passed to listeners:
uint64 device: the ID of the touch device.
const touch_finger& finger: the finger that was lifted, with its last position and pressure. Its id matches the one passed to
on_touch_finger_downwhen it first touched the device.
Remarks:
If the touch is interrupted rather than ending normally, on_touch_finger_cancel is fired instead of this event.
The finger parameter must be declared exactly as const touch_finger& finger. Writing const touch_finger&in finger causes a "No matching signatures" error when adding the listener.
See the Events topic for how listeners are added, ordered and removed, and what their return values mean.
Example:
class tap_counter : engine_touch_event_listener {
int taps = 0;
void on_touch_finger_up(uint64 device, const touch_finger& finger) {
taps++;
screen_reader_output(taps + (taps == 1 ? " tap" : " taps"), true);
}
}
void main() {
show_window("Example");
tap_counter counter;
on_touch_finger_up += counter;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Tap the screen to count taps. Press escape or back to exit.", true);
while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) wait(5);
on_touch_finger_up -= counter;
}
Functions
alert
Display a message box with an OK button to the user.
int alert(const string&in title, const string&in text, bool can_cancel = false, uint flags = 0);
Arguments:
const string&in title: the title of the dialog.
const string&in text: the text of the dialog.
bool can_cancel = false: determines if a cancel button is present.
uint flags = 0: a combination of flags (see message_box_flags for more information).
Returns:
int: the number of the button that was pressed, either OK or cancel.
Example:
void main() {
alert("Hello", "I am a standard alert");
alert("Hi", "And I'm a cancelable one", true);
}
android_request_permission
Request a permission from the Android operating system either synchronously or asynchronously.
bool android_request_permission(string permission, android_permission_request_callback@ callback = null, string callback_data = "");
Arguments:
- string permission: A permission identifier such as android.permission.RECORD_AUDIO.
- android_permission_request_callback@ callback = null: An optional function that should be called when the user responds to the permission request (see remarks).
- string callback_data = "": An arbitrary string that is passed to the given callback function.
Returns:
bool: true if the request succeeded (see remarks), false otherwise or if this function was not called on Android.
Remarks:
The callback signature this function expects is registered as :
funcdef void android_permission_request_callback(string permission, bool granted, string user_data);
This function behaves very differently depending on whether you've provided a callback or not. If you do not, this function blocks the thread that called it until the user responds to the permission request, in which case it returns true or false depending on whether the user has actually granted the permission. On the other hand if you do provide a callback, the instant return value of this function only indicates whether the request has been made rather than whether the permission has been granted, as that information will be provided later in the given callback.
Beware that the callback you provide might get invoked on any thread, thus the provision of a more simple, blocking alternative. If you do provide a callback, you are responsible for handling any data races that may result.
android_show_toast
Shows an Android toast notification, small popups that are unique to that operating system.
bool android_show_toast(const string&in message, int duration, int gravity = -1, int x_offset = 0, int y_offset = 0);
Arguments:
- const string&in message: The message to display.
- int duration: 0 for short or 1 for long, all other values are undefined.
- int gravity = -1: One of the values on this page or -1 for no preference.
- int x_offset = 0, int y_offset = 0: Only used if gravity is set, see Android developer documentation.
Returns:
bool: true if the toast was shown, false otherwise or if called on a platform other than Android.
Remarks:
Learn more about android toasts notifications here.
clipboard_get_text
Returns the text currently on the user's clipboard.
string clipboard_get_text();
Returns:
string: The text on the user's clipboard, as UTF_8.
Example:
void main() {
string text = clipboard_get_text();
if (text == "")
alert("Info", "Your clipboard is empty");
else
if (text.length() > 1024)
alert("Info", "Your clipboard contains a long string. It is " + text.length() + " characters");
else
alert("Info", "Your clipboard contains " + text);
}
clipboard_set_raw_text
Sets the text on the user's clipboard, using the system encoding.
bool clipboard_set_raw_text(const string&in text);
Arguments:
- const string&in text: the text to copy, assumed to be in the system's encoding.
Returns:
Bool: true on success, false on failure.
Remarks:
To copy UTF-8 text, see clipboard_set_text().
Example:
void main() {
string text = input_box("Text", "Enter the text to copy.");
clipboard_set_raw_text(text);
if (text == "")
alert("Info", "Your clipboard has been cleared.");
else
alert("Info", "Text copied");
}
clipboard_set_text
Sets the text on the user's clipboard.
bool clipboard_set_text(const string&in text);
Arguments:
- const string&in text: the text to copy, assumed to be UTF_8.
Returns:
Bool: true on success, false on failure.
Remarks:
To copy text in the system encoding, see clipboard_set_raw_text().
Example:
void main() {
string text = input_box("Text", "Enter the text to copy.");
clipboard_set_text(text);
if (text == "")
alert("Info", "Your clipboard has been cleared.");
else
alert("Info", "Text copied");
}
create_surface
Create a new, blank graphic.
graphic@ create_surface(int width, int height, pixel_format pixel_format);
Arguments:
- int width: the width of the image in pixels.
- int height: the height of the image in pixels.
- pixel_format pixel_format: how the pixels are stored, such as PIXELFORMAT_ARGB8888 for an image with transparency.
Returns:
graphic@: the new image, or null if the size is negative or the format is PIXELFORMAT_UNKNOWN.
destroy_window
Destroys the currently shown window, if it exists.
bool destroy_window();
Returns:
bool: true if the window was successfully destroyed, false otherwise.
Example:
void main() {
alert("Info", "Pressing SPACE will destroy the window");
show_window("Example");
while (true) {
wait(5); // Don't hog all the CPU time.
if (key_pressed(KEY_SPACE)) {
destroy_window();
wait(2000); // Simulate doing things while the window isn't active.
exit();
}
}
}
exit
Completely shut down your application, returning a particular exit code to your operating system in the process.
void exit(int exit_code = 0);
Arguments:
- int exit_code = 0: the exit code to return to your operating system.
Example:
void main() {
show_window("Example");
screen_reader_output("Press escape to exit.", true);
while (true) {
wait(5);
if (key_pressed(KEY_ESCAPE)) {
screen_reader_output("Goodbye.", true);
wait(500);
exit();
}
}
}
focus_window
Attempt to bring your NVGT window to the foreground.
bool focus_window();
Returns:
bool: true if the window was successfully focused, false otherwise.
Example:
void main() {
timer focuser;
show_window("Focus every 5 seconds example");
while (true) {
wait(5);
if (key_pressed(KEY_ESCAPE)) exit();
if (focuser.has_elapsed(5000)) {
focuser.restart();
focus_window();
}
}
}
font_string_to_tag
Convert a 4 character code, such as an ISO 15924 script code like Latn or Arab, to the number text_font uses for it.
uint font_string_to_tag(const string&in str);
Arguments:
- const string&in str: the 4 character code.
Returns:
uint: the code as a number.
font_tag_to_string
Convert a number text_font uses for a 4 character code, such as text_font::script, back to the code.
string font_tag_to_string(uint tag);
Arguments:
- uint tag: the code as a number.
Returns:
string: the 4 character code.
get_characters
Determine any printable characters typed into the games window since this function's lass call.
string get_characters();
Returns:
string: Any characters typed since this function was last called, or an empty string if none are available.
Remarks:
This is the function one would use if they wished to integrate a virtual text field of any sort into their games or applications.
Unlike functions such as key_down or keys_pressed, this function focuses specifically on textual content which has been input to the application. A character returned from this function, for example, could be anything from the space bar to an emoticon inserted using the windows emoji picker.
A typical use case would involve calling this function once per iteration of your game loop and storing any new characters that are typed into a buffer that composes a chat message or a username or anything else requiring virtual text input.
Example:
void main() {
string buffer;
show_window("get_characters example");
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
string char = get_characters();
if (!char.empty()) {
buffer += char;
screen_reader_speak(char, true); // You need to process this further for screen readers, such as replacing . with period and other punctuation.
}
if (key_pressed(KEY_RETURN)) {
screen_reader_speak("You typed " + (!buffer.empty()? buffer : "nothing"), true);
buffer = "";
}
}
}
get_font
Get a font, sharing one object between everything that asks for the same font, size and style.
text_font@ get_font(const string&in name, float size, uint style = FONT_STYLE_NORMAL, bool allow_caching = true);
Arguments:
- const string&in name: the font to load, either the name of an installed font such as
arial, or the path to a .ttf file. - float size: the size of the font in points.
- uint style = FONT_STYLE_NORMAL: a combination of values from the font_style enum.
- bool allow_caching = true: whether to share the font. If false, a new font object is always created, which can be changed without affecting anything else.
Returns:
text_font@: the font. If it couldn't be loaded its methods fail and its family_name is empty.
Remarks:
Shared fonts stay loaded until NVGT exits. Changing the settings of a shared font, such as its size or style, changes it for everything that uses it.
get_touch_device_name
Determine the name of a touch device given it's ID.
string get_touch_device_name(uint64 device_id);
Returns:
string : The name of the given device, or an empty string on failure.
get_touch_device_type
Determine the type of a touch device given it's ID.
touch_device_type get_touch_device_name(uint64 device_id);
Returns:
touch_device_type: The type of the given device, or TOUCH_DEVICE_TYPE_INVALID if a bad ID is given.
get_touch_devices
Enumerate all available touch input devices on the system.
uint64[]@ get_touch_devices();
Returns:
uint64[]@: An array of touch device IDs, may be empty of no touch devices are available.
Remarks:
You can pass any of the IDs returned from this function to the get_touch_device_type, get_touch_device_name, or query_touch_device functions.
Note that on some platforms, certain touch devices might not become available until they first receive input. For example this is true with the Android touch screen.
Example:
void main() {
uint64[]@ devices = get_touch_devices();
if (devices.length() < 1) {
alert("no devices", "There are no detectable touch devices on your system.");
exit();
}
for (uint i = 0; i < devices.length(); i++)
alert("device " + devices[i], get_touch_device_name(devices[i]));
}
get_window_height
Gets the height of the game window in pixels.
int get_window_height();
Returns:
int: The height of the window in pixels, or 0 if no window is currently open.
Example:
void main() {
show_window("Window Size Example");
wait(50); // Give the window time to appear
int width = get_window_width();
int height = get_window_height();
alert("Window Size", "The window is " + width + " pixels wide and " + height + " pixels high.");
}
get_window_os_handle
Returns the native handle used by the operating system to manage NVGT's window.
uint64 get_window_os_handle();
Returns:
uint64: An HWND / NSWindow* / similar handle that the operating system uses to manage the window.
Remarks:
This function is only useful for someone trying to do something advanced, usually involving passing the identifier for the game window to a system API function or something similar. If you don't understand what this function does, you should probably avoid it for the present.
Example:
void main() {
// Lets set the window title using the windows API, typically you'd use show_window a second time for this.
show_window("hello");
uint64 handle = get_window_os_handle();
library lib;
lib.load("user32");
lib.call("int SetWindowTextA(uint64, ptr)", handle, "example window");
wait(500); // Let the user observe the change before exiting.
}
get_window_text
Returns the title of your window.
string get_window_text();
Returns:
string: the title of your window.
Example:
void main() {
string[] possible_titles = {"Hello world", "NVGT test", "My game", "Example", "Window title example"};
show_window(possible_titles[random(0, possible_titles.length() - 1)]);
while (true) {
wait(5);
if (key_pressed(KEY_ESCAPE)) exit();
if (key_pressed(KEY_SPACE)) {
screen_reader_output("The window title currently is: " + get_window_text(), true);
show_window(possible_titles[random(0, possible_titles.length() - 1)]); // Randomize the title again.
}
}
}
get_window_width
Gets the width of the game window in pixels.
int get_window_width();
Returns:
int: The width of the window in pixels, or 0 if no window is currently open.
Example:
void main() {
show_window("Window Size Example");
wait(50); // Give the window time to appear
int width = get_window_width();
int height = get_window_height();
alert("Window Size", "The window is " + width + " pixels wide and " + height + " pixels high.");
}
idle_ticks
Obtain the time passed in milliseconds since a user has pressed a key or used the mouse.
uint64 idle_ticks();
returns
uint64: the number of milliseconds since a user has last interacted with the machine.
remarks
This function can serve as a useful utility to verify whether a user has been away from the keyboard.
It is currently integrated for windows and MacOS. On linux, it will always return 0 until further notice.
Example:
void main() {
int64 t;
show_window("Idle test");
wait(50);
screen_reader_speak("Press space to check the idle time and escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_SPACE))
screen_reader_speak("You have been idle for %0 milliseconds".format(t), true);
t = idle_ticks();
}
}
info_box
Displays a dialog to the user consisting of a read-only text field and a close button.
bool info_box(const string&in title, const string&in label, const string&in text, uint64 flags = 0);
Arguments:
const string&in title: the title of the dialog.
const string&in label: the text to display above the text field.
const string&in text: the text to display in the text field.
uint64 flags = 0: a combination of flags, see message_box_flags for more information.
Returns:
bool: true if the user pressed the close button, false otherwise.
Example:
void main() {
info_box("Test", "Information", "this is a\r\nlong string\r\nthat can be split\r\nacross lines");
}
input_box
Displays a dialog to the user consisting of an input field, an OK button and a cancel button.
string input_box(const string&in title, const string&in text, const string&in default_text = "", uint64 flags = 0);
Arguments:
const string&in title: the title of the input box.
const string&in text: the text to display above the text field.
const string&in default_text = "": the contents to populate the text box with by default.
uint64 flags = 0: a combination of flags, see message_box_flags for more information.
Returns:
string: the text that the user typed.
Example:
void main() {
string name = input_box("Name", "What is your name?", "John Doe");
if (name.is_empty()) {
alert("Error", "You didn't type a name, unidentified person!");
exit();
}
alert("Hi", name + "!");
}
install_keyhook
Attempts to install NVGT's JAWS keyhook.
bool install_keyhook(bool allow_reinstall = true);
Arguments:
- bool allow_reinstall = true: whether or not this function will reinstall the hook on subsequent calls.
Returns:
bool: true if the keyhook was successfully installed, false otherwise.
Remarks:
This keyhook allows NVGT games to properly capture keyboard input while the JAWS for Windows screen reader is running.
Note that installing it when JAWS is not running may yield unintended consequences, such as functionality of other screen readers being slightly limited while in your game window.
Example:
void main() {
bool success = install_keyhook();
if (success) {
alert("Info", "The keyhook was successfully installed!");
uninstall_keyhook();
}
else
alert("Info", "The keyhook was not successfully installed.");
}
is_console_available
Determine if your application has access to a console window or not.
bool is_console_available();
Returns:
bool: true if your application has access to a console window, false otherwise.
Remarks:
If this function returns false, it is very likely that any output passed to the print or println functions or the cout/cerr datastreams will be silently dropped.
Example:
void main() {
if (is_console_available()) println("hello from the console!");
else alert("console unavailable", "hello from the user interface!");
}
is_window_active
Determines if your game's window is active (i.e. has the keyboard focus).
bool is_window_active();
Returns:
bool: true if your game window has the keyboard focus, false if not.
Example:
void main() {
show_window("Test");
wait(1000); // Give the user time to alt+tab away if they so choose.
bool active = is_window_active();
if (active)
alert("Info", "Your game window is active.");
else
alert("Info", "Your game window is not active.");
}
is_window_hidden
Determines if your game's window is hidden or not.
bool is_window_hidden();
Returns:
bool: true if your game window is hidden, false if it's shown.
Example:
void main() {
show_window("Test");
bool hide = random_bool();
if (hide) hide_window();
alert("The window is", is_window_hidden() ? "hidden" : "shown");
}
key_down
Determine if a particular key is held down.
bool key_down(uint key);
Arguments:
- uint key: the key to check.
Returns:
bool: true if the key is down at all, false otherwise.
Remarks:
For a complete list of keys that can be passed to this function, see input constants.
Example:
void main() {
show_window("Example");
while (true) {
wait(5);
if (key_down(KEY_SPACE))
screen_reader_output("space", true);
if (key_pressed(KEY_ESCAPE))
exit();
}
}
key_pressed
Determine if a particular key is pressed.
bool key_pressed(uint key);
Arguments:
- uint key: the key to check.
Returns:
bool: true if the key was just pressed, false otherwise.
Remarks:
For a complete list of keys that can be passed to this function, see input constants.
Example:
void main() {
show_window("Example");
while (true) {
wait(5);
if (key_pressed(KEY_SPACE))
screen_reader_output("You just pressed space!", true);
if (key_pressed(KEY_ESCAPE))
exit();
}
}
key_released
Determine if a particular key was just released.
bool key_released(uint key);
Arguments:
- uint key: the key to check.
Returns:
bool: true if the key was just released, false otherwise.
Remarks:
For a complete list of keys that can be passed to this function, see input constants.
Example:
void main() {
show_window("Example");
while (true) {
wait(5);
if (key_released(KEY_SPACE))
screen_reader_output("you just released the space key", true);
if (key_pressed(KEY_ESCAPE))
exit();
}
}
key_repeating
Determine if a particular key is repeating (i.e. it's being held, but wasn't just pressed).
bool key_repeating(uint key);
Arguments:
- uint key: the key to check.
Returns:
bool: true if the key is repeating, false otherwise.
Remarks:
For a complete list of keys that can be passed to this function, see input constants.
Example:
void main() {
show_window("Example");
while (true) {
wait(5);
if (key_repeating(KEY_SPACE))
screen_reader_output("space", true);
if (key_pressed(KEY_ESCAPE))
exit();
}
}
key_up
Determine if a particular key is up.
bool key_up(uint key);
Arguments:
- uint key: the key to check.
Returns:
bool: true if the key is up, false otherwise.
Remarks:
For a complete list of keys that can be passed to this function, see input constants.
Example:
void main() {
int last_spoken = ticks(); // Speak periodically to avoid overwhelming the user (or their screen reader).
show_window("Example");
while (true) {
wait(5);
if (key_up(KEY_SPACE) && (ticks() - last_spoken) >= 500) {
last_spoken = ticks();
screen_reader_output("space is up", true);
}
if (key_pressed(KEY_ESCAPE))
exit();
}
}
keys_down
Returns a handle to an array of keys that are held down.
uint[]@ keys_down();
Returns:
uint[]@: a handle to an array containing keys that are held down.
Remarks:
For a complete list of keys that can be returned by this function, see input constants.
keys_pressed
Returns a handle to an array of keys that were just pressed.
uint[]@ keys_pressed();
Returns:
uint[]@: a handle to an array containing keycodes that were just pressed.
Remarks:
For a complete list of keys that can be returned by this function, see input constants.
keys_released
Returns a handle to an array of keys that were just released.
uint[]@ keys_released();
Returns:
uint[]@: a handle to an array containing keycodes that were just released.
Remarks:
For a complete list of keys that can be returned by this function, see input constants.
load_bmp
Load a BMP image file into a graphic.
graphic@ load_bmp(const string&in file)graphic@ load_bmp(const string&in file, const pack_interface@ pack_file)
Arguments:
- const string&in file: the path of the file to load, or its name in the pack.
- const pack_interface@ pack_file (2): the pack to load the file from.
Returns:
graphic@: the image, or null if the file is missing or isn't a valid BMP image.
Remarks:
With a pack, null is also returned if the pack is null or hasn't been opened. See load_surface() to load an image of any supported type.
load_png
Load a PNG image file into a graphic.
graphic@ load_png(const string&in file)graphic@ load_png(const string&in file, const pack_interface@ pack_file)
Arguments:
- const string&in file: the path of the file to load, or its name in the pack.
- const pack_interface@ pack_file (2): the pack to load the file from.
Returns:
graphic@: the image, or null if the file is missing or isn't a valid PNG image.
Remarks:
With a pack, null is also returned if the pack is null or hasn't been opened. See load_surface() to load an image of any supported type.
load_surface
Load an image file of any supported type into a graphic.
graphic@ load_surface(const string&in file)graphic@ load_surface(const string&in file, const pack_interface@ pack_file)
Arguments:
- const string&in file: the path of the file to load, or its name in the pack.
- const pack_interface@ pack_file (2): the pack to load the file from.
Returns:
graphic@: the image, or null if the file is missing or isn't a supported image.
Remarks:
The type of the image is detected from its contents rather than its name, and includes BMP and PNG. With a pack, null is also returned if the pack is null or hasn't been opened.
message_box
Displays a customizable message box.
int message_box(const string&in title, const string&in text, string[]@ buttons, uint flags = 0);
Arguments:
const string&in title: the title of the message box.
const string&in text: the text of the message box.
string[]@ buttons: a string array of button names, see remarks for more info.
uint flags = 0: a combination of flags (see message_box_flags for more information).
Returns:
int: the number of the button that was pressed, according to its position in the buttons array.
Remarks:
Notes on button syntax:
A grave character (`) prepending button text is default enter key.
A tilde character (~) before text means default cancel.
Example:
void main() {
message_box("Hello there", "I am a message box with two buttons", {"`OK", "~Cancel"});
}
mouse_down
Determine if a particular mouse button is being held down.
bool mouse_down(uint8 button);
Arguments:
*uint8 button: The button to check.
Returns:
bool: True if the mouse button is being held, false otherwise.
Example:
void main()
{
while(true)
{
wait(5);
if(mouse_down(1))
{
screen_reader_output("Left click is being held!");
}
if(key_pressed(KEY_ESCAPE))
{
exit();
}
}
}
mouse_pressed
Determine if a particular mouse button is pressed.
bool mouse_pressed(uint8 button);
Arguments:
*uint8 button: The mouse button to check.
returns:
bool: If the specified mouse button was pressed.
Example:
void main()
{
show_window("Example");
while(true)
{
wait(5);
if(mouse_pressed(1))
{
screen_reader_output("You just pressed left click!");
}
if(key_pressed(KEY_ESCAPE))
{
exit();
}
}
}
open_file_dialog
Displays a dialog from which a user may select a file to open.
string open_file_dialog(string filters = "", string default_location = "")
Arguments:
string filters = "": A list of file extension filters (see remarks).
string default_location = "": The absolute initial directory to select files from (empty for OS default).
Returns:
string: The path to a file or an empty string on failure/cancelation.
Remarks:
The file extension filters are specified in the format description:extension|description:extension|description:extension1;extension2;extension3... You can also use the filter * as an all files filter. for example: audio files:mp3;wav;ogg|text files:txt;rtf;md|all files:* would produce 3 items in the file type combo box, those being audio files, text files and all files.
On some platforms it might be possible for the user to select a file that does not yet exist, so you should check for that condition yourself after the user selects a file just to be safe if that is important to you.
This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.
You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.
Example:
void main() {
string location = open_file_dialog("NVGT scripts:nvgt", cwdir());
if (location.empty()) return;
alert("example", "you selected " + location);
}
query_touch_device
Check what fingers are in contact with a touch device and where they are on the screen, if any.
touch_finger[]@ query_touch_device(uint64 device_id = 0);
Arguments:
- uint64 device_id = 0: The device to query, 0 for the last device that received input.
Returns:
touch_finger[]@: An array of structures containing touch coordinates and pressure (see remarks).
Remarks:
Each structure in the returned array represents a finger, thus the length of the array indicates how many fingers are touching the device.
Touch_finger objects contain only 4 properties. Int64 id is a unique identifier of the finger that will remain the same as long as the finger touches the devices, float x and float y contain the coordinates of the finger on the device, and the float pressure property indicates how much force or pressure the finger is being applied to the device with.
Usage of this structure other than to receive touch input is not endorsed by the NVGT developers and may lead to unexpected results, most notably creating a touch_finger instance manually will likely set it's properties to random uninitialized memory on the stack. You have been warned.
Example:
void main() {
// Report the number of fingers touching the device.
show_window("touch example");
tts_voice tts;
int prev_finger_count = 0;
tts.speak("ready", true);
while (!key_pressed(KEY_ESCAPE) and !key_pressed(KEY_AC_BACK)) {
wait(5);
touch_finger[]@ fingers = query_touch_device(); // This will query the last device that was touched.
if (fingers.length() != prev_finger_count) {
tts.speak(fingers.length() + (fingers.length() != 1? " fingers" : " finger"), true);
prev_finger_count = fingers.length();
}
}
}
question
Display a yes/no dialog box to the user.
int question(const string&in title, const string&in text, bool can_cancel = false, uint flags = 0);
Arguments:
const string&in title: the title of the dialog.
const string&in text: the text of the dialog.
bool can_cancel = false: determines if a cancel button is present alongside the other buttons.
uint flags = 0: a combination of flags (see message_box_flags for more information).
Returns:
int: the number of the button that was pressed (1 for yes, 2 for no).
Example:
void main() {
int res = question("Hello there", "Do you like pizza?");
alert("Info", "You clicked " + (res == 1 ? "yes" : "no"));
}
refresh_window
Updates the game window, pulling it for any new events and responding to messages from the operating system.
void refresh_window();
Remarks:
You do not need to call this function yourself so long as you use the recommended wait() function in your game's loops, as wait() implicitly calls this function. We provide refresh_window() standalone unless you want to use your own / a different sleeping mechanism such as nanosleep, in which case you do need to manually pull the window using this function.
For the main game window, the first refresh presents an initial black frame if nothing has been drawn yet. The same happens after showing a hidden window if no new drawing is pending. Later refreshes present only drawing that has not already been shown. If you call game_window.present() yourself, the next wait() or refresh_window() will not present that frame a second time.
For UI windows to function on the vast mejority of operating systems, they must maintain a constant stream of communication between the operating system and the program that created them. If a window stops receiving and handling such communications for even a few seconds, it will first become laggy before the operating system decides that the window has gone dead and begins reporting that the application is in a not responding or busy state.
To solve this problem in NVGT applications, refresh_window() is provided to do all of this message handling for you in one repeated function call. This function will pull the operating system for any new messages or events and process them, updating the states of functions like key_pressed, get_characters etc. If it is not repeatedly called in some way, your entire application will be disfunctional.
run
Allows for running exsacutable files from within your program.
bool run(const string&in filename, const string&in arguments, bool wait_for_completion, bool background);
Arguments:
const string&in filename: The exsacutable to run.
const string&in arguments: The arguments to provide to the executable.
bool wait_for_completion: Determines if the program pauses until the run function completes before continuing.
*bool background: Determines if a window is displayed.
Returns
bool: True if the executable was launched successfully.
Example:
void main()
{
//Opens notepad.
run("notepad.exe","",false,false);
}
save_file_dialog
Displays a dialog from which a user may select a location to save a file.
string save_file_dialog(string filters = "", string default_location = "")
Arguments:
string filters = "": A list of file extension filters (see remarks).
string default_location = "": The absolute initial directory to select from (empty for OS default).
Returns:
string: The path to save to or an empty string on failure/cancelation.
Remarks:
The file extension filters are specified in the format description:extension|description:extension|description:extension1;extension2;extension3... You can also use the filter * as an all files filter. for example: audio files:mp3;wav;ogg|text files:txt;rtf;md|all files:* would produce 3 items in the file type combo box, those being audio files, text files and all files.
Keep in mind that the user may select a file that already exists if they wish to overwrite it.
This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.
You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.
Example:
void main() {
string location = save_file_dialog("text files (*.txt):txt|all files:*");
if (location.empty()) return;
alert("example", "you selected " + location);
}
select_folder_dialog
Displays a dialog from which a user may select a folder.
string select_folder_dialog(string default_location = "")
Arguments:
- string default_location = "": The absolute initial directory to select from (empty for OS default).
Returns:
string: The path to a folder or an empty string on failure/cancelation.
Remarks:
Be aware that on some platforms, the user might be able to select a directory that does not yet exist.
This function is blocking, though we plan to add a version of the API in the future that uses a callback function or an event you can wait on if you wish to use this dialog asynchronously.
You should only call this function on your application's main thread, which is what happens by default unless you use any of NVGT's threading facilities.
Example:
void main() {
string location = select_folder_dialog();
if (location.empty()) return;
alert("example", "you selected " + location);
}
set_application_name
This function lets you set the name of your application. This is a name that's sent to your operating system in certain instances, for example in volume mixer dialogs or when an app goes not responding. It does not effect the window title or anything similar.
bool set_application_name(const string&in application_name);
Arguments:
- const string&in application_name: the name to set for your application.
Returns:
bool: true if the name was successfully set, false otherwise.
set_window_fullscreen
Make the main window fullscreen or return it to a normal window.
bool set_window_fullscreen(bool fullscreen);
Arguments:
- bool fullscreen: whether the window should be fullscreen.
Returns:
bool: true on success, false if there is no window or the change failed.
show_window
Shows a window with the specified title.
game_window@ show_window(const string&in title, uint flags = 0);
Arguments:
const string&in title: the title of the window.
uint flags: An optional set of flags to control the window's appearance. This can be a combination of values from the
window_flagsenum.
Returns:
game_window@: the main window, or null if it couldn't be created.
Remarks:
If the main window already exists, its title is changed and it is shown if it was hidden, rather than a second window being created. The window is also available afterwards through the global window property.
This window doesn't do any event processing by default. As such, you have to create a loop in order to keep it alive, calling wait() or refresh_window() regularly.
Example:
void main() {
alert("Info", "Press escape to close the window.");
show_window("Example", WINDOW_FLAG_RESIZABLE | WINDOW_FLAG_MAXIMIZED);
while (true) {
wait(5); // Don't hog all the CPU.
if (key_pressed(KEY_ESCAPE))
exit();
}
}
total_keys_down
Returns the total number of keys that are currently or have just been held down.
int total_keys_down();
Returns:
int: the number of keys currently or recently held down.
Remarks:
This function includes not only keys that are currently being held down, but also keys that have just been released within the last frame. It's purpose is to reduce the worklow of keyboard configuration systems that want to detect how many keys to monitor, including key releases.
Example:
void main() {
int check_time = 1000, orig_ticks = ticks();
show_window("Example");
while (true) {
wait(5);
if ((ticks() - orig_ticks) >= check_time) {
orig_ticks = ticks();
int key_count = total_keys_down();
screen_reader_output(key_count + " " + (key_count == 1 ? "key is" : "keys are") + " currently held down.", true);
}
if (key_pressed(KEY_ESCAPE))
exit();
}
}
uninstall_keyhook
Uninstall's NVGT's JAWS keyhook.
void uninstall_keyhook();
Remarks:
This keyhook allows NVGT games to properly capture keyboard input while the JAWS for Windows screen reader is running.
Example:
void main() {
install_keyhook();
alert("Info", "Keyhook installed. Uninstalling...");
uninstall_keyhook();
alert("Done", "Keyhook uninstalled.");
}
urlopen
Opens the specified URL in the appropriate application, for example an https:// link in your web browser, or a tt://link in TeamTalk.
bool urlopen(const string&in url);
Arguments:
- const string&in url: The URL to open.
Returns:
bool: true if the URl was successfully opened, false otherwise.
Remarks:
What application this function opens depends on what the user has set on their system; there's no way for you to control it.
Example:
void main() {
urlopen("https://nvgt.dev");
}
wait
Waits for a specified number of milliseconds.
void wait(int milliseconds);
Arguments:
- int milliseconds: the number of milliseconds to wait for.
Remarks:
This function blocks the calling thread, meaning no other work can happen on that thread until the wait period is over.
On the main thread, it performs other essential tasks, such as incremental garbage collection, internal event processing, and refreshing the window.
It is strongly advised to always put wait(5); in your main loops. This prevents your game from hogging the CPU, and also makes sure that the window remains responsive and has been updated with the latest input events from the user.
Please note that, due to low-level operating system scheduling behaviors, the millisecond parameter is not an exact value, but rather a guaranteed minimum. This is even more important to remember when calling from the main thread given the additional tasks performed. It should therefore never be used as a time marker where accuracy is required.
Example:
void main() {
alert("Info", "Once you press OK, I will wait for 2000 milliseconds (2 seconds).");
wait(2000);
alert("Info", "2000 milliseconds passed!");
}
Global Properties
cursor_visible
Shows or hides the mouse cursor, or determines whether it is currently visible.
bool cursor_visible;
Remarks:
Hiding the cursor only stops it from being drawn, the mouse still moves and generates input as normal. To keep the mouse inside your game's window, see mouse_grab.
This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false.
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Press space to show or hide the mouse cursor, or escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_SPACE)) {
cursor_visible = !cursor_visible;
screen_reader_output(cursor_visible ? "Cursor shown" : "Cursor hidden", true);
}
}
}
KEYBOARD_AVAILABLE
Determines whether a keyboard is connected to the device.
const bool KEYBOARD_AVAILABLE;
Remarks:
This is mainly useful on mobile devices, where your game might want to offer touch controls when no physical keyboard is attached.
This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false even if a keyboard is connected.
To list the connected keyboards, see get_keyboards().
Example:
void main() {
show_window("Example");
alert("Keyboard", KEYBOARD_AVAILABLE ? "A keyboard is connected." : "No keyboard is connected.");
}
keyboard_modifiers
Gets or sets the modifier keys, such as shift, control and the lock keys, that are currently active.
key_modifier keyboard_modifiers;
Remarks:
The value is a combination of the flags in the key_modifier enum. To check for a particular modifier, combine this value with the flag using the & operator and compare the result against 0, for example (keyboard_modifiers & KEYMOD_SHIFT) != 0. Remember the parentheses, because comparison operators are evaluated before &.
The KEYMOD_CTRL, KEYMOD_SHIFT, KEYMOD_ALT and KEYMOD_GUI values match either the left or the right version of their key.
Setting this property changes the modifier state that NVGT reports, but does not press or release any keys on the user's keyboard. This can be useful to clear a modifier that your game no longer wants to treat as held, for example after showing a dialog.
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Press space, optionally while holding shift or control. Press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (!key_pressed(KEY_SPACE)) continue;
string held;
if ((keyboard_modifiers & KEYMOD_SHIFT) != 0) held += "shift ";
if ((keyboard_modifiers & KEYMOD_CTRL) != 0) held += "control ";
screen_reader_output(held.empty() ? "Space" : held + "space", true);
}
}
MOUSE_ABSOLUTE_X, MOUSE_ABSOLUTE_Y and MOUSE_ABSOLUTE_Z
The current position of the mouse within your game's window, and the total distance its wheel has scrolled.
const float MOUSE_ABSOLUTE_X;const float MOUSE_ABSOLUTE_Y;const float MOUSE_ABSOLUTE_Z;
Remarks:
MOUSE_ABSOLUTE_X and MOUSE_ABSOLUTE_Y are the mouse coordinates relative to the top left corner of your window. They are updated whenever the mouse moves over the window, and are 0 until it does. MOUSE_ABSOLUTE_Z starts at 0 and adds up every scroll of the mouse wheel. Scrolling away from the user usually increases it, though the direction is reversed if the operating system is set to reverse scrolling.
While mouse_relative_mode is enabled, the operating system's cursor is hidden and these coordinates follow the mouse's movement but stay within the window. To track how far the mouse moves without limits, use MOUSE_X and MOUSE_Y.
Unlike MOUSE_X, MOUSE_Y and MOUSE_Z, these properties don't depend on mouse_update(). They are updated as input arrives, which happens during calls such as wait().
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Click anywhere in the window to hear where you clicked, or press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (mouse_pressed(1))
screen_reader_output(round(MOUSE_ABSOLUTE_X, 0) + ", " + round(MOUSE_ABSOLUTE_Y, 0), true);
}
}
MOUSE_AVAILABLE
Determines whether a mouse is connected to the device.
const bool MOUSE_AVAILABLE;
Remarks:
This property only reports accurate information once your game window has been shown with show_window(). Before that, it reads false even if a mouse is connected.
To list the connected mice, see get_mice().
Example:
void main() {
show_window("Example");
alert("Mouse", MOUSE_AVAILABLE ? "A mouse is connected." : "No mouse is connected.");
}
mouse_grab
Confines the mouse to your game's window, or determines whether it is currently confined.
bool mouse_grab;
Remarks:
While the mouse is grabbed, the cursor stays visible but can't leave the window. Because the cursor is still a normal cursor, MOUSE_X and MOUSE_Y stop reporting movement in a direction once the cursor reaches that edge of the window.
For games controlled by moving the mouse, mouse_relative_mode is usually what you want instead. It does everything grabbing does, keeping the mouse inside the window, and also hides the cursor and reports movement that never runs out at the window's edges. Grabbing is practically a subset of relative mode, so you don't need to enable both: while relative mode is enabled, the mouse is confined whether or not it is grabbed. Grabbing on its own is mainly useful when you want the cursor to stay visible and to keep its real position within the window, for example in a game where players click on things on screen.
Whether grabbed or in relative mode, the mouse is only confined while your window has focus. Switching to another window releases it until your window is focused again.
This only has an effect while your game window exists, so set it after calling show_window(). Without a window, it reads false. It also reads false while the mouse is only confined because relative mode is enabled.
This is the same setting as window.mouse_grab.
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Press space to grab or release the mouse, or escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_SPACE)) {
mouse_grab = !mouse_grab;
screen_reader_output(mouse_grab ? "Mouse grabbed" : "Mouse released", true);
}
}
}
mouse_relative_mode
Enables or disables relative mouse mode, or determines whether it is currently enabled.
bool mouse_relative_mode;
Remarks:
In relative mouse mode, the cursor is hidden and kept inside your game's window, and MOUSE_X and MOUSE_Y keep reporting how far the mouse moved even after the cursor would have hit the edge of the window or screen. This is what games that turn the player or aim with the mouse need. Without it, mouse movement in a direction stops being reported once the cursor reaches the edge of the window or screen. Where the platform allows it, movement is read directly from the mouse, so it isn't affected by the operating system's pointer acceleration.
Relative mode is disabled by default, because players don't expect a game to take over their mouse unless they are actively playing with it. A common approach is to enable it when gameplay starts and disable it again whenever the game is paused or a menu is open, so players can always get their mouse back by pressing escape.
Relative mode includes everything mouse_grab does, so there's no need to enable both. The mouse is only captured while your window has focus. Switching to another window releases it until your window is focused again.
MOUSE_ABSOLUTE_X and MOUSE_ABSOLUTE_Y still stay within the window while relative mode is enabled, so use MOUSE_X and MOUSE_Y to track movement.
You can set this before or after calling show_window(); the setting is applied whenever the window is created. Once the window exists, this is the same setting as window.mouse_relative_mode.
Example:
void main() {
show_window("Example");
mouse_relative_mode = true;
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Move the mouse left or right to turn, press space to toggle relative mode, or escape to exit.", true);
float facing = 0;
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
mouse_update();
if (key_pressed(KEY_SPACE)) {
mouse_relative_mode = !mouse_relative_mode;
screen_reader_output(mouse_relative_mode ? "Relative mode enabled" : "Relative mode disabled", true);
}
if (MOUSE_X == 0) continue;
facing = (facing + MOUSE_X * 0.25) % 360;
if (facing < 0) facing += 360;
screen_reader_output(round(facing, 0), true);
}
}
MOUSE_X, MOUSE_Y and MOUSE_Z
How far the mouse has moved, and how far its wheel has scrolled, between the two most recent calls to mouse_update().
const float MOUSE_X;const float MOUSE_Y;const float MOUSE_Z;
Remarks:
MOUSE_X and MOUSE_Y are the horizontal and vertical distance the mouse moved, in window coordinates. Positive values mean right and down. MOUSE_Z is how far the mouse wheel scrolled, where positive values usually mean the wheel was scrolled away from the user. If the operating system is set to reverse the scrolling direction (often called natural scrolling), the sign is reversed as well. Some mice and touchpads scroll in fractions of a step.
These values are only recalculated when you call mouse_update(), which is not called automatically. Call it once per iteration of your game loop, after wait(), and then read these properties. Calling mouse_update() more than once per iteration splits the movement between the calls, so later calls see smaller values.
By default, the movement stops once the cursor reaches the edge of the window or screen. If your game is controlled by moving the mouse, enable mouse_relative_mode so these values keep reporting movement no matter how far the mouse is moved in one direction. To be notified of each movement as it happens instead, see on_mouse_move.
To get the mouse position rather than how far it moved, see MOUSE_ABSOLUTE_X, MOUSE_ABSOLUTE_Y and MOUSE_ABSOLUTE_Z.
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Scroll the mouse wheel, or press escape to exit.", true);
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
mouse_update();
if (MOUSE_Z > 0) screen_reader_output("Scrolled up", true);
else if (MOUSE_Z < 0) screen_reader_output("Scrolled down", true);
}
}
SCREEN_KEYBOARD_SUPPORTED
Determines whether the platform provides an on-screen keyboard, such as the virtual keyboard on a phone or tablet.
const bool SCREEN_KEYBOARD_SUPPORTED;
Remarks:
On platforms with a screen keyboard, text input is not started automatically when your window is shown, because doing so would cover part of the screen with the keyboard. Call start_text_input() when your game wants the user to type, and stop_text_input() when it is done. On other platforms, text input is started automatically by show_window().
To check whether the screen keyboard is currently showing, see is_screen_keyboard_shown().
Example:
void main() {
show_window("Example");
alert("Screen keyboard", SCREEN_KEYBOARD_SUPPORTED ? "This device has a screen keyboard." : "This device does not have a screen keyboard.");
}
window
A handle to your game's main window, which gives access to more window settings than the global window functions provide.
game_window@ window;
Remarks:
This property is read only. It is null until a window has been created with show_window(), and becomes null again after destroy_window(). Check for null before using it if your code can run without a window.
Through this handle you can, for example, change the window's title, size and position, make it fullscreen, or draw text and shapes into it. See the game_window class for everything it offers.
Example:
void main() {
show_window("Example");
wait(50); // Give screen readers time to speak the window title.
screen_reader_output("Press space to change the window title, or escape to exit.", true);
int presses = 0;
while (!key_pressed(KEY_ESCAPE)) {
wait(5);
if (key_pressed(KEY_SPACE)) {
presses++;
window.set_title("Space pressed " + presses + (presses == 1 ? " time" : " times"));
screen_reader_output(window.title, true);
}
}
}