1# Introduction to the API {#intro_guide} 2 3[TOC] 4 5This guide introduces the basic concepts of GLFW and describes initialization, 6error handling and API guarantees and limitations. For a broad but shallow 7tutorial, see @ref quick_guide instead. For details on a specific function in 8this category, see the @ref init. 9 10There are also guides for the other areas of GLFW. 11 12 - @ref window_guide 13 - @ref context_guide 14 - @ref vulkan_guide 15 - @ref monitor_guide 16 - @ref input_guide 17 18 19## Initialization and termination {#intro_init} 20 21Before most GLFW functions may be called, the library must be initialized. 22This initialization checks what features are available on the machine, 23enumerates monitors, initializes the timer and performs any required 24platform-specific initialization. 25 26Only the following functions may be called before the library has been 27successfully initialized, and only from the main thread. 28 29 - @ref glfwGetVersion 30 - @ref glfwGetVersionString 31 - @ref glfwPlatformSupported 32 - @ref glfwGetError 33 - @ref glfwSetErrorCallback 34 - @ref glfwInitHint 35 - @ref glfwInitAllocator 36 - @ref glfwInitVulkanLoader 37 - @ref glfwInit 38 - @ref glfwTerminate 39 40Calling any other function before successful initialization will cause a @ref 41GLFW_NOT_INITIALIZED error. 42 43 44### Initializing GLFW {#intro_init_init} 45 46The library is initialized with @ref glfwInit, which returns `GLFW_FALSE` if an 47error occurred. 48 49```c 50if (!glfwInit()) 51{ 52 // Handle initialization failure 53} 54``` 55 56If any part of initialization fails, any parts that succeeded are terminated as 57if @ref glfwTerminate had been called. The library only needs to be initialized 58once and additional calls to an already initialized library will return 59`GLFW_TRUE` immediately. 60 61Once the library has been successfully initialized, it should be terminated 62before the application exits. Modern systems are very good at freeing resources 63allocated by programs that exit, but GLFW sometimes has to change global system 64settings and these might not be restored without termination. 65 66@macos When the library is initialized the main menu and dock icon are created. 67These are not desirable for a command-line only program. The creation of the 68main menu and dock icon can be disabled with the @ref GLFW_COCOA_MENUBAR init 69hint. 70 71 72### Initialization hints {#init_hints} 73 74Initialization hints are set before @ref glfwInit and affect how the library 75behaves until termination. Hints are set with @ref glfwInitHint. 76 77```c 78glfwInitHint(GLFW_JOYSTICK_HAT_BUTTONS, GLFW_FALSE); 79``` 80 81The values you set hints to are never reset by GLFW, but they only take effect 82during initialization. Once GLFW has been initialized, any values you set will 83be ignored until the library is terminated and initialized again. 84 85Some hints are platform specific. These may be set on any platform but they 86will only affect their specific platform. Other platforms will ignore them. 87Setting these hints requires no platform specific headers or functions. 88 89 90#### Shared init hints {#init_hints_shared} 91 92@anchor GLFW_PLATFORM 93__GLFW_PLATFORM__ specifies the platform to use for windowing and input. 94Possible values are `GLFW_ANY_PLATFORM`, `GLFW_PLATFORM_WIN32`, 95`GLFW_PLATFORM_COCOA`, `GLFW_PLATFORM_WAYLAND`, `GLFW_PLATFORM_X11` and 96`GLFW_PLATFORM_NULL`. The default value is `GLFW_ANY_PLATFORM`, which will 97choose any platform the library includes support for except for the Null 98backend. 99 100 101@anchor GLFW_JOYSTICK_HAT_BUTTONS 102__GLFW_JOYSTICK_HAT_BUTTONS__ specifies whether to also expose joystick hats as 103buttons, for compatibility with earlier versions of GLFW that did not have @ref 104glfwGetJoystickHats. Possible values are `GLFW_TRUE` and `GLFW_FALSE`. 105 106@anchor GLFW_ANGLE_PLATFORM_TYPE_hint 107__GLFW_ANGLE_PLATFORM_TYPE__ specifies the platform type (rendering backend) to 108request when using OpenGL ES and EGL via [ANGLE][]. If the requested platform 109type is unavailable, ANGLE will use its default. Possible values are one of 110`GLFW_ANGLE_PLATFORM_TYPE_NONE`, `GLFW_ANGLE_PLATFORM_TYPE_OPENGL`, 111`GLFW_ANGLE_PLATFORM_TYPE_OPENGLES`, `GLFW_ANGLE_PLATFORM_TYPE_D3D9`, 112`GLFW_ANGLE_PLATFORM_TYPE_D3D11`, `GLFW_ANGLE_PLATFORM_TYPE_VULKAN` and 113`GLFW_ANGLE_PLATFORM_TYPE_METAL`. 114 115[ANGLE]: https://chromium.googlesource.com/angle/angle/ 116 117The ANGLE platform type is specified via the `EGL_ANGLE_platform_angle` 118extension. This extension is not used if this hint is 119`GLFW_ANGLE_PLATFORM_TYPE_NONE`, which is the default value. 120 121 122#### macOS specific init hints {#init_hints_osx} 123 124@anchor GLFW_COCOA_CHDIR_RESOURCES_hint 125__GLFW_COCOA_CHDIR_RESOURCES__ specifies whether to set the current directory to 126the application to the `Contents/Resources` subdirectory of the application's 127bundle, if present. Possible values are `GLFW_TRUE` and `GLFW_FALSE`. This is 128ignored on other platforms. 129 130@anchor GLFW_COCOA_MENUBAR_hint 131__GLFW_COCOA_MENUBAR__ specifies whether to create the menu bar and dock icon 132when GLFW is initialized. This applies whether the menu bar is created from 133a nib or manually by GLFW. Possible values are `GLFW_TRUE` and `GLFW_FALSE`. 134This is ignored on other platforms. 135 136 137#### Wayland specific init hints {#init_hints_wayland} 138 139@anchor GLFW_WAYLAND_LIBDECOR_hint 140__GLFW_WAYLAND_LIBDECOR__ specifies whether to use [libdecor][] for window 141decorations where available. Possible values are `GLFW_WAYLAND_PREFER_LIBDECOR` 142and `GLFW_WAYLAND_DISABLE_LIBDECOR`. This is ignored on other platforms. 143 144[libdecor]: https://gitlab.freedesktop.org/libdecor/libdecor 145 146 147#### X11 specific init hints {#init_hints_x11} 148 149@anchor GLFW_X11_XCB_VULKAN_SURFACE_hint 150__GLFW_X11_XCB_VULKAN_SURFACE__ specifies whether to prefer the 151`VK_KHR_xcb_surface` extension for creating Vulkan surfaces, or whether to use 152the `VK_KHR_xlib_surface` extension. Possible values are `GLFW_TRUE` and 153`GLFW_FALSE`. This is ignored on other platforms. 154 155 156#### Supported and default values {#init_hints_values} 157 158Initialization hint | Default value | Supported values 159-------------------------------- | ------------------------------- | ---------------- 160@ref GLFW_PLATFORM | `GLFW_ANY_PLATFORM` | `GLFW_ANY_PLATFORM`, `GLFW_PLATFORM_WIN32`, `GLFW_PLATFORM_COCOA`, `GLFW_PLATFORM_WAYLAND`, `GLFW_PLATFORM_X11` or `GLFW_PLATFORM_NULL` 161@ref GLFW_JOYSTICK_HAT_BUTTONS | `GLFW_TRUE` | `GLFW_TRUE` or `GLFW_FALSE` 162@ref GLFW_ANGLE_PLATFORM_TYPE | `GLFW_ANGLE_PLATFORM_TYPE_NONE` | `GLFW_ANGLE_PLATFORM_TYPE_NONE`, `GLFW_ANGLE_PLATFORM_TYPE_OPENGL`, `GLFW_ANGLE_PLATFORM_TYPE_OPENGLES`, `GLFW_ANGLE_PLATFORM_TYPE_D3D9`, `GLFW_ANGLE_PLATFORM_TYPE_D3D11`, `GLFW_ANGLE_PLATFORM_TYPE_VULKAN` or `GLFW_ANGLE_PLATFORM_TYPE_METAL` 163@ref GLFW_COCOA_CHDIR_RESOURCES | `GLFW_TRUE` | `GLFW_TRUE` or `GLFW_FALSE` 164@ref GLFW_COCOA_MENUBAR | `GLFW_TRUE` | `GLFW_TRUE` or `GLFW_FALSE` 165@ref GLFW_WAYLAND_LIBDECOR | `GLFW_WAYLAND_PREFER_LIBDECOR` | `GLFW_WAYLAND_PREFER_LIBDECOR` or `GLFW_WAYLAND_DISABLE_LIBDECOR` 166@ref GLFW_X11_XCB_VULKAN_SURFACE | `GLFW_TRUE` | `GLFW_TRUE` or `GLFW_FALSE` 167 168 169### Runtime platform selection {#platform} 170 171GLFW can be compiled for more than one platform (window system) at once. This lets 172a single library binary support both Wayland and X11 on Linux and other Unix-like systems. 173 174You can control platform selection via the @ref GLFW_PLATFORM initialization hint. By 175default, this is set to @ref GLFW_ANY_PLATFORM, which will look for supported window 176systems in order of priority and select the first one it finds. It can also be set to any 177specific platform to have GLFW only look for that one. 178 179```c 180glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11); 181``` 182 183This mechanism also provides the Null platform, which is always supported but needs to be 184explicitly requested. This platform is effectively a stub, emulating a window system on 185a single 1080p monitor, but will not interact with any actual window system. 186 187```c 188glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_NULL); 189``` 190 191You can test whether a library binary was compiled with support for a specific platform 192with @ref glfwPlatformSupported. 193 194```c 195if (glfwPlatformSupported(GLFW_PLATFORM_WAYLAND)) 196 glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_WAYLAND); 197``` 198 199Once GLFW has been initialized, you can query which platform was selected with @ref 200glfwGetPlatform. 201 202```c 203int platform = glfwGetPlatform(); 204``` 205 206If you are using any [native access functions](@ref native), especially on Linux and other 207Unix-like systems, then you may need to check that you are calling the ones matching the 208selected platform. 209 210 211### Custom heap memory allocator {#init_allocator} 212 213The heap memory allocator can be customized before initialization with @ref 214glfwInitAllocator. 215 216```c 217GLFWallocator allocator; 218allocator.allocate = my_malloc; 219allocator.reallocate = my_realloc; 220allocator.deallocate = my_free; 221allocator.user = NULL; 222 223glfwInitAllocator(&allocator); 224``` 225 226The allocator will be made active at the beginning of initialization and will be used by 227GLFW until the library has been fully terminated. Any allocator set after initialization 228will be picked up only at the next initialization. 229 230The allocator will only be used for allocations that would have been made with 231the C standard library. Memory allocations that must be made with platform 232specific APIs will still use those. 233 234The allocation function must have a signature matching @ref GLFWallocatefun. It receives 235the desired size, in bytes, and the user pointer passed to @ref glfwInitAllocator and 236returns the address to the allocated memory block. 237 238```c 239void* my_malloc(size_t size, void* user) 240{ 241 ... 242} 243``` 244 245The documentation for @ref GLFWallocatefun also lists the requirements and limitations for 246an allocation function. If the active one does not meet all of these, GLFW may fail. 247 248The reallocation function must have a function signature matching @ref GLFWreallocatefun. 249It receives the memory block to be reallocated, the new desired size, in bytes, and the user 250pointer passed to @ref glfwInitAllocator and returns the address to the resized memory 251block. 252 253```c 254void* my_realloc(void* block, size_t size, void* user) 255{ 256 ... 257} 258``` 259 260The documentation for @ref GLFWreallocatefun also lists the requirements and limitations 261for a reallocation function. If the active one does not meet all of these, GLFW may fail. 262 263The deallocation function must have a function signature matching @ref GLFWdeallocatefun. 264It receives the memory block to be deallocated and the user pointer passed to @ref 265glfwInitAllocator. 266 267```c 268void my_free(void* block, void* user) 269{ 270 ... 271} 272``` 273 274The documentation for @ref GLFWdeallocatefun also lists the requirements and limitations 275for a deallocation function. If the active one does not meet all of these, GLFW may fail. 276 277 278### Terminating GLFW {#intro_init_terminate} 279 280Before your application exits, you should terminate the GLFW library if it has 281been initialized. This is done with @ref glfwTerminate. 282 283```c 284glfwTerminate(); 285``` 286 287This will destroy any remaining window, monitor and cursor objects, restore any 288modified gamma ramps, re-enable the screensaver if it had been disabled and free 289any other resources allocated by GLFW. 290 291Once the library is terminated, it is as if it had never been initialized, therefore 292you will need to initialize it again before being able to use GLFW. If the 293library was not initialized or had already been terminated, it returns 294immediately. 295 296 297## Error handling {#error_handling} 298 299Some GLFW functions have return values that indicate an error, but this is often 300not very helpful when trying to figure out what happened or why it occurred. 301Other functions have no return value reserved for errors, so error notification 302needs a separate channel. Finally, far from all GLFW functions have return 303values. 304 305The last [error code](@ref errors) for the calling thread can be queried at any 306time with @ref glfwGetError. 307 308```c 309int code = glfwGetError(NULL); 310 311if (code != GLFW_NO_ERROR) 312 handle_error(code); 313``` 314 315If no error has occurred since the last call, @ref GLFW_NO_ERROR (zero) is 316returned. The error is cleared before the function returns. 317 318The error code indicates the general category of the error. Some error codes, 319such as @ref GLFW_NOT_INITIALIZED has only a single meaning, whereas others like 320@ref GLFW_PLATFORM_ERROR are used for many different errors. 321 322GLFW often has more information about an error than its general category. You 323can retrieve a UTF-8 encoded human-readable description along with the error 324code. If no error has occurred since the last call, the description is set to 325`NULL`. 326 327```c 328const char* description; 329int code = glfwGetError(&description); 330 331if (description) 332 display_error_message(code, description); 333``` 334 335The retrieved description string is only valid until the next error occurs. 336This means you must make a copy of it if you want to keep it. 337 338You can also set an error callback, which will be called each time an error 339occurs. It is set with @ref glfwSetErrorCallback. 340 341```c 342glfwSetErrorCallback(error_callback); 343``` 344 345The error callback receives the same error code and human-readable description 346returned by @ref glfwGetError. 347 348```c 349void error_callback(int code, const char* description) 350{ 351 display_error_message(code, description); 352} 353``` 354 355The error callback is called after the error is stored, so calling @ref 356glfwGetError from within the error callback returns the same values as the 357callback argument. 358 359The description string passed to the callback is only valid until the error 360callback returns. This means you must make a copy of it if you want to keep it. 361 362__Reported errors are never fatal.__ As long as GLFW was successfully 363initialized, it will remain initialized and in a safe state until terminated 364regardless of how many errors occur. If an error occurs during initialization 365that causes @ref glfwInit to fail, any part of the library that was initialized 366will be safely terminated. 367 368Do not rely on a currently invalid call to generate a specific error, as in the 369future that same call may generate a different error or become valid. 370 371 372## Coordinate systems {#coordinate_systems} 373 374GLFW has two primary coordinate systems: the _virtual screen_ and the window 375_content area_ or _content area_. Both use the same unit: _virtual screen 376coordinates_, or just _screen coordinates_, which don't necessarily correspond 377to pixels. 378 379<img src="spaces.svg" width="90%" /> 380 381Both the virtual screen and the content area coordinate systems have the X-axis 382pointing to the right and the Y-axis pointing down. 383 384Window and monitor positions are specified as the position of the upper-left 385corners of their content areas relative to the virtual screen, while cursor 386positions are specified relative to a window's content area. 387 388Because the origin of the window's content area coordinate system is also the 389point from which the window position is specified, you can translate content 390area coordinates to the virtual screen by adding the window position. The 391window frame, when present, extends out from the content area but does not 392affect the window position. 393 394Almost all positions and sizes in GLFW are measured in screen coordinates 395relative to one of the two origins above. This includes cursor positions, 396window positions and sizes, window frame sizes, monitor positions and video mode 397resolutions. 398 399Two exceptions are the [monitor physical size](@ref monitor_size), which is 400measured in millimetres, and [framebuffer size](@ref window_fbsize), which is 401measured in pixels. 402 403Pixels and screen coordinates may map 1:1 on your machine, but they won't on 404every other machine, for example on a Mac with a Retina display. The ratio 405between screen coordinates and pixels may also change at run-time depending on 406which monitor the window is currently considered to be on. 407 408 409## Guarantees and limitations {#guarantees_limitations} 410 411This section describes the conditions under which GLFW can be expected to 412function, barring bugs in the operating system or drivers. Use of GLFW outside 413these limits may work on some platforms, or on some machines, or some of the 414time, or on some versions of GLFW, but it may break at any time and this will 415not be considered a bug. 416 417 418### Pointer lifetimes {#lifetime} 419 420GLFW will never free any pointer you provide to it, and you must never free any 421pointer it provides to you. 422 423Many GLFW functions return pointers to dynamically allocated structures, strings 424or arrays, and some callbacks are provided with strings or arrays. These are 425always managed by GLFW and should never be freed by the application. The 426lifetime of these pointers is documented for each GLFW function and callback. 427If you need to keep this data, you must copy it before its lifetime expires. 428 429Many GLFW functions accept pointers to structures or strings allocated by the 430application. These are never freed by GLFW and are always the responsibility of 431the application. If GLFW needs to keep the data in these structures or strings, 432it is copied before the function returns. 433 434Pointer lifetimes are guaranteed not to be shortened in future minor or patch 435releases. 436 437 438### Reentrancy {#reentrancy} 439 440GLFW event processing and object destruction are not reentrant. This means that 441the following functions must not be called from any callback function: 442 443 - @ref glfwDestroyWindow 444 - @ref glfwDestroyCursor 445 - @ref glfwPollEvents 446 - @ref glfwWaitEvents 447 - @ref glfwWaitEventsTimeout 448 - @ref glfwTerminate 449 450These functions may be made reentrant in future minor or patch releases, but 451functions not on this list will not be made non-reentrant. 452 453 454### Thread safety {#thread_safety} 455 456Most GLFW functions must only be called from the main thread (the thread that 457calls main), but some may be called from any thread once the library has been 458initialized. Before initialization the whole library is thread-unsafe. 459 460The reference documentation for every GLFW function states whether it is limited 461to the main thread. 462 463Initialization, termination, event processing and the creation and 464destruction of windows, cursors and OpenGL and OpenGL ES contexts are all 465restricted to the main thread due to limitations of one or several platforms. 466 467Because event processing must be performed on the main thread, all callbacks 468except for the error callback will only be called on that thread. The error 469callback may be called on any thread, as any GLFW function may generate errors. 470 471The error code and description may be queried from any thread. 472 473 - @ref glfwGetError 474 475Empty events may be posted from any thread. 476 477 - @ref glfwPostEmptyEvent 478 479The window user pointer and close flag may be read and written from any thread, 480but this is not synchronized by GLFW. 481 482 - @ref glfwGetWindowUserPointer 483 - @ref glfwSetWindowUserPointer 484 - @ref glfwWindowShouldClose 485 - @ref glfwSetWindowShouldClose 486 487These functions for working with OpenGL and OpenGL ES contexts may be called 488from any thread, but the window object is not synchronized by GLFW. 489 490 - @ref glfwMakeContextCurrent 491 - @ref glfwGetCurrentContext 492 - @ref glfwSwapBuffers 493 - @ref glfwSwapInterval 494 - @ref glfwExtensionSupported 495 - @ref glfwGetProcAddress 496 497The raw timer functions may be called from any thread. 498 499 - @ref glfwGetTimerFrequency 500 - @ref glfwGetTimerValue 501 502The regular timer may be used from any thread, but reading and writing the timer 503offset is not synchronized by GLFW. 504 505 - @ref glfwGetTime 506 - @ref glfwSetTime 507 508Library version information may be queried from any thread. 509 510 - @ref glfwGetVersion 511 - @ref glfwGetVersionString 512 513Platform information may be queried from any thread. 514 515 - @ref glfwPlatformSupported 516 - @ref glfwGetPlatform 517 518All Vulkan related functions may be called from any thread. 519 520 - @ref glfwVulkanSupported 521 - @ref glfwGetRequiredInstanceExtensions 522 - @ref glfwGetInstanceProcAddress 523 - @ref glfwGetPhysicalDevicePresentationSupport 524 - @ref glfwCreateWindowSurface 525 526GLFW uses synchronization objects internally only to manage the per-thread 527context and error states. Additional synchronization is left to the 528application. 529 530Functions that may currently be called from any thread will always remain so, 531but functions that are currently limited to the main thread may be updated to 532allow calls from any thread in future releases. 533 534 535### Version compatibility {#compatibility} 536 537GLFW uses [Semantic Versioning](https://semver.org/). This guarantees source 538and binary backward compatibility with earlier minor versions of the API. This 539means that you can drop in a newer version of the library and existing programs 540will continue to compile and existing binaries will continue to run. 541 542Once a function or constant has been added, the signature of that function or 543value of that constant will remain unchanged until the next major version of 544GLFW. No compatibility of any kind is guaranteed between major versions. 545 546Undocumented behavior, i.e. behavior that is not described in the documentation, 547may change at any time until it is documented. 548 549If the reference documentation and the implementation differ, the reference 550documentation will almost always take precedence and the implementation will be 551fixed in the next release. The reference documentation will also take 552precedence over anything stated in a guide. 553 554 555### Event order {#event_order} 556 557The order of arrival of related events is not guaranteed to be consistent 558across platforms. The exception is synthetic key and mouse button release 559events, which are always delivered after the window defocus event. 560 561 562## Version management {#intro_version} 563 564GLFW provides mechanisms for identifying what version of GLFW your application 565was compiled against as well as what version it is currently running against. 566If you are loading GLFW dynamically (not just linking dynamically), you can use 567this to verify that the library binary is compatible with your application. 568 569 570### Compile-time version {#intro_version_compile} 571 572The compile-time version of GLFW is provided by the GLFW header with the 573`GLFW_VERSION_MAJOR`, `GLFW_VERSION_MINOR` and `GLFW_VERSION_REVISION` macros. 574 575```c 576printf("Compiled against GLFW %i.%i.%i\n", 577 GLFW_VERSION_MAJOR, 578 GLFW_VERSION_MINOR, 579 GLFW_VERSION_REVISION); 580``` 581 582 583### Run-time version {#intro_version_runtime} 584 585The run-time version can be retrieved with @ref glfwGetVersion, a function that 586may be called regardless of whether GLFW is initialized. 587 588```c 589int major, minor, revision; 590glfwGetVersion(&major, &minor, &revision); 591 592printf("Running against GLFW %i.%i.%i\n", major, minor, revision); 593``` 594 595 596### Version string {#intro_version_string} 597 598GLFW 3 also provides a compile-time generated version string that describes the 599version, platform, compiler and any platform-specific compile-time options. 600This is primarily intended for submitting bug reports, to allow developers to 601see which code paths are enabled in a binary. 602 603The version string is returned by @ref glfwGetVersionString, a function that may 604be called regardless of whether GLFW is initialized. 605 606__Do not use the version string__ to parse the GLFW library version. The @ref 607glfwGetVersion function already provides the version of the running library 608binary. 609 610__Do not use the version string__ to parse what platforms are supported. The @ref 611glfwPlatformSupported function lets you query platform support. 612 613__GLFW 3.4:__ The format of this string was changed to support the addition of 614[runtime platform selection](@ref platform). 615 616The format of the string is as follows: 617 - The version of GLFW 618 - For each supported platform: 619 - The name of the window system API 620 - The name of the window system specific context creation API, if applicable 621 - The names of the always supported context creation APIs EGL and OSMesa 622 - Any additional compile-time options, APIs and (on Windows) what compiler was used 623 624For example, compiling GLFW 3.5 with MinGW as a DLL for Windows, may result in a version string 625like this: 626 627```c 6283.5.0 Win32 WGL Null EGL OSMesa MinGW DLL 629``` 630 631Compiling GLFW as a static library for Linux, with both Wayland and X11 enabled, may 632result in a version string like this: 633 634```c 6353.5.0 Wayland X11 GLX Null EGL OSMesa monotonic 636``` 637 638