### Full Contextual Menu Example
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Contextual
This example demonstrates a complete contextual menu within a Nuklear window, featuring labels and interactive buttons for file management actions. `nk_contextual_item_label` functions as a button.
```c
static void scratchpad(struct nk_context *ctx, struct media *media) {
nk_style_set_font(ctx, &media->font_20->handle);
struct nk_rect window_bounds = nk_rect(250, 250, 255, 340);
nk_begin(ctx, "Nuklear Contextual example", window_bounds, NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
if (nk_contextual_begin(ctx, NK_PANEL_CONTEXTUAL, nk_vec2(200, 500), window_bounds)) {
nk_layout_row_dynamic(ctx, 25, 1);
nk_contextual_item_label(ctx, "View", NK_TEXT_CENTERED);
if (nk_contextual_item_label(ctx, "New file", NK_TEXT_CENTERED)) {
printf("%s", "Creating a new file!\n");
}
if (nk_contextual_item_label(ctx, "New folder", NK_TEXT_CENTERED)) {
printf("%s", "Creating a new folder!\n");
}
nk_contextual_item_label(ctx, "More options...", NK_TEXT_CENTERED);
nk_contextual_end(ctx);
}
nk_end(ctx);
}
```
--------------------------------
### Install Git with Homebrew
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started-on-Mac
Install Git using Homebrew if it is not already present on your system.
```bash
$ brew install git
```
--------------------------------
### Begin a Contextual Menu
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Contextual
Use `nk_contextual_begin` to start creating a contextual menu. It requires flags, desired size, and bounds for opening. Items are then added using specific functions.
```c
struct nk_rect window_bounds = nk_rect(50, 50, 255, 340);
if (nk_contextual_begin(ctx, NK_PANEL_CONTEXTUAL, nk_vec2(200, 500), window_bounds)) {
nk_layout_row_dynamic(ctx, 25, 1);
nk_contextual_item_label(ctx, "New folder", NK_TEXT_CENTERED);
nk_contextual_item_label(ctx, "New file", NK_TEXT_CENTERED);
nk_contextual_end(ctx);
}
```
--------------------------------
### File Menu Example
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Menu
Demonstrates creating a 'File' menu with 'New', 'Open', and 'Save' options within a Nuklear window. This example uses `nk_menu_begin_label` for the menu title and `nk_button_label` and `nk_button_image_label` for menu items.
```c
static void scratchpad(struct nk_context *ctx, struct media *media) {
nk_style_set_font(ctx, &media->font_20->handle);
struct nk_vec2 size = nk_vec2(150, 200);
nk_begin(ctx, "Nuklear Menu example", nk_rect(50,50, 255, 340), NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
nk_layout_row_dynamic(ctx, 20, 1);
if (nk_menu_begin_label(ctx, "File", NK_TEXT_LEFT, size)) {
nk_layout_row_dynamic(ctx, 20, 1);
nk_button_label(ctx, "New");
nk_button_image_label(ctx, media->dir, "Open...", NK_TEXT_LEFT);
nk_button_label(ctx, "Save");
nk_menu_end(ctx);
}
nk_end(ctx);
}
```
--------------------------------
### Install GLFW3 with Homebrew
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started-on-Mac
Use Homebrew to install the GLFW3 library, a dependency for Nuklear's OpenGL backend.
```bash
$ brew install glfw3
```
--------------------------------
### Combobox Example with Text Display
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Combobox
This example demonstrates a combobox within a Nuklear window. It displays the selected item's index using `sprintf` and `nk_text`.
```c
static void scratchpad(struct nk_context *ctx) {
nk_style_set_font(ctx, &media->font_20->handle);
static const char *my_options[] = {"Option 1", "Option 2", "Option 3", "Option 4"}; // The options we want to display
static int selected_item_index = 0; // Selected item index
struct nk_vec2 size = {100, 60}; // Size of the dropdown combobox
nk_begin(ctx, "Nuklear Combobox example", nk_rect(50,50, 255, 340), NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
nk_layout_row_dynamic(ctx, 20, 1);
nk_combobox(ctx, my_options, 4, &selected_item_index, 20, size); // draw the combobox
char buffer[20];
sprintf(buffer, "Selected %d", selected_item_index);
nk_text(ctx, buffer, strlen(buffer), NK_TEXT_LEFT); // display our selected index
nk_end(ctx);
}
```
--------------------------------
### Install GLEW with Homebrew
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started-on-Mac
Use Homebrew to install the GLEW library, another dependency for Nuklear's OpenGL backend.
```bash
$ brew install glew
```
--------------------------------
### Color Picker in Window Example (C)
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Color-Picker
An example of integrating `nk_color_picker` within a Nuklear window to dynamically change the color of displayed text. Note the conversion from `nk_colorf` to `nk_color` using `nk_rgb_cf` for `nk_text_colored`.
```c
static void scratchpad(struct nk_context *ctx, struct media *media) {
static struct nk_colorf my_color = {0.8f, 0.3f, 0.2f, 1.0f};
static const char my_text[] = "What a nice color! Or is it colour...?";
nk_style_set_font(ctx, &media->font_20->handle);
nk_begin(ctx, "Nuklear Color Picker example", nk_rect(50,50, 255, 340), NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
nk_layout_row_dynamic(ctx, 200, 1);
my_color = nk_color_picker(ctx, my_color, NK_RGBA); /// Our color picker, returns the newly selected color which we can then use elsewhere
nk_layout_row_dynamic(ctx, 20, 1);
nk_text_colored(ctx, my_text, strlen(my_text), NK_TEXT_LEFT, nk_rgb_cf(my_color)); /// nk_text_colored takes an rgb color instead of rgba so we have to do some magic (nk_rgb_cf)
nk_end(ctx);
}
```
--------------------------------
### Initialize Nuklear UI and Create Widgets
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/src/HEADER.md
Initializes the Nuklear UI context with fixed memory and demonstrates creating various widgets like buttons, option toggles, labels, and sliders within a window. This example shows how to manage UI state and handle basic user interactions.
```c
// init gui state
enum {EASY, HARD};
static int op = EASY;
static float value = 0.6f;
static int i = 20;
struct nk_context ctx;
nk_init_fixed(&ctx, calloc(1, MAX_MEMORY), MAX_MEMORY, &font);
if (nk_begin(&ctx, "Show", nk_rect(50, 50, 220, 220),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) {
// fixed widget pixel width
nk_layout_row_static(&ctx, 30, 80, 1);
if (nk_button_label(&ctx, "button")) {
// event handling
}
// fixed widget window ratio width
nk_layout_row_dynamic(&ctx, 30, 2);
if (nk_option_label(&ctx, "easy", op == EASY)) op = EASY;
if (nk_option_label(&ctx, "hard", op == HARD)) op = HARD;
// custom widget pixel width
nk_layout_row_begin(&ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push(&ctx, 50);
nk_label(&ctx, "Volume:", NK_TEXT_LEFT);
nk_layout_row_push(&ctx, 110);
nk_slider_float(&ctx, 0, &value, 1.0f, 0.1f);
}
nk_layout_row_end(&ctx);
}
nk_end(&ctx);
```
--------------------------------
### Initialize Nuklear SDL Vulkan Context
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_vulkan/README.md
Call this function during setup to initialize the Nuklear context with Vulkan resources. Ensure overlay images match swap chain images in count and format.
```c
/*
Setup: overlay_images have been created and their number match with the number
of the swap_chain_images of your application. The overlay_images in this
example have the same format as your swap_chain images (optional)
*/
struct nk_context *ctx = nk_sdl_init(
demo.win, demo.device, demo.physical_device, demo.indices.graphics,
demo.overlay_image_views, demo.swap_chain_images_len,
demo.swap_chain_image_format, 0,
MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
```
--------------------------------
### Complex Tooltip with nk_tooltip_begin/end
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Tooltip
This example shows how to create advanced tooltips using `nk_tooltip_begin(...)` and `nk_tooltip_end(...)`. This method allows embedding various Nuklear widgets, such as images and buttons, within the tooltip.
```c
static void scratchpad(struct nk_context *ctx, struct media *media) {
nk_style_set_font(ctx, &media->font_20->handle);
nk_begin(ctx, "Nuklear Tooltips example", nk_rect(50,50, 255, 340), NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
const char my_text[] = "Hover me!";
nk_layout_row_dynamic(ctx, 20, 1);
if (nk_widget_is_hovered(ctx)) { /// If the widget below here is hovered, do something...
nk_tooltip_begin(ctx, 400); /// Begin tooltip
nk_layout_row_dynamic(ctx, 400, 1); /// We can add whatever we like here...
nk_image(ctx, media->cloud); /// ...Like images!
nk_layout_row_dynamic(ctx, 40, 1);
nk_button_label(ctx, "Click me if you can! Haha"); /// ... or buttons, try clicking it ;)
nk_tooltip_end(ctx);
}
nk_text(ctx, my_text, strlen(my_text), NK_TEXT_LEFT);
nk_end(ctx);
}
```
--------------------------------
### Initialize Nuklear Context with Vulkan
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/glfw_vulkan/README.md
Initializes the Nuklear context for GLFW and Vulkan. Ensure overlay images are created and match the swap chain's properties. This function installs callbacks for window events.
```c
/*
Setup: overlay_images have been created and their number match with the number
of the swap_chain_images of your application. The overlay_images in this
example have the same format as your swap_chain images (optional)
*/
struct nk_context *ctx = nk_glfw3_init(
demo.win, demo.device, demo.physical_device, demo.indices.graphics,
demo.overlay_image_views, demo.swap_chain_images_len,
demo.swap_chain_image_format, NK_GLFW3_INSTALL_CALLBACKS,
MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER);
```
--------------------------------
### Nuklear Row Template with Dynamic and Static Widgets
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Use nk_layout_row_template_push_dynamic for widgets that should resize with the row, and nk_layout_row_template_push_static for widgets with a fixed pixel width. This example shows a resizable textbox next to a fixed-width button.
```c
nk_layout_row_template_begin(ctx, 24);
nk_layout_row_template_push_dynamic(ctx);
nk_layout_row_template_push_static(ctx, 100);
nk_layout_row_template_end(ctx);
static char buffer[256] = "This can grow or shrink";
nk_edit_string_zero_terminated(ctx, NK_EDIT_SIMPLE, buffer, sizeof(buffer), nk_filter_ascii);
nk_button_label(ctx, "Fixed size");
```
--------------------------------
### Nuklear Row Template with Variable Width Widget
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Utilize nk_layout_row_template_push_variable to create a widget that can resize but has a defined minimum width. This example demonstrates a button that shrinks down to 100 pixels.
```c
// example using nk_layout_row_template_push_variable
nk_layout_row_template_begin(ctx, 24);
nk_layout_row_template_push_variable(ctx, 100);
nk_layout_row_template_end(ctx);
nk_button_label(ctx, "This can grow or shrink, but only down to 100px");
```
--------------------------------
### Display UTF-8 Button with Chinese Characters
Source: https://github.com/immediate-mode-ui/nuklear/wiki/UTF-8-Support
Example of displaying a button with Chinese characters. This may require specific IDE configurations or compiler support.
```C
if (nk_button_label(context, "嗨")) {}
```
--------------------------------
### Define Unicode Ranges for Icon Characters in C
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Define an array of nk_rune for icon characters. This example includes specific codepoints for icons. The array must be null-terminated and have a persistent scope.
```c
nk_rune ranges_icons[] = {
0xF07C, 0xF07C, /* */
0xF083, 0xF083, /* */
0xF0AD, 0xF0AD, /* */
0xF021, 0xF021, /* */
0
};
```
--------------------------------
### Tooltip on Hovered Text with nk_tooltip
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Tooltip
This example demonstrates displaying a tooltip when a specific text widget is hovered. It uses `nk_widget_is_hovered` to check for hover events and `nk_tooltip` to show the associated text.
```c
static void scratchpad(struct nk_context *ctx, struct media *media) {
nk_style_set_font(ctx, &media->font_20->handle);
nk_begin(ctx, "Nuklear Tooltips example", nk_rect(50,50, 255, 340), NK_WINDOW_TITLE | NK_WINDOW_MOVABLE);
const char my_text[] = "This is a very long string that doesnt fit!";
nk_layout_row_dynamic(ctx, 20, 1);
if (nk_widget_is_hovered(ctx)) { /// If the widget below here is hovered, do something...
nk_tooltip(ctx, my_text); /// ... Display our tooltip!
}
nk_text(ctx, my_text, strlen(my_text), NK_TEXT_LEFT); /// Our text, that doesnt quite seem to fit our window.
nk_end(ctx);
}
```
--------------------------------
### Build Linux/Mac OS X Version
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_opengles2/Readme.md
Use 'make' to build the standard Linux or Mac OS X version of the demo. Ensure your system supports OpenGL ES.
```bash
make
```
--------------------------------
### Initialize and Build GUI with Nuklear
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/README.md
Initializes the Nuklear GUI context and demonstrates building a simple window with buttons, options, and a slider. Requires NK_WINDOW_BORDER, NK_WINDOW_MOVABLE, and NK_WINDOW_CLOSABLE flags for window behavior.
```c
/* init gui state */
struct nk_context ctx;
nk_init_fixed(&ctx, calloc(1, MAX_MEMORY), MAX_MEMORY, &font);
enum {EASY, HARD};
static int op = EASY;
static float value = 0.6f;
static int i = 20;
if (nk_begin(&ctx, "Show", nk_rect(50, 50, 220, 220),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) {
/* fixed widget pixel width */
nk_layout_row_static(&ctx, 30, 80, 1);
if (nk_button_label(&ctx, "button")) {
/* event handling */
}
/* fixed widget window ratio width */
nk_layout_row_dynamic(&ctx, 30, 2);
if (nk_option_label(&ctx, "easy", op == EASY)) op = EASY;
if (nk_option_label(&ctx, "hard", op == HARD)) op = HARD;
/* custom widget pixel width */
nk_layout_row_begin(&ctx, NK_STATIC, 30, 2);
{
nk_layout_row_push(&ctx, 50);
nk_label(&ctx, "Volume:", NK_TEXT_LEFT);
nk_layout_row_push(&ctx, 110);
nk_slider_float(&ctx, 0, &value, 1.0f, 0.1f);
}
nk_layout_row_end(&ctx);
}
nk_end(&ctx);
```
--------------------------------
### Define Window Parameters
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Sets up the basic parameters for a Windows window, including its class name and initial dimensions.
```C
ATOM atom;
RECT rect = { 0, 0, 500, 500};
DWORD style = WS_OVERLAPPEDWINDOW;
DWORD exstyle = WS_EX_APPWINDOW;
/* Win32 */
memset(&wc, 0, sizeof(wc));
wc.style = CS_DBLCLKS;
// Reserve space to store the instance pointer
wc.lpfnWndProc = WindowProc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.lpszClassName = L"NuklearWindowClass";
atom = RegisterClassW(&wc);
```
--------------------------------
### Build Nuklear Project
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started---Mac-OS-X
Navigate to the Nuklear directory in the terminal and use the 'make' command to build the project. Warnings are acceptable as long as there are no errors.
```bash
$ cd nuklear
$ make
```
--------------------------------
### Build Nuklear Project
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started-on-Mac
Navigate to the nuklear directory in the terminal and use 'make' to build the project. Warnings are acceptable as long as there are no errors.
```bash
$ make
```
--------------------------------
### Font Xadvance Values Before Pixel Snap
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Example of raw xadvance values for font glyphs before applying the pixel snap feature. These values represent the horizontal advance for each character.
```text
10.646959, 13.322636, 12.393581, 17.949324, 18.135136, 14.939189, 16.555744, 12.040541, 11.854730, 18.841217, 12.059122, 10.479730, 11.297297, 10.535473, 8.528716, 11.037162, 10.293919, 14.121622, 9.476352, 11.724662, 11.724662, 10.331081, 11.000000, 13.136825, 11.668919, 11.260136, 11.483109, 11.520270, 9.457770, 9.532095, 9.680743, 15.236486, 9.253379, 11.501689, 10.628379, 15.552365, 15.701014, 12.356419, 13.991554, 10.182432, 9.457770, 15.310811, 10.665541
```
--------------------------------
### Build Raspberry Pi Version
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_opengles2/Readme.md
Build the demo for Raspberry Pi using 'make rpi'. This requires accelerated OpenGL ES2 output and potentially a custom SDL2 build.
```bash
make rpi
```
--------------------------------
### Create and Use Color Picker (C)
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Color-Picker
Demonstrates the basic usage of `nk_color_picker` to select a color. It takes an initial `nk_colorf` and returns the updated color.
```c
struct nk_colorf my_color = {0.8f, 0.3f, 0.2f, 1.0f};
my_color = nk_color_picker(ctx, my_color, NK_RGBA);
```
--------------------------------
### Font Xadvance Values After Pixel Snap
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Example of xadvance values for font glyphs after applying the pixel snap feature. Notice how the values are rounded to the nearest integer, affecting character spacing.
```text
11.000000, 13.000000, 12.000000, 18.000000, 18.000000, 15.000000, 17.000000, 12.000000, 12.000000, 19.000000, 12.000000, 10.000000, 11.000000, 11.000000, 9.000000, 11.000000, 10.000000, 14.000000, 9.000000, 12.000000, 12.000000, 10.000000, 11.000000, 13.000000, 12.000000, 11.000000, 11.000000, 12.000000, 9.000000, 10.00000, 10.00000, 15.000000, 9.000000, 12.000000, 11.000000, 16.000000, 16.000000, 12.000000, 14.000000, 10.000000, 9.000000, 15.000000, 11.000000
```
--------------------------------
### Create Windows Window
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Creates the main application window using the defined parameters. Adjusts window size to accommodate client area.
```C
AdjustWindowRectEx(&rect, style, FALSE, exstyle);
wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo",
style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT,
rect.right - rect.left, rect.bottom - rect.top,
nullptr, nullptr, wc.hInstance, nullptr);
```
--------------------------------
### Create a Basic Window in Nuklear
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Window
Use `nk_begin` and `nk_end` to define a window. The `NK_WINDOW_CLOSABLE` flag allows the user to close the window.
```c
if (nk_begin(ctx, "Nuklear", nk_rect(WINDOW_WIDTH/2 - 110, WINDOW_HEIGHT/2 - 110, 220, 220),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) {
// Widgets code here
}
nk_end(ctx);
```
--------------------------------
### Access Linked Font Data in C
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
After linking a font object file, you can access the font data using extern symbols provided by the linker. The size is calculated by subtracting the start and end symbols.
```c
extern const char _binary_font_ttf_start[];
extern const char _binary_font_ttf_end[];
const char* font_data = _binary_font_ttf_start;
const size_t font_size = _binary_font_ttf_end - _binary_font_ttf_start;
```
--------------------------------
### Basic Menu Usage
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Menu
This is the basic structure for using any menu type. Remember to always end a menu with `nk_menu_end(...)`.
```c
if (nk_menu_begin_label(...)) {
/// Draw whatever you like!
nk_menu_end(...);
}
```
--------------------------------
### Create Font Configuration
Source: https://github.com/immediate-mode-ui/nuklear/wiki/UTF-8-Support
Initialize nk_font_config with desired pixel height and oversampling settings for high-quality rasterization.
```cpp
struct nk_font_config config = nk_font_config(14);
config.oversample_h = 1;
config.oversample_v = 1;
```
--------------------------------
### Row Layout Begin/End - Dynamic Columns
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Use nk_layout_row_begin with NK_DYNAMIC for dynamic rows. The second argument of nk_layout_row_push specifies a width percentage (e.g., 0.25f for 25%).
```c
// Defining dynamic rows works similarly. Instead of NK_STATIC you need to use NK_DYNAMIC.
// The second argument of nk_layout_row_push has a different meaning when working with dynamic rows.
// For static rows it describes an absolute width. Dynamic rows use a width percentage instead (e.g. 0.25f for 25% width).
// Example for dynamic rows (not directly in code block, but described in text):
// nk_layout_row_begin(ctx, NK_DYNAMIC, 30, 1);
// {
// nk_layout_row_push(ctx, 0.5f); // 50% width
// nk_label(ctx, "Dynamic Label 1", NK_TEXT_LEFT);
// nk_layout_row_push(ctx, 0.5f); // 50% width
// nk_label(ctx, "Dynamic Label 2", NK_TEXT_LEFT);
// }
nk_layout_row_end(ctx);
```
--------------------------------
### Basic Float Slider - C++
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Slider
Demonstrates how to create and use a float slider. The slider's value is updated in real-time. Ensure the `nk_context` is properly initialized.
```cpp
// The value will change if you play with the slider
float value = 0.5f;
nk_slider_float(&ctx, 0, &value, 1.0f, 0.1f);
```
--------------------------------
### Simple Tooltip with nk_tooltip
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Tooltip
Use `nk_tooltip(...)` for displaying basic text pop-ups. This is the easiest method for simple information display.
```c
nk_tooltip(ctx, "This is a tooltip");
```
--------------------------------
### Initialize and Edit Text Buffer
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Text-Edit
Demonstrates initializing a character buffer and using it with `nk_edit_string_zero_terminated` for text input. Ensure the buffer is initialized before `GuiMain` if a default value is needed. The `NK_EDIT_AUTO_SELECT` flag automatically selects text on focus.
```c
/* Global so it can be accessed by both functions */
char buffer[256];
/* This function should be called before GuiMain() in case we wanted to
* initialize the buffer with some value. */
void GuiInit() {
strcpy(buffer, "This is some content");
}
void GuiMain() {
if (nk_begin(...)) {
nk_flags event = nk_edit_string_zero_terminated(
ctx,
NK_EDIT_BOX | NK_EDIT_AUTO_SELECT, /* Auto-select for focusing the text on click */
buffer, sizeof(buffer), nk_filter_ascii /* nk_filter_ascii: text type */
);
}
nk_end(ctx);
}
```
--------------------------------
### Initialize Nuklear Context with GDI
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Retrieves the device context, creates a GDI font, and initializes the Nuklear context for rendering.
```C
/* GUI */
dc = GetDC(wnd);
font = nk_gdifont_create("Arial", 14);
ctx = nk_gdi_init(font, dc, 200, 200);
```
--------------------------------
### Build WebGL Version with Emscripten
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_opengles2/Readme.md
Compile the demo into WebGL using Emscripten by running 'make web'. This version is suitable for web browsers.
```bash
make web
```
--------------------------------
### Initialize Nuklear with DirectX 9
Source: https://github.com/immediate-mode-ui/nuklear/wiki/D3D-9
Call this function to initialize Nuklear with your DirectX 9 device and set up the GUI context. Font atlas is also prepared.
```c
/* Initiating the GUI */
ctx = nk_d3d9_init(d3ddev, s_width, s_height);
struct nk_font_atlas *atlas;
{
struct nk_font_atlas *atlas;
nk_d3d9_font_stash_begin(&atlas);
nk_d3d9_font_stash_end();
}
```
--------------------------------
### Row Layout Begin/End - Static Columns
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Manually define row layouts using nk_layout_row_begin and nk_layout_row_push. For NK_STATIC, values pushed represent absolute column widths.
```c
// This will create a row layout with a single column
// void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols)
nk_layout_row_begin(ctx, NK_STATIC, 30, 1);
{
// nk_layout_row_push(struct nk_context *ctx, float value)
// when using NK_STATIC, `value` means width of each column nk_layout_row_push(ctx, 100); nk_label(ctx, "First Row", NK_TEXT_LEFT);
nk_layout_row_push(ctx, 100); nk_label(ctx, "Second Row", NK_TEXT_LEFT);
}
nk_layout_row_end(ctx);
```
--------------------------------
### Render Nuklear UI to Overlay Image
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_vulkan/README.md
Use this in your draw loop to render the Nuklear UI to a specific overlay image. The application must then wait for the semaphore and produce the swap chain image, sampling from the overlay image.
```c
/*
in your draw loop draw you can then render to the overlay image at
`image_index`
your own application can then wait for the semaphore and produce
the swap_chain_image at `image_index`
this should simply sample from the overlay_image (see example)
*/
nk_semaphore semaphore =
nk_sdl_render(demo.graphics_queue, image_index,
demo.image_available, NK_ANTI_ALIASING_ON);
if (!render(&demo, &bg, nk_semaphore, image_index)) {
fprintf(stderr, "render failed\n");
return false;
}
```
--------------------------------
### Include Nuklear Implementation
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/README.md
Define NK_IMPLEMENTATION in one .c/.cpp file before including nuklear.h to enable the library's implementation. Ensure all includes use the same optional flags.
```c
#define NK_IMPLEMENTATION
#include "nuklear.h"
```
--------------------------------
### Initialize Font Configuration in C
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Initialize nk_font_config structures for each font you intend to load. The initial size is set to 0, as it will be determined during the baking process. These configurations define how each font will be processed.
```c
struct nk_font_config cfg_latin = nk_font_config(0);
struct nk_font_config cfg_icons = nk_font_config(0);
struct nk_font_config cfg_japan = nk_font_config(0);
```
--------------------------------
### Row Layout with Width Ratios - Static and Dynamic
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Use nk_layout_row to define rows with custom width ratios for each column. Ratios can be absolute pixel widths (NK_STATIC) or fractions of available space (NK_DYNAMIC).
```c
// for NK_STATIC, the widths refer to absolute pixel widths
float row1_widths[] = {85, 20, 150};
// for NK_DYNAMIC, the widths refer to the fraction of the window width
// the widgets will take up
float row2_widths[] = {0.25f, 0.1f, 0.65f};
// nk_layout_row(struct nk_context *ctx, enum nk_layout_format fmt, float height, int cols, const float *ratio)
nk_layout_row(ctx, NK_STATIC, 40, 3, row1_widths);
nk_button_label(ctx, "A");
nk_button_label(ctx, "B");
nk_button_label(ctx, "C");
// the widths will repeat for these next three buttons
nk_button_label(ctx, "D");
nk_button_label(ctx, "E");
nk_button_label(ctx, "F");
nk_layout_row(ctx, NK_DYNAMIC, 40, 3, row2_widths);
nk_button_label(ctx, "G");
nk_button_label(ctx, "H");
nk_button_label(ctx, "I");
```
--------------------------------
### Include Nuklear GDI Headers
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Includes necessary headers for Nuklear and its GDI integration. Ensure you are compiling against the gdi32 library.
```C
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include
#define NK_IMPLEMENTATION
#define NK_ASSERT
#include "nuklear/nuklear.h"
#include "nuklear/demo/gdi/nuklear_gdi.h"
```
--------------------------------
### Create a Selectable Label
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Selectable
Use `nk_selectable_label` to create a label that can be selected. The selection state is managed by a boolean variable passed by reference.
```C++
static int selected = nk_true; /* outside main cycle */
```
```C++
/* within main cycle */
if (nk_begin(ctx, "Test", nk_rect(32, 32, 192, 192), NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_CLOSABLE))
{
nk_layout_row_dynamic(ctx, 30, 1);
nk_selectable_label(ctx, "label_1", NK_TEXT_LEFT, &selected);
}
k_end(ctx);
```
--------------------------------
### Link Font File as Object (LLVM/Clang Toolchain)
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
This command converts a font file into an object file, specifying the target architecture for the LLVM/Clang toolchain. This allows the font data to be accessed from memory.
```bash
ld -r -b binary -m elf_amd64 -o font.o font.ttf
```
--------------------------------
### Create a Combobox
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Combobox
Use `nk_combobox` to create a combobox widget. It requires an array of options, the item count, a reference to store the selected index, the height of a single row, and the size of the dropdown box. A scrollbar appears if items exceed the dropdown height.
```c
static const char *my_options[] = {"Option 1", "Option 2"}; // The options we want to display
static int selected_item_index = 0; // Selected item index
struct nk_vec2 size = {100, 100}; // Size of the dropdown that displays all our items
nk_combobox(ctx, my_options, 2, &selected_item_index, 20, size);
```
--------------------------------
### Create Nested Groups in Nuklear
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Group
Demonstrates how to create a window with two nested groups, each containing labels. Use this for organizing complex UI layouts within a single window.
```c
if (nk_begin(ctx, "Demo", nk_rect(50, 50, 450, 250),
NK_WINDOW_BORDER|NK_WINDOW_TITLE|NK_WINDOW_NO_SCROLLBAR))
{
nk_layout_row_dynamic(ctx, 200, 2); // wrapping row
if (nk_group_begin(ctx, "column1", NK_WINDOW_BORDER)) { // column 1
nk_layout_row_dynamic(ctx, 30, 1); // nested row
nk_label(ctx, "column 1.1", NK_TEXT_CENTERED);
nk_layout_row_dynamic(ctx, 30, 1);
nk_label(ctx, "column 1.2", NK_TEXT_CENTERED);
nk_group_end(ctx);
}
if (nk_group_begin(ctx, "column2", NK_WINDOW_BORDER)) { // column 2
nk_layout_row_dynamic(ctx, 30, 1);
nk_label(ctx, "column 2.1", NK_TEXT_CENTERED);
nk_layout_row_dynamic(ctx, 30, 1);
nk_label(ctx, "column 2.2", NK_TEXT_CENTERED);
nk_group_end(ctx);
}
nk_end(ctx);
}
```
--------------------------------
### Create Selectable Text
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Selectable
Use `nk_selectable_text` to create a block of text that can be selected. The selection state is managed by a boolean variable passed by reference.
```C++
/* outside main cycle */
static int selected = nk_true;
static const char text[] = "text";
```
```C++
/* within main cycle */
if (nk_begin(ctx, "Test", nk_rect(32, 32, 192, 192), NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_CLOSABLE))
{
nk_layout_row_dynamic(ctx, 30, 1);
nk_selectable_text(ctx, text, strlen(text), NK_TEXT_LEFT, &selected);
}
k_end(ctx);
```
--------------------------------
### Initialize Chart Data
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Chart
Initialize an array to hold chart values, specify the count and offset, and populate the array with random data. Ensure the array size is sufficient for the number of values.
```C++
float values[1024];
int valueCount = 10;
int valueOffset = 2;
for( int i = 0; i < 200; i++ )
{
values[i] = rand()*100;
}
```
--------------------------------
### Modify Nuklear Include Path
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started-on-Mac
Adjust the include path in main.c to correctly reference the nuklear.h header file after integrating demo files.
```c
#include "nuklear.h"
```
--------------------------------
### Link Font File as Object (GNU Toolchain)
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Use this command to convert a font file into an object file that can be linked into your program. This method is useful for embedding resources directly into the binary.
```bash
ld -r -b binary -o font.o font.ttf
```
--------------------------------
### Static Row Layout
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Use nk_layout_row_static for rows with a fixed height and manually specified widget widths. Widgets do not grow or shrink.
```c
// nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols)
nk_layout_row_static(ctx, 24, 100, 3); // each widget is 100x24 pixels
nk_button_label(ctx, "Button1");
nk_button_label(ctx, "Button2");
nk_button_label(ctx, "Button3");
nk_button_label(ctx, "Button4");
nk_button_label(ctx, "Button5");
nk_button_label(ctx, "Button6");
```
--------------------------------
### Load and Convert SDL Surface to Nuklear Image
Source: https://github.com/immediate-mode-ui/nuklear/wiki/SDL
Loads a BMP image using SDL, creates an SDL texture from it, and then converts this texture into a Nuklear image. Includes error handling for loading and texture creation. Frees the SDL surface after conversion.
```c
/* Create an SDL_Texture from an SDL_Surface, then convert it to an nk_image */
hammer_surface = SDL_LoadBMP("hammer.bmp");
if (hammer_surface == NULL) {
printf("Error SDL_LoadBMP %s\n (ensure you are running the binary from the demo/sdl_renderer/ folder)
", SDL_GetError());
exit(-1);
}
hammer_texture = SDL_CreateTextureFromSurface(renderer, hammer_surface);
if (hammer_texture == NULL) {
printf("Error SDL_CreateTextureFromSurface %s\n", SDL_GetError());
exit(-1);
}
hammer_image = nk_image_ptr(hammer_texture);
SDL_FreeSurface(hammer_surface);
```
--------------------------------
### Set Raspberry Pi Video Driver
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/sdl_opengles2/Readme.md
Before running the application on Raspberry Pi, set the SDL_VIDEODRIVER environment variable to 'rpi' if not using a custom SDL2 build.
```bash
export SDL_VIDEODRIVER=rpi
```
--------------------------------
### Load Font with Custom Configuration
Source: https://github.com/immediate-mode-ui/nuklear/wiki/UTF-8-Support
Load a font file using a custom configuration and set it as the active font for the Nuklear context.
```cpp
nk_sdl_font_stash_begin(&atlas);
struct nk_font *font = nk_font_atlas_add_from_file(atlas, "path_to_your_font", 14, &config);
nk_sdl_font_stash_end();
nk_style_set_font(ctx, &font->handle);
```
--------------------------------
### Render Nuklear GUI with GDI
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Defines and renders the Nuklear GUI elements within a window. After drawing, it calls `nk_gdi_render` to display the GUI.
```C
/* GUI */
if (nk_begin(ctx, "Demo", nk_rect(50, 50, 200, 200),
NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE|
NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE))
{
enum {EASY, HARD};
static int op = EASY;
static int property = 20;
nk_layout_row_static(ctx, 30, 80, 1);
if (nk_button_label(ctx, "button"))
fprintf(stdout, "button pressed\n");
nk_layout_row_dynamic(ctx, 30, 2);
if (nk_option_label(ctx, "easy", op == EASY)) op = EASY;
if (nk_option_label(ctx, "hard", op == HARD)) op = HARD;
nk_layout_row_dynamic(ctx, 22, 1);
nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1);
}
nk_end(ctx);
/* Draw */
nk_gdi_render(nk_rgb(30,30,30));
```
--------------------------------
### Select a Label Directly
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Selectable
Use `nk_select_label` to create a label that returns its selection state. The function directly returns the updated state.
```C++
static int selected = nk_true; /* outside main cycle */
```
```C++
/* within main cycle */
if (nk_begin(ctx, "Test", nk_rect(32, 32, 192, 192), NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_CLOSABLE))
{
nk_layout_row_dynamic(ctx, 30, 1);
selected = nk_select_label(ctx, "label_2", NK_TEXT_LEFT, selected);
}
k_end(ctx);
```
--------------------------------
### Configure Font Glyph Ranges and Settings
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Assign glyph ranges and configure oversampling and pixel snapping for different font configurations. Pixel snapping can improve rendering clarity.
```C
/* assign Glyph ranges, disable oversampling, enable pixel snapping */
cfg_latin.range = ranges_latin;
cfg_icons.range = ranges_icons;
cfg_japan.range = ranges_japan;
cfg_latin.oversample_h = cfg_latin.oversample_v = 1;
cfg_icons.oversample_h = cfg_icons.oversample_v = 1;
cfg_japan.oversample_h = cfg_japan.oversample_v = 1;
cfg_latin.pixel_snap = true;
cfg_icons.pixel_snap = true;
cfg_japan.pixel_snap = true;
```
--------------------------------
### Render Nuklear GUI with DirectX 9
Source: https://github.com/immediate-mode-ui/nuklear/wiki/D3D-9
Define your GUI elements using Nuklear's API and then call nk_d3d9_render to draw them to the screen. Anti-aliasing can be enabled.
```c
nk_begin(ctx, "TestWindow", nk_rect(50, 50, 400, 250),NK_WINDOW_MOVABLE |NK_WINDOW_TITLE);
nk_end(ctx);
nk_d3d9_render(NK_ANTI_ALIASING_ON);
```
--------------------------------
### Render Nuklear UI to Overlay Image
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/glfw_vulkan/README.md
Renders the Nuklear UI to a specified overlay image index. This function should be called within your application's draw loop. It returns a semaphore to synchronize rendering with the swap chain.
```c
/*
in your draw loop draw you can then render to the overlay image at
`image_index`
your own application can then wait for the semaphore and produce
the swap_chain_image at `image_index`
this should simply sample from the overlay_image (see example)
*/
nk_semaphore semaphore =
nk_glfw3_render(demo.graphics_queue, image_index,
demo.image_available, NK_ANTI_ALIASING_ON);
if (!render(&demo, &bg, nk_semaphore, image_index)) {
fprintf(stderr, "render failed\n");
return false;
}
```
--------------------------------
### Modify Nuklear Include Path
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Getting-Started---Mac-OS-X
Adjust the include path for the main Nuklear header file in `main.c` to correctly reference the library after copying demo files.
```c
#include "../../nuklear.h"
```
```c
#include "nuklear.h"
```
--------------------------------
### Handle Input Events for Nuklear
Source: https://github.com/immediate-mode-ui/nuklear/wiki/D3D-9
Process window messages and feed them into Nuklear's input system. Ensure to call nk_input_begin and nk_input_end around message processing.
```c
MSG msg;
nk_input_begin(ctx);
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT)
running = 0;
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
nk_input_end(ctx);
```
--------------------------------
### Load Fonts from Memory with Custom Configurations
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Complete-font-guide
Load fonts from memory into font atlases using specific configurations. This process involves beginning and ending the font stash operation for each font.
```C
nk_glfw3_font_stash_begin(glfw, &atlas);
latin = nk_font_atlas_add_from_memory(
atlas, (void *)NotoSansCJKjp_Regular_otf.pnt,
NotoSansCJKjp_Regular_otf.size, 27.5, &cfg_latin);
nk_glfw3_font_stash_end(glfw);
nk_glfw3_font_stash_begin(glfw, &atlas_icon);
icons = nk_font_atlas_add_from_memory(
atlas_icon, (void *)icons_ttf.pnt,
icons_ttf.size, 63.5, &cfg_icons);
nk_glfw3_font_stash_end(glfw);
nk_glfw3_font_stash_begin(glfw, &atlas_jap);
japan = nk_font_atlas_add_from_memory(
atlas_jap, (void *)NotoSansCJKjp_Regular_otf.pnt,
NotoSansCJKjp_Regular_otf.size, 40.25, &cfg_japan);
nk_glfw3_font_stash_end(glfw);
```
--------------------------------
### Create Nuklear Image Pointer
Source: https://github.com/immediate-mode-ui/nuklear/blob/master/demo/glfw_vulkan/README.md
Creates an nk_image_ptr from a VkImageView for use in Nuklear UI elements. The image must have SHADER_READ_OPTIMAL layout. The integration uses a fixed linear filtering sampler.
```c
img = nk_image_ptr(demo.demo_texture_image_view);
```
--------------------------------
### Select Text Directly
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Selectable
Use `nk_select_text` to create a block of text that returns its selection state. The function directly returns the updated state.
```C++
/* outside main cycle */
static int selected = nk_true;
static const char text[] = "text_2";
```
```C++
/* within main cycle */
if (nk_begin(ctx, "Test", nk_rect(32, 32, 192, 192), NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_CLOSABLE))
{
nk_layout_row_dynamic(ctx, 30, 1);
selected = nk_select_text(ctx, text, strlen(text), NK_TEXT_LEFT, selected);
}
k_end(ctx);
```
--------------------------------
### Dynamic Row Layout
Source: https://github.com/immediate-mode-ui/nuklear/wiki/Row
Use nk_layout_row_dynamic for rows where widgets share equal horizontal space. Rows automatically adjust to fill available width.
```c
// nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols)
nk_layout_row_dynamic(ctx, 24, 3);
nk_button_label(ctx, "Button1");
nk_button_label(ctx, "Button2");
nk_button_label(ctx, "Button3");
nk_button_label(ctx, "Button4");
nk_button_label(ctx, "Button5");
nk_button_label(ctx, "Button6");
```
--------------------------------
### Declare SDL Image Variables for Nuklear
Source: https://github.com/immediate-mode-ui/nuklear/wiki/SDL
Declare necessary variables for handling SDL surfaces, textures, and Nuklear images. Ensure these are declared before use.
```c
SDL_Surface *hammer_surface;
SDL_Texture *hammer_texture;
struct nk_image hammer_image;
```
--------------------------------
### Process Window Messages and Input
Source: https://github.com/immediate-mode-ui/nuklear/wiki/GDI
Handles incoming Windows messages, translating and dispatching them. It also manages input for Nuklear, ensuring events are processed.
```C
/* Input */
MSG msg;
nk_input_begin(ctx);
if (needs_refresh == 0) {
if (GetMessageW(&msg, NULL, 0, 0) <= 0)
running = 0;
else {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
needs_refresh = 1;
} else needs_refresh = 0;
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT)
running = 0;
TranslateMessage(&msg);
DispatchMessageW(&msg);
needs_refresh = 1;
}
nk_input_end(ctx);
```