diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index d935f11..f495a78 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -8,14 +8,42 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: apt-update run: sudo apt-get update -qq - - name: apt get glfw - run: sudo apt-get install -y --no-install-recommends libglfw3 libglfw3-dev libglew-dev - - name: build opengl2 + - name: apt get demo-libs + run: sudo apt-get install -y --no-install-recommends liballegro5-dev liballegro-image5-dev liballegro-ttf5-dev libglfw3 libglfw3-dev libglew-dev libsdl2-dev libwayland-dev libx11-dev libxft-dev wayland-protocols + - name: build allegro5 + run: make -C demo/allegro5 + - name: build glfw_opengl2 run: make -C demo/glfw_opengl2 - - name: build opengl3 + - name: build glfw_opengl3 run: make -C demo/glfw_opengl3 + - name: build glfw_opengl4 + run: make -C demo/glfw_opengl4 +# - name: build glfw_vulkan +# run: make -C demo/glfw_vulkan + - name: build sdl_opengl2 + run: make -C demo/sdl_opengl2 + - name: build sdl_opengl3 + run: make -C demo/sdl_opengl3 + - name: build sdl_opengles2 + run: make -C demo/sdl_opengles2 + - name: build sdl_renderer + run: make -C demo/sdl_renderer + - name: build sdl2surface_rawfb + run: make -C demo/sdl2surface_rawfb + - name: build wayland_rawfb + run: make -C demo/wayland_rawfb + - name: build x11 + run: make -C demo/x11 + - name: build x11_opengl2 + run: make -C demo/x11_opengl2 + - name: build x11_opengl3 + run: make -C demo/x11_opengl3 + - name: build x11_rawfb + run: make -C demo/x11_rawfb + - name: build x11_xft + run: make -C demo/x11_xft - name: build example run: make -C example diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index f5f30b0..b1b92e1 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -9,8 +9,9 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: butlerlogic/action-autotag@stable - with: + - uses: actions/checkout@v4 + - uses: butlerlogic/action-autotag@1.1.2 + env: GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" + with: root: clib.json diff --git a/clib.json b/clib.json index e83c57b..576b8d5 100644 --- a/clib.json +++ b/clib.json @@ -1,6 +1,6 @@ { "name": "nuklear", - "version": "4.10.7", + "version": "4.12.2", "repo": "Immediate-Mode-UI/Nuklear", "description": "A small ANSI C gui toolkit", "keywords": ["gl", "ui", "toolkit"], diff --git a/demo/allegro5/nuklear_allegro5.h b/demo/allegro5/nuklear_allegro5.h index 0e980c7..0e72f16 100644 --- a/demo/allegro5/nuklear_allegro5.h +++ b/demo/allegro5/nuklear_allegro5.h @@ -46,6 +46,7 @@ NK_API void nk_allegro5_font_set_font(NkAllegro5Font *font); * =============================================================== */ #ifdef NK_ALLEGRO5_IMPLEMENTATION +#include #ifndef NK_ALLEGRO5_TEXT_MAX #define NK_ALLEGRO5_TEXT_MAX 256 diff --git a/demo/common/filebrowser/stb_image.h b/demo/common/filebrowser/stb_image.h index 1f4d468..5e807a0 100644 --- a/demo/common/filebrowser/stb_image.h +++ b/demo/common/filebrowser/stb_image.h @@ -1,5 +1,5 @@ -/* stb_image - v2.08 - public domain image loader - http://nothings.org/stb_image.h - no warranty implied; use at your own risk +/* stb_image - v2.28 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION @@ -21,7 +21,7 @@ avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) - PNG 1/2/4/8-bit-per-channel (16 bpc not supported) + PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE @@ -42,184 +42,86 @@ Full documentation under "DOCUMENTATION" below. - Revision 2.00 release notes: +LICENSE - - Progressive JPEG is now supported. + See end of file for license information. - - PPM and PGM binary formats are now supported, thanks to Ken Miller. +RECENT REVISION HISTORY: - - x86 platforms now make use of SSE2 SIMD instructions for - JPEG decoding, and ARM platforms can use NEON SIMD if requested. - This work was done by Fabian "ryg" Giesen. SSE2 is used by - default, but NEON must be enabled explicitly; see docs. - - With other JPEG optimizations included in this version, we see - 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup - on a JPEG on an ARM machine, relative to previous versions of this - library. The same results will not obtain for all JPGs and for all - x86/ARM machines. (Note that progressive JPEGs are significantly - slower to decode than regular JPEGs.) This doesn't mean that this - is the fastest JPEG decoder in the land; rather, it brings it - closer to parity with standard libraries. If you want the fastest - decode, look elsewhere. (See "Philosophy" section of docs below.) - - See final bullet items below for more info on SIMD. - - - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing - the memory allocator. Unlike other STBI libraries, these macros don't - support a context parameter, so if you need to pass a context in to - the allocator, you'll have to store it in a global or a thread-local - variable. - - - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and - STBI_NO_LINEAR. - STBI_NO_HDR: suppress implementation of .hdr reader format - STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API - - - You can suppress implementation of any of the decoders to reduce - your code footprint by #defining one or more of the following - symbols before creating the implementation. - - STBI_NO_JPEG - STBI_NO_PNG - STBI_NO_BMP - STBI_NO_PSD - STBI_NO_TGA - STBI_NO_GIF - STBI_NO_HDR - STBI_NO_PIC - STBI_NO_PNM (.ppm and .pgm) - - - You can request *only* certain decoders and suppress all other ones - (this will be more forward-compatible, as addition of new decoders - doesn't require you to disable them explicitly): - - STBI_ONLY_JPEG - STBI_ONLY_PNG - STBI_ONLY_BMP - STBI_ONLY_PSD - STBI_ONLY_TGA - STBI_ONLY_GIF - STBI_ONLY_HDR - STBI_ONLY_PIC - STBI_ONLY_PNM (.ppm and .pgm) - - Note that you can define multiples of these, and you will get all - of them ("only x" and "only y" is interpreted to mean "only x&y"). - - - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still - want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB - - - Compilation of all SIMD code can be suppressed with - #define STBI_NO_SIMD - It should not be necessary to disable SIMD unless you have issues - compiling (e.g. using an x86 compiler which doesn't support SSE - intrinsics or that doesn't support the method used to detect - SSE2 support at run-time), and even those can be reported as - bugs so I can refine the built-in compile-time checking to be - smarter. - - - The old STBI_SIMD system which allowed installing a user-defined - IDCT etc. has been removed. If you need this, don't upgrade. My - assumption is that almost nobody was doing this, and those who - were will find the built-in SIMD more satisfactory anyway. - - - RGB values computed for JPEG images are slightly different from - previous versions of stb_image. (This is due to using less - integer precision in SIMD.) The C code has been adjusted so - that the same RGB values will be computed regardless of whether - SIMD support is available, so your app should always produce - consistent results. But these results are slightly different from - previous versions. (Specifically, about 3% of available YCbCr values - will compute different RGB results from pre-1.49 versions by +-1; - most of the deviating values are one smaller in the G channel.) - - - If you must produce consistent results with previous versions of - stb_image, #define STBI_JPEG_OLD and you will get the same results - you used to; however, you will not get the SIMD speedups for - the YCbCr-to-RGB conversion step (although you should still see - significant JPEG speedup from the other changes). - - Please note that STBI_JPEG_OLD is a temporary feature; it will be - removed in future versions of the library. It is only intended for - near-term back-compatibility use. - - - Latest revision history: - 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA - 2.07 (2015-09-13) partial animated GIF support - limited 16-bit PSD support - minor bugs, code cleanup, and compiler warnings - 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value - 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning - 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit - 2.03 (2015-04-12) additional corruption checking - stbi_set_flip_vertically_on_load - fix NEON support; fix mingw support - 2.02 (2015-01-19) fix incorrect assert, fix warning - 2.01 (2015-01-17) fix various warnings - 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG - 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD - progressive JPEG - PGM/PPM support - STBI_MALLOC,STBI_REALLOC,STBI_FREE - STBI_NO_*, STBI_ONLY_* - GIF bugfix - 1.48 (2014-12-14) fix incorrectly-named assert() - 1.47 (2014-12-14) 1/2/4-bit PNG support (both grayscale and paletted) - optimize PNG - fix bug in interlaced PNG with user-specified channel count + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED See end of file for full revision history. ============================ Contributors ========================= - Image formats Bug fixes & warning fixes - Sean Barrett (jpeg, png, bmp) Marc LeBlanc - Nicolas Schulz (hdr, psd) Christpher Lloyd - Jonathan Dummer (tga) Dave Moore - Jean-Marc Lienher (gif) Won Chun - Tom Seddon (pic) the Horde3D community - Thatcher Ulrich (psd) Janez Zemva - Ken Miller (pgm, ppm) Jonathan Blow - urraka@github (animated gif) Laurent Gomila - Aruelien Pocheville - Ryamond Barbiero - David Woo - Extensions, features Martin Golini - Jetro Lauha (stbi_info) Roy Eltham - Martin "SpartanJ" Golini (stbi_info) Luke Graham - James "moose2000" Brown (iPhone PNG) Thomas Ruf - Ben "Disch" Wenger (io callbacks) John Bartholomew - Omar Cornut (1/2/4-bit PNG) Ken Hamada - Nicolas Guillemot (vertical flip) Cort Stratton - Richard Mitton (16-bit PSD) Blazej Dariusz Roszkowski - Thibault Reuille - Paul Du Bois - Guillaume George - Jerry Jansson - Hayaki Saito - Johan Duparc - Ronny Chevalier - Optimizations & bugfixes Michal Cichon - Fabian "ryg" Giesen Tero Hanninen - Arseny Kapoulkine Sergio Gonzalez - Cass Everitt - Engin Manap - If your name should be here but Martins Mozeiko - isn't, let Sean know. Joseph Thomson - Phil Jordan - Nathan Reed - Michaelangel007@github - Nick Verigakis + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera -LICENSE + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE -This software is in the public domain. Where that dedication is not -recognized, you are granted a perpetual, irrevocable license to copy, -distribute, and modify this file as you see fit. + Jacko Dirks + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H @@ -228,10 +130,8 @@ distribute, and modify this file as you see fit. // DOCUMENTATION // // Limitations: -// - no 16-bit-per-channel PNG // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding -// - no 1-bit BMP // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): @@ -241,13 +141,13 @@ distribute, and modify this file as you see fit. // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 -// stbi_image_free(data) +// stbi_image_free(data); // // Standard parameters: -// int *x -- outputs image width in pixels -// int *y -- outputs image height in pixels -// int *comp -- outputs # of image components in image file -// int req_comp -- if non-zero, # of image components requested in result +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is @@ -255,11 +155,12 @@ distribute, and modify this file as you see fit. // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of -// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise. -// If req_comp is non-zero, *comp has the number of components that _would_ -// have been output otherwise. E.g. if you set req_comp to 4, you will always -// get RGBA output, but you can check *comp to see if it's trivially opaque -// because e.g. there were only 3 channels in the source image. +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: @@ -271,14 +172,50 @@ distribute, and modify this file as you see fit. // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, -// and *x, *y, *comp will be unchanged. The function stbi_failure_reason() -// can be queried for an extremely brief, end-user unfriendly explanation -// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid -// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// // =========================================================================== // // Philosophy @@ -291,15 +228,15 @@ distribute, and modify this file as you see fit. // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher -// performance, in addition to the easy to use ones. Nevertheless, it's important +// performance, in addition to the easy-to-use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, -// all you care about is #1 and #3, and stb libraries do not emphasize #3 above all. +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which -// make more explicit reasons why performance can't be emphasized. +// provide more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") -// - Small footprint ("easy to maintain") +// - Small source code footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== @@ -331,13 +268,6 @@ distribute, and modify this file as you see fit. // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // -// The output of the JPEG decoder is slightly different from versions where -// SIMD support was introduced (that is, for versions before 1.49). The -// difference is only +-1 in the 8-bit RGB channels, and only on a small -// fraction of pixels. You can force the pre-1.49 behavior by defining -// STBI_JPEG_OLD, but this will disable some of the SIMD decoding path -// and hence cost some performance. -// // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. @@ -346,11 +276,10 @@ distribute, and modify this file as you see fit. // // HDR image support (disable by defining STBI_NO_HDR) // -// stb_image now supports loading HDR images in general, and currently -// the Radiance .HDR file format, although the support is provided -// generically. You can still load any file through the existing interface; -// if you attempt to load an HDR file, it will be automatically remapped to -// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); @@ -382,18 +311,59 @@ distribute, and modify this file as you see fit. // // iPhone PNG support: // -// By default we convert iphone-formatted PNGs back to RGB, even though -// they are internally encoded differently. You can disable this conversion -// by by calling stbi_convert_iphone_png_to_rgb(0), in which case -// you will always just get the native iphone "format" through (which -// is BGR stored in RGB). +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // - +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. #ifndef STBI_NO_STDIO #include @@ -403,7 +373,7 @@ distribute, and modify this file as you see fit. enum { - STBI_default = 0, // only used for req_comp + STBI_default = 0, // only used for desired_channels STBI_grey = 1, STBI_grey_alpha = 2, @@ -411,17 +381,21 @@ enum STBI_rgb_alpha = 4 }; +#include typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif +#ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif +#endif ////////////////////////////////////////////////////////////////////////////// // @@ -439,34 +413,64 @@ typedef struct int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; -STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp); -STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp); -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp); +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO -STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// #ifndef STBI_NO_LINEAR - STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp); - STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp); - STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO - STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp); + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); -#endif +#endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); -#endif // STBI_NO_HDR +#endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); @@ -478,7 +482,7 @@ STBIDEF int stbi_is_hdr_from_file(FILE *f); // get a VERY brief reason for failure -// NOT THREADSAFE +// on most compilers (and ALL modern mainstream compilers) this is threadsafe STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() @@ -487,11 +491,14 @@ STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); #ifndef STBI_NO_STDIO -STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); - +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); #endif @@ -508,6 +515,13 @@ STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); @@ -572,9 +586,10 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #include // ptrdiff_t on osx #include #include +#include #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -#include // ldexp +#include // ldexp, pow #endif #ifndef STBI_NO_STDIO @@ -586,6 +601,12 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #define STBI_ASSERT(x) assert(x) #endif +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + #ifndef _MSC_VER #ifdef __cplusplus @@ -597,8 +618,25 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const ch #define stbi_inline __forceinline #endif +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif -#ifdef _MSC_VER + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; @@ -627,21 +665,25 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else - #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) #endif -#if defined(STBI_MALLOC) && defined(STBI_FREE) && defined(STBI_REALLOC) +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok -#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else -#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC." +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC -#define STBI_MALLOC(sz) malloc(sz) -#define STBI_REALLOC(p,sz) realloc(p,sz) -#define STBI_FREE(p) free(p) +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection @@ -651,12 +693,14 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI__X86_TARGET #endif -#if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) -// NOTE: not clear do we actually need this for the 64-bit path? +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, -// (but compiling with -msse2 allows the compiler to use SSE2 everywhere; -// this is just broken and gcc are jerks for not fixing it properly -// http://www.virtualdub.org/blog/pivot/entry.php?id=363 ) +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. #define STBI_NO_SIMD #endif @@ -675,7 +719,7 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #define STBI_NO_SIMD #endif -#if !defined(STBI_NO_SIMD) && defined(STBI__X86_TARGET) +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include @@ -704,25 +748,27 @@ static int stbi__cpuid3(void) #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name -static int stbi__sse2_available() +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } +#endif + #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) -static int stbi__sse2_available() +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) { -#if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later - // GCC 4.8+ has a nice way to do this - return __builtin_cpu_supports("sse2"); -#else - // portable way to do this, preferably without using GCC inline ASM? - // just bail for now. - return 0; -#endif + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; } +#endif + #endif #endif @@ -733,14 +779,21 @@ static int stbi__sse2_available() #ifdef STBI_NEON #include -// assume GCC or Clang on ARM targets +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif +#endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions @@ -758,6 +811,7 @@ typedef struct int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; + int callback_already_read; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; @@ -771,6 +825,7 @@ static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; + s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } @@ -782,7 +837,8 @@ static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void * s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; - s->img_buffer_original = s->buffer_start; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } @@ -796,12 +852,17 @@ static int stbi__stdio_read(void *user, char *data, int size) static void stbi__stdio_skip(void *user, int n) { + int ch; fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } } static int stbi__stdio_eof(void *user) { - return feof((FILE*) user); + return feof((FILE*) user) || ferror((FILE *) user); } static stbi_io_callbacks stbi__stdio_callbacks = @@ -829,79 +890,197 @@ static void stbi__rewind(stbi__context *s) s->img_buffer_end = s->img_buffer_original_end; } +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); -static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); -static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); -static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); -static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); -static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); -static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); -static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); -static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); #endif -// this is not threadsafe -static const char *stbi__g_failure_reason; +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } +#ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } +#endif static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two signed shorts is valid, 0 on overflow. +static int stbi__mul2shorts_valid(short a, short b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char @@ -930,40 +1109,69 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif -static int stbi__vertically_flip_on_load = 0; +static int stbi__vertically_flip_on_load_global = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { - stbi__vertically_flip_on_load = flag_true_if_should_flip; + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } -static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { - #ifndef STBI_NO_JPEG - if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp); - #endif + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) #ifndef STBI_NO_PNG - if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp); + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_BMP - if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp); + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_GIF - if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp); + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp); + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); #endif #ifndef STBI_NO_PIC - if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp); + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNM - if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp); + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { - float *hdr = stbi__hdr_load(s, x,y,comp,req_comp); + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif @@ -971,66 +1179,179 @@ static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *com #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) - return stbi__tga_load(s,x,y,comp,req_comp); + return stbi__tga_load(s,x,y,comp,req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } -static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { - unsigned char *result = stbi__load_main(s, x, y, comp, req_comp); + int i; + int img_len = w * h * channels; + stbi_uc *reduced; - if (stbi__vertically_flip_on_load && result != NULL) { - int w = *x, h = *y; - int depth = req_comp ? req_comp : *comp; - int row,col,z; - stbi_uc temp; + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); - // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once - for (row = 0; row < (h>>1); row++) { - for (col = 0; col < w; col++) { - for (z = 0; z < depth; z++) { - temp = result[(row * w + col) * depth + z]; - result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; - result[((h - row - 1) * w + col) * depth + z] = temp; - } - } - } - } + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling - return result; + STBI_FREE(orig); + return reduced; } -#ifndef STBI_NO_HDR +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { - int w = *x, h = *y; - int depth = req_comp ? req_comp : *comp; - int row,col,z; - float temp; - - // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once - for (row = 0; row < (h>>1); row++) { - for (col = 0; col < w; col++) { - for (z = 0; z < depth; z++) { - temp = result[(row * w + col) * depth + z]; - result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z]; - result[((h - row - 1) * w + col) * depth + z] = temp; - } - } - } + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } #endif #ifndef STBI_NO_STDIO +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + #if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else @@ -1055,42 +1376,98 @@ STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req unsigned char *result; stbi__context s; stbi__start_file(&s,f); - result = stbi__load_flip(&s,x,y,comp,req_comp); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + #endif //!STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); - return stbi__load_flip(&s,x,y,comp,req_comp); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_flip(&s,x,y,comp,req_comp); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { - float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp); + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif - data = stbi__load_flip(s, x, y, comp, req_comp); + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); @@ -1160,12 +1537,16 @@ STBIDEF int stbi_is_hdr (char const *filename) return result; } -STBIDEF int stbi_is_hdr_from_file(FILE *f) +STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; stbi__context s; stbi__start_file(&s,f); - return stbi__hdr_test(&s); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; #else STBI_NOTUSED(f); return 0; @@ -1186,14 +1567,15 @@ STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void #endif } -static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; +#ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; -#ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } @@ -1213,6 +1595,7 @@ enum static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file @@ -1237,6 +1620,9 @@ stbi_inline static stbi_uc stbi__get8(stbi__context *s) return 0; } +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { @@ -1248,9 +1634,14 @@ stbi_inline static int stbi__at_eof(stbi__context *s) return s->img_buffer >= s->img_buffer_end; } +#endif +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else static void stbi__skip(stbi__context *s, int n) { + if (n == 0) return; // already there! if (n < 0) { s->img_buffer = s->img_buffer_end; return; @@ -1265,7 +1656,11 @@ static void stbi__skip(stbi__context *s, int n) } s->img_buffer += n; } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { @@ -1289,18 +1684,27 @@ static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) } else return 0; } +#endif +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } +#endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing @@ -1316,13 +1720,16 @@ static int stbi__get16le(stbi__context *s) static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); - return z + (stbi__get16le(s) << 16); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings - +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp @@ -1338,7 +1745,11 @@ static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } +#endif +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; @@ -1347,7 +1758,7 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - good = (unsigned char *) stbi__malloc(req_comp * x * y); + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); @@ -1357,37 +1768,97 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; - #define COMBO(a,b) ((a)*8+(b)) - #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros - switch (COMBO(img_n, req_comp)) { - CASE(1,2) dest[0]=src[0], dest[1]=255; break; - CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break; - CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break; - CASE(2,1) dest[0]=src[0]; break; - CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break; - CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break; - CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break; - CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; - CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break; - CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break; - CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break; - CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break; - default: STBI_ASSERT(0); + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); } - #undef CASE + #undef STBI__CASE } STBI_FREE(data); return good; } +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; - float *output = (float *) stbi__malloc(x * y * comp * sizeof(float)); + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; @@ -1395,7 +1866,11 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } - if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f; + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } } STBI_FREE(data); return output; @@ -1407,7 +1882,9 @@ static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; - stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp); + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; @@ -1472,7 +1949,7 @@ typedef struct stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; - stbi_uc dequant[4][64]; + stbi__uint16 dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs @@ -1508,6 +1985,9 @@ typedef struct int succ_high; int succ_low; int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; int scan_n, order[4]; int restart_interval, todo; @@ -1520,11 +2000,15 @@ typedef struct static int stbi__build_huffman(stbi__huffman *h, int *count) { - int i,j,k=0,code; + int i,j,k=0; + unsigned int code; // build size list for each symbol (from JPEG spec) - for (i=0; i < 16; ++i) - for (j=0; j < count[i]; ++j) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } h->size[k] = 0; // compute actual symbols (from jpeg spec) @@ -1536,7 +2020,7 @@ static int stbi__build_huffman(stbi__huffman *h, int *count) if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); - if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); @@ -1577,10 +2061,10 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); - if (k < m) k += (-1 << magbits) + 1; + if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits)); + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } @@ -1589,9 +2073,10 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { - int b = j->nomore ? 0 : stbi__get8(j->s); + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; @@ -1604,7 +2089,7 @@ static void stbi__grow_buffer_unsafe(stbi__jpeg *j) } // (1 << n) - 1 -static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) @@ -1648,6 +2133,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol @@ -1657,7 +2144,7 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) } // bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing - sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) k = stbi_lrot(j->code_buffer, n); - STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; - return k + (stbi__jbias[n] & ~sgn); + return k + (stbi__jbias[n] & (sgn - 1)); } // get some unsigned bits @@ -1681,6 +2168,7 @@ stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; @@ -1692,6 +2180,7 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; @@ -1700,7 +2189,7 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? -static stbi_uc stbi__jpeg_dezigzag[64+15] = +static const stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, @@ -1716,21 +2205,23 @@ static stbi_uc stbi__jpeg_dezigzag[64+15] = }; // decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant) +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec @@ -1744,6 +2235,7 @@ static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location @@ -1780,11 +2272,14 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__ // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; - data[0] = (short) (dc << j->succ_low); + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) @@ -1818,10 +2313,11 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) << shift); + data[zig] = (short) ((r >> 8) * (1 << shift)); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); @@ -1839,7 +2335,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ } else { k += r; zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) << shift); + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); } } } while (k <= j->spec_end); @@ -1926,7 +2422,7 @@ stbi_inline static stbi_uc stbi__clamp(int x) } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) -#define stbi__fsh(x) ((x) << 12) +#define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ @@ -1981,7 +2477,7 @@ static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds - int dcterm = d[0] << 2; + int dcterm = d[0]*4; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) @@ -2425,7 +2921,7 @@ static stbi_uc stbi__get_marker(stbi__jpeg *j) x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) - x = stbi__get8(j->s); + x = stbi__get8(j->s); // consume repeated 0xff fill bytes return x; } @@ -2440,7 +2936,7 @@ static void stbi__jpeg_reset(stbi__jpeg *j) j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; - j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; @@ -2572,7 +3068,7 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) } } -static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant) +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) { int i; for (i=0; i < 64; ++i) @@ -2614,13 +3110,14 @@ static int stbi__process_marker(stbi__jpeg *z, int m) L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); - int p = q >> 4; + int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; - if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG"); + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + for (i=0; i < 64; ++i) - z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s); - L -= 65; + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); } return L==0; @@ -2637,6 +3134,7 @@ static int stbi__process_marker(stbi__jpeg *z, int m) sizes[i] = stbi__get8(z->s); n += sizes[i]; } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; @@ -2653,12 +3151,50 @@ static int stbi__process_marker(stbi__jpeg *z, int m) } return L==0; } + // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { - stbi__skip(z->s, stbi__get16be(z->s)-2); + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); return 1; } - return 0; + + return stbi__err("unknown marker","Corrupt JPEG"); } // after we see SOS @@ -2701,6 +3237,28 @@ static int stbi__process_scan_header(stbi__jpeg *z) return 1; } +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; @@ -2709,8 +3267,10 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); c = stbi__get8(s); - if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; @@ -2719,11 +3279,12 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + z->rgb = 0; for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); - if (z->img_comp[i].id != i+1) // JFIF requires - if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files! - return stbi__err("bad component ID","Corrupt JPEG"); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); @@ -2732,18 +3293,26 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) if (scan != STBI__SCAN_load) return 1; - if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; @@ -2755,28 +3324,27 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; - z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15); - - if (z->img_comp[i].raw_data == NULL) { - for(--i; i >= 0; --i) { - STBI_FREE(z->img_comp[i].raw_data); - z->img_comp[i].raw_data = NULL; - } - return stbi__err("outofmem", "Out of memory"); - } + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); - z->img_comp[i].linebuf = NULL; if (z->progressive) { - z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3; - z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3; - z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15); + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); - } else { - z->img_comp[i].coeff = 0; - z->img_comp[i].raw_coeff = 0; } } @@ -2795,6 +3363,8 @@ static int stbi__process_frame_header(stbi__jpeg *z, int scan) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); @@ -2814,6 +3384,28 @@ static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) return 1; } +static int stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + while (x == 255) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { @@ -2830,22 +3422,22 @@ static int stbi__decode_jpeg_image(stbi__jpeg *j) if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { - // handle 0s at the end of image data from IP Kamera 9060 - while (!stbi__at_eof(j->s)) { - int x = stbi__get8(j->s); - if (x == 255) { - j->marker = stbi__get8(j->s); - break; - } else if (x != 0) { - return stbi__err("junk before marker", "Corrupt JPEG"); - } - } + j->marker = stbi__skip_jpeg_junk_at_end(j); // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); } else { - if (!stbi__process_marker(j, m)) return 0; + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); } - m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); @@ -3060,38 +3652,9 @@ static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_ return out; } -#ifdef STBI_JPEG_OLD -// this is the same YCbCr-to-RGB calculation that stb_image has used -// historically before the algorithm changes in 1.49 -#define float2fixed(x) ((int) ((x) * 65536 + 0.5)) -static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) -{ - int i; - for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 16) + 32768; // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr*float2fixed(1.40200f); - g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f); - b = y_fixed + cb*float2fixed(1.77200f); - r >>= 16; - g >>= 16; - b >>= 16; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} -#else // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar -#define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; @@ -3100,9 +3663,9 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; - r = y_fixed + cr* float2fixed(1.40200f); - g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* float2fixed(1.77200f); + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; @@ -3116,7 +3679,6 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc out += step; } } -#endif #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) @@ -3235,9 +3797,9 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc cons int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; - r = y_fixed + cr* float2fixed(1.40200f); - g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* float2fixed(1.77200f); + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; @@ -3263,18 +3825,14 @@ static void stbi__setup_jpeg(stbi__jpeg *j) #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; - #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; - #ifndef STBI_JPEG_OLD j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - #endif j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } @@ -3282,23 +3840,7 @@ static void stbi__setup_jpeg(stbi__jpeg *j) // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { - int i; - for (i=0; i < j->s->img_n; ++i) { - if (j->img_comp[i].raw_data) { - STBI_FREE(j->img_comp[i].raw_data); - j->img_comp[i].raw_data = NULL; - j->img_comp[i].data = NULL; - } - if (j->img_comp[i].raw_coeff) { - STBI_FREE(j->img_comp[i].raw_coeff); - j->img_comp[i].raw_coeff = 0; - j->img_comp[i].coeff = 0; - } - if (j->img_comp[i].linebuf) { - STBI_FREE(j->img_comp[i].linebuf); - j->img_comp[i].linebuf = NULL; - } - } + stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct @@ -3311,9 +3853,16 @@ typedef struct int ypos; // which pre-expansion row we're on } stbi__resample; +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { - int n, decode_n; + int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp @@ -3323,19 +3872,25 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate - n = req_comp ? req_comp : z->s->img_n; + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - if (z->s->img_n == 3 && n < 3) + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; - stbi_uc *coutput[4]; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; @@ -3362,7 +3917,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } // can't error after this so, this is safe - output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1); + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample @@ -3385,7 +3940,39 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; @@ -3393,37 +3980,74 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp out += n; } } else { - stbi_uc *y = coutput[0]; - if (n == 1) - for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; - else - for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; - if (comp) *comp = z->s->img_n; // report original components, not output + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } -static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { - stbi__jpeg j; - j.s = s; - stbi__setup_jpeg(&j); - return load_jpeg_image(&j, x,y,comp,req_comp); + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; } static int stbi__jpeg_test(stbi__context *s) { int r; - stbi__jpeg j; - j.s = s; - stbi__setup_jpeg(&j); - r = stbi__decode_jpeg_header(&j, STBI__SCAN_type); + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); stbi__rewind(s); + STBI_FREE(j); return r; } @@ -3435,15 +4059,20 @@ static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; - if (comp) *comp = j->s->img_n; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { - stbi__jpeg j; - j.s = s; - return stbi__jpeg_info_raw(&j, x, y, comp); + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; } #endif @@ -3459,6 +4088,7 @@ static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) @@ -3468,8 +4098,8 @@ typedef struct stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; - stbi_uc size[288]; - stbi__uint16 value[288]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) @@ -3489,7 +4119,7 @@ stbi_inline static int stbi__bit_reverse(int v, int bits) return stbi__bitreverse16(v) >> (16-bits); } -static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num) +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; @@ -3556,16 +4186,23 @@ typedef struct stbi__zhuffman z_length, z_distance; } stbi__zbuf; +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { - if (z->zbuffer >= z->zbuffer_end) return 0; - return *z->zbuffer++; + return stbi__zeof(z) ? 0 : *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { - STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); @@ -3590,10 +4227,11 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; - if (s == 16) return -1; // invalid code! + if (s >= 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; - STBI_ASSERT(z->size[b] == s); + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; @@ -3602,7 +4240,12 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; - if (a->num_bits < 16) stbi__fill_bits(a); + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + return -1; /* report error for unexpected end of data. */ + } + stbi__fill_bits(a); + } b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; @@ -3616,14 +4259,18 @@ stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; - int cur, limit; + unsigned int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); - cur = (int) (z->zout - z->zout_start); - limit = (int) (z->zout_end - z->zout_start); - while (cur + n > limit) + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; - q = (char *) STBI_REALLOC(z->zout_start, limit); + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; @@ -3631,18 +4278,18 @@ static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room return 1; } -static int stbi__zlength_base[31] = { +static const int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; -static int stbi__zlength_extra[31]= +static const int stbi__zlength_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; -static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; -static int stbi__zdist_extra[32] = +static const int stbi__zdist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; static int stbi__parse_huffman_block(stbi__zbuf *a) @@ -3664,11 +4311,12 @@ static int stbi__parse_huffman_block(stbi__zbuf *a) a->zout = zout; return 1; } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); @@ -3689,7 +4337,7 @@ static int stbi__parse_huffman_block(stbi__zbuf *a) static int stbi__compute_huffman_codes(stbi__zbuf *a) { - static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; @@ -3698,6 +4346,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a) int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { @@ -3707,33 +4356,36 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a) if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; - while (n < hlit + hdist) { + while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; - else if (c == 16) { - c = stbi__zreceive(a,2)+3; - memset(lencodes+n, lencodes[n-1], c); - n += c; - } else if (c == 17) { - c = stbi__zreceive(a,3)+3; - memset(lencodes+n, 0, c); - n += c; - } else { - STBI_ASSERT(c == 18); - c = stbi__zreceive(a,7)+11; - memset(lencodes+n, 0, c); + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); n += c; } } - if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG"); + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } -static int stbi__parse_uncomperssed_block(stbi__zbuf *a) +static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; @@ -3746,7 +4398,7 @@ static int stbi__parse_uncomperssed_block(stbi__zbuf *a) a->code_buffer >>= 8; a->num_bits -= 8; } - STBI_ASSERT(a->num_bits == 0); + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); @@ -3768,6 +4420,7 @@ static int stbi__parse_zlib_header(stbi__zbuf *a) int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png @@ -3775,9 +4428,24 @@ static int stbi__parse_zlib_header(stbi__zbuf *a) return 1; } -// @TODO: should statically initialize these for optimal thread safety -static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32]; -static void stbi__init_zdefaults(void) +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; @@ -3787,6 +4455,7 @@ static void stbi__init_zdefaults(void) for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } +*/ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { @@ -3799,14 +4468,13 @@ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { - if (!stbi__parse_uncomperssed_block(a)) return 0; + if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths - if (!stbi__zdefault_distance[31]) stbi__init_zdefaults(); - if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; @@ -3930,7 +4598,7 @@ static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) static int stbi__check_png_header(stbi__context *s) { - static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); @@ -3941,6 +4609,7 @@ typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; + int depth; } stbi__png; @@ -3975,44 +4644,50 @@ static int stbi__paeth(int a, int b, int c) return c; } -static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { + int bytes = (depth == 16? 2 : 1); stbi__context *s = a->s; - stbi__uint32 i,j,stride = x*out_n; + stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); - a->out = (stbi_uc *) stbi__malloc(x * y * out_n); // extra bytes to write off the end into + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; - if (s->img_x == x && s->img_y == y) { - if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG"); - } else { // interlaced: - if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); - } + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; - stbi_uc *prior = cur - stride; + stbi_uc *prior; int filter = *raw++; - int filter_bytes = img_n; - int width = x; + if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { - STBI_ASSERT(img_width_bytes <= x); + if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; @@ -4036,6 +4711,14 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r raw += img_n; cur += out_n; prior += out_n; + } else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes+1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; } else { raw += 1; cur += 1; @@ -4044,50 +4727,59 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { - int nk = (width - 1)*img_n; - #define CASE(f) \ + int nk = (width - 1)*filter_bytes; + #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; - CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break; - CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break; - CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break; - CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break; - CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; } - #undef CASE + #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); - #define CASE(f) \ + #define STBI__CASE(f) \ case f: \ - for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \ - for (k=0; k < img_n; ++k) + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) switch (filter) { - CASE(STBI__F_none) cur[k] = raw[k]; break; - CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-out_n]); break; - CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-out_n])>>1)); break; - CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break; - CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-out_n] >> 1)); break; - CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],0,0)); break; + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; + } + #undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i=0; i < x; ++i,cur+=output_bytes) { + cur[filter_bytes+1] = 255; + } } - #undef CASE } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't - // interfere with filtering but will still be in the cache. + // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit - // png guarantee byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. @@ -4151,6 +4843,17 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r } } } + } else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { + *cur16 = (cur[0] << 8) | cur[1]; + } } return 1; @@ -4158,13 +4861,16 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing - final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n); + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; @@ -4184,8 +4890,8 @@ static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint3 for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; - memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n, - a->out + (j*x+i)*out_n, out_n); + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); } } STBI_FREE(a->out); @@ -4223,15 +4929,40 @@ static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) return 1; } +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; - p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n); + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); - // between here and free(out) below, exiting would leak + // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { @@ -4260,19 +4991,46 @@ static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int return 1; } -static int stbi__unpremultiply_on_load = 0; -static int stbi__de_iphone_flag = 0; +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { - stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { - stbi__de_iphone_flag = flag_true_if_should_convert; + stbi__de_iphone_flag_global = flag_true_if_should_convert; } +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; @@ -4294,9 +5052,10 @@ static void stbi__de_iphone(stbi__png *z) stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { - p[0] = p[2] * 255 / a; - p[1] = p[1] * 255 / a; - p[2] = t * 255 / a; + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; } else { p[0] = p[2]; p[2] = t; @@ -4315,14 +5074,15 @@ static void stbi__de_iphone(stbi__png *z) } } -#define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d)) +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; - stbi_uc has_trans=0, tc[3]; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; - int first=1,k,interlace=0, color=0, depth=0, is_iphone=0; + int first=1,k,interlace=0, color=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; @@ -4345,10 +5105,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); - s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); - s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)"); - depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); @@ -4357,14 +5120,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); - if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); - // if SCAN_header, have to scan to see if we have a tRNS } + // even with SCAN_header, have to scan to see if we have a tRNS break; } @@ -4396,8 +5158,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; - for (k=0; k < s->img_n; ++k) - tc[k] = (stbi_uc) (stbi__get16be(s) & 255) * stbi__depth_scale_table[depth]; // non 8-bit images will be larger + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } } break; } @@ -4405,14 +5172,22 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); - if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; - p = (stbi_uc *) STBI_REALLOC(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); @@ -4426,7 +5201,7 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * depth + 7) / 8; // bytes per line, per component + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error @@ -4435,9 +5210,14 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0; - if (has_trans) - if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { @@ -4447,8 +5227,13 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; } STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); return 1; } @@ -4474,21 +5259,30 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) } } -static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp) +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { - unsigned char *result=NULL; + void *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { - result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; - if (n) *n = p->s->img_out_n; + if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; @@ -4497,11 +5291,11 @@ static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req return result; } -static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; - return stbi__do_png(&p, x,y,comp,req_comp); + return stbi__do_png(&p, x,y,comp,req_comp, ri); } static int stbi__png_test(stbi__context *s) @@ -4530,6 +5324,19 @@ static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) p.s = s; return stbi__png_info_raw(&p, x, y, comp); } + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} #endif // Microsoft/Windows BMP image @@ -4563,11 +5370,11 @@ static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; - if (z >= 0x10000) n += 16, z >>= 16; - if (z >= 0x00100) n += 8, z >>= 8; - if (z >= 0x00010) n += 4, z >>= 4; - if (z >= 0x00004) n += 2, z >>= 2; - if (z >= 0x00002) n += 1, z >>= 1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } return n; } @@ -4581,36 +5388,76 @@ static int stbi__bitcount(unsigned int a) return a & 0xff; } -static int stbi__shiftsigned(int v, int shift, int bits) +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) { - int result; - int z=0; - - if (shift < 0) v <<= -shift; - else v >>= shift; - result = v; - - z = bits; - while (z < 8) { - result += v >> z; - z += bits; - } - return result; + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; } -static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +typedef struct { - stbi_uc *out; - unsigned int mr=0,mg=0,mb=0,ma=0, all_a=255; - stbi_uc pal[256][4]; - int psize=0,i,j,compress=0,width; - int bpp, flip_vertically, pad, target, offset, hsz; + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved - offset = stbi__get32le(s); - hsz = stbi__get32le(s); + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); @@ -4620,16 +5467,12 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); - bpp = stbi__get16le(s); - if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit"); - flip_vertically = ((int) s->img_y) > 0; - s->img_y = abs((int) s->img_y); - if (hsz == 12) { - if (bpp < 24) - psize = (offset - 14 - 24) / 3; - } else { - compress = stbi__get32le(s); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres @@ -4642,26 +5485,16 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__get32le(s); stbi__get32le(s); } - if (bpp == 16 || bpp == 32) { - mr = mg = mb = 0; + if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { - if (bpp == 32) { - mr = 0xffu << 16; - mg = 0xffu << 8; - mb = 0xffu << 0; - ma = 0xffu << 24; - all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 - } else { - mr = 31u << 10; - mg = 31u << 5; - mb = 31u << 0; - } + stbi__bmp_set_mask_defaults(info, compress); } else if (compress == 3) { - mr = stbi__get32le(s); - mg = stbi__get32le(s); - mb = stbi__get32le(s); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; // not documented, but generated by photoshop and handled by mspaint - if (mr == mg && mg == mb) { + if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } @@ -4669,11 +5502,16 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int return stbi__errpuc("bad BMP", "bad BMP"); } } else { - STBI_ASSERT(hsz == 108 || hsz == 124); - mr = stbi__get32le(s); - mg = stbi__get32le(s); - mb = stbi__get32le(s); - ma = stbi__get32le(s); + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters @@ -4684,63 +5522,146 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__get32le(s); // discard reserved } } - if (bpp < 16) - psize = (offset - 14 - hsz) >> 2; } - s->img_n = ma ? 4 : 3; + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert - out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y); + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (bpp < 16) { + if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); - if (hsz != 12) stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } - stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4)); - if (bpp == 4) width = (s->img_x + 1) >> 1; - else if (bpp == 8) width = s->img_x; + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; - for (j=0; j < (int) s->img_y; ++j) { - for (i=0; i < (int) s->img_x; i += 2) { - int v=stbi__get8(s),v2=0; - if (bpp == 4) { - v2 = v & 15; - v >>= 4; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } } - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - v = (bpp == 8) ? stbi__get8(s) : v2; - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); } - stbi__skip(s, pad); } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; - stbi__skip(s, offset - 14 - hsz); - if (bpp == 24) width = 3 * s->img_x; - else if (bpp == 16) width = 2*s->img_x; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; - if (bpp == 24) { + if (info.bpp == 24) { easy = 1; - } else if (bpp == 32) { + } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } @@ -4751,6 +5672,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } } for (j=0; j < (int) s->img_y; ++j) { if (easy) { @@ -4765,9 +5687,10 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int if (target == 4) out[z++] = a; } } else { + int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); - int a; + unsigned int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); @@ -4779,7 +5702,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi__skip(s, pad); } } - + // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) @@ -4791,7 +5714,7 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { - t = p1[i], p1[i] = p2[i], p2[i] = t; + t = p1[i]; p1[i] = p2[i]; p2[i] = t; } } } @@ -4811,20 +5734,55 @@ static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { - int tga_w, tga_h, tga_comp; - int sz; + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; stbi__get8(s); // discard Offset - sz = stbi__get8(s); // color type - if( sz > 1 ) { + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } - sz = stbi__get8(s); // image type - // only RGB or grey allowed, +/- RLE - if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0; - stbi__skip(s,9); + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); @@ -4835,45 +5793,81 @@ static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) stbi__rewind(s); return 0; // test height } - sz = stbi__get8(s); // bits per pixel - // only RGB or RGBA or grey allowed - if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) { - stbi__rewind(s); - return 0; + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; } - tga_comp = sz; if (x) *x = tga_w; if (y) *y = tga_h; - if (comp) *comp = tga_comp / 8; + if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { - int res; - int sz; + int res = 0; + int sz, tga_color_type; stbi__get8(s); // discard Offset - sz = stbi__get8(s); // color type - if ( sz > 1 ) return 0; // only RGB or indexed allowed + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type - if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE - stbi__get16be(s); // discard palette start - stbi__get16be(s); // discard palette length - stbi__get8(s); // discard bits per palette color entry - stbi__get16be(s); // discard x origin - stbi__get16be(s); // discard y origin - if ( stbi__get16be(s) < 1 ) return 0; // test width - if ( stbi__get16be(s) < 1 ) return 0; // test height + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel - if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) - res = 0; - else - res = 1; + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: stbi__rewind(s); return res; } -static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); @@ -4888,55 +5882,54 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); - int tga_comp = tga_bits_per_pixel / 8; + int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; - unsigned char raw_data[4]; + unsigned char raw_data[4] = {0}; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO - // do a tiny bit of processing + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } - /* int tga_alpha_bits = tga_inverted & 15; */ tga_inverted = 1 - ((tga_inverted >> 5) & 1); - // error check - if ( //(tga_indexed) || - (tga_width < 1) || (tga_height < 1) || - (tga_image_type < 1) || (tga_image_type > 3) || - ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) && - (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32)) - ) - { - return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA - } - // If I'm paletted, then I'll use the number of bits from the palette - if ( tga_indexed ) - { - tga_comp = tga_palette_bits / 8; - } + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; - tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp ); + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); - if ( !tga_indexed && !tga_is_RLE) { + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; @@ -4946,18 +5939,30 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // do I need to load a palette? if ( tga_indexed) { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette - tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_palette_bits / 8 ); + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } - if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) { - STBI_FREE(tga_data); - STBI_FREE(tga_palette); - return stbi__errpuc("bad palette", "Corrupt TGA"); + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data @@ -4987,23 +5992,22 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // load however much data we did have if ( tga_indexed ) { - // read in 1 byte, then perform the lookup - int pal_idx = stbi__get8(s); - if ( pal_idx >= tga_palette_len ) - { - // invalid index + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index pal_idx = 0; } - pal_idx *= tga_bits_per_pixel / 8; - for (j = 0; j*8 < tga_bits_per_pixel; ++j) - { + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } - } else - { + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { // read in the data raw - for (j = 0; j*8 < tga_bits_per_pixel; ++j) - { + for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } @@ -5042,8 +6046,8 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int } } - // swap RGB - if (tga_comp >= 3) + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) @@ -5063,6 +6067,7 @@ static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; } @@ -5079,14 +6084,53 @@ static int stbi__psd_test(stbi__context *s) return r; } -static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { - int pixelCount; + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; int channelCount, compression; - int channel, i, count, len; + int channel, i; int bitdepth; int w,h; stbi_uc *out; + STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" @@ -5108,6 +6152,9 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int h = stbi__get32be(s); w = stbi__get32be(s); + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) @@ -5143,8 +6190,18 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + // Create the destination image. - out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; @@ -5176,67 +6233,86 @@ static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. - count = 0; - while (count < pixelCount) { - len = stbi__get8(s); - if (len == 128) { - // No-op. - } else if (len < 128) { - // Copy next len+1 bytes literally. - len++; - count += len; - while (len) { - *p = stbi__get8(s); - p += 4; - len--; - } - } else if (len > 128) { - stbi_uc val; - // Next -len+1 bytes in the dest are replicated from next source byte. - // (Interpret len as a negative 8-bit int.) - len ^= 0x0FF; - len += 2; - val = stbi__get8(s); - count += len; - while (len) { - *p = val; - p += 4; - len--; - } - } + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) - // where each channel consists of an 8-bit value for each pixel in the image. + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { - stbi_uc *p; - - p = out + channel; if (channel >= channelCount) { // Fill this channel with default data. - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; - } else { - // Read the data. - if (bitdepth == 16) { - for (i = 0; i < pixelCount; i++, p += 4) - *p = (stbi_uc) (stbi__get16be(s) >> 8); + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } } } } } + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format if (req_comp && req_comp != 4) { - out = stbi__convert_format(out, 4, req_comp, w, h); + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } @@ -5420,25 +6496,33 @@ static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *c return result; } -static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp) +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) { stbi_uc *result; - int i, x,y; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); - if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA - result = (stbi_uc *) stbi__malloc(x*y*4); + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { @@ -5475,11 +6559,13 @@ typedef struct typedef struct { int w,h; - stbi_uc *out, *old_out; // output buffer (always 4 components) - int flags, bgindex, ratio, transparent, eflags, delay; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; - stbi__gif_lzw codes[4096]; + stbi__gif_lzw codes[8192]; stbi_uc *color_table; int parse, step; int lflags; @@ -5487,6 +6573,7 @@ typedef struct int max_x, max_y; int cur_x, cur_y; int line_size; + int delay; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) @@ -5535,6 +6622,9 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in g->ratio = stbi__get8(s); g->transparent = -1; + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; @@ -5547,19 +6637,23 @@ static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_in static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { - stbi__gif g; - if (!stbi__gif_header(s, &g, comp, 1)) { + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); stbi__rewind( s ); return 0; } - if (x) *x = g.w; - if (y) *y = g.h; + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; + int idx; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty @@ -5568,10 +6662,12 @@ static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) if (g->cur_y >= g->max_y) return; - p = &g->out[g->cur_x + g->cur_y]; - c = &g->color_table[g->codes[code].suffix * 4]; + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; - if (c[3] >= 128) { + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; @@ -5645,11 +6741,16 @@ static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) stbi__skip(s,len); return g->out; } else if (code <= avail) { - if (first) return stbi__errpuc("no clear code", "Corrupt GIF"); + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } if (oldcode >= 0) { p = &g->codes[avail++]; - if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF"); + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; @@ -5671,59 +6772,77 @@ static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) } } -static void stbi__fill_gif_background(stbi__gif *g, int x0, int y0, int x1, int y1) -{ - int x, y; - stbi_uc *c = g->pal[g->bgindex]; - for (y = y0; y < y1; y += 4 * g->w) { - for (x = x0; x < x1; x += 4) { - stbi_uc *p = &g->out[y + x]; - p[0] = c[2]; - p[1] = c[1]; - p[2] = c[0]; - p[3] = 0; - } - } -} - // this function is designed to support animated gifs, although stb_image doesn't support it -static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp) +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) { - int i; - stbi_uc *prev_out = 0; + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); - if (g->out == 0 && !stbi__gif_header(s, g, comp,0)) - return 0; // stbi__g_failure_reason set by stbi__gif_header + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); - prev_out = g->out; - g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); - if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; - switch ((g->eflags & 0x1C) >> 2) { - case 0: // unspecified (also always used on 1st frame) - stbi__fill_gif_background(g, 0, 0, 4 * g->w, 4 * g->w * g->h); - break; - case 1: // do not dispose - if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); - g->old_out = prev_out; - break; - case 2: // dispose to background - if (prev_out) memcpy(g->out, prev_out, 4 * g->w * g->h); - stbi__fill_gif_background(g, g->start_x, g->start_y, g->max_x, g->max_y); - break; - case 3: // dispose to previous - if (g->old_out) { - for (i = g->start_y; i < g->max_y; i += 4 * g->w) - memcpy(&g->out[i + g->start_x], &g->old_out[i + g->start_x], g->max_x - g->start_x); + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } } - break; + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); } + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + for (;;) { - switch (stbi__get8(s)) { + int tag = stbi__get8(s); + switch (tag) { case 0x2C: /* Image Descriptor */ { - int prev_trans = -1; stbi__int32 x, y, w, h; stbi_uc *o; @@ -5742,6 +6861,13 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i g->cur_x = g->start_x; g->cur_y = g->start_y; + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + g->lflags = stbi__get8(s); if (g->lflags & 0x40) { @@ -5756,19 +6882,24 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { - if (g->transparent >= 0 && (g->eflags & 0x01)) { - prev_trans = g->pal[g->transparent][3]; - g->pal[g->transparent][3] = 0; - } g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); - if (o == NULL) return NULL; + if (!o) return NULL; - if (prev_trans != -1) - g->pal[g->transparent][3] = (stbi_uc) prev_trans; + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } return o; } @@ -5776,19 +6907,35 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i case 0x21: // Comment Extension. { int len; - if (stbi__get8(s) == 0xF9) { // Graphic Control Extension. + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); - g->delay = stbi__get16le(s); - g->transparent = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } } else { stbi__skip(s, len); break; } } - while ((len = stbi__get8(s)) != 0) + while ((len = stbi__get8(s)) != 0) { stbi__skip(s, len); + } break; } @@ -5799,26 +6946,129 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i return stbi__errpuc("unknown code", "Corrupt GIF"); } } - - STBI_NOTUSED(req_comp); } -static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); - u = stbi__gif_load_next(s, &g, comp, req_comp); + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); - } - else if (g.out) + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); return u; } @@ -5833,20 +7083,24 @@ static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR -static int stbi__hdr_test_core(stbi__context *s) +static int stbi__hdr_test_core(stbi__context *s, const char *signature) { - const char *signature = "#?RADIANCE\n"; int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) - return 0; + return 0; + stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { - int r = stbi__hdr_test_core(s); + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } return r; } @@ -5900,7 +7154,7 @@ static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) } } -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; @@ -5911,10 +7165,12 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re int len; unsigned char count, value; int i, j, k, c1,c2, z; - + const char *headerToken; + STBI_NOTUSED(ri); // Check identifier - if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header @@ -5937,14 +7193,22 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re token += 3; width = (int) strtol(token, NULL, 10); + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + // Read data - hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float)); + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca @@ -5983,20 +7247,29 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } - if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4); + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } for (k = 0; k < 4; ++k) { + int nleft; i = 0; - while (i < width) { + while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } @@ -6005,7 +7278,8 @@ static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int re for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } - STBI_FREE(scanline); + if (scanline) + STBI_FREE(scanline); } return hdr_data; @@ -6016,8 +7290,13 @@ static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; + int dummy; - if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) { + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } @@ -6054,29 +7333,23 @@ static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { - int hsz; - if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') { - stbi__rewind( s ); - return 0; + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; } - stbi__skip(s,12); - hsz = stbi__get32le(s); - if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) { - stbi__rewind( s ); - return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; } - if (hsz == 12) { - *x = stbi__get16le(s); - *y = stbi__get16le(s); - } else { - *x = stbi__get32le(s); - *y = stbi__get32le(s); - } - if (stbi__get16le(s) != 1) { - stbi__rewind( s ); - return 0; - } - *comp = stbi__get16le(s) / 8; return 1; } #endif @@ -6084,7 +7357,10 @@ static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { - int channelCount; + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; @@ -6101,7 +7377,8 @@ static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) } *y = stbi__get32be(s); *x = stbi__get32be(s); - if (stbi__get16be(s) != 8) { + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { stbi__rewind( s ); return 0; } @@ -6112,14 +7389,45 @@ static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) *comp = 4; return 1; } + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { - int act_comp=0,num_packets=0,chained; + int act_comp=0,num_packets=0,chained,dummy; stbi__pic_packet packets[10]; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; @@ -6179,7 +7487,6 @@ static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) -// Does not support 16-bit-per-channel #ifndef STBI_NO_PNM @@ -6195,21 +7502,38 @@ static int stbi__pnm_test(stbi__context *s) return 1; } -static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp) +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; - if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + *x = s->img_x; *y = s->img_y; - *comp = s->img_n; + if (comp) *comp = s->img_n; - out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y); + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); - stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } if (req_comp && req_comp != s->img_n) { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; @@ -6222,8 +7546,16 @@ static int stbi__pnm_isspace(char c) static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } } static int stbi__pnm_isdigit(char c) @@ -6238,6 +7570,8 @@ static int stbi__pnm_getinteger(stbi__context *s, char *c) while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); } return value; @@ -6245,16 +7579,20 @@ static int stbi__pnm_getinteger(stbi__context *s, char *c) static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { - int maxv; + int maxv, dummy; char c, p, t; - stbi__rewind( s ); + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind( s ); + stbi__rewind(s); return 0; } @@ -6264,17 +7602,29 @@ static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value - - if (maxv > 255) - return stbi__err("max value > 255", "PPM image not 8-bit"); + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; else - return 1; + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; } #endif @@ -6320,6 +7670,22 @@ static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { @@ -6341,6 +7707,27 @@ STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) fseek(f,pos,SEEK_SET); return r; } + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) @@ -6357,14 +7744,62 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int return stbi__info_main(&s,x,y,comp); } +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + #endif // STB_IMAGE_IMPLEMENTATION /* revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support - limited 16-bit PSD support + limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value @@ -6429,7 +7864,7 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) - added ability to load files via callbacks to accommodate custom input streams (Ben Wenger) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) @@ -6507,3 +7942,46 @@ STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int 0.50 (2006-11-19) first released version */ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/demo/common/overview.c b/demo/common/overview.c index ab66c84..becdade 100644 --- a/demo/common/overview.c +++ b/demo/common/overview.c @@ -2,16 +2,18 @@ static int overview(struct nk_context *ctx) { /* window flags */ - static int show_menu = nk_true; + static nk_bool show_menu = nk_true; static nk_flags window_flags = NK_WINDOW_TITLE|NK_WINDOW_BORDER|NK_WINDOW_SCALABLE|NK_WINDOW_MOVABLE|NK_WINDOW_MINIMIZABLE; nk_flags actual_window_flags; /* popups */ static enum nk_style_header_align header_align = NK_HEADER_RIGHT; - static int show_app_about = nk_false; + static nk_bool show_app_about = nk_false; ctx->style.window.header.align = header_align; + static nk_bool disable_widgets = nk_false; + actual_window_flags = window_flags; if (!(actual_window_flags & NK_WINDOW_TITLE)) actual_window_flags &= ~(NK_WINDOW_MINIMIZABLE|NK_WINDOW_CLOSABLE); @@ -23,7 +25,7 @@ overview(struct nk_context *ctx) enum menu_states {MENU_DEFAULT, MENU_WINDOWS}; static nk_size mprog = 60; static int mslider = 10; - static int mcheck = nk_true; + static nk_bool mcheck = nk_true; nk_menubar_begin(ctx); /* menu #1 */ @@ -33,7 +35,7 @@ overview(struct nk_context *ctx) { static size_t prog = 40; static int slider = 10; - static int check = nk_true; + static nk_bool check = nk_true; nk_layout_row_dynamic(ctx, 25, 1); if (nk_menu_item_label(ctx, "Hide", NK_TEXT_LEFT)) show_menu = nk_false; @@ -129,14 +131,22 @@ overview(struct nk_context *ctx) nk_checkbox_flags_label(ctx, "No Scrollbar", &window_flags, NK_WINDOW_NO_SCROLLBAR); nk_checkbox_flags_label(ctx, "Minimizable", &window_flags, NK_WINDOW_MINIMIZABLE); nk_checkbox_flags_label(ctx, "Scale Left", &window_flags, NK_WINDOW_SCALE_LEFT); + nk_checkbox_label(ctx, "Disable widgets", &disable_widgets); nk_tree_pop(ctx); } + if (disable_widgets) + nk_widget_disable_begin(ctx); + if (nk_tree_push(ctx, NK_TREE_TAB, "Widgets", NK_MINIMIZED)) { enum options {A,B,C}; - static int checkbox; - static int option; + static nk_bool checkbox_left_text_left; + static nk_bool checkbox_centered_text_right; + static nk_bool checkbox_right_text_right; + static nk_bool checkbox_right_text_left; + static int option_left; + static int option_right; if (nk_tree_push(ctx, NK_TREE_NODE, "Text", NK_MINIMIZED)) { /* Text Widgets */ @@ -180,6 +190,7 @@ overview(struct nk_context *ctx) nk_layout_row_static(ctx, 30, 100, 2); nk_button_symbol_label(ctx, NK_SYMBOL_TRIANGLE_LEFT, "prev", NK_TEXT_RIGHT); nk_button_symbol_label(ctx, NK_SYMBOL_TRIANGLE_RIGHT, "next", NK_TEXT_LEFT); + nk_tree_pop(ctx); } @@ -201,13 +212,21 @@ overview(struct nk_context *ctx) static int range_int_max = 4096; static const float ratio[] = {120, 150}; - nk_layout_row_static(ctx, 30, 100, 1); - nk_checkbox_label(ctx, "Checkbox", &checkbox); + nk_layout_row_dynamic(ctx, 0, 1); + nk_checkbox_label(ctx, "CheckLeft TextLeft", &checkbox_left_text_left); + nk_checkbox_label_align(ctx, "CheckCenter TextRight", &checkbox_centered_text_right, NK_WIDGET_ALIGN_CENTERED | NK_WIDGET_ALIGN_MIDDLE, NK_TEXT_RIGHT); + nk_checkbox_label_align(ctx, "CheckRight TextRight", &checkbox_right_text_right, NK_WIDGET_LEFT, NK_TEXT_RIGHT); + nk_checkbox_label_align(ctx, "CheckRight TextLeft", &checkbox_right_text_left, NK_WIDGET_RIGHT, NK_TEXT_LEFT); nk_layout_row_static(ctx, 30, 80, 3); - option = nk_option_label(ctx, "optionA", option == A) ? A : option; - option = nk_option_label(ctx, "optionB", option == B) ? B : option; - option = nk_option_label(ctx, "optionC", option == C) ? C : option; + option_left = nk_option_label(ctx, "optionA", option_left == A) ? A : option_left; + option_left = nk_option_label(ctx, "optionB", option_left == B) ? B : option_left; + option_left = nk_option_label(ctx, "optionC", option_left == C) ? C : option_left; + + nk_layout_row_static(ctx, 30, 80, 3); + option_right = nk_option_label_align(ctx, "optionA", option_right == A, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? A : option_right; + option_right = nk_option_label_align(ctx, "optionB", option_right == B, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? B : option_right; + option_right = nk_option_label_align(ctx, "optionC", option_right == C, NK_WIDGET_RIGHT, NK_TEXT_RIGHT) ? C : option_right; nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); nk_labelf(ctx, NK_TEXT_LEFT, "Slider int"); @@ -242,35 +261,28 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Inactive", NK_MINIMIZED)) { - static int inactive = 1; + static nk_bool inactive = 1; nk_layout_row_dynamic(ctx, 30, 1); nk_checkbox_label(ctx, "Inactive", &inactive); nk_layout_row_static(ctx, 30, 80, 1); if (inactive) { - struct nk_style_button button; - button = ctx->style.button; - ctx->style.button.normal = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.hover = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.active = nk_style_item_color(nk_rgb(40,40,40)); - ctx->style.button.border_color = nk_rgb(60,60,60); - ctx->style.button.text_background = nk_rgb(60,60,60); - ctx->style.button.text_normal = nk_rgb(60,60,60); - ctx->style.button.text_hover = nk_rgb(60,60,60); - ctx->style.button.text_active = nk_rgb(60,60,60); - nk_button_label(ctx, "button"); - ctx->style.button = button; - } else if (nk_button_label(ctx, "button")) + nk_widget_disable_begin(ctx); + } + + if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); + + nk_widget_disable_end(ctx); + nk_tree_pop(ctx); } - if (nk_tree_push(ctx, NK_TREE_NODE, "Selectable", NK_MINIMIZED)) { if (nk_tree_push(ctx, NK_TREE_NODE, "List", NK_MINIMIZED)) { - static int selected[4] = {nk_false, nk_false, nk_true, nk_false}; + static nk_bool selected[4] = {nk_false, nk_false, nk_true, nk_false}; nk_layout_row_static(ctx, 18, 100, 1); nk_selectable_label(ctx, "Selectable", NK_TEXT_LEFT, &selected[0]); nk_selectable_label(ctx, "Selectable", NK_TEXT_LEFT, &selected[1]); @@ -282,7 +294,7 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Grid", NK_MINIMIZED)) { int i; - static int selected[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; + static nk_bool selected[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; nk_layout_row_static(ctx, 50, 50, 4); for (i = 0; i < 16; ++i) { if (nk_selectable_label(ctx, "Z", NK_TEXT_CENTERED, &selected[i])) { @@ -329,7 +341,7 @@ overview(struct nk_context *ctx) */ static float chart_selection = 8.0f; static int current_weapon = 0; - static int check_values[5]; + static nk_bool check_values[5]; static float position[3]; static struct nk_color combo_color = {130, 50, 50, 255}; static struct nk_colorf combo_color2 = {0.509f, 0.705f, 0.2f, 1.0f}; @@ -590,7 +602,7 @@ overview(struct nk_context *ctx) } nk_tree_pop(ctx); } - + if (nk_tree_push(ctx, NK_TREE_NODE, "Horizontal Rule", NK_MINIMIZED)) { nk_layout_row_dynamic(ctx, 12, 1); @@ -620,6 +632,7 @@ overview(struct nk_context *ctx) float id = 0; static int col_index = -1; static int line_index = -1; + static int show_markers = nk_true; float step = (2*3.141592654f) / 32; int i; @@ -628,7 +641,10 @@ overview(struct nk_context *ctx) /* line chart */ id = 0; index = -1; + nk_layout_row_dynamic(ctx, 15, 1); + nk_checkbox_label(ctx, "Show markers", &show_markers); nk_layout_row_dynamic(ctx, 100, 1); + ctx->style.chart.show_markers = show_markers; if (nk_chart_begin(ctx, NK_CHART_LINES, 32, -1.0f, 1.0f)) { for (i = 0; i < 32; ++i) { nk_flags res = nk_chart_push(ctx, (float)cos(id)); @@ -701,8 +717,8 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_TAB, "Popup", NK_MINIMIZED)) { static struct nk_color color = {255,0,0, 255}; - static int select[4]; - static int popup_active; + static nk_bool select[4]; + static nk_bool popup_active; const struct nk_input *in = &ctx->input; struct nk_rect bounds; @@ -871,9 +887,9 @@ overview(struct nk_context *ctx) if (nk_tree_push(ctx, NK_TREE_NODE, "Group", NK_MINIMIZED)) { - static int group_titlebar = nk_false; - static int group_border = nk_true; - static int group_no_scrollbar = nk_false; + static nk_bool group_titlebar = nk_false; + static nk_bool group_border = nk_true; + static nk_bool group_no_scrollbar = nk_false; static int group_width = 320; static int group_height = 200; @@ -899,7 +915,7 @@ overview(struct nk_context *ctx) nk_layout_row_static(ctx, (float)group_height, group_width, 2); if (nk_group_begin(ctx, "Group", group_flags)) { int i = 0; - static int selected[16]; + static nk_bool selected[16]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 16; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -909,11 +925,12 @@ overview(struct nk_context *ctx) } if (nk_tree_push(ctx, NK_TREE_NODE, "Tree", NK_MINIMIZED)) { - static int root_selected = 0; - int sel = root_selected; + static nk_bool root_selected = 0; + nk_bool sel = root_selected; if (nk_tree_element_push(ctx, NK_TREE_NODE, "Root", NK_MINIMIZED, &sel)) { - static int selected[8]; - int i = 0, node_select = selected[0]; + static nk_bool selected[8]; + int i = 0; + nk_bool node_select = selected[0]; if (sel != root_selected) { root_selected = sel; for (i = 0; i < 8; ++i) @@ -921,7 +938,7 @@ overview(struct nk_context *ctx) } if (nk_tree_element_push(ctx, NK_TREE_NODE, "Node", NK_MINIMIZED, &node_select)) { int j = 0; - static int sel_nodes[4]; + static nk_bool sel_nodes[4]; if (node_select != selected[0]) { selected[0] = node_select; for (i = 0; i < 4; ++i) @@ -1049,7 +1066,7 @@ overview(struct nk_context *ctx) nk_layout_space_begin(ctx, NK_STATIC, 500, 64); nk_layout_space_push(ctx, nk_rect(0,0,150,500)); if (nk_group_begin(ctx, "Group_left", NK_WINDOW_BORDER)) { - static int selected[32]; + static nk_bool selected[32]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 32; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1082,7 +1099,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,0,150,150)); if (nk_group_begin(ctx, "Group_right_top", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1091,7 +1108,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,160,150,150)); if (nk_group_begin(ctx, "Group_right_center", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1100,7 +1117,7 @@ overview(struct nk_context *ctx) nk_layout_space_push(ctx, nk_rect(320,320,150,150)); if (nk_group_begin(ctx, "Group_right_bottom", NK_WINDOW_BORDER)) { - static int selected[4]; + static nk_bool selected[4]; nk_layout_row_static(ctx, 18, 100, 1); for (i = 0; i < 4; ++i) nk_selectable_label(ctx, (selected[i]) ? "Selected": "Unselected", NK_TEXT_CENTERED, &selected[i]); @@ -1289,8 +1306,9 @@ overview(struct nk_context *ctx) } nk_tree_pop(ctx); } + if (disable_widgets) + nk_widget_disable_end(ctx); } nk_end(ctx); return !nk_window_is_closed(ctx, "Overview"); } - diff --git a/demo/d3d11/nuklear_d3d11.h b/demo/d3d11/nuklear_d3d11.h index 27fa2c1..c62be56 100644 --- a/demo/d3d11/nuklear_d3d11.h +++ b/demo/d3d11/nuklear_d3d11.h @@ -41,6 +41,7 @@ NK_API void nk_d3d11_shutdown(void); #define COBJMACROS #include +#include #include #include #include diff --git a/demo/d3d12/nuklear_d3d12.h b/demo/d3d12/nuklear_d3d12.h index 5b86ea1..03560a2 100644 --- a/demo/d3d12/nuklear_d3d12.h +++ b/demo/d3d12/nuklear_d3d12.h @@ -88,6 +88,7 @@ NK_API void nk_d3d12_shutdown(void); #define COBJMACROS #include +#include #include #include #include diff --git a/demo/d3d9/nuklear_d3d9.h b/demo/d3d9/nuklear_d3d9.h index f967678..8af027f 100644 --- a/demo/d3d9/nuklear_d3d9.h +++ b/demo/d3d9/nuklear_d3d9.h @@ -41,6 +41,7 @@ NK_API void nk_d3d9_shutdown(void); #define COBJMACROS #include +#include #include #include diff --git a/demo/gdi/nuklear_gdi.h b/demo/gdi/nuklear_gdi.h index 6bbedb6..ff2ff19 100644 --- a/demo/gdi/nuklear_gdi.h +++ b/demo/gdi/nuklear_gdi.h @@ -38,7 +38,7 @@ NK_API void nk_gdi_set_font(GdiFont *font); * =============================================================== */ #ifdef NK_GDI_IMPLEMENTATION - +#include #include #include diff --git a/demo/gdi_native_nuklear/nuklear_gdi.h b/demo/gdi_native_nuklear/nuklear_gdi.h index 5c2f1f8..aa91740 100644 --- a/demo/gdi_native_nuklear/nuklear_gdi.h +++ b/demo/gdi_native_nuklear/nuklear_gdi.h @@ -50,7 +50,7 @@ NK_API void nk_gdi_set_font(nk_gdi_ctx gdi, GdiFont* font); * =============================================================== */ #ifdef NK_GDI_IMPLEMENTATION - +#include #include #include diff --git a/demo/glfw_opengl2/nuklear_glfw_gl2.h b/demo/glfw_opengl2/nuklear_glfw_gl2.h index fb8b31e..d74b4f2 100644 --- a/demo/glfw_opengl2/nuklear_glfw_gl2.h +++ b/demo/glfw_opengl2/nuklear_glfw_gl2.h @@ -40,6 +40,8 @@ NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xof * =============================================================== */ #ifdef NK_GLFW_GL2_IMPLEMENTATION +#include +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/glfw_opengl3/nuklear_glfw_gl3.h b/demo/glfw_opengl3/nuklear_glfw_gl3.h index cef59e5..8ba361c 100644 --- a/demo/glfw_opengl3/nuklear_glfw_gl3.h +++ b/demo/glfw_opengl3/nuklear_glfw_gl3.h @@ -78,6 +78,9 @@ NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int * =============================================================== */ #ifdef NK_GLFW_GL3_IMPLEMENTATION +#include +#include +#include #ifndef NK_GLFW_DOUBLE_CLICK_LO #define NK_GLFW_DOUBLE_CLICK_LO 0.02 diff --git a/demo/glfw_opengl4/nuklear_glfw_gl4.h b/demo/glfw_opengl4/nuklear_glfw_gl4.h index 781bfc3..b4df990 100644 --- a/demo/glfw_opengl4/nuklear_glfw_gl4.h +++ b/demo/glfw_opengl4/nuklear_glfw_gl4.h @@ -50,6 +50,9 @@ NK_API void nk_glfw3_destroy_texture(int tex_index); */ #ifdef NK_GLFW_GL4_IMPLEMENTATION #undef NK_GLFW_GL4_IMPLEMENTATION +#include +#include +#include #ifndef NK_GLFW_TEXT_MAX #define NK_GLFW_TEXT_MAX 256 diff --git a/demo/glfw_vulkan/.clang-format b/demo/glfw_vulkan/.clang-format new file mode 100644 index 0000000..3fa531e --- /dev/null +++ b/demo/glfw_vulkan/.clang-format @@ -0,0 +1,4 @@ +--- +BasedOnStyle: LLVM +# same as .editorconfig +IndentWidth: 4 diff --git a/demo/glfw_vulkan/.gitignore b/demo/glfw_vulkan/.gitignore new file mode 100644 index 0000000..00569e3 --- /dev/null +++ b/demo/glfw_vulkan/.gitignore @@ -0,0 +1,3 @@ +src/nuklearshaders/*.spv +src/nuklear_glfw_vulkan.h +shaders/*.spv diff --git a/demo/glfw_vulkan/Makefile b/demo/glfw_vulkan/Makefile new file mode 100644 index 0000000..57675fd --- /dev/null +++ b/demo/glfw_vulkan/Makefile @@ -0,0 +1,29 @@ +# Install +BIN = demo + +# Flags +CFLAGS += -std=c89 -Wall -Wextra -pedantic -O2 + +SRC = main.c +OBJ = $(SRC:.c=.o) + +ifeq ($(OS),Windows_NT) +BIN := $(BIN).exe +LIBS = -lglfw3 -lvulkan -lm +else + UNAME_S := $(shell uname -s) + GLFW3 := $(shell pkg-config --libs glfw3) + LIBS = $(GLFW3) -lvulkan -lm +endif + + +$(BIN): shaders/demo.vert.spv shaders/demo.frag.spv + @mkdir -p bin + rm -f bin/$(BIN) $(OBJS) + $(CC) $(SRC) $(CFLAGS) -o bin/$(BIN) $(LIBS) + +shaders/demo.vert.spv: shaders/demo.vert + glslc --target-env=vulkan shaders/demo.vert -o shaders/demo.vert.spv + +shaders/demo.frag.spv: shaders/demo.frag + glslc --target-env=vulkan shaders/demo.frag -o shaders/demo.frag.spv diff --git a/demo/glfw_vulkan/README.md b/demo/glfw_vulkan/README.md new file mode 100644 index 0000000..ff0a2fc --- /dev/null +++ b/demo/glfw_vulkan/README.md @@ -0,0 +1,52 @@ +# nuklear glfw vulkan + +## Theory of operation + +The nuklear glfw vulkan integration creates an independent graphics pipeline that will render the nuklear UI to separate render targets. +The application is responsible to fully manage these render targets. So it must ensure they are properly sized (and resized when requested). + +Furthermore it is assumed that you will have a swap chain in place and the number of nuklear overlay images and number of swap chain images match. + +This is how you can integrate it in your application: + +``` +/* +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); +[...] +/* +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; + } +``` + +You must call `nk_glfw3_resize` whenever the size of the overlay_images resize. + +## Using images + +Images can be used by providing a VkImageView as an nk_image_ptr to nuklear: + +``` +img = nk_image_ptr(demo.demo_texture_image_view); +``` + +Note that they must have SHADER_READ_OPTIMAL layout + +It is currently not possible to specify how they are being sampled. The nuklear glfw vulkan integration uses a fixed sampler that does linear filtering. diff --git a/demo/glfw_vulkan/main.c b/demo/glfw_vulkan/main.c new file mode 100644 index 0000000..071ec31 --- /dev/null +++ b/demo/glfw_vulkan/main.c @@ -0,0 +1,2229 @@ +/* nuklear - 1.32.0 - public domain */ +#include +#include +#include +#include +#include +#include + +#define GLFW_INCLUDE_VULKAN +#include + +#define NK_INCLUDE_FIXED_TYPES +#define NK_INCLUDE_STANDARD_IO +#define NK_INCLUDE_STANDARD_VARARGS +#define NK_INCLUDE_DEFAULT_ALLOCATOR +#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT +#define NK_INCLUDE_FONT_BAKING +#define NK_INCLUDE_DEFAULT_FONT +#define NK_IMPLEMENTATION +#define NK_GLFW_VULKAN_IMPLEMENTATION +#define NK_KEYSTATE_BASED_INPUT +#include "../../nuklear.h" +#include "nuklear_glfw_vulkan.h" + +#define WINDOW_WIDTH 1200 +#define WINDOW_HEIGHT 800 + +#define MAX_VERTEX_BUFFER 512 * 1024 +#define MAX_ELEMENT_BUFFER 128 * 1024 + +/* =============================================================== + * + * EXAMPLE + * + * ===============================================================*/ +/* This are some code examples to provide a small overview of what can be + * done with this library. To try out an example uncomment the defines */ +#define INCLUDE_ALL +/*#define INCLUDE_STYLE */ +/*#define INCLUDE_CALCULATOR */ +/*#define INCLUDE_CANVAS */ +/*#define INCLUDE_OVERVIEW*/ +/*#define INCLUDE_NODE_EDITOR */ + +#ifdef INCLUDE_ALL +#define INCLUDE_STYLE +#define INCLUDE_CALCULATOR +#define INCLUDE_CANVAS +#define INCLUDE_OVERVIEW +#define INCLUDE_NODE_EDITOR +#endif + +#ifdef INCLUDE_STYLE +#include "../../demo/common/style.c" +#endif +#ifdef INCLUDE_CALCULATOR +#include "../../demo/common/calculator.c" +#endif +#ifdef INCLUDE_CANVAS +#include "../../demo/common/canvas.c" +#endif +#ifdef INCLUDE_OVERVIEW +#include "../../demo/common/overview.c" +#endif +#ifdef INCLUDE_NODE_EDITOR +#include "../../demo/common/node_editor.c" +#endif + +/* =============================================================== + * + * DEMO + * + * ===============================================================*/ + +static const char *validation_layer_name = "VK_LAYER_KHRONOS_validation"; + +struct queue_family_indices { + int graphics; + int present; +}; + +struct swap_chain_support_details { + VkSurfaceCapabilitiesKHR capabilities; + VkSurfaceFormatKHR *formats; + uint32_t formats_len; + VkPresentModeKHR *present_modes; + uint32_t present_modes_len; +}; + +void swap_chain_support_details_free( + struct swap_chain_support_details *swap_chain_support) { + if (swap_chain_support->formats_len > 0) { + free(swap_chain_support->formats); + swap_chain_support->formats = NULL; + } + if (swap_chain_support->present_modes_len > 0) { + free(swap_chain_support->present_modes); + swap_chain_support->present_modes = NULL; + } +} + +struct vulkan_demo { + GLFWwindow *win; + VkInstance instance; + VkDebugUtilsMessengerEXT debug_messenger; + VkSurfaceKHR surface; + VkPhysicalDevice physical_device; + struct queue_family_indices indices; + VkDevice device; + VkQueue graphics_queue; + VkQueue present_queue; + VkSampler sampler; + + VkSwapchainKHR swap_chain; + VkImage *swap_chain_images; + uint32_t swap_chain_images_len; + VkImageView *swap_chain_image_views; + VkFormat swap_chain_image_format; + VkExtent2D swap_chain_image_extent; + + VkImage *overlay_images; + VkImageView *overlay_image_views; + VkDeviceMemory *overlay_image_memories; + + VkRenderPass render_pass; + VkFramebuffer *framebuffers; + VkDescriptorSetLayout descriptor_set_layout; + VkDescriptorPool descriptor_pool; + VkDescriptorSet *descriptor_sets; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkCommandPool command_pool; + VkCommandBuffer *command_buffers; + VkSemaphore image_available; + VkSemaphore render_finished; + + VkImage demo_texture_image; + VkImageView demo_texture_image_view; + VkDeviceMemory demo_texture_memory; + + VkFence render_fence; +}; + +static void glfw_error_callback(int e, const char *d) { + fprintf(stderr, "Error %d: %s\n", e, d); +} + +VKAPI_ATTR VkBool32 VKAPI_CALL +vulkan_debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, + VkDebugUtilsMessageTypeFlagsEXT message_type, + const VkDebugUtilsMessengerCallbackDataEXT *callback_data, + void *user_data) { + (void)message_severity; + (void)message_type; + (void)user_data; + fprintf(stderr, "validation layer: %s\n", callback_data->pMessage); + + return VK_FALSE; +} + +bool check_validation_layer_support() { + uint32_t layer_count; + bool ret = false; + VkResult result; + uint32_t i; + VkLayerProperties *available_layers = NULL; + + result = vkEnumerateInstanceLayerProperties(&layer_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceLayerProperties failed: %d\n", + result); + return ret; + } + + available_layers = malloc(layer_count * sizeof(VkLayerProperties)); + result = vkEnumerateInstanceLayerProperties(&layer_count, available_layers); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceLayerProperties failed: %d\n", + result); + goto cleanup; + } + + printf("Available vulkan layers:\n"); + for (i = 0; i < layer_count; i++) { + printf(" %s\n", available_layers[i].layerName); + if (strcmp(validation_layer_name, available_layers[i].layerName) == 0) { + ret = true; + break; + } + } +cleanup: + free(available_layers); + return ret; +} + +VkResult create_debug_utils_messenger_ext( + VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, + const VkAllocationCallbacks *pAllocator, + VkDebugUtilsMessengerEXT *pDebugMessenger) { + PFN_vkCreateDebugUtilsMessengerEXT func = + (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( + instance, "vkCreateDebugUtilsMessengerEXT"); + if (func != NULL) { + return func(instance, pCreateInfo, pAllocator, pDebugMessenger); + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +bool create_debug_callback(struct vulkan_demo *demo) { + VkResult result; + + VkDebugUtilsMessengerCreateInfoEXT create_info; + memset(&create_info, 0, sizeof(VkDebugUtilsMessengerCreateInfoEXT)); + create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + create_info.messageSeverity = + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + create_info.pfnUserCallback = vulkan_debug_callback; + + result = create_debug_utils_messenger_ext(demo->instance, &create_info, + NULL, &demo->debug_messenger); + if (result != VK_SUCCESS) { + fprintf(stderr, "create_debug_utils_messenger_ext failed %d\n", result); + return false; + } + return true; +} + +bool create_instance(struct vulkan_demo *demo) { + uint32_t i; + uint32_t available_instance_extension_count; + VkResult result; + VkExtensionProperties *available_instance_extensions = NULL; + bool ret = false; + VkApplicationInfo app_info; + VkInstanceCreateInfo create_info; + uint32_t glfw_extension_count; + const char **glfw_extensions; + uint32_t enabled_extension_count; + const char **enabled_extensions = NULL; + bool validation_layers_installed; + + validation_layers_installed = check_validation_layer_support(); + + if (!validation_layers_installed) { + fprintf(stdout, + "Couldn't find validation layer %s. Continuing without " + "validation layers.\n", + validation_layer_name); + } + result = vkEnumerateInstanceExtensionProperties( + NULL, &available_instance_extension_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", + result); + return ret; + } + + available_instance_extensions = malloc(available_instance_extension_count * + sizeof(VkExtensionProperties)); + + result = vkEnumerateInstanceExtensionProperties( + NULL, &available_instance_extension_count, + available_instance_extensions); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", + result); + goto cleanup; + } + + printf("available instance extensions:\n"); + for (i = 0; i < available_instance_extension_count; i++) { + printf(" %s\n", available_instance_extensions[i].extensionName); + } + + glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count); + + enabled_extension_count = glfw_extension_count; + if (validation_layers_installed) { + enabled_extension_count += 1; + enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); + memcpy(enabled_extensions, glfw_extensions, + glfw_extension_count * sizeof(char *)); + enabled_extensions[glfw_extension_count] = + VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + } else { + enabled_extensions = malloc(enabled_extension_count * sizeof(char *)); + memcpy(enabled_extensions, glfw_extensions, + glfw_extension_count * sizeof(char *)); + } + + printf("Trying to enable the following instance extensions: "); + for (i = 0; i < enabled_extension_count; i++) { + if (i > 0) { + printf(", "); + } + printf(enabled_extensions[i]); + } + printf("\n"); + for (i = 0; i < enabled_extension_count; i++) { + int extension_missing = 1; + uint32_t j; + for (j = 0; j < available_instance_extension_count; j++) { + if (strcmp(enabled_extensions[i], + available_instance_extensions[j].extensionName) == 0) { + extension_missing = 0; + break; + } + } + if (extension_missing) { + fprintf(stderr, "Extension %s is missing\n", enabled_extensions[i]); + return ret; + } + } + + memset(&app_info, 0, sizeof(VkApplicationInfo)); + app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + app_info.pApplicationName = "Demo"; + app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.pEngineName = "No Engine"; + app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); + app_info.apiVersion = VK_API_VERSION_1_0; + + memset(&create_info, 0, sizeof(VkInstanceCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + create_info.pApplicationInfo = &app_info; + create_info.enabledExtensionCount = enabled_extension_count; + create_info.ppEnabledExtensionNames = enabled_extensions; + if (validation_layers_installed) { + create_info.enabledLayerCount = 1; + create_info.ppEnabledLayerNames = &validation_layer_name; + } + result = vkCreateInstance(&create_info, NULL, &demo->instance); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateInstance result %d\n", result); + return ret; + } + if (validation_layers_installed) { + ret = create_debug_callback(demo); + } else { + ret = true; + } +cleanup: + if (available_instance_extensions) { + free(available_instance_extensions); + } + if (enabled_extensions) { + free(enabled_extensions); + } + + return ret; +} + +bool create_surface(struct vulkan_demo *demo) { + VkResult result; + result = glfwCreateWindowSurface(demo->instance, demo->win, NULL, + &demo->surface); + if (result != VK_SUCCESS) { + fprintf(stderr, "creating vulkan surface failed: %d\n", result); + return false; + } + return true; +} + +bool find_queue_families(VkPhysicalDevice physical_device, VkSurfaceKHR surface, + struct queue_family_indices *indices) { + VkResult result; + uint32_t queue_family_count = 0; + uint32_t i = 0; + bool ret = false; + VkQueueFamilyProperties *queue_family_properties; + VkBool32 present_support; + + vkGetPhysicalDeviceQueueFamilyProperties(physical_device, + &queue_family_count, NULL); + + queue_family_properties = + malloc(queue_family_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties( + physical_device, &queue_family_count, queue_family_properties); + + for (i = 0; i < queue_family_count; i++) { + if (queue_family_properties[i].queueCount == 0) { + continue; + } + if (queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { + indices->graphics = i; + } + + result = vkGetPhysicalDeviceSurfaceSupportKHR( + physical_device, i, surface, &present_support); + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfaceSupportKHR failed with %d\n", + result); + goto cleanup; + } + if (present_support == VK_TRUE) { + indices->present = i; + } + if (indices->graphics >= 0 && indices->present >= 0) { + break; + } + } + ret = true; +cleanup: + free(queue_family_properties); + return ret; +} + +bool query_swap_chain_support( + VkPhysicalDevice device, VkSurfaceKHR surface, + struct swap_chain_support_details *swap_chain_support) { + VkResult result; + + result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR( + device, surface, &swap_chain_support->capabilities); + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfaceCapabilitiesKHR failed: %d\n", + result); + return false; + } + + result = vkGetPhysicalDeviceSurfaceFormatsKHR( + device, surface, &swap_chain_support->formats_len, NULL); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: %d\n", + result); + return false; + } + + if (swap_chain_support->formats_len != 0) { + swap_chain_support->formats = malloc(swap_chain_support->formats_len * + sizeof(VkSurfaceFormatKHR)); + result = vkGetPhysicalDeviceSurfaceFormatsKHR( + device, surface, &swap_chain_support->formats_len, + swap_chain_support->formats); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetPhysicalDeviceSurfaceFormatsKHR failed: %d\n", + result); + return false; + } + } + + result = vkGetPhysicalDeviceSurfacePresentModesKHR( + device, surface, &swap_chain_support->present_modes_len, NULL); + + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfacePresentModesKHR failed: %d\n", + result); + return false; + } + + if (swap_chain_support->present_modes_len != 0) { + swap_chain_support->present_modes = malloc( + swap_chain_support->present_modes_len * sizeof(VkPresentModeKHR)); + result = vkGetPhysicalDeviceSurfacePresentModesKHR( + device, surface, &swap_chain_support->present_modes_len, + swap_chain_support->present_modes); + + if (result != VK_SUCCESS) { + fprintf(stderr, + "vkGetPhysicalDeviceSurfacePresentModesKHR failed: %d\n", + result); + return false; + } + } + + return true; +} + +bool is_suitable_physical_device(VkPhysicalDevice physical_device, + VkSurfaceKHR surface, + struct queue_family_indices *indices) { + VkResult result; + uint32_t device_extension_count; + uint32_t i; + VkExtensionProperties *device_extensions; + bool ret = false; + struct swap_chain_support_details swap_chain_support; + int found_khr_surface = 0; + + VkPhysicalDeviceProperties device_properties; + vkGetPhysicalDeviceProperties(physical_device, &device_properties); + + printf("Probing physical device %s\n", device_properties.deviceName); + + result = vkEnumerateDeviceExtensionProperties( + physical_device, NULL, &device_extension_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed: %d\n", + result); + return false; + } + + device_extensions = + malloc(device_extension_count * sizeof(VkExtensionProperties)); + + result = vkEnumerateDeviceExtensionProperties( + physical_device, NULL, &device_extension_count, device_extensions); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed: %d\n", + result); + goto cleanup; + } + + printf(" Supported device extensions:\n"); + + for (i = 0; i < device_extension_count; i++) { + printf(" %s\n", device_extensions[i].extensionName); + if (strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, + device_extensions[i].extensionName) == 0) { + found_khr_surface = 1; + break; + } + } + if (!found_khr_surface) { + printf(" Device doesnt support %s\n", VK_KHR_SWAPCHAIN_EXTENSION_NAME); + goto cleanup; + } + if (!find_queue_families(physical_device, surface, indices)) { + goto cleanup; + } + if (indices->graphics < 0 || indices->present < 0) { + printf(" Device is missing graphics and/or present support. graphics: " + "%d, present: %d\n", + indices->graphics, indices->present); + goto cleanup; + } + + if (!query_swap_chain_support(physical_device, surface, + &swap_chain_support)) { + goto cleanup; + } + + if (swap_chain_support.formats_len == 0) { + printf(" Device doesn't support any swap chain formats\n"); + goto cleanup; + } + + if (swap_chain_support.present_modes_len == 0) { + printf(" Device doesn't support any swap chain present modes\n"); + goto cleanup; + } + ret = true; + +cleanup: + free(device_extensions); + swap_chain_support_details_free(&swap_chain_support); + + return ret; +} + +bool create_physical_device(struct vulkan_demo *demo) { + uint32_t device_count = 0; + VkPhysicalDevice *physical_devices; + VkResult result; + uint32_t i; + bool ret = false; + + result = vkEnumeratePhysicalDevices(demo->instance, &device_count, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumeratePhysicalDevices failed: %d\n", result); + return ret; + } + if (device_count == 0) { + fprintf(stderr, "no vulkan capable GPU found!"); + return ret; + } + + physical_devices = malloc(device_count * sizeof(VkPhysicalDevice)); + result = vkEnumeratePhysicalDevices(demo->instance, &device_count, + physical_devices); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEnumeratePhysicalDevices failed: %d\n", result); + goto cleanup; + } + + for (i = 0; i < device_count; i++) { + struct queue_family_indices indices = {-1, -1}; + if (is_suitable_physical_device(physical_devices[i], demo->surface, + &indices)) { + printf(" Selecting this device for rendering. Queue families: " + "graphics: %d, present: %d!\n", + indices.graphics, indices.present); + demo->physical_device = physical_devices[i]; + demo->indices = indices; + break; + } + } + if (demo->physical_device == NULL) { + fprintf(stderr, "failed to find a suitable GPU!\n"); + } else { + ret = true; + } +cleanup: + free(physical_devices); + return ret; +} + +bool create_logical_device(struct vulkan_demo *demo) { + VkResult result; + bool ret = false; + float queuePriority = 1.0f; + uint32_t num_queues = 1; + VkDeviceQueueCreateInfo *queue_create_infos; + VkDeviceCreateInfo create_info; + const char *swap_chain_extension_name = VK_KHR_SWAPCHAIN_EXTENSION_NAME; + + queue_create_infos = calloc(2, sizeof(VkDeviceQueueCreateInfo)); + queue_create_infos[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_create_infos[0].queueFamilyIndex = demo->indices.graphics; + queue_create_infos[0].queueCount = 1; + queue_create_infos[0].pQueuePriorities = &queuePriority; + + if (demo->indices.present != demo->indices.graphics) { + queue_create_infos[1].sType = + VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queue_create_infos[1].queueFamilyIndex = demo->indices.present; + queue_create_infos[1].queueCount = 1; + queue_create_infos[1].pQueuePriorities = &queuePriority; + num_queues = 2; + } + + memset(&create_info, 0, sizeof(VkDeviceCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + create_info.queueCreateInfoCount = num_queues; + create_info.pQueueCreateInfos = queue_create_infos; + create_info.enabledExtensionCount = 1; + create_info.ppEnabledExtensionNames = &swap_chain_extension_name; + + result = vkCreateDevice(demo->physical_device, &create_info, NULL, + &demo->device); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDevice failed: %d\n", result); + goto cleanup; + } + + vkGetDeviceQueue(demo->device, demo->indices.graphics, 0, + &demo->graphics_queue); + vkGetDeviceQueue(demo->device, demo->indices.present, 0, + &demo->present_queue); + ret = true; +cleanup: + free(queue_create_infos); + return ret; +} + +bool create_sampler(struct vulkan_demo *demo) { + VkResult result; + VkSamplerCreateInfo sampler_info; + + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(demo->device, &sampler_info, NULL, &demo->sampler); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSampler failed: %d\n", result); + return false; + } + return true; +} + +VkSurfaceFormatKHR +choose_swap_surface_format(VkSurfaceFormatKHR *available_formats, + uint32_t available_formats_len) { + VkSurfaceFormatKHR undefined_format = {VK_FORMAT_B8G8R8A8_UNORM, + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; + uint32_t i; + if (available_formats_len == 1 && + available_formats[0].format == VK_FORMAT_UNDEFINED) { + return undefined_format; + } + + for (i = 0; i < available_formats_len; i++) { + if (available_formats[i].format == VK_FORMAT_B8G8R8A8_UNORM && + available_formats[i].colorSpace == + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { + return available_formats[i]; + } + } + + return available_formats[0]; +} + +VkPresentModeKHR +choose_swap_present_mode(VkPresentModeKHR *available_present_modes, + uint32_t available_present_modes_len) { + uint32_t i; + for (i = 0; i < available_present_modes_len; i++) { + /* + best mode to ensure good input latency while ensuring we are not + producing tearing + */ + if (available_present_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { + return available_present_modes[i]; + } + } + + /* must be supported */ + return VK_PRESENT_MODE_FIFO_KHR; +} + +VkExtent2D choose_swap_extent(struct vulkan_demo *demo, + VkSurfaceCapabilitiesKHR *capabilities) { + int width, height; + VkExtent2D actual_extent; + if (capabilities->currentExtent.width != 0xFFFFFFFF) { + return capabilities->currentExtent; + } else { + /* not window size! */ + glfwGetFramebufferSize(demo->win, &width, &height); + + actual_extent.width = (uint32_t)width; + actual_extent.height = (uint32_t)height; + + actual_extent.width = NK_MAX( + capabilities->minImageExtent.width, + NK_MIN(capabilities->maxImageExtent.width, actual_extent.width)); + actual_extent.height = NK_MAX( + capabilities->minImageExtent.height, + NK_MIN(capabilities->maxImageExtent.height, actual_extent.height)); + + return actual_extent; + } +} + +bool create_swap_chain(struct vulkan_demo *demo) { + struct swap_chain_support_details swap_chain_support; + VkSurfaceFormatKHR surface_format; + VkPresentModeKHR present_mode; + VkExtent2D extent; + VkResult result; + VkSwapchainCreateInfoKHR create_info; + uint32_t queue_family_indices[2]; + bool ret = false; + + queue_family_indices[0] = (uint32_t)demo->indices.graphics; + queue_family_indices[1] = (uint32_t)demo->indices.present; + + if (!query_swap_chain_support(demo->physical_device, demo->surface, + &swap_chain_support)) { + goto cleanup; + } + surface_format = choose_swap_surface_format(swap_chain_support.formats, + swap_chain_support.formats_len); + present_mode = choose_swap_present_mode( + swap_chain_support.present_modes, swap_chain_support.present_modes_len); + extent = choose_swap_extent(demo, &swap_chain_support.capabilities); + + demo->swap_chain_images_len = + swap_chain_support.capabilities.minImageCount + 1; + if (swap_chain_support.capabilities.maxImageCount > 0 && + demo->swap_chain_images_len > + swap_chain_support.capabilities.maxImageCount) { + demo->swap_chain_images_len = + swap_chain_support.capabilities.maxImageCount; + } + + memset(&create_info, 0, sizeof(VkSwapchainCreateInfoKHR)); + create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; + create_info.surface = demo->surface; + + create_info.minImageCount = demo->swap_chain_images_len; + create_info.imageFormat = surface_format.format; + create_info.imageColorSpace = surface_format.colorSpace; + create_info.imageExtent = extent; + create_info.imageArrayLayers = 1; + create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + if (demo->indices.graphics != demo->indices.present) { + create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; + create_info.queueFamilyIndexCount = 2; + create_info.pQueueFamilyIndices = queue_family_indices; + } else { + create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; + } + + create_info.preTransform = swap_chain_support.capabilities.currentTransform; + create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; + create_info.presentMode = present_mode; + create_info.clipped = VK_TRUE; + + result = vkCreateSwapchainKHR(demo->device, &create_info, NULL, + &demo->swap_chain); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSwapchainKHR failed: %d\n", result); + goto cleanup; + } + + result = vkGetSwapchainImagesKHR(demo->device, demo->swap_chain, + &demo->swap_chain_images_len, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetSwapchainImagesKHR failed: %d\n", result); + goto cleanup; + } + if (demo->swap_chain_images == NULL) { + demo->swap_chain_images = + malloc(demo->swap_chain_images_len * sizeof(VkImage)); + } + result = vkGetSwapchainImagesKHR(demo->device, demo->swap_chain, + &demo->swap_chain_images_len, + demo->swap_chain_images); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkGetSwapchainImagesKHR failed: %d\n", result); + return false; + } + + demo->swap_chain_image_format = surface_format.format; + demo->swap_chain_image_extent = extent; + + ret = true; +cleanup: + swap_chain_support_details_free(&swap_chain_support); + + return ret; +} + +bool create_swap_chain_image_views(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + VkImageViewCreateInfo create_info; + + memset(&create_info, 0, sizeof(VkImageViewCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + create_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + create_info.format = demo->swap_chain_image_format; + create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + create_info.subresourceRange.baseMipLevel = 0; + create_info.subresourceRange.levelCount = 1; + create_info.subresourceRange.baseArrayLayer = 0; + create_info.subresourceRange.layerCount = 1; + + if (!demo->swap_chain_image_views) { + demo->swap_chain_image_views = + malloc(demo->swap_chain_images_len * sizeof(VkImageView)); + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + create_info.image = demo->swap_chain_images[i]; + result = vkCreateImageView(demo->device, &create_info, NULL, + &demo->swap_chain_image_views[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed: %d\n", result); + return false; + } + } + return true; +} + +bool create_overlay_images(struct vulkan_demo *demo) { + uint32_t i, j; + VkResult result; + VkMemoryRequirements mem_requirements; + VkPhysicalDeviceMemoryProperties mem_properties; + int found; + VkImageCreateInfo image_info; + VkMemoryAllocateInfo alloc_info; + VkImageViewCreateInfo image_view_info; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.extent.width = demo->swap_chain_image_extent.width; + image_info.extent.height = demo->swap_chain_image_extent.height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.format = demo->swap_chain_image_format; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_info.usage = + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = demo->swap_chain_image_format; + image_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.baseMipLevel = 0; + image_view_info.subresourceRange.levelCount = 1; + image_view_info.subresourceRange.baseArrayLayer = 0; + image_view_info.subresourceRange.layerCount = 1; + + if (!demo->overlay_images) { + demo->overlay_images = + malloc(demo->swap_chain_images_len * sizeof(VkImage)); + } + + if (!demo->overlay_image_memories) { + demo->overlay_image_memories = + malloc(demo->swap_chain_images_len * sizeof(VkDeviceMemory)); + } + if (!demo->overlay_image_views) { + demo->overlay_image_views = + malloc(demo->swap_chain_images_len * sizeof(VkImageView)); + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + result = vkCreateImage(demo->device, &image_info, NULL, + &demo->overlay_images[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImage failed for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + + vkGetImageMemoryRequirements(demo->device, demo->overlay_images[i], + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + + vkGetPhysicalDeviceMemoryProperties(demo->physical_device, + &mem_properties); + found = 0; + for (j = 0; j < mem_properties.memoryTypeCount; j++) { + if ((mem_requirements.memoryTypeBits & (1 << j)) && + (mem_properties.memoryTypes[j].propertyFlags & + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, + "failed to find suitable memory type for index %lu!\n", + (unsigned long)i); + return false; + } + alloc_info.memoryTypeIndex = j; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &demo->overlay_image_memories[i]); + if (result != VK_SUCCESS) { + fprintf(stderr, + "failed to allocate vulkan memory for index %lu: %d!\n", + (unsigned long)i, result); + return false; + } + result = vkBindImageMemory(demo->device, demo->overlay_images[i], + demo->overlay_image_memories[i], 0); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't bind image memory for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + + image_view_info.image = demo->overlay_images[i]; + result = vkCreateImageView(demo->device, &image_view_info, NULL, + &demo->overlay_image_views[i]); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed for index %lu: %d\n", + (unsigned long)i, result); + return false; + } + } + return true; +} + +bool create_render_pass(struct vulkan_demo *demo) { + VkAttachmentDescription attachment; + VkAttachmentReference color_attachment_ref; + VkSubpassDescription subpass; + VkSubpassDependency dependency; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = demo->swap_chain_image_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + memset(&color_attachment_ref, 0, sizeof(VkAttachmentReference)); + color_attachment_ref.attachment = 0; + color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass, 0, sizeof(VkSubpassDescription)); + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color_attachment_ref; + + memset(&dependency, 0, sizeof(VkSubpassDependency)); + dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + dependency.dstSubpass = 0; + dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.srcAccessMask = 0; + dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &dependency; + + result = vkCreateRenderPass(demo->device, &render_pass_info, NULL, + &demo->render_pass); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateRenderPass failed: %d\n", result); + return false; + } + return true; +} + +bool create_framebuffers(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + VkFramebufferCreateInfo framebuffer_info; + + if (!demo->framebuffers) { + demo->framebuffers = + malloc(demo->swap_chain_images_len * sizeof(VkFramebuffer)); + } + + memset(&framebuffer_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_info.renderPass = demo->render_pass; + framebuffer_info.attachmentCount = 1; + framebuffer_info.width = demo->swap_chain_image_extent.width; + framebuffer_info.height = demo->swap_chain_image_extent.height; + framebuffer_info.layers = 1; + + for (i = 0; i < demo->swap_chain_images_len; i++) { + framebuffer_info.pAttachments = &demo->swap_chain_image_views[i]; + + result = vkCreateFramebuffer(demo->device, &framebuffer_info, NULL, + &demo->framebuffers[i]); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFramebuffer failed from index %lu: %d\n", + (unsigned long)i, result); + return false; + } + } + return true; +} + +bool create_descriptor_set_layout(struct vulkan_demo *demo) { + VkDescriptorSetLayoutBinding overlay_layout_binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_nfo; + VkResult result; + + memset(&overlay_layout_binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + overlay_layout_binding.binding = 0; + overlay_layout_binding.descriptorCount = 1; + overlay_layout_binding.descriptorType = + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + overlay_layout_binding.pImmutableSamplers = NULL; + overlay_layout_binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_layout_create_nfo, 0, + sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_layout_create_nfo.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_layout_create_nfo.bindingCount = 1; + descriptor_set_layout_create_nfo.pBindings = &overlay_layout_binding; + + result = vkCreateDescriptorSetLayout(demo->device, + &descriptor_set_layout_create_nfo, + NULL, &demo->descriptor_set_layout); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDescriptorSetLayout failed: %d\n", result); + return false; + } + return true; +} + +bool create_descriptor_pool(struct vulkan_demo *demo) { + VkDescriptorPoolSize pool_size; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_size, 0, sizeof(VkDescriptorPoolSize)); + pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_size.descriptorCount = demo->swap_chain_images_len; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 1; + pool_info.pPoolSizes = &pool_size; + pool_info.maxSets = demo->swap_chain_images_len; + result = vkCreateDescriptorPool(demo->device, &pool_info, NULL, + &demo->descriptor_pool); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateDescriptorPool failed: %d\n", result); + return false; + } + return true; +} + +void update_descriptor_sets(struct vulkan_demo *demo) { + uint32_t i; + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + descriptor_image_info.sampler = demo->sampler; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + for (i = 0; i < demo->swap_chain_images_len; i++) { + descriptor_write.dstSet = demo->descriptor_sets[i]; + descriptor_image_info.imageView = demo->overlay_image_views[i]; + + vkUpdateDescriptorSets(demo->device, 1, &descriptor_write, 0, NULL); + } +} + +bool create_descriptor_sets(struct vulkan_demo *demo) { + bool ret = false; + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSetAllocateInfo alloc_info; + uint32_t i; + VkResult result; + + demo->descriptor_sets = + malloc(demo->swap_chain_images_len * sizeof(VkDescriptorSet)); + descriptor_set_layouts = + malloc(demo->swap_chain_images_len * sizeof(VkDescriptorSetLayout)); + + for (i = 0; i < demo->swap_chain_images_len; i++) { + descriptor_set_layouts[i] = demo->descriptor_set_layout; + } + + memset(&alloc_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = demo->descriptor_pool; + alloc_info.descriptorSetCount = demo->swap_chain_images_len; + alloc_info.pSetLayouts = descriptor_set_layouts; + result = vkAllocateDescriptorSets(demo->device, &alloc_info, + demo->descriptor_sets); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkAllocateDescriptorSets failed: %d\n", result); + goto cleanup; + } + + update_descriptor_sets(demo); + + ret = true; +cleanup: + free(descriptor_set_layouts); + + return ret; +} + +bool create_shader_module(VkDevice device, char *shader_buffer, + size_t shader_buffer_len, + VkShaderModule *shader_module) { + VkShaderModuleCreateInfo create_info; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = shader_buffer_len; + create_info.pCode = (const uint32_t *)shader_buffer; + + result = vkCreateShaderModule(device, &create_info, NULL, shader_module); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateShaderModule failed: %d\n", result); + return false; + } + + return true; +} + +bool create_graphics_pipeline(struct vulkan_demo *demo) { + bool ret = false; + char *vert_shader_code = NULL; + char *frag_shader_code = NULL; + VkShaderModule vert_shader_module; + VkShaderModule frag_shader_module; + FILE *fp; + size_t file_len; + VkPipelineShaderStageCreateInfo vert_shader_stage_info; + VkPipelineShaderStageCreateInfo frag_shader_stage_info; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkPipelineVertexInputStateCreateInfo vertex_input_info; + VkPipelineInputAssemblyStateCreateInfo input_assembly; + VkViewport viewport; + VkRect2D scissor; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineRasterizationStateCreateInfo rasterizer; + VkPipelineMultisampleStateCreateInfo multisampling; + VkPipelineColorBlendAttachmentState color_blend_attachment; + VkPipelineColorBlendStateCreateInfo color_blending; + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkResult result; + VkGraphicsPipelineCreateInfo pipeline_info; + + fp = fopen("shaders/demo.vert.spv", "r"); + if (!fp) { + fprintf(stderr, "Couldn't open shaders/demo.vert.spv\n"); + return false; + } + fseek(fp, 0, SEEK_END); + file_len = ftell(fp); + vert_shader_code = malloc(file_len); + fseek(fp, 0, 0); + fread(vert_shader_code, 1, file_len, fp); + fclose(fp); + + if (!create_shader_module(demo->device, vert_shader_code, file_len, + &vert_shader_module)) { + goto cleanup; + } + + fp = fopen("shaders/demo.frag.spv", "r"); + if (!fp) { + fprintf(stderr, "Couldn't open shaders/demo.frag.spv\n"); + return false; + } + fseek(fp, 0, SEEK_END); + file_len = ftell(fp); + frag_shader_code = malloc(file_len); + fseek(fp, 0, 0); + fread(frag_shader_code, 1, file_len, fp); + fclose(fp); + + if (!create_shader_module(demo->device, frag_shader_code, file_len, + &frag_shader_module)) { + goto cleanup; + } + + memset(&vert_shader_stage_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + vert_shader_stage_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + vert_shader_stage_info.stage = VK_SHADER_STAGE_VERTEX_BIT; + vert_shader_stage_info.module = vert_shader_module; + vert_shader_stage_info.pName = "main"; + + memset(&frag_shader_stage_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + frag_shader_stage_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + frag_shader_stage_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; + frag_shader_stage_info.module = frag_shader_module; + frag_shader_stage_info.pName = "main"; + + shader_stages[0] = vert_shader_stage_info; + shader_stages[1] = frag_shader_stage_info; + + memset(&vertex_input_info, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input_info.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + + memset(&input_assembly, 0, sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly.primitiveRestartEnable = VK_FALSE; + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.x = 0.0f; + viewport.y = 0.0f; + viewport.width = (float)demo->swap_chain_image_extent.width; + viewport.height = (float)demo->swap_chain_image_extent.height; + viewport.minDepth = 0.0f; + viewport.maxDepth = 1.0f; + + memset(&scissor, 0, sizeof(VkRect2D)); + scissor.extent.width = demo->swap_chain_image_extent.width; + scissor.extent.height = demo->swap_chain_image_extent.height; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.pViewports = &viewport; + viewport_state.scissorCount = 1; + viewport_state.pScissors = &scissor; + + memset(&rasterizer, 0, sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterizer.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterizer.depthClampEnable = VK_FALSE; + rasterizer.rasterizerDiscardEnable = VK_FALSE; + rasterizer.polygonMode = VK_POLYGON_MODE_FILL; + rasterizer.lineWidth = 1.0f; + rasterizer.cullMode = VK_CULL_MODE_FRONT_BIT; + rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterizer.depthBiasEnable = VK_FALSE; + + memset(&multisampling, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisampling.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisampling.sampleShadingEnable = VK_FALSE; + multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&color_blend_attachment, 0, + sizeof(VkPipelineColorBlendAttachmentState)); + color_blend_attachment.colorWriteMask = + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + color_blend_attachment.blendEnable = VK_TRUE; + color_blend_attachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; + color_blend_attachment.dstColorBlendFactor = + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + color_blend_attachment.colorBlendOp = VK_BLEND_OP_ADD; + color_blend_attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + color_blend_attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + color_blend_attachment.alphaBlendOp = VK_BLEND_OP_ADD; + + memset(&color_blending, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blending.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blending.logicOpEnable = VK_FALSE; + color_blending.logicOp = VK_LOGIC_OP_COPY; + color_blending.attachmentCount = 1; + color_blending.pAttachments = &color_blend_attachment; + color_blending.blendConstants[0] = 1.0f; + color_blending.blendConstants[1] = 1.0f; + color_blending.blendConstants[2] = 1.0f; + color_blending.blendConstants[3] = 1.0f; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 0; + pipeline_layout_info.pushConstantRangeCount = 0; + pipeline_layout_info.setLayoutCount = 1; + pipeline_layout_info.pSetLayouts = &demo->descriptor_set_layout; + + result = vkCreatePipelineLayout(demo->device, &pipeline_layout_info, NULL, + &demo->pipeline_layout); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreatePipelineLayout failed: %d\n", result); + goto cleanup; + } + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input_info; + pipeline_info.pInputAssemblyState = &input_assembly; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterizer; + pipeline_info.pMultisampleState = &multisampling; + pipeline_info.pColorBlendState = &color_blending; + pipeline_info.layout = demo->pipeline_layout; + pipeline_info.renderPass = demo->render_pass; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(demo->device, NULL, 1, &pipeline_info, + NULL, &demo->pipeline); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateGraphicsPipelines failed: %d\n", result); + goto cleanup; + } + ret = true; +cleanup: + if (frag_shader_module) { + vkDestroyShaderModule(demo->device, frag_shader_module, NULL); + } + if (frag_shader_code) { + free(frag_shader_code); + } + if (vert_shader_module) { + vkDestroyShaderModule(demo->device, vert_shader_module, NULL); + } + if (vert_shader_code) { + free(vert_shader_code); + } + + return ret; +} + +bool create_command_pool(struct vulkan_demo *demo) { + VkCommandPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = demo->indices.graphics; + + result = vkCreateCommandPool(demo->device, &pool_info, NULL, + &demo->command_pool); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateCommandPool failed: %d\n", result); + return false; + } + return true; +} + +bool create_command_buffers(struct vulkan_demo *demo) { + VkCommandBufferAllocateInfo alloc_info; + VkResult result; + + demo->command_buffers = + malloc(demo->swap_chain_images_len * sizeof(VkCommandBuffer)); + + memset(&alloc_info, 0, sizeof(VkCommandBufferAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + alloc_info.commandPool = demo->command_pool; + alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc_info.commandBufferCount = demo->swap_chain_images_len; + + result = vkAllocateCommandBuffers(demo->device, &alloc_info, + demo->command_buffers); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkAllocateCommandBuffers failed: %d\n", result); + return false; + } + + return true; +} + +bool create_semaphores(struct vulkan_demo *demo) { + VkSemaphoreCreateInfo semaphore_info; + VkResult result; + + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = vkCreateSemaphore(demo->device, &semaphore_info, NULL, + &demo->image_available); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSemaphore failed: %d\n", result); + return false; + } + result = vkCreateSemaphore(demo->device, &semaphore_info, NULL, + &demo->render_finished); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateSemaphore failed: %d\n", result); + return false; + } + return true; +} + +bool create_fence(struct vulkan_demo *demo) { + VkResult result; + VkFenceCreateInfo fence_create_info; + + memset(&fence_create_info, 0, sizeof(VkFenceCreateInfo)); + fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + fence_create_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; + + result = vkCreateFence(demo->device, &fence_create_info, NULL, + &demo->render_fence); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFence failed: %d\n", result); + return false; + } + return true; +} + +bool create_swap_chain_related_resources(struct vulkan_demo *demo) { + if (!create_swap_chain(demo)) { + return false; + } + if (!create_swap_chain_image_views(demo)) { + return false; + } + if (!create_overlay_images(demo)) { + return false; + } + if (!create_render_pass(demo)) { + return false; + } + if (!create_framebuffers(demo)) { + return false; + } + if (!create_graphics_pipeline(demo)) { + return false; + } + return true; +} + +bool destroy_swap_chain_related_resources(struct vulkan_demo *demo) { + uint32_t i; + VkResult result; + + result = vkQueueWaitIdle(demo->graphics_queue); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueWaitIdle failed: %d\n", result); + return false; + } + + for (i = 0; i < demo->swap_chain_images_len; i++) { + vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL); + vkDestroyImageView(demo->device, demo->overlay_image_views[i], NULL); + vkDestroyImage(demo->device, demo->overlay_images[i], NULL); + vkFreeMemory(demo->device, demo->overlay_image_memories[i], NULL); + vkDestroyImageView(demo->device, demo->swap_chain_image_views[i], NULL); + } + vkDestroySwapchainKHR(demo->device, demo->swap_chain, NULL); + vkDestroyRenderPass(demo->device, demo->render_pass, NULL); + vkDestroyPipeline(demo->device, demo->pipeline, NULL); + vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL); + return true; +} + +bool create_demo_texture(struct vulkan_demo *demo) { + VkResult result; + VkMemoryRequirements mem_requirements; + VkPhysicalDeviceMemoryProperties mem_properties; + int found; + uint32_t i; + VkImageCreateInfo image_info; + VkMemoryAllocateInfo alloc_info; + VkImageViewCreateInfo image_view_info; + VkBufferCreateInfo buffer_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + void *data; + VkCommandBuffer command_buffer; + VkCommandBufferBeginInfo begin_info; + VkImageMemoryBarrier image_transfer_dst_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.extent.width = 2; + image_info.extent.height = 2; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.format = VK_FORMAT_R8_UNORM; + image_info.tiling = VK_IMAGE_TILING_LINEAR; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = VK_FORMAT_R8_UNORM; + image_view_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.baseMipLevel = 0; + image_view_info.subresourceRange.levelCount = 1; + image_view_info.subresourceRange.baseArrayLayer = 0; + image_view_info.subresourceRange.layerCount = 1; + + result = vkCreateImage(demo->device, &image_info, NULL, + &demo->demo_texture_image); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImage failed: %d\n", result); + return false; + } + + vkGetImageMemoryRequirements(demo->device, demo->demo_texture_image, + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + + vkGetPhysicalDeviceMemoryProperties(demo->physical_device, &mem_properties); + found = 0; + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((mem_requirements.memoryTypeBits & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, "failed to find suitable memory for demo texture!\n"); + return false; + } + alloc_info.memoryTypeIndex = i; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &demo->demo_texture_memory); + if (result != VK_SUCCESS) { + fprintf(stderr, + "failed to allocate vulkan memory for demo texture: %d!\n", + result); + return false; + } + result = vkBindImageMemory(demo->device, demo->demo_texture_image, + demo->demo_texture_memory, 0); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't bind image memory for demo texture: %d\n", + result); + return false; + } + + image_view_info.image = demo->demo_texture_image; + result = vkCreateImageView(demo->device, &image_view_info, NULL, + &demo->demo_texture_image_view); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateImageView failed for demo texture: %d\n", + result); + return false; + } + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(demo->device, &buffer_info, NULL, + &staging_buffer.buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateBuffer failed for demo texture: %d\n", result); + return false; + } + vkGetBufferMemoryRequirements(demo->device, staging_buffer.buffer, + &mem_requirements); + + alloc_info.allocationSize = mem_requirements.size; + found = 0; + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((mem_requirements.memoryTypeBits & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & + (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == + (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) { + found = 1; + break; + } + } + if (!found) { + fprintf(stderr, "failed to find suitable staging buffer memory for " + "demo texture!\n"); + return false; + } + alloc_info.memoryTypeIndex = i; + result = vkAllocateMemory(demo->device, &alloc_info, NULL, + &staging_buffer.memory); + if (!found) { + fprintf(stderr, "vkAllocateMemory failed for demo texture: %d\n", + result); + return false; + } + result = vkBindBufferMemory(demo->device, staging_buffer.buffer, + staging_buffer.memory, 0); + if (!found) { + fprintf(stderr, "vkBindBufferMemory failed for demo texture: %d\n", + result); + return false; + } + + result = vkMapMemory(demo->device, staging_buffer.memory, 0, + sizeof(uint32_t), 0, &data); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkMapMemory failed for demo texture: %d\n", result); + return false; + } + *((uint32_t *)data) = 0x00FFFF00; + vkUnmapMemory(demo->device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + command_buffer = demo->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + + memset(&image_transfer_dst_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_transfer_dst_memory_barrier.sType = + VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_transfer_dst_memory_barrier.image = demo->demo_texture_image; + image_transfer_dst_memory_barrier.srcQueueFamilyIndex = + VK_QUEUE_FAMILY_IGNORED; + image_transfer_dst_memory_barrier.dstQueueFamilyIndex = + VK_QUEUE_FAMILY_IGNORED; + image_transfer_dst_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_transfer_dst_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_transfer_dst_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_transfer_dst_memory_barrier.subresourceRange.levelCount = 1; + image_transfer_dst_memory_barrier.subresourceRange.layerCount = 1; + image_transfer_dst_memory_barrier.dstAccessMask = + VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_transfer_dst_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = 2; + buffer_copy_region.imageExtent.height = 2; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, demo->demo_texture_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = demo->demo_texture_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEndCommandBuffer failed for demo texture: %d\n", + result); + return false; + } + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + result = vkCreateFence(demo->device, &fence_create, NULL, &fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkCreateFence failed for demo texture: %d\n", result); + return false; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueSubmit failed for demo texture: %d\n", result); + return false; + } + result = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkWaitForFences failed for demo texture: %d\n", + result); + return false; + } + + vkDestroyBuffer(demo->device, staging_buffer.buffer, NULL); + vkFreeMemory(demo->device, staging_buffer.memory, NULL); + vkDestroyFence(demo->device, fence, NULL); + + return true; +} + +bool create_vulkan_demo(struct vulkan_demo *demo) { + if (!create_instance(demo)) { + return false; + } + if (!create_surface(demo)) { + return false; + } + if (!create_physical_device(demo)) { + return false; + } + if (!create_logical_device(demo)) { + return false; + } + if (!create_sampler(demo)) { + return false; + } + if (!create_descriptor_set_layout(demo)) { + return false; + } + if (!create_swap_chain_related_resources(demo)) { + return false; + } + if (!create_descriptor_pool(demo)) { + return false; + } + if (!create_descriptor_sets(demo)) { + return false; + } + if (!create_command_pool(demo)) { + return false; + } + if (!create_command_buffers(demo)) { + return false; + } + if (!create_semaphores(demo)) { + return false; + } + if (!create_fence(demo)) { + return false; + } + if (!create_demo_texture(demo)) { + return false; + } + + return true; +} + +bool recreate_swap_chain(struct vulkan_demo *demo) { + printf("recreating swapchain\n"); + if (!destroy_swap_chain_related_resources(demo)) { + return false; + } + if (!create_swap_chain_related_resources(demo)) { + return false; + } + update_descriptor_sets(demo); + nk_glfw3_resize(demo->swap_chain_image_extent.width, + demo->swap_chain_image_extent.height); + return true; +} + +bool render(struct vulkan_demo *demo, struct nk_colorf *bg, + VkSemaphore wait_semaphore, uint32_t image_index) { + VkCommandBufferBeginInfo command_buffer_begin_info; + VkCommandBuffer command_buffer; + VkRenderPassBeginInfo render_pass_info; + VkSubmitInfo submit_info; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkResult result; + VkPresentInfoKHR present_info; + VkClearValue clear_color; + + memcpy(&clear_color.color, bg, sizeof(VkClearColorValue)); + + memset(&command_buffer_begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + command_buffer_begin_info.sType = + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + command_buffer = demo->command_buffers[image_index]; + result = vkBeginCommandBuffer(command_buffer, &command_buffer_begin_info); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkBeginCommandBuffer failed: %d\n", result); + return false; + } + + memset(&render_pass_info, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_info.renderPass = demo->render_pass; + render_pass_info.framebuffer = demo->framebuffers[image_index]; + render_pass_info.renderArea.offset.x = 0; + render_pass_info.renderArea.offset.y = 0; + render_pass_info.renderArea.extent = demo->swap_chain_image_extent; + render_pass_info.clearValueCount = 1; + render_pass_info.pClearValues = &clear_color; + + vkCmdBeginRenderPass(command_buffer, &render_pass_info, + VK_SUBPASS_CONTENTS_INLINE); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + demo->pipeline_layout, 0, 1, + &demo->descriptor_sets[image_index], 0, NULL); + vkCmdDraw(command_buffer, 3, 1, 0, 0); + + vkCmdEndRenderPass(command_buffer); + + result = vkEndCommandBuffer(command_buffer); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkEndCommandBuffer failed: %d\n", result); + return false; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.waitSemaphoreCount = 1; + submit_info.pWaitSemaphores = &wait_semaphore; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &demo->command_buffers[image_index]; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &demo->render_finished; + + result = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, + demo->render_fence); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueueSubmit failed: %d\n", result); + return false; + } + + memset(&present_info, 0, sizeof(VkPresentInfoKHR)); + present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; + present_info.waitSemaphoreCount = 1; + present_info.pWaitSemaphores = &demo->render_finished; + present_info.swapchainCount = 1; + present_info.pSwapchains = &demo->swap_chain; + present_info.pImageIndices = &image_index; + + result = vkQueuePresentKHR(demo->present_queue, &present_info); + + if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { + recreate_swap_chain(demo); + } else if (result != VK_SUCCESS) { + fprintf(stderr, "vkQueuePresentKHR failed: %d\n", result); + return false; + } + return true; +} + +VkResult +destroy_debug_utils_messenger_ext(VkInstance instance, + VkDebugUtilsMessengerEXT debugMessenger, + const VkAllocationCallbacks *pAllocator) { + PFN_vkDestroyDebugUtilsMessengerEXT func = + (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr( + instance, "vkDestroyDebugUtilsMessengerEXT"); + if (func != NULL) { + func(instance, debugMessenger, pAllocator); + return VK_SUCCESS; + } else { + return VK_ERROR_EXTENSION_NOT_PRESENT; + } +} + +bool cleanup(struct vulkan_demo *demo) { + VkResult result; + + printf("cleaning up\n"); + result = vkDeviceWaitIdle(demo->device); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkDeviceWaitIdle failed: %d\n", result); + return false; + } + + destroy_swap_chain_related_resources(demo); + + vkFreeCommandBuffers(demo->device, demo->command_pool, + demo->swap_chain_images_len, demo->command_buffers); + vkDestroyCommandPool(demo->device, demo->command_pool, NULL); + vkDestroySampler(demo->device, demo->sampler, NULL); + vkDestroySemaphore(demo->device, demo->render_finished, NULL); + vkDestroySemaphore(demo->device, demo->image_available, NULL); + vkDestroyFence(demo->device, demo->render_fence, NULL); + + vkDestroyImage(demo->device, demo->demo_texture_image, NULL); + vkDestroyImageView(demo->device, demo->demo_texture_image_view, NULL); + vkFreeMemory(demo->device, demo->demo_texture_memory, NULL); + + vkDestroyDescriptorSetLayout(demo->device, demo->descriptor_set_layout, + NULL); + vkDestroyDescriptorPool(demo->device, demo->descriptor_pool, NULL); + + vkDestroyDevice(demo->device, NULL); + vkDestroySurfaceKHR(demo->instance, demo->surface, NULL); + + if (demo->debug_messenger) { + result = destroy_debug_utils_messenger_ext(demo->instance, + demo->debug_messenger, NULL); + if (result != VK_SUCCESS) { + fprintf(stderr, "Couldn't destroy debug messenger: %d\n", result); + return false; + } + } + vkDestroyInstance(demo->instance, NULL); + if (demo->swap_chain_images) { + free(demo->swap_chain_images); + } + if (demo->swap_chain_image_views) { + free(demo->swap_chain_image_views); + } + + if (demo->overlay_images) { + free(demo->overlay_images); + } + if (demo->overlay_image_views) { + free(demo->overlay_image_views); + } + if (demo->overlay_image_memories) { + free(demo->overlay_image_memories); + } + + if (demo->descriptor_sets) { + free(demo->descriptor_sets); + } + if (demo->framebuffers) { + free(demo->framebuffers); + } + if (demo->command_buffers) { + free(demo->command_buffers); + } + + return true; +} + +int main(void) { + struct vulkan_demo demo; + struct nk_context *ctx; + struct nk_colorf bg; + struct nk_image img; + uint32_t image_index; + VkResult result; + VkSemaphore nk_semaphore; + + glfwSetErrorCallback(glfw_error_callback); + if (!glfwInit()) { + fprintf(stderr, "[GFLW] failed to init!\n"); + exit(1); + } + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + memset(&demo, 0, sizeof(struct vulkan_demo)); + demo.win = + glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL); + + if (!create_vulkan_demo(&demo)) { + fprintf(stderr, "failed to create vulkan demo!\n"); + exit(1); + } + 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); + /* Load Fonts: if none of these are loaded a default font will be used */ + /* Load Cursor: if you uncomment cursor loading please hide the cursor */ + { + struct nk_font_atlas *atlas; + nk_glfw3_font_stash_begin(&atlas); + /*struct nk_font *droid = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/DroidSans.ttf", 14, 0);*/ + /*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/ + /*struct nk_font *future = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/ + /*struct nk_font *clean = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/ProggyClean.ttf", 12, 0);*/ + /*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/ProggyTiny.ttf", 10, 0);*/ + /*struct nk_font *cousine = nk_font_atlas_add_from_file(atlas, + * "../../../extra_font/Cousine-Regular.ttf", 13, 0);*/ + nk_glfw3_font_stash_end(demo.graphics_queue); + /*nk_style_load_all_cursors(ctx, atlas->cursors);*/ + /*nk_style_set_font(ctx, &droid->handle);*/} + +#ifdef INCLUDE_STYLE + /* ease regression testing during Nuklear release process; not needed for + * anything else */ +#ifdef STYLE_WHITE + set_style(ctx, THEME_WHITE); +#elif defined(STYLE_RED) + set_style(ctx, THEME_RED); +#elif defined(STYLE_BLUE) + set_style(ctx, THEME_BLUE); +#elif defined(STYLE_DARK) + set_style(ctx, THEME_DARK); +#endif +#endif + + img = nk_image_ptr(demo.demo_texture_image_view); + bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f; + while (!glfwWindowShouldClose(demo.win)) { + /* Input */ + glfwPollEvents(); + nk_glfw3_new_frame(); + + /* GUI */ + if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), + NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | + 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, 25, 1); + nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); + + nk_layout_row_dynamic(ctx, 20, 1); + nk_label(ctx, "background:", NK_TEXT_LEFT); + nk_layout_row_dynamic(ctx, 25, 1); + if (nk_combo_begin_color(ctx, nk_rgb_cf(bg), + nk_vec2(nk_widget_width(ctx), 400))) { + nk_layout_row_dynamic(ctx, 120, 1); + bg = nk_color_picker(ctx, bg, NK_RGBA); + nk_layout_row_dynamic(ctx, 25, 1); + bg.r = nk_propertyf(ctx, "#R:", 0, bg.r, 1.0f, 0.01f, 0.005f); + bg.g = nk_propertyf(ctx, "#G:", 0, bg.g, 1.0f, 0.01f, 0.005f); + bg.b = nk_propertyf(ctx, "#B:", 0, bg.b, 1.0f, 0.01f, 0.005f); + bg.a = nk_propertyf(ctx, "#A:", 0, bg.a, 1.0f, 0.01f, 0.005f); + nk_combo_end(ctx); + } + } + nk_end(ctx); + + /* Bindless Texture */ + if (nk_begin(ctx, "Texture", nk_rect(500, 300, 200, 200), + NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE | + NK_WINDOW_MINIMIZABLE | NK_WINDOW_TITLE)) { + struct nk_command_buffer *canvas = nk_window_get_canvas(ctx); + struct nk_rect total_space = nk_window_get_content_region(ctx); + nk_draw_image(canvas, total_space, &img, nk_white); + } + nk_end(ctx); + + /* -------------- EXAMPLES ---------------- */ +#ifdef INCLUDE_CALCULATOR + calculator(ctx); +#endif +#ifdef INCLUDE_CANVAS + canvas(ctx); +#endif +#ifdef INCLUDE_OVERVIEW + overview(ctx); +#endif +#ifdef INCLUDE_NODE_EDITOR + node_editor(ctx); +#endif + /* ----------------------------------------- */ + + result = vkWaitForFences(demo.device, 1, &demo.render_fence, VK_TRUE, + UINT64_MAX); + + if (result != VK_SUCCESS) { + fprintf(stderr, "vkWaitForFences failed: %d\n", result); + return false; + } + + result = vkResetFences(demo.device, 1, &demo.render_fence); + if (result != VK_SUCCESS) { + fprintf(stderr, "vkResetFences failed: %d\n", result); + return false; + } + + result = + vkAcquireNextImageKHR(demo.device, demo.swap_chain, UINT64_MAX, + demo.image_available, NULL, &image_index); + + if (result == VK_ERROR_OUT_OF_DATE_KHR) { + continue; + } + if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { + fprintf(stderr, "vkAcquireNextImageKHR failed: %d\n", result); + return false; + } + + /* Draw */ + nk_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; + } + } + nk_glfw3_shutdown(); + cleanup(&demo); + glfwTerminate(); + return 0; +} diff --git a/demo/glfw_vulkan/nuklear_glfw_vulkan.h b/demo/glfw_vulkan/nuklear_glfw_vulkan.h new file mode 100644 index 0000000..3c1e358 --- /dev/null +++ b/demo/glfw_vulkan/nuklear_glfw_vulkan.h @@ -0,0 +1,1649 @@ +/* + * Nuklear - 1.32.0 - public domain + * no warrenty implied; use at your own risk. + * authored from 2015-2016 by Micha Mettke + */ +/* + * ============================================================== + * + * API + * + * =============================================================== + */ +#ifndef NK_GLFW_VULKAN_H_ +#define NK_GLFW_VULKAN_H_ + +unsigned char nuklearshaders_nuklear_vert_spv[] = { + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x0d, 0x00, + 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, + 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x2a, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, + 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, + 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, + 0x04, 0x00, 0x0a, 0x00, 0x47, 0x4c, 0x5f, 0x47, 0x4f, 0x4f, 0x47, 0x4c, + 0x45, 0x5f, 0x63, 0x70, 0x70, 0x5f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x5f, + 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x47, 0x4c, 0x5f, 0x47, + 0x4f, 0x4f, 0x47, 0x4c, 0x45, 0x5f, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, + 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x67, 0x6c, 0x5f, 0x50, 0x65, 0x72, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, + 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x00, 0x05, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x55, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x75, 0x66, 0x66, 0x65, + 0x72, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x00, 0x06, 0x00, 0x06, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x72, 0x6f, 0x6a, + 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x75, 0x62, 0x6f, 0x00, 0x05, 0x00, 0x05, 0x00, + 0x16, 0x00, 0x00, 0x00, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x66, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6c, 0x6f, + 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x42, 0x00, 0x00, 0x00, + 0x66, 0x72, 0x61, 0x67, 0x55, 0x76, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, + 0x43, 0x00, 0x00, 0x00, 0x75, 0x76, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x48, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x16, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x2a, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x42, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x43, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x15, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00, + 0x0d, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x11, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x20, 0x00, 0x04, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x15, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x22, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x28, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x29, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x29, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x7f, 0x43, 0x2b, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x36, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, + 0x20, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x41, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x41, 0x00, 0x00, 0x00, + 0x42, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x12, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, + 0x12, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x1b, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, + 0x1a, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x19, 0x00, 0x00, 0x00, 0x91, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x1d, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, + 0x41, 0x00, 0x05, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x1f, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, + 0x22, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, + 0x7f, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, + 0x24, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x22, 0x00, 0x00, 0x00, + 0x26, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x26, 0x00, 0x00, 0x00, + 0x25, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x2d, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, + 0x2d, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x2f, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x34, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x37, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, + 0x37, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x39, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x2c, 0x00, 0x00, 0x00, + 0x3c, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, + 0x3c, 0x00, 0x00, 0x00, 0x70, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, + 0x30, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x40, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, + 0x3a, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x27, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x43, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x03, 0x00, 0x42, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, + 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 +}; +unsigned int nuklearshaders_nuklear_vert_spv_len = 1856; +unsigned char nuklearshaders_nuklear_frag_spv[] = { + 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x0d, 0x00, + 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, + 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, + 0x11, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, + 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, + 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, + 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, + 0x04, 0x00, 0x0a, 0x00, 0x47, 0x4c, 0x5f, 0x47, 0x4f, 0x4f, 0x47, 0x4c, + 0x45, 0x5f, 0x63, 0x70, 0x70, 0x5f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x5f, + 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x47, 0x4c, 0x5f, 0x47, + 0x4f, 0x4f, 0x47, 0x4c, 0x45, 0x5f, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, + 0x65, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x06, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x63, 0x75, 0x72, 0x72, + 0x65, 0x6e, 0x74, 0x54, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x00, 0x00, + 0x05, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, + 0x55, 0x76, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x15, 0x00, 0x00, 0x00, + 0x6f, 0x75, 0x74, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, + 0x05, 0x00, 0x05, 0x00, 0x17, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, + 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x0d, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, + 0x15, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x47, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, + 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, + 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, + 0x0b, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, + 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, + 0x20, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, + 0x17, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, + 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, + 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x0f, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, + 0x0e, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, + 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x09, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, + 0x1a, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x3e, 0x00, 0x03, 0x00, 0x15, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, + 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 +}; +unsigned int nuklearshaders_nuklear_frag_spv_len = 860; + +#include +#include +#include +#define GLFW_INCLUDE_VULKAN +#include + +enum nk_glfw_init_state { NK_GLFW3_DEFAULT = 0, NK_GLFW3_INSTALL_CALLBACKS }; + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer); +NK_API void nk_glfw3_shutdown(void); +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas); +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue); +NK_API void nk_glfw3_new_frame(); +NK_API VkSemaphore nk_glfw3_render(VkQueue graphics_queue, + uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA); +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height); +NK_API void nk_glfw3_device_destroy(void); +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height); + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint); +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff); +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, + int action, int mods); + +#endif +/* + * ============================================================== + * + * IMPLEMENTATION + * + * =============================================================== + */ +#ifdef NK_GLFW_VULKAN_IMPLEMENTATION +#undef NK_GLFW_VULKAN_IMPLEMENTATION +#include + +#ifndef NK_GLFW_TEXT_MAX +#define NK_GLFW_TEXT_MAX 256 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_LO +#define NK_GLFW_DOUBLE_CLICK_LO 0.02 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_HI +#define NK_GLFW_DOUBLE_CLICK_HI 0.2 +#endif +#ifndef NK_GLFW_MAX_TEXTURES +#define NK_GLFW_MAX_TEXTURES 256 +#endif + +#define VK_COLOR_COMPONENT_MASK_RGBA \ + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | \ + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT + +struct nk_glfw_vertex { + float position[2]; + float uv[2]; + nk_byte col[4]; +}; + +struct nk_vulkan_texture_descriptor_set { + VkImageView image_view; + VkDescriptorSet descriptor_set; +}; + +struct nk_glfw_device { + struct nk_buffer cmds; + struct nk_draw_null_texture tex_null; + int max_vertex_buffer; + int max_element_buffer; + VkDevice logical_device; + VkPhysicalDevice physical_device; + VkImageView *image_views; + uint32_t image_views_len; + VkFormat color_format; + VkFramebuffer *framebuffers; + uint32_t framebuffers_len; + VkCommandBuffer *command_buffers; + uint32_t command_buffers_len; + VkSampler sampler; + VkCommandPool command_pool; + VkSemaphore render_completed; + VkBuffer vertex_buffer; + VkDeviceMemory vertex_memory; + void *mapped_vertex; + VkBuffer index_buffer; + VkDeviceMemory index_memory; + void *mapped_index; + VkBuffer uniform_buffer; + VkDeviceMemory uniform_memory; + void *mapped_uniform; + VkRenderPass render_pass; + VkDescriptorPool descriptor_pool; + VkDescriptorSetLayout uniform_descriptor_set_layout; + VkDescriptorSet uniform_descriptor_set; + VkDescriptorSetLayout texture_descriptor_set_layout; + struct nk_vulkan_texture_descriptor_set *texture_descriptor_sets; + uint32_t texture_descriptor_sets_len; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkImage font_image; + VkImageView font_image_view; + VkDeviceMemory font_memory; +}; + +static struct nk_glfw { + GLFWwindow *win; + int width, height; + int display_width, display_height; + struct nk_glfw_device vulkan; + struct nk_context ctx; + struct nk_font_atlas atlas; + struct nk_vec2 fb_scale; + unsigned int text[NK_GLFW_TEXT_MAX]; + int text_len; + struct nk_vec2 scroll; + double last_button_click; + int is_double_click_down; + struct nk_vec2 double_click_pos; +} glfw; + +struct Mat4f { + float m[16]; +}; + +NK_INTERN uint32_t nk_glfw3_find_memory_index( + VkPhysicalDevice physical_device, uint32_t type_filter, + VkMemoryPropertyFlags properties) { + VkPhysicalDeviceMemoryProperties mem_properties; + uint32_t i; + + vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_properties); + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((type_filter & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & properties) == + properties) { + return i; + } + } + + assert(0); + return 0; +} + +NK_INTERN void nk_glfw3_create_sampler(struct nk_glfw_device *dev) { + VkResult result; + VkSamplerCreateInfo sampler_info; + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(dev->logical_device, &sampler_info, NULL, + &dev->sampler); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_command_pool(struct nk_glfw_device *dev, + uint32_t graphics_queue_family_index) { + VkResult result; + VkCommandPoolCreateInfo pool_info; + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = graphics_queue_family_index; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + result = vkCreateCommandPool(dev->logical_device, &pool_info, NULL, + &dev->command_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_command_buffers(struct nk_glfw_device *dev) { + VkResult result; + VkCommandBufferAllocateInfo allocate_info; + memset(&allocate_info, 0, sizeof(VkCommandBufferAllocateInfo)); + + dev->command_buffers = (VkCommandBuffer *)malloc(dev->image_views_len * + sizeof(VkCommandBuffer)); + dev->command_buffers_len = dev->image_views_len; + + allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocate_info.commandPool = dev->command_pool; + allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate_info.commandBufferCount = dev->command_buffers_len; + + result = vkAllocateCommandBuffers(dev->logical_device, &allocate_info, + dev->command_buffers); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_semaphore(struct nk_glfw_device *dev) { + VkResult result; + VkSemaphoreCreateInfo semaphore_info; + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = (vkCreateSemaphore(dev->logical_device, &semaphore_info, NULL, + &dev->render_completed)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_buffer_and_memory(struct nk_glfw_device *dev, + VkBuffer *buffer, + VkBufferUsageFlags usage, + VkDeviceMemory *memory, + VkDeviceSize size) { + VkMemoryRequirements mem_reqs; + VkResult result; + VkBufferCreateInfo buffer_info; + VkMemoryAllocateInfo alloc_info; + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = size; + buffer_info.usage = usage; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, buffer); + NK_ASSERT(result == VK_SUCCESS); + + vkGetBufferMemoryRequirements(dev->logical_device, *buffer, &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, *buffer, *memory, 0); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_render_pass(struct nk_glfw_device *dev) { + VkAttachmentDescription attachment; + VkAttachmentReference color_reference; + VkSubpassDependency subpass_dependency; + VkSubpassDescription subpass_description; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = dev->color_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&color_reference, 0, sizeof(VkAttachmentReference)); + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass_dependency, 0, sizeof(VkSubpassDependency)); + subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + subpass_dependency.srcAccessMask = 0; + subpass_dependency.srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpass_dependency.dstSubpass = 0; + subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + subpass_dependency.dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + + memset(&subpass_description, 0, sizeof(VkSubpassDescription)); + subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass_description.colorAttachmentCount = 1; + subpass_description.pColorAttachments = &color_reference; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass_description; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &subpass_dependency; + + result = vkCreateRenderPass(dev->logical_device, &render_pass_info, NULL, + &dev->render_pass); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_framebuffers(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + + VkFramebufferCreateInfo framebuffer_create_info; + uint32_t i; + VkResult result; + + dev->framebuffers = + (VkFramebuffer *)malloc(dev->image_views_len * sizeof(VkFramebuffer)); + + memset(&framebuffer_create_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_create_info.renderPass = dev->render_pass; + framebuffer_create_info.attachmentCount = 1; + framebuffer_create_info.width = framebuffer_width; + framebuffer_create_info.height = framebuffer_height; + framebuffer_create_info.layers = 1; + for (i = 0; i < dev->image_views_len; i++) { + framebuffer_create_info.pAttachments = &dev->image_views[i]; + result = + vkCreateFramebuffer(dev->logical_device, &framebuffer_create_info, + NULL, &dev->framebuffers[i]); + NK_ASSERT(result == VK_SUCCESS); + } + dev->framebuffers_len = dev->image_views_len; +} + +NK_INTERN void nk_glfw3_create_descriptor_pool(struct nk_glfw_device *dev) { + VkDescriptorPoolSize pool_sizes[2]; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_sizes, 0, sizeof(VkDescriptorPoolSize) * 2); + pool_sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + pool_sizes[0].descriptorCount = 1; + pool_sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_sizes[1].descriptorCount = NK_GLFW_MAX_TEXTURES; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 2; + pool_info.pPoolSizes = pool_sizes; + pool_info.maxSets = 1 + NK_GLFW_MAX_TEXTURES; + + result = vkCreateDescriptorPool(dev->logical_device, &pool_info, NULL, + &dev->descriptor_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_uniform_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->uniform_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_and_update_uniform_descriptor_set(struct nk_glfw_device *dev) { + VkDescriptorSetAllocateInfo allocate_info; + VkDescriptorBufferInfo buffer_info; + VkWriteDescriptorSet descriptor_write; + VkResult result; + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = 1; + allocate_info.pSetLayouts = &dev->uniform_descriptor_set_layout; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + &dev->uniform_descriptor_set); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkDescriptorBufferInfo)); + buffer_info.buffer = dev->uniform_buffer; + buffer_info.offset = 0; + buffer_info.range = sizeof(struct Mat4f); + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = dev->uniform_descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptor_write.descriptorCount = 1; + descriptor_write.pBufferInfo = &buffer_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->texture_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_sets(struct nk_glfw_device *dev) { + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSet *descriptor_sets; + VkDescriptorSetAllocateInfo allocate_info; + VkResult result; + int i; + + descriptor_set_layouts = (VkDescriptorSetLayout *)malloc( + NK_GLFW_MAX_TEXTURES * sizeof(VkDescriptorSetLayout)); + descriptor_sets = (VkDescriptorSet *)malloc(NK_GLFW_MAX_TEXTURES * + sizeof(VkDescriptorSet)); + + dev->texture_descriptor_sets = + (struct nk_vulkan_texture_descriptor_set *)malloc( + NK_GLFW_MAX_TEXTURES * + sizeof(struct nk_vulkan_texture_descriptor_set)); + dev->texture_descriptor_sets_len = 0; + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + descriptor_set_layouts[i] = dev->texture_descriptor_set_layout; + descriptor_sets[i] = dev->texture_descriptor_sets[i].descriptor_set; + } + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = NK_GLFW_MAX_TEXTURES; + allocate_info.pSetLayouts = descriptor_set_layouts; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + descriptor_sets); + NK_ASSERT(result == VK_SUCCESS); + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + dev->texture_descriptor_sets[i].descriptor_set = descriptor_sets[i]; + } + free(descriptor_set_layouts); + free(descriptor_sets); +} + +NK_INTERN void nk_glfw3_create_pipeline_layout(struct nk_glfw_device *dev) { + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkDescriptorSetLayout descriptor_set_layouts[2]; + VkResult result; + + descriptor_set_layouts[0] = dev->uniform_descriptor_set_layout; + descriptor_set_layouts[1] = dev->texture_descriptor_set_layout; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 2; + pipeline_layout_info.pSetLayouts = descriptor_set_layouts; + + result = (vkCreatePipelineLayout(dev->logical_device, &pipeline_layout_info, + NULL, &dev->pipeline_layout)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN VkPipelineShaderStageCreateInfo +nk_glfw3_create_shader(struct nk_glfw_device *dev, unsigned char *spv_shader, + uint32_t size, VkShaderStageFlagBits stage_bit) { + VkShaderModuleCreateInfo create_info; + VkPipelineShaderStageCreateInfo shader_info; + VkShaderModule module = NULL; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = size; + create_info.pCode = (const uint32_t *)spv_shader; + result = + vkCreateShaderModule(dev->logical_device, &create_info, NULL, &module); + NK_ASSERT(result == VK_SUCCESS); + + memset(&shader_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_info.stage = stage_bit; + shader_info.module = module; + shader_info.pName = "main"; + return shader_info; +} + +NK_INTERN void nk_glfw3_create_pipeline(struct nk_glfw_device *dev) { + VkPipelineInputAssemblyStateCreateInfo input_assembly_state; + VkPipelineRasterizationStateCreateInfo rasterization_state; + VkPipelineColorBlendAttachmentState attachment_state = { + VK_TRUE, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_OP_ADD, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE, + VK_BLEND_OP_ADD, + VK_COLOR_COMPONENT_MASK_RGBA, + }; + VkPipelineColorBlendStateCreateInfo color_blend_state; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineMultisampleStateCreateInfo multisample_state; + VkDynamicState dynamic_states[2] = {VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkVertexInputBindingDescription vertex_input_info; + VkVertexInputAttributeDescription vertex_attribute_description[3]; + VkPipelineVertexInputStateCreateInfo vertex_input; + VkGraphicsPipelineCreateInfo pipeline_info; + VkResult result; + + memset(&input_assembly_state, 0, + sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly_state.primitiveRestartEnable = VK_FALSE; + + memset(&rasterization_state, 0, + sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterization_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterization_state.polygonMode = VK_POLYGON_MODE_FILL; + rasterization_state.cullMode = VK_CULL_MODE_NONE; + rasterization_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterization_state.lineWidth = 1.0f; + + memset(&color_blend_state, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blend_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &attachment_state; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + + memset(&multisample_state, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisample_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&dynamic_state, 0, sizeof(VkPipelineDynamicStateCreateInfo)); + dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_state.pDynamicStates = dynamic_states; + dynamic_state.dynamicStateCount = 2; + + shader_stages[0] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_vert_spv, + nuklearshaders_nuklear_vert_spv_len, VK_SHADER_STAGE_VERTEX_BIT); + shader_stages[1] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_frag_spv, + nuklearshaders_nuklear_frag_spv_len, VK_SHADER_STAGE_FRAGMENT_BIT); + + memset(&vertex_input_info, 0, sizeof(VkVertexInputBindingDescription)); + vertex_input_info.binding = 0; + vertex_input_info.stride = sizeof(struct nk_glfw_vertex); + vertex_input_info.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + + memset(&vertex_attribute_description, 0, + sizeof(VkVertexInputAttributeDescription) * 3); + vertex_attribute_description[0].location = 0; + vertex_attribute_description[0].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[0].offset = + NK_OFFSETOF(struct nk_glfw_vertex, position); + vertex_attribute_description[1].location = 1; + vertex_attribute_description[1].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[1].offset = + NK_OFFSETOF(struct nk_glfw_vertex, uv); + vertex_attribute_description[2].location = 2; + vertex_attribute_description[2].format = VK_FORMAT_R8G8B8A8_UINT; + vertex_attribute_description[2].offset = + NK_OFFSETOF(struct nk_glfw_vertex, col); + + memset(&vertex_input, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vertex_input_info; + vertex_input.vertexAttributeDescriptionCount = 3; + vertex_input.pVertexAttributeDescriptions = vertex_attribute_description; + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.flags = 0; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input; + pipeline_info.pInputAssemblyState = &input_assembly_state; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterization_state; + pipeline_info.pMultisampleState = &multisample_state; + pipeline_info.pColorBlendState = &color_blend_state; + pipeline_info.pDynamicState = &dynamic_state; + pipeline_info.layout = dev->pipeline_layout; + pipeline_info.renderPass = dev->render_pass; + pipeline_info.basePipelineIndex = -1; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(dev->logical_device, NULL, 1, + &pipeline_info, NULL, &dev->pipeline); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyShaderModule(dev->logical_device, shader_stages[0].module, NULL); + vkDestroyShaderModule(dev->logical_device, shader_stages[1].module, NULL); +} + +NK_INTERN void nk_glfw3_create_render_resources(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + nk_glfw3_create_render_pass(dev); + nk_glfw3_create_framebuffers(dev, framebuffer_width, framebuffer_height); + nk_glfw3_create_descriptor_pool(dev); + nk_glfw3_create_uniform_descriptor_set_layout(dev); + nk_glfw3_create_and_update_uniform_descriptor_set(dev); + nk_glfw3_create_texture_descriptor_set_layout(dev); + nk_glfw3_create_texture_descriptor_sets(dev); + nk_glfw3_create_pipeline_layout(dev); + nk_glfw3_create_pipeline(dev); +} + +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + dev->max_vertex_buffer = max_vertex_buffer; + dev->max_element_buffer = max_element_buffer; + nk_buffer_init_default(&dev->cmds); + dev->logical_device = logical_device; + dev->physical_device = physical_device; + dev->image_views = image_views; + dev->image_views_len = image_views_len; + dev->color_format = color_format; + dev->framebuffers = NULL; + dev->framebuffers_len = 0; + + nk_glfw3_create_sampler(dev); + nk_glfw3_create_command_pool(dev, graphics_queue_family_index); + nk_glfw3_create_command_buffers(dev); + nk_glfw3_create_semaphore(dev); + + nk_glfw3_create_buffer_and_memory(dev, &dev->vertex_buffer, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + &dev->vertex_memory, max_vertex_buffer); + nk_glfw3_create_buffer_and_memory(dev, &dev->index_buffer, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + &dev->index_memory, max_element_buffer); + nk_glfw3_create_buffer_and_memory( + dev, &dev->uniform_buffer, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + &dev->uniform_memory, sizeof(struct Mat4f)); + + vkMapMemory(dev->logical_device, dev->vertex_memory, 0, max_vertex_buffer, + 0, &dev->mapped_vertex); + vkMapMemory(dev->logical_device, dev->index_memory, 0, max_element_buffer, + 0, &dev->mapped_index); + vkMapMemory(dev->logical_device, dev->uniform_memory, 0, + sizeof(struct Mat4f), 0, &dev->mapped_uniform); + + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_INTERN void nk_glfw3_device_upload_atlas(VkQueue graphics_queue, + const void *image, int width, + int height) { + struct nk_glfw_device *dev = &glfw.vulkan; + + VkImageCreateInfo image_info; + VkResult result; + VkMemoryRequirements mem_reqs; + VkMemoryAllocateInfo alloc_info; + VkBufferCreateInfo buffer_info; + uint8_t *data = 0; + VkCommandBufferBeginInfo begin_info; + VkCommandBuffer command_buffer; + VkImageMemoryBarrier image_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + VkImageViewCreateInfo image_view_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_info.extent.width = (uint32_t)width; + image_info.extent.height = (uint32_t)height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + result = + vkCreateImage(dev->logical_device, &image_info, NULL, &dev->font_image); + NK_ASSERT(result == VK_SUCCESS); + + vkGetImageMemoryRequirements(dev->logical_device, dev->font_image, + &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &dev->font_memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindImageMemory(dev->logical_device, dev->font_image, + dev->font_memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, + &staging_buffer.buffer); + NK_ASSERT(result == VK_SUCCESS); + vkGetBufferMemoryRequirements(dev->logical_device, staging_buffer.buffer, + &mem_reqs); + + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &staging_buffer.memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, staging_buffer.buffer, + staging_buffer.memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + result = vkMapMemory(dev->logical_device, staging_buffer.memory, 0, + alloc_info.allocationSize, 0, (void **)&data); + NK_ASSERT(result == VK_SUCCESS); + memcpy(data, image, width * height * 4); + vkUnmapMemory(dev->logical_device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + NK_ASSERT(dev->command_buffers_len > 0); + /* + use the same command buffer as for render as we are regenerating the + buffer during render anyway + */ + command_buffer = dev->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + + memset(&image_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.image = dev->font_image; + image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = (uint32_t)width; + buffer_copy_region.imageExtent.height = (uint32_t)height; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, dev->font_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = dev->font_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + + result = vkCreateFence(dev->logical_device, &fence_create, NULL, &fence); + NK_ASSERT(result == VK_SUCCESS); + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, fence); + NK_ASSERT(result == VK_SUCCESS); + result = + vkWaitForFences(dev->logical_device, 1, &fence, VK_TRUE, UINT64_MAX); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyFence(dev->logical_device, fence, NULL); + + vkFreeMemory(dev->logical_device, staging_buffer.memory, NULL); + vkDestroyBuffer(dev->logical_device, staging_buffer.buffer, NULL); + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.image = dev->font_image; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = image_info.format; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.layerCount = 1; + image_view_info.subresourceRange.levelCount = 1; + + result = vkCreateImageView(dev->logical_device, &image_view_info, NULL, + &dev->font_image_view); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_destroy_render_resources(struct nk_glfw_device *dev) { + uint32_t i; + + vkDestroyPipeline(dev->logical_device, dev->pipeline, NULL); + vkDestroyPipelineLayout(dev->logical_device, dev->pipeline_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->texture_descriptor_set_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->uniform_descriptor_set_layout, NULL); + vkDestroyDescriptorPool(dev->logical_device, dev->descriptor_pool, NULL); + for (i = 0; i < dev->framebuffers_len; i++) { + vkDestroyFramebuffer(dev->logical_device, dev->framebuffers[i], NULL); + } + free(dev->framebuffers); + dev->framebuffers_len = 0; + free(dev->texture_descriptor_sets); + dev->texture_descriptor_sets_len = 0; + vkDestroyRenderPass(dev->logical_device, dev->render_pass, NULL); +} + +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + glfwGetWindowSize(glfw.win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(glfw.win, &glfw.display_width, &glfw.display_height); + glfw.fb_scale.x = (float)glfw.display_width / (float)glfw.width; + glfw.fb_scale.y = (float)glfw.display_height / (float)glfw.height; + + nk_glfw3_destroy_render_resources(dev); + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_API void nk_glfw3_device_destroy(void) { + struct nk_glfw_device *dev = &glfw.vulkan; + + vkDeviceWaitIdle(dev->logical_device); + + nk_glfw3_destroy_render_resources(dev); + + vkFreeCommandBuffers(dev->logical_device, dev->command_pool, + dev->command_buffers_len, dev->command_buffers); + vkDestroyCommandPool(dev->logical_device, dev->command_pool, NULL); + vkDestroySemaphore(dev->logical_device, dev->render_completed, NULL); + + vkUnmapMemory(dev->logical_device, dev->vertex_memory); + vkUnmapMemory(dev->logical_device, dev->index_memory); + vkUnmapMemory(dev->logical_device, dev->uniform_memory); + + vkFreeMemory(dev->logical_device, dev->vertex_memory, NULL); + vkFreeMemory(dev->logical_device, dev->index_memory, NULL); + vkFreeMemory(dev->logical_device, dev->uniform_memory, NULL); + + vkDestroyBuffer(dev->logical_device, dev->vertex_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->index_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->uniform_buffer, NULL); + + vkDestroySampler(dev->logical_device, dev->sampler, NULL); + + vkFreeMemory(dev->logical_device, dev->font_memory, NULL); + vkDestroyImage(dev->logical_device, dev->font_image, NULL); + vkDestroyImageView(dev->logical_device, dev->font_image_view, NULL); + + free(dev->command_buffers); + nk_buffer_free(&dev->cmds); +} + +NK_API +void nk_glfw3_shutdown(void) { + nk_font_atlas_clear(&glfw.atlas); + nk_free(&glfw.ctx); + nk_glfw3_device_destroy(); + memset(&glfw, 0, sizeof(glfw)); +} + +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas) { + nk_font_atlas_init_default(&glfw.atlas); + nk_font_atlas_begin(&glfw.atlas); + *atlas = &glfw.atlas; +} + +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue) { + struct nk_glfw_device *dev = &glfw.vulkan; + + const void *image; + int w, h; + image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); + nk_glfw3_device_upload_atlas(graphics_queue, image, w, h); + nk_font_atlas_end(&glfw.atlas, nk_handle_ptr(dev->font_image_view), + &dev->tex_null); + if (glfw.atlas.default_font) { + nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); + } +} + +NK_API void nk_glfw3_new_frame(void) { + int i; + double x, y; + struct nk_context *ctx = &glfw.ctx; + struct GLFWwindow *win = glfw.win; + + nk_input_begin(ctx); + for (i = 0; i < glfw.text_len; ++i) + nk_input_unicode(ctx, glfw.text[i]); + +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + /* optional grabbing behavior */ + if (ctx->input.mouse.grab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + else if (ctx->input.mouse.ungrab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif + + nk_input_key(ctx, NK_KEY_DEL, + glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_ENTER, + glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_BACKSPACE, + glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_DOWN, + glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_DOWN, + glfwGetKey(win, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_UP, + glfwGetKey(win, GLFW_KEY_PAGE_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SHIFT, + glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); + + if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { + nk_input_key(ctx, NK_KEY_COPY, + glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_PASTE, + glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_CUT, + glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_UNDO, + glfwGetKey(win, GLFW_KEY_Z) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_REDO, + glfwGetKey(win, GLFW_KEY_R) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_START, + glfwGetKey(win, GLFW_KEY_B) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_END, + glfwGetKey(win, GLFW_KEY_E) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_SELECT_ALL, + glfwGetKey(win, GLFW_KEY_A) == GLFW_PRESS); + } else { + nk_input_key(ctx, NK_KEY_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_COPY, 0); + nk_input_key(ctx, NK_KEY_PASTE, 0); + nk_input_key(ctx, NK_KEY_CUT, 0); + nk_input_key(ctx, NK_KEY_SHIFT, 0); + } + + glfwGetCursorPos(win, &x, &y); + nk_input_motion(ctx, (int)x, (int)y); +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + if (ctx->input.mouse.grabbed) { + glfwSetCursorPos(glfw.win, ctx->input.mouse.prev.x, + ctx->input.mouse.prev.y); + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +#endif + nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)glfw.double_click_pos.x, + (int)glfw.double_click_pos.y, glfw.is_double_click_down); + nk_input_scroll(ctx, glfw.scroll); + nk_input_end(&glfw.ctx); + glfw.text_len = 0; + glfw.scroll = nk_vec2(0, 0); +} + +NK_INTERN void update_texture_descriptor_set( + struct nk_glfw_device *dev, + struct nk_vulkan_texture_descriptor_set *texture_descriptor_set, + VkImageView image_view) { + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + texture_descriptor_set->image_view = image_view; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.sampler = dev->sampler; + descriptor_image_info.imageView = texture_descriptor_set->image_view; + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = texture_descriptor_set->descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_API +VkSemaphore nk_glfw3_render(VkQueue graphics_queue, uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA) { + struct nk_glfw_device *dev = &glfw.vulkan; + struct nk_buffer vbuf, ebuf; + + struct Mat4f projection = { + {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, + 0.0f, -1.0f, 1.0f, 0.0f, 1.0f}, + }; + + VkCommandBufferBeginInfo begin_info; + VkClearValue clear_value = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; + VkRenderPassBeginInfo render_pass_begin_nfo; + VkCommandBuffer command_buffer; + VkResult result; + VkViewport viewport; + + VkDeviceSize doffset = 0; + VkImageView current_texture = NULL; + uint32_t index_offset = 0; + VkRect2D scissor; + uint32_t wait_semaphore_count; + VkSemaphore *wait_semaphores; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo submit_info; + + projection.m[0] /= glfw.width; + projection.m[5] /= glfw.height; + + memcpy(dev->mapped_uniform, &projection, sizeof(projection)); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + memset(&render_pass_begin_nfo, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_begin_nfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_begin_nfo.renderPass = dev->render_pass; + render_pass_begin_nfo.renderArea.extent.width = (uint32_t)glfw.width; + render_pass_begin_nfo.renderArea.extent.height = (uint32_t)glfw.height; + render_pass_begin_nfo.clearValueCount = 1; + render_pass_begin_nfo.pClearValues = &clear_value; + render_pass_begin_nfo.framebuffer = dev->framebuffers[buffer_index]; + + command_buffer = dev->command_buffers[buffer_index]; + + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + vkCmdBeginRenderPass(command_buffer, &render_pass_begin_nfo, + VK_SUBPASS_CONTENTS_INLINE); + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.width = (float)glfw.width; + viewport.height = (float)glfw.height; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 0, 1, + &dev->uniform_descriptor_set, 0, NULL); + { + /* convert from command queue into draw list and draw to screen */ + const struct nk_draw_command *cmd; + /* load draw vertices & elements directly into vertex + element buffer + */ + { + /* fill convert configuration */ + struct nk_convert_config config; + static const struct nk_draw_vertex_layout_element vertex_layout[] = + {{NK_VERTEX_POSITION, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, position)}, + {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, uv)}, + {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, + NK_OFFSETOF(struct nk_glfw_vertex, col)}, + {NK_VERTEX_LAYOUT_END}}; + NK_MEMSET(&config, 0, sizeof(config)); + config.vertex_layout = vertex_layout; + config.vertex_size = sizeof(struct nk_glfw_vertex); + config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); + config.tex_null = dev->tex_null; + config.circle_segment_count = 22; + config.curve_segment_count = 22; + config.arc_segment_count = 22; + config.global_alpha = 1.0f; + config.shape_AA = AA; + config.line_AA = AA; + + /* setup buffers to load vertices and elements */ + nk_buffer_init_fixed(&vbuf, dev->mapped_vertex, + (size_t)dev->max_vertex_buffer); + nk_buffer_init_fixed(&ebuf, dev->mapped_index, + (size_t)dev->max_element_buffer); + nk_convert(&glfw.ctx, &dev->cmds, &vbuf, &ebuf, &config); + } + + /* iterate over and execute each draw command */ + + vkCmdBindVertexBuffers(command_buffer, 0, 1, &dev->vertex_buffer, + &doffset); + vkCmdBindIndexBuffer(command_buffer, dev->index_buffer, 0, + VK_INDEX_TYPE_UINT16); + + nk_draw_foreach(cmd, &glfw.ctx, &dev->cmds) { + if (!cmd->texture.ptr) { + continue; + } + if (cmd->texture.ptr && cmd->texture.ptr != current_texture) { + int found = 0; + uint32_t i; + for (i = 0; i < dev->texture_descriptor_sets_len; i++) { + if (dev->texture_descriptor_sets[i].image_view == + cmd->texture.ptr) { + found = 1; + break; + } + } + + if (!found) { + update_texture_descriptor_set( + dev, &dev->texture_descriptor_sets[i], + (VkImageView)cmd->texture.ptr); + dev->texture_descriptor_sets_len++; + } + vkCmdBindDescriptorSets( + command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 1, 1, + &dev->texture_descriptor_sets[i].descriptor_set, 0, NULL); + } + + if (!cmd->elem_count) + continue; + + scissor.offset.x = (int32_t)(NK_MAX(cmd->clip_rect.x, 0.f)); + scissor.offset.y = (int32_t)(NK_MAX(cmd->clip_rect.y, 0.f)); + scissor.extent.width = (uint32_t)(cmd->clip_rect.w); + scissor.extent.height = (uint32_t)(cmd->clip_rect.h); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + vkCmdDrawIndexed(command_buffer, cmd->elem_count, 1, index_offset, + 0, 0); + index_offset += cmd->elem_count; + } + nk_clear(&glfw.ctx); + } + + vkCmdEndRenderPass(command_buffer); + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + if (wait_semaphore) { + wait_semaphore_count = 1; + wait_semaphores = &wait_semaphore; + } else { + wait_semaphore_count = 0; + wait_semaphores = NULL; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.waitSemaphoreCount = wait_semaphore_count; + submit_info.pWaitSemaphores = wait_semaphores; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &dev->render_completed; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, NULL); + NK_ASSERT(result == VK_SUCCESS); + + return dev->render_completed; +} + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint) { + (void)win; + if (glfw.text_len < NK_GLFW_TEXT_MAX) + glfw.text[glfw.text_len++] = codepoint; +} + +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, + double yoff) { + (void)win; + (void)xoff; + glfw.scroll.x += (float)xoff; + glfw.scroll.y += (float)yoff; +} + +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *window, int button, + int action, int mods) { + double x, y; + NK_UNUSED(mods); + if (button != GLFW_MOUSE_BUTTON_LEFT) + return; + glfwGetCursorPos(window, &x, &y); + if (action == GLFW_PRESS) { + double dt = glfwGetTime() - glfw.last_button_click; + if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { + glfw.is_double_click_down = nk_true; + glfw.double_click_pos = nk_vec2((float)x, (float)y); + } + glfw.last_button_click = glfwGetTime(); + } else + glfw.is_double_click_down = nk_false; +} + +NK_INTERN void nk_glfw3_clipboard_paste(nk_handle usr, + struct nk_text_edit *edit) { + const char *text = glfwGetClipboardString(glfw.win); + if (text) + nk_textedit_paste(edit, text, nk_strlen(text)); + (void)usr; +} + +NK_INTERN void nk_glfw3_clipboard_copy(nk_handle usr, const char *text, + int len) { + char *str = 0; + (void)usr; + if (!len) + return; + str = (char *)malloc((size_t)len + 1); + if (!str) + return; + memcpy(str, text, (size_t)len); + str[len] = '\0'; + glfwSetClipboardString(glfw.win, str); + free(str); +} + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer) { + memset(&glfw, 0, sizeof(struct nk_glfw)); + glfw.win = win; + if (init_state == NK_GLFW3_INSTALL_CALLBACKS) { + glfwSetScrollCallback(win, nk_gflw3_scroll_callback); + glfwSetCharCallback(win, nk_glfw3_char_callback); + glfwSetMouseButtonCallback(win, nk_glfw3_mouse_button_callback); + } + nk_init_default(&glfw.ctx, 0); + glfw.ctx.clip.copy = nk_glfw3_clipboard_copy; + glfw.ctx.clip.paste = nk_glfw3_clipboard_paste; + glfw.ctx.clip.userdata = nk_handle_ptr(0); + glfw.last_button_click = 0; + + glfwGetWindowSize(win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(win, &glfw.display_width, &glfw.display_height); + + nk_glfw3_device_create(logical_device, physical_device, + graphics_queue_family_index, image_views, + image_views_len, color_format, max_vertex_buffer, + max_element_buffer, (uint32_t)glfw.display_width, + (uint32_t)glfw.display_height); + + glfw.is_double_click_down = nk_false; + glfw.double_click_pos = nk_vec2(0, 0); + + return &glfw.ctx; +} + +#endif diff --git a/demo/glfw_vulkan/shaders/demo.frag b/demo/glfw_vulkan/shaders/demo.frag new file mode 100644 index 0000000..2034597 --- /dev/null +++ b/demo/glfw_vulkan/shaders/demo.frag @@ -0,0 +1,12 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(binding = 0) uniform sampler2D overlay; + +layout(location = 0) in vec2 inUV; + +layout(location = 0) out vec4 outColor; + +void main() { + outColor = texture(overlay, inUV); +} diff --git a/demo/glfw_vulkan/shaders/demo.vert b/demo/glfw_vulkan/shaders/demo.vert new file mode 100644 index 0000000..c39196a --- /dev/null +++ b/demo/glfw_vulkan/shaders/demo.vert @@ -0,0 +1,10 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout (location = 0) out vec2 outUV; + +void main() +{ + outUV = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(outUV * 2.0f + -1.0f, 0.0f, 1.0f); +} diff --git a/demo/glfw_vulkan/src/Makefile b/demo/glfw_vulkan/src/Makefile new file mode 100644 index 0000000..8a5dee9 --- /dev/null +++ b/demo/glfw_vulkan/src/Makefile @@ -0,0 +1,11 @@ +create_shader_inlined_header: nuklearshaders/nuklear.vert.spv nuklearshaders/nuklear.frag.spv + awk -v st='// NUKLEAR_SHADERS_START' -v et='// NUKLEAR_SHADERS_END' -v repl="$$(xxd -i nuklearshaders/nuklear.vert.spv && xxd -i nuklearshaders/nuklear.frag.spv)" '$$0 == st{del=1} $$0 == et{$$0 = repl; del=0} !del' nuklear_glfw_vulkan.in.h > nuklear_glfw_vulkan.h + +nuklearshaders/nuklear.vert.spv: nuklearshaders/nuklear.vert + glslc --target-env=vulkan nuklearshaders/nuklear.vert -o nuklearshaders/nuklear.vert.spv + +nuklearshaders/nuklear.frag.spv: nuklearshaders/nuklear.frag + glslc --target-env=vulkan nuklearshaders/nuklear.frag -o nuklearshaders/nuklear.frag.spv + +clean: + rm nuklearshaders/nuklear.vert.spv nuklearshaders/nuklear.frag.spv nuklear_glfw_vulkan.h diff --git a/demo/glfw_vulkan/src/README.md b/demo/glfw_vulkan/src/README.md new file mode 100644 index 0000000..c911fbc --- /dev/null +++ b/demo/glfw_vulkan/src/README.md @@ -0,0 +1,5 @@ +Contrary to OpenGL Vulkan needs precompiled shaders in the SPIR-V format which makes it a bit more difficult to inline the shadercode. + +After executing `make` the result should be a self contained `nuklear_glfw_vulkan.h`. Copy the result file to the parent directory and the "release" should be done. + +You will need to have `xxd`, `glslc` and `awk` installed for this. diff --git a/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h new file mode 100644 index 0000000..ea86e5b --- /dev/null +++ b/demo/glfw_vulkan/src/nuklear_glfw_vulkan.in.h @@ -0,0 +1,1426 @@ +/* + * Nuklear - 1.32.0 - public domain + * no warrenty implied; use at your own risk. + * authored from 2015-2016 by Micha Mettke + */ +/* + * ============================================================== + * + * API + * + * =============================================================== + */ +#ifndef NK_GLFW_VULKAN_H_ +#define NK_GLFW_VULKAN_H_ + +// NUKLEAR_SHADERS_START +// will be replaced with the real shader code +// so we can have some ide support while editing the .in file +#include "nuklear.h" + +unsigned char nuklearshaders_nuklear_vert_spv[] = {}; +unsigned int nuklearshaders_nuklear_vert_spv_len = 0; +unsigned char nuklearshaders_nuklear_frag_spv[] = {}; +unsigned int nuklearshaders_nuklear_frag_spv_len = 0; +// NUKLEAR_SHADERS_END + +#include +#include +#define GLFW_INCLUDE_VULKAN +#include + +enum nk_glfw_init_state { NK_GLFW3_DEFAULT = 0, NK_GLFW3_INSTALL_CALLBACKS }; + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer); +NK_API void nk_glfw3_shutdown(void); +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas); +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue); +NK_API void nk_glfw3_new_frame(); +NK_API VkSemaphore nk_glfw3_render(VkQueue graphics_queue, + uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA); +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height); +NK_API void nk_glfw3_device_destroy(void); +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height); + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint); +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff); +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *win, int button, + int action, int mods); + +#endif +/* + * ============================================================== + * + * IMPLEMENTATION + * + * =============================================================== + */ +#ifdef NK_GLFW_VULKAN_IMPLEMENTATION +#undef NK_GLFW_VULKAN_IMPLEMENTATION +#include +#include + +#ifndef NK_GLFW_TEXT_MAX +#define NK_GLFW_TEXT_MAX 256 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_LO +#define NK_GLFW_DOUBLE_CLICK_LO 0.02 +#endif +#ifndef NK_GLFW_DOUBLE_CLICK_HI +#define NK_GLFW_DOUBLE_CLICK_HI 0.2 +#endif +#ifndef NK_GLFW_MAX_TEXTURES +#define NK_GLFW_MAX_TEXTURES 256 +#endif + +#define VK_COLOR_COMPONENT_MASK_RGBA \ + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | \ + VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT + +struct nk_glfw_vertex { + float position[2]; + float uv[2]; + nk_byte col[4]; +}; + +struct nk_vulkan_texture_descriptor_set { + VkImageView image_view; + VkDescriptorSet descriptor_set; +}; + +struct nk_glfw_device { + struct nk_buffer cmds; + struct nk_draw_null_texture tex_null; + int max_vertex_buffer; + int max_element_buffer; + VkDevice logical_device; + VkPhysicalDevice physical_device; + VkImageView *image_views; + uint32_t image_views_len; + VkFormat color_format; + VkFramebuffer *framebuffers; + uint32_t framebuffers_len; + VkCommandBuffer *command_buffers; + uint32_t command_buffers_len; + VkSampler sampler; + VkCommandPool command_pool; + VkSemaphore render_completed; + VkBuffer vertex_buffer; + VkDeviceMemory vertex_memory; + void *mapped_vertex; + VkBuffer index_buffer; + VkDeviceMemory index_memory; + void *mapped_index; + VkBuffer uniform_buffer; + VkDeviceMemory uniform_memory; + void *mapped_uniform; + VkRenderPass render_pass; + VkDescriptorPool descriptor_pool; + VkDescriptorSetLayout uniform_descriptor_set_layout; + VkDescriptorSet uniform_descriptor_set; + VkDescriptorSetLayout texture_descriptor_set_layout; + struct nk_vulkan_texture_descriptor_set *texture_descriptor_sets; + uint32_t texture_descriptor_sets_len; + VkPipelineLayout pipeline_layout; + VkPipeline pipeline; + VkImage font_image; + VkImageView font_image_view; + VkDeviceMemory font_memory; +}; + +static struct nk_glfw { + GLFWwindow *win; + int width, height; + int display_width, display_height; + struct nk_glfw_device vulkan; + struct nk_context ctx; + struct nk_font_atlas atlas; + struct nk_vec2 fb_scale; + unsigned int text[NK_GLFW_TEXT_MAX]; + int text_len; + struct nk_vec2 scroll; + double last_button_click; + int is_double_click_down; + struct nk_vec2 double_click_pos; +} glfw; + +struct Mat4f { + float m[16]; +}; + +NK_INTERN uint32_t nk_glfw3_find_memory_index( + VkPhysicalDevice physical_device, uint32_t type_filter, + VkMemoryPropertyFlags properties) { + VkPhysicalDeviceMemoryProperties mem_properties; + uint32_t i; + + vkGetPhysicalDeviceMemoryProperties(physical_device, &mem_properties); + for (i = 0; i < mem_properties.memoryTypeCount; i++) { + if ((type_filter & (1 << i)) && + (mem_properties.memoryTypes[i].propertyFlags & properties) == + properties) { + return i; + } + } + + assert(0); + return 0; +} + +NK_INTERN void nk_glfw3_create_sampler(struct nk_glfw_device *dev) { + VkResult result; + VkSamplerCreateInfo sampler_info; + memset(&sampler_info, 0, sizeof(VkSamplerCreateInfo)); + + sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + sampler_info.pNext = NULL; + sampler_info.maxAnisotropy = 1.0; + sampler_info.magFilter = VK_FILTER_LINEAR; + sampler_info.minFilter = VK_FILTER_LINEAR; + sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; + sampler_info.mipLodBias = 0.0f; + sampler_info.compareEnable = VK_FALSE; + sampler_info.compareOp = VK_COMPARE_OP_ALWAYS; + sampler_info.minLod = 0.0f; + sampler_info.maxLod = 0.0f; + sampler_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; + + result = vkCreateSampler(dev->logical_device, &sampler_info, NULL, + &dev->sampler); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_command_pool(struct nk_glfw_device *dev, + uint32_t graphics_queue_family_index) { + VkResult result; + VkCommandPoolCreateInfo pool_info; + memset(&pool_info, 0, sizeof(VkCommandPoolCreateInfo)); + + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = graphics_queue_family_index; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + result = vkCreateCommandPool(dev->logical_device, &pool_info, NULL, + &dev->command_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_command_buffers(struct nk_glfw_device *dev) { + VkResult result; + VkCommandBufferAllocateInfo allocate_info; + memset(&allocate_info, 0, sizeof(VkCommandBufferAllocateInfo)); + + dev->command_buffers = (VkCommandBuffer *)malloc(dev->image_views_len * + sizeof(VkCommandBuffer)); + dev->command_buffers_len = dev->image_views_len; + + allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + allocate_info.commandPool = dev->command_pool; + allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate_info.commandBufferCount = dev->command_buffers_len; + + result = vkAllocateCommandBuffers(dev->logical_device, &allocate_info, + dev->command_buffers); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_semaphore(struct nk_glfw_device *dev) { + VkResult result; + VkSemaphoreCreateInfo semaphore_info; + memset(&semaphore_info, 0, sizeof(VkSemaphoreCreateInfo)); + + semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + result = (vkCreateSemaphore(dev->logical_device, &semaphore_info, NULL, + &dev->render_completed)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_buffer_and_memory(struct nk_glfw_device *dev, + VkBuffer *buffer, + VkBufferUsageFlags usage, + VkDeviceMemory *memory, + VkDeviceSize size) { + VkMemoryRequirements mem_reqs; + VkResult result; + VkBufferCreateInfo buffer_info; + VkMemoryAllocateInfo alloc_info; + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = size; + buffer_info.usage = usage; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, buffer); + NK_ASSERT(result == VK_SUCCESS); + + vkGetBufferMemoryRequirements(dev->logical_device, *buffer, &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, *buffer, *memory, 0); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_render_pass(struct nk_glfw_device *dev) { + VkAttachmentDescription attachment; + VkAttachmentReference color_reference; + VkSubpassDependency subpass_dependency; + VkSubpassDescription subpass_description; + VkRenderPassCreateInfo render_pass_info; + VkResult result; + + memset(&attachment, 0, sizeof(VkAttachmentDescription)); + attachment.format = dev->color_format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&color_reference, 0, sizeof(VkAttachmentReference)); + color_reference.attachment = 0; + color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + memset(&subpass_dependency, 0, sizeof(VkSubpassDependency)); + subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + subpass_dependency.srcAccessMask = 0; + subpass_dependency.srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + subpass_dependency.dstSubpass = 0; + subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + subpass_dependency.dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + + memset(&subpass_description, 0, sizeof(VkSubpassDescription)); + subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass_description.colorAttachmentCount = 1; + subpass_description.pColorAttachments = &color_reference; + + memset(&render_pass_info, 0, sizeof(VkRenderPassCreateInfo)); + render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + render_pass_info.attachmentCount = 1; + render_pass_info.pAttachments = &attachment; + render_pass_info.subpassCount = 1; + render_pass_info.pSubpasses = &subpass_description; + render_pass_info.dependencyCount = 1; + render_pass_info.pDependencies = &subpass_dependency; + + result = vkCreateRenderPass(dev->logical_device, &render_pass_info, NULL, + &dev->render_pass); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_create_framebuffers(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + + VkFramebufferCreateInfo framebuffer_create_info; + uint32_t i; + VkResult result; + + dev->framebuffers = + (VkFramebuffer *)malloc(dev->image_views_len * sizeof(VkFramebuffer)); + + memset(&framebuffer_create_info, 0, sizeof(VkFramebufferCreateInfo)); + framebuffer_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + framebuffer_create_info.renderPass = dev->render_pass; + framebuffer_create_info.attachmentCount = 1; + framebuffer_create_info.width = framebuffer_width; + framebuffer_create_info.height = framebuffer_height; + framebuffer_create_info.layers = 1; + for (i = 0; i < dev->image_views_len; i++) { + framebuffer_create_info.pAttachments = &dev->image_views[i]; + result = + vkCreateFramebuffer(dev->logical_device, &framebuffer_create_info, + NULL, &dev->framebuffers[i]); + NK_ASSERT(result == VK_SUCCESS); + } + dev->framebuffers_len = dev->image_views_len; +} + +NK_INTERN void nk_glfw3_create_descriptor_pool(struct nk_glfw_device *dev) { + VkDescriptorPoolSize pool_sizes[2]; + VkDescriptorPoolCreateInfo pool_info; + VkResult result; + + memset(&pool_sizes, 0, sizeof(VkDescriptorPoolSize) * 2); + pool_sizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + pool_sizes[0].descriptorCount = 1; + pool_sizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_sizes[1].descriptorCount = NK_GLFW_MAX_TEXTURES; + + memset(&pool_info, 0, sizeof(VkDescriptorPoolCreateInfo)); + pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + pool_info.poolSizeCount = 2; + pool_info.pPoolSizes = pool_sizes; + pool_info.maxSets = 1 + NK_GLFW_MAX_TEXTURES; + + result = vkCreateDescriptorPool(dev->logical_device, &pool_info, NULL, + &dev->descriptor_pool); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_uniform_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->uniform_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_and_update_uniform_descriptor_set(struct nk_glfw_device *dev) { + VkDescriptorSetAllocateInfo allocate_info; + VkDescriptorBufferInfo buffer_info; + VkWriteDescriptorSet descriptor_write; + VkResult result; + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = 1; + allocate_info.pSetLayouts = &dev->uniform_descriptor_set_layout; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + &dev->uniform_descriptor_set); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkDescriptorBufferInfo)); + buffer_info.buffer = dev->uniform_buffer; + buffer_info.offset = 0; + buffer_info.range = sizeof(struct Mat4f); + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = dev->uniform_descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptor_write.descriptorCount = 1; + descriptor_write.pBufferInfo = &buffer_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_set_layout(struct nk_glfw_device *dev) { + VkDescriptorSetLayoutBinding binding; + VkDescriptorSetLayoutCreateInfo descriptor_set_info; + VkResult result; + + memset(&binding, 0, sizeof(VkDescriptorSetLayoutBinding)); + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + memset(&descriptor_set_info, 0, sizeof(VkDescriptorSetLayoutCreateInfo)); + descriptor_set_info.sType = + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + descriptor_set_info.bindingCount = 1; + descriptor_set_info.pBindings = &binding; + + result = + vkCreateDescriptorSetLayout(dev->logical_device, &descriptor_set_info, + NULL, &dev->texture_descriptor_set_layout); + + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void +nk_glfw3_create_texture_descriptor_sets(struct nk_glfw_device *dev) { + VkDescriptorSetLayout *descriptor_set_layouts; + VkDescriptorSet *descriptor_sets; + VkDescriptorSetAllocateInfo allocate_info; + VkResult result; + int i; + + descriptor_set_layouts = (VkDescriptorSetLayout *)malloc( + NK_GLFW_MAX_TEXTURES * sizeof(VkDescriptorSetLayout)); + descriptor_sets = (VkDescriptorSet *)malloc(NK_GLFW_MAX_TEXTURES * + sizeof(VkDescriptorSet)); + + dev->texture_descriptor_sets = + (struct nk_vulkan_texture_descriptor_set *)malloc( + NK_GLFW_MAX_TEXTURES * + sizeof(struct nk_vulkan_texture_descriptor_set)); + dev->texture_descriptor_sets_len = 0; + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + descriptor_set_layouts[i] = dev->texture_descriptor_set_layout; + descriptor_sets[i] = dev->texture_descriptor_sets[i].descriptor_set; + } + + memset(&allocate_info, 0, sizeof(VkDescriptorSetAllocateInfo)); + allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocate_info.descriptorPool = dev->descriptor_pool; + allocate_info.descriptorSetCount = NK_GLFW_MAX_TEXTURES; + allocate_info.pSetLayouts = descriptor_set_layouts; + + result = vkAllocateDescriptorSets(dev->logical_device, &allocate_info, + descriptor_sets); + NK_ASSERT(result == VK_SUCCESS); + + for (i = 0; i < NK_GLFW_MAX_TEXTURES; i++) { + dev->texture_descriptor_sets[i].descriptor_set = descriptor_sets[i]; + } + free(descriptor_set_layouts); + free(descriptor_sets); +} + +NK_INTERN void nk_glfw3_create_pipeline_layout(struct nk_glfw_device *dev) { + VkPipelineLayoutCreateInfo pipeline_layout_info; + VkDescriptorSetLayout descriptor_set_layouts[2]; + VkResult result; + + descriptor_set_layouts[0] = dev->uniform_descriptor_set_layout; + descriptor_set_layouts[1] = dev->texture_descriptor_set_layout; + + memset(&pipeline_layout_info, 0, sizeof(VkPipelineLayoutCreateInfo)); + pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + pipeline_layout_info.setLayoutCount = 2; + pipeline_layout_info.pSetLayouts = descriptor_set_layouts; + + result = (vkCreatePipelineLayout(dev->logical_device, &pipeline_layout_info, + NULL, &dev->pipeline_layout)); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN VkPipelineShaderStageCreateInfo +nk_glfw3_create_shader(struct nk_glfw_device *dev, unsigned char *spv_shader, + uint32_t size, VkShaderStageFlagBits stage_bit) { + VkShaderModuleCreateInfo create_info; + VkPipelineShaderStageCreateInfo shader_info; + VkShaderModule module = NULL; + VkResult result; + + memset(&create_info, 0, sizeof(VkShaderModuleCreateInfo)); + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.codeSize = size; + create_info.pCode = (const uint32_t *)spv_shader; + result = + vkCreateShaderModule(dev->logical_device, &create_info, NULL, &module); + NK_ASSERT(result == VK_SUCCESS); + + memset(&shader_info, 0, sizeof(VkPipelineShaderStageCreateInfo)); + shader_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shader_info.stage = stage_bit; + shader_info.module = module; + shader_info.pName = "main"; + return shader_info; +} + +NK_INTERN void nk_glfw3_create_pipeline(struct nk_glfw_device *dev) { + VkPipelineInputAssemblyStateCreateInfo input_assembly_state; + VkPipelineRasterizationStateCreateInfo rasterization_state; + VkPipelineColorBlendAttachmentState attachment_state = { + VK_TRUE, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + VK_BLEND_OP_ADD, + VK_BLEND_FACTOR_SRC_ALPHA, + VK_BLEND_FACTOR_ONE, + VK_BLEND_OP_ADD, + VK_COLOR_COMPONENT_MASK_RGBA, + }; + VkPipelineColorBlendStateCreateInfo color_blend_state; + VkPipelineViewportStateCreateInfo viewport_state; + VkPipelineMultisampleStateCreateInfo multisample_state; + VkDynamicState dynamic_states[2] = {VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state; + VkPipelineShaderStageCreateInfo shader_stages[2]; + VkVertexInputBindingDescription vertex_input_info; + VkVertexInputAttributeDescription vertex_attribute_description[3]; + VkPipelineVertexInputStateCreateInfo vertex_input; + VkGraphicsPipelineCreateInfo pipeline_info; + VkResult result; + + memset(&input_assembly_state, 0, + sizeof(VkPipelineInputAssemblyStateCreateInfo)); + input_assembly_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + input_assembly_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + input_assembly_state.primitiveRestartEnable = VK_FALSE; + + memset(&rasterization_state, 0, + sizeof(VkPipelineRasterizationStateCreateInfo)); + rasterization_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rasterization_state.polygonMode = VK_POLYGON_MODE_FILL; + rasterization_state.cullMode = VK_CULL_MODE_NONE; + rasterization_state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + rasterization_state.lineWidth = 1.0f; + + memset(&color_blend_state, 0, sizeof(VkPipelineColorBlendStateCreateInfo)); + color_blend_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &attachment_state; + + memset(&viewport_state, 0, sizeof(VkPipelineViewportStateCreateInfo)); + viewport_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + viewport_state.viewportCount = 1; + viewport_state.scissorCount = 1; + + memset(&multisample_state, 0, sizeof(VkPipelineMultisampleStateCreateInfo)); + multisample_state.sType = + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + multisample_state.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + memset(&dynamic_state, 0, sizeof(VkPipelineDynamicStateCreateInfo)); + dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dynamic_state.pDynamicStates = dynamic_states; + dynamic_state.dynamicStateCount = 2; + + shader_stages[0] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_vert_spv, + nuklearshaders_nuklear_vert_spv_len, VK_SHADER_STAGE_VERTEX_BIT); + shader_stages[1] = nk_glfw3_create_shader( + dev, nuklearshaders_nuklear_frag_spv, + nuklearshaders_nuklear_frag_spv_len, VK_SHADER_STAGE_FRAGMENT_BIT); + + memset(&vertex_input_info, 0, sizeof(VkVertexInputBindingDescription)); + vertex_input_info.binding = 0; + vertex_input_info.stride = sizeof(struct nk_glfw_vertex); + vertex_input_info.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; + + memset(&vertex_attribute_description, 0, + sizeof(VkVertexInputAttributeDescription) * 3); + vertex_attribute_description[0].location = 0; + vertex_attribute_description[0].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[0].offset = + NK_OFFSETOF(struct nk_glfw_vertex, position); + vertex_attribute_description[1].location = 1; + vertex_attribute_description[1].format = VK_FORMAT_R32G32_SFLOAT; + vertex_attribute_description[1].offset = + NK_OFFSETOF(struct nk_glfw_vertex, uv); + vertex_attribute_description[2].location = 2; + vertex_attribute_description[2].format = VK_FORMAT_R8G8B8A8_UINT; + vertex_attribute_description[2].offset = + NK_OFFSETOF(struct nk_glfw_vertex, col); + + memset(&vertex_input, 0, sizeof(VkPipelineVertexInputStateCreateInfo)); + vertex_input.sType = + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + vertex_input.vertexBindingDescriptionCount = 1; + vertex_input.pVertexBindingDescriptions = &vertex_input_info; + vertex_input.vertexAttributeDescriptionCount = 3; + vertex_input.pVertexAttributeDescriptions = vertex_attribute_description; + + memset(&pipeline_info, 0, sizeof(VkGraphicsPipelineCreateInfo)); + pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + pipeline_info.flags = 0; + pipeline_info.stageCount = 2; + pipeline_info.pStages = shader_stages; + pipeline_info.pVertexInputState = &vertex_input; + pipeline_info.pInputAssemblyState = &input_assembly_state; + pipeline_info.pViewportState = &viewport_state; + pipeline_info.pRasterizationState = &rasterization_state; + pipeline_info.pMultisampleState = &multisample_state; + pipeline_info.pColorBlendState = &color_blend_state; + pipeline_info.pDynamicState = &dynamic_state; + pipeline_info.layout = dev->pipeline_layout; + pipeline_info.renderPass = dev->render_pass; + pipeline_info.basePipelineIndex = -1; + pipeline_info.basePipelineHandle = NULL; + + result = vkCreateGraphicsPipelines(dev->logical_device, NULL, 1, + &pipeline_info, NULL, &dev->pipeline); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyShaderModule(dev->logical_device, shader_stages[0].module, NULL); + vkDestroyShaderModule(dev->logical_device, shader_stages[1].module, NULL); +} + +NK_INTERN void nk_glfw3_create_render_resources(struct nk_glfw_device *dev, + uint32_t framebuffer_width, + uint32_t framebuffer_height) { + nk_glfw3_create_render_pass(dev); + nk_glfw3_create_framebuffers(dev, framebuffer_width, framebuffer_height); + nk_glfw3_create_descriptor_pool(dev); + nk_glfw3_create_uniform_descriptor_set_layout(dev); + nk_glfw3_create_and_update_uniform_descriptor_set(dev); + nk_glfw3_create_texture_descriptor_set_layout(dev); + nk_glfw3_create_texture_descriptor_sets(dev); + nk_glfw3_create_pipeline_layout(dev); + nk_glfw3_create_pipeline(dev); +} + +NK_API void nk_glfw3_device_create( + VkDevice logical_device, VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer, + uint32_t framebuffer_width, uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + dev->max_vertex_buffer = max_vertex_buffer; + dev->max_element_buffer = max_element_buffer; + nk_buffer_init_default(&dev->cmds); + dev->logical_device = logical_device; + dev->physical_device = physical_device; + dev->image_views = image_views; + dev->image_views_len = image_views_len; + dev->color_format = color_format; + dev->framebuffers = NULL; + dev->framebuffers_len = 0; + + nk_glfw3_create_sampler(dev); + nk_glfw3_create_command_pool(dev, graphics_queue_family_index); + nk_glfw3_create_command_buffers(dev); + nk_glfw3_create_semaphore(dev); + + nk_glfw3_create_buffer_and_memory(dev, &dev->vertex_buffer, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + &dev->vertex_memory, max_vertex_buffer); + nk_glfw3_create_buffer_and_memory(dev, &dev->index_buffer, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + &dev->index_memory, max_element_buffer); + nk_glfw3_create_buffer_and_memory( + dev, &dev->uniform_buffer, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + &dev->uniform_memory, sizeof(struct Mat4f)); + + vkMapMemory(dev->logical_device, dev->vertex_memory, 0, max_vertex_buffer, + 0, &dev->mapped_vertex); + vkMapMemory(dev->logical_device, dev->index_memory, 0, max_element_buffer, + 0, &dev->mapped_index); + vkMapMemory(dev->logical_device, dev->uniform_memory, 0, + sizeof(struct Mat4f), 0, &dev->mapped_uniform); + + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_INTERN void nk_glfw3_device_upload_atlas(VkQueue graphics_queue, + const void *image, int width, + int height) { + struct nk_glfw_device *dev = &glfw.vulkan; + + VkImageCreateInfo image_info; + VkResult result; + VkMemoryRequirements mem_reqs; + VkMemoryAllocateInfo alloc_info; + VkBufferCreateInfo buffer_info; + uint8_t *data = 0; + VkCommandBufferBeginInfo begin_info; + VkCommandBuffer command_buffer; + VkImageMemoryBarrier image_memory_barrier; + VkBufferImageCopy buffer_copy_region; + VkImageMemoryBarrier image_shader_memory_barrier; + VkFence fence; + VkFenceCreateInfo fence_create; + VkSubmitInfo submit_info; + VkImageViewCreateInfo image_view_info; + struct { + VkDeviceMemory memory; + VkBuffer buffer; + } staging_buffer; + + memset(&image_info, 0, sizeof(VkImageCreateInfo)); + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = VK_FORMAT_R8G8B8A8_UNORM; + image_info.extent.width = (uint32_t)width; + image_info.extent.height = (uint32_t)height; + image_info.extent.depth = 1; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = + VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + + result = + vkCreateImage(dev->logical_device, &image_info, NULL, &dev->font_image); + NK_ASSERT(result == VK_SUCCESS); + + vkGetImageMemoryRequirements(dev->logical_device, dev->font_image, + &mem_reqs); + + memset(&alloc_info, 0, sizeof(VkMemoryAllocateInfo)); + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &dev->font_memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindImageMemory(dev->logical_device, dev->font_image, + dev->font_memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + memset(&buffer_info, 0, sizeof(VkBufferCreateInfo)); + buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + buffer_info.size = alloc_info.allocationSize; + buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + + result = vkCreateBuffer(dev->logical_device, &buffer_info, NULL, + &staging_buffer.buffer); + NK_ASSERT(result == VK_SUCCESS); + vkGetBufferMemoryRequirements(dev->logical_device, staging_buffer.buffer, + &mem_reqs); + + alloc_info.allocationSize = mem_reqs.size; + alloc_info.memoryTypeIndex = nk_glfw3_find_memory_index( + dev->physical_device, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + result = vkAllocateMemory(dev->logical_device, &alloc_info, NULL, + &staging_buffer.memory); + NK_ASSERT(result == VK_SUCCESS); + result = vkBindBufferMemory(dev->logical_device, staging_buffer.buffer, + staging_buffer.memory, 0); + NK_ASSERT(result == VK_SUCCESS); + + result = vkMapMemory(dev->logical_device, staging_buffer.memory, 0, + alloc_info.allocationSize, 0, (void **)&data); + NK_ASSERT(result == VK_SUCCESS); + memcpy(data, image, width * height * 4); + vkUnmapMemory(dev->logical_device, staging_buffer.memory); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + NK_ASSERT(dev->command_buffers_len > 0); + /* + use the same command buffer as for render as we are regenerating the + buffer during render anyway + */ + command_buffer = dev->command_buffers[0]; + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + + memset(&image_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_memory_barrier.image = dev->font_image; + image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_memory_barrier.subresourceRange.levelCount = 1; + image_memory_barrier.subresourceRange.layerCount = 1; + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, + &image_memory_barrier); + + memset(&buffer_copy_region, 0, sizeof(VkBufferImageCopy)); + buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + buffer_copy_region.imageSubresource.layerCount = 1; + buffer_copy_region.imageExtent.width = (uint32_t)width; + buffer_copy_region.imageExtent.height = (uint32_t)height; + buffer_copy_region.imageExtent.depth = 1; + + vkCmdCopyBufferToImage( + command_buffer, staging_buffer.buffer, dev->font_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + + memset(&image_shader_memory_barrier, 0, sizeof(VkImageMemoryBarrier)); + image_shader_memory_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + image_shader_memory_barrier.image = dev->font_image; + image_shader_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + image_shader_memory_barrier.oldLayout = + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + image_shader_memory_barrier.newLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + image_shader_memory_barrier.subresourceRange.aspectMask = + VK_IMAGE_ASPECT_COLOR_BIT; + image_shader_memory_barrier.subresourceRange.levelCount = 1; + image_shader_memory_barrier.subresourceRange.layerCount = 1; + image_shader_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, + image_shader_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, + NULL, 1, &image_shader_memory_barrier); + + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + memset(&fence_create, 0, sizeof(VkFenceCreateInfo)); + fence_create.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + + result = vkCreateFence(dev->logical_device, &fence_create, NULL, &fence); + NK_ASSERT(result == VK_SUCCESS); + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, fence); + NK_ASSERT(result == VK_SUCCESS); + result = + vkWaitForFences(dev->logical_device, 1, &fence, VK_TRUE, UINT64_MAX); + NK_ASSERT(result == VK_SUCCESS); + + vkDestroyFence(dev->logical_device, fence, NULL); + + vkFreeMemory(dev->logical_device, staging_buffer.memory, NULL); + vkDestroyBuffer(dev->logical_device, staging_buffer.buffer, NULL); + + memset(&image_view_info, 0, sizeof(VkImageViewCreateInfo)); + image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + image_view_info.image = dev->font_image; + image_view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + image_view_info.format = image_info.format; + image_view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + image_view_info.subresourceRange.layerCount = 1; + image_view_info.subresourceRange.levelCount = 1; + + result = vkCreateImageView(dev->logical_device, &image_view_info, NULL, + &dev->font_image_view); + NK_ASSERT(result == VK_SUCCESS); +} + +NK_INTERN void nk_glfw3_destroy_render_resources(struct nk_glfw_device *dev) { + uint32_t i; + + vkDestroyPipeline(dev->logical_device, dev->pipeline, NULL); + vkDestroyPipelineLayout(dev->logical_device, dev->pipeline_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->texture_descriptor_set_layout, NULL); + vkDestroyDescriptorSetLayout(dev->logical_device, + dev->uniform_descriptor_set_layout, NULL); + vkDestroyDescriptorPool(dev->logical_device, dev->descriptor_pool, NULL); + for (i = 0; i < dev->framebuffers_len; i++) { + vkDestroyFramebuffer(dev->logical_device, dev->framebuffers[i], NULL); + } + free(dev->framebuffers); + dev->framebuffers_len = 0; + free(dev->texture_descriptor_sets); + dev->texture_descriptor_sets_len = 0; + vkDestroyRenderPass(dev->logical_device, dev->render_pass, NULL); +} + +NK_API void nk_glfw3_resize(uint32_t framebuffer_width, + uint32_t framebuffer_height) { + struct nk_glfw_device *dev = &glfw.vulkan; + glfwGetWindowSize(glfw.win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(glfw.win, &glfw.display_width, &glfw.display_height); + glfw.fb_scale.x = (float)glfw.display_width / (float)glfw.width; + glfw.fb_scale.y = (float)glfw.display_height / (float)glfw.height; + + nk_glfw3_destroy_render_resources(dev); + nk_glfw3_create_render_resources(dev, framebuffer_width, + framebuffer_height); +} + +NK_API void nk_glfw3_device_destroy(void) { + struct nk_glfw_device *dev = &glfw.vulkan; + + vkDeviceWaitIdle(dev->logical_device); + + nk_glfw3_destroy_render_resources(dev); + + vkFreeCommandBuffers(dev->logical_device, dev->command_pool, + dev->command_buffers_len, dev->command_buffers); + vkDestroyCommandPool(dev->logical_device, dev->command_pool, NULL); + vkDestroySemaphore(dev->logical_device, dev->render_completed, NULL); + + vkUnmapMemory(dev->logical_device, dev->vertex_memory); + vkUnmapMemory(dev->logical_device, dev->index_memory); + vkUnmapMemory(dev->logical_device, dev->uniform_memory); + + vkFreeMemory(dev->logical_device, dev->vertex_memory, NULL); + vkFreeMemory(dev->logical_device, dev->index_memory, NULL); + vkFreeMemory(dev->logical_device, dev->uniform_memory, NULL); + + vkDestroyBuffer(dev->logical_device, dev->vertex_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->index_buffer, NULL); + vkDestroyBuffer(dev->logical_device, dev->uniform_buffer, NULL); + + vkDestroySampler(dev->logical_device, dev->sampler, NULL); + + vkFreeMemory(dev->logical_device, dev->font_memory, NULL); + vkDestroyImage(dev->logical_device, dev->font_image, NULL); + vkDestroyImageView(dev->logical_device, dev->font_image_view, NULL); + + free(dev->command_buffers); + nk_buffer_free(&dev->cmds); +} + +NK_API +void nk_glfw3_shutdown(void) { + nk_font_atlas_clear(&glfw.atlas); + nk_free(&glfw.ctx); + nk_glfw3_device_destroy(); + memset(&glfw, 0, sizeof(glfw)); +} + +NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas) { + nk_font_atlas_init_default(&glfw.atlas); + nk_font_atlas_begin(&glfw.atlas); + *atlas = &glfw.atlas; +} + +NK_API void nk_glfw3_font_stash_end(VkQueue graphics_queue) { + struct nk_glfw_device *dev = &glfw.vulkan; + + const void *image; + int w, h; + image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); + nk_glfw3_device_upload_atlas(graphics_queue, image, w, h); + nk_font_atlas_end(&glfw.atlas, nk_handle_ptr(dev->font_image_view), + &dev->tex_null); + if (glfw.atlas.default_font) { + nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); + } +} + +NK_API void nk_glfw3_new_frame(void) { + int i; + double x, y; + struct nk_context *ctx = &glfw.ctx; + struct GLFWwindow *win = glfw.win; + + nk_input_begin(ctx); + for (i = 0; i < glfw.text_len; ++i) + nk_input_unicode(ctx, glfw.text[i]); + +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + /* optional grabbing behavior */ + if (ctx->input.mouse.grab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); + else if (ctx->input.mouse.ungrab) + glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif + + nk_input_key(ctx, NK_KEY_DEL, + glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_ENTER, + glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_BACKSPACE, + glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_DOWN, + glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_START, + glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_END, + glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_DOWN, + glfwGetKey(win, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SCROLL_UP, + glfwGetKey(win, GLFW_KEY_PAGE_UP) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_SHIFT, + glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); + + if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || + glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { + nk_input_key(ctx, NK_KEY_COPY, + glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_PASTE, + glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_CUT, + glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_UNDO, + glfwGetKey(win, GLFW_KEY_Z) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_REDO, + glfwGetKey(win, GLFW_KEY_R) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_START, + glfwGetKey(win, GLFW_KEY_B) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_LINE_END, + glfwGetKey(win, GLFW_KEY_E) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_TEXT_SELECT_ALL, + glfwGetKey(win, GLFW_KEY_A) == GLFW_PRESS); + } else { + nk_input_key(ctx, NK_KEY_LEFT, + glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_RIGHT, + glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); + nk_input_key(ctx, NK_KEY_COPY, 0); + nk_input_key(ctx, NK_KEY_PASTE, 0); + nk_input_key(ctx, NK_KEY_CUT, 0); + nk_input_key(ctx, NK_KEY_SHIFT, 0); + } + + glfwGetCursorPos(win, &x, &y); + nk_input_motion(ctx, (int)x, (int)y); +#ifdef NK_GLFW_GL4_MOUSE_GRABBING + if (ctx->input.mouse.grabbed) { + glfwSetCursorPos(glfw.win, ctx->input.mouse.prev.x, + ctx->input.mouse.prev.y); + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +#endif + nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, + glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == + GLFW_PRESS); + nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)glfw.double_click_pos.x, + (int)glfw.double_click_pos.y, glfw.is_double_click_down); + nk_input_scroll(ctx, glfw.scroll); + nk_input_end(&glfw.ctx); + glfw.text_len = 0; + glfw.scroll = nk_vec2(0, 0); +} + +NK_INTERN void update_texture_descriptor_set( + struct nk_glfw_device *dev, + struct nk_vulkan_texture_descriptor_set *texture_descriptor_set, + VkImageView image_view) { + VkDescriptorImageInfo descriptor_image_info; + VkWriteDescriptorSet descriptor_write; + + texture_descriptor_set->image_view = image_view; + + memset(&descriptor_image_info, 0, sizeof(VkDescriptorImageInfo)); + descriptor_image_info.sampler = dev->sampler; + descriptor_image_info.imageView = texture_descriptor_set->image_view; + descriptor_image_info.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + memset(&descriptor_write, 0, sizeof(VkWriteDescriptorSet)); + descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptor_write.dstSet = texture_descriptor_set->descriptor_set; + descriptor_write.dstBinding = 0; + descriptor_write.dstArrayElement = 0; + descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + descriptor_write.descriptorCount = 1; + descriptor_write.pImageInfo = &descriptor_image_info; + + vkUpdateDescriptorSets(dev->logical_device, 1, &descriptor_write, 0, NULL); +} + +NK_API +VkSemaphore nk_glfw3_render(VkQueue graphics_queue, uint32_t buffer_index, + VkSemaphore wait_semaphore, + enum nk_anti_aliasing AA) { + struct nk_glfw_device *dev = &glfw.vulkan; + struct nk_buffer vbuf, ebuf; + + struct Mat4f projection = { + {2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, + 0.0f, -1.0f, 1.0f, 0.0f, 1.0f}, + }; + + VkCommandBufferBeginInfo begin_info; + VkClearValue clear_value = {{{0.0f, 0.0f, 0.0f, 0.0f}}}; + VkRenderPassBeginInfo render_pass_begin_nfo; + VkCommandBuffer command_buffer; + VkResult result; + VkViewport viewport; + + VkDeviceSize doffset = 0; + VkImageView current_texture = NULL; + uint32_t index_offset = 0; + VkRect2D scissor; + uint32_t wait_semaphore_count; + VkSemaphore *wait_semaphores; + VkPipelineStageFlags wait_stage = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo submit_info; + + projection.m[0] /= glfw.width; + projection.m[5] /= glfw.height; + + memcpy(dev->mapped_uniform, &projection, sizeof(projection)); + + memset(&begin_info, 0, sizeof(VkCommandBufferBeginInfo)); + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + memset(&render_pass_begin_nfo, 0, sizeof(VkRenderPassBeginInfo)); + render_pass_begin_nfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; + render_pass_begin_nfo.renderPass = dev->render_pass; + render_pass_begin_nfo.renderArea.extent.width = (uint32_t)glfw.width; + render_pass_begin_nfo.renderArea.extent.height = (uint32_t)glfw.height; + render_pass_begin_nfo.clearValueCount = 1; + render_pass_begin_nfo.pClearValues = &clear_value; + render_pass_begin_nfo.framebuffer = dev->framebuffers[buffer_index]; + + command_buffer = dev->command_buffers[buffer_index]; + + result = vkBeginCommandBuffer(command_buffer, &begin_info); + NK_ASSERT(result == VK_SUCCESS); + vkCmdBeginRenderPass(command_buffer, &render_pass_begin_nfo, + VK_SUBPASS_CONTENTS_INLINE); + + memset(&viewport, 0, sizeof(VkViewport)); + viewport.width = (float)glfw.width; + viewport.height = (float)glfw.height; + viewport.maxDepth = 1.0f; + vkCmdSetViewport(command_buffer, 0, 1, &viewport); + + vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 0, 1, + &dev->uniform_descriptor_set, 0, NULL); + { + /* convert from command queue into draw list and draw to screen */ + const struct nk_draw_command *cmd; + /* load draw vertices & elements directly into vertex + element buffer + */ + { + /* fill convert configuration */ + struct nk_convert_config config; + static const struct nk_draw_vertex_layout_element vertex_layout[] = + {{NK_VERTEX_POSITION, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, position)}, + {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, + NK_OFFSETOF(struct nk_glfw_vertex, uv)}, + {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, + NK_OFFSETOF(struct nk_glfw_vertex, col)}, + {NK_VERTEX_LAYOUT_END}}; + NK_MEMSET(&config, 0, sizeof(config)); + config.vertex_layout = vertex_layout; + config.vertex_size = sizeof(struct nk_glfw_vertex); + config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); + config.tex_null = dev->tex_null; + config.circle_segment_count = 22; + config.curve_segment_count = 22; + config.arc_segment_count = 22; + config.global_alpha = 1.0f; + config.shape_AA = AA; + config.line_AA = AA; + + /* setup buffers to load vertices and elements */ + nk_buffer_init_fixed(&vbuf, dev->mapped_vertex, + (size_t)dev->max_vertex_buffer); + nk_buffer_init_fixed(&ebuf, dev->mapped_index, + (size_t)dev->max_element_buffer); + nk_convert(&glfw.ctx, &dev->cmds, &vbuf, &ebuf, &config); + } + + /* iterate over and execute each draw command */ + + vkCmdBindVertexBuffers(command_buffer, 0, 1, &dev->vertex_buffer, + &doffset); + vkCmdBindIndexBuffer(command_buffer, dev->index_buffer, 0, + VK_INDEX_TYPE_UINT16); + + nk_draw_foreach(cmd, &glfw.ctx, &dev->cmds) { + if (!cmd->texture.ptr) { + continue; + } + if (cmd->texture.ptr && cmd->texture.ptr != current_texture) { + int found = 0; + uint32_t i; + for (i = 0; i < dev->texture_descriptor_sets_len; i++) { + if (dev->texture_descriptor_sets[i].image_view == + cmd->texture.ptr) { + found = 1; + break; + } + } + + if (!found) { + update_texture_descriptor_set( + dev, &dev->texture_descriptor_sets[i], + (VkImageView)cmd->texture.ptr); + dev->texture_descriptor_sets_len++; + } + vkCmdBindDescriptorSets( + command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, + dev->pipeline_layout, 1, 1, + &dev->texture_descriptor_sets[i].descriptor_set, 0, NULL); + } + + if (!cmd->elem_count) + continue; + + scissor.offset.x = (int32_t)(NK_MAX(cmd->clip_rect.x, 0.f)); + scissor.offset.y = (int32_t)(NK_MAX(cmd->clip_rect.y, 0.f)); + scissor.extent.width = (uint32_t)(cmd->clip_rect.w); + scissor.extent.height = (uint32_t)(cmd->clip_rect.h); + vkCmdSetScissor(command_buffer, 0, 1, &scissor); + vkCmdDrawIndexed(command_buffer, cmd->elem_count, 1, index_offset, + 0, 0); + index_offset += cmd->elem_count; + } + nk_clear(&glfw.ctx); + } + + vkCmdEndRenderPass(command_buffer); + result = vkEndCommandBuffer(command_buffer); + NK_ASSERT(result == VK_SUCCESS); + + if (wait_semaphore) { + wait_semaphore_count = 1; + wait_semaphores = &wait_semaphore; + } else { + wait_semaphore_count = 0; + wait_semaphores = NULL; + } + + memset(&submit_info, 0, sizeof(VkSubmitInfo)); + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + submit_info.pWaitDstStageMask = &wait_stage; + submit_info.waitSemaphoreCount = wait_semaphore_count; + submit_info.pWaitSemaphores = wait_semaphores; + submit_info.signalSemaphoreCount = 1; + submit_info.pSignalSemaphores = &dev->render_completed; + + result = vkQueueSubmit(graphics_queue, 1, &submit_info, NULL); + NK_ASSERT(result == VK_SUCCESS); + + return dev->render_completed; +} + +NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint) { + (void)win; + if (glfw.text_len < NK_GLFW_TEXT_MAX) + glfw.text[glfw.text_len++] = codepoint; +} + +NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, + double yoff) { + (void)win; + (void)xoff; + glfw.scroll.x += (float)xoff; + glfw.scroll.y += (float)yoff; +} + +NK_API void nk_glfw3_mouse_button_callback(GLFWwindow *window, int button, + int action, int mods) { + double x, y; + NK_UNUSED(mods); + if (button != GLFW_MOUSE_BUTTON_LEFT) + return; + glfwGetCursorPos(window, &x, &y); + if (action == GLFW_PRESS) { + double dt = glfwGetTime() - glfw.last_button_click; + if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { + glfw.is_double_click_down = nk_true; + glfw.double_click_pos = nk_vec2((float)x, (float)y); + } + glfw.last_button_click = glfwGetTime(); + } else + glfw.is_double_click_down = nk_false; +} + +NK_INTERN void nk_glfw3_clipboard_paste(nk_handle usr, + struct nk_text_edit *edit) { + const char *text = glfwGetClipboardString(glfw.win); + if (text) + nk_textedit_paste(edit, text, nk_strlen(text)); + (void)usr; +} + +NK_INTERN void nk_glfw3_clipboard_copy(nk_handle usr, const char *text, + int len) { + char *str = 0; + (void)usr; + if (!len) + return; + str = (char *)malloc((size_t)len + 1); + if (!str) + return; + memcpy(str, text, (size_t)len); + str[len] = '\0'; + glfwSetClipboardString(glfw.win, str); + free(str); +} + +NK_API struct nk_context * +nk_glfw3_init(GLFWwindow *win, VkDevice logical_device, + VkPhysicalDevice physical_device, + uint32_t graphics_queue_family_index, VkImageView *image_views, + uint32_t image_views_len, VkFormat color_format, + enum nk_glfw_init_state init_state, + VkDeviceSize max_vertex_buffer, VkDeviceSize max_element_buffer) { + memset(&glfw, 0, sizeof(struct nk_glfw)); + glfw.win = win; + if (init_state == NK_GLFW3_INSTALL_CALLBACKS) { + glfwSetScrollCallback(win, nk_gflw3_scroll_callback); + glfwSetCharCallback(win, nk_glfw3_char_callback); + glfwSetMouseButtonCallback(win, nk_glfw3_mouse_button_callback); + } + nk_init_default(&glfw.ctx, 0); + glfw.ctx.clip.copy = nk_glfw3_clipboard_copy; + glfw.ctx.clip.paste = nk_glfw3_clipboard_paste; + glfw.ctx.clip.userdata = nk_handle_ptr(0); + glfw.last_button_click = 0; + + glfwGetWindowSize(win, &glfw.width, &glfw.height); + glfwGetFramebufferSize(win, &glfw.display_width, &glfw.display_height); + + nk_glfw3_device_create(logical_device, physical_device, + graphics_queue_family_index, image_views, + image_views_len, color_format, max_vertex_buffer, + max_element_buffer, (uint32_t)glfw.display_width, + (uint32_t)glfw.display_height); + + glfw.is_double_click_down = nk_false; + glfw.double_click_pos = nk_vec2(0, 0); + + return &glfw.ctx; +} + +#endif diff --git a/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag b/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag new file mode 100644 index 0000000..376ad16 --- /dev/null +++ b/demo/glfw_vulkan/src/nuklearshaders/nuklear.frag @@ -0,0 +1,13 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(binding = 0, set = 1) uniform sampler2D currentTexture; + +layout(location = 0) in vec4 fragColor; +layout(location = 1) in vec2 fragUv; +layout(location = 0) out vec4 outColor; + +void main() { + vec4 texColor = texture(currentTexture, fragUv); + outColor = fragColor * texColor; +} diff --git a/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert b/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert new file mode 100644 index 0000000..3eee82d --- /dev/null +++ b/demo/glfw_vulkan/src/nuklearshaders/nuklear.vert @@ -0,0 +1,23 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +out gl_PerVertex { + vec4 gl_Position; +}; + +layout(binding = 0) uniform UniformBufferObject { + mat4 projection; +} ubo; + +layout(location = 0) in vec2 position; +layout(location = 1) in vec2 uv; +layout(location = 2) in uvec4 color; +layout(location = 0) out vec4 fragColor; +layout(location = 1) out vec2 fragUv; + +void main() { + gl_Position = ubo.projection * vec4(position, 0.0, 1.0); + gl_Position.y = -gl_Position.y; + fragColor = vec4(color[0]/255.0, color[1]/255.0, color[2]/255.0, color[3]/255.0); + fragUv = uv; +} diff --git a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h b/demo/sdl2surface_rawfb/sdl2surface_rawfb.h index 6e2eb59..7b4b1cf 100644 --- a/demo/sdl2surface_rawfb/sdl2surface_rawfb.h +++ b/demo/sdl2surface_rawfb/sdl2surface_rawfb.h @@ -49,6 +49,10 @@ void nk_sdlsurface_shutdown(struct sdlsurface_context *sdlsurfa * =============================================================== */ #ifdef NK_SDLSURFACE_IMPLEMENTATION +#include +#include +#include + struct sdlsurface_context { struct nk_context ctx; struct nk_rect scissors; diff --git a/demo/sdl_opengl2/main.c b/demo/sdl_opengl2/main.c index 45c51d2..438f2d3 100644 --- a/demo/sdl_opengl2/main.c +++ b/demo/sdl_opengl2/main.c @@ -139,6 +139,7 @@ main(int argc, char *argv[]) if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); /* GUI */ diff --git a/demo/sdl_opengl2/nuklear_sdl_gl2.h b/demo/sdl_opengl2/nuklear_sdl_gl2.h index 0c6a2fb..fbc7ec7 100644 --- a/demo/sdl_opengl2/nuklear_sdl_gl2.h +++ b/demo/sdl_opengl2/nuklear_sdl_gl2.h @@ -30,6 +30,8 @@ NK_API void nk_sdl_shutdown(void); * =============================================================== */ #ifdef NK_SDL_GL2_IMPLEMENTATION +#include +#include struct nk_sdl_device { struct nk_buffer cmds; @@ -231,22 +233,27 @@ nk_sdl_font_stash_end(void) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ + SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_opengl3/main.c b/demo/sdl_opengl3/main.c index e039a2f..44c8c74 100644 --- a/demo/sdl_opengl3/main.c +++ b/demo/sdl_opengl3/main.c @@ -149,7 +149,9 @@ int main(int argc, char *argv[]) while (SDL_PollEvent(&evt)) { if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); - } nk_input_end(ctx); + } + nk_sdl_handle_grab(); /* optional grabbing behavior */ + nk_input_end(ctx); /* GUI */ if (nk_begin(ctx, "Demo", nk_rect(50, 50, 230, 250), diff --git a/demo/sdl_opengl3/nuklear_sdl_gl3.h b/demo/sdl_opengl3/nuklear_sdl_gl3.h index cac8629..6c9d4b1 100644 --- a/demo/sdl_opengl3/nuklear_sdl_gl3.h +++ b/demo/sdl_opengl3/nuklear_sdl_gl3.h @@ -36,6 +36,8 @@ NK_API void nk_sdl_device_create(void); */ #ifdef NK_SDL_GL3_IMPLEMENTATION +#include +#include #include struct nk_sdl_device { @@ -340,22 +342,27 @@ nk_sdl_font_stash_end(void) } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ + SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_opengles2/main.c b/demo/sdl_opengles2/main.c index b114159..9ef90a7 100644 --- a/demo/sdl_opengles2/main.c +++ b/demo/sdl_opengles2/main.c @@ -92,6 +92,7 @@ MainLoop(void* loopArg){ if (evt.type == SDL_QUIT) running = nk_false; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); diff --git a/demo/sdl_opengles2/nuklear_sdl_gles2.h b/demo/sdl_opengles2/nuklear_sdl_gles2.h index 595d7a7..6f46d52 100644 --- a/demo/sdl_opengles2/nuklear_sdl_gles2.h +++ b/demo/sdl_opengles2/nuklear_sdl_gles2.h @@ -38,7 +38,8 @@ NK_API void nk_sdl_device_create(void); * =============================================================== */ #ifdef NK_SDL_GLES2_IMPLEMENTATION - +#include +#include #include struct nk_sdl_device { @@ -341,22 +342,27 @@ nk_sdl_font_stash_end(void) } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ + SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sdl_renderer/main.c b/demo/sdl_renderer/main.c index 940ea84..a4a0f28 100644 --- a/demo/sdl_renderer/main.c +++ b/demo/sdl_renderer/main.c @@ -177,6 +177,7 @@ main(int argc, char *argv[]) if (evt.type == SDL_QUIT) goto cleanup; nk_sdl_handle_event(&evt); } + nk_sdl_handle_grab(); /* optional grabbing behavior */ nk_input_end(ctx); /* GUI */ diff --git a/demo/sdl_renderer/nuklear_sdl_renderer.h b/demo/sdl_renderer/nuklear_sdl_renderer.h index 672b81b..fb8596f 100644 --- a/demo/sdl_renderer/nuklear_sdl_renderer.h +++ b/demo/sdl_renderer/nuklear_sdl_renderer.h @@ -39,8 +39,8 @@ NK_API void nk_sdl_shutdown(void); * =============================================================== */ #ifdef NK_SDL_RENDERER_IMPLEMENTATION - -#include +#include +#include struct nk_sdl_device { struct nk_buffer cmds; @@ -264,22 +264,27 @@ nk_sdl_font_stash_end(void) nk_style_set_font(&sdl.ctx, &sdl.atlas.default_font->handle); } +NK_API void +nk_sdl_handle_grab(void) +{ + struct nk_context *ctx = &sdl.ctx; + if (ctx->input.mouse.grab) { + SDL_SetRelativeMouseMode(SDL_TRUE); + } else if (ctx->input.mouse.ungrab) { + /* better support for older SDL by setting mode first; causes an extra mouse motion event */ + SDL_SetRelativeMouseMode(SDL_FALSE); + SDL_WarpMouseInWindow(sdl.win, (int)ctx->input.mouse.prev.x, (int)ctx->input.mouse.prev.y); + } else if (ctx->input.mouse.grabbed) { + ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; + ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; + } +} + NK_API int nk_sdl_handle_event(SDL_Event *evt) { struct nk_context *ctx = &sdl.ctx; - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) { - SDL_SetRelativeMouseMode(SDL_TRUE); - ctx->input.mouse.grab = 0; - } else if (ctx->input.mouse.ungrab) { - int x = (int)ctx->input.mouse.prev.x, y = (int)ctx->input.mouse.prev.y; - SDL_SetRelativeMouseMode(SDL_FALSE); - SDL_WarpMouseInWindow(sdl.win, x, y); - ctx->input.mouse.ungrab = 0; - } - switch(evt->type) { case SDL_KEYUP: /* KEYUP & KEYDOWN share same routine */ diff --git a/demo/sfml_opengl2/Readme.md b/demo/sfml_opengl2/Readme.md index e3879c0..ac055d6 100644 --- a/demo/sfml_opengl2/Readme.md +++ b/demo/sfml_opengl2/Readme.md @@ -6,4 +6,4 @@ This backend provides support for [SFML 2.4](http://www.sfml-dev.org). It will w You have to edit the Makefile provided so that you can build the demo. Edit the SFML_DIR variable to point to your SFML root folder. This will be the folder to which SFML was installed and contains the lib and include folders. -On Linux there is an extra step. You need to install the the udev development files. +On Linux there is an extra step. You need to install the udev development files. diff --git a/demo/sfml_opengl2/nuklear_sfml_gl2.h b/demo/sfml_opengl2/nuklear_sfml_gl2.h index f168bab..5677405 100644 --- a/demo/sfml_opengl2/nuklear_sfml_gl2.h +++ b/demo/sfml_opengl2/nuklear_sfml_gl2.h @@ -31,6 +31,8 @@ NK_API void nk_sfml_shutdown(void); * =============================================================== */ #ifdef NK_SFML_GL2_IMPLEMENTATION +#include +#include struct nk_sfml_device { struct nk_buffer cmds; diff --git a/demo/sfml_opengl3/Readme.md b/demo/sfml_opengl3/Readme.md index ac03e75..4336fce 100644 --- a/demo/sfml_opengl3/Readme.md +++ b/demo/sfml_opengl3/Readme.md @@ -8,4 +8,4 @@ This backend uses Glad to handle OpenGL extensions. You can download the Glad fi Once SFML and Glad have been installed on your system you have to edit the Makefile provided so that you can build the demo. There are two variables that need to be edited: SFML_DIR and GLAD_DIR. Make these point to your SFML root folder and Glad root folder respectively. -On Linux there is an extra step. You need to install the the udev development files. +On Linux there is an extra step. You need to install the udev development files. diff --git a/demo/sfml_opengl3/nuklear_sfml_gl3.h b/demo/sfml_opengl3/nuklear_sfml_gl3.h index 286cfc1..c58bde7 100644 --- a/demo/sfml_opengl3/nuklear_sfml_gl3.h +++ b/demo/sfml_opengl3/nuklear_sfml_gl3.h @@ -38,7 +38,8 @@ NK_API void nk_sfml_device_destroy(void); * =============================================================== */ #ifdef NK_SFML_GL3_IMPLEMENTATION - +#include +#include #include struct nk_sfml_device { diff --git a/demo/wayland_rawfb/nuklear_raw_wayland.h b/demo/wayland_rawfb/nuklear_raw_wayland.h index 49082c5..1a465fc 100644 --- a/demo/wayland_rawfb/nuklear_raw_wayland.h +++ b/demo/wayland_rawfb/nuklear_raw_wayland.h @@ -1,6 +1,10 @@ #ifndef NK_RAW_WAYLAND_H_ #define NK_RAW_WAYLAND_H_ +#include +#include +#include + #define WIDTH 800 #define HEIGHT 600 diff --git a/demo/x11/nuklear_xlib.h b/demo/x11/nuklear_xlib.h index 9b3a861..28fb4cc 100644 --- a/demo/x11/nuklear_xlib.h +++ b/demo/x11/nuklear_xlib.h @@ -44,6 +44,9 @@ NK_API void nk_xfont_del(Display *dpy, XFont *font); * =============================================================== */ #ifdef NK_XLIB_IMPLEMENTATION +#include +#include +#include #include #include #include diff --git a/demo/x11_opengl3/nuklear_xlib_gl3.h b/demo/x11_opengl3/nuklear_xlib_gl3.h index 9dd0181..c343bb5 100644 --- a/demo/x11_opengl3/nuklear_xlib_gl3.h +++ b/demo/x11_opengl3/nuklear_xlib_gl3.h @@ -32,6 +32,7 @@ NK_API void nk_x11_device_destroy(void); * =============================================================== */ #ifdef NK_XLIB_GL3_IMPLEMENTATION +#include #include #include #include diff --git a/demo/x11_rawfb/nuklear_rawfb.h b/demo/x11_rawfb/nuklear_rawfb.h index ce84222..6aece67 100644 --- a/demo/x11_rawfb/nuklear_rawfb.h +++ b/demo/x11_rawfb/nuklear_rawfb.h @@ -55,6 +55,10 @@ NK_API void nk_rawfb_resize_fb(struct rawfb_context *rawfb, voi * =============================================================== */ #ifdef NK_RAWFB_IMPLEMENTATION +#include +#include +#include + struct rawfb_image { void *pixels; int w, h, pitch; diff --git a/demo/x11_rawfb/nuklear_xlib.h b/demo/x11_rawfb/nuklear_xlib.h index 0d23135..3174e24 100644 --- a/demo/x11_rawfb/nuklear_xlib.h +++ b/demo/x11_rawfb/nuklear_xlib.h @@ -49,6 +49,9 @@ NK_API void nk_xlib_shutdown(void); * =============================================================== */ #ifdef NK_XLIBSHM_IMPLEMENTATION +#include +#include +#include #include #include #include diff --git a/demo/x11_xft/nuklear_xlib.h b/demo/x11_xft/nuklear_xlib.h index 9526e3e..f0fb074 100644 --- a/demo/x11_xft/nuklear_xlib.h +++ b/demo/x11_xft/nuklear_xlib.h @@ -48,6 +48,9 @@ NK_API void nk_xfont_del(Display *dpy, XFont *font); * =============================================================== */ #ifdef NK_XLIB_IMPLEMENTATION +#include +#include +#include #include #include #include diff --git a/doc/index.html b/doc/index.html index 919cd95..aa18a37 100644 --- a/doc/index.html +++ b/doc/index.html @@ -886,7 +886,7 @@ NK_WINDOW_NO_INPUT | Prevents window of scaling, moving or getting focu #### nk_collapse_states State | Description ----------------|----------------------------------------------------------- -__NK_MINIMIZED__| UI section is collased and not visible until maximized +__NK_MINIMIZED__| UI section is collapsed and not visible until maximized __NK_MAXIMIZED__| UI section is extended and visible until minimized

#### nk_begin @@ -1267,7 +1267,7 @@ Parameter | Description __ctx__ | Must point to an previously initialized `nk_context` struct __name__ | Identifier of the window to either hide or show __state__ | state with either visible or hidden to modify the window with -__cond__ | condition that has to be met to actually commit the visbility state change +__cond__ | condition that has to be met to actually commit the visibility state change ### Layouting Layouting in general describes placing widget inside a window with position and size. While in this particular implementation there are five different APIs for layouting @@ -1306,7 +1306,7 @@ functions should be fine. if the owning window grows in width. So the number of columns dictates the size of each widget dynamically by formula: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c - widget_width = (window_width - padding - spacing) * (1/colum_count) + widget_width = (window_width - padding - spacing) * (1/column_count) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Just like all other layouting APIs if you define more widget than columns this library will allocate a new row and keep all layouting parameters previously @@ -2760,7 +2760,7 @@ X...XXXXXXXXXXXXX...X - " dynamic and static widgets. - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -- 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +- 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -2898,7 +2898,7 @@ X...XXXXXXXXXXXXX...X - " precision. - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading - to wrong wiget width calculation which results in widgets falsely + to wrong widget width calculation which results in widgets falsely becoming tagged as not inside window and cannot be accessed. - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/example/file_browser.c b/example/file_browser.c index 6bf23c2..30f2a46 100644 --- a/example/file_browser.c +++ b/example/file_browser.c @@ -345,7 +345,8 @@ media_init(struct media *media) static void file_browser_reload_directory_content(struct file_browser *browser, const char *path) { - strncpy(browser->directory, path, MAX_PATH_LEN); + const size_t path_len = nk_strlen(path) + 1; + NK_MEMCPY(browser->directory, path, MIN(path_len, MAX_PATH_LEN)); browser->directory[MAX_PATH_LEN - 1] = 0; dir_free_list(browser->files, browser->file_count); dir_free_list(browser->directories, browser->dir_count); diff --git a/nuklear.h b/nuklear.h index 9b06398..c964f7a 100644 --- a/nuklear.h +++ b/nuklear.h @@ -1463,7 +1463,7 @@ NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command* /// #### nk_collapse_states /// State | Description /// ----------------|----------------------------------------------------------- -/// __NK_MINIMIZED__| UI section is collased and not visible until maximized +/// __NK_MINIMIZED__| UI section is collapsed and not visible until maximized /// __NK_MAXIMIZED__| UI section is extended and visible until minimized ///

*/ @@ -2001,11 +2001,11 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __ctx__ | Must point to an previously initialized `nk_context` struct /// __name__ | Identifier of the window to either hide or show /// __state__ | state with either visible or hidden to modify the window with -/// __cond__ | condition that has to be met to actually commit the visbility state change +/// __cond__ | condition that has to be met to actually commit the visibility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); /*/// #### nk_window_show_if -/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// Line for visual separation. Draws a line with thickness determined by the current row height. /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -2069,7 +2069,7 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// the size of each widget dynamically by formula: /// /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// widget_width = (window_width - padding - spacing) * (1/colum_count) +/// widget_width = (window_width - padding - spacing) * (1/column_count) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// Just like all other layouting APIs if you define more widget than columns this @@ -2290,6 +2290,21 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space /// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates */ + +enum nk_widget_align { + NK_WIDGET_ALIGN_LEFT = 0x01, + NK_WIDGET_ALIGN_CENTERED = 0x02, + NK_WIDGET_ALIGN_RIGHT = 0x04, + NK_WIDGET_ALIGN_TOP = 0x08, + NK_WIDGET_ALIGN_MIDDLE = 0x10, + NK_WIDGET_ALIGN_BOTTOM = 0x20 +}; +enum nk_widget_alignment { + NK_WIDGET_LEFT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_LEFT, + NK_WIDGET_CENTERED = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_CENTERED, + NK_WIDGET_RIGHT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_RIGHT +}; + /*/// #### nk_layout_set_min_row_height /// Sets the currently used minimum row height. /// !!! WARNING @@ -3089,7 +3104,8 @@ NK_API void nk_list_view_end(struct nk_list_view*); enum nk_widget_layout_states { NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ - NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ + NK_WIDGET_ROM, /* The widget is partially visible and cannot be updated */ + NK_WIDGET_DISABLED /* The widget is manually disabled and acts like NK_WIDGET_ROM */ }; enum nk_widget_states { NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), @@ -3112,6 +3128,8 @@ NK_API nk_bool nk_widget_is_hovered(struct nk_context*); NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down); NK_API void nk_spacing(struct nk_context*, int cols); +NK_API void nk_widget_disable_begin(struct nk_context* ctx); +NK_API void nk_widget_disable_end(struct nk_context* ctx); /* ============================================================================= * * TEXT @@ -3189,10 +3207,13 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * ============================================================================= */ NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_check_text_align(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); /* ============================================================================= @@ -3201,9 +3222,13 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * * ============================================================================= */ NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); +NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE @@ -3606,6 +3631,9 @@ NK_API void nk_menu_end(struct nk_context*); * STYLE * * ============================================================================= */ + +#define NK_WIDGET_DISABLED_FACTOR 0.5f + enum nk_style_colors { NK_COLOR_TEXT, NK_COLOR_WINDOW, @@ -3682,6 +3710,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); +NK_API struct nk_color nk_rgb_factor(struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); @@ -4902,6 +4931,8 @@ struct nk_style_item { struct nk_style_text { struct nk_color color; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_button { @@ -4910,6 +4941,7 @@ struct nk_style_button { struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; + float color_factor_background; /* text */ struct nk_color text_background; @@ -4917,6 +4949,7 @@ struct nk_style_button { struct nk_color text_hover; struct nk_color text_active; nk_flags text_alignment; + float color_factor_text; /* properties */ float border; @@ -4924,6 +4957,7 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4954,6 +4988,8 @@ struct nk_style_toggle { struct nk_vec2 touch_padding; float spacing; float border; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4989,6 +5025,8 @@ struct nk_style_selectable { struct nk_vec2 padding; struct nk_vec2 touch_padding; struct nk_vec2 image_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -5021,6 +5059,8 @@ struct nk_style_slider { struct nk_vec2 padding; struct nk_vec2 spacing; struct nk_vec2 cursor_size; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -5054,6 +5094,8 @@ struct nk_style_progress { float cursor_border; float cursor_rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -5080,6 +5122,8 @@ struct nk_style_scrollbar { float border_cursor; float rounding_cursor; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -5126,6 +5170,8 @@ struct nk_style_edit { struct nk_vec2 scrollbar_size; struct nk_vec2 padding; float row_padding; + float color_factor; + float disabled_factor; }; struct nk_style_property { @@ -5148,6 +5194,8 @@ struct nk_style_property { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; struct nk_style_edit edit; struct nk_style_button inc_button; @@ -5170,6 +5218,9 @@ struct nk_style_chart { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; + nk_bool show_markers; }; struct nk_style_combo { @@ -5201,6 +5252,8 @@ struct nk_style_combo { struct nk_vec2 content_padding; struct nk_vec2 button_padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; struct nk_style_tab { @@ -5223,6 +5276,8 @@ struct nk_style_tab { float indent; struct nk_vec2 padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; enum nk_style_header_align { @@ -5356,6 +5411,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; + nk_bool show_markers; }; struct nk_chart { @@ -5505,6 +5561,7 @@ struct nk_window { struct nk_popup_state popup; struct nk_edit_state edit; unsigned int scrolled; + nk_bool widgets_disabled; struct nk_table *tables; unsigned int table_count; @@ -6030,9 +6087,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); @@ -6125,14 +6182,14 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifndef STBTT_malloc static void* nk_stbtt_malloc(nk_size size, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - return alloc->alloc(alloc->userdata, 0, size); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + return alloc->alloc(alloc->userdata, 0, size); } static void nk_stbtt_free(void *ptr, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - alloc->free(alloc->userdata, ptr); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + alloc->free(alloc->userdata, ptr); } #define STBTT_malloc(x,u) nk_stbtt_malloc(x,u) @@ -7603,6 +7660,16 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color +nk_rgb_factor(struct nk_color col, const float factor) +{ + if (factor == 1.0f) + return col; + col.r = (nk_byte)(col.r * factor); + col.g = (nk_byte)(col.g * factor); + col.b = (nk_byte)(col.b * factor); + return col; +} +NK_API struct nk_color nk_rgba(int r, int g, int b, int a) { struct nk_color ret; @@ -11077,7 +11144,7 @@ static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0 if (node->y > min_y) { /* raise min_y higher. */ /* we've accounted for all waste up to min_y, */ - /* but we'll now add more waste for everything we've visted */ + /* but we'll now add more waste for everything we've visited */ waste_area += visited_width * (node->y - min_y); min_y = node->y; /* the first time through, visited_width might be reduced */ @@ -11232,7 +11299,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i /* insert the new node into the right starting point, and */ /* let 'cur' point to the remaining nodes needing to be */ - /* stiched back in */ + /* stitched back in */ cur = *res.prev_link; if (cur->x < res.x) { @@ -18240,27 +18307,32 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text = &style->text; text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); + text->color_factor = 1.0f; + text->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* default button */ button = &style->button; nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_BORDER]; - button->text_background = table[NK_COLOR_BUTTON]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->image_padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f, 0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 4.0f; - button->draw_begin = 0; - button->draw_end = 0; + button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); + button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); + button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); + button->border_color = table[NK_COLOR_BORDER]; + button->text_background = table[NK_COLOR_BUTTON]; + button->text_normal = table[NK_COLOR_TEXT]; + button->text_hover = table[NK_COLOR_TEXT]; + button->text_active = table[NK_COLOR_TEXT]; + button->padding = nk_vec2(2.0f,2.0f); + button->image_padding = nk_vec2(0.0f,0.0f); + button->touch_padding = nk_vec2(0.0f, 0.0f); + button->userdata = nk_handle_ptr(0); + button->text_alignment = NK_TEXT_CENTERED; + button->border = 1.0f; + button->rounding = 4.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + button->draw_begin = 0; + button->draw_end = 0; /* contextual button */ button = &style->contextual_button; @@ -18279,6 +18351,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18299,6 +18374,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18320,6 +18398,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* option toggle */ toggle = &style->option; @@ -18339,6 +18419,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* selectable */ select = &style->selectable; @@ -18360,6 +18442,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->touch_padding = nk_vec2(0,0); select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; + select->color_factor = 1.0f; + select->disabled_factor = NK_WIDGET_DISABLED_FACTOR; select->draw_begin = 0; select->draw_end = 0; @@ -18385,6 +18469,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->show_buttons = nk_false; slider->bar_height = 8; slider->rounding = 0; + slider->color_factor = 1.0f; + slider->disabled_factor = NK_WIDGET_DISABLED_FACTOR; slider->draw_begin = 0; slider->draw_end = 0; @@ -18404,6 +18490,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -18425,6 +18514,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->border = 0; prog->cursor_rounding = 0; prog->cursor_border = 0; + prog->color_factor = 1.0f; + prog->disabled_factor = NK_WIDGET_DISABLED_FACTOR; prog->draw_begin = 0; prog->draw_end = 0; @@ -18448,6 +18539,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->rounding = 0; scroll->border_cursor = 0; scroll->rounding_cursor = 0; + scroll->color_factor = 1.0f; + scroll->disabled_factor = NK_WIDGET_DISABLED_FACTOR; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -18468,6 +18561,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -18499,6 +18595,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 4; edit->border = 1; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property */ property = &style->property; @@ -18518,6 +18616,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->rounding = 10; property->draw_begin = 0; property->draw_end = 0; + property->color_factor = 1.0f; + property->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property buttons */ button = &style->property.dec_button; @@ -18536,6 +18636,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -18562,6 +18665,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 8; edit->border = 0; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* chart */ chart = &style->chart; @@ -18573,6 +18678,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->padding = nk_vec2(4,4); chart->border = 0; chart->rounding = 0; + chart->color_factor = 1.0f; + chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + chart->show_markers = nk_true; /* combo */ combo = &style->combo; @@ -18591,6 +18699,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->spacing = nk_vec2(4,0); combo->border = 1; combo->rounding = 0; + combo->color_factor = 1.0f; + combo->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo button */ button = &style->combo.button; @@ -18609,6 +18719,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18624,6 +18737,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->indent = 10.0f; tab->border = 1; tab->rounding = 0; + tab->color_factor = 1.0f; + tab->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* tab button */ button = &style->tab.tab_minimize_button; @@ -18642,6 +18757,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -18663,6 +18781,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -18700,6 +18821,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -18720,6 +18844,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -19543,12 +19670,12 @@ nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) NK_LIB nk_bool nk_panel_is_sub(enum nk_panel_type type) { - return (type & NK_PANEL_SET_SUB)?1:0; + return ((int)type & (int)NK_PANEL_SET_SUB)?1:0; } NK_LIB nk_bool nk_panel_is_nonblock(enum nk_panel_type type) { - return (type & NK_PANEL_SET_NONBLOCK)?1:0; + return ((int)type & (int)NK_PANEL_SET_NONBLOCK)?1:0; } NK_LIB nk_bool nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) @@ -20269,6 +20396,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; + win->widgets_disabled = nk_false; if (!ctx->active) ctx->active = win; } else { @@ -20797,7 +20925,7 @@ nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type, win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); (void)panel; title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); @@ -20891,7 +21019,7 @@ nk_nonblock_begin(struct nk_context *ctx, /* popups cannot have popups */ win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP)); (void)panel; popup = win->popup.win; if (!popup) { @@ -20964,7 +21092,7 @@ nk_popup_close(struct nk_context *ctx) popup = ctx->current; NK_ASSERT(popup->parent); - NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)popup->layout->type & (int)NK_PANEL_SET_POPUP); popup->flags |= NK_WINDOW_HIDDEN; } NK_API void @@ -21047,6 +21175,7 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, struct nk_window *win; struct nk_window *popup; struct nk_rect body; + struct nk_input* in; NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0}; int is_clicked = 0; @@ -21067,35 +21196,39 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, /* check if currently active contextual is active */ popup = win->popup.win; is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); - is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); - if (win->popup.active_con && win->popup.con_count != win->popup.active_con) - return 0; - if (!is_open && win->popup.active_con) - win->popup.active_con = 0; - if ((!is_open && !is_clicked)) - return 0; + in = win->widgets_disabled ? 0 : &ctx->input; + if (in) { + is_clicked = nk_input_mouse_clicked(in, NK_BUTTON_RIGHT, trigger_bounds); + if (win->popup.active_con && win->popup.con_count != win->popup.active_con) + return 0; + if (!is_open && win->popup.active_con) + win->popup.active_con = 0; + if ((!is_open && !is_clicked)) + return 0; - /* calculate contextual position on click */ - win->popup.active_con = win->popup.con_count; - if (is_clicked) { - body.x = ctx->input.mouse.pos.x; - body.y = ctx->input.mouse.pos.y; - } else { - body.x = popup->bounds.x; - body.y = popup->bounds.y; - } - body.w = size.x; - body.h = size.y; + /* calculate contextual position on click */ + win->popup.active_con = win->popup.con_count; + if (is_clicked) { + body.x = in->mouse.pos.x; + body.y = in->mouse.pos.y; + } else { + body.x = popup->bounds.x; + body.y = popup->bounds.y; + } - /* start nonblocking contextual popup */ - ret = nk_nonblock_begin(ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, + body.w = size.x; + body.h = size.y; + + /* start nonblocking contextual popup */ + ret = nk_nonblock_begin(ctx, flags | NK_WINDOW_NO_SCROLLBAR, body, null_rect, NK_PANEL_CONTEXTUAL); - if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; - else { - win->popup.active_con = 0; - win->popup.type = NK_PANEL_NONE; - if (win->popup.win) - win->popup.win->flags = 0; + if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; + else { + win->popup.active_con = 0; + win->popup.type = NK_PANEL_NONE; + if (win->popup.win) + win->popup.win->flags = 0; + } } return ret; } @@ -21227,7 +21360,7 @@ nk_contextual_end(struct nk_context *ctx) popup = ctx->current; panel = popup->layout; NK_ASSERT(popup->parent); - NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)panel->type & (int)NK_PANEL_SET_POPUP); if (panel->flags & NK_WINDOW_DYNAMIC) { /* Close behavior This is a bit of a hack solution since we do not know before we end our popup @@ -21384,7 +21517,7 @@ nk_menu_begin_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -21414,7 +21547,7 @@ nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) is_clicked = nk_true; @@ -21439,7 +21572,7 @@ nk_menu_begin_symbol(struct nk_context *ctx, const char *id, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -21464,7 +21597,7 @@ nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) @@ -21497,7 +21630,7 @@ nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len, state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; @@ -22375,15 +22508,15 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); break; } } else text.background = style->window.background; @@ -22428,7 +22561,7 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, label.y = sym.y; label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); label.h = style->font->height; - text.text = style->tab.text; + text.text = nk_rgb_factor(style->tab.text, style->tab.color_factor); text.padding = nk_vec2(0,0); nk_widget_text(out, label, title, nk_strlen(title), &text, NK_TEXT_LEFT, style->font);} @@ -22565,15 +22698,16 @@ nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); + break; } } @@ -23201,6 +23335,8 @@ nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h); if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h)) return NK_WIDGET_INVALID; + if (win->widgets_disabled) + return NK_WIDGET_DISABLED; if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h)) return NK_WIDGET_ROM; return NK_WIDGET_VALID; @@ -23253,7 +23389,132 @@ nk_spacing(struct nk_context *ctx, int cols) nk_panel_alloc_space(&none, ctx); } layout->row.index = index; } +NK_API void +nk_widget_disable_begin(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_true; + + style->button.color_factor_text = style->button.disabled_factor; + style->button.color_factor_background = style->button.disabled_factor; + style->chart.color_factor = style->chart.disabled_factor; + style->checkbox.color_factor = style->checkbox.disabled_factor; + style->combo.color_factor = style->combo.disabled_factor; + style->combo.button.color_factor_text = style->combo.button.disabled_factor; + style->combo.button.color_factor_background = style->combo.button.disabled_factor; + style->contextual_button.color_factor_text = style->contextual_button.disabled_factor; + style->contextual_button.color_factor_background = style->contextual_button.disabled_factor; + style->edit.color_factor = style->edit.disabled_factor; + style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; + style->menu_button.color_factor_text = style->menu_button.disabled_factor; + style->menu_button.color_factor_background = style->menu_button.disabled_factor; + style->option.color_factor = style->option.disabled_factor; + style->progress.color_factor = style->progress.disabled_factor; + style->property.color_factor = style->property.disabled_factor; + style->property.inc_button.color_factor_text = style->property.inc_button.disabled_factor; + style->property.inc_button.color_factor_background = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor_text = style->property.dec_button.disabled_factor; + style->property.dec_button.color_factor_background = style->property.dec_button.disabled_factor; + style->property.edit.color_factor = style->property.edit.disabled_factor; + style->scrollh.color_factor = style->scrollh.disabled_factor; + style->scrollh.inc_button.color_factor_text = style->scrollh.inc_button.disabled_factor; + style->scrollh.inc_button.color_factor_background = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor_text = style->scrollh.dec_button.disabled_factor; + style->scrollh.dec_button.color_factor_background = style->scrollh.dec_button.disabled_factor; + style->scrollv.color_factor = style->scrollv.disabled_factor; + style->scrollv.inc_button.color_factor_text = style->scrollv.inc_button.disabled_factor; + style->scrollv.inc_button.color_factor_background = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor_text = style->scrollv.dec_button.disabled_factor; + style->scrollv.dec_button.color_factor_background = style->scrollv.dec_button.disabled_factor; + style->selectable.color_factor = style->selectable.disabled_factor; + style->slider.color_factor = style->slider.disabled_factor; + style->slider.inc_button.color_factor_text = style->slider.inc_button.disabled_factor; + style->slider.inc_button.color_factor_background = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor_text = style->slider.dec_button.disabled_factor; + style->slider.dec_button.color_factor_background = style->slider.dec_button.disabled_factor; + style->tab.color_factor = style->tab.disabled_factor; + style->tab.node_maximize_button.color_factor_text = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor_text = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_text = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_background = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_text = style->tab.tab_minimize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_background = style->tab.tab_minimize_button.disabled_factor; + style->text.color_factor = style->text.disabled_factor; +} +NK_API void +nk_widget_disable_end(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_false; + + style->button.color_factor_text = 1.0f; + style->button.color_factor_background = 1.0f; + style->chart.color_factor = 1.0f; + style->checkbox.color_factor = 1.0f; + style->combo.color_factor = 1.0f; + style->combo.button.color_factor_text = 1.0f; + style->combo.button.color_factor_background = 1.0f; + style->contextual_button.color_factor_text = 1.0f; + style->contextual_button.color_factor_background = 1.0f; + style->edit.color_factor = 1.0f; + style->edit.scrollbar.color_factor = 1.0f; + style->menu_button.color_factor_text = 1.0f; + style->menu_button.color_factor_background = 1.0f; + style->option.color_factor = 1.0f; + style->progress.color_factor = 1.0f; + style->property.color_factor = 1.0f; + style->property.inc_button.color_factor_text = 1.0f; + style->property.inc_button.color_factor_background = 1.0f; + style->property.dec_button.color_factor_text = 1.0f; + style->property.dec_button.color_factor_background = 1.0f; + style->property.edit.color_factor = 1.0f; + style->scrollh.color_factor = 1.0f; + style->scrollh.inc_button.color_factor_text = 1.0f; + style->scrollh.inc_button.color_factor_background = 1.0f; + style->scrollh.dec_button.color_factor_text = 1.0f; + style->scrollh.dec_button.color_factor_background = 1.0f; + style->scrollv.color_factor = 1.0f; + style->scrollv.inc_button.color_factor_text = 1.0f; + style->scrollv.inc_button.color_factor_background = 1.0f; + style->scrollv.dec_button.color_factor_text = 1.0f; + style->scrollv.dec_button.color_factor_background = 1.0f; + style->selectable.color_factor = 1.0f; + style->slider.color_factor = 1.0f; + style->slider.inc_button.color_factor_text = 1.0f; + style->slider.inc_button.color_factor_background = 1.0f; + style->slider.dec_button.color_factor_text = 1.0f; + style->slider.dec_button.color_factor_background = 1.0f; + style->tab.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor_text = 1.0f; + style->tab.node_minimize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_background = 1.0f; + style->tab.tab_minimize_button.color_factor_text = 1.0f; + style->tab.tab_minimize_button.color_factor_background = 1.0f; + style->text.color_factor = 1.0f; +} @@ -23371,7 +23632,7 @@ nk_text_colored(struct nk_context *ctx, const char *str, int len, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); } NK_API void @@ -23398,7 +23659,7 @@ nk_text_wrap_colored(struct nk_context *ctx, const char *str, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); } #ifdef NK_INCLUDE_STANDARD_VARARGS @@ -23895,16 +24156,16 @@ nk_draw_button(struct nk_command_buffer *out, background = &style->active; else background = &style->normal; - switch(background->type) { + switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor_background)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor_background)); break; } return background; @@ -23924,8 +24185,8 @@ nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, /* calculate button content space */ content->x = r.x + style->padding.x + style->border + style->rounding; content->y = r.y + style->padding.y + style->border + style->rounding; - content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); - content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); + content->w = r.w - (2 * (style->padding.x + style->border + style->rounding)); + content->h = r.h - (2 * (style->padding.y + style->border + style->rounding)); /* execute button behavior */ bounds.x = r.x - style->touch_padding.x; @@ -23954,6 +24215,8 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; + text.text = nk_rgb_factor(text.text, style->color_factor_text); + text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); } @@ -24001,6 +24264,8 @@ nk_draw_button_symbol(struct nk_command_buffer *out, else if (state & NK_WIDGET_STATE_ACTIVED) sym = style->text_active; else sym = style->text_normal; + + sym = nk_rgb_factor(sym, style->color_factor_text); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -24032,7 +24297,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_white); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -24089,6 +24354,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } + sym = nk_rgb_factor(sym, style->color_factor_text); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -24146,9 +24413,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.padding = nk_vec2(0,0); + text.text = nk_rgb_factor(text.text, style->color_factor_text); + text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_white); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, @@ -24253,7 +24521,7 @@ nk_button_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, title, len, style->text_alignment, ctx->button_behavior, style, in, ctx->style.font); @@ -24298,7 +24566,7 @@ nk_button_color(struct nk_context *ctx, struct nk_color color) state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; button = ctx->style.button; button.normal = nk_style_item_color(color); @@ -24330,7 +24598,7 @@ nk_button_symbol_styled(struct nk_context *ctx, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, ctx->button_behavior, style, in, ctx->style.font); } @@ -24363,7 +24631,7 @@ nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *sty state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, img, ctx->button_behavior, style, in); } @@ -24397,7 +24665,7 @@ nk_button_symbol_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -24444,7 +24712,7 @@ nk_button_image_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -24496,7 +24764,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24517,28 +24785,29 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *selector, 0, style->border_color); - nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_rect(out, *cursors, 0, cursor->data.color); - } - + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); + + /* draw background and cursor */ + if (background->type == NK_STYLE_ITEM_COLOR) { + nk_fill_rect(out, *selector, 0, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + if (active) { + if (cursor->type == NK_STYLE_ITEM_IMAGE) + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); + else nk_fill_rect(out, *cursors, 0, cursor->data.color); + } } NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -24559,28 +24828,29 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_circle(out, *selector, style->border_color); - nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_circle(out, *cursors, cursor->data.color); - } - + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); + + /* draw background and cursor */ + if (background->type == NK_STYLE_ITEM_COLOR) { + nk_fill_circle(out, *selector, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_circle(out, nk_shrink_rect(*selector, style->border), nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + if (active) { + if (cursor->type == NK_STYLE_ITEM_IMAGE) + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); + else nk_fill_circle(out, *cursors, cursor->data.color); + } } NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; struct nk_rect bounds; @@ -24606,8 +24876,37 @@ nk_do_toggle(nk_flags *state, /* calculate the selector space */ select.w = font->height; select.h = select.w; - select.y = r.y + r.h/2.0f - select.h/2.0f; - select.x = r.x; + + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { + select.x = r.x + r.w - font->height; + + /* label in front of the selector */ + label.x = r.x; + label.w = r.w - select.w - style->spacing * 2; + } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { + select.x = r.x + (r.w - select.w) / 2; + + /* label in front of selector */ + label.x = r.x; + label.w = (r.w - select.w - style->spacing * 2) / 2; + } else { /* Default: NK_WIDGET_ALIGN_LEFT */ + select.x = r.x; + + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } + + if (widget_alignment & NK_WIDGET_ALIGN_TOP) { + select.y = r.y; + } else if (widget_alignment & NK_WIDGET_ALIGN_BOTTOM) { + select.y = r.y + r.h - select.h - 2 * style->padding.y; + } else { /* Default: NK_WIDGET_ALIGN_MIDDLE */ + select.y = r.y + r.h/2.0f - select.h/2.0f; + } + + label.y = select.y; + label.h = select.w; /* calculate the bounds of the cursor inside the selector */ cursor.x = select.x + style->padding.x + style->border; @@ -24615,12 +24914,6 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.y = select.y; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - label.h = select.w; - /* update selector */ was_active = *active; *active = nk_toggle_behavior(in, bounds, state, *active); @@ -24629,9 +24922,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -24665,9 +24958,37 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) state = nk_widget(&bounds, ctx); if (!state) return active; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return active; +} +NK_API nk_bool +nk_check_text_align(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return active; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, widget_alignment, text_alignment); return active; } NK_API unsigned int @@ -24697,6 +25018,18 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act return old_val != *active; } NK_API nk_bool +nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_val; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_val = *active; + *active = nk_check_text_align(ctx, text, len, *active, widget_alignment, text_alignment); + return old_val != *active; +} +NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, unsigned int *flags, unsigned int value) { @@ -24727,6 +25060,10 @@ NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_b { return nk_checkbox_text(ctx, label, nk_strlen(label), active); } +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_checkbox_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, unsigned int *flags, unsigned int value) { @@ -24760,9 +25097,37 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act state = nk_widget(&bounds, ctx); if (!state) return (int)state; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return is_active; +} +NK_API nk_bool +nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return is_active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return (int)state; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, widget_alignment, text_alignment); return is_active; } NK_API nk_bool @@ -24778,15 +25143,37 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active return old_value != *active; } NK_API nk_bool +nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_value; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_value = *active; + *active = nk_option_text_align(ctx, text, len, old_value, widget_alignment, text_alignment); + return old_value != *active; +} +NK_API nk_bool nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) { return nk_option_text(ctx, label, nk_strlen(label), active); } NK_API nk_bool +nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_option_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} +NK_API nk_bool nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) { return nk_radio_text(ctx, label, nk_strlen(label), active); } +NK_API nk_bool +nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_radio_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} @@ -24832,15 +25219,18 @@ nk_draw_selectable(struct nk_command_buffer *out, text.text = style->text_normal_active; } } + + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw selectable background and text */ switch (background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; @@ -24848,7 +25238,7 @@ nk_draw_selectable(struct nk_command_buffer *out, break; } if (icon) { - if (img) nk_draw_image(out, *icon, img, nk_white); + if (img) nk_draw_image(out, *icon, img, nk_rgb_factor(nk_white, style->color_factor)); else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font); } nk_widget_text(out, *bounds, string, len, &text, align, font); @@ -25009,7 +25399,7 @@ nk_selectable_text(struct nk_context *ctx, const char *str, int len, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &style->selectable, in, style->font); } @@ -25038,7 +25428,7 @@ nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &img, &style->selectable, in, style->font); } @@ -25067,7 +25457,7 @@ nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, sym, &style->selectable, in, style->font); } @@ -25199,6 +25589,7 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, bar_color = style->bar_normal; cursor = &style->cursor_normal; } + /* calculate slider background bar */ bar.x = bounds->x; bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; @@ -25214,26 +25605,26 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw slider bar */ - nk_fill_rect(out, bar, style->rounding, bar_color); - nk_fill_rect(out, fill, style->rounding, style->bar_filled); + nk_fill_rect(out, bar, style->rounding, nk_rgb_factor(bar_color, style->color_factor)); + nk_fill_rect(out, fill, style->rounding, nk_rgb_factor(style->bar_filled, style->color_factor)); /* draw cursor */ if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); + nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else - nk_fill_circle(out, *visual_cursor, cursor->data.color); + nk_fill_circle(out, *visual_cursor, nk_rgb_factor(cursor->data.color, style->color_factor)); } NK_LIB float nk_do_slider(nk_flags *state, @@ -25351,7 +25742,7 @@ nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max state = nk_widget(&bounds, ctx); if (!state) return ret; - in = (/*state == NK_WIDGET_ROM || */ layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (/*state == NK_WIDGET_ROM || */ state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *value; *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, @@ -25445,28 +25836,28 @@ nk_draw_progress(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw cursor */ switch(cursor->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *scursor, &cursor->data.image, nk_white); + nk_draw_image(out, *scursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_white); + nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *scursor, style->rounding, cursor->data.color); - nk_stroke_rect(out, *scursor, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *scursor, style->rounding, nk_rgb_factor(cursor->data.color, style->color_factor)); + nk_stroke_rect(out, *scursor, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } } @@ -25526,7 +25917,7 @@ nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, nk_bool is_modify state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *cur; *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, *cur, max, is_modifyable, &style->progress, in); @@ -26977,6 +27368,9 @@ nk_edit_draw_text(struct nk_command_buffer *out, txt.background = background; txt.text = foreground; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); if (!glyph_len) return; while ((text_len < byte_len) && glyph_len) @@ -27214,14 +27608,14 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, /* draw background frame */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, bounds, &background->data.image, nk_white); + nk_draw_image(out, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, bounds, style->rounding, background->data.color); - nk_stroke_rect(out, bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; }} @@ -27430,6 +27824,8 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, else background_color = background->data.color; + cursor_color = nk_rgb_factor(cursor_color, style->color_factor); + cursor_text_color = nk_rgb_factor(cursor_text_color, style->color_factor); if (edit->select_start == edit->select_end) { /* no selection so just draw the complete text */ @@ -27537,6 +27933,10 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; + + background_color = nk_rgb_factor(background_color, style->color_factor); + text_color = nk_rgb_factor(text_color, style->color_factor); + nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); @@ -27656,6 +28056,8 @@ nk_edit_buffer(struct nk_context *ctx, nk_flags flags, style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return state; + else if (state == NK_WIDGET_DISABLED) + flags |= NK_EDIT_READ_ONLY; in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* check if edit is currently hot item */ @@ -27789,20 +28191,22 @@ nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property * text.text = style->label_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(background->data.color, style->color_factor)); break; } @@ -27953,7 +28357,7 @@ nk_do_property(nk_flags *ws, text_edit->string.buffer.memory.ptr = dst; text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; - nk_do_edit(ws, out, edit, NK_EDIT_FIELD|NK_EDIT_AUTO_SELECT, + nk_do_edit(ws, out, edit, (int)NK_EDIT_FIELD|(int)NK_EDIT_AUTO_SELECT, filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); *length = text_edit->string.len; @@ -28087,7 +28491,7 @@ nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant old_state = *state; ctx->text_edit.clip = ctx->clip; in = ((s == NK_WIDGET_ROM && !win->property.active) || - layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED) ? 0 : &ctx->input; nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, variant, inc_per_pixel, buffer, len, state, cursor, select_begin, select_end, &style->property, filter, in, style->font, &ctx->text_edit, @@ -28256,26 +28660,27 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->show_markers = style->show_markers;} /* draw chart background */ background = &style->background; switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); + nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), - style->rounding, style->background.data.color); + style->rounding, nk_rgb_factor(style->background.data.color, style->color_factor)); break; } return 1; @@ -28292,6 +28697,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { + const struct nk_style_chart* style; + NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); @@ -28299,16 +28706,19 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, if (!ctx || !ctx->current || !ctx->current->layout) return; if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; + style = &ctx->style.chart; + /* add another slot into the graph */ {struct nk_chart *chart = &ctx->current->layout->chart; struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->show_markers = style->show_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -28322,7 +28732,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float value, int slot) { struct nk_panel *layout = win->layout; - const struct nk_input *i = &ctx->input; + const struct nk_input *i = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; @@ -28348,14 +28758,16 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, bounds.w = bounds.h = 4; color = g->slots[slot].color; - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && i && NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - nk_fill_rect(out, bounds, 0, color); + if (g->slots[slot].show_markers) { + nk_fill_rect(out, bounds, 0, color); + } g->slots[slot].index += 1; return ret; } @@ -28379,7 +28791,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + if (g->slots[slot].show_markers) { + nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + } /* save current data point position */ g->slots[slot].last.x = cur.x; @@ -28392,7 +28806,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, struct nk_chart *chart, float value, int slot) { struct nk_command_buffer *out = &win->buffer; - const struct nk_input *in = &ctx->input; + const struct nk_input *in = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_panel *layout = win->layout; float ratio; @@ -28422,7 +28836,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, item.x = item.x + ((float)chart->slots[slot].index); /* user chart bar selection */ - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && in && NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { ret = NK_CHART_HOVERING; ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && @@ -28721,7 +29135,7 @@ nk_color_pick(struct nk_context * ctx, struct nk_colorf *color, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, nk_vec2(0,0), in, config->font); } @@ -28803,7 +29217,7 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -28819,19 +29233,21 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -28911,7 +29327,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -28924,14 +29340,14 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -28969,7 +29385,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; else bounds.w = header.w - 4 * style->combo.content_padding.x; - nk_fill_rect(&win->buffer, bounds, 0, color); + nk_fill_rect(&win->buffer, bounds, 0, nk_rgb_factor(color, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -29004,7 +29420,7 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29020,19 +29436,21 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct symbol_color = style->combo.symbol_hover; } + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: sym_background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29098,7 +29516,7 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29117,19 +29535,22 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29200,7 +29621,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29213,14 +29634,14 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29258,7 +29679,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; else bounds.w = header.w - 2 * style->combo.content_padding.x; - nk_draw_image(&win->buffer, bounds, &img, nk_white); + nk_draw_image(&win->buffer, bounds, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -29292,7 +29713,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -29308,19 +29729,21 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -29359,7 +29782,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; - nk_draw_image(&win->buffer, image, &img, nk_white); + nk_draw_image(&win->buffer, image, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw label */ text.padding = nk_vec2(0,0); @@ -29600,7 +30023,7 @@ nk_tooltip_begin(struct nk_context *ctx, float width) /* make sure that no nonblocking popup is currently active */ win = ctx->current; in = &ctx->input; - if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) + if (win->popup.win && ((int)win->popup.type & (int)NK_PANEL_SET_NONBLOCK)) return 0; w = nk_iceilf(width); @@ -29741,7 +30164,10 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/03 (4.10.7) - Fix null pointer dereference with nk_group and nk_listview scroll offsets +/// - 2024/04/04 (4.12.2) - Fix null pointer dereference with nk_group and nk_listview scroll offsets +/// - 2024/03/07 (4.12.1) - Fix bitwise operations warnings in C++20 +/// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. +/// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 @@ -29886,7 +30312,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// dynamic and static widgets. /// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. /// - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. /// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. /// - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. /// - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -30024,7 +30450,7 @@ nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) /// precision. /// - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. /// - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading -/// to wrong wiget width calculation which results in widgets falsely +/// to wrong widget width calculation which results in widgets falsely /// becoming tagged as not inside window and cannot be accessed. /// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and /// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/src/CHANGELOG b/src/CHANGELOG index 09eebad..4aa0faf 100644 --- a/src/CHANGELOG +++ b/src/CHANGELOG @@ -7,7 +7,10 @@ /// - [y]: Minor version with non-breaking API and library changes /// - [z]: Patch version with no direct changes to the API /// -/// - 2023/11/03 (4.10.7) - Fix null pointer dereference with nk_group and nk_listview scroll offsets +/// - 2024/04/04 (4.12.2) - Fix null pointer dereference with nk_group and nk_listview scroll offsets +/// - 2024/03/07 (4.12.1) - Fix bitwise operations warnings in C++20 +/// - 2023/11/26 (4.12.0) - Added an alignment option to checkboxes and radio buttons. +/// - 2023/10/11 (4.11.0) - Added nk_widget_disable_begin() and nk_widget_disable_end() /// - 2022/12/23 (4.10.6) - Fix incorrect glyph index in nk_font_bake() /// - 2022/12/17 (4.10.5) - Fix nk_font_bake_pack() using TTC font offset incorrectly /// - 2022/10/24 (4.10.4) - Fix nk_str_{append,insert}_str_utf8 always returning 0 @@ -152,7 +155,7 @@ /// dynamic and static widgets. /// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit. /// - 2016/12/31 (1.29.2) - Fixed closing window bug of minimized windows. -/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no seperator and C89 error. +/// - 2016/12/03 (1.29.1) - Fixed wrapped text with no separator and C89 error. /// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters. /// - 2016/11/22 (1.28.6) - Fixed window minimized closing bug. /// - 2016/11/19 (1.28.5) - Fixed abstract combo box closing behavior. @@ -290,7 +293,7 @@ /// precision. /// - 2016/08/08 (1.07.2) - Fixed compiling error without define `NK_INCLUDE_FIXED_TYPE`. /// - 2016/08/08 (1.07.1) - Fixed possible floating point error inside `nk_widget` leading -/// to wrong wiget width calculation which results in widgets falsely +/// to wrong widget width calculation which results in widgets falsely /// becoming tagged as not inside window and cannot be accessed. /// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and /// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown diff --git a/src/nuklear.h b/src/nuklear.h index 0b829c4..9fb0be4 100644 --- a/src/nuklear.h +++ b/src/nuklear.h @@ -1241,7 +1241,7 @@ NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command* /// #### nk_collapse_states /// State | Description /// ----------------|----------------------------------------------------------- -/// __NK_MINIMIZED__| UI section is collased and not visible until maximized +/// __NK_MINIMIZED__| UI section is collapsed and not visible until maximized /// __NK_MAXIMIZED__| UI section is extended and visible until minimized ///

*/ @@ -1779,11 +1779,11 @@ NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_st /// __ctx__ | Must point to an previously initialized `nk_context` struct /// __name__ | Identifier of the window to either hide or show /// __state__ | state with either visible or hidden to modify the window with -/// __cond__ | condition that has to be met to actually commit the visbility state change +/// __cond__ | condition that has to be met to actually commit the visibility state change */ NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); /*/// #### nk_window_show_if -/// Line for visual seperation. Draws a line with thickness determined by the current row height. +/// Line for visual separation. Draws a line with thickness determined by the current row height. /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c /// void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, NK_BOOL rounding) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1847,7 +1847,7 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// the size of each widget dynamically by formula: /// /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// widget_width = (window_width - padding - spacing) * (1/colum_count) +/// widget_width = (window_width - padding - spacing) * (1/column_count) /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// /// Just like all other layouting APIs if you define more widget than columns this @@ -2068,6 +2068,21 @@ NK_API void nk_rule_horizontal(struct nk_context *ctx, struct nk_color color, nk /// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space /// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates */ + +enum nk_widget_align { + NK_WIDGET_ALIGN_LEFT = 0x01, + NK_WIDGET_ALIGN_CENTERED = 0x02, + NK_WIDGET_ALIGN_RIGHT = 0x04, + NK_WIDGET_ALIGN_TOP = 0x08, + NK_WIDGET_ALIGN_MIDDLE = 0x10, + NK_WIDGET_ALIGN_BOTTOM = 0x20 +}; +enum nk_widget_alignment { + NK_WIDGET_LEFT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_LEFT, + NK_WIDGET_CENTERED = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_CENTERED, + NK_WIDGET_RIGHT = NK_WIDGET_ALIGN_MIDDLE|NK_WIDGET_ALIGN_RIGHT +}; + /*/// #### nk_layout_set_min_row_height /// Sets the currently used minimum row height. /// !!! WARNING @@ -2867,7 +2882,8 @@ NK_API void nk_list_view_end(struct nk_list_view*); enum nk_widget_layout_states { NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ - NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ + NK_WIDGET_ROM, /* The widget is partially visible and cannot be updated */ + NK_WIDGET_DISABLED /* The widget is manually disabled and acts like NK_WIDGET_ROM */ }; enum nk_widget_states { NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), @@ -2890,6 +2906,8 @@ NK_API nk_bool nk_widget_is_hovered(struct nk_context*); NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down); NK_API void nk_spacing(struct nk_context*, int cols); +NK_API void nk_widget_disable_begin(struct nk_context* ctx); +NK_API void nk_widget_disable_end(struct nk_context* ctx); /* ============================================================================= * * TEXT @@ -2967,10 +2985,13 @@ NK_API nk_bool nk_button_pop_behavior(struct nk_context*); * ============================================================================= */ NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active); NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_check_text_align(struct nk_context*, const char*, int, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); /* ============================================================================= @@ -2979,9 +3000,13 @@ NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsi * * ============================================================================= */ NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active); +NK_API nk_bool nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active); +NK_API nk_bool nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active); +NK_API nk_bool nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment); NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active); +NK_API nk_bool nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment); /* ============================================================================= * * SELECTABLE @@ -3384,6 +3409,9 @@ NK_API void nk_menu_end(struct nk_context*); * STYLE * * ============================================================================= */ + +#define NK_WIDGET_DISABLED_FACTOR 0.5f + enum nk_style_colors { NK_COLOR_TEXT, NK_COLOR_WINDOW, @@ -3460,6 +3488,7 @@ NK_API struct nk_color nk_rgb_f(float r, float g, float b); NK_API struct nk_color nk_rgb_fv(const float *rgb); NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); NK_API struct nk_color nk_rgb_hex(const char *rgb); +NK_API struct nk_color nk_rgb_factor(struct nk_color col, const float factor); NK_API struct nk_color nk_rgba(int r, int g, int b, int a); NK_API struct nk_color nk_rgba_u32(nk_uint); @@ -4680,6 +4709,8 @@ struct nk_style_item { struct nk_style_text { struct nk_color color; struct nk_vec2 padding; + float color_factor; + float disabled_factor; }; struct nk_style_button { @@ -4688,6 +4719,7 @@ struct nk_style_button { struct nk_style_item hover; struct nk_style_item active; struct nk_color border_color; + float color_factor_background; /* text */ struct nk_color text_background; @@ -4695,6 +4727,7 @@ struct nk_style_button { struct nk_color text_hover; struct nk_color text_active; nk_flags text_alignment; + float color_factor_text; /* properties */ float border; @@ -4702,6 +4735,7 @@ struct nk_style_button { struct nk_vec2 padding; struct nk_vec2 image_padding; struct nk_vec2 touch_padding; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4732,6 +4766,8 @@ struct nk_style_toggle { struct nk_vec2 touch_padding; float spacing; float border; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4767,6 +4803,8 @@ struct nk_style_selectable { struct nk_vec2 padding; struct nk_vec2 touch_padding; struct nk_vec2 image_padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4799,6 +4837,8 @@ struct nk_style_slider { struct nk_vec2 padding; struct nk_vec2 spacing; struct nk_vec2 cursor_size; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -4832,6 +4872,8 @@ struct nk_style_progress { float cursor_border; float cursor_rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional user callbacks */ nk_handle userdata; @@ -4858,6 +4900,8 @@ struct nk_style_scrollbar { float border_cursor; float rounding_cursor; struct nk_vec2 padding; + float color_factor; + float disabled_factor; /* optional buttons */ int show_buttons; @@ -4904,6 +4948,8 @@ struct nk_style_edit { struct nk_vec2 scrollbar_size; struct nk_vec2 padding; float row_padding; + float color_factor; + float disabled_factor; }; struct nk_style_property { @@ -4926,6 +4972,8 @@ struct nk_style_property { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; struct nk_style_edit edit; struct nk_style_button inc_button; @@ -4948,6 +4996,9 @@ struct nk_style_chart { float border; float rounding; struct nk_vec2 padding; + float color_factor; + float disabled_factor; + nk_bool show_markers; }; struct nk_style_combo { @@ -4979,6 +5030,8 @@ struct nk_style_combo { struct nk_vec2 content_padding; struct nk_vec2 button_padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; struct nk_style_tab { @@ -5001,6 +5054,8 @@ struct nk_style_tab { float indent; struct nk_vec2 padding; struct nk_vec2 spacing; + float color_factor; + float disabled_factor; }; enum nk_style_header_align { @@ -5134,6 +5189,7 @@ struct nk_chart_slot { int count; struct nk_vec2 last; int index; + nk_bool show_markers; }; struct nk_chart { @@ -5283,6 +5339,7 @@ struct nk_window { struct nk_popup_state popup; struct nk_edit_state edit; unsigned int scrolled; + nk_bool widgets_disabled; struct nk_table *tables; unsigned int table_count; diff --git a/src/nuklear_button.c b/src/nuklear_button.c index 2636b60..655692c 100644 --- a/src/nuklear_button.c +++ b/src/nuklear_button.c @@ -98,16 +98,16 @@ nk_draw_button(struct nk_command_buffer *out, background = &style->active; else background = &style->normal; - switch(background->type) { + switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor_background)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor_background)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor_background)); break; } return background; @@ -127,8 +127,8 @@ nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, /* calculate button content space */ content->x = r.x + style->padding.x + style->border + style->rounding; content->y = r.y + style->padding.y + style->border + style->rounding; - content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); - content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); + content->w = r.w - (2 * (style->padding.x + style->border + style->rounding)); + content->h = r.h - (2 * (style->padding.y + style->border + style->rounding)); /* execute button behavior */ bounds.x = r.x - style->touch_padding.x; @@ -157,6 +157,8 @@ nk_draw_button_text(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; + text.text = nk_rgb_factor(text.text, style->color_factor_text); + text.padding = nk_vec2(0,0); nk_widget_text(out, *content, txt, len, &text, text_alignment, font); } @@ -204,6 +206,8 @@ nk_draw_button_symbol(struct nk_command_buffer *out, else if (state & NK_WIDGET_STATE_ACTIVED) sym = style->text_active; else sym = style->text_normal; + + sym = nk_rgb_factor(sym, style->color_factor_text); nk_draw_symbol(out, type, *content, bg, sym, 1, font); } NK_LIB nk_bool @@ -235,7 +239,7 @@ nk_draw_button_image(struct nk_command_buffer *out, nk_flags state, const struct nk_style_button *style, const struct nk_image *img) { nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_white); + nk_draw_image(out, *content, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_image(nk_flags *state, @@ -292,6 +296,8 @@ nk_draw_button_text_symbol(struct nk_command_buffer *out, text.text = style->text_normal; } + sym = nk_rgb_factor(sym, style->color_factor_text); + text.text = nk_rgb_factor(text.text, style->color_factor_text); text.padding = nk_vec2(0,0); nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); @@ -349,9 +355,10 @@ nk_draw_button_text_image(struct nk_command_buffer *out, text.text = style->text_active; else text.text = style->text_normal; - text.padding = nk_vec2(0,0); + text.text = nk_rgb_factor(text.text, style->color_factor_text); + text.padding = nk_vec2(0, 0); nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_white); + nk_draw_image(out, *image, img, nk_rgb_factor(nk_white, style->color_factor_background)); } NK_LIB nk_bool nk_do_button_text_image(nk_flags *state, @@ -456,7 +463,7 @@ nk_button_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, title, len, style->text_alignment, ctx->button_behavior, style, in, ctx->style.font); @@ -501,7 +508,7 @@ nk_button_color(struct nk_context *ctx, struct nk_color color) state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; button = ctx->style.button; button.normal = nk_style_item_color(color); @@ -533,7 +540,7 @@ nk_button_symbol_styled(struct nk_context *ctx, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, ctx->button_behavior, style, in, ctx->style.font); } @@ -566,7 +573,7 @@ nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *sty state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, img, ctx->button_behavior, style, in); } @@ -600,7 +607,7 @@ nk_button_symbol_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, symbol, text, len, align, ctx->button_behavior, style, ctx->style.font, in); @@ -647,7 +654,7 @@ nk_button_image_text_styled(struct nk_context *ctx, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, img, text, len, align, ctx->button_behavior, style, ctx->style.font, in); diff --git a/src/nuklear_chart.c b/src/nuklear_chart.c index d4fd902..87301fa 100644 --- a/src/nuklear_chart.c +++ b/src/nuklear_chart.c @@ -48,26 +48,27 @@ nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->show_markers = style->show_markers;} /* draw chart background */ background = &style->background; switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); + nk_draw_image(&win->buffer, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); + nk_fill_rect(&win->buffer, bounds, style->rounding, nk_rgb_factor(style->border_color, style->color_factor)); nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), - style->rounding, style->background.data.color); + style->rounding, nk_rgb_factor(style->background.data.color, style->color_factor)); break; } return 1; @@ -84,6 +85,8 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, struct nk_color color, struct nk_color highlight, int count, float min_value, float max_value) { + const struct nk_style_chart* style; + NK_ASSERT(ctx); NK_ASSERT(ctx->current); NK_ASSERT(ctx->current->layout); @@ -91,16 +94,19 @@ nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, if (!ctx || !ctx->current || !ctx->current->layout) return; if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; + style = &ctx->style.chart; + /* add another slot into the graph */ {struct nk_chart *chart = &ctx->current->layout->chart; struct nk_chart_slot *slot = &chart->slots[chart->slot++]; slot->type = type; slot->count = count; - slot->color = color; + slot->color = nk_rgb_factor(color, style->color_factor); slot->highlight = highlight; slot->min = NK_MIN(min_value, max_value); slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} + slot->range = slot->max - slot->min; + slot->show_markers = style->show_markers;} } NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, @@ -114,7 +120,7 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, struct nk_chart *g, float value, int slot) { struct nk_panel *layout = win->layout; - const struct nk_input *i = &ctx->input; + const struct nk_input *i = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_command_buffer *out = &win->buffer; nk_flags ret = 0; @@ -140,14 +146,16 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, bounds.w = bounds.h = 4; color = g->slots[slot].color; - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && i && NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; color = g->slots[slot].highlight; } - nk_fill_rect(out, bounds, 0, color); + if (g->slots[slot].show_markers) { + nk_fill_rect(out, bounds, 0, color); + } g->slots[slot].index += 1; return ret; } @@ -171,7 +179,9 @@ nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, color = g->slots[slot].highlight; } } - nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + if (g->slots[slot].show_markers) { + nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); + } /* save current data point position */ g->slots[slot].last.x = cur.x; @@ -184,7 +194,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, struct nk_chart *chart, float value, int slot) { struct nk_command_buffer *out = &win->buffer; - const struct nk_input *in = &ctx->input; + const struct nk_input *in = ctx->current->widgets_disabled ? 0 : &ctx->input; struct nk_panel *layout = win->layout; float ratio; @@ -214,7 +224,7 @@ nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, item.x = item.x + ((float)chart->slots[slot].index); /* user chart bar selection */ - if (!(layout->flags & NK_WINDOW_ROM) && + if (!(layout->flags & NK_WINDOW_ROM) && in && NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { ret = NK_CHART_HOVERING; ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && diff --git a/src/nuklear_color.c b/src/nuklear_color.c index f2e1e85..d73da63 100644 --- a/src/nuklear_color.c +++ b/src/nuklear_color.c @@ -23,6 +23,16 @@ nk_parse_hex(const char *p, int length) return i; } NK_API struct nk_color +nk_rgb_factor(struct nk_color col, const float factor) +{ + if (factor == 1.0f) + return col; + col.r = (nk_byte)(col.r * factor); + col.g = (nk_byte)(col.g * factor); + col.b = (nk_byte)(col.b * factor); + return col; +} +NK_API struct nk_color nk_rgba(int r, int g, int b, int a) { struct nk_color ret; diff --git a/src/nuklear_color_picker.c b/src/nuklear_color_picker.c index f9f7dfb..114c3c1 100644 --- a/src/nuklear_color_picker.c +++ b/src/nuklear_color_picker.c @@ -187,7 +187,7 @@ nk_color_pick(struct nk_context * ctx, struct nk_colorf *color, layout = win->layout; state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, nk_vec2(0,0), in, config->font); } diff --git a/src/nuklear_combo.c b/src/nuklear_combo.c index df1db0a..0e403b8 100644 --- a/src/nuklear_combo.c +++ b/src/nuklear_combo.c @@ -67,7 +67,7 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -83,19 +83,21 @@ nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -175,7 +177,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -188,14 +190,14 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -233,7 +235,7 @@ nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_ve bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; else bounds.w = header.w - 4 * style->combo.content_padding.x; - nk_fill_rect(&win->buffer, bounds, 0, color); + nk_fill_rect(&win->buffer, bounds, 0, nk_rgb_factor(color, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -268,7 +270,7 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -284,19 +286,21 @@ nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct symbol_color = style->combo.symbol_hover; } + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: sym_background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: sym_background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -362,7 +366,7 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -381,19 +385,22 @@ nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + symbol_color = nk_rgb_factor(symbol_color, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -464,7 +471,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 if (s == NK_WIDGET_INVALID) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -477,14 +484,14 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -522,7 +529,7 @@ nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; else bounds.w = header.w - 2 * style->combo.content_padding.x; - nk_draw_image(&win->buffer, bounds, &img, nk_white); + nk_draw_image(&win->buffer, bounds, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw open/close button */ if (draw_button_symbol) @@ -556,7 +563,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, s = nk_widget(&header, ctx); if (!s) return 0; - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; + in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED || s == NK_WIDGET_ROM)? 0: &ctx->input; if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) is_clicked = nk_true; @@ -572,19 +579,21 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, text.text = style->combo.label_normal; } + text.text = nk_rgb_factor(text.text, style->combo.color_factor); + switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); + nk_draw_image(&win->buffer, header, &background->data.image, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_white); + nk_draw_nine_slice(&win->buffer, header, &background->data.slice, nk_rgb_factor(nk_white, style->combo.color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); + nk_fill_rect(&win->buffer, header, style->combo.rounding, nk_rgb_factor(background->data.color, style->combo.color_factor)); + nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, nk_rgb_factor(style->combo.border_color, style->combo.color_factor)); break; } { @@ -623,7 +632,7 @@ nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, image.y = header.y + style->combo.content_padding.y; image.h = header.h - 2 * style->combo.content_padding.y; image.w = image.h; - nk_draw_image(&win->buffer, image, &img, nk_white); + nk_draw_image(&win->buffer, image, &img, nk_rgb_factor(nk_white, style->combo.color_factor)); /* draw label */ text.padding = nk_vec2(0,0); diff --git a/src/nuklear_contextual.c b/src/nuklear_contextual.c index 6d9358f..da66854 100644 --- a/src/nuklear_contextual.c +++ b/src/nuklear_contextual.c @@ -13,6 +13,7 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, struct nk_window *win; struct nk_window *popup; struct nk_rect body; + struct nk_input* in; NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0}; int is_clicked = 0; @@ -33,35 +34,39 @@ nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, /* check if currently active contextual is active */ popup = win->popup.win; is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); - is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); - if (win->popup.active_con && win->popup.con_count != win->popup.active_con) - return 0; - if (!is_open && win->popup.active_con) - win->popup.active_con = 0; - if ((!is_open && !is_clicked)) - return 0; + in = win->widgets_disabled ? 0 : &ctx->input; + if (in) { + is_clicked = nk_input_mouse_clicked(in, NK_BUTTON_RIGHT, trigger_bounds); + if (win->popup.active_con && win->popup.con_count != win->popup.active_con) + return 0; + if (!is_open && win->popup.active_con) + win->popup.active_con = 0; + if ((!is_open && !is_clicked)) + return 0; - /* calculate contextual position on click */ - win->popup.active_con = win->popup.con_count; - if (is_clicked) { - body.x = ctx->input.mouse.pos.x; - body.y = ctx->input.mouse.pos.y; - } else { - body.x = popup->bounds.x; - body.y = popup->bounds.y; - } - body.w = size.x; - body.h = size.y; + /* calculate contextual position on click */ + win->popup.active_con = win->popup.con_count; + if (is_clicked) { + body.x = in->mouse.pos.x; + body.y = in->mouse.pos.y; + } else { + body.x = popup->bounds.x; + body.y = popup->bounds.y; + } - /* start nonblocking contextual popup */ - ret = nk_nonblock_begin(ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, + body.w = size.x; + body.h = size.y; + + /* start nonblocking contextual popup */ + ret = nk_nonblock_begin(ctx, flags | NK_WINDOW_NO_SCROLLBAR, body, null_rect, NK_PANEL_CONTEXTUAL); - if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; - else { - win->popup.active_con = 0; - win->popup.type = NK_PANEL_NONE; - if (win->popup.win) - win->popup.win->flags = 0; + if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; + else { + win->popup.active_con = 0; + win->popup.type = NK_PANEL_NONE; + if (win->popup.win) + win->popup.win->flags = 0; + } } return ret; } @@ -193,7 +198,7 @@ nk_contextual_end(struct nk_context *ctx) popup = ctx->current; panel = popup->layout; NK_ASSERT(popup->parent); - NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)panel->type & (int)NK_PANEL_SET_POPUP); if (panel->flags & NK_WINDOW_DYNAMIC) { /* Close behavior This is a bit of a hack solution since we do not know before we end our popup diff --git a/src/nuklear_edit.c b/src/nuklear_edit.c index 8cab48e..a7b2bfc 100644 --- a/src/nuklear_edit.c +++ b/src/nuklear_edit.c @@ -94,6 +94,9 @@ nk_edit_draw_text(struct nk_command_buffer *out, txt.background = background; txt.text = foreground; + foreground = nk_rgb_factor(foreground, style->color_factor); + background = nk_rgb_factor(background, style->color_factor); + glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); if (!glyph_len) return; while ((text_len < byte_len) && glyph_len) @@ -331,14 +334,14 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, /* draw background frame */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, bounds, &background->data.image, nk_white); + nk_draw_image(out, bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, bounds, style->rounding, background->data.color); - nk_stroke_rect(out, bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; }} @@ -547,6 +550,8 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, else background_color = background->data.color; + cursor_color = nk_rgb_factor(cursor_color, style->color_factor); + cursor_text_color = nk_rgb_factor(cursor_text_color, style->color_factor); if (edit->select_start == edit->select_end) { /* no selection so just draw the complete text */ @@ -654,6 +659,10 @@ nk_do_edit(nk_flags *state, struct nk_command_buffer *out, background_color = nk_rgba(0,0,0,0); else background_color = background->data.color; + + background_color = nk_rgb_factor(background_color, style->color_factor); + text_color = nk_rgb_factor(text_color, style->color_factor); + nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, area.y - edit->scrollbar.y, 0, begin, l, row_height, font, background_color, text_color, nk_false); @@ -773,6 +782,8 @@ nk_edit_buffer(struct nk_context *ctx, nk_flags flags, style = &ctx->style; state = nk_widget(&bounds, ctx); if (!state) return state; + else if (state == NK_WIDGET_DISABLED) + flags |= NK_EDIT_READ_ONLY; in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; /* check if edit is currently hot item */ diff --git a/src/nuklear_internal.h b/src/nuklear_internal.h index 4f71f30..a1c00bc 100644 --- a/src/nuklear_internal.h +++ b/src/nuklear_internal.h @@ -255,9 +255,9 @@ enum nk_toggle_type { NK_TOGGLE_OPTION }; NK_LIB nk_bool nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, nk_bool active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font); +NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font, nk_flags text_alignment); +NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment); /* progress */ NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, nk_bool modifiable); @@ -350,14 +350,14 @@ NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_prop #ifndef STBTT_malloc static void* nk_stbtt_malloc(nk_size size, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - return alloc->alloc(alloc->userdata, 0, size); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + return alloc->alloc(alloc->userdata, 0, size); } static void nk_stbtt_free(void *ptr, void *user_data) { - struct nk_allocator *alloc = (struct nk_allocator *) user_data; - alloc->free(alloc->userdata, ptr); + struct nk_allocator *alloc = (struct nk_allocator *) user_data; + alloc->free(alloc->userdata, ptr); } #define STBTT_malloc(x,u) nk_stbtt_malloc(x,u) diff --git a/src/nuklear_menu.c b/src/nuklear_menu.c index 60fe692..00ec5e1 100644 --- a/src/nuklear_menu.c +++ b/src/nuklear_menu.c @@ -128,7 +128,7 @@ nk_menu_begin_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -158,7 +158,7 @@ nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) is_clicked = nk_true; @@ -183,7 +183,7 @@ nk_menu_begin_symbol(struct nk_context *ctx, const char *id, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) is_clicked = nk_true; @@ -208,7 +208,7 @@ nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len, win = ctx->current; state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) @@ -241,7 +241,7 @@ nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len, state = nk_widget(&header, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, ctx->style.font, in)) is_clicked = nk_true; diff --git a/src/nuklear_panel.c b/src/nuklear_panel.c index f170d7c..792d774 100644 --- a/src/nuklear_panel.c +++ b/src/nuklear_panel.c @@ -76,12 +76,12 @@ nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) NK_LIB nk_bool nk_panel_is_sub(enum nk_panel_type type) { - return (type & NK_PANEL_SET_SUB)?1:0; + return ((int)type & (int)NK_PANEL_SET_SUB)?1:0; } NK_LIB nk_bool nk_panel_is_nonblock(enum nk_panel_type type) { - return (type & NK_PANEL_SET_NONBLOCK)?1:0; + return ((int)type & (int)NK_PANEL_SET_NONBLOCK)?1:0; } NK_LIB nk_bool nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) diff --git a/src/nuklear_popup.c b/src/nuklear_popup.c index e0c64dc..ee3a578 100644 --- a/src/nuklear_popup.c +++ b/src/nuklear_popup.c @@ -27,7 +27,7 @@ nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type, win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); (void)panel; title_len = (int)nk_strlen(title); title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); @@ -121,7 +121,7 @@ nk_nonblock_begin(struct nk_context *ctx, /* popups cannot have popups */ win = ctx->current; panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); + NK_ASSERT(!((int)panel->type & (int)NK_PANEL_SET_POPUP)); (void)panel; popup = win->popup.win; if (!popup) { @@ -194,7 +194,7 @@ nk_popup_close(struct nk_context *ctx) popup = ctx->current; NK_ASSERT(popup->parent); - NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); + NK_ASSERT((int)popup->layout->type & (int)NK_PANEL_SET_POPUP); popup->flags |= NK_WINDOW_HIDDEN; } NK_API void diff --git a/src/nuklear_progress.c b/src/nuklear_progress.c index 65578ca..4f487d7 100644 --- a/src/nuklear_progress.c +++ b/src/nuklear_progress.c @@ -62,28 +62,28 @@ nk_draw_progress(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw cursor */ switch(cursor->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *scursor, &cursor->data.image, nk_white); + nk_draw_image(out, *scursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_white); + nk_draw_nine_slice(out, *scursor, &cursor->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *scursor, style->rounding, cursor->data.color); - nk_stroke_rect(out, *scursor, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *scursor, style->rounding, nk_rgb_factor(cursor->data.color, style->color_factor)); + nk_stroke_rect(out, *scursor, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } } @@ -143,7 +143,7 @@ nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, nk_bool is_modify state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *cur; *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, *cur, max, is_modifyable, &style->progress, in); diff --git a/src/nuklear_property.c b/src/nuklear_property.c index 3470873..fb76d67 100644 --- a/src/nuklear_property.c +++ b/src/nuklear_property.c @@ -85,20 +85,22 @@ nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property * text.text = style->label_normal; } + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, background->data.color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(background->data.color, style->color_factor)); break; } @@ -249,7 +251,7 @@ nk_do_property(nk_flags *ws, text_edit->string.buffer.memory.ptr = dst; text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; - nk_do_edit(ws, out, edit, NK_EDIT_FIELD|NK_EDIT_AUTO_SELECT, + nk_do_edit(ws, out, edit, (int)NK_EDIT_FIELD|(int)NK_EDIT_AUTO_SELECT, filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); *length = text_edit->string.len; @@ -383,7 +385,7 @@ nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant old_state = *state; ctx->text_edit.clip = ctx->clip; in = ((s == NK_WIDGET_ROM && !win->property.active) || - layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_DISABLED) ? 0 : &ctx->input; nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, variant, inc_per_pixel, buffer, len, state, cursor, select_begin, select_end, &style->property, filter, in, style->font, &ctx->text_edit, diff --git a/src/nuklear_selectable.c b/src/nuklear_selectable.c index e5f7278..1b8c0b2 100644 --- a/src/nuklear_selectable.c +++ b/src/nuklear_selectable.c @@ -41,15 +41,18 @@ nk_draw_selectable(struct nk_command_buffer *out, text.text = style->text_normal_active; } } + + text.text = nk_rgb_factor(text.text, style->color_factor); + /* draw selectable background and text */ switch (background->type) { case NK_STYLE_ITEM_IMAGE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: text.background = nk_rgba(0, 0, 0, 0); - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: text.background = background->data.color; @@ -57,7 +60,7 @@ nk_draw_selectable(struct nk_command_buffer *out, break; } if (icon) { - if (img) nk_draw_image(out, *icon, img, nk_white); + if (img) nk_draw_image(out, *icon, img, nk_rgb_factor(nk_white, style->color_factor)); else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font); } nk_widget_text(out, *bounds, string, len, &text, align, font); @@ -218,7 +221,7 @@ nk_selectable_text(struct nk_context *ctx, const char *str, int len, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &style->selectable, in, style->font); } @@ -247,7 +250,7 @@ nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, &img, &style->selectable, in, style->font); } @@ -276,7 +279,7 @@ nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, state = nk_widget(&bounds, ctx); if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds, str, len, align, value, sym, &style->selectable, in, style->font); } diff --git a/src/nuklear_slider.c b/src/nuklear_slider.c index 188f7f4..872cbd1 100644 --- a/src/nuklear_slider.c +++ b/src/nuklear_slider.c @@ -78,6 +78,7 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, bar_color = style->bar_normal; cursor = &style->cursor_normal; } + /* calculate slider background bar */ bar.x = bounds->x; bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; @@ -93,26 +94,26 @@ nk_draw_slider(struct nk_command_buffer *out, nk_flags state, /* draw background */ switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, *bounds, &background->data.image, nk_white); + nk_draw_image(out, *bounds, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_white); + nk_draw_nine_slice(out, *bounds, &background->data.slice, nk_rgb_factor(nk_white, style->color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); + nk_fill_rect(out, *bounds, style->rounding, nk_rgb_factor(background->data.color, style->color_factor)); + nk_stroke_rect(out, *bounds, style->rounding, style->border, nk_rgb_factor(style->border_color, style->color_factor)); break; } /* draw slider bar */ - nk_fill_rect(out, bar, style->rounding, bar_color); - nk_fill_rect(out, fill, style->rounding, style->bar_filled); + nk_fill_rect(out, bar, style->rounding, nk_rgb_factor(bar_color, style->color_factor)); + nk_fill_rect(out, fill, style->rounding, nk_rgb_factor(style->bar_filled, style->color_factor)); /* draw cursor */ if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); + nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); else - nk_fill_circle(out, *visual_cursor, cursor->data.color); + nk_fill_circle(out, *visual_cursor, nk_rgb_factor(cursor->data.color, style->color_factor)); } NK_LIB float nk_do_slider(nk_flags *state, @@ -230,7 +231,7 @@ nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max state = nk_widget(&bounds, ctx); if (!state) return ret; - in = (/*state == NK_WIDGET_ROM || */ layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (/*state == NK_WIDGET_ROM || */ state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; old_value = *value; *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, diff --git a/src/nuklear_style.c b/src/nuklear_style.c index 0e0851e..709fe68 100644 --- a/src/nuklear_style.c +++ b/src/nuklear_style.c @@ -113,27 +113,32 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) text = &style->text; text->color = table[NK_COLOR_TEXT]; text->padding = nk_vec2(0,0); + text->color_factor = 1.0f; + text->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* default button */ button = &style->button; nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_BORDER]; - button->text_background = table[NK_COLOR_BUTTON]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->image_padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f, 0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 4.0f; - button->draw_begin = 0; - button->draw_end = 0; + button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); + button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); + button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); + button->border_color = table[NK_COLOR_BORDER]; + button->text_background = table[NK_COLOR_BUTTON]; + button->text_normal = table[NK_COLOR_TEXT]; + button->text_hover = table[NK_COLOR_TEXT]; + button->text_active = table[NK_COLOR_TEXT]; + button->padding = nk_vec2(2.0f,2.0f); + button->image_padding = nk_vec2(0.0f,0.0f); + button->touch_padding = nk_vec2(0.0f, 0.0f); + button->userdata = nk_handle_ptr(0); + button->text_alignment = NK_TEXT_CENTERED; + button->border = 1.0f; + button->rounding = 4.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + button->draw_begin = 0; + button->draw_end = 0; /* contextual button */ button = &style->contextual_button; @@ -152,6 +157,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -172,6 +180,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 1.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -193,6 +204,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* option toggle */ toggle = &style->option; @@ -212,6 +225,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) toggle->border_color = nk_rgba(0,0,0,0); toggle->border = 0.0f; toggle->spacing = 4; + toggle->color_factor = 1.0f; + toggle->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* selectable */ select = &style->selectable; @@ -233,6 +248,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) select->touch_padding = nk_vec2(0,0); select->userdata = nk_handle_ptr(0); select->rounding = 0.0f; + select->color_factor = 1.0f; + select->disabled_factor = NK_WIDGET_DISABLED_FACTOR; select->draw_begin = 0; select->draw_end = 0; @@ -258,6 +275,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) slider->show_buttons = nk_false; slider->bar_height = 8; slider->rounding = 0; + slider->color_factor = 1.0f; + slider->disabled_factor = NK_WIDGET_DISABLED_FACTOR; slider->draw_begin = 0; slider->draw_end = 0; @@ -277,6 +296,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->slider.dec_button = style->slider.inc_button; @@ -298,6 +320,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) prog->border = 0; prog->cursor_rounding = 0; prog->cursor_border = 0; + prog->color_factor = 1.0f; + prog->disabled_factor = NK_WIDGET_DISABLED_FACTOR; prog->draw_begin = 0; prog->draw_end = 0; @@ -321,6 +345,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) scroll->rounding = 0; scroll->border_cursor = 0; scroll->rounding_cursor = 0; + scroll->color_factor = 1.0f; + scroll->disabled_factor = NK_WIDGET_DISABLED_FACTOR; scroll->draw_begin = 0; scroll->draw_end = 0; style->scrollv = style->scrollh; @@ -341,6 +367,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 1.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->scrollh.dec_button = style->scrollh.inc_button; @@ -372,6 +401,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 4; edit->border = 1; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property */ property = &style->property; @@ -391,6 +422,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) property->rounding = 10; property->draw_begin = 0; property->draw_end = 0; + property->color_factor = 1.0f; + property->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* property buttons */ button = &style->property.dec_button; @@ -409,6 +442,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->property.inc_button = style->property.dec_button; @@ -435,6 +471,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) edit->cursor_size = 8; edit->border = 0; edit->rounding = 0; + edit->color_factor = 1.0f; + edit->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* chart */ chart = &style->chart; @@ -446,6 +484,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) chart->padding = nk_vec2(4,4); chart->border = 0; chart->rounding = 0; + chart->color_factor = 1.0f; + chart->disabled_factor = NK_WIDGET_DISABLED_FACTOR; + chart->show_markers = nk_true; /* combo */ combo = &style->combo; @@ -464,6 +505,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) combo->spacing = nk_vec2(4,0); combo->border = 1; combo->rounding = 0; + combo->color_factor = 1.0f; + combo->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* combo button */ button = &style->combo.button; @@ -482,6 +525,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -497,6 +543,8 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) tab->indent = 10.0f; tab->border = 1; tab->rounding = 0; + tab->color_factor = 1.0f; + tab->disabled_factor = NK_WIDGET_DISABLED_FACTOR; /* tab button */ button = &style->tab.tab_minimize_button; @@ -515,6 +563,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.tab_maximize_button =*button; @@ -536,6 +587,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; style->tab.node_maximize_button =*button; @@ -573,6 +627,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; @@ -593,6 +650,9 @@ nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) button->text_alignment = NK_TEXT_CENTERED; button->border = 0.0f; button->rounding = 0.0f; + button->color_factor_text = 1.0f; + button->color_factor_background = 1.0f; + button->disabled_factor = NK_WIDGET_DISABLED_FACTOR; button->draw_begin = 0; button->draw_end = 0; diff --git a/src/nuklear_text.c b/src/nuklear_text.c index 1ed967e..3df9149 100644 --- a/src/nuklear_text.c +++ b/src/nuklear_text.c @@ -114,7 +114,7 @@ nk_text_colored(struct nk_context *ctx, const char *str, int len, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); } NK_API void @@ -141,7 +141,7 @@ nk_text_wrap_colored(struct nk_context *ctx, const char *str, text.padding.x = item_padding.x; text.padding.y = item_padding.y; text.background = style->window.background; - text.text = color; + text.text = nk_rgb_factor(color, style->text.color_factor); nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); } #ifdef NK_INCLUDE_STANDARD_VARARGS diff --git a/src/nuklear_toggle.c b/src/nuklear_toggle.c index 0644a80..cb9e56a 100644 --- a/src/nuklear_toggle.c +++ b/src/nuklear_toggle.c @@ -26,7 +26,7 @@ nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -47,28 +47,29 @@ nk_draw_checkbox(struct nk_command_buffer *out, text.text = style->text_normal; } - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *selector, 0, style->border_color); - nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_rect(out, *cursors, 0, cursor->data.color); - } - + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); + + /* draw background and cursor */ + if (background->type == NK_STYLE_ITEM_COLOR) { + nk_fill_rect(out, *selector, 0, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + if (active) { + if (cursor->type == NK_STYLE_ITEM_IMAGE) + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); + else nk_fill_rect(out, *cursors, 0, cursor->data.color); + } } NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, nk_bool active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags text_alignment) { const struct nk_style_item *background; const struct nk_style_item *cursor; @@ -89,28 +90,29 @@ nk_draw_option(struct nk_command_buffer *out, text.text = style->text_normal; } - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_circle(out, *selector, style->border_color); - nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_circle(out, *cursors, cursor->data.color); - } - + text.text = nk_rgb_factor(text.text, style->color_factor); text.padding.x = 0; text.padding.y = 0; text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); + nk_widget_text(out, *label, string, len, &text, text_alignment, font); + + /* draw background and cursor */ + if (background->type == NK_STYLE_ITEM_COLOR) { + nk_fill_circle(out, *selector, nk_rgb_factor(style->border_color, style->color_factor)); + nk_fill_circle(out, nk_shrink_rect(*selector, style->border), nk_rgb_factor(background->data.color, style->color_factor)); + } else nk_draw_image(out, *selector, &background->data.image, nk_rgb_factor(nk_white, style->color_factor)); + if (active) { + if (cursor->type == NK_STYLE_ITEM_IMAGE) + nk_draw_image(out, *cursors, &cursor->data.image, nk_rgb_factor(nk_white, style->color_factor)); + else nk_fill_circle(out, *cursors, cursor->data.color); + } } NK_LIB nk_bool nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, nk_bool *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font) + const struct nk_user_font *font, nk_flags widget_alignment, nk_flags text_alignment) { int was_active; struct nk_rect bounds; @@ -136,8 +138,37 @@ nk_do_toggle(nk_flags *state, /* calculate the selector space */ select.w = font->height; select.h = select.w; - select.y = r.y + r.h/2.0f - select.h/2.0f; - select.x = r.x; + + if (widget_alignment & NK_WIDGET_ALIGN_RIGHT) { + select.x = r.x + r.w - font->height; + + /* label in front of the selector */ + label.x = r.x; + label.w = r.w - select.w - style->spacing * 2; + } else if (widget_alignment & NK_WIDGET_ALIGN_CENTERED) { + select.x = r.x + (r.w - select.w) / 2; + + /* label in front of selector */ + label.x = r.x; + label.w = (r.w - select.w - style->spacing * 2) / 2; + } else { /* Default: NK_WIDGET_ALIGN_LEFT */ + select.x = r.x; + + /* label behind the selector */ + label.x = select.x + select.w + style->spacing; + label.w = NK_MAX(r.x + r.w, label.x) - label.x; + } + + if (widget_alignment & NK_WIDGET_ALIGN_TOP) { + select.y = r.y; + } else if (widget_alignment & NK_WIDGET_ALIGN_BOTTOM) { + select.y = r.y + r.h - select.h - 2 * style->padding.y; + } else { /* Default: NK_WIDGET_ALIGN_MIDDLE */ + select.y = r.y + r.h/2.0f - select.h/2.0f; + } + + label.y = select.y; + label.h = select.w; /* calculate the bounds of the cursor inside the selector */ cursor.x = select.x + style->padding.x + style->border; @@ -145,12 +176,6 @@ nk_do_toggle(nk_flags *state, cursor.w = select.w - (2 * style->padding.x + 2 * style->border); cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.y = select.y; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - label.h = select.w; - /* update selector */ was_active = *active; *active = nk_toggle_behavior(in, bounds, state, *active); @@ -159,9 +184,9 @@ nk_do_toggle(nk_flags *state, if (style->draw_begin) style->draw_begin(out, style->userdata); if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); + nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font, text_alignment); } if (style->draw_end) style->draw_end(out, style->userdata); @@ -195,9 +220,37 @@ nk_check_text(struct nk_context *ctx, const char *text, int len, nk_bool active) state = nk_widget(&bounds, ctx); if (!state) return active; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return active; +} +NK_API nk_bool +nk_check_text_align(struct nk_context *ctx, const char *text, int len, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return active; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, + text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font, widget_alignment, text_alignment); return active; } NK_API unsigned int @@ -227,6 +280,18 @@ nk_checkbox_text(struct nk_context *ctx, const char *text, int len, nk_bool *act return old_val != *active; } NK_API nk_bool +nk_checkbox_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_val; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_val = *active; + *active = nk_check_text_align(ctx, text, len, *active, widget_alignment, text_alignment); + return old_val != *active; +} +NK_API nk_bool nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, unsigned int *flags, unsigned int value) { @@ -257,6 +322,10 @@ NK_API nk_bool nk_checkbox_label(struct nk_context *ctx, const char *label, nk_b { return nk_checkbox_text(ctx, label, nk_strlen(label), active); } +NK_API nk_bool nk_checkbox_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_checkbox_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} NK_API nk_bool nk_checkbox_flags_label(struct nk_context *ctx, const char *label, unsigned int *flags, unsigned int value) { @@ -290,9 +359,37 @@ nk_option_text(struct nk_context *ctx, const char *text, int len, nk_bool is_act state = nk_widget(&bounds, ctx); if (!state) return (int)state; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, NK_WIDGET_LEFT, NK_TEXT_LEFT); + return is_active; +} +NK_API nk_bool +nk_option_text_align(struct nk_context *ctx, const char *text, int len, nk_bool is_active, nk_flags widget_alignment, nk_flags text_alignment) +{ + struct nk_window *win; + struct nk_panel *layout; + const struct nk_input *in; + const struct nk_style *style; + + struct nk_rect bounds; + enum nk_widget_layout_states state; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + NK_ASSERT(ctx->current->layout); + if (!ctx || !ctx->current || !ctx->current->layout) + return is_active; + + win = ctx->current; + style = &ctx->style; + layout = win->layout; + + state = nk_widget(&bounds, ctx); + if (!state) return (int)state; + in = (state == NK_WIDGET_ROM || state == NK_WIDGET_DISABLED || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; + nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, + text, len, NK_TOGGLE_OPTION, &style->option, in, style->font, widget_alignment, text_alignment); return is_active; } NK_API nk_bool @@ -308,13 +405,35 @@ nk_radio_text(struct nk_context *ctx, const char *text, int len, nk_bool *active return old_value != *active; } NK_API nk_bool +nk_radio_text_align(struct nk_context *ctx, const char *text, int len, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + int old_value; + NK_ASSERT(ctx); + NK_ASSERT(text); + NK_ASSERT(active); + if (!ctx || !text || !active) return 0; + old_value = *active; + *active = nk_option_text_align(ctx, text, len, old_value, widget_alignment, text_alignment); + return old_value != *active; +} +NK_API nk_bool nk_option_label(struct nk_context *ctx, const char *label, nk_bool active) { return nk_option_text(ctx, label, nk_strlen(label), active); } NK_API nk_bool +nk_option_label_align(struct nk_context *ctx, const char *label, nk_bool active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_option_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} +NK_API nk_bool nk_radio_label(struct nk_context *ctx, const char *label, nk_bool *active) { return nk_radio_text(ctx, label, nk_strlen(label), active); } +NK_API nk_bool +nk_radio_label_align(struct nk_context *ctx, const char *label, nk_bool *active, nk_flags widget_alignment, nk_flags text_alignment) +{ + return nk_radio_text_align(ctx, label, nk_strlen(label), active, widget_alignment, text_alignment); +} diff --git a/src/nuklear_tooltip.c b/src/nuklear_tooltip.c index 38d8696..f4d78c6 100644 --- a/src/nuklear_tooltip.c +++ b/src/nuklear_tooltip.c @@ -24,7 +24,7 @@ nk_tooltip_begin(struct nk_context *ctx, float width) /* make sure that no nonblocking popup is currently active */ win = ctx->current; in = &ctx->input; - if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) + if (win->popup.win && ((int)win->popup.type & (int)NK_PANEL_SET_NONBLOCK)) return 0; w = nk_iceilf(width); diff --git a/src/nuklear_tree.c b/src/nuklear_tree.c index ef37ff0..0ccf68e 100644 --- a/src/nuklear_tree.c +++ b/src/nuklear_tree.c @@ -52,15 +52,15 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, switch(background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); break; } } else text.background = style->window.background; @@ -105,7 +105,7 @@ nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, label.y = sym.y; label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); label.h = style->font->height; - text.text = style->tab.text; + text.text = nk_rgb_factor(style->tab.text, style->tab.color_factor); text.padding = nk_vec2(0,0); nk_widget_text(out, label, title, nk_strlen(title), &text, NK_TEXT_LEFT, style->font);} @@ -242,15 +242,16 @@ nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type switch (background->type) { case NK_STYLE_ITEM_IMAGE: - nk_draw_image(out, header, &background->data.image, nk_white); + nk_draw_image(out, header, &background->data.image, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_NINE_SLICE: - nk_draw_nine_slice(out, header, &background->data.slice, nk_white); + nk_draw_nine_slice(out, header, &background->data.slice, nk_rgb_factor(nk_white, style->tab.color_factor)); break; case NK_STYLE_ITEM_COLOR: - nk_fill_rect(out, header, 0, style->tab.border_color); + nk_fill_rect(out, header, 0, nk_rgb_factor(style->tab.border_color, style->tab.color_factor)); nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); + style->tab.rounding, nk_rgb_factor(background->data.color, style->tab.color_factor)); + break; } } diff --git a/src/nuklear_widget.c b/src/nuklear_widget.c index 2e78cd5..a21f137 100644 --- a/src/nuklear_widget.c +++ b/src/nuklear_widget.c @@ -175,6 +175,8 @@ nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h); if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h)) return NK_WIDGET_INVALID; + if (win->widgets_disabled) + return NK_WIDGET_DISABLED; if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h)) return NK_WIDGET_ROM; return NK_WIDGET_VALID; @@ -227,4 +229,129 @@ nk_spacing(struct nk_context *ctx, int cols) nk_panel_alloc_space(&none, ctx); } layout->row.index = index; } +NK_API void +nk_widget_disable_begin(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_true; + + style->button.color_factor_text = style->button.disabled_factor; + style->button.color_factor_background = style->button.disabled_factor; + style->chart.color_factor = style->chart.disabled_factor; + style->checkbox.color_factor = style->checkbox.disabled_factor; + style->combo.color_factor = style->combo.disabled_factor; + style->combo.button.color_factor_text = style->combo.button.disabled_factor; + style->combo.button.color_factor_background = style->combo.button.disabled_factor; + style->contextual_button.color_factor_text = style->contextual_button.disabled_factor; + style->contextual_button.color_factor_background = style->contextual_button.disabled_factor; + style->edit.color_factor = style->edit.disabled_factor; + style->edit.scrollbar.color_factor = style->edit.scrollbar.disabled_factor; + style->menu_button.color_factor_text = style->menu_button.disabled_factor; + style->menu_button.color_factor_background = style->menu_button.disabled_factor; + style->option.color_factor = style->option.disabled_factor; + style->progress.color_factor = style->progress.disabled_factor; + style->property.color_factor = style->property.disabled_factor; + style->property.inc_button.color_factor_text = style->property.inc_button.disabled_factor; + style->property.inc_button.color_factor_background = style->property.inc_button.disabled_factor; + style->property.dec_button.color_factor_text = style->property.dec_button.disabled_factor; + style->property.dec_button.color_factor_background = style->property.dec_button.disabled_factor; + style->property.edit.color_factor = style->property.edit.disabled_factor; + style->scrollh.color_factor = style->scrollh.disabled_factor; + style->scrollh.inc_button.color_factor_text = style->scrollh.inc_button.disabled_factor; + style->scrollh.inc_button.color_factor_background = style->scrollh.inc_button.disabled_factor; + style->scrollh.dec_button.color_factor_text = style->scrollh.dec_button.disabled_factor; + style->scrollh.dec_button.color_factor_background = style->scrollh.dec_button.disabled_factor; + style->scrollv.color_factor = style->scrollv.disabled_factor; + style->scrollv.inc_button.color_factor_text = style->scrollv.inc_button.disabled_factor; + style->scrollv.inc_button.color_factor_background = style->scrollv.inc_button.disabled_factor; + style->scrollv.dec_button.color_factor_text = style->scrollv.dec_button.disabled_factor; + style->scrollv.dec_button.color_factor_background = style->scrollv.dec_button.disabled_factor; + style->selectable.color_factor = style->selectable.disabled_factor; + style->slider.color_factor = style->slider.disabled_factor; + style->slider.inc_button.color_factor_text = style->slider.inc_button.disabled_factor; + style->slider.inc_button.color_factor_background = style->slider.inc_button.disabled_factor; + style->slider.dec_button.color_factor_text = style->slider.dec_button.disabled_factor; + style->slider.dec_button.color_factor_background = style->slider.dec_button.disabled_factor; + style->tab.color_factor = style->tab.disabled_factor; + style->tab.node_maximize_button.color_factor_text = style->tab.node_maximize_button.disabled_factor; + style->tab.node_minimize_button.color_factor_text = style->tab.node_minimize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_text = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_maximize_button.color_factor_background = style->tab.tab_maximize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_text = style->tab.tab_minimize_button.disabled_factor; + style->tab.tab_minimize_button.color_factor_background = style->tab.tab_minimize_button.disabled_factor; + style->text.color_factor = style->text.disabled_factor; +} +NK_API void +nk_widget_disable_end(struct nk_context* ctx) +{ + struct nk_window* win; + struct nk_style* style; + + NK_ASSERT(ctx); + NK_ASSERT(ctx->current); + + if (!ctx || !ctx->current) + return; + + win = ctx->current; + style = &ctx->style; + + win->widgets_disabled = nk_false; + + style->button.color_factor_text = 1.0f; + style->button.color_factor_background = 1.0f; + style->chart.color_factor = 1.0f; + style->checkbox.color_factor = 1.0f; + style->combo.color_factor = 1.0f; + style->combo.button.color_factor_text = 1.0f; + style->combo.button.color_factor_background = 1.0f; + style->contextual_button.color_factor_text = 1.0f; + style->contextual_button.color_factor_background = 1.0f; + style->edit.color_factor = 1.0f; + style->edit.scrollbar.color_factor = 1.0f; + style->menu_button.color_factor_text = 1.0f; + style->menu_button.color_factor_background = 1.0f; + style->option.color_factor = 1.0f; + style->progress.color_factor = 1.0f; + style->property.color_factor = 1.0f; + style->property.inc_button.color_factor_text = 1.0f; + style->property.inc_button.color_factor_background = 1.0f; + style->property.dec_button.color_factor_text = 1.0f; + style->property.dec_button.color_factor_background = 1.0f; + style->property.edit.color_factor = 1.0f; + style->scrollh.color_factor = 1.0f; + style->scrollh.inc_button.color_factor_text = 1.0f; + style->scrollh.inc_button.color_factor_background = 1.0f; + style->scrollh.dec_button.color_factor_text = 1.0f; + style->scrollh.dec_button.color_factor_background = 1.0f; + style->scrollv.color_factor = 1.0f; + style->scrollv.inc_button.color_factor_text = 1.0f; + style->scrollv.inc_button.color_factor_background = 1.0f; + style->scrollv.dec_button.color_factor_text = 1.0f; + style->scrollv.dec_button.color_factor_background = 1.0f; + style->selectable.color_factor = 1.0f; + style->slider.color_factor = 1.0f; + style->slider.inc_button.color_factor_text = 1.0f; + style->slider.inc_button.color_factor_background = 1.0f; + style->slider.dec_button.color_factor_text = 1.0f; + style->slider.dec_button.color_factor_background = 1.0f; + style->tab.color_factor = 1.0f; + style->tab.node_maximize_button.color_factor_text = 1.0f; + style->tab.node_minimize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_text = 1.0f; + style->tab.tab_maximize_button.color_factor_background = 1.0f; + style->tab.tab_minimize_button.color_factor_text = 1.0f; + style->tab.tab_minimize_button.color_factor_background = 1.0f; + style->text.color_factor = 1.0f; +} diff --git a/src/nuklear_window.c b/src/nuklear_window.c index e69ad39..2e382b2 100644 --- a/src/nuklear_window.c +++ b/src/nuklear_window.c @@ -180,6 +180,7 @@ nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, NK_MEMCPY(win->name_string, name, name_length); win->name_string[name_length] = 0; win->popup.win = 0; + win->widgets_disabled = nk_false; if (!ctx->active) ctx->active = win; } else { diff --git a/src/stb_rect_pack.h b/src/stb_rect_pack.h index 6a633ce..1417197 100644 --- a/src/stb_rect_pack.h +++ b/src/stb_rect_pack.h @@ -311,7 +311,7 @@ static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0 if (node->y > min_y) { // raise min_y higher. // we've accounted for all waste up to min_y, - // but we'll now add more waste for everything we've visted + // but we'll now add more waste for everything we've visited waste_area += visited_width * (node->y - min_y); min_y = node->y; // the first time through, visited_width might be reduced @@ -466,7 +466,7 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i // insert the new node into the right starting point, and // let 'cur' point to the remaining nodes needing to be - // stiched back in + // stitched back in cur = *res.prev_link; if (cur->x < res.x) {