├── app └── .emptyfolder ├── gif └── .emptyfolder ├── img └── .emptyfolder ├── log └── .emptyfolder ├── out └── .emptyfolder ├── vid └── VKAutomata0000.mp4 ├── .editorconfig ├── sav ├── PCD256_archive.vkpat ├── PCD256_global_all.vkpat ├── PCD256_global_all.vkpat.bk ├── PCD256_global_all.vkpat.bk2 ├── PCD256_global_all.vkpat.bk3 ├── PCD256_global_all.vkpat.bk4 └── PCD256_global_all.vkpat.bk99 ├── res ├── data │ └── save_global.vkpat ├── vert │ └── vert_TriQuad.vert └── frag │ └── frag_automata0000.frag ├── script_buildrun.sh ├── make.ps1 ├── panic.sh ├── LICENSE ├── windows.md ├── README.md ├── lib ├── imgui_impl_glfw.h ├── imgui_impl_vulkan.h ├── imconfig.h ├── imstb_rectpack.h ├── imgui_impl_glfw.cpp └── imstb_textedit.h ├── imgui.ini └── make_video.sh /app/.emptyfolder: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /gif/.emptyfolder: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/.emptyfolder: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /log/.emptyfolder: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /out/.emptyfolder: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vid/VKAutomata0000.mp4: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | [*] 3 | indent_style = tab 4 | indent_size = 4 5 | -------------------------------------------------------------------------------- /sav/PCD256_archive.vkpat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_archive.vkpat -------------------------------------------------------------------------------- /res/data/save_global.vkpat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/res/data/save_global.vkpat -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat.bk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat.bk -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat.bk2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat.bk2 -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat.bk3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat.bk3 -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat.bk4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat.bk4 -------------------------------------------------------------------------------- /sav/PCD256_global_all.vkpat.bk99: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Slackermanz/VulkanAutomata/HEAD/sav/PCD256_global_all.vkpat.bk99 -------------------------------------------------------------------------------- /script_buildrun.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | logfn="./log/AppLog"$(date +%s)".log" 3 | script -q -c "./buildrun.sh" $logfn 4 | echo " " 5 | echo ' file://'$(realpath $logfn) 6 | echo " " 7 | -------------------------------------------------------------------------------- /make.ps1: -------------------------------------------------------------------------------- 1 | glslc -O ./res/vert/vert_TriQuad.vert -o ./app/vert_TriQuad.spv 2 | glslc -O ./res/frag/frag_automata0000.frag -o ./app/frag_automata0000.spv 3 | # g++ -std=c++17 lib/*.cpp VulkanAutomataGLFW.cpp -fconcepts -L C:\glfw-3.3.4.bin.WIN32\lib-mingw -lglfw3dll -L C:\VulkanSDK\1.2.170.0\Lib32 -lvulkan-1 -I C:\VulkanSDK\1.2.170.0\Include -I C:\glfw-3.3.4.bin.WIN32\include -o ./app/RunVkAuto 4 | # ./app/RunVKAuto 5 | -------------------------------------------------------------------------------- /res/vert/vert_TriQuad.vert: -------------------------------------------------------------------------------- 1 | #version 460 2 | #extension GL_ARB_separate_shader_objects : enable 3 | 4 | const float FILL_SCALE = 1.0; 5 | const float TRQD_SCALE = FILL_SCALE + 2.0; 6 | 7 | vec2 positions[3] = vec2[]( 8 | vec2(-FILL_SCALE, -FILL_SCALE), 9 | vec2( TRQD_SCALE, -FILL_SCALE), 10 | vec2(-FILL_SCALE, TRQD_SCALE) 11 | ); 12 | 13 | void main() { 14 | gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); 15 | } 16 | -------------------------------------------------------------------------------- /panic.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | killall 'RunVulkanAutomataGLFW' 3 | killall 'RunVulkanAutomataSDL' 4 | killall 'buildrun.sh' 5 | killall 'script_buildrun.sh' 6 | killall 'RunVkAuto' 7 | killall 'buildrun' 8 | killall 'script_buildrun' 9 | 10 | kill $(pidof xfce4-panel) 11 | killall xfce4-panel 12 | xfce4-panel & 13 | disown 14 | 15 | kill $(pidof xfce4-taskmanager) 16 | killall xfce4-taskmanager 17 | xfce4-taskmanager 18 | 19 | kill $(pidof bash) 20 | killall bash 21 | 22 | 23 | # xfwm4 --replace 24 | # kill $(pidof xfwm4) 25 | # killall xfwm4 26 | # xfwm4 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /windows.md: -------------------------------------------------------------------------------- 1 | ## VulkanAutomata 2 | Clone the VKAutoGLFW branch of VulkanAutomata.
3 | https://github.com/Slackermanz/VulkanAutomata/tree/VKAutoGLFW
4 | You could use this command to do it: `git clone --branch VKAutoGLFW https://github.com/Slackermanz/VulkanAutomata` 5 | 6 | ## GLFW 7 | Download and install the GLFW development library.
8 | You need to download the 32-bit binaries so that it works with MinGW.
9 | https://www.glfw.org/download
10 | 11 | Also, find `glfw3.dll` and place it into the `app` folder. 12 | 13 | ## Vulkan 14 | Download and install the Vulkan SDK.
15 | The one called something like: VulkanSDK-1.2.182.0-Installer.exe
16 | https://vulkan.lunarg.com/sdk/home 17 | 18 | ## MinGW 19 | Download and install MinGW from WinLibs, so that you can use the `g++` command to compile stuff.
20 | https://winlibs.com/
21 | Get the latest Win32 release version.
22 | Extract it somewhere and then add the `bin` folder to your path.
23 | For me, I had to my path: `C:\mingw32\bin`
24 | 25 | ## Includes 26 | Now you need to make a file called `make.ps1` with this inside: 27 | ```ps1 28 | glslc -O ./res/vert/vert_TriQuad.vert -o ./app/vert_TriQuad.spv 29 | glslc -O ./res/frag/frag_automata0000.frag -o ./app/frag_automata0000.spv 30 | g++ -std=c++17 lib/*.cpp VulkanAutomataGLFW.cpp -fconcepts -L C:\glfw-3.3.4.bin.WIN32\lib-mingw -lglfw3dll -L C:\VulkanSDK\1.2.170.0\Lib32 -lvulkan-1 -I C:\VulkanSDK\1.2.170.0\Include -I C:\glfw-3.3.4.bin.WIN32\include -o ./app/RunVkAuto 31 | ``` 32 | You need to edit the file with the locations of your Vulkan and GLFW installs.
33 | For example, do you see where it says `C:\glfw-3.3.4.bin.WIN32\lib-mingw`? Change that to where your GLFW install is.
34 | Do that for all four locations. 35 | 36 | ## Edit 37 | Change line 80 of `VulkanAutomataGLFW.cpp` to this: 38 | ```cpp 39 | valid = 1; } 40 | ``` 41 | 42 | ## Compile 43 | Run `make.ps1` in powershell with a command like this: `./make.ps1` 44 | 45 | ## Go! 46 | To use the VulkanAutomata... run `./app/RunVKAuto` in powershell. 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VulkanAutomata 2 | GPU-Accelerated Cellular Automata Render Engine using the Vulkan API 3 | 4 | Developed on `Xubuntu 20.04` 5 | 6 | --- 7 | 8 | [![Alt text](https://img.youtube.com/vi/MSINHosdRjU/0.jpg)](https://www.youtube.com/watch?v=MSINHosdRjU) 9 | 10 | Demo video: https://www.youtube.com/watch?v=MSINHosdRjU 11 | 12 | --- 13 | 14 | The Vulkan SDK can be found at: https://vulkan.lunarg.com/sdk/home 15 | 16 | For `Xubuntu 20.04`: 17 | 18 | `wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo apt-key add -` 19 | 20 | `sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-focal.list https://packages.lunarg.com/vulkan/lunarg-vulkan-focal.list` 21 | 22 | `sudo apt update` 23 | 24 | `sudo apt install vulkan-sdk` 25 | 26 | --- 27 | 28 | The Cellular Automata 'rules' are coded as Fragment Shaders in `./res/frag/` 29 | 30 | Shaders are compiled from `./res/vert/` and `./res/frag/` using the program `glslc` from the Vulkan SDK 31 | 32 | --- 33 | 34 | Scripts should be called from the location `./VulkanAutomata` 35 | 36 | Build & Run: 37 | 38 | `script_buildrun.sh` 39 | 40 | or 41 | 42 | `buildrun.sh` 43 | 44 | or 45 | 46 | `glslc -O ./res/vert/vert_TriQuad.vert -o ./app/vert_TriQuad.spv` 47 | 48 | `glslc -O ./res/frag/frag_automata0000.frag -o ./app/frag_automata0000.spv` 49 | 50 | `g++ VulkanAutomata.cpp -fconcepts -lvulkan -o ./app/RunVkAuto` 51 | 52 | `./app/RunVkAuto` 53 | 54 | --- 55 | 56 | Contacts & Networking: 57 | 58 | - Website: https://slackermanz.com 59 | 60 | - Discord: Slackermanz#3405 61 | 62 | - Github: https://github.com/Slackermanz 63 | 64 | - Twitter: https://twitter.com/slackermanz 65 | 66 | - YouTube: https://www.youtube.com/c/slackermanz 67 | 68 | - Shadertoy: https://www.shadertoy.com/user/SlackermanzCA 69 | 70 | - Reddit: https://old.reddit.com/user/slackermanz 71 | 72 | --- 73 | 74 | Communities: 75 | 76 | - Emergence Discord: https://discord.com/invite/J3phjtD 77 | 78 | - ConwayLifeLounge Discord: https://discord.gg/BCuYCEn 79 | 80 | - Reddit: https://old.reddit.com/r/cellular_automata 81 | 82 | 83 | -------------------------------------------------------------------------------- /lib/imgui_impl_glfw.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for GLFW 2 | // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) 3 | // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) 4 | 5 | // Implemented features: 6 | // [X] Platform: Clipboard support. 7 | // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 8 | // [x] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: 3 cursors types are missing from GLFW. 9 | // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 15 | 16 | // About GLSL version: 17 | // The 'glsl_version' initialization parameter defaults to "#version 150" if NULL. 18 | // Only override if your GL version doesn't handle this GLSL version. Keep NULL if unsure! 19 | 20 | #pragma once 21 | #include "imgui.h" // IMGUI_IMPL_API 22 | 23 | struct GLFWwindow; 24 | struct GLFWmonitor; 25 | 26 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); 27 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); 28 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks); 29 | IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); 30 | IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); 31 | 32 | // GLFW callbacks 33 | // - When calling Init with 'install_callbacks=true': GLFW callbacks will be installed for you. They will call user's previously installed callbacks, if any. 34 | // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call those function yourself from your own GLFW callbacks. 35 | IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); 36 | IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); 37 | IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); 38 | IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); 39 | IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); 40 | IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); 41 | -------------------------------------------------------------------------------- /imgui.ini: -------------------------------------------------------------------------------- 1 | [Window][Debug##Default] 2 | Pos=60,60 3 | Size=400,400 4 | Collapsed=0 5 | 6 | [Window][Dear ImGui Demo] 7 | Pos=108,68 8 | Size=569,463 9 | Collapsed=1 10 | 11 | [Window][Example: Log] 12 | Pos=-4,77 13 | Size=500,400 14 | Collapsed=0 15 | 16 | [Window][Example: Console] 17 | Pos=62,60 18 | Size=520,600 19 | Collapsed=0 20 | 21 | [Window][Dear ImGui Metrics/Debugger] 22 | Pos=209,94 23 | Size=339,290 24 | Collapsed=0 25 | 26 | [Window][Example: Custom rendering] 27 | Pos=104,77 28 | Size=485,414 29 | Collapsed=0 30 | 31 | [Window][Dear ImGui Style Editor] 32 | Pos=60,60 33 | Size=353,506 34 | Collapsed=0 35 | 36 | [Window][Stacked 1] 37 | Pos=307,170 38 | Size=409,172 39 | Collapsed=0 40 | 41 | [Window][Example: Long text display] 42 | Pos=345,182 43 | Size=520,600 44 | Collapsed=0 45 | 46 | [Window][Example: Property editor] 47 | Pos=60,60 48 | Size=430,450 49 | Collapsed=0 50 | 51 | [Window][Example: Simple layout] 52 | Pos=323,61 53 | Size=300,40 54 | Collapsed=0 55 | 56 | [Window][Demo window] 57 | Pos=60,60 58 | Size=196,83 59 | Collapsed=0 60 | 61 | [Window][Load Pattern Index] 62 | Pos=7,260 63 | Size=246,77 64 | Collapsed=0 65 | 66 | [Window][Recording Controls] 67 | Pos=150,92 68 | Size=216,154 69 | Collapsed=0 70 | 71 | [Window][Example: Constrained Resize] 72 | Pos=60,60 73 | Size=689,317 74 | Collapsed=0 75 | 76 | [Window][Example: Documents] 77 | Pos=60,60 78 | Size=621,506 79 | Collapsed=0 80 | 81 | [Window][Mutate] 82 | Pos=539,170 83 | Size=248,188 84 | Collapsed=0 85 | 86 | [Window][FPS Throttle] 87 | Pos=444,66 88 | Size=130,77 89 | Collapsed=0 90 | 91 | [Window][Load Pattern] 92 | Pos=74,94 93 | Size=272,77 94 | Collapsed=0 95 | 96 | [Window][Scale & Zoom] 97 | Pos=347,387 98 | Size=384,104 99 | Collapsed=0 100 | 101 | [Table][0xD0F0C6E3,2] 102 | Column 0 Weight=1.0000 103 | Column 1 Weight=1.0000 104 | 105 | [Table][0xC9935533,3] 106 | Column 0 Weight=1.0000 107 | Column 1 Weight=1.0000 108 | Column 2 Weight=1.0000 109 | 110 | [Table][0x64418101,3] 111 | RefScale=13 112 | Column 0 Width=63 113 | Column 1 Width=63 114 | Column 2 Width=63 115 | 116 | [Table][0x861D378E,3] 117 | Column 0 Weight=1.0000 118 | Column 1 Weight=1.0000 119 | Column 2 Weight=1.0000 120 | 121 | [Table][0x1F146634,3] 122 | RefScale=13 123 | Column 0 Width=63 124 | Column 1 Width=63 125 | Column 2 Width=63 126 | 127 | [Table][0xE0773582,3] 128 | Column 0 Weight=1.0000 129 | Column 1 Weight=1.0000 130 | Column 2 Weight=1.0000 131 | 132 | [Table][0x8DFA6E86,2] 133 | Column 0 Weight=1.0000 134 | Column 1 Weight=1.0000 135 | 136 | [Table][0xFABAAEF7,2] 137 | Column 0 Weight=1.0000 138 | Column 1 Weight=1.0000 139 | 140 | [Table][0x20DF7A63,4] 141 | RefScale=13 142 | Column 0 Width=28 Sort=0v 143 | Column 1 Width=42 144 | Column 2 Width=42 145 | Column 3 Weight=1.0000 146 | 147 | [Table][0xDA36A7E0,6] 148 | RefScale=13 149 | Column 0 Width=28 Sort=0v 150 | Column 1 Width=42 151 | Column 2 Width=73 152 | Column 3 Width=68 153 | Column 4 Weight=1.0000 154 | Column 5 Width=-1 155 | 156 | -------------------------------------------------------------------------------- /make_video.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | starttime=$(date +%s) 3 | 4 | # Get filename 5 | fn=$(basename -s .mp4 vid/VKAutomata[0-9][0-9][0-9][0-9].mp4) 6 | c0=${#fn} 7 | let c0=c0-3 8 | c1=${#fn} 9 | idn=$(echo $fn | cut -c$c0-$c1) 10 | idn=$(( 10#$idn )) 11 | let idn=idn+1 12 | let pad=4-${#idn} 13 | sf="0000" 14 | sf=$(echo $sf | cut -c1-$pad) 15 | sf=$sf$idn 16 | 17 | # Set inital "Thumbnail" frame, create seperate slides from potential thumnail frames 18 | th="out/IMG0.PAM" 19 | if test -f $th; then 20 | cp $th "out/SCR_INITAL.PAM" 21 | fi 22 | th="out/IMG1.PAM" 23 | if test -f $th; then 24 | cp $th "out/IMG0.PAM" 25 | cp $th "out/SCR0.PAM" 26 | fi 27 | th="out/IMG10.PAM" 28 | if test -f $th; then 29 | cp $th "out/IMG0.PAM" 30 | cp $th "out/SCR1.PAM" 31 | fi 32 | th="out/IMG60.PAM" 33 | if test -f $th; then 34 | cp $th "out/IMG0.PAM" 35 | cp $th "out/SCR2.PAM" 36 | fi 37 | th="out/IMG180.PAM" 38 | if test -f $th; then 39 | cp $th "out/IMG0.PAM" 40 | cp $th "out/SCR3.PAM" 41 | fi 42 | th="out/IMG600.PAM" 43 | if test -f $th; then 44 | cp $th "out/IMG0.PAM" 45 | cp $th "out/SCR4.PAM" 46 | fi 47 | th="out/IMG2400.PAM" 48 | if test -f $th; then 49 | cp $th "out/IMG0.PAM" 50 | cp $th "out/SCR5.PAM" 51 | fi 52 | th="out/IMG6400.PAM" 53 | if test -f $th; then 54 | cp $th "out/IMG0.PAM" 55 | cp $th "out/SCR6.PAM" 56 | fi 57 | th="out/IMG18000.PAM" 58 | if test -f $th; then 59 | cp $th "out/IMG0.PAM" 60 | cp $th "out/SCR7.PAM" 61 | fi 62 | 63 | ffmpeg -loglevel 4 -i out/SCR%00d.PAM "img/VKAutomata$sf"SCR%00d.png 64 | 65 | # Video output filepaths/filenames 66 | v0="vid/VKAutomata"$sf".mp4" 67 | 68 | v1="vid/VKAutomata"$sf"_SCALE.mp4" 69 | v2="vid/VKAutomata"$sf"_SMALL.mp4" 70 | 71 | v3="vid/VKAutomata"$sf"_4096x2048.mp4" 72 | v4="vid/VKAutomata"$sf"_2048x1024.mp4" 73 | v5="vid/VKAutomata"$sf"_1024x512.mp4" 74 | v6="vid/VKAutomata"$sf"_512x256.mp4" 75 | v7="vid/VKAutomata"$sf"_256x128.mp4" 76 | 77 | # Create MP4 videos 78 | buildtime=$(date +%s) 79 | echo " VID [1/3] "$v0 80 | ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -c:v libx264 -crf 12 -movflags +faststart -vf 'eq=gamma_r=1.26:gamma_g=1.19:gamma_b=1.08' -pix_fmt yuv420p $v0 81 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 82 | 83 | buildtime=$(date +%s) 84 | echo " VID [2/3] "$v2 85 | ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -c:v libx264 -crf 12 -movflags +faststart -vf 'scale=iw/2:ih/2:flags=bicubic,eq=gamma_r=1.26:gamma_g=1.19:gamma_b=1.08' -pix_fmt yuv420p $v2 86 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 87 | 88 | buildtime=$(date +%s) 89 | echo " VID [3/3] "$v1 90 | ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -c:v libx264 -crf 12 -movflags +faststart -vf 'scale=iw*4:ih*4:flags=neighbor,eq=gamma_r=1.26:gamma_g=1.19:gamma_b=1.08' -pix_fmt yuv420p $v1 91 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 92 | 93 | 94 | buildtime=$(date +%s) 95 | echo " VID [4/8] "$v3 96 | # ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -s 4096x2048 -sws_flags neighbor -c:v libx264 -crf 14 -movflags +faststart -pix_fmt yuv420p $v3 97 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 98 | 99 | buildtime=$(date +%s) 100 | echo " VID [5/8] "$v4 101 | # ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -s 2048x1024 -sws_flags neighbor -c:v libx264 -crf 14 -movflags +faststart -pix_fmt yuv420p $v4 102 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 103 | 104 | buildtime=$(date +%s) 105 | echo " VID [6/8] "$v5 106 | # ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -s 1024x512 -sws_flags neighbor -c:v libx264 -crf 14 -movflags +faststart -pix_fmt yuv420p $v5 107 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 108 | 109 | buildtime=$(date +%s) 110 | echo " VID [7/8] "$v6 111 | # ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -s 512x256 -sws_flags bicubic -c:v libx264 -crf 14 -movflags +faststart -pix_fmt yuv420p $v6 112 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 113 | 114 | buildtime=$(date +%s) 115 | echo " VID [8/8] "$v7 116 | # ffmpeg -loglevel 4 -framerate 60 -i out/IMG%00d.PAM -s 256x128 -sws_flags bicubic -c:v libx264 -crf 14 -movflags +faststart -pix_fmt yuv420p $v7 117 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 118 | 119 | 120 | # Temporary "Size" GIF output filepaths/filenames 121 | gs="gif/VKAutomata"$sf"_GSIZE.gif" 122 | gss="gif/VKAutomata"$sf"_GSSML.gif" 123 | 124 | # GIF output filepaths/filenames 125 | gf="gif/VKAutomata"$sf"_GFULL.gif" 126 | gc="gif/VKAutomata"$sf"_GCLIP.gif" 127 | 128 | gfs="gif/VKAutomata"$sf"_GFSML.gif" 129 | gcs="gif/VKAutomata"$sf"_GCSML.gif" 130 | 131 | # Get the filesize of the GIF 132 | buildtime=$(date +%s) 133 | echo " SIZE GIF [1/2] "$gss 134 | ffmpeg -loglevel 4 -i $v2 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30 $gss 135 | gssml=$(ls -s $gss | cut -d' ' -f 1) 136 | flsml=$(ls ./out | wc -l) 137 | let gsmod=($gssml/13312)+1 138 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 139 | 140 | # Create GIFs 141 | buildtime=$(date +%s) 142 | echo " GIF [1/4] "$gfs 143 | ffmpeg -loglevel 4 -i $v2 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30,"select=not(mod(n\,"$gsmod"))*gt(n\,0)",setpts=N/30/TB $gfs 144 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 145 | 146 | buildtime=$(date +%s) 147 | echo " GIF [2/4] "$gcs 148 | ffmpeg -loglevel 4 -i $v2 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30,"select=not(mod(n\,"$gsmod"))*gt(n\,12)",setpts=N/30/TB $gcs 149 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 150 | 151 | # Get the filesize of the GIF 152 | buildtime=$(date +%s) 153 | echo " SIZE GIF [2/2] "$gs 154 | ffmpeg -loglevel 4 -i $v0 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30 $gs 155 | gsize=$(ls -s $gs | cut -d' ' -f 1) 156 | files=$(ls ./out | wc -l) 157 | let gsmod=($gsize/13312)+1 158 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 159 | 160 | # Create GIFs 161 | buildtime=$(date +%s) 162 | echo " GIF [3/4] "$gf 163 | ffmpeg -loglevel 4 -i $v0 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30,"select=not(mod(n\,"$gsmod"))*gt(n\,0)",setpts=N/30/TB $gf 164 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 165 | 166 | buildtime=$(date +%s) 167 | echo " GIF [4/4] "$gc 168 | ffmpeg -loglevel 4 -i $v0 -lavfi palettegen=reserve_transparent=0:stats_mode=single[pal],[0:v][pal]paletteuse=new=1,fps=fps=30,"select=not(mod(n\,"$gsmod"))*gt(n\,12)",setpts=N/30/TB $gc 169 | echo " Seconds elapsed: "$(($(date +%s)-$buildtime)) 170 | 171 | 172 | # Delete temporary "Size" GIF files (cleanup) 173 | echo "REMOVING TEMP GIF [1/2] "$gs 174 | rm $gs 175 | echo "REMOVING TEMP GIF [2/2] "$gss 176 | rm $gss 177 | 178 | # Hope and pray that it worked! 179 | echo " Video Creation Complete!" 180 | echo " Total Seconds elapsed: "$(($(date +%s)-$starttime)) 181 | echo "" 182 | 183 | 184 | -------------------------------------------------------------------------------- /lib/imgui_impl_vulkan.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for Vulkan 2 | // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 3 | 4 | // Implemented features: 5 | // [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices. 6 | // Missing features: 7 | // [ ] Renderer: User texture binding. Changes of ImTextureID aren't supported by this backend! See https://github.com/ocornut/imgui/pull/914 8 | 9 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 10 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 11 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 12 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 13 | 14 | // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. 15 | // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ 16 | 17 | // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. 18 | // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. 19 | // You will use those if you want to use this rendering backend in your engine/app. 20 | // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by 21 | // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. 22 | // Read comments in imgui_impl_vulkan.h. 23 | 24 | #pragma once 25 | #include "imgui.h" // IMGUI_IMPL_API 26 | 27 | // [Configuration] in order to use a custom Vulkan function loader: 28 | // (1) You'll need to disable default Vulkan function prototypes. 29 | // We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag. 30 | // In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit: 31 | // - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file 32 | // - Or as a compilation flag in your build system 33 | // - Or uncomment here (not recommended because you'd be modifying imgui sources!) 34 | // - Do not simply add it in a .cpp file! 35 | // (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function. 36 | // If you have no idea what this is, leave it alone! 37 | //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES 38 | 39 | // Vulkan includes 40 | #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) 41 | #define VK_NO_PROTOTYPES 42 | #endif 43 | #include 44 | 45 | // Initialization data, for ImGui_ImplVulkan_Init() 46 | // [Please zero-clear before use!] 47 | struct ImGui_ImplVulkan_InitInfo 48 | { 49 | VkInstance Instance; 50 | VkPhysicalDevice PhysicalDevice; 51 | VkDevice Device; 52 | uint32_t QueueFamily; 53 | VkQueue Queue; 54 | VkPipelineCache PipelineCache; 55 | VkDescriptorPool DescriptorPool; 56 | uint32_t Subpass; 57 | uint32_t MinImageCount; // >= 2 58 | uint32_t ImageCount; // >= MinImageCount 59 | VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT 60 | const VkAllocationCallbacks* Allocator; 61 | void (*CheckVkResultFn)(VkResult err); 62 | }; 63 | 64 | // Called by user code 65 | IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); 66 | IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); 67 | IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); 68 | IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); 69 | IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); 70 | IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); 71 | IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) 72 | 73 | // Optional: load Vulkan functions with a custom function loader 74 | // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES 75 | IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = NULL); 76 | 77 | //------------------------------------------------------------------------- 78 | // Internal / Miscellaneous Vulkan Helpers 79 | // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) 80 | //------------------------------------------------------------------------- 81 | // You probably do NOT need to use or care about those functions. 82 | // Those functions only exist because: 83 | // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. 84 | // 2) the upcoming multi-viewport feature will need them internally. 85 | // Generally we avoid exposing any kind of superfluous high-level helpers in the backends, 86 | // but it is too much code to duplicate everywhere so we exceptionally expose them. 87 | // 88 | // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). 89 | // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. 90 | // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) 91 | //------------------------------------------------------------------------- 92 | 93 | struct ImGui_ImplVulkanH_Frame; 94 | struct ImGui_ImplVulkanH_Window; 95 | 96 | // Helpers 97 | IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); 98 | IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); 99 | IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); 100 | IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); 101 | IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); 102 | 103 | // Helper structure to hold the data needed by one rendering frame 104 | // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) 105 | // [Please zero-clear before use!] 106 | struct ImGui_ImplVulkanH_Frame 107 | { 108 | VkCommandPool CommandPool; 109 | VkCommandBuffer CommandBuffer; 110 | VkFence Fence; 111 | VkImage Backbuffer; 112 | VkImageView BackbufferView; 113 | VkFramebuffer Framebuffer; 114 | }; 115 | 116 | struct ImGui_ImplVulkanH_FrameSemaphores 117 | { 118 | VkSemaphore ImageAcquiredSemaphore; 119 | VkSemaphore RenderCompleteSemaphore; 120 | }; 121 | 122 | // Helper structure to hold the data needed by one rendering context into one OS window 123 | // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) 124 | struct ImGui_ImplVulkanH_Window 125 | { 126 | int Width; 127 | int Height; 128 | VkSwapchainKHR Swapchain; 129 | VkSurfaceKHR Surface; 130 | VkSurfaceFormatKHR SurfaceFormat; 131 | VkPresentModeKHR PresentMode; 132 | VkRenderPass RenderPass; 133 | VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo 134 | bool ClearEnable; 135 | VkClearValue ClearValue; 136 | uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) 137 | uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) 138 | uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) 139 | ImGui_ImplVulkanH_Frame* Frames; 140 | ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; 141 | 142 | ImGui_ImplVulkanH_Window() 143 | { 144 | memset(this, 0, sizeof(*this)); 145 | PresentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; 146 | ClearEnable = true; 147 | } 148 | }; 149 | 150 | -------------------------------------------------------------------------------- /lib/imconfig.h: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------------- 2 | // COMPILE-TIME OPTIONS FOR DEAR IMGUI 3 | // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. 4 | // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. 5 | //----------------------------------------------------------------------------- 6 | // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) 7 | // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. 8 | //----------------------------------------------------------------------------- 9 | // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp 10 | // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. 11 | // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. 12 | // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. 13 | //----------------------------------------------------------------------------- 14 | 15 | #pragma once 16 | 17 | //---- Define assertion handler. Defaults to calling assert(). 18 | // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. 19 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) 20 | //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts 21 | 22 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows 23 | // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. 24 | // DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() 25 | // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. 26 | //#define IMGUI_API __declspec( dllexport ) 27 | //#define IMGUI_API __declspec( dllimport ) 28 | 29 | //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. 30 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS 31 | 32 | //---- Disable all of Dear ImGui or don't implement standard windows. 33 | // It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp. 34 | //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. 35 | //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended. 36 | //#define IMGUI_DISABLE_METRICS_WINDOW // Disable metrics/debugger window: ShowMetricsWindow() will be empty. 37 | 38 | //---- Don't implement some functions to reduce linkage requirements. 39 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) 40 | //#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) 41 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) 42 | //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). 43 | //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). 44 | //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) 45 | //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. 46 | //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) 47 | //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. 48 | //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). 49 | //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available 50 | 51 | //---- Include imgui_user.h at the end of imgui.h as a convenience 52 | //#define IMGUI_INCLUDE_IMGUI_USER_H 53 | 54 | //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) 55 | //#define IMGUI_USE_BGRA_PACKED_COLOR 56 | 57 | //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) 58 | //#define IMGUI_USE_WCHAR32 59 | 60 | //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version 61 | // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. 62 | //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" 63 | //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" 64 | //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION 65 | //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION 66 | 67 | //---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) 68 | // Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf. 69 | // #define IMGUI_USE_STB_SPRINTF 70 | 71 | //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) 72 | // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). 73 | // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. 74 | //#define IMGUI_ENABLE_FREETYPE 75 | 76 | //---- Use stb_truetype to build and rasterize the font atlas (default) 77 | // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. 78 | //#define IMGUI_ENABLE_STB_TRUETYPE 79 | 80 | //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. 81 | // This will be inlined as part of ImVec2 and ImVec4 class declarations. 82 | /* 83 | #define IM_VEC2_CLASS_EXTRA \ 84 | ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ 85 | operator MyVec2() const { return MyVec2(x,y); } 86 | 87 | #define IM_VEC4_CLASS_EXTRA \ 88 | ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ 89 | operator MyVec4() const { return MyVec4(x,y,z,w); } 90 | */ 91 | 92 | //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. 93 | // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). 94 | // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. 95 | // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. 96 | //#define ImDrawIdx unsigned int 97 | 98 | //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) 99 | //struct ImDrawList; 100 | //struct ImDrawCmd; 101 | //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); 102 | //#define ImDrawCallback MyImDrawCallback 103 | 104 | //---- Debug Tools: Macro to break in Debugger 105 | // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) 106 | //#define IM_DEBUG_BREAK IM_ASSERT(0) 107 | //#define IM_DEBUG_BREAK __debugbreak() 108 | 109 | //---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(), 110 | // (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.) 111 | // This adds a small runtime cost which is why it is not enabled by default. 112 | //#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX 113 | 114 | //---- Debug Tools: Enable slower asserts 115 | //#define IMGUI_DEBUG_PARANOID 116 | 117 | //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. 118 | /* 119 | namespace ImGui 120 | { 121 | void MyFunction(const char* name, const MyMatrix44& v); 122 | } 123 | */ 124 | -------------------------------------------------------------------------------- /res/frag/frag_automata0000.frag: -------------------------------------------------------------------------------- 1 | // ---- ---- ---- ---- ---- ---- ---- ---- 2 | // 3 | // Shader developed by Slackermanz: 4 | // 5 | // https://slackermanz.com 6 | // 7 | // Discord: Slackermanz#3405 8 | // Github: https://github.com/Slackermanz 9 | // Twitter: https://twitter.com/slackermanz 10 | // YouTube: https://www.youtube.com/c/slackermanz 11 | // Shadertoy: https://www.shadertoy.com/user/SlackermanzCA 12 | // Reddit: https://old.reddit.com/user/slackermanz 13 | // 14 | // Communities: 15 | // Reddit: https://old.reddit.com/r/cellular_automata 16 | // Discord Servers: 17 | // Artificial Life: https://discord.gg/7qvBBVca7u 18 | // Emergence: https://discord.com/invite/J3phjtD 19 | // ConwayLifeLounge: https://discord.gg/BCuYCEn 20 | // 21 | // ---- ---- ---- ---- ---- ---- ---- ---- 22 | 23 | #version 460 24 | #define PI 3.14159265359 25 | #define LN 2.71828182846 26 | 27 | // ---- ---- ---- ---- ---- ---- ---- ---- 28 | 29 | layout(location = 0) out vec4 out_col; 30 | layout(binding = 1) uniform sampler2D txdata; 31 | layout(binding = 0) uniform UniBuf { 32 | uint v0; uint v1; uint v2; uint v3; uint v4; uint v5; uint v6; uint v7; 33 | uint v8; uint v9; uint v10; uint v11; uint v12; uint v13; uint v14; uint v15; 34 | uint v16; uint v17; uint v18; uint v19; uint v20; uint v21; uint v22; uint v23; 35 | uint v24; uint v25; uint v26; uint v27; uint v28; uint v29; uint v30; uint v31; 36 | uint v32; uint v33; uint v34; uint v35; uint v36; uint v37; uint v38; uint v39; 37 | uint v40; uint v41; uint v42; uint v43; uint v44; uint v45; uint v46; uint v47; 38 | uint v48; uint v49; uint v50; uint v51; uint v52; uint v53; uint v54; uint v55; 39 | uint v56; uint v57; uint v58; uint v59; uint v60; uint v61; uint v62; uint v63; } ub; 40 | 41 | // ---- ---- ---- ---- ---- ---- ---- ---- 42 | 43 | const uint MAX_RADIUS = 12u; 44 | 45 | // ---- ---- ---- ---- ---- ---- ---- ---- 46 | 47 | uint u32_upk(uint u32, uint bts, uint off) { return (u32 >> off) & ((1u << bts)-1u); } 48 | 49 | float lmap() { return (gl_FragCoord[0] / textureSize(txdata,0)[0]); } 50 | float vmap() { return (gl_FragCoord[1] / textureSize(txdata,0)[1]); } 51 | float cmap() { return sqrt ( ((gl_FragCoord[0] - textureSize(txdata,0)[0]*0.5) / textureSize(txdata,0)[0]*0.5) 52 | * ((gl_FragCoord[0] - textureSize(txdata,0)[0]*0.5) / textureSize(txdata,0)[0]*0.5) 53 | + ((gl_FragCoord[1] - textureSize(txdata,0)[1]*0.5) / textureSize(txdata,0)[1]*0.5) 54 | * ((gl_FragCoord[1] - textureSize(txdata,0)[1]*0.5) / textureSize(txdata,0)[1]*0.5) ); } 55 | 56 | float vwm() { 57 | float scale_raw = uintBitsToFloat(ub.v62); 58 | float zoom = uintBitsToFloat(ub.v61); 59 | float scale_new = scale_raw; 60 | uint mode = u32_upk(ub.v59, 2u, 0u); 61 | if( mode == 1u ) { // Linear Parameter Map 62 | scale_new = ((lmap() + zoom) * (scale_raw / (1.0 + zoom * 2.0))) * 2.0; } 63 | if( mode == 2u ) { // Circular Parameter Map 64 | scale_new = ((sqrt(cmap()) + zoom) * (scale_raw / (1.0 + zoom * 2.0))) * 2.0; } 65 | return scale_new; } 66 | 67 | float tp(uint n, float s) { return (float(n+1u)/256.0) * ((s*0.5)/128.0); } 68 | float bsn(uint v, uint o) { return float(u32_upk(v,1u,o)*2u)-1.0; } 69 | float utp(uint v, uint w, uint o) { return tp(u32_upk(v,w,w*o), vwm()); } 70 | 71 | vec4 sigm(vec4 x, float w) { return 1.0 / ( 1.0 + exp( (-w*2.0 * x * (PI/2.0)) + w * (PI/2.0) ) ); } 72 | float hmp2(float x, float w) { return 3.0*((x-0.5)*(x-0.5))+0.25; } 73 | 74 | vec4 gdv( ivec2 of, sampler2D tx ) { 75 | of = ivec2(gl_FragCoord) + of; 76 | of[0] = (of[0] + textureSize(tx,0)[0]) & (textureSize(tx,0)[0]-1); 77 | of[1] = (of[1] + textureSize(tx,0)[1]) & (textureSize(tx,0)[1]-1); 78 | return texelFetch( tx, of, 0); } 79 | 80 | vec4[2] nbhd( vec2 r, sampler2D tx ) { 81 | // Precision limit of signed float32 for [n] neighbors in a 16 bit texture (symmetry preservation) 82 | uint chk = 2147483648u / 83 | ( ( uint( r[0]*r[0]*PI + r[0]*PI + PI + 1u ) 84 | - uint( r[1]*r[1]*PI + r[1]*PI ) ) * 128u ); 85 | float psn = (chk >= 65536u) ? 65536.0 : float(chk); 86 | vec4 a = vec4(0.0,0.0,0.0,0.0); 87 | vec4 b = vec4(0.0,0.0,0.0,0.0); 88 | float w = 1.0; // Weighting, unused 89 | if(r[0] == 0.0) { return vec4[2]( gdv( ivec2(0,0), tx )*w*psn, vec4(psn,psn,psn,psn) ); } 90 | else { 91 | for(float i = 0.0; i <= r[0]; i++) { 92 | for(float j = 1.0; j <= r[0]; j++) { 93 | float d = round(sqrt(i*i+j*j)); 94 | w = 1.0; // Per-Neighbor Weighting, unused 95 | if( d <= r[0] && d > r[1] ) { 96 | b += w * psn * 4.0; 97 | vec4 t0 = gdv( ivec2( i, j), tx ) * w * psn; a += t0 - fract(t0); 98 | vec4 t1 = gdv( ivec2( j,-i), tx ) * w * psn; a += t1 - fract(t1); 99 | vec4 t2 = gdv( ivec2(-i,-j), tx ) * w * psn; a += t2 - fract(t2); 100 | vec4 t3 = gdv( ivec2(-j, i), tx ) * w * psn; a += t3 - fract(t3); } } } 101 | return vec4[2](a, b); } } 102 | 103 | vec4 bitring(vec4[MAX_RADIUS][2] rings, uint bits, uint of) { 104 | vec4 sum = vec4(0.0,0.0,0.0,0.0); 105 | vec4 tot = vec4(0.0,0.0,0.0,0.0); 106 | for(uint i = 0u; i < MAX_RADIUS; i++) { 107 | if(u32_upk(bits, 1u, i+of) == 1u) { sum += rings[i][0]; tot += rings[i][1]; } } 108 | return sigm( (sum / tot), LN ); } // TODO 109 | 110 | // ---- ---- ---- ---- ---- ---- ---- ---- 111 | 112 | // Used to reseed the surface with lumpy noise 113 | // TODO - Breaks down at 2048+ resolution 114 | float get_xc(float x, float y, float xmod) { 115 | float sq = sqrt(mod(x*y+y, xmod)) / sqrt(xmod); 116 | float xc = mod((x*x)+(y*y), xmod) / xmod; 117 | return clamp((sq+xc)*0.5, 0.0, 1.0); } 118 | float shuffle(float x, float y, float xmod, float val) { 119 | val = val * mod( x*y + x, xmod ); 120 | return (val-floor(val)); } 121 | float get_xcn(float x, float y, float xm0, float xm1, float ox, float oy) { 122 | float xc = get_xc(x+ox, y+oy, xm0); 123 | return shuffle(x+ox, y+oy, xm1, xc); } 124 | float get_lump(float x, float y, float nhsz, float xm0, float xm1) { 125 | float nhsz_c = 0.0; 126 | float xcn = 0.0; 127 | float nh_val = 0.0; 128 | for(float i = -nhsz; i <= nhsz; i += 1.0) { 129 | for(float j = -nhsz; j <= nhsz; j += 1.0) { 130 | nh_val = round(sqrt(i*i+j*j)); 131 | if(nh_val <= nhsz) { 132 | xcn = xcn + get_xcn(x, y, xm0, xm1, i, j); 133 | nhsz_c = nhsz_c + 1.0; } } } 134 | float xcnf = ( xcn / nhsz_c ); 135 | float xcaf = xcnf; 136 | for(float i = 0.0; i <= nhsz; i += 1.0) { 137 | xcaf = clamp((xcnf*xcaf + xcnf*xcaf) * (xcnf+xcnf), 0.0, 1.0); } 138 | return xcaf; } 139 | float reseed(uint seed, float scl, float amp) { 140 | float fx = gl_FragCoord[0]; 141 | float fy = gl_FragCoord[1]; 142 | float r0 = get_lump(fx, fy, round( 6.0 * scl), 19.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,17.0), 23.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,43.0)); 143 | float r1 = get_lump(fx, fy, round( 22.0 * scl), 13.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,29.0), 17.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,31.0)); 144 | float r2 = get_lump(fx, fy, round( 14.0 * scl), 13.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,11.0), 51.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,37.0)); 145 | float r3 = get_lump(fx, fy, round( 18.0 * scl), 29.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed, 7.0), 61.0 + mod(u32_upk(ub.v63, 24u, 0u)+seed,28.0)); 146 | return clamp( sqrt((r0+r1)*r3*(amp+1.2))-r2*(amp*1.8+0.2) , 0.0, 1.0); } 147 | 148 | vec4 place( vec4 col, float sz, vec2 mxy, uint s, float off ) { 149 | vec2 dxy = (vec2(gl_FragCoord) - mxy) * (vec2(gl_FragCoord) - mxy); 150 | float dist = sqrt(dxy[0] + dxy[1]); 151 | float cy = mod(u32_upk(ub.v63, 24u, 0u)+off, 213.0) / 213.0; 152 | float c2 = mod(u32_upk(ub.v63, 24u, 0u)+off, 377.0) / 377.0; 153 | float z2 = ((cos(2.0*PI*c2)/2.0)+0.5); 154 | float z3 = z2/4.0; 155 | float z4 = z2-z3; 156 | float ds = (1.0-dist/sz); 157 | float vr = (((cos((1.0*PI*4.0*cy)/2.0)+0.5) * z4 + z3) * ds * 0.85 + 0.38 * ds * ds); 158 | float vg = (((cos((2.0*PI*4.0*cy)/2.0)+0.5) * z4 + z3) * ds * 0.85 + 0.38 * ds * ds); 159 | float vb = (((cos((3.0*PI*4.0*cy)/2.0)+0.5) * z4 + z3) * ds * 0.85 + 0.38 * ds * ds); 160 | if(dist <= sz) { col += (s != 1u) ? vec4(-0.38,-0.38,-0.38,-0.38)*ds : vec4(vr,vg,vb,1.0); } 161 | return col; } 162 | 163 | vec4 mouse(vec4 col, float sz) { 164 | vec2 mxy = vec2( u32_upk(ub.v60, 12u, 0u), u32_upk(ub.v60, 12u, 12u) ); 165 | return place(col, sz, mxy, u32_upk(ub.v60, 2u, 24u), 0.0); } 166 | 167 | vec4 symsd(vec4 col, float sz) { 168 | vec2 posxy = vec2(textureSize(txdata,0)[0]/2.0,textureSize(txdata,0)[1]/2.0); 169 | for(int i = 0; i < 11; i++) { 170 | uint sn = ((i&2u)==0u) ? 1u : 0u; 171 | col = place(col, (sz/11.0)*((11.0-i)), posxy + vec2( 0.0, 0.0 ), sn, i*u32_upk(ub.v63, 24u, 0u)); 172 | col = place(col, (sz/11.0)*((11.0-i))*0.5, posxy + vec2( sz, 0.0 ), sn, i*u32_upk(ub.v63, 24u, 0u)); 173 | col = place(col, (sz/11.0)*((11.0-i))*0.5, posxy + vec2( -sz, 0.0 ), sn, i*u32_upk(ub.v63, 24u, 0u)); 174 | col = place(col, (sz/11.0)*((11.0-i))*0.5, posxy + vec2( 0.0, sz ), sn, i*u32_upk(ub.v63, 24u, 0u)); 175 | col = place(col, (sz/11.0)*((11.0-i))*0.5, posxy + vec2( 0.0, -sz ), sn, i*u32_upk(ub.v63, 24u, 0u)); } 176 | return col; } 177 | 178 | vec4 conv(vec2 r, sampler2D tx) { 179 | vec4[2] nh = nbhd(r, tx); 180 | return nh[0] / nh[1]; } 181 | 182 | vec4 blendseed(vec4 col, uint seed, float str) { 183 | 184 | // str = str * reseed(seed + 17u, 0.8, 0.0) + str * 0.5; 185 | 186 | float amp = 2.4 - (0.6 + str * 2.0); 187 | 188 | float randr = reseed(seed + 0u, 1.0, amp); 189 | float randg = reseed(seed + 1u, 1.0, amp); 190 | float randb = reseed(seed + 3u, 1.0, amp); 191 | float randa = reseed(seed + 5u, 1.0, amp); 192 | 193 | float blend = sqrt(reseed(seed + 7u, 0.3, 1.0) * reseed(seed + 11u, 0.6, 0.4)) + reseed(seed + 13u, 1.2, 0.0); 194 | 195 | float strsq = str * str; 196 | 197 | col = ( col - col * strsq ) + conv( vec2(round(11.0*str)+1.0, 0.0), txdata ) * strsq; 198 | 199 | col[0] = ( col[0] - col[0] * str * 0.5 ) + sqrt(randr * blend) * str; 200 | col[1] = ( col[1] - col[1] * str * 0.5 ) + sqrt(randg * blend) * str; 201 | col[2] = ( col[2] - col[2] * str * 0.5 ) + sqrt(randb * blend) * str; 202 | col[3] = ( col[3] - col[3] * str * 0.5 ) + sqrt(randa * blend) * str; 203 | 204 | col = ( col - col * str ) + conv( vec2(1.0, 0.0), txdata ) * str; 205 | 206 | return col; } 207 | 208 | // Seems to be very unstable, can compile as invalid SPIR-V 209 | // Split into seperate arrays, it seems to work (???) 210 | // Disabled (no entry point) by default, used for debugging 211 | vec4 show_data(vec4 col) { 212 | uint[16] ubval_0 = uint[16] ( 213 | ub.v0, ub.v1, ub.v2, ub.v3, ub.v4, ub.v5, ub.v6, ub.v7, 214 | ub.v8, ub.v9, ub.v10, ub.v11, ub.v12, ub.v13, ub.v14, ub.v15 ); 215 | for(uint i = 0u; i < 16u; i++) { 216 | for(uint j = 0u; j < 32u; j++) { 217 | if( uint(gl_FragCoord[1])/4u == i + 8u 218 | && uint(gl_FragCoord[0])/4u == j + 8u ) { 219 | float v = float(u32_upk(ubval_0[i-0u], 1u, j)); 220 | col[0] = v; col[1] = v; col[2] = v; } } } 221 | 222 | uint[16] ubval_1 = uint[16] ( 223 | ub.v16, ub.v17, ub.v18, ub.v19, ub.v20, ub.v21, ub.v22, ub.v23, 224 | ub.v24, ub.v25, ub.v26, ub.v27, ub.v28, ub.v29, ub.v30, ub.v31 ); 225 | for(uint i = 16u; i < 32u; i++) { 226 | for(uint j = 0u; j < 32u; j++) { 227 | if( uint(gl_FragCoord[1])/4u == i + 8u 228 | && uint(gl_FragCoord[0])/4u == j + 8u ) { 229 | float v = float(u32_upk(ubval_1[i-16u], 1u, j)); 230 | col[0] = v; col[1] = v; col[2] = v; } } } 231 | 232 | uint[16] ubval_2 = uint[16] ( 233 | ub.v32, ub.v33, ub.v34, ub.v35, ub.v36, ub.v37, ub.v38, ub.v39, 234 | ub.v40, ub.v41, ub.v42, ub.v43, ub.v44, ub.v45, ub.v46, ub.v47 ); 235 | for(uint i = 32u; i < 48u; i++) { 236 | for(uint j = 0u; j < 32u; j++) { 237 | if( uint(gl_FragCoord[1])/4u == i + 8u 238 | && uint(gl_FragCoord[0])/4u == j + 8u ) { 239 | float v = float(u32_upk(ubval_2[i-32u], 1u, j)); 240 | col[0] = v; col[1] = v; col[2] = v; } } } 241 | 242 | uint[16] ubval_3 = uint[16] ( 243 | ub.v48, ub.v49, ub.v50, ub.v51, ub.v52, ub.v53, ub.v54, ub.v55, 244 | ub.v56, ub.v57, ub.v58, ub.v59, ub.v60, ub.v61, ub.v62, ub.v63 ); 245 | for(uint i = 48u; i < 64u; i++) { 246 | for(uint j = 0u; j < 32u; j++) { 247 | if( uint(gl_FragCoord[1])/4u == i + 8u 248 | && uint(gl_FragCoord[0])/4u == j + 8u ) { 249 | float v = float(u32_upk(ubval_3[i-48u], 1u, j)); 250 | col[0] = v; col[1] = v; col[2] = v; } } } 251 | 252 | return col; } 253 | 254 | void main() { 255 | 256 | // ---- ---- ---- ---- ---- ---- ---- ---- 257 | // Rule Initilisation 258 | // ---- ---- ---- ---- ---- ---- ---- ---- 259 | 260 | // NH Rings 261 | vec4[MAX_RADIUS][2] nh_rings_c; 262 | for(uint i = 0u; i < MAX_RADIUS; i++) { 263 | nh_rings_c[i] = nbhd( vec2(i+1u,i), txdata ); } 264 | 265 | // Parameters 266 | const float mnp = 1.0 / 65536.0; // Minimum value of a precise step for 16-bit channel 267 | const float s = mnp * 48.0 * 64.0; 268 | const float n = mnp * 48.0 * 2.0; 269 | 270 | // Output Values 271 | vec4 res_c = gdv( ivec2(0, 0), txdata ); 272 | 273 | // Result Values 274 | vec4 res_v = res_c; 275 | 276 | // ---- ---- ---- ---- ---- ---- ---- ---- 277 | // Update Functions 278 | // ---- ---- ---- ---- ---- ---- ---- ---- 279 | /* 280 | // For patterns before ~18080 in the PCD408 global.vkpat 281 | // Neighborhoods 282 | uint[12] nb = uint[12] ( 283 | ub.v0, ub.v1, ub.v2, ub.v3, 284 | ub.v4, ub.v5, ub.v6, ub.v7, 285 | ub.v8, ub.v9, ub.v10, ub.v11 ); 286 | 287 | // Update Ranges 288 | uint[24] ur = uint[24] ( 289 | ub.v12, ub.v13, ub.v14, ub.v15, 290 | ub.v16, ub.v17, ub.v18, ub.v19, 291 | ub.v20, ub.v21, ub.v22, ub.v23, 292 | ub.v24, ub.v25, ub.v26, ub.v27, 293 | ub.v28, ub.v29, ub.v30, ub.v31, 294 | ub.v32, ub.v33, ub.v34, ub.v35 ); 295 | 296 | // Channel I/O 297 | uint[ 3] ch = uint[ 3] ( 2286157824u, 295261525u, 1713547946u ); 298 | 299 | // Update Signs (+/-) 300 | uint[ 2] us = uint[ 2] ( ub.v36, ub.v37 ); 301 | 302 | // Transition Function 303 | for(uint i = 0u; i < 24u; i++) { 304 | float nhv = bitring( nh_rings_c, nb[i/2u], (i & 1u) * 16u )[u32_upk( ch[i/8u], 2u, (i*4u+0u) & 31u )]; 305 | if( nhv >= utp( ur[i], 8u, 0u) && nhv <= utp( ur[i], 8u, 1u)) { 306 | float h = hmp2(res_c[u32_upk( ch[i/8u], 2u, (i*4u+0u) & 31u )],1.2); 307 | res_v[u32_upk( ch[i/8u], 2u, (i*4u+2u) & 31u )] 308 | += bsn(us[i/16u], ((i*2u+0u) & 31u)) * s * h; } 309 | if( nhv >= utp( ur[i], 8u, 2u) && nhv <= utp( ur[i], 8u, 3u)) { 310 | float h = hmp2(res_c[u32_upk( ch[i/8u], 2u, (i*4u+0u) & 31u )],1.2); 311 | res_v[u32_upk( ch[i/8u], 2u, (i*4u+2u) & 31u )] 312 | += bsn(us[i/16u], ((i*2u+1u) & 31u)) * s * h; } } 313 | 314 | // Decay Curve 315 | vec4 n4 = sigm(res_v, 0.5) * n * 64.0 + n; 316 | res_c = res_v - n4; 317 | /**/ 318 | 319 | // For patterns after ~18080 in the PCD408 global.vkpat 320 | // Neighborhoods 321 | /**/uint[12] nb = uint[12] ( 322 | ub.v0, ub.v1, ub.v2, ub.v3, 323 | ub.v4, ub.v5, ub.v6, ub.v7, 324 | ub.v8, ub.v9, ub.v10, ub.v11 ); 325 | 326 | uint[24] ur = uint[24] ( 327 | ub.v12, ub.v13, ub.v14, ub.v15, 328 | ub.v16, ub.v17, ub.v18, ub.v19, 329 | ub.v20, ub.v21, ub.v22, ub.v23, 330 | ub.v24, ub.v25, ub.v26, ub.v27, 331 | ub.v28, ub.v29, ub.v30, ub.v31, 332 | ub.v32, ub.v33, ub.v34, ub.v35 ); 333 | 334 | uint[ 3] ch2 = uint[ 3] ( 2286157824u, 295261525u, 1713547946u ); 335 | uint[ 3] ch = uint[ 3] ( ub.v38, ub.v39, ub.v40 ); 336 | uint[ 3] ch3 = uint[ 3] ( ub.v41, ub.v42, ub.v43 ); 337 | 338 | // Update Sign 339 | uint[ 2] us = uint[ 2] ( ub.v36, ub.v37 ); 340 | 341 | for(uint i = 0u; i < 24u; i++) { 342 | uint cho = u32_upk( ch[i/8u], 2u, (i*4u+0u) & 31u ); 343 | cho = (cho == 3u) ? u32_upk( ch2[i/8u], 2u, (i*4u+0u) & 31u ) : cho; 344 | uint chi = u32_upk( ch[i/8u], 2u, (i*4u+2u) & 31u ); 345 | chi = (chi == 3u) ? u32_upk( ch2[i/8u], 2u, (i*4u+2u) & 31u ) : chi; 346 | uint chm = u32_upk( ch3[i/8u], 2u, (i*4u+2u) & 31u ); 347 | chm = (chm == 3u) ? u32_upk( ch[i/8u], 2u, (i*4u+2u) & 31u ) : chm; 348 | 349 | float nhv = bitring( nh_rings_c, nb[i/2u], (i & 1u) * 16u )[cho]; 350 | 351 | if( nhv >= utp( ur[i], 8u, 0u) && nhv <= utp( ur[i], 8u, 1u)) { 352 | float h = hmp2(res_c[chm],1.2); 353 | res_v[chi] += bsn(us[i/16u], ((i*2u+0u) & 31u)) * s * h; } 354 | if( nhv >= utp( ur[i], 8u, 2u) && nhv <= utp( ur[i], 8u, 3u)) { 355 | float h = hmp2(res_c[chm],1.2); 356 | res_v[chi] += bsn(us[i/16u], ((i*2u+1u) & 31u)) * s * h; } } 357 | 358 | vec4 n4 = sigm(res_v, 0.5) * n * 64.0 + n; 359 | res_c = res_v - n4; 360 | 361 | /**/ 362 | 363 | // CGOL TEST OVERRIDE 364 | /* 365 | res_c = gdv( ivec2(0, 0), txdata ); 366 | vec4[2] cgol_val = nbhd( vec2(1.0,0.0), txdata ); 367 | vec4 sum = cgol_val[0]; 368 | vec4 tot = cgol_val[1]; 369 | vec4 res = sum / tot; 370 | 371 | if(res_c[0] >= 0.5 ) { res_c[0] = 1.0; } 372 | if(res_c[0] < 0.5 ) { res_c[0] = 0.0; } 373 | 374 | if(res_c[1] >= 0.5 ) { res_c[1] = 1.0; } 375 | if(res_c[1] < 0.5 ) { res_c[1] = 0.0; } 376 | 377 | if(res_c[2] >= 0.5 ) { res_c[2] = 1.0; } 378 | if(res_c[2] < 0.5 ) { res_c[2] = 0.0; } 379 | 380 | if(res_c[3] >= 0.5 ) { res_c[3] = 1.0; } 381 | if(res_c[3] < 0.5 ) { res_c[3] = 0.0; } 382 | 383 | if(res[0] <= (1.0 / 8.0)) { res_c[0] = 0.0; } 384 | if(res[0] >= (4.0 / 8.0)) { res_c[0] = 0.0; } 385 | if(res[0] >= (3.0 / 8.0) && res[0] <= (3.0 / 8.0) ) { res_c[0] = 1.0; } 386 | 387 | if(res[1] <= (1.0 / 8.0)) { res_c[1] = 0.0; } 388 | if(res[1] >= (4.0 / 8.0)) { res_c[1] = 0.0; } 389 | if(res[1] >= (3.0 / 8.0) && res[1] <= (3.0 / 8.0) ) { res_c[1] = 1.0; } 390 | 391 | if(res[2] <= (1.0 / 8.0)) { res_c[2] = 0.0; } 392 | if(res[2] >= (4.0 / 8.0)) { res_c[2] = 0.0; } 393 | if(res[2] >= (3.0 / 8.0) && res[2] <= (3.0 / 8.0) ) { res_c[2] = 1.0; } 394 | 395 | if(res[3] <= (1.0 / 8.0)) { res_c[3] = 0.0; } 396 | if(res[3] >= (4.0 / 8.0)) { res_c[3] = 0.0; } 397 | if(res[3] >= (3.0 / 8.0) && res[3] <= (3.0 / 8.0) ) { res_c[3] = 1.0; } 398 | /**/ 399 | 400 | // ---- ---- ---- ---- ---- ---- ---- ---- 401 | // Shader Output 402 | // ---- ---- ---- ---- ---- ---- ---- ---- 403 | 404 | //res_c = conv( vec2(1.0, 0.0) , txdata ); 405 | 406 | if( u32_upk(ub.v63, 24u, 0u) <= 0u 407 | || u32_upk(ub.v60, 6u, 26u) == 1u ) { 408 | res_c[0] = reseed( u32_upk(ub.v63, 8u, 24u) + 0u, 1.0, 0.4 ); 409 | res_c[1] = reseed( u32_upk(ub.v63, 8u, 24u) + 1u, 1.0, 0.4 ); 410 | res_c[2] = reseed( u32_upk(ub.v63, 8u, 24u) + 2u, 1.0, 0.4 ); 411 | res_c[3] = reseed( u32_upk(ub.v63, 8u, 24u) + 3u, 1.0, 0.4 ); } 412 | 413 | if( u32_upk(ub.v60, 6u, 26u) == 2u ) { 414 | res_c[0] = 0.0; 415 | res_c[1] = 0.0; 416 | res_c[2] = 0.0; 417 | res_c[3] = 1.0; } 418 | 419 | if( u32_upk(ub.v60, 6u, 26u) == 3u ) { 420 | res_c = symsd(res_c, 128.0); } 421 | 422 | if( u32_upk(ub.v60, 6u, 26u) == 4u ) { 423 | res_c = blendseed(res_c, u32_upk(ub.v63, 8u, 24u), vmap() * cmap() * 1.4 ); } 424 | 425 | if(u32_upk(ub.v60, 2u, 24u) != 0u) { 426 | res_c = mouse(res_c, 38.0); } 427 | 428 | // ShowData - Very slow if enabled, even if 'unused' 429 | // ... Modes are probably best facilitated by specialization constants 430 | // if(u32_upk(ub.v59, 1u, 2u) != 0u) { 431 | // res_c = show_data(res_c); } 432 | 433 | // Force alpha to 1.0 434 | res_c[3] = 1.0; 435 | 436 | out_col = res_c; 437 | 438 | } 439 | 440 | 441 | -------------------------------------------------------------------------------- /lib/imstb_rectpack.h: -------------------------------------------------------------------------------- 1 | // [DEAR IMGUI] 2 | // This is a slightly modified version of stb_rect_pack.h 1.00. 3 | // Those changes would need to be pushed into nothings/stb: 4 | // - Added STBRP__CDECL 5 | // Grep for [DEAR IMGUI] to find the changes. 6 | 7 | // stb_rect_pack.h - v1.00 - public domain - rectangle packing 8 | // Sean Barrett 2014 9 | // 10 | // Useful for e.g. packing rectangular textures into an atlas. 11 | // Does not do rotation. 12 | // 13 | // Not necessarily the awesomest packing method, but better than 14 | // the totally naive one in stb_truetype (which is primarily what 15 | // this is meant to replace). 16 | // 17 | // Has only had a few tests run, may have issues. 18 | // 19 | // More docs to come. 20 | // 21 | // No memory allocations; uses qsort() and assert() from stdlib. 22 | // Can override those by defining STBRP_SORT and STBRP_ASSERT. 23 | // 24 | // This library currently uses the Skyline Bottom-Left algorithm. 25 | // 26 | // Please note: better rectangle packers are welcome! Please 27 | // implement them to the same API, but with a different init 28 | // function. 29 | // 30 | // Credits 31 | // 32 | // Library 33 | // Sean Barrett 34 | // Minor features 35 | // Martins Mozeiko 36 | // github:IntellectualKitty 37 | // 38 | // Bugfixes / warning fixes 39 | // Jeremy Jaussaud 40 | // Fabian Giesen 41 | // 42 | // Version history: 43 | // 44 | // 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles 45 | // 0.99 (2019-02-07) warning fixes 46 | // 0.11 (2017-03-03) return packing success/fail result 47 | // 0.10 (2016-10-25) remove cast-away-const to avoid warnings 48 | // 0.09 (2016-08-27) fix compiler warnings 49 | // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) 50 | // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) 51 | // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort 52 | // 0.05: added STBRP_ASSERT to allow replacing assert 53 | // 0.04: fixed minor bug in STBRP_LARGE_RECTS support 54 | // 0.01: initial release 55 | // 56 | // LICENSE 57 | // 58 | // See end of file for license information. 59 | 60 | ////////////////////////////////////////////////////////////////////////////// 61 | // 62 | // INCLUDE SECTION 63 | // 64 | 65 | #ifndef STB_INCLUDE_STB_RECT_PACK_H 66 | #define STB_INCLUDE_STB_RECT_PACK_H 67 | 68 | #define STB_RECT_PACK_VERSION 1 69 | 70 | #ifdef STBRP_STATIC 71 | #define STBRP_DEF static 72 | #else 73 | #define STBRP_DEF extern 74 | #endif 75 | 76 | #ifdef __cplusplus 77 | extern "C" { 78 | #endif 79 | 80 | typedef struct stbrp_context stbrp_context; 81 | typedef struct stbrp_node stbrp_node; 82 | typedef struct stbrp_rect stbrp_rect; 83 | 84 | #ifdef STBRP_LARGE_RECTS 85 | typedef int stbrp_coord; 86 | #else 87 | typedef unsigned short stbrp_coord; 88 | #endif 89 | 90 | STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); 91 | // Assign packed locations to rectangles. The rectangles are of type 92 | // 'stbrp_rect' defined below, stored in the array 'rects', and there 93 | // are 'num_rects' many of them. 94 | // 95 | // Rectangles which are successfully packed have the 'was_packed' flag 96 | // set to a non-zero value and 'x' and 'y' store the minimum location 97 | // on each axis (i.e. bottom-left in cartesian coordinates, top-left 98 | // if you imagine y increasing downwards). Rectangles which do not fit 99 | // have the 'was_packed' flag set to 0. 100 | // 101 | // You should not try to access the 'rects' array from another thread 102 | // while this function is running, as the function temporarily reorders 103 | // the array while it executes. 104 | // 105 | // To pack into another rectangle, you need to call stbrp_init_target 106 | // again. To continue packing into the same rectangle, you can call 107 | // this function again. Calling this multiple times with multiple rect 108 | // arrays will probably produce worse packing results than calling it 109 | // a single time with the full rectangle array, but the option is 110 | // available. 111 | // 112 | // The function returns 1 if all of the rectangles were successfully 113 | // packed and 0 otherwise. 114 | 115 | struct stbrp_rect 116 | { 117 | // reserved for your use: 118 | int id; 119 | 120 | // input: 121 | stbrp_coord w, h; 122 | 123 | // output: 124 | stbrp_coord x, y; 125 | int was_packed; // non-zero if valid packing 126 | 127 | }; // 16 bytes, nominally 128 | 129 | 130 | STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); 131 | // Initialize a rectangle packer to: 132 | // pack a rectangle that is 'width' by 'height' in dimensions 133 | // using temporary storage provided by the array 'nodes', which is 'num_nodes' long 134 | // 135 | // You must call this function every time you start packing into a new target. 136 | // 137 | // There is no "shutdown" function. The 'nodes' memory must stay valid for 138 | // the following stbrp_pack_rects() call (or calls), but can be freed after 139 | // the call (or calls) finish. 140 | // 141 | // Note: to guarantee best results, either: 142 | // 1. make sure 'num_nodes' >= 'width' 143 | // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' 144 | // 145 | // If you don't do either of the above things, widths will be quantized to multiples 146 | // of small integers to guarantee the algorithm doesn't run out of temporary storage. 147 | // 148 | // If you do #2, then the non-quantized algorithm will be used, but the algorithm 149 | // may run out of temporary storage and be unable to pack some rectangles. 150 | 151 | STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); 152 | // Optionally call this function after init but before doing any packing to 153 | // change the handling of the out-of-temp-memory scenario, described above. 154 | // If you call init again, this will be reset to the default (false). 155 | 156 | 157 | STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); 158 | // Optionally select which packing heuristic the library should use. Different 159 | // heuristics will produce better/worse results for different data sets. 160 | // If you call init again, this will be reset to the default. 161 | 162 | enum 163 | { 164 | STBRP_HEURISTIC_Skyline_default=0, 165 | STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, 166 | STBRP_HEURISTIC_Skyline_BF_sortHeight 167 | }; 168 | 169 | 170 | ////////////////////////////////////////////////////////////////////////////// 171 | // 172 | // the details of the following structures don't matter to you, but they must 173 | // be visible so you can handle the memory allocations for them 174 | 175 | struct stbrp_node 176 | { 177 | stbrp_coord x,y; 178 | stbrp_node *next; 179 | }; 180 | 181 | struct stbrp_context 182 | { 183 | int width; 184 | int height; 185 | int align; 186 | int init_mode; 187 | int heuristic; 188 | int num_nodes; 189 | stbrp_node *active_head; 190 | stbrp_node *free_head; 191 | stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' 192 | }; 193 | 194 | #ifdef __cplusplus 195 | } 196 | #endif 197 | 198 | #endif 199 | 200 | ////////////////////////////////////////////////////////////////////////////// 201 | // 202 | // IMPLEMENTATION SECTION 203 | // 204 | 205 | #ifdef STB_RECT_PACK_IMPLEMENTATION 206 | #ifndef STBRP_SORT 207 | #include 208 | #define STBRP_SORT qsort 209 | #endif 210 | 211 | #ifndef STBRP_ASSERT 212 | #include 213 | #define STBRP_ASSERT assert 214 | #endif 215 | 216 | // [DEAR IMGUI] Added STBRP__CDECL 217 | #ifdef _MSC_VER 218 | #define STBRP__NOTUSED(v) (void)(v) 219 | #define STBRP__CDECL __cdecl 220 | #else 221 | #define STBRP__NOTUSED(v) (void)sizeof(v) 222 | #define STBRP__CDECL 223 | #endif 224 | 225 | enum 226 | { 227 | STBRP__INIT_skyline = 1 228 | }; 229 | 230 | STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) 231 | { 232 | switch (context->init_mode) { 233 | case STBRP__INIT_skyline: 234 | STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); 235 | context->heuristic = heuristic; 236 | break; 237 | default: 238 | STBRP_ASSERT(0); 239 | } 240 | } 241 | 242 | STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) 243 | { 244 | if (allow_out_of_mem) 245 | // if it's ok to run out of memory, then don't bother aligning them; 246 | // this gives better packing, but may fail due to OOM (even though 247 | // the rectangles easily fit). @TODO a smarter approach would be to only 248 | // quantize once we've hit OOM, then we could get rid of this parameter. 249 | context->align = 1; 250 | else { 251 | // if it's not ok to run out of memory, then quantize the widths 252 | // so that num_nodes is always enough nodes. 253 | // 254 | // I.e. num_nodes * align >= width 255 | // align >= width / num_nodes 256 | // align = ceil(width/num_nodes) 257 | 258 | context->align = (context->width + context->num_nodes-1) / context->num_nodes; 259 | } 260 | } 261 | 262 | STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) 263 | { 264 | int i; 265 | #ifndef STBRP_LARGE_RECTS 266 | STBRP_ASSERT(width <= 0xffff && height <= 0xffff); 267 | #endif 268 | 269 | for (i=0; i < num_nodes-1; ++i) 270 | nodes[i].next = &nodes[i+1]; 271 | nodes[i].next = NULL; 272 | context->init_mode = STBRP__INIT_skyline; 273 | context->heuristic = STBRP_HEURISTIC_Skyline_default; 274 | context->free_head = &nodes[0]; 275 | context->active_head = &context->extra[0]; 276 | context->width = width; 277 | context->height = height; 278 | context->num_nodes = num_nodes; 279 | stbrp_setup_allow_out_of_mem(context, 0); 280 | 281 | // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) 282 | context->extra[0].x = 0; 283 | context->extra[0].y = 0; 284 | context->extra[0].next = &context->extra[1]; 285 | context->extra[1].x = (stbrp_coord) width; 286 | #ifdef STBRP_LARGE_RECTS 287 | context->extra[1].y = (1<<30); 288 | #else 289 | context->extra[1].y = 65535; 290 | #endif 291 | context->extra[1].next = NULL; 292 | } 293 | 294 | // find minimum y position if it starts at x1 295 | static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) 296 | { 297 | stbrp_node *node = first; 298 | int x1 = x0 + width; 299 | int min_y, visited_width, waste_area; 300 | 301 | STBRP__NOTUSED(c); 302 | 303 | STBRP_ASSERT(first->x <= x0); 304 | 305 | #if 0 306 | // skip in case we're past the node 307 | while (node->next->x <= x0) 308 | ++node; 309 | #else 310 | STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency 311 | #endif 312 | 313 | STBRP_ASSERT(node->x <= x0); 314 | 315 | min_y = 0; 316 | waste_area = 0; 317 | visited_width = 0; 318 | while (node->x < x1) { 319 | if (node->y > min_y) { 320 | // raise min_y higher. 321 | // we've accounted for all waste up to min_y, 322 | // but we'll now add more waste for everything we've visted 323 | waste_area += visited_width * (node->y - min_y); 324 | min_y = node->y; 325 | // the first time through, visited_width might be reduced 326 | if (node->x < x0) 327 | visited_width += node->next->x - x0; 328 | else 329 | visited_width += node->next->x - node->x; 330 | } else { 331 | // add waste area 332 | int under_width = node->next->x - node->x; 333 | if (under_width + visited_width > width) 334 | under_width = width - visited_width; 335 | waste_area += under_width * (min_y - node->y); 336 | visited_width += under_width; 337 | } 338 | node = node->next; 339 | } 340 | 341 | *pwaste = waste_area; 342 | return min_y; 343 | } 344 | 345 | typedef struct 346 | { 347 | int x,y; 348 | stbrp_node **prev_link; 349 | } stbrp__findresult; 350 | 351 | static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) 352 | { 353 | int best_waste = (1<<30), best_x, best_y = (1 << 30); 354 | stbrp__findresult fr; 355 | stbrp_node **prev, *node, *tail, **best = NULL; 356 | 357 | // align to multiple of c->align 358 | width = (width + c->align - 1); 359 | width -= width % c->align; 360 | STBRP_ASSERT(width % c->align == 0); 361 | 362 | // if it can't possibly fit, bail immediately 363 | if (width > c->width || height > c->height) { 364 | fr.prev_link = NULL; 365 | fr.x = fr.y = 0; 366 | return fr; 367 | } 368 | 369 | node = c->active_head; 370 | prev = &c->active_head; 371 | while (node->x + width <= c->width) { 372 | int y,waste; 373 | y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); 374 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL 375 | // bottom left 376 | if (y < best_y) { 377 | best_y = y; 378 | best = prev; 379 | } 380 | } else { 381 | // best-fit 382 | if (y + height <= c->height) { 383 | // can only use it if it first vertically 384 | if (y < best_y || (y == best_y && waste < best_waste)) { 385 | best_y = y; 386 | best_waste = waste; 387 | best = prev; 388 | } 389 | } 390 | } 391 | prev = &node->next; 392 | node = node->next; 393 | } 394 | 395 | best_x = (best == NULL) ? 0 : (*best)->x; 396 | 397 | // if doing best-fit (BF), we also have to try aligning right edge to each node position 398 | // 399 | // e.g, if fitting 400 | // 401 | // ____________________ 402 | // |____________________| 403 | // 404 | // into 405 | // 406 | // | | 407 | // | ____________| 408 | // |____________| 409 | // 410 | // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned 411 | // 412 | // This makes BF take about 2x the time 413 | 414 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { 415 | tail = c->active_head; 416 | node = c->active_head; 417 | prev = &c->active_head; 418 | // find first node that's admissible 419 | while (tail->x < width) 420 | tail = tail->next; 421 | while (tail) { 422 | int xpos = tail->x - width; 423 | int y,waste; 424 | STBRP_ASSERT(xpos >= 0); 425 | // find the left position that matches this 426 | while (node->next->x <= xpos) { 427 | prev = &node->next; 428 | node = node->next; 429 | } 430 | STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); 431 | y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); 432 | if (y + height <= c->height) { 433 | if (y <= best_y) { 434 | if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { 435 | best_x = xpos; 436 | STBRP_ASSERT(y <= best_y); 437 | best_y = y; 438 | best_waste = waste; 439 | best = prev; 440 | } 441 | } 442 | } 443 | tail = tail->next; 444 | } 445 | } 446 | 447 | fr.prev_link = best; 448 | fr.x = best_x; 449 | fr.y = best_y; 450 | return fr; 451 | } 452 | 453 | static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) 454 | { 455 | // find best position according to heuristic 456 | stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); 457 | stbrp_node *node, *cur; 458 | 459 | // bail if: 460 | // 1. it failed 461 | // 2. the best node doesn't fit (we don't always check this) 462 | // 3. we're out of memory 463 | if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { 464 | res.prev_link = NULL; 465 | return res; 466 | } 467 | 468 | // on success, create new node 469 | node = context->free_head; 470 | node->x = (stbrp_coord) res.x; 471 | node->y = (stbrp_coord) (res.y + height); 472 | 473 | context->free_head = node->next; 474 | 475 | // insert the new node into the right starting point, and 476 | // let 'cur' point to the remaining nodes needing to be 477 | // stiched back in 478 | 479 | cur = *res.prev_link; 480 | if (cur->x < res.x) { 481 | // preserve the existing one, so start testing with the next one 482 | stbrp_node *next = cur->next; 483 | cur->next = node; 484 | cur = next; 485 | } else { 486 | *res.prev_link = node; 487 | } 488 | 489 | // from here, traverse cur and free the nodes, until we get to one 490 | // that shouldn't be freed 491 | while (cur->next && cur->next->x <= res.x + width) { 492 | stbrp_node *next = cur->next; 493 | // move the current node to the free list 494 | cur->next = context->free_head; 495 | context->free_head = cur; 496 | cur = next; 497 | } 498 | 499 | // stitch the list back in 500 | node->next = cur; 501 | 502 | if (cur->x < res.x + width) 503 | cur->x = (stbrp_coord) (res.x + width); 504 | 505 | #ifdef _DEBUG 506 | cur = context->active_head; 507 | while (cur->x < context->width) { 508 | STBRP_ASSERT(cur->x < cur->next->x); 509 | cur = cur->next; 510 | } 511 | STBRP_ASSERT(cur->next == NULL); 512 | 513 | { 514 | int count=0; 515 | cur = context->active_head; 516 | while (cur) { 517 | cur = cur->next; 518 | ++count; 519 | } 520 | cur = context->free_head; 521 | while (cur) { 522 | cur = cur->next; 523 | ++count; 524 | } 525 | STBRP_ASSERT(count == context->num_nodes+2); 526 | } 527 | #endif 528 | 529 | return res; 530 | } 531 | 532 | // [DEAR IMGUI] Added STBRP__CDECL 533 | static int STBRP__CDECL rect_height_compare(const void *a, const void *b) 534 | { 535 | const stbrp_rect *p = (const stbrp_rect *) a; 536 | const stbrp_rect *q = (const stbrp_rect *) b; 537 | if (p->h > q->h) 538 | return -1; 539 | if (p->h < q->h) 540 | return 1; 541 | return (p->w > q->w) ? -1 : (p->w < q->w); 542 | } 543 | 544 | // [DEAR IMGUI] Added STBRP__CDECL 545 | static int STBRP__CDECL rect_original_order(const void *a, const void *b) 546 | { 547 | const stbrp_rect *p = (const stbrp_rect *) a; 548 | const stbrp_rect *q = (const stbrp_rect *) b; 549 | return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); 550 | } 551 | 552 | #ifdef STBRP_LARGE_RECTS 553 | #define STBRP__MAXVAL 0xffffffff 554 | #else 555 | #define STBRP__MAXVAL 0xffff 556 | #endif 557 | 558 | STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) 559 | { 560 | int i, all_rects_packed = 1; 561 | 562 | // we use the 'was_packed' field internally to allow sorting/unsorting 563 | for (i=0; i < num_rects; ++i) { 564 | rects[i].was_packed = i; 565 | } 566 | 567 | // sort according to heuristic 568 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); 569 | 570 | for (i=0; i < num_rects; ++i) { 571 | if (rects[i].w == 0 || rects[i].h == 0) { 572 | rects[i].x = rects[i].y = 0; // empty rect needs no space 573 | } else { 574 | stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); 575 | if (fr.prev_link) { 576 | rects[i].x = (stbrp_coord) fr.x; 577 | rects[i].y = (stbrp_coord) fr.y; 578 | } else { 579 | rects[i].x = rects[i].y = STBRP__MAXVAL; 580 | } 581 | } 582 | } 583 | 584 | // unsort 585 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); 586 | 587 | // set was_packed flags and all_rects_packed status 588 | for (i=0; i < num_rects; ++i) { 589 | rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); 590 | if (!rects[i].was_packed) 591 | all_rects_packed = 0; 592 | } 593 | 594 | // return the all_rects_packed status 595 | return all_rects_packed; 596 | } 597 | #endif 598 | 599 | /* 600 | ------------------------------------------------------------------------------ 601 | This software is available under 2 licenses -- choose whichever you prefer. 602 | ------------------------------------------------------------------------------ 603 | ALTERNATIVE A - MIT License 604 | Copyright (c) 2017 Sean Barrett 605 | Permission is hereby granted, free of charge, to any person obtaining a copy of 606 | this software and associated documentation files (the "Software"), to deal in 607 | the Software without restriction, including without limitation the rights to 608 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 609 | of the Software, and to permit persons to whom the Software is furnished to do 610 | so, subject to the following conditions: 611 | The above copyright notice and this permission notice shall be included in all 612 | copies or substantial portions of the Software. 613 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 614 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 615 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 616 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 617 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 618 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 619 | SOFTWARE. 620 | ------------------------------------------------------------------------------ 621 | ALTERNATIVE B - Public Domain (www.unlicense.org) 622 | This is free and unencumbered software released into the public domain. 623 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 624 | software, either in source code form or as a compiled binary, for any purpose, 625 | commercial or non-commercial, and by any means. 626 | In jurisdictions that recognize copyright laws, the author or authors of this 627 | software dedicate any and all copyright interest in the software to the public 628 | domain. We make this dedication for the benefit of the public at large and to 629 | the detriment of our heirs and successors. We intend this dedication to be an 630 | overt act of relinquishment in perpetuity of all present and future rights to 631 | this software under copyright law. 632 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 633 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 634 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 635 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 636 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 637 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 638 | ------------------------------------------------------------------------------ 639 | */ 640 | -------------------------------------------------------------------------------- /lib/imgui_impl_glfw.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for GLFW 2 | // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) 3 | // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) 4 | // (Requires: GLFW 3.1+) 5 | 6 | // Implemented features: 7 | // [X] Platform: Clipboard support. 8 | // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). 10 | // [X] Platform: Keyboard arrays indexed using GLFW_KEY_* codes, e.g. ImGui::IsKeyPressed(GLFW_KEY_SPACE). 11 | 12 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 13 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 14 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 15 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 16 | 17 | // CHANGELOG 18 | // (minor and older changes stripped away, please see git history for details) 19 | // 2021-07-29: *BREAKING CHANGE*: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using glfwSetCursorEnterCallback). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install the glfwSetCursorEnterCallback() callback and the forward to the backend via ImGui_ImplGlfw_CursorEnterCallback(). 20 | // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). 21 | // 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors. 22 | // 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor). 23 | // 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown. 24 | // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter. 25 | // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter(). 26 | // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized. 27 | // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. 28 | // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them. 29 | // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls. 30 | // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. 31 | // 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples. 32 | // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag. 33 | // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()). 34 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. 35 | // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. 36 | // 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set. 37 | // 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). 38 | // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. 39 | // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert. 40 | // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1). 41 | // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. 42 | 43 | #include "imgui.h" 44 | #include "imgui_impl_glfw.h" 45 | 46 | // GLFW 47 | #include 48 | #ifdef _WIN32 49 | #undef APIENTRY 50 | #define GLFW_EXPOSE_NATIVE_WIN32 51 | #include // for glfwGetWin32Window 52 | #endif 53 | #define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ GLFW_FLOATING 54 | #define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ GLFW_HOVERED 55 | #define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwSetWindowOpacity 56 | #define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3300) // 3.3+ glfwGetMonitorContentScale 57 | #define GLFW_HAS_VULKAN (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3200) // 3.2+ glfwCreateWindowSurface 58 | #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released? 59 | #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR 60 | #else 61 | #define GLFW_HAS_NEW_CURSORS (0) 62 | #endif 63 | 64 | // GLFW data 65 | enum GlfwClientApi 66 | { 67 | GlfwClientApi_Unknown, 68 | GlfwClientApi_OpenGL, 69 | GlfwClientApi_Vulkan 70 | }; 71 | 72 | struct ImGui_ImplGlfw_Data 73 | { 74 | GLFWwindow* Window; 75 | GlfwClientApi ClientApi; 76 | double Time; 77 | GLFWwindow* MouseWindow; 78 | bool MouseJustPressed[ImGuiMouseButton_COUNT]; 79 | GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT]; 80 | bool InstalledCallbacks; 81 | 82 | // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. 83 | GLFWcursorenterfun PrevUserCallbackCursorEnter; 84 | GLFWmousebuttonfun PrevUserCallbackMousebutton; 85 | GLFWscrollfun PrevUserCallbackScroll; 86 | GLFWkeyfun PrevUserCallbackKey; 87 | GLFWcharfun PrevUserCallbackChar; 88 | GLFWmonitorfun PrevUserCallbackMonitor; 89 | 90 | ImGui_ImplGlfw_Data() { memset(this, 0, sizeof(*this)); } 91 | }; 92 | 93 | // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts 94 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 95 | // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. 96 | // - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks 97 | // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks. 98 | // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it. 99 | // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. 100 | static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData() 101 | { 102 | return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : NULL; 103 | } 104 | 105 | // Functions 106 | static const char* ImGui_ImplGlfw_GetClipboardText(void* user_data) 107 | { 108 | return glfwGetClipboardString((GLFWwindow*)user_data); 109 | } 110 | 111 | static void ImGui_ImplGlfw_SetClipboardText(void* user_data, const char* text) 112 | { 113 | glfwSetClipboardString((GLFWwindow*)user_data, text); 114 | } 115 | 116 | void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods) 117 | { 118 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 119 | if (bd->PrevUserCallbackMousebutton != NULL && window == bd->Window) 120 | bd->PrevUserCallbackMousebutton(window, button, action, mods); 121 | 122 | if (action == GLFW_PRESS && button >= 0 && button < IM_ARRAYSIZE(bd->MouseJustPressed)) 123 | bd->MouseJustPressed[button] = true; 124 | } 125 | 126 | void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset) 127 | { 128 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 129 | if (bd->PrevUserCallbackScroll != NULL && window == bd->Window) 130 | bd->PrevUserCallbackScroll(window, xoffset, yoffset); 131 | 132 | ImGuiIO& io = ImGui::GetIO(); 133 | io.MouseWheelH += (float)xoffset; 134 | io.MouseWheel += (float)yoffset; 135 | } 136 | 137 | void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) 138 | { 139 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 140 | if (bd->PrevUserCallbackKey != NULL && window == bd->Window) 141 | bd->PrevUserCallbackKey(window, key, scancode, action, mods); 142 | 143 | ImGuiIO& io = ImGui::GetIO(); 144 | if (key >= 0 && key < IM_ARRAYSIZE(io.KeysDown)) 145 | { 146 | if (action == GLFW_PRESS) 147 | io.KeysDown[key] = true; 148 | if (action == GLFW_RELEASE) 149 | io.KeysDown[key] = false; 150 | } 151 | 152 | // Modifiers are not reliable across systems 153 | io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; 154 | io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; 155 | io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; 156 | #ifdef _WIN32 157 | io.KeySuper = false; 158 | #else 159 | io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; 160 | #endif 161 | } 162 | 163 | void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered) 164 | { 165 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 166 | if (bd->PrevUserCallbackCursorEnter != NULL) 167 | bd->PrevUserCallbackCursorEnter(window, entered); 168 | if (entered) 169 | bd->MouseWindow = window; 170 | if (!entered && bd->MouseWindow == window) 171 | bd->MouseWindow = NULL; 172 | } 173 | 174 | void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c) 175 | { 176 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 177 | if (bd->PrevUserCallbackChar != NULL && window == bd->Window) 178 | bd->PrevUserCallbackChar(window, c); 179 | 180 | ImGuiIO& io = ImGui::GetIO(); 181 | io.AddInputCharacter(c); 182 | } 183 | 184 | void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int) 185 | { 186 | // Unused in 'master' branch but 'docking' branch will use this, so we declare it ahead of it so if you have to install callbacks you can install this one too. 187 | } 188 | 189 | static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) 190 | { 191 | ImGuiIO& io = ImGui::GetIO(); 192 | IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!"); 193 | 194 | // Setup backend capabilities flags 195 | ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)(); 196 | io.BackendPlatformUserData = (void*)bd; 197 | io.BackendPlatformName = "imgui_impl_glfw"; 198 | io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) 199 | io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) 200 | 201 | bd->Window = window; 202 | bd->Time = 0.0; 203 | 204 | // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array. 205 | io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; 206 | io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; 207 | io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; 208 | io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; 209 | io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; 210 | io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; 211 | io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; 212 | io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; 213 | io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; 214 | io.KeyMap[ImGuiKey_Insert] = GLFW_KEY_INSERT; 215 | io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; 216 | io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; 217 | io.KeyMap[ImGuiKey_Space] = GLFW_KEY_SPACE; 218 | io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; 219 | io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; 220 | io.KeyMap[ImGuiKey_KeyPadEnter] = GLFW_KEY_KP_ENTER; 221 | io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; 222 | io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; 223 | io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; 224 | io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; 225 | io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; 226 | io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; 227 | 228 | io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; 229 | io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; 230 | io.ClipboardUserData = bd->Window; 231 | #if defined(_WIN32) 232 | io.ImeWindowHandle = (void*)glfwGetWin32Window(bd->Window); 233 | #endif 234 | 235 | // Create mouse cursors 236 | // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist, 237 | // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting. 238 | // Missing cursors will return NULL and our _UpdateMouseCursor() function will use the Arrow cursor instead.) 239 | GLFWerrorfun prev_error_callback = glfwSetErrorCallback(NULL); 240 | bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); 241 | bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); 242 | bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR); 243 | bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR); 244 | bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR); 245 | #if GLFW_HAS_NEW_CURSORS 246 | bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR); 247 | bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR); 248 | bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR); 249 | bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR); 250 | #else 251 | bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); 252 | bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); 253 | bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); 254 | bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); 255 | #endif 256 | glfwSetErrorCallback(prev_error_callback); 257 | 258 | // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. 259 | bd->PrevUserCallbackMousebutton = NULL; 260 | bd->PrevUserCallbackScroll = NULL; 261 | bd->PrevUserCallbackKey = NULL; 262 | bd->PrevUserCallbackChar = NULL; 263 | bd->PrevUserCallbackMonitor = NULL; 264 | if (install_callbacks) 265 | { 266 | bd->InstalledCallbacks = true; 267 | bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback); 268 | bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback); 269 | bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback); 270 | bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback); 271 | bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback); 272 | bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback); 273 | } 274 | 275 | bd->ClientApi = client_api; 276 | return true; 277 | } 278 | 279 | bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks) 280 | { 281 | return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL); 282 | } 283 | 284 | bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks) 285 | { 286 | return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan); 287 | } 288 | 289 | bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks) 290 | { 291 | return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown); 292 | } 293 | 294 | void ImGui_ImplGlfw_Shutdown() 295 | { 296 | ImGuiIO& io = ImGui::GetIO(); 297 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 298 | 299 | if (bd->InstalledCallbacks) 300 | { 301 | glfwSetCursorEnterCallback(bd->Window, bd->PrevUserCallbackCursorEnter); 302 | glfwSetMouseButtonCallback(bd->Window, bd->PrevUserCallbackMousebutton); 303 | glfwSetScrollCallback(bd->Window, bd->PrevUserCallbackScroll); 304 | glfwSetKeyCallback(bd->Window, bd->PrevUserCallbackKey); 305 | glfwSetCharCallback(bd->Window, bd->PrevUserCallbackChar); 306 | glfwSetMonitorCallback(bd->PrevUserCallbackMonitor); 307 | } 308 | 309 | for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) 310 | glfwDestroyCursor(bd->MouseCursors[cursor_n]); 311 | 312 | io.BackendPlatformName = NULL; 313 | io.BackendPlatformUserData = NULL; 314 | IM_DELETE(bd); 315 | } 316 | 317 | static void ImGui_ImplGlfw_UpdateMousePosAndButtons() 318 | { 319 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 320 | ImGuiIO& io = ImGui::GetIO(); 321 | 322 | const ImVec2 mouse_pos_prev = io.MousePos; 323 | io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); 324 | 325 | // Update mouse buttons 326 | // (if a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame) 327 | for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) 328 | { 329 | io.MouseDown[i] = bd->MouseJustPressed[i] || glfwGetMouseButton(bd->Window, i) != 0; 330 | bd->MouseJustPressed[i] = false; 331 | } 332 | 333 | #ifdef __EMSCRIPTEN__ 334 | const bool focused = true; 335 | #else 336 | const bool focused = glfwGetWindowAttrib(bd->Window, GLFW_FOCUSED) != 0; 337 | #endif 338 | GLFWwindow* mouse_window = (bd->MouseWindow == bd->Window || focused) ? bd->Window : NULL; 339 | 340 | // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) 341 | if (io.WantSetMousePos && focused) 342 | glfwSetCursorPos(bd->Window, (double)mouse_pos_prev.x, (double)mouse_pos_prev.y); 343 | 344 | // Set Dear ImGui mouse position from OS position 345 | if (mouse_window != NULL) 346 | { 347 | double mouse_x, mouse_y; 348 | glfwGetCursorPos(mouse_window, &mouse_x, &mouse_y); 349 | io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); 350 | } 351 | } 352 | 353 | static void ImGui_ImplGlfw_UpdateMouseCursor() 354 | { 355 | ImGuiIO& io = ImGui::GetIO(); 356 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 357 | if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) 358 | return; 359 | 360 | ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); 361 | if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) 362 | { 363 | // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor 364 | glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); 365 | } 366 | else 367 | { 368 | // Show OS mouse cursor 369 | // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here. 370 | glfwSetCursor(bd->Window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]); 371 | glfwSetInputMode(bd->Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); 372 | } 373 | } 374 | 375 | static void ImGui_ImplGlfw_UpdateGamepads() 376 | { 377 | ImGuiIO& io = ImGui::GetIO(); 378 | memset(io.NavInputs, 0, sizeof(io.NavInputs)); 379 | if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) 380 | return; 381 | 382 | // Update gamepad inputs 383 | #define MAP_BUTTON(NAV_NO, BUTTON_NO) { if (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS) io.NavInputs[NAV_NO] = 1.0f; } 384 | #define MAP_ANALOG(NAV_NO, AXIS_NO, V0, V1) { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); if (v > 1.0f) v = 1.0f; if (io.NavInputs[NAV_NO] < v) io.NavInputs[NAV_NO] = v; } 385 | int axes_count = 0, buttons_count = 0; 386 | const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count); 387 | const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count); 388 | MAP_BUTTON(ImGuiNavInput_Activate, 0); // Cross / A 389 | MAP_BUTTON(ImGuiNavInput_Cancel, 1); // Circle / B 390 | MAP_BUTTON(ImGuiNavInput_Menu, 2); // Square / X 391 | MAP_BUTTON(ImGuiNavInput_Input, 3); // Triangle / Y 392 | MAP_BUTTON(ImGuiNavInput_DpadLeft, 13); // D-Pad Left 393 | MAP_BUTTON(ImGuiNavInput_DpadRight, 11); // D-Pad Right 394 | MAP_BUTTON(ImGuiNavInput_DpadUp, 10); // D-Pad Up 395 | MAP_BUTTON(ImGuiNavInput_DpadDown, 12); // D-Pad Down 396 | MAP_BUTTON(ImGuiNavInput_FocusPrev, 4); // L1 / LB 397 | MAP_BUTTON(ImGuiNavInput_FocusNext, 5); // R1 / RB 398 | MAP_BUTTON(ImGuiNavInput_TweakSlow, 4); // L1 / LB 399 | MAP_BUTTON(ImGuiNavInput_TweakFast, 5); // R1 / RB 400 | MAP_ANALOG(ImGuiNavInput_LStickLeft, 0, -0.3f, -0.9f); 401 | MAP_ANALOG(ImGuiNavInput_LStickRight,0, +0.3f, +0.9f); 402 | MAP_ANALOG(ImGuiNavInput_LStickUp, 1, +0.3f, +0.9f); 403 | MAP_ANALOG(ImGuiNavInput_LStickDown, 1, -0.3f, -0.9f); 404 | #undef MAP_BUTTON 405 | #undef MAP_ANALOG 406 | if (axes_count > 0 && buttons_count > 0) 407 | io.BackendFlags |= ImGuiBackendFlags_HasGamepad; 408 | else 409 | io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; 410 | } 411 | 412 | void ImGui_ImplGlfw_NewFrame() 413 | { 414 | ImGuiIO& io = ImGui::GetIO(); 415 | ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); 416 | IM_ASSERT(bd != NULL && "Did you call ImGui_ImplGlfw_InitForXXX()?"); 417 | 418 | // Setup display size (every frame to accommodate for window resizing) 419 | int w, h; 420 | int display_w, display_h; 421 | glfwGetWindowSize(bd->Window, &w, &h); 422 | glfwGetFramebufferSize(bd->Window, &display_w, &display_h); 423 | io.DisplaySize = ImVec2((float)w, (float)h); 424 | if (w > 0 && h > 0) 425 | io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); 426 | 427 | // Setup time step 428 | double current_time = glfwGetTime(); 429 | io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f); 430 | bd->Time = current_time; 431 | 432 | ImGui_ImplGlfw_UpdateMousePosAndButtons(); 433 | ImGui_ImplGlfw_UpdateMouseCursor(); 434 | 435 | // Update game controllers (if enabled and available) 436 | ImGui_ImplGlfw_UpdateGamepads(); 437 | } 438 | -------------------------------------------------------------------------------- /lib/imstb_textedit.h: -------------------------------------------------------------------------------- 1 | // [DEAR IMGUI] 2 | // This is a slightly modified version of stb_textedit.h 1.13. 3 | // Those changes would need to be pushed into nothings/stb: 4 | // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) 5 | // Grep for [DEAR IMGUI] to find the changes. 6 | 7 | // stb_textedit.h - v1.13 - public domain - Sean Barrett 8 | // Development of this library was sponsored by RAD Game Tools 9 | // 10 | // This C header file implements the guts of a multi-line text-editing 11 | // widget; you implement display, word-wrapping, and low-level string 12 | // insertion/deletion, and stb_textedit will map user inputs into 13 | // insertions & deletions, plus updates to the cursor position, 14 | // selection state, and undo state. 15 | // 16 | // It is intended for use in games and other systems that need to build 17 | // their own custom widgets and which do not have heavy text-editing 18 | // requirements (this library is not recommended for use for editing large 19 | // texts, as its performance does not scale and it has limited undo). 20 | // 21 | // Non-trivial behaviors are modelled after Windows text controls. 22 | // 23 | // 24 | // LICENSE 25 | // 26 | // See end of file for license information. 27 | // 28 | // 29 | // DEPENDENCIES 30 | // 31 | // Uses the C runtime function 'memmove', which you can override 32 | // by defining STB_TEXTEDIT_memmove before the implementation. 33 | // Uses no other functions. Performs no runtime allocations. 34 | // 35 | // 36 | // VERSION HISTORY 37 | // 38 | // 1.13 (2019-02-07) fix bug in undo size management 39 | // 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash 40 | // 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield 41 | // 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual 42 | // 1.9 (2016-08-27) customizable move-by-word 43 | // 1.8 (2016-04-02) better keyboard handling when mouse button is down 44 | // 1.7 (2015-09-13) change y range handling in case baseline is non-0 45 | // 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove 46 | // 1.5 (2014-09-10) add support for secondary keys for OS X 47 | // 1.4 (2014-08-17) fix signed/unsigned warnings 48 | // 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary 49 | // 1.2 (2014-05-27) fix some RAD types that had crept into the new code 50 | // 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) 51 | // 1.0 (2012-07-26) improve documentation, initial public release 52 | // 0.3 (2012-02-24) bugfixes, single-line mode; insert mode 53 | // 0.2 (2011-11-28) fixes to undo/redo 54 | // 0.1 (2010-07-08) initial version 55 | // 56 | // ADDITIONAL CONTRIBUTORS 57 | // 58 | // Ulf Winklemann: move-by-word in 1.1 59 | // Fabian Giesen: secondary key inputs in 1.5 60 | // Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 61 | // 62 | // Bugfixes: 63 | // Scott Graham 64 | // Daniel Keller 65 | // Omar Cornut 66 | // Dan Thompson 67 | // 68 | // USAGE 69 | // 70 | // This file behaves differently depending on what symbols you define 71 | // before including it. 72 | // 73 | // 74 | // Header-file mode: 75 | // 76 | // If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, 77 | // it will operate in "header file" mode. In this mode, it declares a 78 | // single public symbol, STB_TexteditState, which encapsulates the current 79 | // state of a text widget (except for the string, which you will store 80 | // separately). 81 | // 82 | // To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a 83 | // primitive type that defines a single character (e.g. char, wchar_t, etc). 84 | // 85 | // To save space or increase undo-ability, you can optionally define the 86 | // following things that are used by the undo system: 87 | // 88 | // STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position 89 | // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow 90 | // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer 91 | // 92 | // If you don't define these, they are set to permissive types and 93 | // moderate sizes. The undo system does no memory allocations, so 94 | // it grows STB_TexteditState by the worst-case storage which is (in bytes): 95 | // 96 | // [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT 97 | // + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT 98 | // 99 | // 100 | // Implementation mode: 101 | // 102 | // If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it 103 | // will compile the implementation of the text edit widget, depending 104 | // on a large number of symbols which must be defined before the include. 105 | // 106 | // The implementation is defined only as static functions. You will then 107 | // need to provide your own APIs in the same file which will access the 108 | // static functions. 109 | // 110 | // The basic concept is that you provide a "string" object which 111 | // behaves like an array of characters. stb_textedit uses indices to 112 | // refer to positions in the string, implicitly representing positions 113 | // in the displayed textedit. This is true for both plain text and 114 | // rich text; even with rich text stb_truetype interacts with your 115 | // code as if there was an array of all the displayed characters. 116 | // 117 | // Symbols that must be the same in header-file and implementation mode: 118 | // 119 | // STB_TEXTEDIT_CHARTYPE the character type 120 | // STB_TEXTEDIT_POSITIONTYPE small type that is a valid cursor position 121 | // STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow 122 | // STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer 123 | // 124 | // Symbols you must define for implementation mode: 125 | // 126 | // STB_TEXTEDIT_STRING the type of object representing a string being edited, 127 | // typically this is a wrapper object with other data you need 128 | // 129 | // STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) 130 | // STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters 131 | // starting from character #n (see discussion below) 132 | // STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character 133 | // to the xpos of the i+1'th char for a line of characters 134 | // starting at character #n (i.e. accounts for kerning 135 | // with previous char) 136 | // STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character 137 | // (return type is int, -1 means not valid to insert) 138 | // STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based 139 | // STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize 140 | // as manually wordwrapping for end-of-line positioning 141 | // 142 | // STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i 143 | // STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) 144 | // 145 | // STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key 146 | // 147 | // STB_TEXTEDIT_K_LEFT keyboard input to move cursor left 148 | // STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right 149 | // STB_TEXTEDIT_K_UP keyboard input to move cursor up 150 | // STB_TEXTEDIT_K_DOWN keyboard input to move cursor down 151 | // STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page 152 | // STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page 153 | // STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME 154 | // STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END 155 | // STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME 156 | // STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END 157 | // STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor 158 | // STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor 159 | // STB_TEXTEDIT_K_UNDO keyboard input to perform undo 160 | // STB_TEXTEDIT_K_REDO keyboard input to perform redo 161 | // 162 | // Optional: 163 | // STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode 164 | // STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), 165 | // required for default WORDLEFT/WORDRIGHT handlers 166 | // STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to 167 | // STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to 168 | // STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT 169 | // STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT 170 | // STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line 171 | // STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line 172 | // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text 173 | // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text 174 | // 175 | // Keyboard input must be encoded as a single integer value; e.g. a character code 176 | // and some bitflags that represent shift states. to simplify the interface, SHIFT must 177 | // be a bitflag, so we can test the shifted state of cursor movements to allow selection, 178 | // i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. 179 | // 180 | // You can encode other things, such as CONTROL or ALT, in additional bits, and 181 | // then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, 182 | // my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN 183 | // bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, 184 | // and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the 185 | // API below. The control keys will only match WM_KEYDOWN events because of the 186 | // keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN 187 | // bit so it only decodes WM_CHAR events. 188 | // 189 | // STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed 190 | // row of characters assuming they start on the i'th character--the width and 191 | // the height and the number of characters consumed. This allows this library 192 | // to traverse the entire layout incrementally. You need to compute word-wrapping 193 | // here. 194 | // 195 | // Each textfield keeps its own insert mode state, which is not how normal 196 | // applications work. To keep an app-wide insert mode, update/copy the 197 | // "insert_mode" field of STB_TexteditState before/after calling API functions. 198 | // 199 | // API 200 | // 201 | // void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) 202 | // 203 | // void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 204 | // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 205 | // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 206 | // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) 207 | // void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) 208 | // 209 | // Each of these functions potentially updates the string and updates the 210 | // state. 211 | // 212 | // initialize_state: 213 | // set the textedit state to a known good default state when initially 214 | // constructing the textedit. 215 | // 216 | // click: 217 | // call this with the mouse x,y on a mouse down; it will update the cursor 218 | // and reset the selection start/end to the cursor point. the x,y must 219 | // be relative to the text widget, with (0,0) being the top left. 220 | // 221 | // drag: 222 | // call this with the mouse x,y on a mouse drag/up; it will update the 223 | // cursor and the selection end point 224 | // 225 | // cut: 226 | // call this to delete the current selection; returns true if there was 227 | // one. you should FIRST copy the current selection to the system paste buffer. 228 | // (To copy, just copy the current selection out of the string yourself.) 229 | // 230 | // paste: 231 | // call this to paste text at the current cursor point or over the current 232 | // selection if there is one. 233 | // 234 | // key: 235 | // call this for keyboard inputs sent to the textfield. you can use it 236 | // for "key down" events or for "translated" key events. if you need to 237 | // do both (as in Win32), or distinguish Unicode characters from control 238 | // inputs, set a high bit to distinguish the two; then you can define the 239 | // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit 240 | // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is 241 | // clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to 242 | // anything other type you wante before including. 243 | // 244 | // 245 | // When rendering, you can read the cursor position and selection state from 246 | // the STB_TexteditState. 247 | // 248 | // 249 | // Notes: 250 | // 251 | // This is designed to be usable in IMGUI, so it allows for the possibility of 252 | // running in an IMGUI that has NOT cached the multi-line layout. For this 253 | // reason, it provides an interface that is compatible with computing the 254 | // layout incrementally--we try to make sure we make as few passes through 255 | // as possible. (For example, to locate the mouse pointer in the text, we 256 | // could define functions that return the X and Y positions of characters 257 | // and binary search Y and then X, but if we're doing dynamic layout this 258 | // will run the layout algorithm many times, so instead we manually search 259 | // forward in one pass. Similar logic applies to e.g. up-arrow and 260 | // down-arrow movement.) 261 | // 262 | // If it's run in a widget that *has* cached the layout, then this is less 263 | // efficient, but it's not horrible on modern computers. But you wouldn't 264 | // want to edit million-line files with it. 265 | 266 | 267 | //////////////////////////////////////////////////////////////////////////// 268 | //////////////////////////////////////////////////////////////////////////// 269 | //// 270 | //// Header-file mode 271 | //// 272 | //// 273 | 274 | #ifndef INCLUDE_STB_TEXTEDIT_H 275 | #define INCLUDE_STB_TEXTEDIT_H 276 | 277 | //////////////////////////////////////////////////////////////////////// 278 | // 279 | // STB_TexteditState 280 | // 281 | // Definition of STB_TexteditState which you should store 282 | // per-textfield; it includes cursor position, selection state, 283 | // and undo state. 284 | // 285 | 286 | #ifndef STB_TEXTEDIT_UNDOSTATECOUNT 287 | #define STB_TEXTEDIT_UNDOSTATECOUNT 99 288 | #endif 289 | #ifndef STB_TEXTEDIT_UNDOCHARCOUNT 290 | #define STB_TEXTEDIT_UNDOCHARCOUNT 999 291 | #endif 292 | #ifndef STB_TEXTEDIT_CHARTYPE 293 | #define STB_TEXTEDIT_CHARTYPE int 294 | #endif 295 | #ifndef STB_TEXTEDIT_POSITIONTYPE 296 | #define STB_TEXTEDIT_POSITIONTYPE int 297 | #endif 298 | 299 | typedef struct 300 | { 301 | // private data 302 | STB_TEXTEDIT_POSITIONTYPE where; 303 | STB_TEXTEDIT_POSITIONTYPE insert_length; 304 | STB_TEXTEDIT_POSITIONTYPE delete_length; 305 | int char_storage; 306 | } StbUndoRecord; 307 | 308 | typedef struct 309 | { 310 | // private data 311 | StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; 312 | STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; 313 | short undo_point, redo_point; 314 | int undo_char_point, redo_char_point; 315 | } StbUndoState; 316 | 317 | typedef struct 318 | { 319 | ///////////////////// 320 | // 321 | // public data 322 | // 323 | 324 | int cursor; 325 | // position of the text cursor within the string 326 | 327 | int select_start; // selection start point 328 | int select_end; 329 | // selection start and end point in characters; if equal, no selection. 330 | // note that start may be less than or greater than end (e.g. when 331 | // dragging the mouse, start is where the initial click was, and you 332 | // can drag in either direction) 333 | 334 | unsigned char insert_mode; 335 | // each textfield keeps its own insert mode state. to keep an app-wide 336 | // insert mode, copy this value in/out of the app state 337 | 338 | int row_count_per_page; 339 | // page size in number of row. 340 | // this value MUST be set to >0 for pageup or pagedown in multilines documents. 341 | 342 | ///////////////////// 343 | // 344 | // private data 345 | // 346 | unsigned char cursor_at_end_of_line; // not implemented yet 347 | unsigned char initialized; 348 | unsigned char has_preferred_x; 349 | unsigned char single_line; 350 | unsigned char padding1, padding2, padding3; 351 | float preferred_x; // this determines where the cursor up/down tries to seek to along x 352 | StbUndoState undostate; 353 | } STB_TexteditState; 354 | 355 | 356 | //////////////////////////////////////////////////////////////////////// 357 | // 358 | // StbTexteditRow 359 | // 360 | // Result of layout query, used by stb_textedit to determine where 361 | // the text in each row is. 362 | 363 | // result of layout query 364 | typedef struct 365 | { 366 | float x0,x1; // starting x location, end x location (allows for align=right, etc) 367 | float baseline_y_delta; // position of baseline relative to previous row's baseline 368 | float ymin,ymax; // height of row above and below baseline 369 | int num_chars; 370 | } StbTexteditRow; 371 | #endif //INCLUDE_STB_TEXTEDIT_H 372 | 373 | 374 | //////////////////////////////////////////////////////////////////////////// 375 | //////////////////////////////////////////////////////////////////////////// 376 | //// 377 | //// Implementation mode 378 | //// 379 | //// 380 | 381 | 382 | // implementation isn't include-guarded, since it might have indirectly 383 | // included just the "header" portion 384 | #ifdef STB_TEXTEDIT_IMPLEMENTATION 385 | 386 | #ifndef STB_TEXTEDIT_memmove 387 | #include 388 | #define STB_TEXTEDIT_memmove memmove 389 | #endif 390 | 391 | 392 | ///////////////////////////////////////////////////////////////////////////// 393 | // 394 | // Mouse input handling 395 | // 396 | 397 | // traverse the layout to locate the nearest character to a display position 398 | static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) 399 | { 400 | StbTexteditRow r; 401 | int n = STB_TEXTEDIT_STRINGLEN(str); 402 | float base_y = 0, prev_x; 403 | int i=0, k; 404 | 405 | r.x0 = r.x1 = 0; 406 | r.ymin = r.ymax = 0; 407 | r.num_chars = 0; 408 | 409 | // search rows to find one that straddles 'y' 410 | while (i < n) { 411 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 412 | if (r.num_chars <= 0) 413 | return n; 414 | 415 | if (i==0 && y < base_y + r.ymin) 416 | return 0; 417 | 418 | if (y < base_y + r.ymax) 419 | break; 420 | 421 | i += r.num_chars; 422 | base_y += r.baseline_y_delta; 423 | } 424 | 425 | // below all text, return 'after' last character 426 | if (i >= n) 427 | return n; 428 | 429 | // check if it's before the beginning of the line 430 | if (x < r.x0) 431 | return i; 432 | 433 | // check if it's before the end of the line 434 | if (x < r.x1) { 435 | // search characters in row for one that straddles 'x' 436 | prev_x = r.x0; 437 | for (k=0; k < r.num_chars; ++k) { 438 | float w = STB_TEXTEDIT_GETWIDTH(str, i, k); 439 | if (x < prev_x+w) { 440 | if (x < prev_x+w/2) 441 | return k+i; 442 | else 443 | return k+i+1; 444 | } 445 | prev_x += w; 446 | } 447 | // shouldn't happen, but if it does, fall through to end-of-line case 448 | } 449 | 450 | // if the last character is a newline, return that. otherwise return 'after' the last character 451 | if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) 452 | return i+r.num_chars-1; 453 | else 454 | return i+r.num_chars; 455 | } 456 | 457 | // API click: on mouse down, move the cursor to the clicked location, and reset the selection 458 | static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 459 | { 460 | // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse 461 | // goes off the top or bottom of the text 462 | if( state->single_line ) 463 | { 464 | StbTexteditRow r; 465 | STB_TEXTEDIT_LAYOUTROW(&r, str, 0); 466 | y = r.ymin; 467 | } 468 | 469 | state->cursor = stb_text_locate_coord(str, x, y); 470 | state->select_start = state->cursor; 471 | state->select_end = state->cursor; 472 | state->has_preferred_x = 0; 473 | } 474 | 475 | // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location 476 | static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) 477 | { 478 | int p = 0; 479 | 480 | // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse 481 | // goes off the top or bottom of the text 482 | if( state->single_line ) 483 | { 484 | StbTexteditRow r; 485 | STB_TEXTEDIT_LAYOUTROW(&r, str, 0); 486 | y = r.ymin; 487 | } 488 | 489 | if (state->select_start == state->select_end) 490 | state->select_start = state->cursor; 491 | 492 | p = stb_text_locate_coord(str, x, y); 493 | state->cursor = state->select_end = p; 494 | } 495 | 496 | ///////////////////////////////////////////////////////////////////////////// 497 | // 498 | // Keyboard input handling 499 | // 500 | 501 | // forward declarations 502 | static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); 503 | static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); 504 | static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); 505 | static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); 506 | static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); 507 | 508 | typedef struct 509 | { 510 | float x,y; // position of n'th character 511 | float height; // height of line 512 | int first_char, length; // first char of row, and length 513 | int prev_first; // first char of previous row 514 | } StbFindState; 515 | 516 | // find the x/y location of a character, and remember info about the previous row in 517 | // case we get a move-up event (for page up, we'll have to rescan) 518 | static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) 519 | { 520 | StbTexteditRow r; 521 | int prev_start = 0; 522 | int z = STB_TEXTEDIT_STRINGLEN(str); 523 | int i=0, first; 524 | 525 | if (n == z) { 526 | // if it's at the end, then find the last line -- simpler than trying to 527 | // explicitly handle this case in the regular code 528 | if (single_line) { 529 | STB_TEXTEDIT_LAYOUTROW(&r, str, 0); 530 | find->y = 0; 531 | find->first_char = 0; 532 | find->length = z; 533 | find->height = r.ymax - r.ymin; 534 | find->x = r.x1; 535 | } else { 536 | find->y = 0; 537 | find->x = 0; 538 | find->height = 1; 539 | while (i < z) { 540 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 541 | prev_start = i; 542 | i += r.num_chars; 543 | } 544 | find->first_char = i; 545 | find->length = 0; 546 | find->prev_first = prev_start; 547 | } 548 | return; 549 | } 550 | 551 | // search rows to find the one that straddles character n 552 | find->y = 0; 553 | 554 | for(;;) { 555 | STB_TEXTEDIT_LAYOUTROW(&r, str, i); 556 | if (n < i + r.num_chars) 557 | break; 558 | prev_start = i; 559 | i += r.num_chars; 560 | find->y += r.baseline_y_delta; 561 | } 562 | 563 | find->first_char = first = i; 564 | find->length = r.num_chars; 565 | find->height = r.ymax - r.ymin; 566 | find->prev_first = prev_start; 567 | 568 | // now scan to find xpos 569 | find->x = r.x0; 570 | for (i=0; first+i < n; ++i) 571 | find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); 572 | } 573 | 574 | #define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) 575 | 576 | // make the selection/cursor state valid if client altered the string 577 | static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 578 | { 579 | int n = STB_TEXTEDIT_STRINGLEN(str); 580 | if (STB_TEXT_HAS_SELECTION(state)) { 581 | if (state->select_start > n) state->select_start = n; 582 | if (state->select_end > n) state->select_end = n; 583 | // if clamping forced them to be equal, move the cursor to match 584 | if (state->select_start == state->select_end) 585 | state->cursor = state->select_start; 586 | } 587 | if (state->cursor > n) state->cursor = n; 588 | } 589 | 590 | // delete characters while updating undo 591 | static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) 592 | { 593 | stb_text_makeundo_delete(str, state, where, len); 594 | STB_TEXTEDIT_DELETECHARS(str, where, len); 595 | state->has_preferred_x = 0; 596 | } 597 | 598 | // delete the section 599 | static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 600 | { 601 | stb_textedit_clamp(str, state); 602 | if (STB_TEXT_HAS_SELECTION(state)) { 603 | if (state->select_start < state->select_end) { 604 | stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); 605 | state->select_end = state->cursor = state->select_start; 606 | } else { 607 | stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); 608 | state->select_start = state->cursor = state->select_end; 609 | } 610 | state->has_preferred_x = 0; 611 | } 612 | } 613 | 614 | // canoncialize the selection so start <= end 615 | static void stb_textedit_sortselection(STB_TexteditState *state) 616 | { 617 | if (state->select_end < state->select_start) { 618 | int temp = state->select_end; 619 | state->select_end = state->select_start; 620 | state->select_start = temp; 621 | } 622 | } 623 | 624 | // move cursor to first character of selection 625 | static void stb_textedit_move_to_first(STB_TexteditState *state) 626 | { 627 | if (STB_TEXT_HAS_SELECTION(state)) { 628 | stb_textedit_sortselection(state); 629 | state->cursor = state->select_start; 630 | state->select_end = state->select_start; 631 | state->has_preferred_x = 0; 632 | } 633 | } 634 | 635 | // move cursor to last character of selection 636 | static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 637 | { 638 | if (STB_TEXT_HAS_SELECTION(state)) { 639 | stb_textedit_sortselection(state); 640 | stb_textedit_clamp(str, state); 641 | state->cursor = state->select_end; 642 | state->select_start = state->select_end; 643 | state->has_preferred_x = 0; 644 | } 645 | } 646 | 647 | #ifdef STB_TEXTEDIT_IS_SPACE 648 | static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) 649 | { 650 | return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; 651 | } 652 | 653 | #ifndef STB_TEXTEDIT_MOVEWORDLEFT 654 | static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) 655 | { 656 | --c; // always move at least one character 657 | while( c >= 0 && !is_word_boundary( str, c ) ) 658 | --c; 659 | 660 | if( c < 0 ) 661 | c = 0; 662 | 663 | return c; 664 | } 665 | #define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous 666 | #endif 667 | 668 | #ifndef STB_TEXTEDIT_MOVEWORDRIGHT 669 | static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) 670 | { 671 | const int len = STB_TEXTEDIT_STRINGLEN(str); 672 | ++c; // always move at least one character 673 | while( c < len && !is_word_boundary( str, c ) ) 674 | ++c; 675 | 676 | if( c > len ) 677 | c = len; 678 | 679 | return c; 680 | } 681 | #define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next 682 | #endif 683 | 684 | #endif 685 | 686 | // update selection and cursor to match each other 687 | static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) 688 | { 689 | if (!STB_TEXT_HAS_SELECTION(state)) 690 | state->select_start = state->select_end = state->cursor; 691 | else 692 | state->cursor = state->select_end; 693 | } 694 | 695 | // API cut: delete selection 696 | static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 697 | { 698 | if (STB_TEXT_HAS_SELECTION(state)) { 699 | stb_textedit_delete_selection(str,state); // implicitly clamps 700 | state->has_preferred_x = 0; 701 | return 1; 702 | } 703 | return 0; 704 | } 705 | 706 | // API paste: replace existing selection with passed-in text 707 | static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) 708 | { 709 | // if there's a selection, the paste should delete it 710 | stb_textedit_clamp(str, state); 711 | stb_textedit_delete_selection(str,state); 712 | // try to insert the characters 713 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { 714 | stb_text_makeundo_insert(state, state->cursor, len); 715 | state->cursor += len; 716 | state->has_preferred_x = 0; 717 | return 1; 718 | } 719 | // [DEAR IMGUI] 720 | //// remove the undo since we didn't actually insert the characters 721 | //if (state->undostate.undo_point) 722 | // --state->undostate.undo_point; 723 | // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details) 724 | return 0; 725 | } 726 | 727 | #ifndef STB_TEXTEDIT_KEYTYPE 728 | #define STB_TEXTEDIT_KEYTYPE int 729 | #endif 730 | 731 | // API key: process a keyboard input 732 | static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) 733 | { 734 | retry: 735 | switch (key) { 736 | default: { 737 | int c = STB_TEXTEDIT_KEYTOTEXT(key); 738 | if (c > 0) { 739 | STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; 740 | 741 | // can't add newline in single-line mode 742 | if (c == '\n' && state->single_line) 743 | break; 744 | 745 | if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { 746 | stb_text_makeundo_replace(str, state, state->cursor, 1, 1); 747 | STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); 748 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { 749 | ++state->cursor; 750 | state->has_preferred_x = 0; 751 | } 752 | } else { 753 | stb_textedit_delete_selection(str,state); // implicitly clamps 754 | if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { 755 | stb_text_makeundo_insert(state, state->cursor, 1); 756 | ++state->cursor; 757 | state->has_preferred_x = 0; 758 | } 759 | } 760 | } 761 | break; 762 | } 763 | 764 | #ifdef STB_TEXTEDIT_K_INSERT 765 | case STB_TEXTEDIT_K_INSERT: 766 | state->insert_mode = !state->insert_mode; 767 | break; 768 | #endif 769 | 770 | case STB_TEXTEDIT_K_UNDO: 771 | stb_text_undo(str, state); 772 | state->has_preferred_x = 0; 773 | break; 774 | 775 | case STB_TEXTEDIT_K_REDO: 776 | stb_text_redo(str, state); 777 | state->has_preferred_x = 0; 778 | break; 779 | 780 | case STB_TEXTEDIT_K_LEFT: 781 | // if currently there's a selection, move cursor to start of selection 782 | if (STB_TEXT_HAS_SELECTION(state)) 783 | stb_textedit_move_to_first(state); 784 | else 785 | if (state->cursor > 0) 786 | --state->cursor; 787 | state->has_preferred_x = 0; 788 | break; 789 | 790 | case STB_TEXTEDIT_K_RIGHT: 791 | // if currently there's a selection, move cursor to end of selection 792 | if (STB_TEXT_HAS_SELECTION(state)) 793 | stb_textedit_move_to_last(str, state); 794 | else 795 | ++state->cursor; 796 | stb_textedit_clamp(str, state); 797 | state->has_preferred_x = 0; 798 | break; 799 | 800 | case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: 801 | stb_textedit_clamp(str, state); 802 | stb_textedit_prep_selection_at_cursor(state); 803 | // move selection left 804 | if (state->select_end > 0) 805 | --state->select_end; 806 | state->cursor = state->select_end; 807 | state->has_preferred_x = 0; 808 | break; 809 | 810 | #ifdef STB_TEXTEDIT_MOVEWORDLEFT 811 | case STB_TEXTEDIT_K_WORDLEFT: 812 | if (STB_TEXT_HAS_SELECTION(state)) 813 | stb_textedit_move_to_first(state); 814 | else { 815 | state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); 816 | stb_textedit_clamp( str, state ); 817 | } 818 | break; 819 | 820 | case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: 821 | if( !STB_TEXT_HAS_SELECTION( state ) ) 822 | stb_textedit_prep_selection_at_cursor(state); 823 | 824 | state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); 825 | state->select_end = state->cursor; 826 | 827 | stb_textedit_clamp( str, state ); 828 | break; 829 | #endif 830 | 831 | #ifdef STB_TEXTEDIT_MOVEWORDRIGHT 832 | case STB_TEXTEDIT_K_WORDRIGHT: 833 | if (STB_TEXT_HAS_SELECTION(state)) 834 | stb_textedit_move_to_last(str, state); 835 | else { 836 | state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); 837 | stb_textedit_clamp( str, state ); 838 | } 839 | break; 840 | 841 | case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: 842 | if( !STB_TEXT_HAS_SELECTION( state ) ) 843 | stb_textedit_prep_selection_at_cursor(state); 844 | 845 | state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); 846 | state->select_end = state->cursor; 847 | 848 | stb_textedit_clamp( str, state ); 849 | break; 850 | #endif 851 | 852 | case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: 853 | stb_textedit_prep_selection_at_cursor(state); 854 | // move selection right 855 | ++state->select_end; 856 | stb_textedit_clamp(str, state); 857 | state->cursor = state->select_end; 858 | state->has_preferred_x = 0; 859 | break; 860 | 861 | case STB_TEXTEDIT_K_DOWN: 862 | case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: 863 | case STB_TEXTEDIT_K_PGDOWN: 864 | case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: { 865 | StbFindState find; 866 | StbTexteditRow row; 867 | int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; 868 | int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN; 869 | int row_count = is_page ? state->row_count_per_page : 1; 870 | 871 | if (!is_page && state->single_line) { 872 | // on windows, up&down in single-line behave like left&right 873 | key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); 874 | goto retry; 875 | } 876 | 877 | if (sel) 878 | stb_textedit_prep_selection_at_cursor(state); 879 | else if (STB_TEXT_HAS_SELECTION(state)) 880 | stb_textedit_move_to_last(str, state); 881 | 882 | // compute current position of cursor point 883 | stb_textedit_clamp(str, state); 884 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 885 | 886 | for (j = 0; j < row_count; ++j) { 887 | float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; 888 | int start = find.first_char + find.length; 889 | 890 | if (find.length == 0) 891 | break; 892 | 893 | // [DEAR IMGUI] 894 | // going down while being on the last line shouldn't bring us to that line end 895 | if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE) 896 | break; 897 | 898 | // now find character position down a row 899 | state->cursor = start; 900 | STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); 901 | x = row.x0; 902 | for (i=0; i < row.num_chars; ++i) { 903 | float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); 904 | #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE 905 | if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) 906 | break; 907 | #endif 908 | x += dx; 909 | if (x > goal_x) 910 | break; 911 | ++state->cursor; 912 | } 913 | stb_textedit_clamp(str, state); 914 | 915 | state->has_preferred_x = 1; 916 | state->preferred_x = goal_x; 917 | 918 | if (sel) 919 | state->select_end = state->cursor; 920 | 921 | // go to next line 922 | find.first_char = find.first_char + find.length; 923 | find.length = row.num_chars; 924 | } 925 | break; 926 | } 927 | 928 | case STB_TEXTEDIT_K_UP: 929 | case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: 930 | case STB_TEXTEDIT_K_PGUP: 931 | case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: { 932 | StbFindState find; 933 | StbTexteditRow row; 934 | int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; 935 | int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP; 936 | int row_count = is_page ? state->row_count_per_page : 1; 937 | 938 | if (!is_page && state->single_line) { 939 | // on windows, up&down become left&right 940 | key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); 941 | goto retry; 942 | } 943 | 944 | if (sel) 945 | stb_textedit_prep_selection_at_cursor(state); 946 | else if (STB_TEXT_HAS_SELECTION(state)) 947 | stb_textedit_move_to_first(state); 948 | 949 | // compute current position of cursor point 950 | stb_textedit_clamp(str, state); 951 | stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); 952 | 953 | for (j = 0; j < row_count; ++j) { 954 | float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; 955 | 956 | // can only go up if there's a previous row 957 | if (find.prev_first == find.first_char) 958 | break; 959 | 960 | // now find character position up a row 961 | state->cursor = find.prev_first; 962 | STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); 963 | x = row.x0; 964 | for (i=0; i < row.num_chars; ++i) { 965 | float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); 966 | #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE 967 | if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) 968 | break; 969 | #endif 970 | x += dx; 971 | if (x > goal_x) 972 | break; 973 | ++state->cursor; 974 | } 975 | stb_textedit_clamp(str, state); 976 | 977 | state->has_preferred_x = 1; 978 | state->preferred_x = goal_x; 979 | 980 | if (sel) 981 | state->select_end = state->cursor; 982 | 983 | // go to previous line 984 | // (we need to scan previous line the hard way. maybe we could expose this as a new API function?) 985 | prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0; 986 | while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE) 987 | --prev_scan; 988 | find.first_char = find.prev_first; 989 | find.prev_first = prev_scan; 990 | } 991 | break; 992 | } 993 | 994 | case STB_TEXTEDIT_K_DELETE: 995 | case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: 996 | if (STB_TEXT_HAS_SELECTION(state)) 997 | stb_textedit_delete_selection(str, state); 998 | else { 999 | int n = STB_TEXTEDIT_STRINGLEN(str); 1000 | if (state->cursor < n) 1001 | stb_textedit_delete(str, state, state->cursor, 1); 1002 | } 1003 | state->has_preferred_x = 0; 1004 | break; 1005 | 1006 | case STB_TEXTEDIT_K_BACKSPACE: 1007 | case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: 1008 | if (STB_TEXT_HAS_SELECTION(state)) 1009 | stb_textedit_delete_selection(str, state); 1010 | else { 1011 | stb_textedit_clamp(str, state); 1012 | if (state->cursor > 0) { 1013 | stb_textedit_delete(str, state, state->cursor-1, 1); 1014 | --state->cursor; 1015 | } 1016 | } 1017 | state->has_preferred_x = 0; 1018 | break; 1019 | 1020 | #ifdef STB_TEXTEDIT_K_TEXTSTART2 1021 | case STB_TEXTEDIT_K_TEXTSTART2: 1022 | #endif 1023 | case STB_TEXTEDIT_K_TEXTSTART: 1024 | state->cursor = state->select_start = state->select_end = 0; 1025 | state->has_preferred_x = 0; 1026 | break; 1027 | 1028 | #ifdef STB_TEXTEDIT_K_TEXTEND2 1029 | case STB_TEXTEDIT_K_TEXTEND2: 1030 | #endif 1031 | case STB_TEXTEDIT_K_TEXTEND: 1032 | state->cursor = STB_TEXTEDIT_STRINGLEN(str); 1033 | state->select_start = state->select_end = 0; 1034 | state->has_preferred_x = 0; 1035 | break; 1036 | 1037 | #ifdef STB_TEXTEDIT_K_TEXTSTART2 1038 | case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: 1039 | #endif 1040 | case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: 1041 | stb_textedit_prep_selection_at_cursor(state); 1042 | state->cursor = state->select_end = 0; 1043 | state->has_preferred_x = 0; 1044 | break; 1045 | 1046 | #ifdef STB_TEXTEDIT_K_TEXTEND2 1047 | case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: 1048 | #endif 1049 | case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: 1050 | stb_textedit_prep_selection_at_cursor(state); 1051 | state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); 1052 | state->has_preferred_x = 0; 1053 | break; 1054 | 1055 | 1056 | #ifdef STB_TEXTEDIT_K_LINESTART2 1057 | case STB_TEXTEDIT_K_LINESTART2: 1058 | #endif 1059 | case STB_TEXTEDIT_K_LINESTART: 1060 | stb_textedit_clamp(str, state); 1061 | stb_textedit_move_to_first(state); 1062 | if (state->single_line) 1063 | state->cursor = 0; 1064 | else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) 1065 | --state->cursor; 1066 | state->has_preferred_x = 0; 1067 | break; 1068 | 1069 | #ifdef STB_TEXTEDIT_K_LINEEND2 1070 | case STB_TEXTEDIT_K_LINEEND2: 1071 | #endif 1072 | case STB_TEXTEDIT_K_LINEEND: { 1073 | int n = STB_TEXTEDIT_STRINGLEN(str); 1074 | stb_textedit_clamp(str, state); 1075 | stb_textedit_move_to_first(state); 1076 | if (state->single_line) 1077 | state->cursor = n; 1078 | else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) 1079 | ++state->cursor; 1080 | state->has_preferred_x = 0; 1081 | break; 1082 | } 1083 | 1084 | #ifdef STB_TEXTEDIT_K_LINESTART2 1085 | case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: 1086 | #endif 1087 | case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: 1088 | stb_textedit_clamp(str, state); 1089 | stb_textedit_prep_selection_at_cursor(state); 1090 | if (state->single_line) 1091 | state->cursor = 0; 1092 | else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) 1093 | --state->cursor; 1094 | state->select_end = state->cursor; 1095 | state->has_preferred_x = 0; 1096 | break; 1097 | 1098 | #ifdef STB_TEXTEDIT_K_LINEEND2 1099 | case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: 1100 | #endif 1101 | case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { 1102 | int n = STB_TEXTEDIT_STRINGLEN(str); 1103 | stb_textedit_clamp(str, state); 1104 | stb_textedit_prep_selection_at_cursor(state); 1105 | if (state->single_line) 1106 | state->cursor = n; 1107 | else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) 1108 | ++state->cursor; 1109 | state->select_end = state->cursor; 1110 | state->has_preferred_x = 0; 1111 | break; 1112 | } 1113 | } 1114 | } 1115 | 1116 | ///////////////////////////////////////////////////////////////////////////// 1117 | // 1118 | // Undo processing 1119 | // 1120 | // @OPTIMIZE: the undo/redo buffer should be circular 1121 | 1122 | static void stb_textedit_flush_redo(StbUndoState *state) 1123 | { 1124 | state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; 1125 | state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; 1126 | } 1127 | 1128 | // discard the oldest entry in the undo list 1129 | static void stb_textedit_discard_undo(StbUndoState *state) 1130 | { 1131 | if (state->undo_point > 0) { 1132 | // if the 0th undo state has characters, clean those up 1133 | if (state->undo_rec[0].char_storage >= 0) { 1134 | int n = state->undo_rec[0].insert_length, i; 1135 | // delete n characters from all other records 1136 | state->undo_char_point -= n; 1137 | STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); 1138 | for (i=0; i < state->undo_point; ++i) 1139 | if (state->undo_rec[i].char_storage >= 0) 1140 | state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it 1141 | } 1142 | --state->undo_point; 1143 | STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); 1144 | } 1145 | } 1146 | 1147 | // discard the oldest entry in the redo list--it's bad if this 1148 | // ever happens, but because undo & redo have to store the actual 1149 | // characters in different cases, the redo character buffer can 1150 | // fill up even though the undo buffer didn't 1151 | static void stb_textedit_discard_redo(StbUndoState *state) 1152 | { 1153 | int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; 1154 | 1155 | if (state->redo_point <= k) { 1156 | // if the k'th undo state has characters, clean those up 1157 | if (state->undo_rec[k].char_storage >= 0) { 1158 | int n = state->undo_rec[k].insert_length, i; 1159 | // move the remaining redo character data to the end of the buffer 1160 | state->redo_char_point += n; 1161 | STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); 1162 | // adjust the position of all the other records to account for above memmove 1163 | for (i=state->redo_point; i < k; ++i) 1164 | if (state->undo_rec[i].char_storage >= 0) 1165 | state->undo_rec[i].char_storage += n; 1166 | } 1167 | // now move all the redo records towards the end of the buffer; the first one is at 'redo_point' 1168 | // [DEAR IMGUI] 1169 | size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); 1170 | const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; 1171 | const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; 1172 | IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); 1173 | IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); 1174 | STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); 1175 | 1176 | // now move redo_point to point to the new one 1177 | ++state->redo_point; 1178 | } 1179 | } 1180 | 1181 | static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) 1182 | { 1183 | // any time we create a new undo record, we discard redo 1184 | stb_textedit_flush_redo(state); 1185 | 1186 | // if we have no free records, we have to make room, by sliding the 1187 | // existing records down 1188 | if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1189 | stb_textedit_discard_undo(state); 1190 | 1191 | // if the characters to store won't possibly fit in the buffer, we can't undo 1192 | if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { 1193 | state->undo_point = 0; 1194 | state->undo_char_point = 0; 1195 | return NULL; 1196 | } 1197 | 1198 | // if we don't have enough free characters in the buffer, we have to make room 1199 | while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) 1200 | stb_textedit_discard_undo(state); 1201 | 1202 | return &state->undo_rec[state->undo_point++]; 1203 | } 1204 | 1205 | static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) 1206 | { 1207 | StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); 1208 | if (r == NULL) 1209 | return NULL; 1210 | 1211 | r->where = pos; 1212 | r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len; 1213 | r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len; 1214 | 1215 | if (insert_len == 0) { 1216 | r->char_storage = -1; 1217 | return NULL; 1218 | } else { 1219 | r->char_storage = state->undo_char_point; 1220 | state->undo_char_point += insert_len; 1221 | return &state->undo_char[r->char_storage]; 1222 | } 1223 | } 1224 | 1225 | static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 1226 | { 1227 | StbUndoState *s = &state->undostate; 1228 | StbUndoRecord u, *r; 1229 | if (s->undo_point == 0) 1230 | return; 1231 | 1232 | // we need to do two things: apply the undo record, and create a redo record 1233 | u = s->undo_rec[s->undo_point-1]; 1234 | r = &s->undo_rec[s->redo_point-1]; 1235 | r->char_storage = -1; 1236 | 1237 | r->insert_length = u.delete_length; 1238 | r->delete_length = u.insert_length; 1239 | r->where = u.where; 1240 | 1241 | if (u.delete_length) { 1242 | // if the undo record says to delete characters, then the redo record will 1243 | // need to re-insert the characters that get deleted, so we need to store 1244 | // them. 1245 | 1246 | // there are three cases: 1247 | // there's enough room to store the characters 1248 | // characters stored for *redoing* don't leave room for redo 1249 | // characters stored for *undoing* don't leave room for redo 1250 | // if the last is true, we have to bail 1251 | 1252 | if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { 1253 | // the undo records take up too much character space; there's no space to store the redo characters 1254 | r->insert_length = 0; 1255 | } else { 1256 | int i; 1257 | 1258 | // there's definitely room to store the characters eventually 1259 | while (s->undo_char_point + u.delete_length > s->redo_char_point) { 1260 | // should never happen: 1261 | if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1262 | return; 1263 | // there's currently not enough room, so discard a redo record 1264 | stb_textedit_discard_redo(s); 1265 | } 1266 | r = &s->undo_rec[s->redo_point-1]; 1267 | 1268 | r->char_storage = s->redo_char_point - u.delete_length; 1269 | s->redo_char_point = s->redo_char_point - u.delete_length; 1270 | 1271 | // now save the characters 1272 | for (i=0; i < u.delete_length; ++i) 1273 | s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); 1274 | } 1275 | 1276 | // now we can carry out the deletion 1277 | STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); 1278 | } 1279 | 1280 | // check type of recorded action: 1281 | if (u.insert_length) { 1282 | // easy case: was a deletion, so we need to insert n characters 1283 | STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); 1284 | s->undo_char_point -= u.insert_length; 1285 | } 1286 | 1287 | state->cursor = u.where + u.insert_length; 1288 | 1289 | s->undo_point--; 1290 | s->redo_point--; 1291 | } 1292 | 1293 | static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) 1294 | { 1295 | StbUndoState *s = &state->undostate; 1296 | StbUndoRecord *u, r; 1297 | if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) 1298 | return; 1299 | 1300 | // we need to do two things: apply the redo record, and create an undo record 1301 | u = &s->undo_rec[s->undo_point]; 1302 | r = s->undo_rec[s->redo_point]; 1303 | 1304 | // we KNOW there must be room for the undo record, because the redo record 1305 | // was derived from an undo record 1306 | 1307 | u->delete_length = r.insert_length; 1308 | u->insert_length = r.delete_length; 1309 | u->where = r.where; 1310 | u->char_storage = -1; 1311 | 1312 | if (r.delete_length) { 1313 | // the redo record requires us to delete characters, so the undo record 1314 | // needs to store the characters 1315 | 1316 | if (s->undo_char_point + u->insert_length > s->redo_char_point) { 1317 | u->insert_length = 0; 1318 | u->delete_length = 0; 1319 | } else { 1320 | int i; 1321 | u->char_storage = s->undo_char_point; 1322 | s->undo_char_point = s->undo_char_point + u->insert_length; 1323 | 1324 | // now save the characters 1325 | for (i=0; i < u->insert_length; ++i) 1326 | s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); 1327 | } 1328 | 1329 | STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); 1330 | } 1331 | 1332 | if (r.insert_length) { 1333 | // easy case: need to insert n characters 1334 | STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); 1335 | s->redo_char_point += r.insert_length; 1336 | } 1337 | 1338 | state->cursor = r.where + r.insert_length; 1339 | 1340 | s->undo_point++; 1341 | s->redo_point++; 1342 | } 1343 | 1344 | static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) 1345 | { 1346 | stb_text_createundo(&state->undostate, where, 0, length); 1347 | } 1348 | 1349 | static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) 1350 | { 1351 | int i; 1352 | STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); 1353 | if (p) { 1354 | for (i=0; i < length; ++i) 1355 | p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); 1356 | } 1357 | } 1358 | 1359 | static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) 1360 | { 1361 | int i; 1362 | STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); 1363 | if (p) { 1364 | for (i=0; i < old_length; ++i) 1365 | p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); 1366 | } 1367 | } 1368 | 1369 | // reset the state to default 1370 | static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) 1371 | { 1372 | state->undostate.undo_point = 0; 1373 | state->undostate.undo_char_point = 0; 1374 | state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; 1375 | state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; 1376 | state->select_end = state->select_start = 0; 1377 | state->cursor = 0; 1378 | state->has_preferred_x = 0; 1379 | state->preferred_x = 0; 1380 | state->cursor_at_end_of_line = 0; 1381 | state->initialized = 1; 1382 | state->single_line = (unsigned char) is_single_line; 1383 | state->insert_mode = 0; 1384 | state->row_count_per_page = 0; 1385 | } 1386 | 1387 | // API initialize 1388 | static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) 1389 | { 1390 | stb_textedit_clear_state(state, is_single_line); 1391 | } 1392 | 1393 | #if defined(__GNUC__) || defined(__clang__) 1394 | #pragma GCC diagnostic push 1395 | #pragma GCC diagnostic ignored "-Wcast-qual" 1396 | #endif 1397 | 1398 | static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) 1399 | { 1400 | return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len); 1401 | } 1402 | 1403 | #if defined(__GNUC__) || defined(__clang__) 1404 | #pragma GCC diagnostic pop 1405 | #endif 1406 | 1407 | #endif//STB_TEXTEDIT_IMPLEMENTATION 1408 | 1409 | /* 1410 | ------------------------------------------------------------------------------ 1411 | This software is available under 2 licenses -- choose whichever you prefer. 1412 | ------------------------------------------------------------------------------ 1413 | ALTERNATIVE A - MIT License 1414 | Copyright (c) 2017 Sean Barrett 1415 | Permission is hereby granted, free of charge, to any person obtaining a copy of 1416 | this software and associated documentation files (the "Software"), to deal in 1417 | the Software without restriction, including without limitation the rights to 1418 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 1419 | of the Software, and to permit persons to whom the Software is furnished to do 1420 | so, subject to the following conditions: 1421 | The above copyright notice and this permission notice shall be included in all 1422 | copies or substantial portions of the Software. 1423 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 1424 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 1425 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 1426 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 1427 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 1428 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 1429 | SOFTWARE. 1430 | ------------------------------------------------------------------------------ 1431 | ALTERNATIVE B - Public Domain (www.unlicense.org) 1432 | This is free and unencumbered software released into the public domain. 1433 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 1434 | software, either in source code form or as a compiled binary, for any purpose, 1435 | commercial or non-commercial, and by any means. 1436 | In jurisdictions that recognize copyright laws, the author or authors of this 1437 | software dedicate any and all copyright interest in the software to the public 1438 | domain. We make this dedication for the benefit of the public at large and to 1439 | the detriment of our heirs and successors. We intend this dedication to be an 1440 | overt act of relinquishment in perpetuity of all present and future rights to 1441 | this software under copyright law. 1442 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 1443 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 1444 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 1445 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 1446 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 1447 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 1448 | ------------------------------------------------------------------------------ 1449 | */ 1450 | --------------------------------------------------------------------------------